<commit_before>/**********************************************************************************************

Script.js

**********************************************************************************************/

/*global jQuery */
/*!
* Lettering.JS 0.7.0
*
* Copyright 2010, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Thanks to Paul Irish - http://paulirish.com - for the feedback.
*
* Date: Mon Sep 20 17:14:00 2010 -0600
*/
(function($){
	function injector(t, splitter, klass, after) {
		var text = t.text()
		, a = text.split(splitter)
		, inject = '';
		if (a.length) {
			$(a).each(function(i, item) {
				inject += ''+item+''+after;
			});
			t.attr('aria-label',text)
			.empty()
			.append(inject)

		}
	}

	var methods = {
		init : function() {

			return this.each(function() {
				injector($(this), '', 'char', '');
			});

		},

		words : function() {

			return this.each(function() {
				injector($(this), ' ', 'word', ' ');
			});

		},

		lines : function() {

			return this.each(function() {
				var r = "eefec303079ad17405c889e092e105b0";
				// Because it's hard to split a
 tag consistently across browsers,
				// (*ahem* IE *ahem*), we replace all
 instances with an md5 hash
				// (of the word "split").  If you're trying to use this plugin on that
				// md5 hash string, it will fail because you're being ridiculous.
				injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
			});

		}
	};

	$.fn.lettering = function( method ) {
		// Method calling logic
		if ( method && methods[method] ) {
			return methods[ method ].apply( this, [].slice.call( arguments, 1 ));
		} else if ( method === 'letters' || ! method ) {
			return methods.init.apply( this, [].slice.call( arguments, 0 ) ); // always pass an array
		}
		$.error( 'Method ' +  method + ' does not exist on jQuery.lettering' );
		return this;
	};

})(jQuery);

/**********************************************************************************************

Stuff specific to Anna McIlwraith site is below

**********************************************************************************************/

function applyLetteringFixes()
{
	// Fix 'Wayward Heart'
	$(".lettering-wayward-heart").lettering();

	// a
	$(".lettering-wayward-heart .char2").css({
		marginLeft: "-3px"
	});
	// y
	$(".lettering-wayward-heart .char3").css({
		marginLeft: "-2px"
	});
	// a
	$(".lettering-wayward-heart .char5").css({
		marginLeft: "-2px"
	});
	// Fix 'The Wolf’s Heir'
	$(".post-title:contains('The Wolf’s Heir')").addClass('lettering-fix-wolf').lettering();
	// o
	$(".lettering-fix-wolf .char6").css({
		marginLeft: "-3px"
	});
}

function buildPopups()
{
	// uses Magnific Popup
	$('.image-popup-fit-width').magnificPopup({
		type: 'image',
		closeOnContentClick: true,
		image: {
			verticalFit: true
		}
	});
}

function smoothScrollToTitle() {
	var resumeSession = false;
	resumeSession = sessionStorage.getItem('sessionExists');
	console.log(resumeSession);
	if (resumeSession) {
	    $('html, body').animate({
            scrollTop: $('#post').offset().top
        }, 500);
    }
    else {
    	sessionStorage.setItem('sessionExists', true);
    }
}

$(document).ready(function() {
	applyLetteringFixes();
	buildPopups();
	smoothScrollToTitle();
});<commit_msg>Update smooth scroll<commit_after>/**********************************************************************************************

Script.js

**********************************************************************************************/

/*global jQuery */
/*!
* Lettering.JS 0.7.0
*
* Copyright 2010, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Thanks to Paul Irish - http://paulirish.com - for the feedback.
*
* Date: Mon Sep 20 17:14:00 2010 -0600
*/
(function($){
	function injector(t, splitter, klass, after) {
		var text = t.text()
		, a = text.split(splitter)
		, inject = '';
		if (a.length) {
			$(a).each(function(i, item) {
				inject += ''+item+''+after;
			});
			t.attr('aria-label',text)
			.empty()
			.append(inject)

		}
	}

	var methods = {
		init : function() {

			return this.each(function() {
				injector($(this), '', 'char', '');
			});

		},

		words : function() {

			return this.each(function() {
				injector($(this), ' ', 'word', ' ');
			});

		},

		lines : function() {

			return this.each(function() {
				var r = "eefec303079ad17405c889e092e105b0";
				// Because it's hard to split a
 tag consistently across browsers,
				// (*ahem* IE *ahem*), we replace all
 instances with an md5 hash
				// (of the word "split").  If you're trying to use this plugin on that
				// md5 hash string, it will fail because you're being ridiculous.
				injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
			});

		}
	};

	$.fn.lettering = function( method ) {
		// Method calling logic
		if ( method && methods[method] ) {
			return methods[ method ].apply( this, [].slice.call( arguments, 1 ));
		} else if ( method === 'letters' || ! method ) {
			return methods.init.apply( this, [].slice.call( arguments, 0 ) ); // always pass an array
		}
		$.error( 'Method ' +  method + ' does not exist on jQuery.lettering' );
		return this;
	};

})(jQuery);

/**********************************************************************************************

Stuff specific to Anna McIlwraith site is below

**********************************************************************************************/

function applyLetteringFixes()
{
	// Fix 'Wayward Heart'
	$(".lettering-wayward-heart").lettering();

	// a
	$(".lettering-wayward-heart .char2").css({
		marginLeft: "-3px"
	});
	// y
	$(".lettering-wayward-heart .char3").css({
		marginLeft: "-2px"
	});
	// a
	$(".lettering-wayward-heart .char5").css({
		marginLeft: "-2px"
	});
	// Fix 'The Wolf’s Heir'
	$(".post-title:contains('The Wolf’s Heir')").addClass('lettering-fix-wolf').lettering();
	// o
	$(".lettering-fix-wolf .char6").css({
		marginLeft: "-3px"
	});
}

function buildPopups()
{
	// uses Magnific Popup
	$('.image-popup-fit-width').magnificPopup({
		type: 'image',
		closeOnContentClick: true,
		image: {
			verticalFit: true
		}
	});
}

function smoothScrollToTitle() {
	// smooth scroll to main post heading on page load
	var resumeSession = false;
	resumeSession = sessionStorage.getItem('sessionExists');
	console.log(resumeSession);
	if (resumeSession) {
		$(function() {
		    $('html, body').animate({
	            scrollTop: $('#post').offset().top
	        }, 500);
        	return false;
		});
    }
    else {
    	sessionStorage.setItem('sessionExists', true);
    }
    // make anchor links to ids on the same page smooth scroll
    // from: https://css-tricks.com/snippets/jquery/smooth-scrolling/
    $(function() {
	  $('a[href*=#]:not([href=#])').click(function() {
	    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
	      var target = $(this.hash);
	      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
	      if (target.length) {
	        $('html,body').animate({
	          scrollTop: target.offset().top
	        }, 500);
	        return false;
	      }
	    }
	  });
	});
}

$(document).ready(function() {
	applyLetteringFixes();
	buildPopups();
	smoothScrollToTitle();
});<|endoftext|>


<commit_before>/*jshint -W079 */

'use strict';

var CMAQ = angular.module('CMAQ', [
  'templates',
  'ngSanitize',
  'ui.router',
  'angularMoment',
]);

CMAQ.config(function ($httpProvider, $urlRouterProvider, $stateProvider, appConfig, platformConfig) {
  if (_.isEmpty(appConfig)) {
    throw new Error('App configuration not set');
  } else if (!appConfig.title) {
    throw new Error('App title not set');
  } else if (_.isEmpty(platformConfig)) {
    throw new Error('Platform configuration not set');
  } else if (!platformConfig.url) {
    throw new Error('Path to platform not set');
  }

  appConfig.version = '@@version';
  platformConfig.url = platformConfig.url.replace(/\/$/, '');

  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  $urlRouterProvider.when('', '/').otherwise('/404');

  $urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    if ('/' === path[path.length - 1]) {
      return path.replace(/\/$/, '');
    }

    if (path.indexOf('/?') > 0) {
      return path.replace('/?', '?');
    }

    return false;
  });

  $stateProvider
    .state('index', {
      url: '/',
      controller: 'IndexController'
    })
    .state('404', {
      url: '/404',
      controller: '404Controller'
    })
    .state('redirect', {
      url: '/redirect',
      controller: 'RedirectController'
    })
    .state('login', {
      url: '/login',
      views: {
        content: {
          controller: 'LoginController',
          templateUrl: 'partials/login.html'
        }
      }
    });
});

CMAQ.run(function ($window, $rootScope, appConfig, viewport, state, oauth) {
  viewport.version = appConfig.version;

  if (!_.isEmpty(appConfig.ga) && _.isFunction($window.ga)) {
    $window.ga('create', appConfig.ga, 'auto');
  }

  oauth.authorize();
  viewport.ready = true;

  $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    state.saveHistory(toState.name, toParams, fromState.name, fromParams);
  });
});
<commit_msg>Fixed view containers<commit_after>/*jshint -W079 */

'use strict';

var CMAQ = angular.module('CMAQ', [
  'templates',
  'ngSanitize',
  'ui.router',
  'angularMoment',
]);

CMAQ.config(function ($httpProvider, $urlRouterProvider, $stateProvider, appConfig, platformConfig) {
  if (_.isEmpty(appConfig)) {
    throw new Error('App configuration not set');
  } else if (!appConfig.title) {
    throw new Error('App title not set');
  } else if (_.isEmpty(platformConfig)) {
    throw new Error('Platform configuration not set');
  } else if (!platformConfig.url) {
    throw new Error('Path to platform not set');
  }

  appConfig.version = '@@version';
  platformConfig.url = platformConfig.url.replace(/\/$/, '');

  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  $urlRouterProvider.when('', '/').otherwise('/404');

  $urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.url();

    if ('/' === path[path.length - 1]) {
      return path.replace(/\/$/, '');
    }

    if (path.indexOf('/?') > 0) {
      return path.replace('/?', '?');
    }

    return false;
  });

  $stateProvider
    .state('index', {
      url: '/',
      views: {
        content: {
          controller: 'IndexController'
        }
      }
    })
    .state('404', {
      url: '/404',
      views: {
        content: {
          controller: '404Controller'
        }
      }
    })
    .state('redirect', {
      url: '/redirect',
      views: {
        content: {
          controller: 'RedirectController'
        }
      }
    })
    .state('login', {
      url: '/login',
      views: {
        content: {
          controller: 'LoginController',
          templateUrl: 'partials/login.html'
        }
      }
    });
});

CMAQ.run(function ($window, $rootScope, appConfig, viewport, state, oauth) {
  viewport.version = appConfig.version;

  if (!_.isEmpty(appConfig.ga) && _.isFunction($window.ga)) {
    $window.ga('create', appConfig.ga, 'auto');
  }

  oauth.authorize();
  viewport.ready = true;

  $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    state.saveHistory(toState.name, toParams, fromState.name, fromParams);
  });
});
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
//var Vector2 = require('vector2');

var mainItems = {
  title: 'ToDo',
  //icon: 'images/menu_icon.png',
  //subtitle: "Don't forget!",
  //body: 'Press any button.'
};

function getTodos() {
  var fromLocal = localStorage.getItem('todos');
  console.log("localStorage.getItem('todos') //=> ");
  console.log(fromLocal);
  if(fromLocal === null) {
    return {};
  } else
    try {
      return JSON.parse(fromLocal);
    } catch (err) {
      console.log('Error!!!');
      console.log(err);
      return {};
    }
}

function toggleTodo(todo) {
  if(checkTodo(todo) == 1) {
    unsetTodo(todo);
  } else {
    setTodo(todo);
  }
}

function setTodo(todo) {
  var current = getTodos();
  current[todo] = 1;
  saveTodoData(current);
}

function unsetTodo(todo) {
  var current = getTodos();
  current[todo] = 0;
  saveTodoData(current);
}

function checkTodo(todo) {
  if(todo == 'Home') {
    return 1;
  } else {
    return getTodos()[todo] == 1;
  }
}

function saveTodoData(data) {
  console.log('start saveTodoData');
  console.log(JSON.stringify(data));
  localStorage.setItem('todos', JSON.stringify(data));
  console.log(JSON.stringify(getTodos()));
}

function getTodosCount() {
  console.log('start getTodosCount');
  var count = 0,
      current = getTodos();
  console.log(current);
  for (var prop in current) {
    if(current[prop] == 1) {
      count++;
    }
  }
  return count;
}

function mainSubtitleStr() {
  return "You have "+getTodosCount()+" Todos.";
}

mainItems.subtitle = mainSubtitleStr();

var main = new UI.Card(mainItems);
main.show();

main.on('click', 'select', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Home',
        //icon: 'images/menu_icon.png',
        subtitle: checkTodo('Home') ? 'Set' : 'Unset'
      }, {
        title: 'Work',
        subtitle: checkTodo('Work') ? 'Set' : 'Unset'
      }]
    }]
  });
  menu.on('select', function(e) {
    var selectedTitle = e.item.title;
    toggleTodo(selectedTitle);
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + selectedTitle +
                '" and is now ' + (checkTodo(selectedTitle) ? 'Set' : 'Unset')
               );
    main.subtitle(mainSubtitleStr());
  });
  menu.show();
});

/*
main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});
*/
<commit_msg>ToDo count simplification<commit_after>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
//var Vector2 = require('vector2');

function getTodos() {
  var fromLocal = localStorage.getItem('todos');
  if(fromLocal === null) {
    return {};
  } else
    try {
      return JSON.parse(fromLocal);
    } catch (err) {
      console.log('Error!!!');
      console.log(err);
      return {};
    }
}

function toggleTodo(todo) {
  if(checkTodo(todo) == 1) {
    unsetTodo(todo);
  } else {
    setTodo(todo);
  }
}

function setTodo(todo) {
  var current = getTodos();
  current[todo] = 1;
  saveTodoData(current);
}

function unsetTodo(todo) {
  var current = getTodos();
  current[todo] = 0;
  saveTodoData(current);
}

function checkTodo(todo) {
  return getTodos()[todo] == 1;
}

function saveTodoData(data) {
  localStorage.setItem('todos', JSON.stringify(data));
}

function getTodosCount() {
  var count = 0,
      current = getTodos();
  for (var prop in current) {
    if(current[prop] == 1) {
      count++;
    }
  }
  return count;
}

function mainSubtitleStr() {
  var count = getTodosCount();
  if(count == 1) {
    return "1 Todo";
  } else {
    return count + " Todos";
  }
}

var main = new UI.Card({
  title: 'ToDo',
  subtitle: mainSubtitleStr(),
});
main.show();

main.on('click', 'select', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Home',
        //icon: 'images/menu_icon.png',
        subtitle: checkTodo('Home') ? 'Set' : 'Unset'
      }, {
        title: 'Work',
        subtitle: checkTodo('Work') ? 'Set' : 'Unset'
      }, {
        title: 'Misc',
        subtitle: checkTodo('Misc') ? 'Set' : 'Unset'
      }]
    }]
  });
  menu.on('select', function(e) {
    var selectedTitle = e.item.title;
    toggleTodo(selectedTitle);
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + selectedTitle +
                '" and is now ' + (checkTodo(selectedTitle) ? 'Set' : 'Unset')
               );
    main.subtitle(mainSubtitleStr());
  });
  menu.show();
});

/*
main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});
*/
<|endoftext|>


<commit_before>export { default as Box } from './Box/Box.osx';
export {default as Form } from './Form/Form.common';
export { default as IndeterminateCircularProgressIndicator } from
  './IndeterminateCircularProgressIndicator/IndeterminateCircularProgressIndicator.osx';
export { default as Label } from './Label/Label.osx';
export { default as PushButton } from './Button/PushButton.osx';
export { default as SegmentedControl } from './SegmentedControl/SegmentedControl.osx';
export { default as TextField } from './TextInput/TextField.osx';
export { default as TitleBar } from './TitleBar/TitleBar.osx';
export { default as Toolbar } from './Toolbar/Toolbar.osx';
export { default as Window } from './Window/Window.osx';
<commit_msg>Coding Style: add a missing space<commit_after>export { default as Box } from './Box/Box.osx';
export { default as Form } from './Form/Form.common';
export { default as IndeterminateCircularProgressIndicator } from
  './IndeterminateCircularProgressIndicator/IndeterminateCircularProgressIndicator.osx';
export { default as Label } from './Label/Label.osx';
export { default as PushButton } from './Button/PushButton.osx';
export { default as SegmentedControl } from './SegmentedControl/SegmentedControl.osx';
export { default as TextField } from './TextInput/TextField.osx';
export { default as TitleBar } from './TitleBar/TitleBar.osx';
export { default as Toolbar } from './Toolbar/Toolbar.osx';
export { default as Window } from './Window/Window.osx';
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should have a section ## License');
            console.log();
        }
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function(grunt) {
  var browsers = grunt.option('browser') ? grunt.option('browser').split(',') : ['PhantomJS'];

  var copyright = '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today(\'yyyy-mm-dd\') %>\n' +
                  '*   Copyright (c) <%= grunt.template.today(\'yyyy\') %> Environmental Systems Research Institute, Inc.\n' +
                  '*   Apache License' +
                  '*/\n';

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: {
        src: [
          'src/**/*.js'
        ]
      }
    },

    watch: {
      scripts: {
        files: [
          'src/**/*.js',
          'spec/**/*.js'
        ],
        tasks: ['test'],
        options: {
          spawn: false
        }
      }
    },

    concat: {
      options: {
        sourceMap: true,
        separator: '\n',
        banner: copyright,
      },
      cluster: {
        src: [
          'src/ClusteredFeatureLayer.js'
        ],
        dest: 'dist/esri-leaflet-clustered-feature-layer-src.js'
      },
    },

    uglify: {
      options: {
        sourceMap: true,
        wrap: false,
        mangle: {
          except: ['L']
        },
        preserveComments: 'some',
        report: 'gzip',
        banner: copyright
      },
      dist: {
        files: {
          'dist/esri-leaflet-clustered-feature-layer.js': [
            'src/ClusteredFeatureLayer.js'
          ],
        }
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js'
      },
      run: {
        reporters: ['progress'],
        browsers: browsers
      },
      coverage: {
        reporters: ['progress', 'coverage'],
        browsers: browsers,
        preprocessors: {
          'src/**/*.js': 'coverage'
        }
      },
      watch: {
        singleRun: false,
        autoWatch: true,
        browsers: browsers
      }
    },

    releaseable: {
      release: {
        options: {
          remote: 'upstream',
          dryRun: grunt.option('dryRun') ? grunt.option('dryRun') : false,
          silent: false
        },
        src: ['dist/**/*.js', 'dist/**/*.map']
      }
    }
  });

  // Development Tasks
  grunt.registerTask('default', ['watch']);
  grunt.registerTask('build', ['jshint', 'karma:coverage', 'concat', 'uglify']);
  grunt.registerTask('test', ['jshint', 'karma:run']);
  grunt.registerTask('prepublish', ['concat', 'uglify']);
  grunt.registerTask('release', ['releaseable', 's3']);

  // Require all grunt modules
  require('load-grunt-tasks')(grunt);

};
<commit_msg>fix release task<commit_after>var fs = require('fs');

module.exports = function(grunt) {
  var browsers = grunt.option('browser') ? grunt.option('browser').split(',') : ['PhantomJS'];

  var copyright = '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today(\'yyyy-mm-dd\') %>\n' +
                  '*   Copyright (c) <%= grunt.template.today(\'yyyy\') %> Environmental Systems Research Institute, Inc.\n' +
                  '*   Apache License' +
                  '*/\n';

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: {
        src: [
          'src/**/*.js'
        ]
      }
    },

    watch: {
      scripts: {
        files: [
          'src/**/*.js',
          'spec/**/*.js'
        ],
        tasks: ['test'],
        options: {
          spawn: false
        }
      }
    },

    concat: {
      options: {
        sourceMap: true,
        separator: '\n',
        banner: copyright,
      },
      cluster: {
        src: [
          'src/ClusteredFeatureLayer.js'
        ],
        dest: 'dist/esri-leaflet-clustered-feature-layer-src.js'
      },
    },

    uglify: {
      options: {
        sourceMap: true,
        wrap: false,
        mangle: {
          except: ['L']
        },
        preserveComments: 'some',
        report: 'gzip',
        banner: copyright
      },
      dist: {
        files: {
          'dist/esri-leaflet-clustered-feature-layer.js': [
            'src/ClusteredFeatureLayer.js'
          ],
        }
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js'
      },
      run: {
        reporters: ['progress'],
        browsers: browsers
      },
      coverage: {
        reporters: ['progress', 'coverage'],
        browsers: browsers,
        preprocessors: {
          'src/**/*.js': 'coverage'
        }
      },
      watch: {
        singleRun: false,
        autoWatch: true,
        browsers: browsers
      }
    },

    releaseable: {
      release: {
        options: {
          remote: 'upstream',
          dryRun: grunt.option('dryRun') ? grunt.option('dryRun') : false,
          silent: false
        },
        src: ['dist/**/*.js', 'dist/**/*.map']
      }
    }
  });

  // Development Tasks
  grunt.registerTask('default', ['watch']);
  grunt.registerTask('build', ['jshint', 'karma:coverage', 'concat', 'uglify']);
  grunt.registerTask('test', ['jshint', 'karma:run']);
  grunt.registerTask('prepublish', ['concat', 'uglify']);
  grunt.registerTask('release', ['releaseable']);

  // Require all grunt modules
  require('load-grunt-tasks')(grunt);

};
<|endoftext|>


<commit_before>Ui.LBox.extend('Ui.Draggable',
{
	/**
	 * Fires when object start to be dragged
	 * @name Ui.Draggable#dragstart
	 * @event
	 * @param {Ui.Draggable} draggable The draggable itself
	 */
	/**
	 * Fires when object stop to be dragged
	 * @name Ui.Draggable#dragend
	 * @event
	 * @param {Ui.Draggable} draggable The draggable itself
	 * @param {string} dropEffect Give the operation done: [none|copy|link|move]
	 */

	icon: undefined,
	downloadUrl: undefined,
	downloadMimetype: undefined,
	downloadFilename: undefined,
	allowedMode: 'copyMove',
	mimetype: undefined,
	data: undefined,
	lastPress: undefined,
	isDown: false,
	isDrag: false,
	timer: undefined,
	dragDelta: undefined,
	clock: undefined,
	screenX: undefined,
	screenY: undefined,
	lock: false,

	/**
	 * @constructs
	 * @class
	 * @extends Ui.LBox
	 */
	constructor: function(config) {
		this.addEvents('dragstart', 'dragend', 'press', 'activate', 'menu');

		this.getDrawing().style.cursor = 'pointer';

		this.setFocusable(true);

		this.getDrawing().setAttribute('draggable', true);
		this.connect(this.getDrawing(), 'dragstart', this.onDragStart, true);
		this.connect(this.getDrawing(), 'dragend', this.onDragEnd, true);

		this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);
		this.connect(this.getDrawing(), 'fingerdown', this.onFingerDown);
	},

	setLock: function(lock) {
    	this.lock = lock;
	},

	getLock: function() {
		return this.lock;
	},

	/**
	 * Set the mimetype of the data
	 */
	setMimetype: function(mimetype) {
		if(mimetype === undefined)
			this.mimetype = 'application/era-framework';
		else
			this.mimetype = mimetype;
	},

	/**
	 * Set the data that we drag & drop
	 */
	setData: function(data) {
		this.data = data;
	},

	/**
	 * Set the allowed operation. Possible values are:
	 * [copy|copyLink|copyMove|link|linkMove|move|all]
	 */
	setAllowedMode: function(allowedMode) {
		this.allowedMode = allowedMode;
	},

	/**
	 * Provide an Ui.Image that will be used when
	 * dragging the element
	 * Supported by: Firefox, Chrome and Safari on Windows
	 */
	setIcon: function(icon) {
		this.icon = icon;
	},

	/**
	 * Provide an URL to download the associated file (if any)
	 * if the element is dropped on the desktop
	 * Supported by: Chrome only
	 */
	setDownloadUrl: function(url, mimetype, filename) {
		// TODO: if url is relative, make it absolute
		var uri = new Core.Uri({ uri: url });
		this.downloadUrl = uri.toString();
		// extract the fileName if not given
		if(filename === undefined) {
			// TODO
		}
		// guess the mimetype if not given
		if(mimetype === undefined) {
			// TODO
		}
	 	this.downloadMimetype = mimetype;
		this.downloadFilename = filename;
	},

	getDragDelta: function() {
		return this.dragDelta;
	},

	/**#@+
	 * @private
	 */

	onDragStart: function(event) {
		if(this.lock || this.getIsDisabled())
			return;
		if(!this.dragAllowed) {
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			event.stopPropagation();
			event.preventDefault();
			return;
		}

		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
			this.setTransform(new Ui.Matrix());
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		this.isDown = false;
		this.isDrag = true;
		this.dragDelta = this.pointFromWindow({ x: event.clientX, y: event.clientY });

		this.disconnect(window, 'mouseup', this.onMouseUp, true);

		event.stopPropagation();
		event.dataTransfer.effectAllowed = this.allowedMode;

		// if the element if downloadable to the destkop,
		// try to provide the link
		if(this.downloadUrl != undefined) {
			try {
				event.dataTransfer.setData('DownloadURL', this.downloadMimetype+':'+this.downloadFilename+':'+this.downloadUrl);
			} catch(e) {}
		}

		// use Text as data because it is the only thing
		// that works cross browser. Only Firefox support different mimetypes
		//event.dataTransfer.setData('Text', this.mimetype+':'+this.dragDelta.x+':'+this.dragDelta.y+':'+this.data);
		event.dataTransfer.setData(this.mimetype, this.data);

		this.fireEvent('dragstart', this);

		if(this.icon != undefined) {
			// TODO: improve this
			if(event.dataTransfer.setDragImage != undefined)
				event.dataTransfer.setDragImage(this.icon.drawing.childNodes[0], 0, 0);
		}
		return false;
	},

	onDragEnd: function(event) {
		this.isDrag = false;
		this.isDown = false;

		event.stopPropagation();
		// dropEffect give the operation done: [none|copy|link|move]
		this.fireEvent('dragend', this, event.dataTransfer.dropEffect);
	},

	onMouseDown: function(event) {
		if(this.lock || this.isDown || (event.button != 0) || this.getIsDisabled())
			return;
		this.isDown = true;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });

		this.screenX = event.screenX;
		this.screenY = event.screenY;

		this.connect(window, 'mousemove', this.onMouseMove, true);
		this.connect(window, 'mouseup', this.onMouseUp, true);

		event.stopPropagation();
		if(!navigator.supportDrag && (event.button == 0))
			new Core.DragDataTransfer({ draggable: this.getDrawing(), x: event.clientX, y: event.clientY, event: event, mouse: true });
	},

	onMouseMove: function(event) {
		var deltaX = event.screenX - this.screenX;
		var deltaY = event.screenY - this.screenY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		event.preventDefault();
		event.stopPropagation();

		// if the user move to much, release the touch event
		if(delta > 10) {
			this.disconnect(window, 'mousemove', this.onMouseMove, true);
			this.disconnect(window, 'mouseup', this.onMouseUp, true);

			this.isDrag = false;
			this.isDown = false;
			this.dragAllowed = false;
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}

			var mouseDownEvent = document.createEvent('MouseEvents');
			mouseDownEvent.initMouseEvent('mousedown', true, true, window, 1, event.screenX, event.screenY,
				event.clientX, event.clientY,
				event.ctrlKey, event.altKey, event.shiftKey,
				event.metaKey, 0, event.target);
			this.getDrawing().offsetParent.dispatchEvent(mouseDownEvent);
		}
	},

	onMouseUp: function(event) {
		this.disconnect(window, 'mousemove', this.onMouseMove, true);
		this.disconnect(window, 'mouseup', this.onMouseUp, true);

		this.isDown = false;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		if(!this.isDrag) {
			this.isDrag = false;
			this.fireEvent('press', this);

			var currentTime = (new Date().getTime())/1000;
			if((this.lastPress != undefined) && ((currentTime - this.lastPress) < 0.25)) {
				this.fireEvent('activate', this);
			}
			this.lastPress = currentTime;
			this.focus();
		}
		this.isDrag = false;
	},

	onFingerDown: function(event) {
		if(this.lock || this.isDown || this.getIsDisabled())
			return;
		this.connect(event.finger, 'fingermove', this.onFingerMove);
		this.connect(event.finger, 'fingerup', this.onFingerUp);
		event.finger.capture(this.getDrawing());

		event.preventDefault();
		event.stopPropagation();

		this.screenX = event.finger.getX();
		this.screenY = event.finger.getY();

		this.isDown = true;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });
	},

	onFingerMove: function(event) {
		event.preventDefault();
		event.stopPropagation();

		var deltaX = event.finger.getX() - this.screenX;
		var deltaY = event.finger.getY() - this.screenY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		// if the user move to much, release the touch event
		if(delta > 20) {
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}

			this.disconnect(event.finger, 'fingermove', this.onFingerMove);
			this.disconnect(event.finger, 'fingerup', this.onFingerUp);

			if(this.dragAllowed) {
				if(navigator.supportDrag)
					event.finger.release();
				else
					new Core.DragDataTransfer({ draggable: this.getDrawing(), x: event.finger.getX(), y: event.finger.getY(), event: event, finger: event.finger });
			}
			else {
				event.finger.release();
			}
			this.dragAllowed = false;
			this.isDown = false;
		}
	},

	onFingerUp: function(event) {
		event.preventDefault();
		event.stopPropagation();

		this.disconnect(event.finger, 'fingermove', this.onFingerMove);
		this.disconnect(event.finger, 'fingerup', this.onFingerUp);

		this.dragAllowed = false;
		this.isDown = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		if(!this.isDrag) {
			this.isDrag = false;
			this.fireEvent('press', this);
			var currentTime = (new Date().getTime())/1000;
			if((this.lastPress != undefined) && ((currentTime - this.lastPress) < 0.25)) {
				this.fireEvent('activate', this);
			}
			this.lastPress = currentTime;
			this.focus();
		}
		this.isDrag = false;
	},

	onTimer: function() {
		this.timer = undefined;

		this.isDrag = true;
		this.dragAllowed = true;
		this.disconnect(window, 'mousemove', this.onMouseMove, true);

		this.clock = new Anim.Clock({ duration: 'forever' });
		this.connect(this.clock, 'timeupdate', this.onAnim);
		this.clock.begin();
	},

	onAnim: function(clock) {
		var progress = (clock.getGlobalTime() % 0.8) / 0.8;
		var ease = new Anim.ElasticEase({ mode: 'inout' });
		progress = ease.ease(progress);

		var scale = 1 + (progress/12);
		this.setTransform(Ui.Matrix.createScale(scale, scale));
	}
});

<commit_msg>add keyboard support for press event<commit_after>Ui.LBox.extend('Ui.Draggable',
{
	/**
	 * Fires when object start to be dragged
	 * @name Ui.Draggable#dragstart
	 * @event
	 * @param {Ui.Draggable} draggable The draggable itself
	 */
	/**
	 * Fires when object stop to be dragged
	 * @name Ui.Draggable#dragend
	 * @event
	 * @param {Ui.Draggable} draggable The draggable itself
	 * @param {string} dropEffect Give the operation done: [none|copy|link|move]
	 */

	icon: undefined,
	downloadUrl: undefined,
	downloadMimetype: undefined,
	downloadFilename: undefined,
	allowedMode: 'copyMove',
	mimetype: undefined,
	data: undefined,
	lastPress: undefined,
	isDown: false,
	isDrag: false,
	timer: undefined,
	dragDelta: undefined,
	clock: undefined,
	screenX: undefined,
	screenY: undefined,
	lock: false,

	/**
	 * @constructs
	 * @class
	 * @extends Ui.LBox
	 */
	constructor: function(config) {
		this.addEvents('dragstart', 'dragend', 'press', 'activate', 'menu');

		this.getDrawing().style.cursor = 'pointer';

		this.setFocusable(true);

		this.getDrawing().setAttribute('draggable', true);
		this.connect(this.getDrawing(), 'dragstart', this.onDragStart, true);
		this.connect(this.getDrawing(), 'dragend', this.onDragEnd, true);

		this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);
		this.connect(this.getDrawing(), 'fingerdown', this.onFingerDown);

		// handle keyboard
		this.connect(this.getDrawing(), 'keyup', this.onKeyUp);
	},

	setLock: function(lock) {
    	this.lock = lock;
	},

	getLock: function() {
		return this.lock;
	},

	/**
	 * Set the mimetype of the data
	 */
	setMimetype: function(mimetype) {
		if(mimetype === undefined)
			this.mimetype = 'application/era-framework';
		else
			this.mimetype = mimetype;
	},

	/**
	 * Set the data that we drag & drop
	 */
	setData: function(data) {
		this.data = data;
	},

	/**
	 * Set the allowed operation. Possible values are:
	 * [copy|copyLink|copyMove|link|linkMove|move|all]
	 */
	setAllowedMode: function(allowedMode) {
		this.allowedMode = allowedMode;
	},

	/**
	 * Provide an Ui.Image that will be used when
	 * dragging the element
	 * Supported by: Firefox, Chrome and Safari on Windows
	 */
	setIcon: function(icon) {
		this.icon = icon;
	},

	/**
	 * Provide an URL to download the associated file (if any)
	 * if the element is dropped on the desktop
	 * Supported by: Chrome only
	 */
	setDownloadUrl: function(url, mimetype, filename) {
		// TODO: if url is relative, make it absolute
		var uri = new Core.Uri({ uri: url });
		this.downloadUrl = uri.toString();
		// extract the fileName if not given
		if(filename === undefined) {
			// TODO
		}
		// guess the mimetype if not given
		if(mimetype === undefined) {
			// TODO
		}
	 	this.downloadMimetype = mimetype;
		this.downloadFilename = filename;
	},

	getDragDelta: function() {
		return this.dragDelta;
	},

	/**#@+
	 * @private
	 */

	onDragStart: function(event) {
		if(this.lock || this.getIsDisabled())
			return;
		if(!this.dragAllowed) {
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			event.stopPropagation();
			event.preventDefault();
			return;
		}

		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
			this.setTransform(new Ui.Matrix());
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		this.isDown = false;
		this.isDrag = true;
		this.dragDelta = this.pointFromWindow({ x: event.clientX, y: event.clientY });

		this.disconnect(window, 'mouseup', this.onMouseUp, true);

		event.stopPropagation();
		event.dataTransfer.effectAllowed = this.allowedMode;

		// if the element if downloadable to the destkop,
		// try to provide the link
		if(this.downloadUrl != undefined) {
			try {
				event.dataTransfer.setData('DownloadURL', this.downloadMimetype+':'+this.downloadFilename+':'+this.downloadUrl);
			} catch(e) {}
		}

		// use Text as data because it is the only thing
		// that works cross browser. Only Firefox support different mimetypes
		//event.dataTransfer.setData('Text', this.mimetype+':'+this.dragDelta.x+':'+this.dragDelta.y+':'+this.data);
		event.dataTransfer.setData(this.mimetype, this.data);

		this.fireEvent('dragstart', this);

		if(this.icon != undefined) {
			// TODO: improve this
			if(event.dataTransfer.setDragImage != undefined)
				event.dataTransfer.setDragImage(this.icon.drawing.childNodes[0], 0, 0);
		}
		return false;
	},

	onDragEnd: function(event) {
		this.isDrag = false;
		this.isDown = false;

		event.stopPropagation();
		// dropEffect give the operation done: [none|copy|link|move]
		this.fireEvent('dragend', this, event.dataTransfer.dropEffect);
	},

	onMouseDown: function(event) {
		if(this.lock || this.isDown || (event.button != 0) || this.getIsDisabled())
			return;
		this.isDown = true;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });

		this.screenX = event.screenX;
		this.screenY = event.screenY;

		this.connect(window, 'mousemove', this.onMouseMove, true);
		this.connect(window, 'mouseup', this.onMouseUp, true);

		event.stopPropagation();
		if(!navigator.supportDrag && (event.button == 0))
			new Core.DragDataTransfer({ draggable: this.getDrawing(), x: event.clientX, y: event.clientY, event: event, mouse: true });
	},

	onMouseMove: function(event) {
		var deltaX = event.screenX - this.screenX;
		var deltaY = event.screenY - this.screenY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		event.preventDefault();
		event.stopPropagation();

		// if the user move to much, release the touch event
		if(delta > 10) {
			this.disconnect(window, 'mousemove', this.onMouseMove, true);
			this.disconnect(window, 'mouseup', this.onMouseUp, true);

			this.isDrag = false;
			this.isDown = false;
			this.dragAllowed = false;
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}

			var mouseDownEvent = document.createEvent('MouseEvents');
			mouseDownEvent.initMouseEvent('mousedown', true, true, window, 1, event.screenX, event.screenY,
				event.clientX, event.clientY,
				event.ctrlKey, event.altKey, event.shiftKey,
				event.metaKey, 0, event.target);
			this.getDrawing().offsetParent.dispatchEvent(mouseDownEvent);
		}
	},

	onMouseUp: function(event) {
		this.disconnect(window, 'mousemove', this.onMouseMove, true);
		this.disconnect(window, 'mouseup', this.onMouseUp, true);

		this.isDown = false;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		if(!this.isDrag) {
			this.isDrag = false;
			this.fireEvent('press', this);

			var currentTime = (new Date().getTime())/1000;
			if((this.lastPress != undefined) && ((currentTime - this.lastPress) < 0.25)) {
				this.fireEvent('activate', this);
			}
			this.lastPress = currentTime;
			this.focus();
		}
		this.isDrag = false;
	},

	onFingerDown: function(event) {
		if(this.lock || this.isDown || this.getIsDisabled())
			return;
		this.connect(event.finger, 'fingermove', this.onFingerMove);
		this.connect(event.finger, 'fingerup', this.onFingerUp);
		event.finger.capture(this.getDrawing());

		event.preventDefault();
		event.stopPropagation();

		this.screenX = event.finger.getX();
		this.screenY = event.finger.getY();

		this.isDown = true;
		this.dragAllowed = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });
	},

	onFingerMove: function(event) {
		event.preventDefault();
		event.stopPropagation();

		var deltaX = event.finger.getX() - this.screenX;
		var deltaY = event.finger.getY() - this.screenY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		// if the user move to much, release the touch event
		if(delta > 20) {
			this.setTransform(new Ui.Matrix());
			if(this.clock != undefined) {
				this.clock.stop();
				this.clock = undefined;
			}
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}

			this.disconnect(event.finger, 'fingermove', this.onFingerMove);
			this.disconnect(event.finger, 'fingerup', this.onFingerUp);

			if(this.dragAllowed) {
				if(navigator.supportDrag)
					event.finger.release();
				else
					new Core.DragDataTransfer({ draggable: this.getDrawing(), x: event.finger.getX(), y: event.finger.getY(), event: event, finger: event.finger });
			}
			else {
				event.finger.release();
			}
			this.dragAllowed = false;
			this.isDown = false;
		}
	},

	onFingerUp: function(event) {
		event.preventDefault();
		event.stopPropagation();

		this.disconnect(event.finger, 'fingermove', this.onFingerMove);
		this.disconnect(event.finger, 'fingerup', this.onFingerUp);

		this.dragAllowed = false;
		this.isDown = false;
		this.setTransform(new Ui.Matrix());
		if(this.clock != undefined) {
			this.clock.stop();
			this.clock = undefined;
		}
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		if(!this.isDrag) {
			this.isDrag = false;
			this.fireEvent('press', this);
			var currentTime = (new Date().getTime())/1000;
			if((this.lastPress != undefined) && ((currentTime - this.lastPress) < 0.25)) {
				this.fireEvent('activate', this);
			}
			this.lastPress = currentTime;
			this.focus();
		}
		this.isDrag = false;
	},

	onTimer: function() {
		this.timer = undefined;

		this.isDrag = true;
		this.dragAllowed = true;
		this.disconnect(window, 'mousemove', this.onMouseMove, true);

		this.clock = new Anim.Clock({ duration: 'forever' });
		this.connect(this.clock, 'timeupdate', this.onAnim);
		this.clock.begin();
	},

	onKeyUp: function(event) {
		var key = event.which;
		if((key == 13) && !this.getIsDisabled() && !this.lock) {
			event.preventDefault();
			event.stopPropagation();
			this.fireEvent('press', this);
		}
	},

	onAnim: function(clock) {
		var progress = (clock.getGlobalTime() % 0.8) / 0.8;
		var ease = new Anim.ElasticEase({ mode: 'inout' });
		progress = ease.ease(progress);

		var scale = 1 + (progress/12);
		this.setTransform(Ui.Matrix.createScale(scale, scale));
	}
});

<|endoftext|>


<commit_before>import R from 'ramda';
import { requestCoursework } from '../../../datasource/network';
import {
  parseCourses,
  parseCoursework,
  parseMidterms,
} from '../../../datasource/parser';
import { filterBy } from '../helpers';

const augmentCoursework = coursework => course =>
  R.assoc('coursework', R.filter(R.propEq('code', course.code))(coursework))(
    course,
  );

const augmentMidterm = midterms => course =>
  R.assoc('midterm', R.find(R.propEq('code', course.code))(midterms))(course);

const coursesResolver = async (obj, args, context) => {
  const { code } = args;
  const { username, password } = context;

  const response = await requestCoursework({ username, password });

  const courses = parseCourses(response);
  const coursework = parseCoursework(response);
  const midterms = parseMidterms(response);

  return R.pipe(
    filterBy('code', code),
    R.map(R.pipe(augmentCoursework(coursework), augmentMidterm(midterms))),
  )(courses);
};

export default coursesResolver;
<commit_msg>:hammer: Disentangle nested operations<commit_after>import R from 'ramda';
import { requestCoursework } from '../../../datasource/network';
import {
  parseCourses,
  parseCoursework,
  parseMidterms,
} from '../../../datasource/parser';
import { filterBy } from '../helpers';

const augmentCoursework = coursework => course =>
  R.assoc('coursework', R.filter(R.propEq('code', course.code))(coursework))(
    course,
  );

const augmentMidterm = midterms => course =>
  R.assoc('midterm', R.find(R.propEq('code', course.code))(midterms))(course);

const coursesResolver = async (obj, args, context) => {
  const { code } = args;
  const { username, password } = context;

  const response = await requestCoursework({ username, password });

  const courses = parseCourses(response);
  const coursework = parseCoursework(response);
  const midterms = parseMidterms(response);

  return R.pipe(
    filterBy('code', code),
    R.map(augmentCoursework(coursework)),
    R.map(augmentMidterm(midterms)),
  )(courses);
};

export default coursesResolver;
<|endoftext|>


<commit_before>describe("lange-ui", function() {
    var addCheckBoxesToEvents = LangeUI.addCheckBoxesToEvents;
    var renderPlan = LangeUI.renderPlan;
    var extractSelectedEvents = LangeUI.extractSelectedEvents;
    var numEvents;

    beforeEach(function(){
        myLoadFixture("selected_events.html");
    });

    function loadEventsFixture(){
        myLoadFixture("events.html");
        numEvents = $(".vevent").length;
        expect(numEvents).toBeGreaterThan(0);
        expect($(".vevent>input.fancy-checkbox").length).toEqual(0);
    };

    it("should add checkboxes to all events", function(){
        loadEventsFixture();

        addCheckBoxesToEvents();

        expect($(".vevent>input.fancy-checkbox").length).toEqual(numEvents);
    });

    it("should add class 'selected' to an event when it's checkbox is clicked", function(){
        loadEventsFixture();
        addCheckBoxesToEvents();

        $('.fancy-checkbox').first().click();

        expect($('.vevent').first()).toHaveClass('selected');
    });

    it("should extract selected events from html", function() {
        var expectedEvents =  [
            { id : 0, summary : 'See Jellyfish Play Guitar', dtstart : '2011-07-21T13:00', dateDescription : '1pm, July 21' }
        ];

        expect(extractSelectedEvents()).toEqual(expectedEvents);
    });

    it("should renderPlan when event is selected", function(){
        spyOn(LangeUI, 'renderPlan');

        addCheckBoxesToEvents();
        $('.vevent:not(.selected) .fancy-checkbox').click();

        expect(LangeUI.renderPlan).toHaveBeenCalled();
    });

    it("should toggle selected events", function(){
        spyOn(LangeUI, 'renderPlan');

        addCheckBoxesToEvents();
        $('.vevent.selected .fancy-checkbox').click();
        $('.vevent:not(.selected) .fancy-checkbox').click();

        expect(extractSelectedEvents().length).toEqual($(".vevent").length);
    });
});
<commit_msg>refactor test to deselect event<commit_after>describe("lange-ui", function() {
    var addCheckBoxesToEvents = LangeUI.addCheckBoxesToEvents;
    var renderPlan = LangeUI.renderPlan;
    var extractSelectedEvents = LangeUI.extractSelectedEvents;
    var numEvents;

    beforeEach(function(){
        myLoadFixture("selected_events.html");
    });

    function loadEventsFixture(){
        myLoadFixture("events.html");
        numEvents = $(".vevent").length;
        expect(numEvents).toBeGreaterThan(0);
        expect($(".vevent>input.fancy-checkbox").length).toEqual(0);
    };

    it("should add checkboxes to all events", function(){
        loadEventsFixture();

        addCheckBoxesToEvents();

        expect($(".vevent>input.fancy-checkbox").length).toEqual(numEvents);
    });

    it("should add class 'selected' to an event when it is checked", function(){
        loadEventsFixture();
        addCheckBoxesToEvents();

        $('.fancy-checkbox').first().click();

        expect($('.vevent').first()).toHaveClass('selected');
    });

    it("should remove class 'selected' from an event when it is unchecked", function(){
        loadEventsFixture();
        addCheckBoxesToEvents();
        $('.fancy-checkbox').first().click();
        $('.fancy-checkbox').first().click();

        expect($('.vevent').first()).not.toHaveClass('selected');
    });

    it("should extract selected events from html", function() {
        var expectedEvents =  [
            { id : 0, summary : 'See Jellyfish Play Guitar', dtstart : '2011-07-21T13:00', dateDescription : '1pm, July 21' }
        ];

        expect(extractSelectedEvents()).toEqual(expectedEvents);
    });

    it("should renderPlan when event is selected", function(){
        spyOn(LangeUI, 'renderPlan');

        addCheckBoxesToEvents();
        $('.vevent:not(.selected) .fancy-checkbox').click();

        expect(LangeUI.renderPlan).toHaveBeenCalled();
    });

});
<|endoftext|>


<commit_before>const gulp = require('gulp')
const browserSync = require('browser-sync').create()

const sass = require('gulp-sass')
const sourcemaps = require('gulp-sourcemaps')
const autoprefixer = require('gulp-autoprefixer')

gulp.task('sass', function () {
  gulp.src('./app/src/sass/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({ outputStyle: 'expanded'} ).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe( autoprefixer({ browsers: ['last 2 versions'] }) )
    .pipe(gulp.dest('./app/assets/css/'))
    .pipe(browserSync.stream())
})

gulp.task('serve', ['sass'], function () {
  browserSync.init({
    server: "./app",
    injectChanges: true,
    notify: false
  })

  gulp.watch('./app/src/sass/*.scss', ['sass'])
  gulp.watch('./app/*.html').on('change', browserSync.reload)
})

gulp.task('default', ['serve'])
<commit_msg>Update gulpfile<commit_after>const gulp = require('gulp')
const browserSync = require('browser-sync').create()

const sass = require('gulp-sass')
const sourcemaps = require('gulp-sourcemaps')
const autoprefixer = require('gulp-autoprefixer')

gulp.task('sass', function () {
  gulp.src('./app/src/sass/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({ outputStyle: 'expanded'} ).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe( autoprefixer({ browsers: ['last 2 versions'] }) )
    .pipe(gulp.dest('./app/assets/css/'))
    .pipe(browserSync.stream())
})

gulp.task('serve', ['sass'], function () {
  browserSync.init({
    server: "./app",
    injectChanges: true,
    notify: false
  })

  gulp.watch('./app/src/sass/**/*.scss', ['sass'])
  gulp.watch('./app/*.html').on('change', browserSync.reload)
})

gulp.task('default', ['serve'])
<|endoftext|>


<commit_before>var Stream = require('../models/streamsModel');
var User = require('../models/usersModel');
var usersController = require('./usersController');

module.exports = {
  createStream: function(req, res, next) {
    var streamName = req.body.name;
    var streamDesc = req.body.desc;
    //to make location into array
    var streamLongitude = req.body.lng;
    var streamLatitude = req.body.lat;
    var streamCreator = req.body.creator;

    User.findOne({
      scId: streamCreator.id
    }, function(err, user) {
      if (user) {
        console.log('creator found');
        console.log(user)
        var newStream = new Stream({
          name: streamName,
          broadcaster: user.scUsername,
          description: streamDesc,
          heartCountNum: 0,
          listenerMaxCount: 0,
          listenerLiveCount: 0,
          timestamp: Date.now(),
          playing: false,
          latitude: streamLatitude,
          longitude: streamLongitude,
          creator: user._id
        });
        newStream.save(function(err, stream) {
          if (err) {
            throw err;
          }
          else {
            res.status(201).send(stream);
          }
        });
      }
      else {
        usersController.createUser(streamCreator, function(user) {
          var newStream = new Stream({
            name: streamName,
            broadcaster: user.scUsername,
            description: streamDesc,
            heartCountNum: 0,
            listenerMaxCount: 0,
            listenerLiveCount: 0,
            timestamp: Date.now(),
            playing: false,
            latitude: streamLatitude,
            longitude: streamLongitude,
            creator: user._id
          });
          newStream.save(function(err, stream) {
            if (err) {
              throw err
            }
            else {
              res.status(201).send(stream);
            }
          });
        });
      }
    });
  },

  getStream: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      if (stream) {
        res.status(200).send(stream);
      }
      else {
        res.status(404).send('stream not found');
      }
      // if (err) {
      //   throw err;
      // }
      // else {
      //   res.status(200).send(stream);
      // }
    });
  },

  upHeart: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.heartCountNum++;
      console.log('updated the heartCount');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  },

  toggleStream: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.playing = !stream.playing;
      console.log('updated stream status');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  }

  addListener: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.listenerLiveCount++;
      stream.listenerMaxCount = Math.max(stream.listenerMaxCount, stream.listenerLiveCount);
      console.log('added listener');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  },

  removeListener: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.listenerLiveCount--;
      console.log('removed listener');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).doc;
        }
      });
    });
  },

  modifyStreamDetails: function(req, res, next) {
    var streamId = req.params.stream;
    var streamName = req.body.name;
    var streamDesc = req.body.desc;
    var streamLocation = req.body.loc;
    Stream.findOneAndUpdate({_id: streamId}, {description: streamDesc, location: streamLocation},
      function(err, doc) {
        if (err) {
          throw err;
        }
        else {
          res.status(200).send(doc);
        }
      });
  },

  getAllStreams: function(req, res, next) {
    Stream.find({}, function(err, docs) {
      if (err) {
        throw err;
      }
      else {
        res.send(docs);
      }
    });
  }

};<commit_msg>Return only playing streams.<commit_after>var Stream = require('../models/streamsModel');
var User = require('../models/usersModel');
var usersController = require('./usersController');

module.exports = {
  createStream: function(req, res, next) {
    var streamName = req.body.name;
    var streamDesc = req.body.desc;
    //to make location into array
    var streamLongitude = req.body.lng;
    var streamLatitude = req.body.lat;
    var streamCreator = req.body.creator;

    User.findOne({
      scId: streamCreator.id
    }, function(err, user) {
      if (user) {
        console.log('creator found');
        console.log(user)
        var newStream = new Stream({
          name: streamName,
          broadcaster: user.scUsername,
          description: streamDesc,
          heartCountNum: 0,
          listenerMaxCount: 0,
          listenerLiveCount: 0,
          timestamp: Date.now(),
          playing: false,
          latitude: streamLatitude,
          longitude: streamLongitude,
          creator: user._id
        });
        newStream.save(function(err, stream) {
          if (err) {
            throw err;
          }
          else {
            res.status(201).send(stream);
          }
        });
      }
      else {
        usersController.createUser(streamCreator, function(user) {
          var newStream = new Stream({
            name: streamName,
            broadcaster: user.scUsername,
            description: streamDesc,
            heartCountNum: 0,
            listenerMaxCount: 0,
            listenerLiveCount: 0,
            timestamp: Date.now(),
            playing: false,
            latitude: streamLatitude,
            longitude: streamLongitude,
            creator: user._id
          });
          newStream.save(function(err, stream) {
            if (err) {
              throw err
            }
            else {
              res.status(201).send(stream);
            }
          });
        });
      }
    });
  },

  getStream: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      if (stream) {
        res.status(200).send(stream);
      }
      else {
        res.status(404).send('stream not found');
      }
      // if (err) {
      //   throw err;
      // }
      // else {
      //   res.status(200).send(stream);
      // }
    });
  },

  upHeart: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.heartCountNum++;
      console.log('updated the heartCount');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  },

  toggleStream: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.playing = !stream.playing;
      console.log('updated stream status');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  }

  addListener: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.listenerLiveCount++;
      stream.listenerMaxCount = Math.max(stream.listenerMaxCount, stream.listenerLiveCount);
      console.log('added listener');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).send(doc);
        }
      });
    });
  },

  removeListener: function(req, res, next) {
    var streamId = req.params.stream;
    Stream.findById(streamId, function(err, stream) {
      stream.listenerLiveCount--;
      console.log('removed listener');
      stream.save(function(err, doc) {
        if (err) {
          return err;
        }
        else {
          res.status(200).doc;
        }
      });
    });
  },

  modifyStreamDetails: function(req, res, next) {
    var streamId = req.params.stream;
    var streamName = req.body.name;
    var streamDesc = req.body.desc;
    var streamLocation = req.body.loc;
    Stream.findOneAndUpdate({_id: streamId}, {description: streamDesc, location: streamLocation},
      function(err, doc) {
        if (err) {
          throw err;
        }
        else {
          res.status(200).send(doc);
        }
      });
  },

  getAllStreams: function(req, res, next) {
    Stream.find({playing: true}, function(err, docs) {
      if (err) {
        throw err;
      }
      else {
        res.send(docs);
      }
    });
  }

};<|endoftext|>


<commit_before>
/**
 * TabNavigator UI-Component for static and dinamic content.
 * @name TabNavigator
 * @class TabNavigator
 * @augments ch.Controllers
 * @memberOf ch
 * @param {Configuration Object} conf Object with configuration properties
 * @returns {Chico-UI Object}
 */

ch.tabNavigator = function(conf){

    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.TabNavigator
     */
	var that = this;

	conf = ch.clon(conf);

	that.conf = conf;

/**
 *	Inheritance
 */

    that = ch.controllers.call(that);
    that.parent = ch.clon(that);

/**
 *  Private Members
 */

    /**
     * The actual location hash, is used to know if there's a specific tab selected.
     * @private
     * @name hash
     * @type {String}
     * @memberOf ch.TabNavigator
     */
	var hash = window.location.hash.replace("#!", "");
    /**
     * A boolean property to know if the some tag should be selected.
     * @private
     * @name hashed
     * @type {Boolean}
     * @default false
     * @memberOf ch.TabNavigator
     */
    var hashed = false;
    /**
     * Get wich tab is selected.
     * @private
     * @name selected
     * @type {Number}
     * @memberOf ch.TabNavigator
     */
    var selected = conf.selected - 1 || conf.value - 1 || 0;
    /**
     * Create controller's children.
     * @private
     * @name createTabs
     * @function
     * @memberOf ch.TabNavigator
     */
	var createTabs = function(){

		// Children
		that.$triggers.find("a").each(function(i, e){

			// Tab context
			var tab = {};
				tab.uid = that.uid + "#" + i;
				tab.type = "tab";
				tab.element = e;
				tab.$element = $(e);
				tab.controller = that["public"];

			// Tab configuration
			var config = {};
				config.open = (selected == i);
				config.onShow = function(){
					selected = i;
				};

			if(ch.utils.hasOwn(that.conf, "cache")) {
				config.cache = that.conf.cache;
			};

           /**
            * Callback function
            * @name onContentLoad
            * @type {Function}
            * @memberOf ch.TabNavigator
            */
			if ( ch.utils.hasOwn(that.conf, "onContentLoad") ) config.onContentLoad = that.conf.onContentLoad;
           /**
            * Callback function
            * @name onContentError
            * @type {Function}
            * @memberOf ch.TabNavigator
            */
			if ( ch.utils.hasOwn(that.conf, "onContentError") ) config.onContentError = that.conf.onContentError;

			// Create Tabs
			that.children.push(
				ch.tab.call(tab, config)
			);

			// Bind new click to have control
			$(e).unbind("click").bind("click", function(event){
				that.prevent(event);
				select(i + 1);
			});

		});

		return;

	};
    /**
     * Select a child to show its content.
     * @private
     * @function
     * @memberOf ch.TabNavigator
     */
	var select = function(tab){

		tab = that.children[tab - 1];

		if(tab === that.children[selected]) return; // Don't click me if I'm open

		// Hide my open bro
		$.each(that.children, function(i, e){
			if(tab !== e) e.hide();
		});

		tab.show();

        //Change location hash
		window.location.hash = "#!" + tab.$content.attr("id");

       /**
        * Callback function
        * @name onSelect
        * @type {Function}
        * @memberOf ch.TabNavigator
        */
		that.callbacks("onSelect");

        return that;
	};

/**
 *  Protected Members
 */

    /**
     * The component's triggers container.
     * @private
     * @name $triggers
     * @type {jQuery Object}
     * @memberOf ch.TabNavigator
     */
	that.$triggers = that.$element.children(":first").addClass("ch-tabNavigator-triggers");

    /**
     * The component's content.
     * @private
     * @name $content
     * @type {jQuery Object}
     * @memberOf ch.TabNavigator
     */
	that.$content = that.$triggers.next().addClass("ch-tabNavigator-content box");

/**
 *  Public Members
 */

    /**
     * The component's instance unique identifier.
     * @public
     * @name uid
     * @type {Number}
     * @memberOf ch.TabNavigator
     */
	that["public"].uid = that.uid;
    /**
     * The element reference.
     * @public
     * @name element
     * @type {HTMLElement}
     * @memberOf ch.TabNavigator
     */
	that["public"].element = that.element;
    /**
     * The component's type.
     * @public
     * @name type
     * @type {String}
     * @memberOf ch.TabNavigator
     */
	that["public"].type = that.type;
    /**
     * Children instances associated to this controller.
     * @public
     * @name children
     * @type {Collection}
     * @memberOf ch.TabNavigator
     */
	that["public"].children = that.children;
    /**
     * Select a specific child.
     * @public
     * @function
     * @name select
     * @param {Number} tab Tab's index.
     * @memberOf ch.TabNavigator
     */
	that["public"].select = function(tab){
		select(tab);

		return that["public"];
	};
    /**
     * Returns the selected child's index.
     * @public
     * @function
     * @name getSelected
     * @returns {Number} selected Tab's index.
     * @memberOf ch.TabNavigator
     */
	that["public"].getSelected = function(){ return (selected + 1); };

/**
 *  Default event delegation
 */

    that.$element.addClass("ch-tabNavigator");

	createTabs();

	//Default: Load hash tab or Open first tab
	for(var i = that.children.length; i--; ){
		if ( that.children[i].$content.attr("id") === hash ) {
			select(i + 1);

			hashed = true;

			break;
		};
	};

	return that;

};

/**
 * Simple unit of content for TabNavigators.
 * @abstract
 * @name Tab
 * @class Tab
 * @augments ch.Navs
 * @memberOf ch
 * @param {Configuration Object} conf Object with configuration properties
 * @returns {Chico-UI Object}
 */

ch.tab = function(conf){
    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.Tab
     */
    var that = this;

	conf = ch.clon(conf);
	conf.icon = false;

	that.conf = conf;

/**
 *	Inheritance
 */

	that = ch.navs.call(that);
	that.parent = ch.clon(that);

/**
 *  Private Members
 */
    /**
     * Creates the basic structure for the tab's content.
     * @private
     * @name createContent
     * @function
     * @memberOf ch.Tab
     */
	var createContent = function(){
		var href = that.element.href.split("#");
		var controller = that.$element.parents(".ch-tabNavigator");
		var content = controller.find("#" + href[1]);

		// If there are a tabContent...
		if ( content.length > 0 ) {

			return content;

		// If tabContent doesn't exists
		} else {
			/**
		     * Content configuration property.
		     * @public
		     * @name source
		     * @type {String}
		     * @memberOf ch.Tab
		     */
			that.source = that.element.href;

			var id = (href.length == 2) ? href[1] : "ch-tab" + that.uid.replace("#","-");

			// Create tabContent
			return $("
").appendTo( controller.children().eq(1) );
		};

	};

/**
 *  Protected Members
 */
    /**
     * Reference to the trigger element.
     * @private
     * @name $trigger
     * @type {jQuery Object}
     * @memberOf ch.Tab
     */
	that.$trigger = that.$element;

    /**
     * The component's content.
     * @private
     * @name $content
     * @type {jQuery Object}
     * @memberOf ch.Tab
     */
	that.$content = createContent();

    /**
     * Process the show event.
     * @private
     * @function
     * @name show
     * @returns {jQuery Object}
     * @memberOf ch.Tab
     */
	that.show = function(event){
		that.prevent(event);

		// Load my content if I'need an ajax request
		if( ch.utils.hasOwn(that, "source") ) {
			that.$content.html( that.content() );
		};

		// Show me
		that.parent.show(event);

		return that;
	};

	/**
     * This callback is triggered when async data is loaded into component's content, when ajax content comes back.
     * @public
     * @name contentCallback
     * @returns {Chico-UI Object}
     * @memberOf ch.TabNavigator
     */
    that.contentCallback = function(data) {
		that.staticContent = data;
        that.$content.html(that.staticContent);
    };

/**
 *  Public Members
 */

/**
 *  Default event delegation
 */

	that.configBehavior();

	return that;
}
<commit_msg>Added new callbacks on TabNavigator.js<commit_after>
/**
 * TabNavigator UI-Component for static and dinamic content.
 * @name TabNavigator
 * @class TabNavigator
 * @augments ch.Controllers
 * @memberOf ch
 * @param {Configuration Object} conf Object with configuration properties
 * @returns {Chico-UI Object}
 */

ch.tabNavigator = function(conf){

    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.TabNavigator
     */
	var that = this;

	conf = ch.clon(conf);

	that.conf = conf;

/**
 *	Inheritance
 */

    that = ch.controllers.call(that);
    that.parent = ch.clon(that);

/**
 *  Private Members
 */

    /**
     * The actual location hash, is used to know if there's a specific tab selected.
     * @private
     * @name hash
     * @type {String}
     * @memberOf ch.TabNavigator
     */
	var hash = window.location.hash.replace("#!", "");
    /**
     * A boolean property to know if the some tag should be selected.
     * @private
     * @name hashed
     * @type {Boolean}
     * @default false
     * @memberOf ch.TabNavigator
     */
    var hashed = false;
    /**
     * Get wich tab is selected.
     * @private
     * @name selected
     * @type {Number}
     * @memberOf ch.TabNavigator
     */
    var selected = conf.selected - 1 || conf.value - 1 || 0;
    /**
     * Create controller's children.
     * @private
     * @name createTabs
     * @function
     * @memberOf ch.TabNavigator
     */
	var createTabs = function(){

		// Children
		that.$triggers.find("a").each(function(i, e){

			// Tab context
			var tab = {};
				tab.uid = that.uid + "#" + i;
				tab.type = "tab";
				tab.element = e;
				tab.$element = $(e);
				tab.controller = that["public"];

			// Tab configuration
			var config = {};
				config.open = (selected == i);
				config.onShow = function(){
					selected = i;
				};

			if(ch.utils.hasOwn(that.conf, "cache")) {
				config.cache = that.conf.cache;
			};

           /**
            * Callback function
            * @name onContentLoad
            * @type {Function}
            * @memberOf ch.TabNavigator
            */
			if ( ch.utils.hasOwn(that.conf, "onContentLoad") ) config.onContentLoad = that.conf.onContentLoad;
           /**
            * Callback function
            * @name onContentError
            * @type {Function}
            * @memberOf ch.TabNavigator
            */
			if ( ch.utils.hasOwn(that.conf, "onContentError") ) config.onContentError = that.conf.onContentError;

			// Create Tabs
			that.children.push(
				ch.tab.call(tab, config)
			);

			// Bind new click to have control
			$(e).unbind("click").bind("click", function(event){
				that.prevent(event);
				select(i + 1);
			});

		});

		return;

	};
    /**
     * Select a child to show its content.
     * @private
     * @function
     * @memberOf ch.TabNavigator
     */
	var select = function(tab){

		tab = that.children[tab - 1];

		if(tab === that.children[selected]) return; // Don't click me if I'm open

		// Hide my open bro
		$.each(that.children, function(i, e){
			if(tab !== e) e.hide();
		});

		tab.show();

        //Change location hash
		window.location.hash = "#!" + tab.$content.attr("id");

       /**
        * Callback function
        * @name onSelect
        * @type {Function}
        * @memberOf ch.TabNavigator
        */
		that.callbacks("onSelect");
		// new callback
		that.trigger("select");

        return that;
	};

/**
 *  Protected Members
 */

    /**
     * The component's triggers container.
     * @private
     * @name $triggers
     * @type {jQuery Object}
     * @memberOf ch.TabNavigator
     */
	that.$triggers = that.$element.children(":first").addClass("ch-tabNavigator-triggers");

    /**
     * The component's content.
     * @private
     * @name $content
     * @type {jQuery Object}
     * @memberOf ch.TabNavigator
     */
	that.$content = that.$triggers.next().addClass("ch-tabNavigator-content box");

/**
 *  Public Members
 */

    /**
     * The component's instance unique identifier.
     * @public
     * @name uid
     * @type {Number}
     * @memberOf ch.TabNavigator
     */
	that["public"].uid = that.uid;
    /**
     * The element reference.
     * @public
     * @name element
     * @type {HTMLElement}
     * @memberOf ch.TabNavigator
     */
	that["public"].element = that.element;
    /**
     * The component's type.
     * @public
     * @name type
     * @type {String}
     * @memberOf ch.TabNavigator
     */
	that["public"].type = that.type;
    /**
     * Children instances associated to this controller.
     * @public
     * @name children
     * @type {Collection}
     * @memberOf ch.TabNavigator
     */
	that["public"].children = that.children;
    /**
     * Select a specific child.
     * @public
     * @function
     * @name select
     * @param {Number} tab Tab's index.
     * @memberOf ch.TabNavigator
     */
	that["public"].select = function(tab){
		select(tab);

		return that["public"];
	};
    /**
     * Returns the selected child's index.
     * @public
     * @function
     * @name getSelected
     * @returns {Number} selected Tab's index.
     * @memberOf ch.TabNavigator
     */
	that["public"].getSelected = function(){ return (selected + 1); };

/**
 *  Default event delegation
 */

    that.$element.addClass("ch-tabNavigator");

	createTabs();

	//Default: Load hash tab or Open first tab
	for(var i = that.children.length; i--; ){
		if ( that.children[i].$content.attr("id") === hash ) {
			select(i + 1);

			hashed = true;

			break;
		};
	};

	return that;

};

/**
 * Simple unit of content for TabNavigators.
 * @abstract
 * @name Tab
 * @class Tab
 * @augments ch.Navs
 * @memberOf ch
 * @param {Configuration Object} conf Object with configuration properties
 * @returns {Chico-UI Object}
 */

ch.tab = function(conf){
    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.Tab
     */
    var that = this;

	conf = ch.clon(conf);
	conf.icon = false;

	that.conf = conf;

/**
 *	Inheritance
 */

	that = ch.navs.call(that);
	that.parent = ch.clon(that);

/**
 *  Private Members
 */
    /**
     * Creates the basic structure for the tab's content.
     * @private
     * @name createContent
     * @function
     * @memberOf ch.Tab
     */
	var createContent = function(){
		var href = that.element.href.split("#");
		var controller = that.$element.parents(".ch-tabNavigator");
		var content = controller.find("#" + href[1]);

		// If there are a tabContent...
		if ( content.length > 0 ) {

			return content;

		// If tabContent doesn't exists
		} else {
			/**
		     * Content configuration property.
		     * @public
		     * @name source
		     * @type {String}
		     * @memberOf ch.Tab
		     */
			that.source = that.element.href;

			var id = (href.length == 2) ? href[1] : "ch-tab" + that.uid.replace("#","-");

			// Create tabContent
			return $("
").appendTo( controller.children().eq(1) );
		};

	};

/**
 *  Protected Members
 */
    /**
     * Reference to the trigger element.
     * @private
     * @name $trigger
     * @type {jQuery Object}
     * @memberOf ch.Tab
     */
	that.$trigger = that.$element;

    /**
     * The component's content.
     * @private
     * @name $content
     * @type {jQuery Object}
     * @memberOf ch.Tab
     */
	that.$content = createContent();

    /**
     * Process the show event.
     * @private
     * @function
     * @name show
     * @returns {jQuery Object}
     * @memberOf ch.Tab
     */
	that.show = function(event){
		that.prevent(event);

		// Load my content if I'need an ajax request
		if( ch.utils.hasOwn(that, "source") ) {
			that.$content.html( that.content() );
		};

		// Show me
		that.parent.show(event);

		return that;
	};

	/**
     * This callback is triggered when async data is loaded into component's content, when ajax content comes back.
     * @public
     * @name contentCallback
     * @returns {Chico-UI Object}
     * @memberOf ch.TabNavigator
     */
    that.contentCallback = function(data) {
		that.staticContent = data;
        that.$content.html(that.staticContent);
    };

/**
 *  Public Members
 */

/**
 *  Default event delegation
 */

	that.configBehavior();

	return that;
}
<|endoftext|>


<commit_before>
$(document).ready(function () {

    var container = $('#picture-container');
    var containerWidth = container.width();

    var xInput = $('#pic-x');
    var yInput = $('#pic-y');
    var x2Input = $('#pic-x2');
    var y2Input = $('#pic-y2');
    var widthInput = $('#pic-width');
    var heightInput = $('#pic-height');
    var originalWidthInput = $('#original-width');
    var originalHeightInput = $('#original-height');

    var setCoords = function (c) {
        xInput.val(c.x);
        yInput.val(c.y);
        x2Input.val(c.x2);
        y2Input.val(c.y2);
        widthInput.val(c.w);
        heightInput.val(c.h);
    };

    var getSelectCoords = function (width, height) {
        var x, y, x2, y2;

        if (width > height) {
            x = (width / 2) - (height / 2);
            y = 0;
            x2 = height;
            y2 = height;
        } else if (width < height) {
            x = 0;
            y = (height / 2) - (width / 2);
            x2 = width;
            y2 = width;
        } else {
            x = 0;
            y = 0;
            x2 = width;
            y2 = height;
        }

        return {
            x: x,
            y: y,
            x2: x2,
            y2: y2
        };
    };

    $('#picture-file').change(function (e) {
        container.empty();
        container.append('

');
        var thumb = container.children('#picture-thumb');

        loadImage(
            e.target.files[0],
            function (img) {
                var coords = getSelectCoords(img.width, img.height);

                originalWidthInput.val(img.width);
                originalHeightInput.val(img.height);

                thumb.html(img);
                thumb.Jcrop({
                    aspectRatio: 1,
                    setSelect: [coords.x, coords.y, coords.x2, coords.y2],
                    onChange: setCoords,
                    onSelect: setCoords
                });
            },
            {maxWidth: containerWidth}
        );

    });

});
<commit_msg>Added possibility to upload an image without crop<commit_after>
$(document).ready(function () {

    var container = $('#picture-container');
    var containerWidth = container.width();
    var cropPicContainer = $('#crop-pic-container');
    var cropPicInput = $('#crop-pic');

    var xInput = $('#pic-x');
    var yInput = $('#pic-y');
    var x2Input = $('#pic-x2');
    var y2Input = $('#pic-y2');
    var widthInput = $('#pic-width');
    var heightInput = $('#pic-height');
    var originalWidthInput = $('#original-width');
    var originalHeightInput = $('#original-height');

    var noCrop = function () {
        cropPicInput.prop('checked', false);
    };

    var setCoords = function (c) {
        xInput.val(c.x);
        yInput.val(c.y);
        x2Input.val(c.x2);
        y2Input.val(c.y2);
        widthInput.val(c.w);
        heightInput.val(c.h);

        cropPicInput.prop('checked', true);
    };

    var getSelectCoords = function (width, height) {
        var x, y, x2, y2;

        if (width > height) {
            x = (width / 2) - (height / 2);
            y = 0;
            x2 = height;
            y2 = height;
        } else if (width < height) {
            x = 0;
            y = (height / 2) - (width / 2);
            x2 = width;
            y2 = width;
        } else {
            x = 0;
            y = 0;
            x2 = width;
            y2 = height;
        }

        return {
            x: x,
            y: y,
            x2: x2,
            y2: y2
        };
    };

    $('#picture-file').change(function (e) {
        container.empty();
        container.append('

');

        var thumb = container.children('#picture-thumb');

        loadImage(
            e.target.files[0],
            function (img) {
                var coords = getSelectCoords(img.width, img.height);

                originalWidthInput.val(img.width);
                originalHeightInput.val(img.height);

                thumb.html(img);
                thumb.Jcrop({
                    aspectRatio: 1,
                    setSelect: [coords.x, coords.y, coords.x2, coords.y2],
                    onChange: setCoords,
                    onSelect: setCoords,
                    onRelease: noCrop
                });
            },
            {maxWidth: containerWidth}
        );

        cropPicContainer.show();

    });

    /*$('#crop-pic').change(function (e) {

    });*/

});
<|endoftext|>


<commit_before>var crel = require('crel');
var qsa = require('cog/qsa');
var loader = require('cog/loader');
var main = qsa('.main')[0];
var reStatusOK = /^(2|3)\d{2}$/;
var reStripExt = /^(.*)\.js$/;
var baseScripts = [
  'http://sig.rtc.io:50000/rtc.io/primus.js'
];

function createCodeFrame(sample, anchor, callback) {
  var frameContainer;
  var frame;
  var closeBar;
  var content;
  var xhr = new XMLHttpRequest();
  var sampleHTML = '';

  frameContainer = crel('div', { class: 'codeframe' },
    closeBar = crel('div', { class: 'closer' }, 'close sample'),
    frame = crel('iframe')
  );

  // insert the code frame
  document.body.insertBefore(frameContainer, main);

  // initialise the content
  content = frame.contentDocument || frame.contentWindow.document;

  // check if we have custom html for this demo
  xhr.open('GET', 'code/' + sample + '.html');
  xhr.onload = function() {
    // if we got it, then use that as the document
    if (this.status === 200) {
      sampleHTML = this.response;
    }

    // write the sample html into the frame
    content.open();
    content.write(sampleHTML);
    content.close();

    // trigger the callback
    callback(frameContainer, content);
  };

  xhr.send();
}

function initSample(anchor) {

  function closeCode() {
    var frame = anchor.codeframe;

    // if the anchor already has a codeframe associated with it dropit
    if (frame) {
      frame.className = 'codeframe';
      anchor.codeframe = null;

      setTimeout(function() {
        frame.parentNode.removeChild(frame);
      }, 500);
    }
  }

  anchor.addEventListener('click', function(evt) {
    var sample = (anchor.dataset.sample || '').replace(reStripExt, '$1');
    var frame;

    // don't do the default click anchor thing...
    evt.preventDefault();

    // create the code frame
    createCodeFrame(sample, anchor, function(frame, doc) {
      var style = doc.createElement('style');
      style.innerHTML = [
        'html { overflow: hidden; }',
        'body { width: 820px; margin: 5px auto 0; }',
        'body video { width: 100% }',
        'body canvas { width: 100% }'
      ].join('\n');

      doc.head.appendChild(style);

      // load the required scripts
      loader(baseScripts, { target: doc.body }, function() {
        loader('js/samples/' + sample + '.js', { target: doc.body });

        setTimeout(function() {
          frame.className += ' active';
        }, 100);
      });

      // associate the code frame with the frame
      anchor.codeframe = frame;
      qsa('.closer', frame)[0].addEventListener('click', closeCode);
    });
  });
}

qsa('.sample').forEach(initSample);
<commit_msg>Fix primus script link so samples run again<commit_after>var crel = require('crel');
var qsa = require('cog/qsa');
var loader = require('cog/loader');
var main = qsa('.main')[0];
var reStatusOK = /^(2|3)\d{2}$/;
var reStripExt = /^(.*)\.js$/;
var baseScripts = [
  'http://rtc.io/switchboard/rtc.io/primus.js'
];

function createCodeFrame(sample, anchor, callback) {
  var frameContainer;
  var frame;
  var closeBar;
  var content;
  var xhr = new XMLHttpRequest();
  var sampleHTML = '';

  frameContainer = crel('div', { class: 'codeframe' },
    closeBar = crel('div', { class: 'closer' }, 'close sample'),
    frame = crel('iframe')
  );

  // insert the code frame
  document.body.insertBefore(frameContainer, main);

  // initialise the content
  content = frame.contentDocument || frame.contentWindow.document;

  // check if we have custom html for this demo
  xhr.open('GET', 'code/' + sample + '.html');
  xhr.onload = function() {
    // if we got it, then use that as the document
    if (this.status === 200) {
      sampleHTML = this.response;
    }

    // write the sample html into the frame
    content.open();
    content.write(sampleHTML);
    content.close();

    // trigger the callback
    callback(frameContainer, content);
  };

  xhr.send();
}

function initSample(anchor) {

  function closeCode() {
    var frame = anchor.codeframe;

    // if the anchor already has a codeframe associated with it dropit
    if (frame) {
      frame.className = 'codeframe';
      anchor.codeframe = null;

      setTimeout(function() {
        frame.parentNode.removeChild(frame);
      }, 500);
    }
  }

  anchor.addEventListener('click', function(evt) {
    var sample = (anchor.dataset.sample || '').replace(reStripExt, '$1');
    var frame;

    // don't do the default click anchor thing...
    evt.preventDefault();

    // create the code frame
    createCodeFrame(sample, anchor, function(frame, doc) {
      var style = doc.createElement('style');
      style.innerHTML = [
        'html { overflow: hidden; }',
        'body { width: 820px; margin: 5px auto 0; }',
        'body video { width: 100% }',
        'body canvas { width: 100% }'
      ].join('\n');

      doc.head.appendChild(style);

      // load the required scripts
      loader(baseScripts, { target: doc.body }, function() {
        loader('js/samples/' + sample + '.js', { target: doc.body });

        setTimeout(function() {
          frame.className += ' active';
        }, 100);
      });

      // associate the code frame with the frame
      anchor.codeframe = frame;
      qsa('.closer', frame)[0].addEventListener('click', closeCode);
    });
  });
}

qsa('.sample').forEach(initSample);
<|endoftext|>