<commit_before>Core.Object.extend('Anim.TimeManager',
/**@lends Anim.TimeManager#*/
{
	clocks: undefined,
	timer: undefined,
	start: 0,

	/**
    *   @constructs
	*	@class The TimeManager handle animations clocks
    *   @extends Core.Object
	*/
	constructor: function(config) {
		this.clocks = [];
		this.start = new Date().getTime();
		this.addEvents('tick');
	},

	add: function(clock) {
		this.clocks.push(clock);
		if(this.clocks.length === 1)
			this.timer = new Core.Timer({ onTimeupdate: this.onTick, scope: this, interval: 1/60 });
	},

	remove: function(clock) {
		var i = 0;
		while((i < this.clocks.length) && (this.clocks[i] != clock)) { i++; }
		if(i < this.clocks.length)
			this.clocks.splice(i, 1);
		if(this.clocks.length === 0) {
			this.timer.abort();
			this.timer = undefined;
		}
	},

	/**	@Private*/
	onTick: function() {
		var current = (new Date().getTime()) - this.start;
		current /= 1000;
		for(var i = 0; i < this.clocks.length; i++)
			this.clocks[i].update(current);
		this.fireEvent('tick');
	}
});

Anim.TimeManager.current = new Anim.TimeManager();
<commit_msg>allow sending javascript using the remote debug<commit_after>Core.Object.extend('Anim.TimeManager',
/**@lends Anim.TimeManager#*/
{
	clocks: undefined,
	timer: undefined,
	start: 0,

	/**
    *   @constructs
	*	@class The TimeManager handle animations clocks
    *   @extends Core.Object
	*/
	constructor: function(config) {
		this.clocks = [];
		this.start = new Date().getTime();
		this.addEvents('tick');
	},

	add: function(clock) {
		this.clocks.push(clock);
		if(this.clocks.length === 1) {
			this.timer = new Core.Timer({ interval: 1/60 });
			this.connect(this.timer, 'timeupdate', this.onTick);
		}
	},

	remove: function(clock) {
		var i = 0;
		while((i < this.clocks.length) && (this.clocks[i] != clock)) { i++; }
		if(i < this.clocks.length)
			this.clocks.splice(i, 1);
		if(this.clocks.length === 0) {
			this.timer.abort();
			this.timer = undefined;
		}
	},

	/**	@Private*/
	onTick: function() {
		var current = (new Date().getTime()) - this.start;
		current /= 1000;
		for(var i = 0; i < this.clocks.length; i++)
			this.clocks[i].update(current);
		this.fireEvent('tick');
	}
});

Anim.TimeManager.current = new Anim.TimeManager();
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var handlebars = require('handlebars');
var UglifyJS = require('uglify-js');

exports.prepareScenes = function(scenePath, output, callback) {

  var sceneObject = '(function() {';
  var sceneList = fs.readdirSync(scenePath);

  sceneList.forEach(function(scene) {

    if (path.extname(scene) === '') {
      if (fs.existsSync(path.join(scenePath, scene))) {

        sceneObject[scene] = {};

        sceneObject += 'Lyria.Scenes["' + scene + '"] = new Lyria.Scene("' + scene + '", function(sender) {';

        var sceneFunc = path.join(scenePath, scene, 'scene.js');
        var sceneLoc = path.join(scenePath, scene, 'localization.json');
        var sceneMarkup = path.join(scenePath, scene, 'scene.html');

        if (fs.existsSync(sceneLoc)) {
          try {
            sceneObject += 'var localization = sender.localization = ' + fs.readFileSync(sceneLoc) + ';';
          } catch (e) {
            console.log('Error while evaluating ' + sceneLoc + ' :' + e);
          }
        } else {
          sceneObject += 'var localization = sender.localization = {}';
        }

        if (fs.existsSync(sceneMarkup)) {
          sceneObject += 'sender.template = ' + handlebars.precompile(fs.readFileSync(sceneMarkup, 'utf8')) + ';';
        }

        if (fs.existsSync(sceneFunc)) {
          sceneObject += fs.readFileSync(sceneFunc, 'utf8');
        }

        sceneObject += '});'
      }
    }

  });

  sceneObject += '})();';

  fs.writeFile(output, sceneObject, 'utf8', function(err) {
    if (err) {
      console.log(err);
    }

    if (callback) {
      callback();
    }
  });
}

<commit_msg>templates are more like the standard precompiled Handlebars templates + scenes IIFE is being returned<commit_after>var fs = require('fs');
var path = require('path');
var handlebars = require('handlebars');
var UglifyJS = require('uglify-js');

exports.prepareScenes = function(scenePath, output, callback) {

  var sceneObject = '(function() {';
  var sceneList = fs.readdirSync(scenePath);

  sceneList.forEach(function(scene) {

    if (path.extname(scene) === '') {
      if (fs.existsSync(path.join(scenePath, scene))) {

        sceneObject[scene] = {};

        sceneObject += 'Lyria.Scenes["' + scene + '"] = new Lyria.Scene("' + scene + '", function(sender) {';

        var sceneFunc = path.join(scenePath, scene, 'scene.js');
        var sceneLoc = path.join(scenePath, scene, 'localization.json');
        var sceneMarkup = path.join(scenePath, scene, 'scene.html');

        if (fs.existsSync(sceneLoc)) {
          try {
            sceneObject += 'var localization = sender.localization = ' + fs.readFileSync(sceneLoc) + ';';
          } catch (e) {
            console.log('Error while evaluating ' + sceneLoc + ' :' + e);
          }
        } else {
          sceneObject += 'var localization = sender.localization = {}';
        }

        if (fs.existsSync(sceneMarkup)) {
          sceneObject += 'sender.template = window.Handlebars.template(' + handlebars.precompile(fs.readFileSync(sceneMarkup, 'utf8')) + ');';
        }

        if (fs.existsSync(sceneFunc)) {
          sceneObject += 'return ' + fs.readFileSync(sceneFunc, 'utf8');
        }

        sceneObject += '});'
      }
    }

  });

  sceneObject += '})();';

  fs.writeFile(output, sceneObject, 'utf8', function(err) {
    if (err) {
      console.log(err);
    }

    if (callback) {
      callback();
    }
  });
}

<|endoftext|>


<commit_before>const utils = require('./utils.js');

module.exports = class Command {
    constructor(name, type, settings) {
        this.name = name; //Command Name
        this.type = type; //Comand Type
        this.usage = settings.usage || 'No Usage Currently Set.'; //Command Usage for in the help message
        this.currentCooldown = {}; //currentlyOnCooldown time for use in coolDown Check
        this.execTimes = 0; //# of Execution times since startup
        this.run = settings.process; //The Function of the command
        this.delete = !(settings.delete === false); //Setting to delete command on use(true by default)
        this.dm = !(settings.dm === false); //Setting for command to work in DM's(Private messages)(true by default)
        this.cooldown = settings.cooldown || 0; //The cooldown for the command
        this.togglable = !(settings.togglable === false); //Wheather the command is toggable or not with the toggle command(true by default)
        this.aliases = settings.aliases || null //Array of aliases the commmand has(none by default)
        this.privateGuild = settings.privateGuild || null; //Array of guilds the command is resticted to(no restriction by default)
        this.permissions = settings.permissions || {};
    }
    //The template help message which is used in `help [cmdName]`
    get help() {
        return `
__**Command Info for:**__ \`${this.name}\`

${this.usage}

${this.aliases !== null ? '**Aliases:** '+(this.aliases.map(a=> "\`"+a+"\`").join(', ') +'\n') : ''}**Cooldown:** \`${this.cooldown}s\` | **Delete on Use:** \`${this.delete}\` | **DM:** \`${this.dm}\` | **Uses:** \`${this.execTimes}\``;
    }

    //Function to get the current cooldown time for the user(is used when a command is on cooldown to show the time left til off cooldown)
    cooldownTime(user) {
        return ((this.currentCooldown[user] + (this.cooldown * 1000)) - Date.now()) / 1000;
    }

    //Command Processing
    exec(msg, args, bot) {
        return new Promise(resolve => { //Commands can take and manipulate the msg object, the command arguments and the bot object
            //Checks if the command deletes on use as well as if the bot has delete permissions before running the msg deletion
            if (this.delete && msg.channel.guild && msg.channel.permissionsOf(bot.user.id).has('manageMessages')) msg.delete();
            this.execTimes++; //Adds 1 the current number of execution times(Uses)
            //Run the command
            this.run(msg, args, bot).then(response => {
                if (response.embed !== undefined && msg.channel.guild && !(msg.channel.permissionsOf(bot.user.id).has('embedLinks'))) return; //If command needs embed permissions and bot doesn't have it
                //Main Processing of Command(uses Promises)
                //Commands return a Promise which can contain a 'message, 'upload', 'embed' or 'disableEveryone' to send message being the message content, upload being whatever file you'd like to, embed being a discord embed object or allow the message to mention everyone with @everyone
                //Commands also can return a edit function which allows you to edit messages while also taking the inital sent message object
                //They can also return a delete after 5s boolean which deletes the sent message after 5s
                msg.channel.createMessage({
                    content: response.message ? response.message : '', //Message content
                    embed: response.embed ? response.embed : undefined, //Message embed
                    disableEveryone: response.disableEveryone != null ? response.disableEveryone : undefined //Allow/deny use of @everyone or @here in sendmessages
                }, response.upload).then(message => {
                    if (response.edit) message.edit(response.edit(message)) //Edit sent message
                    if (response.delete) utils.messageDelete(message); //Check for delete sent message
                })
            }).catch(err => utils.fileLog(err)); //Log to console and file if errored
        })
    }

    //Cooldown Check(returns true if the command shouldn't be processed)
    cooldownCheck(user) {
        //If the user has a currentCooldown
        if (this.currentCooldown.hasOwnProperty(user)) //If the user last used the command within the cooldown period return true
            return true;
        else {
            this.currentCooldown[user] = Date.now();
            setTimeout(() => {
                delete this.currentCooldown[user]
            }, this.cooldown * 1000)
            return false;
        }
    }

    //Private Server Command Check(returns true if command shouldn't be processed)
    privateCheck(msg) {
        if (this.privateGuild === null) //If the command doesn't have a private server array return false
            return false;
        else if (!msg.channel.guild) //Prevents private server commands from working in DM's by returning true if not used in a guild
            return true;
        else if (this.privateGuild.indexOf(msg.channel.guild.id) > -1) //Guild is in the array of privateServers so return false
            return false;
        else //If all else fails return true
            return true;
    }

    //Used to check if the user has the correct permissions for the command if it has any additonal permissions
    permissionsCheck(msg) {
        var hasPermssion = true,
            permissionKeys = Object.keys(this.permissions);
        if (permissionKeys.length > 0) {
            var userPermissions = msg.channel.permissionsOf(msg.author.id).json;
            for (var key of permissionKeys) {
                if (this.permissions[key] !== userPermissions[key]) {
                    hasPermssion = false;
                    break;
                }
            }
        }
        return hasPermssion;
    }
}<commit_msg>Added extra permissions to command message<commit_after>const utils = require('./utils.js');

module.exports = class Command {
    constructor(name, type, settings) {
        this.name = name; //Command Name
        this.type = type; //Comand Type
        this.usage = settings.usage || 'No Usage Currently Set.'; //Command Usage for in the help message
        this.currentCooldown = {}; //currentlyOnCooldown time for use in coolDown Check
        this.execTimes = 0; //# of Execution times since startup
        this.run = settings.process; //The Function of the command
        this.delete = !(settings.delete === false); //Setting to delete command on use(true by default)
        this.dm = !(settings.dm === false); //Setting for command to work in DM's(Private messages)(true by default)
        this.cooldown = settings.cooldown || 0; //The cooldown for the command
        this.togglable = !(settings.togglable === false); //Wheather the command is toggable or not with the toggle command(true by default)
        this.aliases = settings.aliases || null //Array of aliases the commmand has(none by default)
        this.privateGuild = settings.privateGuild || null; //Array of guilds the command is resticted to(no restriction by default)
        this.permissions = settings.permissions || {};
    }
    //The template help message which is used in `help [cmdName]`
    get help() {
        return `
__**Command Info for:**__ \`${this.name}\`

${this.usage}

${this.permissions != {} ? '**Permissions:**' + Object.keys(this.permissions).map(p => "\`"+p+"\`").join(', ') +'\n' : ''}${this.aliases !== null ? '**Aliases:** ' + this.aliases.map(a => "\`"+a+"\`").join(', ') +'\n' : ''}**Cooldown:** \`${this.cooldown}s\` | **Delete on Use:** \`${this.delete}\` | **DM:** \`${this.dm}\` | **Uses:** \`${this.execTimes}\``;
    }

    //Function to get the current cooldown time for the user(is used when a command is on cooldown to show the time left til off cooldown)
    cooldownTime(user) {
        return ((this.currentCooldown[user] + (this.cooldown * 1000)) - Date.now()) / 1000;
    }

    //Command Processing
    exec(msg, args, bot) {
        return new Promise(resolve => { //Commands can take and manipulate the msg object, the command arguments and the bot object
            //Checks if the command deletes on use as well as if the bot has delete permissions before running the msg deletion
            if (this.delete && msg.channel.guild && msg.channel.permissionsOf(bot.user.id).has('manageMessages')) msg.delete();
            this.execTimes++; //Adds 1 the current number of execution times(Uses)
            //Run the command
            this.run(msg, args, bot).then(response => {
                if (response.embed !== undefined && msg.channel.guild && !(msg.channel.permissionsOf(bot.user.id).has('embedLinks'))) return; //If command needs embed permissions and bot doesn't have it
                //Main Processing of Command(uses Promises)
                //Commands return a Promise which can contain a 'message, 'upload', 'embed' or 'disableEveryone' to send message being the message content, upload being whatever file you'd like to, embed being a discord embed object or allow the message to mention everyone with @everyone
                //Commands also can return a edit function which allows you to edit messages while also taking the inital sent message object
                //They can also return a delete after 5s boolean which deletes the sent message after 5s
                msg.channel.createMessage({
                    content: response.message ? response.message : '', //Message content
                    embed: response.embed ? response.embed : undefined, //Message embed
                    disableEveryone: response.disableEveryone != null ? response.disableEveryone : undefined //Allow/deny use of @everyone or @here in sendmessages
                }, response.upload).then(message => {
                    if (response.edit) message.edit(response.edit(message)) //Edit sent message
                    if (response.delete) utils.messageDelete(message); //Check for delete sent message
                })
            }).catch(err => utils.fileLog(err)); //Log to console and file if errored
        })
    }

    //Cooldown Check(returns true if the command shouldn't be processed)
    cooldownCheck(user) {
        //If the user has a currentCooldown
        if (this.currentCooldown.hasOwnProperty(user)) //If the user last used the command within the cooldown period return true
            return true;
        else {
            this.currentCooldown[user] = Date.now();
            setTimeout(() => {
                delete this.currentCooldown[user]
            }, this.cooldown * 1000)
            return false;
        }
    }

    //Private Server Command Check(returns true if command shouldn't be processed)
    privateCheck(msg) {
        if (this.privateGuild === null) //If the command doesn't have a private server array return false
            return false;
        else if (!msg.channel.guild) //Prevents private server commands from working in DM's by returning true if not used in a guild
            return true;
        else if (this.privateGuild.indexOf(msg.channel.guild.id) > -1) //Guild is in the array of privateServers so return false
            return false;
        else //If all else fails return true
            return true;
    }

    //Used to check if the user has the correct permissions for the command if it has any additonal permissions
    permissionsCheck(msg) {
        var hasPermssion = true,
            permissionKeys = Object.keys(this.permissions);
        if (permissionKeys.length > 0) {
            var userPermissions = msg.channel.permissionsOf(msg.author.id).json;
            for (var key of permissionKeys) {
                if (this.permissions[key] !== userPermissions[key]) {
                    hasPermssion = false;
                    break;
                }
            }
        }
        return hasPermssion;
    }
}<|endoftext|>


<commit_before>Ui.LBox.extend('Ui.TransitionBox',
/**@lends Ui.TransitionBox#*/
{
	transition: undefined,
	duration: 0.5,
	ease: undefined,
	position: -1,
	transitionClock: undefined,
	current: undefined,
	next: undefined,
	replaceMode: false,

	/**
     * @constructs
	 * @class Container that displays only one element at a time and allows differents kind of transition between elements
     * @extends Ui.LBox
     * @param {number} [config.duration] Transition duration in second (can be float)
	 * @param {string} [config.ease] Transition ease behaviour [linear|bounce|elastic]
	 * @param {string} [config.transition] Transition type [slide|fade|flip]
	 */
	constructor: function(config) {
		this.addEvents('change');

		this.connect(this, 'load', this.onTransitionBoxLoad);
		this.connect(this, 'unload', this.onTransitionBoxUnload);

		this.setClipToBounds(true);
		this.setTransition('fade');
	},

	getPosition: function() {
		return this.position;
	},

	setDuration: function(duration) {
		this.duration = duration;
	},

	setEase: function(ease) {
		this.ease = Anim.EasingFunction.create(ease);
	},

	/**
	 * @param {Ui.Transition|object|string} transition Type of transition use
	 * @example
	 * t = new TransitionBox();
	 * t.setTransition('slide');
	 * t.setTransition({ type: Ui.Slide, direction: 'left' });
	 * t.setTransition(new Ui.Transition({ type: Ui.Slide, direction: 'left' }));
	 */
	setTransition: function(transition) {
		this.transition = Ui.Transition.create(transition);
	},

	setCurrent: function(child) {
		var pos = this.getChildPosition(child);
		if(pos != -1)
			this.setCurrentAt(pos);
	},

	setCurrentAt: function(position) {
		if(this.position != position) {
			if(this.next != undefined) {
				if(this.current != undefined) {
					this.current.hide();
					this.current = this.next;
					this.current.show();
					this.next = undefined;
				}
			}
			if(this.transitionClock != undefined) {
				this.disconnect(this.transitionClock, 'complete', this.onTransitionComplete);
				this.transitionClock.stop();
			}

			if(this.position != -1)
				this.current = this.getChildren()[this.position];
			else
				this.current = undefined;

			this.next = this.getChildren()[position];
			this.next.show();

			this.transition.run(this.current, this.next, 0);

			this.transitionClock = new Anim.Clock({ duration: this.duration, scope: this, onTimeupdate: this.onTransitionTick, ease: this.ease });
			this.connect(this.transitionClock, 'complete', this.onTransitionComplete);
			this.transitionClock.begin();

			this.position = position;
		}
	},

	getCurrent: function() {
		if(this.position == -1)
			return undefined;
		else
			return this.getChildren()[this.position].getChildren()[0];
	},

	replaceContent: function(content) {
		this.replaceMode = true;
		this.append(content);
		this.setCurrent(content);
	},

	/**#@+
	 * @private
	 */
	onTransitionBoxLoad: function() {
	},

	onTransitionBoxUnload: function() {
		if(this.transitionClock != undefined) {
			this.transitionClock.stop();
			this.transitionClock = undefined;
		}
	},

	onTransitionTick: function(clock, progress) {
		this.progress = progress;
		this.transition.run(this.current, this.next, progress);
	},

	onTransitionComplete: function(clock) {
		this.transitionClock = undefined;

		var current = this.next;

		if(this.current != undefined)
			this.current.hide();
		this.next = undefined;
		if(this.replaceMode) {
			this.replaceMode = false;

			var removeList = [];
			for(var i = 0; i < this.getChildren(); i++) {
				var item = this.getChildren()[i];
				if(item !== current)
					removeList.push(item.getFirstChild());
			}
			for(var i = 0; i < removeList.length; i++)
				this.remove(removeList[i]);
		}
		this.fireEvent('change', this, this.position);
	}
	/**#@-*/
}, {
	arrangeCore: function(width, height) {
		Ui.TransitionBox.base.arrangeCore.call(this, width, height);
		// update the transition if needed
		if(this.transitionClock != undefined)
			this.transition.run(this.current, this.next, this.transitionClock.getProgress());
	},

	append: function(child) {
		child = Ui.Element.create(child);
		var content = new Ui.TransitionBoxContent();
		content.append(child);
		content.hide();
		Ui.TransitionBox.base.append.call(this, content);
	},

	prepend: function(child) {
		child = Ui.Element.create(child);
		if(this.position != -1)
			this.position++;

		var content = new Ui.TransitionBoxContent();
		content.append(child);
		content.hide();
		Ui.TransitionBox.base.prepend.call(this, this.position);
	},

	remove: function(child) {
		for(var i = 0; i < this.getChildren().length; i++) {
			if(this.getChildren()[i].getChildren()[0] == child) {
				if(i < this.position)
					this.position--;
				if(i == this.position)
					this.position = -1;
				this.getChildren()[i].remove(child);
				Ui.TransitionBox.base.remove.call(this, this.getChildren()[i]);
				break;
			}
		}
	},

	getChildPosition: function(child) {
		for(var i = 0; i < this.getChildren().length; i++) {
			if(this.getChildren()[i].getChildren()[0] == child)
				return i;
		}
		return -1;
	}
});

Ui.LBox.extend('Ui.TransitionBoxContent', {});

<commit_msg>correct a very bad bug in TransitionBox which slow perf each time replaceContent was used because previous content was never removed<commit_after>Ui.LBox.extend('Ui.TransitionBox',
/**@lends Ui.TransitionBox#*/
{
	transition: undefined,
	duration: 0.5,
	ease: undefined,
	position: -1,
	transitionClock: undefined,
	current: undefined,
	next: undefined,
	replaceMode: false,

	/**
     * @constructs
	 * @class Container that displays only one element at a time and allows differents kind of transition between elements
     * @extends Ui.LBox
     * @param {number} [config.duration] Transition duration in second (can be float)
	 * @param {string} [config.ease] Transition ease behaviour [linear|bounce|elastic]
	 * @param {string} [config.transition] Transition type [slide|fade|flip]
	 */
	constructor: function(config) {
		this.addEvents('change');

		this.connect(this, 'load', this.onTransitionBoxLoad);
		this.connect(this, 'unload', this.onTransitionBoxUnload);

		this.setClipToBounds(true);
		this.setTransition('fade');
	},

	getPosition: function() {
		return this.position;
	},

	setDuration: function(duration) {
		this.duration = duration;
	},

	setEase: function(ease) {
		this.ease = Anim.EasingFunction.create(ease);
	},

	/**
	 * @param {Ui.Transition|object|string} transition Type of transition use
	 * @example
	 * t = new TransitionBox();
	 * t.setTransition('slide');
	 * t.setTransition({ type: Ui.Slide, direction: 'left' });
	 * t.setTransition(new Ui.Transition({ type: Ui.Slide, direction: 'left' }));
	 */
	setTransition: function(transition) {
		this.transition = Ui.Transition.create(transition);
	},

	setCurrent: function(child) {
		var pos = this.getChildPosition(child);
		if(pos != -1)
			this.setCurrentAt(pos);
	},

	setCurrentAt: function(position) {
		if(this.position != position) {
			if(this.next != undefined) {
				if(this.current != undefined) {
					this.current.hide();
					this.current = this.next;
					this.current.show();
					this.next = undefined;
				}
			}
			if(this.transitionClock != undefined) {
				this.disconnect(this.transitionClock, 'complete', this.onTransitionComplete);
				this.transitionClock.stop();
			}

			if(this.position != -1)
				this.current = this.getChildren()[this.position];
			else
				this.current = undefined;

			this.next = this.getChildren()[position];
			this.next.show();

			this.transition.run(this.current, this.next, 0);

			this.transitionClock = new Anim.Clock({ duration: this.duration, scope: this, onTimeupdate: this.onTransitionTick, ease: this.ease });
			this.connect(this.transitionClock, 'complete', this.onTransitionComplete);
			this.transitionClock.begin();

			this.position = position;
		}
	},

	getCurrent: function() {
		if(this.position == -1)
			return undefined;
		else
			return this.getChildren()[this.position].getChildren()[0];
	},

	replaceContent: function(content) {
		this.replaceMode = true;
		this.append(content);
		this.setCurrent(content);
	},

	/**#@+
	 * @private
	 */
	onTransitionBoxLoad: function() {
	},

	onTransitionBoxUnload: function() {
		if(this.transitionClock != undefined) {
			this.transitionClock.stop();
			this.transitionClock = undefined;
		}
	},

	onTransitionTick: function(clock, progress) {
		this.progress = progress;
		this.transition.run(this.current, this.next, progress);
	},

	onTransitionComplete: function(clock) {
		this.transitionClock = undefined;

		var current = this.next;

		if(this.current != undefined)
			this.current.hide();
		this.next = undefined;
		if(this.replaceMode) {
			this.replaceMode = false;

			var removeList = [];
			for(var i = 0; i < this.getChildren().length; i++) {
				var item = this.getChildren()[i];
				if(item !== current)
					removeList.push(item.getFirstChild());
			}
			for(var i = 0; i < removeList.length; i++)
				this.remove(removeList[i]);
		}
		this.fireEvent('change', this, this.position);
	}
	/**#@-*/
}, {
	arrangeCore: function(width, height) {
		Ui.TransitionBox.base.arrangeCore.call(this, width, height);
		// update the transition if needed
		if(this.transitionClock != undefined)
			this.transition.run(this.current, this.next, this.transitionClock.getProgress());
	},

	append: function(child) {
		child = Ui.Element.create(child);
		var content = new Ui.TransitionBoxContent();
		content.append(child);
		content.hide();
		Ui.TransitionBox.base.append.call(this, content);
	},

	prepend: function(child) {
		child = Ui.Element.create(child);
		if(this.position != -1)
			this.position++;

		var content = new Ui.TransitionBoxContent();
		content.append(child);
		content.hide();
		Ui.TransitionBox.base.prepend.call(this, this.position);
	},

	remove: function(child) {
		for(var i = 0; i < this.getChildren().length; i++) {
			if(this.getChildren()[i].getChildren()[0] == child) {
				if(i < this.position)
					this.position--;
				if(i == this.position)
					this.position = -1;
				this.getChildren()[i].remove(child);
				Ui.TransitionBox.base.remove.call(this, this.getChildren()[i]);
				break;
			}
		}
	},

	getChildPosition: function(child) {
		for(var i = 0; i < this.getChildren().length; i++) {
			if(this.getChildren()[i].getChildren()[0] == child)
				return i;
		}
		return -1;
	}
});

Ui.LBox.extend('Ui.TransitionBoxContent', {});

<|endoftext|>


<commit_before>
var fixture = '\

\

\

\

\
    <input class="event-focus">\

\
';

describe ( 'Events', { beforeEach: getFixtureInit ( fixture ) }, function () {

  describe ( '$.fn.on', function ( it ) {

    it ( 'attaches to single event', function ( t ) {

      var ele = $('.event');
      var count = 0;
      var that;

      function handler () {
        count++;
        that = this;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' ).trigger ( 'click' );

      t.is ( count, 2 );
      t.is ( that, ele[0] );

    });

    it ( 'attaches to multiple events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar', handler );
      ele.trigger ( 'foo' ).trigger ( 'bar' );

      t.is ( count, 2 );

    });

    it ( 'stops propagation if false is returned', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var count = 0;

      function handler () {
        count++;
        return false;
      }

      parent.on ( 'foo', handler );
      parent.on ( 'foo', handler );
      ele.on ( 'foo', handler );
      ele.on ( 'foo', handler ); // We are not using `stopImmediatePropagation`
      ele.trigger ( 'foo' );

      t.is ( count, 2 );

    });

    ( document.hasFocus () ? it : it.skip )( 'supports events that do not bubble', function ( t ) { // If the document isn't focused the element won't get the focus either

      var events = ['focus', 'blur', 'mouseenter', 'mouseleave'],
          eventsTrigger = ['focus', 'blur', 'mouseover', 'mouseout'];

      events.forEach ( function ( event, index ) {

        var ele = $('.event-focus');
        var parent = $('.parent');
        var count = 0;
        var eventTrigger = eventsTrigger[index];

        function handler () {
          count++;
        }

        parent.on ( event, handler );
        ele.on ( event, handler );
        ele.trigger ( eventTrigger );

        parent.off ( event );
        ele.off ( event );
        ele.trigger ( eventTrigger );

        t.is ( count, 2 );

      });

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar.ns1', handler );
      ele.on ( 'foo.ns1.ns2', handler );
      ele.trigger ( 'foo.ns1.ns2' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' );

      t.is ( count, 3 );

    });

    it ( 'supports event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var count = 0;

      function handler () {
        count++;
      };

      parent.on ( 'click', '.event', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

      parent.off ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    it ( 'overwrites event.currentTarget when using event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var html = $('html');
      var count = 0;
      var currentTargets = [];

      function handler ( event ) {
        count++;
        event.bubbles; // Ensuring the event object hasn't been corrupted
        currentTargets.push ( event.currentTarget );
      };

      ele.on ( 'click', handler );
      parent.on ( 'click', '.event', handler );
      html.on ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 3 );
      t.deepEqual ( currentTargets, [ele[0], ele[0], html[0]] );

    });

    it.skip ( 'stops propagation if false is returned when using event delegation', function ( t ) { //URL: https://github.com/kenwheeler/cash/issues/235

      var ele = $('.event');
      var parent = $('.parent');
      var child = $('.child');
      var count = 0;
      var currentTargets = [];

      function handler ( event ) {
        count++;
        currentTargets.push ( event.currentTarget );
        return false;
      }

      parent.on ( 'foo', handler );
      parent.on ( 'foo', handler );
      parent.on ( 'foo', '.event', handler );
      parent.on ( 'foo', '.event', handler );
      parent.on ( 'foo', '.child', handler );
      parent.on ( 'foo', '.child', handler );

      parent.trigger ( 'foo' );

      t.is ( count, 2 );
      t.deepEqual ( currentTargets.slice ( 0 ), [parent[0], parent[0]] );

      ele.trigger ( 'foo' );

      t.is ( count, 4 );
      t.deepEqual ( currentTargets.slice ( 2 ), [ele[0], ele[0]] );

      child.trigger ( 'foo' );

      t.is ( count, 6 );
      t.deepEqual ( currentTargets.slice ( 4 ), [child[0], child[0]] );

    });

  });

  describe ( '$.fn.one', function ( it ) {

    it ( 'removes the handler after the first call', function ( t ) {

      var ele = $('.event');
      var count = 0;

      var handler = function () {
        count++;
      };

      ele.one ( 'click', handler );
      ele.trigger ( 'click' ).trigger ( 'click' );

      t.is ( count, 1 );

      ele.one ( 'click', handler ).off ( 'click', handler ).trigger ( 'click' );

      t.is ( count, 1 );

    });

  });

  describe ( '$.fn.off', function ( it ) {

    it ( 'removes single event', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' );
      ele.off ( 'click' );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    it ( 'removes multiple events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar baz', handler );
      ele.off ( 'foo bar', handler );
      ele.trigger ( 'foo' ).trigger ( 'bar' ).trigger ( 'baz' );

      t.is ( count, 1 );

    });

    it ( 'removes namespaced events, preserving regular ones', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo foo.ns1', handler ).off ( '.ns1' ).trigger ( 'foo' ).off ( 'foo' ).trigger ( 'foo' );

      t.is ( count, 1 );

    });

    it ( 'removes all events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar', handler );
      ele.off ();
      ele.trigger ( 'foo' ).trigger ( 'bar' );

      t.is ( count, 0 );

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns1' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns2' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns1.ns2' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2 bar.ns1.ns2 baz.ns1.ns2', handler ).off ( '.ns1' ).trigger ( 'foo' ).trigger ( 'bar' ).trigger ( 'baz' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns3' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 3 );

    });

    it ( 'supports event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var countChild = 0;
      var countDelegate = 0;

      function handlerChild () {
        countChild++;
      };

      function handlerDelegate () {
        countDelegate++;
      };

      ele.on ( 'click', handlerChild );
      parent.on ( 'click', '.event', handlerDelegate );
      parent.off ( 'click', '.event', handlerDelegate );
      ele.trigger ( 'click' );

      t.is ( countChild, 1 );
      t.is ( countDelegate, 0 );

    });

  });

  describe ( '$.fn.trigger', function ( it ) {

    it ( 'triggers single event', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    ( document.hasFocus () ? it : it.skip )( 'triggers focus/blur natively', function ( t ) { // If the document isn't focused the element won't get the focus either

      var events = ['focus', 'blur'];

      events.forEach ( function ( event ) {

        var ele = $('.event-focus');
        var count = 0;

        function handler () {
          count++;
        }

        var nativeHandler = ele[0][event];
        ele[0][event] = function () {
          handler ();
          nativeHandler.apply ( this, arguments );
        };

        ele.on ( event, handler );
        ele.trigger ( event );

        t.is ( count, 2 );

      });

    });

    it ( 'can pass data to the handler', function ( t ) {

      var ele = $('.event');
      var count;
      var eventData;
      var data;

      function handler ( event, d ) {
        count ++;
        eventData = event.data;
        data = d;
      }

      var values = [123, 'string', { obj: true }];

      values.forEach ( function ( value ) {

        count = 0;

        ele.on ( 'custom', handler );
        ele.trigger ( 'custom', value );
        ele.off ( 'custom', handler );

        t.is ( count, 1 );
        t.is ( eventData, value );
        t.is ( data, value );

      });

    });

    it ( 'can pass namespaces to the handler', function ( t ) {

      var ele = $('.event');
      var namespaces = [];

      function handler ( event ) {
        namespaces.push ( event.namespace );
      }

      ele.on ( 'foo.ns1.ns2', handler );
      ele.trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns1.ns2' );

      t.deepEqual ( namespaces ['', 'ns1', 'ns2', 'ns1.ns2'] );

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo.ns1.ns2', handler ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' ).trigger ( 'foo.ns1.ns3' );

      t.is ( count, 3 );

    });

  });

});
<commit_msg>Ensuring the order of event namespaces doesn’t matter<commit_after>
var fixture = '\

\

\

\

\
    <input class="event-focus">\

\
';

describe ( 'Events', { beforeEach: getFixtureInit ( fixture ) }, function () {

  describe ( '$.fn.on', function ( it ) {

    it ( 'attaches to single event', function ( t ) {

      var ele = $('.event');
      var count = 0;
      var that;

      function handler () {
        count++;
        that = this;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' ).trigger ( 'click' );

      t.is ( count, 2 );
      t.is ( that, ele[0] );

    });

    it ( 'attaches to multiple events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar', handler );
      ele.trigger ( 'foo' ).trigger ( 'bar' );

      t.is ( count, 2 );

    });

    it ( 'stops propagation if false is returned', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var count = 0;

      function handler () {
        count++;
        return false;
      }

      parent.on ( 'foo', handler );
      parent.on ( 'foo', handler );
      ele.on ( 'foo', handler );
      ele.on ( 'foo', handler ); // We are not using `stopImmediatePropagation`
      ele.trigger ( 'foo' );

      t.is ( count, 2 );

    });

    ( document.hasFocus () ? it : it.skip )( 'supports events that do not bubble', function ( t ) { // If the document isn't focused the element won't get the focus either

      var events = ['focus', 'blur', 'mouseenter', 'mouseleave'],
          eventsTrigger = ['focus', 'blur', 'mouseover', 'mouseout'];

      events.forEach ( function ( event, index ) {

        var ele = $('.event-focus');
        var parent = $('.parent');
        var count = 0;
        var eventTrigger = eventsTrigger[index];

        function handler () {
          count++;
        }

        parent.on ( event, handler );
        ele.on ( event, handler );
        ele.trigger ( eventTrigger );

        parent.off ( event );
        ele.off ( event );
        ele.trigger ( eventTrigger );

        t.is ( count, 2 );

      });

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar.ns1', handler );
      ele.on ( 'foo.ns1.ns2', handler );
      ele.trigger ( 'foo.ns1.ns2' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' );

      t.is ( count, 3 );

    });

    it ( 'supports event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var count = 0;

      function handler () {
        count++;
      };

      parent.on ( 'click', '.event', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

      parent.off ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    it ( 'ignores the order of namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;
      var namespaces = [];

      function handler ( event ) {
        count++;
        namespaces.push ( event.namespace );
      }

      ele.on ( 'foo.ns1.ns2', handler ).on ( 'foo.ns2.ns1', handler );

      ele.trigger ( 'foo.ns1.ns2' );
      ele.trigger ( 'foo.ns2.ns1' );

      ele.off ( 'foo.ns1.ns2' ).trigger ( 'foo.ns1.ns2' );

      t.is ( count, 4 );
      t.deepEqual ( namespaces, ['ns1.ns2', 'ns1.ns2', 'ns1.ns2', 'ns1.ns2'] );

    });

    it ( 'overwrites event.currentTarget when using event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var html = $('html');
      var count = 0;
      var currentTargets = [];

      function handler ( event ) {
        count++;
        event.bubbles; // Ensuring the event object hasn't been corrupted
        currentTargets.push ( event.currentTarget );
      };

      ele.on ( 'click', handler );
      parent.on ( 'click', '.event', handler );
      html.on ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 3 );
      t.deepEqual ( currentTargets, [ele[0], ele[0], html[0]] );

    });

    it.skip ( 'stops propagation if false is returned when using event delegation', function ( t ) { //URL: https://github.com/kenwheeler/cash/issues/235

      var ele = $('.event');
      var parent = $('.parent');
      var child = $('.child');
      var count = 0;
      var currentTargets = [];

      function handler ( event ) {
        count++;
        currentTargets.push ( event.currentTarget );
        return false;
      }

      parent.on ( 'foo', handler );
      parent.on ( 'foo', handler );
      parent.on ( 'foo', '.event', handler );
      parent.on ( 'foo', '.event', handler );
      parent.on ( 'foo', '.child', handler );
      parent.on ( 'foo', '.child', handler );

      parent.trigger ( 'foo' );

      t.is ( count, 2 );
      t.deepEqual ( currentTargets.slice ( 0 ), [parent[0], parent[0]] );

      ele.trigger ( 'foo' );

      t.is ( count, 4 );
      t.deepEqual ( currentTargets.slice ( 2 ), [ele[0], ele[0]] );

      child.trigger ( 'foo' );

      t.is ( count, 6 );
      t.deepEqual ( currentTargets.slice ( 4 ), [child[0], child[0]] );

    });

  });

  describe ( '$.fn.one', function ( it ) {

    it ( 'removes the handler after the first call', function ( t ) {

      var ele = $('.event');
      var count = 0;

      var handler = function () {
        count++;
      };

      ele.one ( 'click', handler );
      ele.trigger ( 'click' ).trigger ( 'click' );

      t.is ( count, 1 );

      ele.one ( 'click', handler ).off ( 'click', handler ).trigger ( 'click' );

      t.is ( count, 1 );

    });

  });

  describe ( '$.fn.off', function ( it ) {

    it ( 'removes single event', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' );
      ele.off ( 'click' );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    it ( 'removes multiple events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar baz', handler );
      ele.off ( 'foo bar', handler );
      ele.trigger ( 'foo' ).trigger ( 'bar' ).trigger ( 'baz' );

      t.is ( count, 1 );

    });

    it ( 'removes namespaced events, preserving regular ones', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo foo.ns1', handler ).off ( '.ns1' ).trigger ( 'foo' ).off ( 'foo' ).trigger ( 'foo' );

      t.is ( count, 1 );

    });

    it ( 'removes all events', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo bar', handler );
      ele.off ();
      ele.trigger ( 'foo' ).trigger ( 'bar' );

      t.is ( count, 0 );

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns1' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns2' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns1.ns2' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2 bar.ns1.ns2 baz.ns1.ns2', handler ).off ( '.ns1' ).trigger ( 'foo' ).trigger ( 'bar' ).trigger ( 'baz' );

      t.is ( count, 0 );

      ele.on ( 'foo.ns1.ns2', handler ).off ( 'foo.ns3' ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' );

      t.is ( count, 3 );

    });

    it ( 'supports event delegation', function ( t ) {

      var ele = $('.event');
      var parent = $('.parent');
      var countChild = 0;
      var countDelegate = 0;

      function handlerChild () {
        countChild++;
      };

      function handlerDelegate () {
        countDelegate++;
      };

      ele.on ( 'click', handlerChild );
      parent.on ( 'click', '.event', handlerDelegate );
      parent.off ( 'click', '.event', handlerDelegate );
      ele.trigger ( 'click' );

      t.is ( countChild, 1 );
      t.is ( countDelegate, 0 );

    });

  });

  describe ( '$.fn.trigger', function ( it ) {

    it ( 'triggers single event', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'click', handler );
      ele.trigger ( 'click' );

      t.is ( count, 1 );

    });

    ( document.hasFocus () ? it : it.skip )( 'triggers focus/blur natively', function ( t ) { // If the document isn't focused the element won't get the focus either

      var events = ['focus', 'blur'];

      events.forEach ( function ( event ) {

        var ele = $('.event-focus');
        var count = 0;

        function handler () {
          count++;
        }

        var nativeHandler = ele[0][event];
        ele[0][event] = function () {
          handler ();
          nativeHandler.apply ( this, arguments );
        };

        ele.on ( event, handler );
        ele.trigger ( event );

        t.is ( count, 2 );

      });

    });

    it ( 'can pass data to the handler', function ( t ) {

      var ele = $('.event');
      var count;
      var eventData;
      var data;

      function handler ( event, d ) {
        count ++;
        eventData = event.data;
        data = d;
      }

      var values = [123, 'string', { obj: true }];

      values.forEach ( function ( value ) {

        count = 0;

        ele.on ( 'custom', handler );
        ele.trigger ( 'custom', value );
        ele.off ( 'custom', handler );

        t.is ( count, 1 );
        t.is ( eventData, value );
        t.is ( data, value );

      });

    });

    it ( 'can pass namespaces to the handler', function ( t ) {

      var ele = $('.event');
      var namespaces = [];

      function handler ( event ) {
        namespaces.push ( event.namespace );
      }

      ele.on ( 'foo.ns1.ns2', handler );
      ele.trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns1.ns2' );

      t.deepEqual ( namespaces ['', 'ns1', 'ns2', 'ns1.ns2'] );

    });

    it ( 'supports namespaces', function ( t ) {

      var ele = $('.event');
      var count = 0;

      function handler () {
        count++;
      }

      ele.on ( 'foo.ns1.ns2', handler ).trigger ( 'foo' ).trigger ( 'foo.ns1' ).trigger ( 'foo.ns2' ).trigger ( 'foo.ns3' ).trigger ( 'foo.ns1.ns3' );

      t.is ( count, 3 );

    });

  });

});
<|endoftext|>


<commit_before>'use strict';

var defaultTasks = require('../tasks');

module.exports = function extendTasks(gulp, tasks) {
    var allTasks = Object.assign({}, defaultTasks, tasks);

    Object.keys(allTasks).forEach(function(taskName) {
        var args = [taskName].concat(tasks[taskName]);
        gulp.task.apply(gulp, args);
    });
};
<commit_msg>Fix tasks not running.<commit_after>'use strict';

var defaultTasks = require('../tasks');

module.exports = function extendTasks(gulp, tasks) {
    tasks = Object.assign({}, defaultTasks, tasks);

    Object.keys(tasks).forEach(function(taskName) {
        var args = [taskName].concat(tasks[taskName]);
        gulp.task.apply(gulp, args);
    });
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*jshint laxcomma:true es5:true node:true*/

(function () {
  var ArgumentParser = require('argparse').ArgumentParser
    , watch = require('nodewatch')
    , colors = require('colors')
    , util = require('util')
    , path = require('path')
    , exec = require('child_process').exec
    , relevantExtensions = []
    , timeoutId
    , parser = new ArgumentParser({
          version: '0.0.0'
        , addHelp: true
        , descriptions: 'Simple app that recursively watches the working directory and runs a script when files with the appropriate extensions change'
      })
    , args
    ;

  parser.addArgument(['-x', '--extension'], {help: 'extensions that will trigger the script to run', metavar: 'EXT', action: 'append', required: true});
  parser.addArgument(['-s', '--script'], {help: 'script that runs when files with the correct extension change', defaultValue: 'deploy.sh'});
  parser.addArgument(['--timeout'], {help: 'time in ms following the most recent relevant change before the script is run', metavar: 'TIME', type:'int', defaultValue: 500});

  function log(msg, level) {
    if (typeof level !== 'string') {
      level = 'info';
    }
    level = level.toUpperCase();

    if (level === 'ERROR') {
      level = level.red.bold;
    }
    else if (level === 'ACTION') {
      level = level.yellow.bold;
    }
    else if (level === 'DEBUG') {
      level = level.magenta;
    }
    else {
      level = level.green;
    }

    console.log('[' + level + '] ' + msg);
  }

  function redeploy() {
    timeoutId = null;
    watch.clearListeners();
    log('starting redeployment', 'action');

    exec(args.script, function (err, stdout, stderr) {
      if (err) {
        log('problem deploying', 'error');
        console.log(stderr);
        return;
      }
      log('redeployment complete', 'action');
      watch.onChange(fileChanged);
    });
  }

  function fileChanged(file, prev, curr, action) {
    var relevant = relevantExtensions.some(function (regExp) {
      return regExp.test(file);
    });

    if (relevant) {
      log(action + ': ' + path.relative(process.cwd(), file), 'info');
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(redeploy, args.timeout);
    }
    else {
      log(action + ': ' + path.relative(process.cwd(), file) + ' unwatched extension', 'debug');
    }
  }

  args = parser.parseArgs();
  if (!args.extension || args.extension.length <= 0) {
    log('must specify at least one extension', 'error');
    process.exit(1);
  }
  args.script = path.resolve(args.script);
  if (!path.existsSync(args.script)) {
    log('script ' + args.script + ' not found', 'error');
    process.exit(1);
  }

  args.extension.forEach(function (extension) {
    relevantExtensions.push(new RegExp('\\.' + extension + '$'));
  });

  watch.add('.', true);
  watch.onChange(fileChanged);

}());
<commit_msg>changing the way the watcher handles errors in the deploy script<commit_after>#!/usr/bin/env node
/*jshint laxcomma:true es5:true node:true*/

(function () {
  var ArgumentParser = require('argparse').ArgumentParser
    , watch = require('nodewatch')
    , colors = require('colors')
    , util = require('util')
    , path = require('path')
    , exec = require('child_process').exec
    , relevantExtensions = []
    , timeoutId
    , parser = new ArgumentParser({
          version: '0.0.0'
        , addHelp: true
        , descriptions: 'Simple app that recursively watches the working directory and runs a script when files with the appropriate extensions change'
      })
    , args
    ;

  parser.addArgument(['-x', '--extension'], {help: 'extensions that will trigger the script to run', metavar: 'EXT', action: 'append', required: true});
  parser.addArgument(['-s', '--script'], {help: 'script that runs when files with the correct extension change', defaultValue: 'deploy.sh'});
  parser.addArgument(['--timeout'], {help: 'time in ms following the most recent relevant change before the script is run', metavar: 'TIME', type:'int', defaultValue: 500});

  function log(msg, level) {
    if (typeof level !== 'string') {
      level = 'info';
    }
    level = level.toUpperCase();

    if (level === 'ERROR') {
      level = level.red.bold;
    }
    else if (level === 'ACTION') {
      level = level.yellow.bold;
    }
    else if (level === 'DEBUG') {
      level = level.magenta;
    }
    else {
      level = level.green;
    }

    console.log('[' + level + '] ' + msg);
  }

  function redeploy() {
    timeoutId = null;
    watch.clearListeners();
    log('starting redeployment', 'action');

    exec(args.script, function (err, stdout, stderr) {
      if (err) {
        log('problem deploying', 'error');
        console.log(stderr);
        process.exit(1);
      }
      log('redeployment complete', 'action');
      watch.onChange(fileChanged);
    });
  }

  function fileChanged(file, prev, curr, action) {
    var relevant = relevantExtensions.some(function (regExp) {
      return regExp.test(file);
    });

    if (relevant) {
      log(action + ': ' + path.relative(process.cwd(), file), 'info');
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(redeploy, args.timeout);
    }
    else {
      log(action + ': ' + path.relative(process.cwd(), file) + ' unwatched extension', 'debug');
    }
  }

  args = parser.parseArgs();
  if (!args.extension || args.extension.length <= 0) {
    log('must specify at least one extension', 'error');
    process.exit(1);
  }
  args.script = path.resolve(args.script);
  if (!path.existsSync(args.script)) {
    log('script ' + args.script + ' not found', 'error');
    process.exit(1);
  }

  args.extension.forEach(function (extension) {
    relevantExtensions.push(new RegExp('\\.' + extension + '$'));
  });

  watch.add('.', true);
  watch.onChange(fileChanged);

}());
<|endoftext|>


<commit_before>/* @flow */
'use strict';

import React from 'react';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from './Button';
import { Platform } from 'react-native';
import View from './View';
import Icon from './Icon';
import Badge from './Badge';
import IconNB from './Icon';
import Text from './Text';
import _ from 'lodash';
export default class Footer extends NativeBaseComponent {

    propTypes: {
        style : React.PropTypes.object
    }

    getInitialStyle() {
        return {
            footerTab: {
                flexDirection: 'row',
                justifyContent: 'space-between',
                flex: 1,
                alignSelf: 'stretch'
            },
            btnTextStyle: {
                color: this.getTheme().tabBarTextColor,
                fontSize: (Platform.OS=='ios') ? 12.5 : 10,
                lineHeight: 13
            },
            btnActiveTextStyle: {
                color: this.getTheme().tabBarActiveTextColor,
                fontSize: (Platform.OS=='ios') ? 12.5 : 11,
                lineHeight: 13
            },
            btnStringTextStyle: {
                color: this.getTheme().tabBarTextColor,
                fontSize: (Platform.OS=='ios') ? 14 : 11,
                lineHeight: 16
            },
            btnStringActiveTextStyle: {
                color: this.getTheme().tabBarActiveTextColor,
                fontSize: (Platform.OS=='ios') ? 14 : 12,
                lineHeight: 16
            },
            btnStyle: {
                alignSelf: 'center',
                flex: 1,
                justifyContent: 'center',
                margin: 1,
                height: this.getTheme().footerHeight-4,
                borderRadius: (Platform.OS == 'ios') ? 7 : 0
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().footerTab
        };

        return computeProps(this.props, defaultProps);

    }

    renderFooter() {
        var childrenArray = React.Children.toArray(this.props.children);
        let length = childrenArray.length;
        var newChildren = [];

        {childrenArray.map((child, i) => {
        	let children = _.clone(child.props.children);
            if (typeof children==='string') {
                newChildren.push(React.cloneElement(child, {
                    style: [this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined }],
                    vertical: true,
                    capitalize: false,
                    transparent:true,
                    textStyle: (child.props.active) ? this.getInitialStyle().btnStringActiveTextStyle : this.getInitialStyle().btnStringTextStyle,
                    key: i}));
            }
            else {
                let iconElement = [];
                iconElement = _.remove(children, function(item) {
                    if(item.type == IconNB) {
                        return true;
                    }
                });
                let badgeElement = [];
                badgeElement = _.remove(children, function(item) {
                    if(item.type == Badge) {
                        return true;
                    }
                });
                if (iconElement.length>0) {
                    if (badgeElement.length>0) {
                      newChildren.push(
                        <View key={i} style={{position: 'relative', flex: 1}}>
                          <Button transparent vertical
                              capitalize={false}
                              style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined, alignSelf: 'stretch'}]}
                              textStyle={(child.props.active) ? this.getInitialStyle().btnActiveTextStyle : this.getInitialStyle().btnTextStyle}
                              onPress={child.props.onPress}>
                              {children}
                              <Icon
                                  style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor}}
                                  name={iconElement[0].props.name} />
                          </Button>
                          <Badge style={{position: 'absolute', top: 4, right: (length==2) ? 68 : (length==3) ? 36 : (length==4) ? 20 : undefined, height: 18, paddingHorizontal: 6, padding: 1.5, backgroundColor: (badgeElement[0].props.badgeColor) ? badgeElement[0].props.badgeColor : undefined }} textStyle={{fontSize: 11, lineHeight: 14, color: (badgeElement[0].props.textColor) ? badgeElement[0].props.textColor : undefined }}>
                            {badgeElement[0].props.children}
                          </Badge>
                      </View>
                      );
                    }
                    else {
                      newChildren.push(
                          <Button transparent vertical
                              capitalize={false}
                              style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined}]}
                              textStyle={(child.props.active) ? this.getInitialStyle().btnActiveTextStyle : this.getInitialStyle().btnTextStyle}
                              key={i} onPress={child.props.onPress}>
                              {children}
                              <Icon
                                  style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor}}
                                  name={iconElement[0].props.name} />
                          </Button>
                      );
                    }
                }
                else {
                    newChildren.push(
                        <Button transparent vertical
                            capitalize={false}
                            style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined}]}
                            key={i} onPress={child.props.onPress}>
                            <Icon
                                style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor,
                                        fontSize: 28, height: 30, lineHeight: 28}}
                                name={children.props.name} />
                        </Button>
                    );
                }
            };
        })}
        return newChildren;
    }

    render() {

        return(
            <View ref={c => this._root = c} {...this.prepareRootProps()} >
                {this.renderFooter()}
            </View>
        );
    }
}
<commit_msg>fixes #337<commit_after>/* @flow */
'use strict';

import React from 'react';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from './Button';
import { Platform } from 'react-native';
import View from './View';
import Icon from './Icon';
import Badge from './Badge';
import IconNB from './Icon';
import Text from './Text';
import _ from 'lodash';
export default class Footer extends NativeBaseComponent {

    propTypes: {
        style : React.PropTypes.object
    }

    getInitialStyle() {
        return {
            footerTab: {
                flexDirection: 'row',
                justifyContent: 'space-between',
                flex: 1,
                alignSelf: 'stretch'
            },
            btnTextStyle: {
                color: this.getTheme().tabBarTextColor,
                fontSize: (Platform.OS=='ios') ? 12.5 : 10,
                lineHeight: 13
            },
            btnActiveTextStyle: {
                color: this.getTheme().tabBarActiveTextColor,
                fontSize: (Platform.OS=='ios') ? 12.5 : 11,
                lineHeight: 13
            },
            btnStringTextStyle: {
                color: this.getTheme().tabBarTextColor,
                fontSize: (Platform.OS=='ios') ? 14 : 11,
                lineHeight: 16
            },
            btnStringActiveTextStyle: {
                color: this.getTheme().tabBarActiveTextColor,
                fontSize: (Platform.OS=='ios') ? 14 : 12,
                lineHeight: 16
            },
            btnStyle: {
                alignSelf: 'center',
                flex: 1,
                justifyContent: 'center',
                margin: 1,
                height: this.getTheme().footerHeight-4,
                borderRadius: (Platform.OS == 'ios') ? this.getTheme().tabActiveBorderRadius : 0
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().footerTab
        };

        return computeProps(this.props, defaultProps);

    }

    renderFooter() {
        var childrenArray = React.Children.toArray(this.props.children);
        let length = childrenArray.length;
        var newChildren = [];

        {childrenArray.map((child, i) => {
        	let children = _.clone(child.props.children);
            if (typeof children==='string') {
                newChildren.push(React.cloneElement(child, {
                    style: [this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined }],
                    vertical: true,
                    capitalize: false,
                    transparent:true,
                    textStyle: (child.props.active) ? this.getInitialStyle().btnStringActiveTextStyle : this.getInitialStyle().btnStringTextStyle,
                    key: i}));
            }
            else {
                let iconElement = [];
                iconElement = _.remove(children, function(item) {
                    if(item.type == IconNB) {
                        return true;
                    }
                });
                let badgeElement = [];
                badgeElement = _.remove(children, function(item) {
                    if(item.type == Badge) {
                        return true;
                    }
                });
                if (iconElement.length>0) {
                    if (badgeElement.length>0) {
                        if (children.length> 0) {
                        newChildren.push(
                            <View key={i} style={{position: 'relative', flex: 1}}>
                            <Button transparent vertical
                                capitalize={false}
                                style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined, alignSelf: 'stretch'}]}
                                textStyle={(child.props.active) ? this.getInitialStyle().btnActiveTextStyle : this.getInitialStyle().btnTextStyle}
                                onPress={child.props.onPress}>
                                {children}
                                <Icon
                                    style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor}}
                                    name={iconElement[0].props.name} />
                            </Button>
                            <Badge style={{position: 'absolute', top: 4, right: (length==2) ? 68 : (length==3) ? 36 : (length==4) ? 20 : undefined, height: 18, paddingHorizontal: 6, padding: 1.5, backgroundColor: (badgeElement[0].props.badgeColor) ? badgeElement[0].props.badgeColor : undefined }} textStyle={{fontSize: 11, lineHeight: 14, color: (badgeElement[0].props.textColor) ? badgeElement[0].props.textColor : undefined }}>
                                {badgeElement[0].props.children}
                            </Badge>
                        </View>
                        );
                    }
                        else {
                            newChildren.push(
                            <View key={i} style={{position: 'relative', flex: 1}}>
                            <Button transparent vertical
                                capitalize={false}
                                style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined, alignSelf: 'stretch'}]}
                                textStyle={(child.props.active) ? this.getInitialStyle().btnActiveTextStyle : this.getInitialStyle().btnTextStyle}
                                onPress={child.props.onPress}>
                                <Icon
                                    style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor}}
                                    name={iconElement[0].props.name} />
                            </Button>
                            <Badge style={{position: 'absolute', top: 4, right: (length==2) ? 68 : (length==3) ? 36 : (length==4) ? 20 : undefined, height: 18, paddingHorizontal: 6, padding: 1.5, backgroundColor: (badgeElement[0].props.badgeColor) ? badgeElement[0].props.badgeColor : undefined }} textStyle={{fontSize: 11, lineHeight: 14, color: (badgeElement[0].props.textColor) ? badgeElement[0].props.textColor : undefined }}>
                                {badgeElement[0].props.children}
                            </Badge>
                        </View>
                        );
                        }
                    }
                    else {
                      newChildren.push(
                          <Button transparent vertical
                              capitalize={false}
                              style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined}]}
                              textStyle={(child.props.active) ? this.getInitialStyle().btnActiveTextStyle : this.getInitialStyle().btnTextStyle}
                              key={i} onPress={child.props.onPress}>
                              {children}
                              <Icon
                                  style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor}}
                                  name={iconElement[0].props.name} />
                          </Button>
                      );
                    }
                }
                else {
                    newChildren.push(
                        <Button transparent vertical
                            capitalize={false}
                            style={[this.getInitialStyle().btnStyle, {backgroundColor: (child.props.active) ? this.getTheme().tabActiveBgColor : undefined}]}
                            key={i} onPress={child.props.onPress}>
                            <Icon
                                style={{color: (child.props.active) ? this.getTheme().tabBarActiveTextColor : this.getTheme().tabBarTextColor,
                                        fontSize: 28, height: 30, lineHeight: 28}}
                                name={children.props.name} />
                        </Button>
                    );
                }
            };
        })}
        return newChildren;
    }

    render() {

        return(
            <View ref={c => this._root = c} {...this.prepareRootProps()} >
                {this.renderFooter()}
            </View>
        );
    }
}
<|endoftext|>


<commit_before>describe('Operative (worker Context)', function() {

	describe('Callback', function() {
		it('Is called correctly', function(done) {
			var o = operative({
				longAction: function(cb) {
					for (var i = 0; i < 10000000; ++i);
					cb();
				}
			});

			function callback() {
				done();
			}

			o.longAction(callback);
			expect(o.__operative__.callbacks[1]).to.equal(callback);

		});
	});

	describe('Destroying', function() {
		it('Should have destroy + terminate alias', function() {
			expect(function() {
				operative(function(){}).destroy();
				operative(function(){}).terminate();
			}).to.not.throw();
		});
	});

	describe('Multiple Operatives', function() {
		it('Each complete asynchronously', function(done) {
			var s = [];
			var a = operative({
				run: function(cb) {
					for (var i = 0; i < 1000000; ++i);
					cb('A');
				}
			});
			var b = operative({
				run: function(cb) {
					for (var i = 0; i < 1000; ++i);
					cb('B');
				}
			});
			var c = operative({
				run: function(cb) {
					for (var i = 0; i < 1; ++i);
					cb('C');
				}
			});
			function add(v) {
				s.push(v);
				if (s.length === 3) {
					expect(s.sort().join('')).to.equal('ABC');
					done();
				}
			}

			a.run(add);
			b.run(add);
			c.run(add);

		});
	});

	describe('Promise API', function() {
		describe('Operative', function() {
			var op;
			beforeEach(function() {
				op = operative(function(beSuccessful, cb) {
					var deferred = this.deferred();
					if (beSuccessful) {
						deferred.fulfil(873);
					} else {
						deferred.reject(999);
					}
				});
			})
			it('Should return a promise', function() {
				expect(op() instanceof operative.Operative.Promise).to.be.true;
			});
			describe('fulfil()', function() {
				it('Should fulfil the exposed promise', function(done) {
					var fulfilled = false;

					op(true).then(function(a) {
						expect(a).to.equal(873);
						done();
					}, function() {
						expect(true).to.be.false; // this should not run
						done();
					});

				});
			});
			describe('reject()', function() {
				it('Should reject the exposed promise', function(done) {
					var rejected = false;
					var fulfilled = false;
					op(false).then(function() {
						expect(true).to.be.false; // this should not run
						done();
					}, function(err) {
						expect(err).to.equal(999);
						done();
					});
				});
			});
		});
	});

	describe('An example stream of operations', function() {

		it('Works with basic calculator', function(done) {
			var o = operative({
				something: 3333,
				setup: function(cb) {
					this.somethingElse = 4444;
					cb();
				},
				add: function(a, b) {
					return a + b;
				},
				subtract: function(a, b) {
					return a - b;
				},
				getSomething: function() {
					return this.something;
				},
				getSomethingElse: function() {
					return this.somethingElse;
				},
				isItAWorker: function() {
					return this.isWorker;
				},
				isItAWorker_Promisable: function() {
					this.deferred().fulfil(this.isWorker);
				}
			});

			o.setup()
				.then(function() {
					return o.add(1, 2);
				})
				.then(function(n) {
					expect(n).to.equal(3);
				})
				.then(o.isItAWorker_Promisable)
				.then(function(isWorker) {
					expect(isWorker).to.equal( operative.hasWorkerSupport );
				})
				.then(o.isItAWorker)
				.then(function(isWorker) {
					expect(isWorker).to.equal( operative.hasWorkerSupport );
				})
				.then(o.getSomething)
				.then(function(n) {
					expect(n).to.equal(3333);
				})
				.then(o.getSomethingElse)
				.then(function(n) {
					expect(n).to.equal(4444);
				})
				.then(function() {
					return o.subtract(100, 2);
				})
				.then(function(n) {
					expect(n).to.equal(98);
				})
				.then(done, done);

		});

	});

	describe('Dependency loading', function() {

		it('Can load dependencies', function(done) {
			var o = operative({
				typeofDependencies: function(cb) {
					cb([ typeof dependency1, typeof dependency2 ]);
				}
			}, ['dependency1.js', 'dependency2.js']);

			o.typeofDependencies(function(t) {
				expect(t).to.deep.equal(['function', 'function']);
				done();
			});
		});

		it('Can load external dependencies', function(done) {
			var o = operative({
				version_: function(cb) {
					cb( _.VERSION );
				}
			}, ['http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js']);

			o.version_(function(t) {
				expect(t).to.equal('1.3.1');
				done();
			});

		});
	});

	describe('No blob-support case', function() {
		beforeEach(function() {
			operative.Operative.BrowserWorker.prototype._isWorkerViaBlobSupported = function() {
				return false;
			};
		});
		it('Works correctly', function(done) {
			var o = operative(function() {
				return 888;
			});
			o(function(v) {
				expect(v).to.equal(888);
				done();
			});
		});
		describe('Explicitly setting the self URL', function() {
			beforeEach(function() {
				operative.setSelfURL(
					'../../src/contexts/BrowserWorker.js?test-explicit'
				);
			});
			it('Works; a new Worker is created with that URL', function(done) {
				var o = operative(function() {
					return self.location.href;
				});
				o(function(url) {
					expect(url).to.contain('?test-explicit');
					done();
				});
			});
		});
	});

	describe('Perpetual callbacks', function() {

		it('Is possible to keep calling the same callback (with progress etc.)', function(done) {

			var o = operative({
				process: function(cb) {

					var progress = 0;
					var me = setInterval(function() {
						progress++;
						if (progress === 5) {
							clearInterval(me);
							cb({ progress: 5, done: true });
						} else {
							cb({ progress: progress, done: false });
						}
					}, 30);

				}
			});

			var called = 0;

			o.process(function(status) {
				called++;
				expect(status.progress).to.be.above(0);
				if (status.progress === 5) {
					expect(status.done).to.equal(true);
					expect(called).to.equal(5); // called five times
					done();
				}
			});

		});

	});

	describe('Transfers', function() {
		describe('Using callback API', function() {
			it('Transfers ownership of the buffer', function(done) {

				if (!operative.hasTransferSupport && typeof Uint8Array == 'undefined') {
					done();
					return;
				}

				var o = operative({
					receive: function(t, cb) {
						self.arr = new Uint8Array([1,2,3]);
						cb.transfer(self.arr.buffer, [self.arr.buffer]);
					},
					isYourByteLengthEmpty: function(cb) {
						cb(
							0 == (self.arr.buffer ? self.arr.buffer.byteLength : self.arr.byteLength)
						);
					}
				});

				var a = new Uint8Array([33,22,11]);

				o.receive.transfer(a.buffer, [a.buffer], function(r) {
					if (operative.hasTransferSupport) {
						expect(a.buffer ? a.buffer.byteLength : a.byteLength).to.equal(0);
					}
					o.isYourByteLengthEmpty(function(result) {
						if (operative.hasTransferSupport) {
							expect(result).to.be.true;
						}
						done();
					})
				});

			});
		});
		describe('Using promise API', function() {
			it('Transfers ownership of the buffer', function(done) {

				if (!operative.hasTransferSupport && typeof Uint8Array == 'undefined') {
					done();
					return;
				}

				var o = operative({
					receive: function(t, cb) {
						self.arr = new Uint8Array([1,2,3]);
						var def = this.deferred();
						def.transferResolve(self.arr.buffer, [self.arr.buffer]);
					},
					isYourByteLengthEmpty: function(cb) {
						this.deferred().resolve(
							0 == (self.arr.buffer ? self.arr.buffer.byteLength : self.arr.byteLength)
						);
					}
				});

				var a = new Uint8Array([33,22,11]);

				o.receive.transfer(a.buffer, [a.buffer])
					.then(function(r) {
						if (operative.hasTransferSupport) {
							expect(a.buffer ? a.buffer.byteLength : a.byteLength).to.equal(0);
						}
						return o.isYourByteLengthEmpty().then(function(result) {
							if (operative.hasTransferSupport) {
								expect(result).to.be.true;
							}
						})
					}).then(done, done);

			});
		});
	});

});<commit_msg>Assert for non-worker case (<=IE9, etc.)<commit_after>describe('Operative (worker Context)', function() {

	describe('Callback', function() {
		it('Is called correctly', function(done) {
			var o = operative({
				longAction: function(cb) {
					for (var i = 0; i < 10000000; ++i);
					cb();
				}
			});

			function callback() {
				done();
			}

			o.longAction(callback);
			expect(o.__operative__.callbacks[1]).to.equal(callback);

		});
	});

	describe('Destroying', function() {
		it('Should have destroy + terminate alias', function() {
			expect(function() {
				operative(function(){}).destroy();
				operative(function(){}).terminate();
			}).to.not.throw();
		});
	});

	describe('Multiple Operatives', function() {
		it('Each complete asynchronously', function(done) {
			var s = [];
			var a = operative({
				run: function(cb) {
					for (var i = 0; i < 1000000; ++i);
					cb('A');
				}
			});
			var b = operative({
				run: function(cb) {
					for (var i = 0; i < 1000; ++i);
					cb('B');
				}
			});
			var c = operative({
				run: function(cb) {
					for (var i = 0; i < 1; ++i);
					cb('C');
				}
			});
			function add(v) {
				s.push(v);
				if (s.length === 3) {
					expect(s.sort().join('')).to.equal('ABC');
					done();
				}
			}

			a.run(add);
			b.run(add);
			c.run(add);

		});
	});

	describe('Promise API', function() {
		describe('Operative', function() {
			var op;
			beforeEach(function() {
				op = operative(function(beSuccessful, cb) {
					var deferred = this.deferred();
					if (beSuccessful) {
						deferred.fulfil(873);
					} else {
						deferred.reject(999);
					}
				});
			})
			it('Should return a promise', function() {
				expect(op() instanceof operative.Operative.Promise).to.be.true;
			});
			describe('fulfil()', function() {
				it('Should fulfil the exposed promise', function(done) {
					var fulfilled = false;

					op(true).then(function(a) {
						expect(a).to.equal(873);
						done();
					}, function() {
						expect(true).to.be.false; // this should not run
						done();
					});

				});
			});
			describe('reject()', function() {
				it('Should reject the exposed promise', function(done) {
					var rejected = false;
					var fulfilled = false;
					op(false).then(function() {
						expect(true).to.be.false; // this should not run
						done();
					}, function(err) {
						expect(err).to.equal(999);
						done();
					});
				});
			});
		});
	});

	describe('An example stream of operations', function() {

		it('Works with basic calculator', function(done) {
			var o = operative({
				something: 3333,
				setup: function(cb) {
					this.somethingElse = 4444;
					cb();
				},
				add: function(a, b) {
					return a + b;
				},
				subtract: function(a, b) {
					return a - b;
				},
				getSomething: function() {
					return this.something;
				},
				getSomethingElse: function() {
					return this.somethingElse;
				},
				isItAWorker: function() {
					return this.isWorker;
				},
				isItAWorker_Promisable: function() {
					this.deferred().fulfil(this.isWorker);
				}
			});

			o.setup()
				.then(function() {
					return o.add(1, 2);
				})
				.then(function(n) {
					expect(n).to.equal(3);
				})
				.then(o.isItAWorker_Promisable)
				.then(function(isWorker) {
					expect(isWorker).to.equal( operative.hasWorkerSupport );
				})
				.then(o.isItAWorker)
				.then(function(isWorker) {
					expect(isWorker).to.equal( operative.hasWorkerSupport );
				})
				.then(o.getSomething)
				.then(function(n) {
					expect(n).to.equal(3333);
				})
				.then(o.getSomethingElse)
				.then(function(n) {
					expect(n).to.equal(4444);
				})
				.then(function() {
					return o.subtract(100, 2);
				})
				.then(function(n) {
					expect(n).to.equal(98);
				})
				.then(done, done);

		});

	});

	describe('Dependency loading', function() {

		it('Can load dependencies', function(done) {
			var o = operative({
				typeofDependencies: function(cb) {
					cb([ typeof dependency1, typeof dependency2 ]);
				}
			}, ['dependency1.js', 'dependency2.js']);

			o.typeofDependencies(function(t) {
				expect(t).to.deep.equal(['function', 'function']);
				done();
			});
		});

		it('Can load external dependencies', function(done) {
			var o = operative({
				version_: function(cb) {
					cb( _.VERSION );
				}
			}, ['http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js']);

			o.version_(function(t) {
				expect(t).to.equal('1.3.1');
				done();
			});

		});
	});

	describe('No blob-support case', function() {
		beforeEach(function() {
			operative.Operative.BrowserWorker.prototype._isWorkerViaBlobSupported = function() {
				return false;
			};
		});
		it('Works correctly', function(done) {
			var o = operative(function() {
				return 888;
			});
			o(function(v) {
				expect(v).to.equal(888);
				done();
			});
		});
		describe('Explicitly setting the self URL', function() {
			beforeEach(function() {
				operative.setSelfURL(
					'../../src/contexts/BrowserWorker.js?test-explicit'
				);
			});
			it('Works; a new Worker is created with that URL', function(done) {
				var o = operative(function() {
					return self.location.href;
				});
				o(function(url) {
					if (operative.hasWorkerSupport) {
						// Worker context
						expect(url).to.contain('?test-explicit');
					} else {
						// Iframe context (self-url changing does nothing)
						expect(url).to.contain('.html');
					}
					done();
				});
			});
		});
	});

	describe('Perpetual callbacks', function() {

		it('Is possible to keep calling the same callback (with progress etc.)', function(done) {

			var o = operative({
				process: function(cb) {

					var progress = 0;
					var me = setInterval(function() {
						progress++;
						if (progress === 5) {
							clearInterval(me);
							cb({ progress: 5, done: true });
						} else {
							cb({ progress: progress, done: false });
						}
					}, 30);

				}
			});

			var called = 0;

			o.process(function(status) {
				called++;
				expect(status.progress).to.be.above(0);
				if (status.progress === 5) {
					expect(status.done).to.equal(true);
					expect(called).to.equal(5); // called five times
					done();
				}
			});

		});

	});

	describe('Transfers', function() {
		describe('Using callback API', function() {
			it('Transfers ownership of the buffer', function(done) {

				if (!operative.hasTransferSupport && typeof Uint8Array == 'undefined') {
					done();
					return;
				}

				var o = operative({
					receive: function(t, cb) {
						self.arr = new Uint8Array([1,2,3]);
						cb.transfer(self.arr.buffer, [self.arr.buffer]);
					},
					isYourByteLengthEmpty: function(cb) {
						cb(
							0 == (self.arr.buffer ? self.arr.buffer.byteLength : self.arr.byteLength)
						);
					}
				});

				var a = new Uint8Array([33,22,11]);

				o.receive.transfer(a.buffer, [a.buffer], function(r) {
					if (operative.hasTransferSupport) {
						expect(a.buffer ? a.buffer.byteLength : a.byteLength).to.equal(0);
					}
					o.isYourByteLengthEmpty(function(result) {
						if (operative.hasTransferSupport) {
							expect(result).to.be.true;
						}
						done();
					})
				});

			});
		});
		describe('Using promise API', function() {
			it('Transfers ownership of the buffer', function(done) {

				if (!operative.hasTransferSupport && typeof Uint8Array == 'undefined') {
					done();
					return;
				}

				var o = operative({
					receive: function(t, cb) {
						self.arr = new Uint8Array([1,2,3]);
						var def = this.deferred();
						def.transferResolve(self.arr.buffer, [self.arr.buffer]);
					},
					isYourByteLengthEmpty: function(cb) {
						this.deferred().resolve(
							0 == (self.arr.buffer ? self.arr.buffer.byteLength : self.arr.byteLength)
						);
					}
				});

				var a = new Uint8Array([33,22,11]);

				o.receive.transfer(a.buffer, [a.buffer])
					.then(function(r) {
						if (operative.hasTransferSupport) {
							expect(a.buffer ? a.buffer.byteLength : a.byteLength).to.equal(0);
						}
						return o.isYourByteLengthEmpty().then(function(result) {
							if (operative.hasTransferSupport) {
								expect(result).to.be.true;
							}
						})
					}).then(done, done);

			});
		});
	});

});<|endoftext|>