<commit_before>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Engine
*/

// TODO: multiple event handlers, before & after handlers
// TODO: viewports
// TODO: frameskipping

var Engine = {};

(function() {

    var _fps = 60,
        _deltaSampleSize = 8,
        _delta = 1000 / _fps;

    var _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame
                                      || window.mozRequestAnimationFrame || window.msRequestAnimationFrame
                                      || function(callback){ window.setTimeout(function() { callback(Common.now()); }, _delta); };

    /**
     * Description
     * @method create
     * @param {HTMLElement} element
     * @param {object} options
     * @return {engine} engine
     */
    Engine.create = function(element, options) {
        var defaults = {
            enabled: true,
            positionIterations: 6,
            velocityIterations: 4,
            constraintIterations: 1,
            pairs: {
                table: {},
                list: [],
                collisionStart: [],
                collisionActive: [],
                collisionEnd: []
            },
            enableSleeping: false,
            timeScale: 1,
            input: {},
            events: [],
            timing: {
                fps: _fps,
                timestamp: 0,
                delta: _delta,
                correction: 1,
                deltaMin: 1000 / _fps,
                deltaMax: 1000 / (_fps * 0.5)
            }
        };

        var engine = Common.extend(defaults, options);
        engine = Common.isElement(element) ? (engine || {}) : element;

        // create default renderer only if no custom renderer set
        // but still allow engine.render.engine to pass through if set
        if (!engine.render || (engine.render && !engine.render.controller)) {
            engine.render = Render.create(engine.render);
            if (Common.isElement(element))
                element.appendChild(engine.render.canvas);
        }

        engine.world = World.create(engine.world);
        engine.metrics = engine.metrics || Metrics.create();
        engine.input.mouse = engine.input.mouse || Mouse.create(engine.render.canvas);
        engine.mouseConstraint = engine.mouseConstraint || MouseConstraint.create(engine.input.mouse);
        World.addComposite(engine.world, engine.mouseConstraint);

        engine.broadphase = engine.broadphase || {
            current: 'grid',
            grid: {
                controller: Grid,
                instance: Grid.create(),
                detector: Detector.collisions
            },
            bruteForce: {
                detector: Detector.bruteForce
            }
        };

        return engine;
    };

    /**
     * Description
     * @method run
     * @param {engine} engine
     */
    Engine.run = function(engine) {
        var timing = engine.timing,
            delta,
            correction,
            counterTimestamp = 0,
            frameCounter = 0,
            deltaHistory = [];

        (function render(timestamp){
            _requestAnimationFrame(render);

            if (!engine.enabled)
                return;

            // create an event object
            var event = {
                timestamp: timestamp
            };

            /**
            * Fired at the start of a tick, before any updates to the engine or timing
            *
            * @event beforeTick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'beforeTick', event);

            delta = (timestamp - timing.timestamp) || _delta;

            // optimistically filter delta over a few frames, to improve stability
            deltaHistory.push(delta);
            deltaHistory = deltaHistory.slice(-_deltaSampleSize);
            delta = Math.min.apply(null, deltaHistory);

            // limit delta
            delta = delta < engine.timing.deltaMin ? engine.timing.deltaMin : delta;
            delta = delta > engine.timing.deltaMax ? engine.timing.deltaMax : delta;

            // verlet time correction
            correction = delta / timing.delta;

            // update engine timing object
            timing.timestamp = timestamp;
            timing.correction = correction;
            timing.delta = delta;

            // fps counter
            frameCounter += 1;
            if (timestamp - counterTimestamp >= 1000) {
                timing.fps = frameCounter * ((timestamp - counterTimestamp) / 1000);
                counterTimestamp = timestamp;
                frameCounter = 0;
            }

            /**
            * Fired after engine timing updated, but just before engine state updated
            *
            * @event tick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired just before an update
            *
            * @event beforeUpdate
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'tick beforeUpdate', event);

            // update
            Engine.update(engine, delta, correction);

            // trigger events that may have occured during the step
            _triggerCollisionEvents(engine);
            _triggerMouseEvents(engine);

            /**
            * Fired after engine update and all collision events
            *
            * @event afterUpdate
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired just before rendering
            *
            * @event beforeRender
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'afterUpdate beforeRender', event);

            // render
            if (engine.render.options.enabled)
                engine.render.controller.world(engine);

            /**
            * Fired after rendering
            *
            * @event afterRender
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired after engine update and after rendering
            *
            * @event afterTick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'afterTick afterRender', event);
        })();
    };

    /**
     * Description
     * @method update
     * @param {engine} engine
     * @param {number} delta
     * @param {number} correction
     * @return engine
     */
    Engine.update = function(engine, delta, correction) {
        var world = engine.world,
            broadphase = engine.broadphase[engine.broadphase.current],
            broadphasePairs = [],
            i;

        Metrics.reset(engine.metrics);

        if (engine.enableSleeping)
            Sleeping.update(world.bodies);

        Body.applyGravityAll(world.bodies, world.gravity);

        MouseConstraint.update(engine.mouseConstraint, world.bodies, engine.input);

        Body.updateAll(world.bodies, delta * engine.timeScale, correction, world.bounds);

        // update all constraints
        for (i = 0; i < engine.constraintIterations; i++) {
            Constraint.updateAll(world.constraints);
        }

        // broadphase pass: find potential collision pairs
        if (broadphase.controller) {
            broadphase.controller.update(broadphase.instance, world.bodies, engine);
            broadphasePairs = broadphase.instance.pairsList;
        } else {
            broadphasePairs = world.bodies;
        }

        // narrowphase pass: find actual collisions, then create or update collision pairs
        var collisions = broadphase.detector(broadphasePairs, engine.metrics);

        // update pairs
        var pairs = engine.pairs;
        Manager.updatePairs(pairs, collisions);
        Manager.removeOldPairs(pairs);

        // wake up bodies involved in collisions
        if (engine.enableSleeping)
            Sleeping.afterCollisions(pairs.list);

        // iteratively resolve velocity between collisions
        Resolver.preSolveVelocity(pairs.list);
        for (i = 0; i < engine.velocityIterations; i++) {
            Resolver.solveVelocity(pairs.list);
        }

        // iteratively resolve position between collisions
        for (i = 0; i < engine.positionIterations; i++) {
            Resolver.solvePosition(pairs.list);
        }
        Resolver.postSolvePosition(world.bodies);

        Metrics.update(engine.metrics, engine);

        // clear force buffers
        Body.resetForcesAll(world.bodies);

        return engine;
    };

    /**
     * Description
     * @method merge
     * @param {engine} engineA
     * @param {engine} engineB
     */
    Engine.merge = function(engineA, engineB) {
        Common.extend(engineA, engineB);

        if (engineB.world) {
            engineA.world = engineB.world;

            Engine.clear(engineA);

            var bodies = engineA.world.bodies;

            for (var i = 0; i < bodies.length; i++) {
                var body = bodies[i];
                Sleeping.set(body, false);
                body.id = Body.nextId();
            }

            var broadphase = engineA.broadphase[engineA.broadphase.current];

            if (broadphase.controller === Grid) {
                var grid = broadphase.instance;
                Grid.clear(grid);
                Grid.update(grid, engineA.world.bodies, engineA, true);
            }
        }
    };

    /**
     * Description
     * @method clear
     * @param {engine} engine
     */
    Engine.clear = function(engine) {
        var world = engine.world;

        engine.pairs.table = {};
        engine.pairs.list = [];

        World.addComposite(engine.world, engine.mouseConstraint);

        var broadphase = engine.broadphase[engine.broadphase.current];

        if (broadphase.controller === Grid)
            Grid.clear(broadphase.instance);

        if (broadphase.controller) {
            broadphase.controller.update(broadphase.instance, world.bodies, engine, true);
        }
    };

    /**
     * Triggers mouse events
     * @method _triggerMouseEvents
     * @private
     * @param {engine} engine
     */
    var _triggerMouseEvents = function(engine) {
        var mouse = engine.input.mouse,
            mouseEvents = mouse.sourceEvents;

        /**
        * Fired when the mouse has moved (or a touch moves) during the last step
        *
        * @event mousemove
        * @param {} event An event object
        * @param {MouseEvent} event.mouseEvent The native MouseEvent from the browser
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mousemove) {
            Events.trigger(mouse, 'mousemove', {
                mouseEvent: mouseEvents.mousemove
            });
        }

        /**
        * Fired when the mouse is down (or a touch has started) during the last step
        *
        * @event mousedown
        * @param {} event An event object
        * @param {MouseEvent} event.mouseEvent The native MouseEvent from the browser
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mousedown) {
            Events.trigger(mouse, 'mousedown', {
                mouseEvent: mouseEvents.mousedown
            });
        }

        /**
        * Fired when the mouse is up (or a touch has ended) during the last step
        *
        * @event mouseup
        * @param {} event An event object
        * @param {MouseEvent} event.mouseEvent The native MouseEvent from the browser
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mouseup) {
            Events.trigger(mouse, 'mouseup', {
                mouseEvent: mouseEvents.mouseup
            });
        }

        // reset the mouse state ready for the next step
        Mouse.clearSourceEvents(mouse);
    };

    /**
     * Triggers collision events
     * @method _triggerMouseEvents
     * @private
     * @param {engine} engine
     */
    var _triggerCollisionEvents = function(engine) {
        var pairs = engine.pairs;

        /**
        * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any)
        *
        * @event collisionStart
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionStart.length > 0) {
            Events.trigger(engine, 'collisionStart', {
                pairs: pairs.collisionStart
            });
        }

        /**
        * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any)
        *
        * @event collisionActive
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionActive.length > 0) {
            Events.trigger(engine, 'collisionActive', {
                pairs: pairs.collisionActive
            });
        }

        /**
        * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any)
        *
        * @event collisionEnd
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionEnd.length > 0) {
            Events.trigger(engine, 'collisionEnd', {
                pairs: pairs.collisionEnd
            });
        }
    };

})();<commit_msg>changes to mouse events<commit_after>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Engine
*/

// TODO: multiple event handlers, before & after handlers
// TODO: viewports
// TODO: frameskipping

var Engine = {};

(function() {

    var _fps = 60,
        _deltaSampleSize = 8,
        _delta = 1000 / _fps;

    var _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame
                                      || window.mozRequestAnimationFrame || window.msRequestAnimationFrame
                                      || function(callback){ window.setTimeout(function() { callback(Common.now()); }, _delta); };

    /**
     * Description
     * @method create
     * @param {HTMLElement} element
     * @param {object} options
     * @return {engine} engine
     */
    Engine.create = function(element, options) {
        var defaults = {
            enabled: true,
            positionIterations: 6,
            velocityIterations: 4,
            constraintIterations: 1,
            pairs: {
                table: {},
                list: [],
                collisionStart: [],
                collisionActive: [],
                collisionEnd: []
            },
            enableSleeping: false,
            timeScale: 1,
            input: {},
            events: [],
            timing: {
                fps: _fps,
                timestamp: 0,
                delta: _delta,
                correction: 1,
                deltaMin: 1000 / _fps,
                deltaMax: 1000 / (_fps * 0.5)
            }
        };

        var engine = Common.extend(defaults, options);
        engine = Common.isElement(element) ? (engine || {}) : element;

        // create default renderer only if no custom renderer set
        // but still allow engine.render.engine to pass through if set
        if (!engine.render || (engine.render && !engine.render.controller)) {
            engine.render = Render.create(engine.render);
            if (Common.isElement(element))
                element.appendChild(engine.render.canvas);
        }

        engine.world = World.create(engine.world);
        engine.metrics = engine.metrics || Metrics.create();
        engine.input.mouse = engine.input.mouse || Mouse.create(engine.render.canvas);
        engine.mouseConstraint = engine.mouseConstraint || MouseConstraint.create(engine.input.mouse);
        World.addComposite(engine.world, engine.mouseConstraint);

        engine.broadphase = engine.broadphase || {
            current: 'grid',
            grid: {
                controller: Grid,
                instance: Grid.create(),
                detector: Detector.collisions
            },
            bruteForce: {
                detector: Detector.bruteForce
            }
        };

        return engine;
    };

    /**
     * Description
     * @method run
     * @param {engine} engine
     */
    Engine.run = function(engine) {
        var timing = engine.timing,
            delta,
            correction,
            counterTimestamp = 0,
            frameCounter = 0,
            deltaHistory = [];

        (function render(timestamp){
            _requestAnimationFrame(render);

            if (!engine.enabled)
                return;

            // create an event object
            var event = {
                timestamp: timestamp
            };

            /**
            * Fired at the start of a tick, before any updates to the engine or timing
            *
            * @event beforeTick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'beforeTick', event);

            delta = (timestamp - timing.timestamp) || _delta;

            // optimistically filter delta over a few frames, to improve stability
            deltaHistory.push(delta);
            deltaHistory = deltaHistory.slice(-_deltaSampleSize);
            delta = Math.min.apply(null, deltaHistory);

            // limit delta
            delta = delta < engine.timing.deltaMin ? engine.timing.deltaMin : delta;
            delta = delta > engine.timing.deltaMax ? engine.timing.deltaMax : delta;

            // verlet time correction
            correction = delta / timing.delta;

            // update engine timing object
            timing.timestamp = timestamp;
            timing.correction = correction;
            timing.delta = delta;

            // fps counter
            frameCounter += 1;
            if (timestamp - counterTimestamp >= 1000) {
                timing.fps = frameCounter * ((timestamp - counterTimestamp) / 1000);
                counterTimestamp = timestamp;
                frameCounter = 0;
            }

            /**
            * Fired after engine timing updated, but just before engine state updated
            *
            * @event tick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired just before an update
            *
            * @event beforeUpdate
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'tick beforeUpdate', event);

            // update
            Engine.update(engine, delta, correction);

            // trigger events that may have occured during the step
            _triggerCollisionEvents(engine);
            _triggerMouseEvents(engine);

            /**
            * Fired after engine update and all collision events
            *
            * @event afterUpdate
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired just before rendering
            *
            * @event beforeRender
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'afterUpdate beforeRender', event);

            // render
            if (engine.render.options.enabled)
                engine.render.controller.world(engine);

            /**
            * Fired after rendering
            *
            * @event afterRender
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            /**
            * Fired after engine update and after rendering
            *
            * @event afterTick
            * @param {} event An event object
            * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
            * @param {} event.source The source object of the event
            * @param {} event.name The name of the event
            */
            Events.trigger(engine, 'afterTick afterRender', event);
        })();
    };

    /**
     * Description
     * @method update
     * @param {engine} engine
     * @param {number} delta
     * @param {number} correction
     * @return engine
     */
    Engine.update = function(engine, delta, correction) {
        var world = engine.world,
            broadphase = engine.broadphase[engine.broadphase.current],
            broadphasePairs = [],
            i;

        Metrics.reset(engine.metrics);

        if (engine.enableSleeping)
            Sleeping.update(world.bodies);

        Body.applyGravityAll(world.bodies, world.gravity);

        MouseConstraint.update(engine.mouseConstraint, world.bodies, engine.input);

        Body.updateAll(world.bodies, delta * engine.timeScale, correction, world.bounds);

        // update all constraints
        for (i = 0; i < engine.constraintIterations; i++) {
            Constraint.updateAll(world.constraints);
        }

        // broadphase pass: find potential collision pairs
        if (broadphase.controller) {
            broadphase.controller.update(broadphase.instance, world.bodies, engine);
            broadphasePairs = broadphase.instance.pairsList;
        } else {
            broadphasePairs = world.bodies;
        }

        // narrowphase pass: find actual collisions, then create or update collision pairs
        var collisions = broadphase.detector(broadphasePairs, engine.metrics);

        // update pairs
        var pairs = engine.pairs;
        Manager.updatePairs(pairs, collisions);
        Manager.removeOldPairs(pairs);

        // wake up bodies involved in collisions
        if (engine.enableSleeping)
            Sleeping.afterCollisions(pairs.list);

        // iteratively resolve velocity between collisions
        Resolver.preSolveVelocity(pairs.list);
        for (i = 0; i < engine.velocityIterations; i++) {
            Resolver.solveVelocity(pairs.list);
        }

        // iteratively resolve position between collisions
        for (i = 0; i < engine.positionIterations; i++) {
            Resolver.solvePosition(pairs.list);
        }
        Resolver.postSolvePosition(world.bodies);

        Metrics.update(engine.metrics, engine);

        // clear force buffers
        Body.resetForcesAll(world.bodies);

        return engine;
    };

    /**
     * Description
     * @method merge
     * @param {engine} engineA
     * @param {engine} engineB
     */
    Engine.merge = function(engineA, engineB) {
        Common.extend(engineA, engineB);

        if (engineB.world) {
            engineA.world = engineB.world;

            Engine.clear(engineA);

            var bodies = engineA.world.bodies;

            for (var i = 0; i < bodies.length; i++) {
                var body = bodies[i];
                Sleeping.set(body, false);
                body.id = Body.nextId();
            }

            var broadphase = engineA.broadphase[engineA.broadphase.current];

            if (broadphase.controller === Grid) {
                var grid = broadphase.instance;
                Grid.clear(grid);
                Grid.update(grid, engineA.world.bodies, engineA, true);
            }
        }
    };

    /**
     * Description
     * @method clear
     * @param {engine} engine
     */
    Engine.clear = function(engine) {
        var world = engine.world;

        engine.pairs.table = {};
        engine.pairs.list = [];

        World.addComposite(engine.world, engine.mouseConstraint);

        var broadphase = engine.broadphase[engine.broadphase.current];

        if (broadphase.controller === Grid)
            Grid.clear(broadphase.instance);

        if (broadphase.controller) {
            broadphase.controller.update(broadphase.instance, world.bodies, engine, true);
        }
    };

    /**
     * Triggers mouse events
     * @method _triggerMouseEvents
     * @private
     * @param {engine} engine
     */
    var _triggerMouseEvents = function(engine) {
        var mouse = engine.input.mouse,
            mouseEvents = mouse.sourceEvents;

        /**
        * Fired when the mouse has moved (or a touch moves) during the last step
        *
        * @event mousemove
        * @param {} event An event object
        * @param {mouse} event.mouse The engine's mouse instance
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mousemove) {
            Events.trigger(engine, 'mousemove', {
                mouse: mouse
            });
        }

        /**
        * Fired when the mouse is down (or a touch has started) during the last step
        *
        * @event mousedown
        * @param {} event An event object
        * @param {mouse} event.mouse The engine's mouse instance
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mousedown) {
            Events.trigger(engine, 'mousedown', {
                mouse: mouse
            });
        }

        /**
        * Fired when the mouse is up (or a touch has ended) during the last step
        *
        * @event mouseup
        * @param {} event An event object
        * @param {mouse} event.mouse The engine's mouse instance
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (mouseEvents.mouseup) {
            Events.trigger(engine, 'mouseup', {
                mouse: mouse
            });
        }

        // reset the mouse state ready for the next step
        Mouse.clearSourceEvents(mouse);
    };

    /**
     * Triggers collision events
     * @method _triggerMouseEvents
     * @private
     * @param {engine} engine
     */
    var _triggerCollisionEvents = function(engine) {
        var pairs = engine.pairs;

        /**
        * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any)
        *
        * @event collisionStart
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionStart.length > 0) {
            Events.trigger(engine, 'collisionStart', {
                pairs: pairs.collisionStart
            });
        }

        /**
        * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any)
        *
        * @event collisionActive
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionActive.length > 0) {
            Events.trigger(engine, 'collisionActive', {
                pairs: pairs.collisionActive
            });
        }

        /**
        * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any)
        *
        * @event collisionEnd
        * @param {} event An event object
        * @param {} event.pairs List of affected pairs
        * @param {DOMHighResTimeStamp} event.timestamp The timestamp of the current tick
        * @param {} event.source The source object of the event
        * @param {} event.name The name of the event
        */
        if (pairs.collisionEnd.length > 0) {
            Events.trigger(engine, 'collisionEnd', {
                pairs: pairs.collisionEnd
            });
        }
    };

})();<|endoftext|>


<commit_before>/**
 * @fileOverview
 *
 * KityMinder 类，暴露在 window 上的唯一变量
 *
 * @author: techird
 * @copyright: Baidu FEX, 2014
 */
define(function(require, exports, module) {
    var kity = require('./kity');
    var utils = require('./utils');

    var _initHooks = [];

    var Minder = kity.createClass('Minder', {
        constructor: function(options) {
            this._options = utils.extend({}, options);

            var initHooks = _initHooks.slice();

            var initHook;
            while (initHooks.length) {
                initHook = initHooks.shift();
                if (typeof(initHook) == 'function') {
                    initHook.call(this, this._options);
                }
            }

            this.fire('finishInitHook');
        }
    });

    Minder.version = '1.4.25';

    Minder.registerInitHook = function(hook) {
        _initHooks.push(hook);
    };

    module.exports = Minder;
});
<commit_msg>changed version<commit_after>/**
 * @fileOverview
 *
 * KityMinder 类，暴露在 window 上的唯一变量
 *
 * @author: techird
 * @copyright: Baidu FEX, 2014
 */
define(function(require, exports, module) {
    var kity = require('./kity');
    var utils = require('./utils');

    var _initHooks = [];

    var Minder = kity.createClass('Minder', {
        constructor: function(options) {
            this._options = utils.extend({}, options);

            var initHooks = _initHooks.slice();

            var initHook;
            while (initHooks.length) {
                initHook = initHooks.shift();
                if (typeof(initHook) == 'function') {
                    initHook.call(this, this._options);
                }
            }

            this.fire('finishInitHook');
        }
    });

    Minder.version = '1.4.26';

    Minder.registerInitHook = function(hook) {
        _initHooks.push(hook);
    };

    module.exports = Minder;
});
<|endoftext|>


<commit_before>const path = require('path')
const { DAGNode } = require('ipld-dag-pb')

// Creates a DB manifest file and saves it in IPFS
const createDBManifest = async (ipfs, name, type, accessControllerAddress, onlyHash) => {
  const manifest = {
    name: name,
    type: type,
    accessController: path.join('/ipfs', accessControllerAddress),
  }
  let dag
  const manifestJSON = JSON.stringify(manifest)
  if (onlyHash) {
    dag = await new Promise(resolve => {
      DAGNode.create(Buffer.from(manifestJSON), (err, n) => { resolve(n) })
    })
  } else {
    dag = await ipfs.object.put(Buffer.from(manifestJSON))
  }
  return dag.toJSON().multihash.toString()
}

module.exports = createDBManifest
<commit_msg>Throw error returned from DAGNode.create<commit_after>const path = require('path')
const { DAGNode } = require('ipld-dag-pb')

// Creates a DB manifest file and saves it in IPFS
const createDBManifest = async (ipfs, name, type, accessControllerAddress, onlyHash) => {
  const manifest = {
    name: name,
    type: type,
    accessController: path.join('/ipfs', accessControllerAddress),
  }
  let dag
  const manifestJSON = JSON.stringify(manifest)
  if (onlyHash) {
    dag = await new Promise(resolve => {
      DAGNode.create(Buffer.from(manifestJSON), (err, n) => {
        if (err) {
          throw err
        }
        resolve(n)
      })
    })
  } else {
    dag = await ipfs.object.put(Buffer.from(manifestJSON))
  }
  return dag.toJSON().multihash.toString()
}

module.exports = createDBManifest
<|endoftext|>


<commit_before>import { OpenSearchUrl } from './url';
import { parseXml, xPath, xPathArray } from './utils';

/**
 * Class to parse the OpenSearchDescription XML document and get the saerch URLs
 */
export class OpenSearchDescription {
  /**
   * Create an OpenSearchDescription object
   * @param {string} xml The string containing the desription XML
   */
  constructor(xml) {
    // parse XML and get metadata and list of URLs
    const xmlDoc = parseXml(xml).documentElement;

    this.shortName = xPath(xmlDoc, 'os:ShortName/text()');
    this.description = xPath(xmlDoc, 'os:Description/text()');
    this.tags = xPath(xmlDoc, 'os:Tags/text()');
    this.contact = xPath(xmlDoc, 'os:Contact/text()');
    this.urls = xPathArray(xmlDoc, 'os:Url').map(
      (node) => OpenSearchUrl.fromNode(node)
    );
    this.longName = xPath(xmlDoc, 'os:LongName/text()');
    this.images = xPathArray(xmlDoc, 'os:Image').map((node) => {
      return {
        height: parseInt(node.getAttribute('height'), 10),
        width: parseInt(node.getAttribute('width'), 10),
        type: node.getAttribute('type'),
        url: node.textContent,
      };
    });
    this.queries = xPathArray(xmlDoc, 'os:Query').map((node) => {
      const query = { role: node.getAttribute('role') };
      for (let i = 0; i < node.attributes.length; ++i) {
        const attribute = node.attributes[i];
        query[attribute.name] = attribute.value;
      }
      return query;
    });
    this.developer = xPath(xmlDoc, 'os:Developer/text()');
    this.attribution = xPath(xmlDoc, 'os:Attribution/text()');
    this.syndicationRight = xPath(xmlDoc, 'os:SyndicationRight/text()');
    this.adultContent = xPath(xmlDoc, 'os:AdultContent/text()');
    this.language = xPath(xmlDoc, 'os:Language/text()');
    this.outputEncoding = xPath(xmlDoc, 'os:OutputEncoding/text()');
    this.inputEncoding = xPath(xmlDoc, 'os:InputEncoding/text()');
  }

  /**
   * Get the {@link OpenSearchUrl} for the given parameters, mime type and HTTP
   * method.
   * @param {object} parameters An object containing parameters for the URL
   * @param {string} [type=null] The mime-type for the URL
   * @param {string} [method='GET'] The preferred HTTP method of the URL
   */
  getUrl(parameters, type = null, method = 'GET') {
    const urls = this.urls.filter(
      (url) => (type === null || url.type === type) && url.method === method
    ).filter(
      (url) => url.isCompatible(parameters)
    );

    return urls[0];
  }
}
<commit_msg>Fix for lint.<commit_after>import { OpenSearchUrl } from './url';
import { parseXml, xPath, xPathArray } from './utils';

/**
 * Class to parse the OpenSearchDescription XML document and get the saerch URLs
 */
export class OpenSearchDescription {
  /**
   * Create an OpenSearchDescription object
   * @param {string} xml The string containing the desription XML
   */
  constructor(xml) {
    // parse XML and get metadata and list of URLs
    const xmlDoc = parseXml(xml).documentElement;

    this.shortName = xPath(xmlDoc, 'os:ShortName/text()');
    this.description = xPath(xmlDoc, 'os:Description/text()');
    this.tags = xPath(xmlDoc, 'os:Tags/text()');
    this.contact = xPath(xmlDoc, 'os:Contact/text()');
    this.urls = xPathArray(xmlDoc, 'os:Url').map(
      (node) => OpenSearchUrl.fromNode(node)
    );
    this.longName = xPath(xmlDoc, 'os:LongName/text()');
    this.images = xPathArray(xmlDoc, 'os:Image').map((node) => { // eslint-disable-line
      return {
        height: parseInt(node.getAttribute('height'), 10),
        width: parseInt(node.getAttribute('width'), 10),
        type: node.getAttribute('type'),
        url: node.textContent,
      };
    });
    this.queries = xPathArray(xmlDoc, 'os:Query').map((node) => {
      const query = { role: node.getAttribute('role') };
      for (let i = 0; i < node.attributes.length; ++i) {
        const attribute = node.attributes[i];
        query[attribute.name] = attribute.value;
      }
      return query;
    });
    this.developer = xPath(xmlDoc, 'os:Developer/text()');
    this.attribution = xPath(xmlDoc, 'os:Attribution/text()');
    this.syndicationRight = xPath(xmlDoc, 'os:SyndicationRight/text()');
    this.adultContent = xPath(xmlDoc, 'os:AdultContent/text()');
    this.language = xPath(xmlDoc, 'os:Language/text()');
    this.outputEncoding = xPath(xmlDoc, 'os:OutputEncoding/text()');
    this.inputEncoding = xPath(xmlDoc, 'os:InputEncoding/text()');
  }

  /**
   * Get the {@link OpenSearchUrl} for the given parameters, mime type and HTTP
   * method.
   * @param {object} parameters An object containing parameters for the URL
   * @param {string} [type=null] The mime-type for the URL
   * @param {string} [method='GET'] The preferred HTTP method of the URL
   */
  getUrl(parameters, type = null, method = 'GET') {
    const urls = this.urls.filter(
      (url) => (type === null || url.type === type) && url.method === method
    ).filter(
      (url) => url.isCompatible(parameters)
    );

    return urls[0];
  }
}
<|endoftext|>


<commit_before>import { getParentSvg } from './utils.js';
import _throttle from 'lodash/throttle';
import { sumPoints, minusPoints, dividePoints, _p } from './points';

export function registerEvents () {
  const store = {};
  const svg = this._svg;

  const normalizeEvent = e => {
    if (e.x == undefined) e.x = e.clientX;
    if (e.y == undefined) e.y = e.clientY;
  };

  // DOM Events
  svg.addEventListener('mousedown', e => {
    normalizeEvent(e);
    this.lastSelected = null;
    const { target } = e;

    if (target.type === 'container') {
      this.dragging = target;
      // const { x, y } = sumPoints(e, 0);
      const { x, y } = dividePoints(e, this.zoom);
      // this._aux.mouseDown = { x, y, offset: dividePoints(this.offset, this.zoom)};
      this._aux.mouseDown = { x, y, offset: { ...this.offset } };
      return ;
    }

    if (target.type === 'wire') {
      this.lastSelected = target.wrapper;
      return this.selectedWire = target.wrapper;
    }

    if (target.type === 'port' && target.direction === 'out') {
      return this.startAttach(target);
    }

    const parentSvg = getParentSvg(target);
    const captureList = ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON'];
    const shouldCapture = tagName => !captureList.includes(tagName);
    if (shouldCapture(target.tagName) && parentSvg && parentSvg.type == 'node') {
      if (this.disableDragging)
        return true;

      const nodeNode = parentSvg;
      console.debug('Node selected:', nodeNode, 'Triggered by: ', target);
      var wrapper = nodeNode.wrapper;
      this.lastSelected = wrapper;
      this.dragging = nodeNode;
      var SVGbox = wrapper._svg.getBoundingClientRect();
      const mouse = dividePoints(e, this.zoom);
      const offset = minusPoints(mouse, [SVGbox.left, SVGbox.top]);
      this._aux.mouseDown = {
        wrapper: sumPoints(wrapper, 1),
        barePos: sumPoints(e, 1),
        mouse,
        x: offset.x - wrapper.x,
        y: offset.y - wrapper.y,
      };
      this._svg.appendChild(this.dragging);
      wrapper.wires.forEach(wire => this._svg.appendChild(wire._el));
    }

  }, false);

  document.addEventListener('keydown', e => {
    if (e.keyCode == 46) {
      console.debug('deleting', this.lastSelected);
      this.lastSelected.delete();
      // @TODO should remove from state (brick, wire, port)
    }
  }, false);

  svg.addEventListener('mouseup', e => {
    this.dragging = null;
    if(e.target.type === 'port')
      return this.endAttach(e.target);

    if(this.isState('attaching')) {
      this.setState(null)
      svg.removeChild(this._aux['wire']._el);
    }
  });

  const forceUpdate = _throttle(() => {
    if (this.react)
      this.react.forceUpdate(() => this.renderWires());
  }, 1);

  svg.addEventListener('mousemove', e => {
    normalizeEvent(e);
    const { dragging, zoom } = this;
    const mouse = e;

    if (this.isState('attaching')) {
      const { wire } = this._aux;
      const SVGbox = this._svg.getBoundingClientRect();
      // offset the wire away so we can detect the event on port
      const padding = wire._inverted ? 4 : -4;
      const vMouse = _p.add(_p.subtract(mouse, [SVGbox.left, SVGbox.top]), padding);
      const vOffset = _p.multiply(this.offset, this.zoom);
      const port = wire._cp1.getPoint(this.zoom);

      wire.renderPoints(_p.add(port, vOffset), vMouse, wire._inverted);
      return true;
    }

    if (dragging && dragging.type == 'container') {
      const firstState = this._aux.mouseDown;
      this.offset = sumPoints(firstState.offset, minusPoints(dividePoints(e, zoom), firstState));
      this.renderGrid(this.offset, zoom);
      console.debug('offset', this.offset);
      forceUpdate();
      return true;
    }

    if (dragging) {
      const wrapper = this.dragging.wrapper;
      const firstState = this._aux.mouseDown;
      const mouse = dividePoints(e, this.zoom);
      const dtMouse = minusPoints(e, firstState.barePos);
      const { x, y } = sumPoints(firstState.wrapper, _p.divide(dtMouse, zoom));
      wrapper.x = x;
      wrapper.y = y;

      forceUpdate();
      return true;
    }
  });

  const zoomVelocity = 0.05;
  let lastTime = null;
  window.addEventListener('wheel', event => {
    if (this.disableZoom && this.dragging)
      return false;

    if (lastTime === null)
      lastTime = Date.now();

    const delta = Math.sign(event.deltaY);
    const zoomDt = (zoomVelocity * delta);
    this.setZoom(_p.clamp(0.3, (this.zoom - zoomDt), 3));
    // svg.style.transform = `scale(${this.zoom})`;
    console.info('MouseWheel - zoomDt', zoomDt);
    console.info('MouseWheel - zoom', this.zoom);

    this.renderGrid(this.offset, this.zoom);
    this.forceUpdate();
    this.renderWires();

    lastTime = Date.now();
    return false;
  });

  return store;
}
<commit_msg>Fix renderGrid ordering on call stack<commit_after>import { getParentSvg } from './utils.js';
import _throttle from 'lodash/throttle';
import { sumPoints, minusPoints, dividePoints, _p } from './points';

export function registerEvents () {
  const store = {};
  const svg = this._svg;

  const normalizeEvent = e => {
    if (e.x == undefined) e.x = e.clientX;
    if (e.y == undefined) e.y = e.clientY;
  };

  // DOM Events
  svg.addEventListener('mousedown', e => {
    normalizeEvent(e);
    this.lastSelected = null;
    const { target } = e;

    if (target.type === 'container') {
      this.dragging = target;
      // const { x, y } = sumPoints(e, 0);
      const { x, y } = dividePoints(e, this.zoom);
      // this._aux.mouseDown = { x, y, offset: dividePoints(this.offset, this.zoom)};
      this._aux.mouseDown = { x, y, offset: { ...this.offset } };
      return ;
    }

    if (target.type === 'wire') {
      this.lastSelected = target.wrapper;
      return this.selectedWire = target.wrapper;
    }

    if (target.type === 'port' && target.direction === 'out') {
      return this.startAttach(target);
    }

    const parentSvg = getParentSvg(target);
    const captureList = ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON'];
    const shouldCapture = tagName => !captureList.includes(tagName);
    if (shouldCapture(target.tagName) && parentSvg && parentSvg.type == 'node') {
      if (this.disableDragging)
        return true;

      const nodeNode = parentSvg;
      console.debug('Node selected:', nodeNode, 'Triggered by: ', target);
      var wrapper = nodeNode.wrapper;
      this.lastSelected = wrapper;
      this.dragging = nodeNode;
      var SVGbox = wrapper._svg.getBoundingClientRect();
      const mouse = dividePoints(e, this.zoom);
      const offset = minusPoints(mouse, [SVGbox.left, SVGbox.top]);
      this._aux.mouseDown = {
        wrapper: sumPoints(wrapper, 1),
        barePos: sumPoints(e, 1),
        mouse,
        x: offset.x - wrapper.x,
        y: offset.y - wrapper.y,
      };
      this._svg.appendChild(this.dragging);
      wrapper.wires.forEach(wire => this._svg.appendChild(wire._el));
    }

  }, false);

  document.addEventListener('keydown', e => {
    if (e.keyCode == 46) {
      console.debug('deleting', this.lastSelected);
      this.lastSelected.delete();
      // @TODO should remove from state (brick, wire, port)
    }
  }, false);

  svg.addEventListener('mouseup', e => {
    this.dragging = null;
    if(e.target.type === 'port')
      return this.endAttach(e.target);

    if(this.isState('attaching')) {
      this.setState(null)
      svg.removeChild(this._aux['wire']._el);
    }
  });

  const forceUpdate = _throttle(() => {
    if (this.react)
      this.react.forceUpdate(() => this.renderWires());
  }, 1);

  svg.addEventListener('mousemove', e => {
    normalizeEvent(e);
    const { dragging, zoom } = this;
    const mouse = e;

    if (this.isState('attaching')) {
      const { wire } = this._aux;
      const SVGbox = this._svg.getBoundingClientRect();
      // offset the wire away so we can detect the event on port
      const padding = wire._inverted ? 4 : -4;
      const vMouse = _p.add(_p.subtract(mouse, [SVGbox.left, SVGbox.top]), padding);
      const vOffset = _p.multiply(this.offset, this.zoom);
      const port = wire._cp1.getPoint(this.zoom);

      wire.renderPoints(_p.add(port, vOffset), vMouse, wire._inverted);
      return true;
    }

    if (dragging && dragging.type == 'container') {
      const firstState = this._aux.mouseDown;
      this.offset = sumPoints(firstState.offset, minusPoints(dividePoints(e, zoom), firstState));
      console.debug('offset', this.offset);
      forceUpdate();
      this.renderGrid(this.offset, zoom);
      return true;
    }

    if (dragging) {
      const wrapper = this.dragging.wrapper;
      const firstState = this._aux.mouseDown;
      const mouse = dividePoints(e, this.zoom);
      const dtMouse = minusPoints(e, firstState.barePos);
      const { x, y } = sumPoints(firstState.wrapper, _p.divide(dtMouse, zoom));
      wrapper.x = x;
      wrapper.y = y;

      forceUpdate();
      return true;
    }
  });

  const zoomVelocity = 0.05;
  let lastTime = null;
  window.addEventListener('wheel', event => {
    if (this.disableZoom && this.dragging)
      return false;

    if (lastTime === null)
      lastTime = Date.now();

    const delta = Math.sign(event.deltaY);
    const zoomDt = (zoomVelocity * delta);
    this.setZoom(_p.clamp(0.3, (this.zoom - zoomDt), 3));
    // svg.style.transform = `scale(${this.zoom})`;
    console.info('MouseWheel - zoomDt', zoomDt);
    console.info('MouseWheel - zoom', this.zoom);

    this.renderGrid(this.offset, this.zoom);
    this.forceUpdate();
    this.renderWires();

    lastTime = Date.now();
    return false;
  });

  return store;
}
<|endoftext|>


<commit_before>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

/**
 * @class easyXDM.Url
 * Contains methods for dealing with url's
 * @singleton
 */
easyXDM.Url = {
    /**
     * A hashtable that gives access to the documents query string
     * The hashtable is cached internally
     * @returns A hashtable populated with keys and values from the querystring
     * @type {Object}
     */
    Query: function(){
        if (this._query) {
            return this._query;
        }
        this._query = {};
        var pair, key, value, search = location.search.substring(1).split("&");
        for (var i = 0, len = search.length; i < len; i++) {
            pair = search[i];
            key = pair.substring(0, pair.indexOf("="));
            value = pair.substring(key.length + 1);
            this._query[key] = value;
        }
        return this._query;
    },
    /**
     * Get the domain name from a url
     * @param {String} url The url to extract the domain from
     * @returns The domain part of the url
     * @type {String}
     */
    getDomainName: function(url){
        var domain = url.substring(url.indexOf("//") + 2);
        domain = domain.substring(0, domain.indexOf("/"));
        var _indexOf = domain.indexOf(":");
        if (_indexOf != -1) {
            domain = domain.substring(0, _indexOf);
        }
        return domain;
    },
    /**
     * Returns  a string containing the schema, domain and if present the port
     * @param {String} url The url to extract the location from
     * @return {String} The location part of the url
     */
    getLocation: function(url){
        var indexOf = url.indexOf("//");
        var loc = url.substring(indexOf + 2);
        loc = loc.substring(0, loc.indexOf("/"));
        return url.substring(0, indexOf + 2) + loc;
    },
    /**
     * Resolves a path to a complete url
     * @param {String} url The path to resolve
     * @return {String} The resolved url
     */
    resolveUrl: function(url){
        // If the url is a valid url we do nothing
        if (url.match(/^(http||https):\/\//)) {
            return url;
        }

        var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
        if (path.substring(path.length - 1) !== "/") {
            path = path.substring(0, path.lastIndexOf("/") + 1);
        }
        var resolved = location.protocol + "//" + location.host + path + url;
        // #ifdef debug
        easyXDM.Debug.trace("resolved url '" + url + ' into ' + resolved + "'");
        // #endif
        return resolved;
    },
    /**
     * Appends the parameters to the given url.

     * The base url can contain existing query parameters.
     * @param {String} url The base url
     * @param {Object} parameters The parameters to add
     */
    appendQueryParameters: function(url, parameters){
        var q = "";
        for (var key in parameters) {
            if (parameters.hasOwnProperty(key)) {
                q += key + "=" + parameters[key] + "&";
            }
        }
        return url + ((url.indexOf("?") == -1) ? "?" : "&") + q.substring(0, q.length - 1);
    }
};
<commit_msg>Fixed it so that getLocation returns the location when given an url without path instead of just 'http://'.<commit_after>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

/**
 * @class easyXDM.Url
 * Contains methods for dealing with url's
 * @singleton
 */
easyXDM.Url = {
    /**
     * A hashtable that gives access to the documents query string
     * The hashtable is cached internally
     * @returns A hashtable populated with keys and values from the querystring
     * @type {Object}
     */
    Query: function(){
        if (this._query) {
            return this._query;
        }
        this._query = {};
        var pair, key, value, search = location.search.substring(1).split("&");
        for (var i = 0, len = search.length; i < len; i++) {
            pair = search[i];
            key = pair.substring(0, pair.indexOf("="));
            value = pair.substring(key.length + 1);
            this._query[key] = value;
        }
        return this._query;
    },
    /**
     * Get the domain name from a url
     * @param {String} url The url to extract the domain from
     * @returns The domain part of the url
     * @type {String}
     */
    getDomainName: function(url){
        var domain = url.substring(url.indexOf("//") + 2);
        domain = domain.substring(0, domain.indexOf("/"));
        var _indexOf = domain.indexOf(":");
        if (_indexOf != -1) {
            domain = domain.substring(0, _indexOf);
        }
        return domain;
    },
    /**
     * Returns  a string containing the schema, domain and if present the port
     * @param {String} url The url to extract the location from
     * @return {String} The location part of the url
     */
    getLocation: function(url){
        var indexOf = url.indexOf("//");
        var loc = url.substring(indexOf + 2);
        if (loc.indexOf("/") == -1) {
            return url;
        }
        loc = loc.substring(0, loc.indexOf("/"));
        return url.substring(0, indexOf + 2) + loc;
    },
    /**
     * Resolves a path to a complete url
     * @param {String} url The path to resolve
     * @return {String} The resolved url
     */
    resolveUrl: function(url){
        // If the url is a valid url we do nothing
        if (url.match(/^(http||https):\/\//)) {
            return url;
        }

        var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
        if (path.substring(path.length - 1) !== "/") {
            path = path.substring(0, path.lastIndexOf("/") + 1);
        }
        var resolved = location.protocol + "//" + location.host + path + url;
        // #ifdef debug
        easyXDM.Debug.trace("resolved url '" + url + ' into ' + resolved + "'");
        // #endif
        return resolved;
    },
    /**
     * Appends the parameters to the given url.

     * The base url can contain existing query parameters.
     * @param {String} url The base url
     * @param {Object} parameters The parameters to add
     */
    appendQueryParameters: function(url, parameters){
        var q = "";
        for (var key in parameters) {
            if (parameters.hasOwnProperty(key)) {
                q += key + "=" + parameters[key] + "&";
            }
        }
        return url + ((url.indexOf("?") == -1) ? "?" : "&") + q.substring(0, q.length - 1);
    }
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
import serialize from '../serializers/user';

/**
 * Show myself
 *
 * @param {Object} params
 * @param {Object} reply
 * @param {Object} user
 * @param {Object} app
 * @param {Boolean} isWeb
 * @return {void}
 */
module.exports = async (params, reply, user, _, isWeb) =>
{
	// serialize
	reply(await serialize(user, {
		includePrivates: true
		includeSecrets: isWeb,
		includeProfileImageIds: isWeb
	}));
};
<commit_msg>Fix typo<commit_after>'use strict';

/**
 * Module dependencies
 */
import serialize from '../serializers/user';

/**
 * Show myself
 *
 * @param {Object} params
 * @param {Object} reply
 * @param {Object} user
 * @param {Object} app
 * @param {Boolean} isWeb
 * @return {void}
 */
module.exports = async (params, reply, user, _, isWeb) =>
{
	// serialize
	reply(await serialize(user, {
		includePrivates: true,
		includeSecrets: isWeb,
		includeProfileImageIds: isWeb
	}));
};
<|endoftext|>


<commit_before>(function(lib, undefined) {
    /*global lib*/
    "use strict";

    var event = {
        add: function(target, type, callback) {
            var _type = type.toLowerCase();
            this.initEventProperty(target, type);
            target.__events[type].callbacks[lib.guid(callback)] = callback;

            if (this.w3c) {
                target.addEventListener(type, callback, false);
            } else if (this.ie) {
                target.__events[type].handle = null;
                target.__events[type].IECallbacks = target.__events[type].IECallbacks || { keys: [], callbacks: []};
                target.__events[type].hasAttribute = false;
                target.__events[type].supported = typeof target["on" + _type] === "object" ||
                                                  typeof target["on" + _type] === "function";

                if (target.__events[type].supported) {
                    if (target["on" + _type] !== null) {
                        this.addIEAttributeEvent(target, type);
                    }

                    var _callback = lib.bind(function() {
                        var event;
                        if (typeof callback.attributeEvent === "undefined") {
                            event = fixIEEvent(lib.window.event, target);
                        } else {
                            event = fixIEEvent(lib.window.event, null);
                        }

                        return callback.apply(target, [event]);
                    }, this);
                    target.__events[type].IECallbacks.keys.push(callback.__guid);
                    target.__events[type].IECallbacks.callbacks.push(_callback);
                    target.attachEvent("on" + type, _callback);
                } else {
                    target.__events[type].handle = function(event) {
                        this.event = extendIEEventSafe(this.event, event);
                        this.event = fixIEEvent(this.event);
                        return this.callback.apply(this.event.currentTarget, [this.event]);
                    };

                    var _target = (target === lib.document) ? lib.document.documentElement : target;
                    if (typeof target.libEvent === "undefined") {
                        target.libEvent = 0;
                        if (target !== _target) {
                            _target.libEvent = 0;
                        }
                    }

                    _target.attachEvent("onpropertychange", function(event) {
                        if (event.propertyName === "libEvent") {
                            if (target.__events[type].handle.event &&
                                target === target.__events[type].handle.event.currentTarget &&
                                target.__events[type].handle.dispatched === false) {
                                target.__events[type].handle.dispatched = true;
                                return lib.bind(target.__events[type].handle, target.__events[type].handle)(event);
                            }
                        }
                    });
                }
            }
        },

        initEventProperty: function(target, type) {
            if (typeof target.__events === "undefined") {
                target.__events = {};
            }
            if (typeof target.__events[type] === "undefined") {
                target.__events[type] = {};
            }
            if (typeof target.__events[type].callbacks === "undefined") {
                target.__events[type].callbacks = {};
            }
        },

        addIEAttributeEvent: function(target, type) {
            this.initEventProperty(target, type);
            target.__events[type].hasAttribute = true;

            var _type = type.toLowerCase(),
                e = target["on" + _type];
            target["on" + _type] = null;
            e.attributeEvent = true;
            this.add(target, type, e);
        },

        remove: function(target, type, callback) {
            var i, len, t;
            if (typeof type === "undefined") {
                for (t in target.__events) {
                    if (target.__events.hasOwnProperty(t)) {
                        this.remove(target, t);
                    }
                }
            }

            if (typeof target.__events === "object" && typeof target.__events[type] === "object") {
                if (typeof callback === "function") {
                    if (this.w3c) {
                        target.removeEventListener(type, callback, false);
                    } else if (this.ie && target.__events[type].supported) {
                        var _callback,
                            iec = target.__events[type].IECallbacks,
                            guid = callback.__guid;
                        for (i = 0, len = iec.keys.length; i < len; i++) {
                            if (iec.keys[i] === guid) {
                                _callback = iec.callbacks[i];
                                iec.keys.splice(i, 0);
                                iec.callbacks.splice(i, 0);
                                break;
                            }
                        }
                        target.detachEvent("on" + type, _callback);
                    }
                    delete target.__events[type].callbacks[callback.__guid];
                } else {
                    for (i in target.__events[type].callbacks) {
                        if (target.__events[type].callbacks.hasOwnProperty(i)) {
                            this.remove(target, type, target.__events[type].callbacks[i]);
                        }
                    }
                }
            }
        },

        dispatch: function(target, type, properties) {
            if (this.w3c) {
                switch (this.events[type]) {
                    case this.types.mouse:
                        return this.dispatchMouseEvent(target, type, properties);
                    case this.types.keyboard:
                        return this.dispatchKeyboardEvent(target, type, properties);
                    case this.types.html:
                        return this.dispatchHTMLEvent(target, type, properties);
                    case this.types.dom: // not implemented
                        break;
                    case this.types.wheel: // not implemented
                        break;
                    default:
                        return this.dispatchUIEvent(target, type, properties);
                }
            } else if (this.ie) {
                return this.dispatchIEEvent(target, type, properties);
            }
        },

        dispatchMouseEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    detail: 1,
                    screenX: 0,
                    screenY: 0,
                    clientX: 0,
                    clientY: 0,
                    ctrlKey: false,
                    altKey: false,
                    shiftKey: false,
                    metaKey: false,
                    button: 0,
                    relatedTarget: null
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(type, eventProperties.bubbles, eventProperties.cancelable, lib.window,
                eventProperties.detail, eventProperties.screenX, eventProperties.screenY, eventProperties.clientX,
                eventProperties.clientY, eventProperties.ctrlKey, eventProperties.altKey, eventProperties.shiftKey,
                eventProperties.metaKey, eventProperties.button, eventProperties.relatedTarget);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchKeyboardEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    ctrlKey: false,
                    altKey: false,
                    shiftKey: false,
                    metaKey: false,
                    keyCode: 9,
                    charCode: 0
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("KeyboardEvent");
            if (typeof event.initKeyboardEvent === "undefined" && event.initKeyEvent) {
                event.initKeyboardEvent = event.initKeyEvent;
            }

            event.initKeyboardEvent(type, eventProperties.bubbles, eventProperties.cancelable, lib.window,
                eventProperties.ctrlKey, eventProperties.altKey, eventProperties.shiftKey, eventProperties.metaKey,
                eventProperties.keyCode, eventProperties.charCode);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchHTMLEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("HTMLEvents");
            event.initEvent(type, eventProperties.bubbles, eventProperties.cancelable);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchUIEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    detail: null
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("UIEvents");
            event.initUIEvent(type, eventProperties.bubbles,
                              eventProperties.cancelable,
                              lib.window,
                              eventProperties.detail);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchIEEvent: function(target, type, properties) {
            var event, _type = type.toLowerCase();
            if (typeof target.__events === "undefined") {
                if (typeof target["on" + _type] === "object" || typeof target["on" + _type] === "function") {
                    this.addIEAttributeEvent(target, type);
                } else {
                    return;
                }
            }

            if (typeof target.__events[type] === "undefined") {
                return;
            }

            properties = properties || {};
            if (target.__events[type].supported) {
                event = document.createEventObject();
                lib.extend(event, properties);
                return target.fireEvent("on" + type, event);
            } else {
                event = lib.extend(properties, {
                    target: target,
                    type: type,
                    currentTarget: target
                });

                while (target) {
                    if (target.__events && target.__events[type]) {
                        for (var i in target.__events[type].callbacks) {
                            if (typeof properties.safe === "boolean" && properties.safe === true) {
                                target.__events[type].handle.callback = target.__events[type].callbacks[i];
                                target.__events[type].handle.event = event;
                                target.__events[type].handle.dispatched = false;

                                if (event.currentTarget === document) {
                                    document.documentElement.libEvent++;
                                } else {
                                    event.currentTarget.libEvent++;
                                }
                            } else {

                                if (target.__events[type].callbacks[i].call(
                                        target, fixIEEvent(event, target)) === false) {
                                    event.preventDefault();
                                    event.stopPropagation();
                                }
                            }
                        }
                    }
                    target = event.currentTarget = (!event.cancelBubble && target.parentNode);
                }
                return (event.returnValue !== false);
            }
        },

        w3c: (document.addEventListener) ? true : false,
        ie: (document.attachEvent && !document.addEventListener) ? true : false,

        types: {
            mouse: 1,
            keyboard: 2,
            html: 3,
            dom: 4,
            wheel: 5
        }
    };

    event.events = {
        click: event.types.mouse,
        dblclick: event.types.mouse,
        mousedown: event.types.mouse,
        mouseenter: event.types.mouse,
        mouseleave: event.types.mouse,
        mouseup: event.types.mouse,
        mouseover: event.types.mouse,
        mousemove: event.types.mouse,
        mouseout: event.types.mouse,
        keypress: event.types.keyboard,
        keydown: event.types.keyboard,
        keyup: event.types.keyboard,
        load: event.types.html,
        unload: event.types.html,
        abort: event.types.html,
        error: event.types.html,
        resize: event.types.html,
        scroll: event.types.html,
        select: event.types.html,
        change: event.types.html,
        submit: event.types.html,
        reset: event.types.html,
        focus: event.types.html,
        blur: event.types.html,
        DOMFocusIn: event.types.dom,
        DOMFocusOut: event.types.dom,
        DOMActivate: event.types.dom,
        DOMSubtreeModified: event.types.dom,
        DOMNodeInserted: event.types.dom,
        DOMNodeRemoved: event.types.dom,
        DOMNodeRemovedFromDocument: event.types.dom,
        DOMNodeInsertedIntoDocument: event.types.dom,
        DOMAttrModified: event.types.dom,
        DOMCharacterDataModified: event.types.dom,
        mousewheel: event.types.wheel,
        DOMMouseScroll: event.types.wheel
    };

    function fixIEEvent(event) {
        event.target = event.target || event.srcElement;
        event.currentTarget = (arguments[1] && arguments[1].nodeName) ? arguments[1] :
                                  (arguments[1] === null) ? null : event.currentTarget;

        if (arguments[1] && arguments[1].nodeName && event.toElement && event.toElement.nodeName) {
            event.relatedTarget = (event.toElement === event.target) ? event.fromElement : event.toElement;
        }

        event.preventDefault = function() {
            event.returnValue = false;
        };

        event.stopPropagation = function() {
            event.cancelBubble = true;
        };

        return event;
    }

    function extendIEEventSafe(target) {
        var props = ["altKey", "attrChange", "attrName", "bubbles", "button", "cancelable", "charCode",
                    "clientX", "clientY", "ctrlKey", "currentTarget", "data", "detail", "eventPhase",
                    "fromElement", "handler", "keyCode", "layerX", "layerY", "metaKey", "newValue",
                    "offsetX", "offsetY", "originalTarget", "pageX", "pageY", "prevValue", "relatedNode",
                    "relatedTarget", "screenX", "screenY", "shiftKey", "srcElement", "target", "toElement",
                    "view", "wheelDelta", "which"];
        for (var i, k = 0; ++k < arguments.length;) {
            for (i in props) {
                if (typeof arguments[k][props[i]] !== "undefined") {
                    target[props[i]] = arguments[k][props[i]];
                }
            }
        }

        target.originalEvent = arguments[1];
        return target;
    }

    lib.event = {
        add: lib.bind(event.add, event),
        remove: lib.bind(event.remove, event),
        dispatch: lib.bind(event.dispatch, event)
    };
})(lib);
<commit_msg>shorthand to prevent default<commit_after>(function(lib, undefined) {
    /*global lib*/
    "use strict";

    var event = {
        add: function(target, type, callback) {
            var _type = type.toLowerCase();
            this.initEventProperty(target, type);
            target.__events[type].callbacks[lib.guid(callback)] = callback;

            if (this.w3c) {
                target.addEventListener(type, callback, false);
            } else if (this.ie) {
                target.__events[type].handle = null;
                target.__events[type].IECallbacks = target.__events[type].IECallbacks || { keys: [], callbacks: []};
                target.__events[type].hasAttribute = false;
                target.__events[type].supported = typeof target["on" + _type] === "object" ||
                                                  typeof target["on" + _type] === "function";

                if (target.__events[type].supported) {
                    if (target["on" + _type] !== null) {
                        this.addIEAttributeEvent(target, type);
                    }

                    var _callback = lib.bind(function() {
                        var event;
                        if (typeof callback.attributeEvent === "undefined") {
                            event = fixIEEvent(lib.window.event, target);
                        } else {
                            event = fixIEEvent(lib.window.event, null);
                        }

                        return callback.apply(target, [event]);
                    }, this);
                    target.__events[type].IECallbacks.keys.push(callback.__guid);
                    target.__events[type].IECallbacks.callbacks.push(_callback);
                    target.attachEvent("on" + type, _callback);
                } else {
                    target.__events[type].handle = function(event) {
                        this.event = extendIEEventSafe(this.event, event);
                        this.event = fixIEEvent(this.event);
                        return this.callback.apply(this.event.currentTarget, [this.event]);
                    };

                    var _target = (target === lib.document) ? lib.document.documentElement : target;
                    if (typeof target.libEvent === "undefined") {
                        target.libEvent = 0;
                        if (target !== _target) {
                            _target.libEvent = 0;
                        }
                    }

                    _target.attachEvent("onpropertychange", function(event) {
                        if (event.propertyName === "libEvent") {
                            if (target.__events[type].handle.event &&
                                target === target.__events[type].handle.event.currentTarget &&
                                target.__events[type].handle.dispatched === false) {
                                target.__events[type].handle.dispatched = true;
                                return lib.bind(target.__events[type].handle, target.__events[type].handle)(event);
                            }
                        }
                    });
                }
            }
        },

        initEventProperty: function(target, type) {
            if (typeof target.__events === "undefined") {
                target.__events = {};
            }
            if (typeof target.__events[type] === "undefined") {
                target.__events[type] = {};
            }
            if (typeof target.__events[type].callbacks === "undefined") {
                target.__events[type].callbacks = {};
            }
        },

        addIEAttributeEvent: function(target, type) {
            this.initEventProperty(target, type);
            target.__events[type].hasAttribute = true;

            var _type = type.toLowerCase(),
                e = target["on" + _type];
            target["on" + _type] = null;
            e.attributeEvent = true;
            this.add(target, type, e);
        },

        remove: function(target, type, callback) {
            var i, len, t;
            if (typeof type === "undefined") {
                for (t in target.__events) {
                    if (target.__events.hasOwnProperty(t)) {
                        this.remove(target, t);
                    }
                }
            }

            if (typeof target.__events === "object" && typeof target.__events[type] === "object") {
                if (typeof callback === "function") {
                    if (this.w3c) {
                        target.removeEventListener(type, callback, false);
                    } else if (this.ie && target.__events[type].supported) {
                        var _callback,
                            iec = target.__events[type].IECallbacks,
                            guid = callback.__guid;
                        for (i = 0, len = iec.keys.length; i < len; i++) {
                            if (iec.keys[i] === guid) {
                                _callback = iec.callbacks[i];
                                iec.keys.splice(i, 0);
                                iec.callbacks.splice(i, 0);
                                break;
                            }
                        }
                        target.detachEvent("on" + type, _callback);
                    }
                    delete target.__events[type].callbacks[callback.__guid];
                } else {
                    for (i in target.__events[type].callbacks) {
                        if (target.__events[type].callbacks.hasOwnProperty(i)) {
                            this.remove(target, type, target.__events[type].callbacks[i]);
                        }
                    }
                }
            }
        },

        dispatch: function(target, type, properties) {
            if (this.w3c) {
                switch (this.events[type]) {
                    case this.types.mouse:
                        return this.dispatchMouseEvent(target, type, properties);
                    case this.types.keyboard:
                        return this.dispatchKeyboardEvent(target, type, properties);
                    case this.types.html:
                        return this.dispatchHTMLEvent(target, type, properties);
                    case this.types.dom: // not implemented
                        break;
                    case this.types.wheel: // not implemented
                        break;
                    default:
                        return this.dispatchUIEvent(target, type, properties);
                }
            } else if (this.ie) {
                return this.dispatchIEEvent(target, type, properties);
            }
        },

        dispatchMouseEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    detail: 1,
                    screenX: 0,
                    screenY: 0,
                    clientX: 0,
                    clientY: 0,
                    ctrlKey: false,
                    altKey: false,
                    shiftKey: false,
                    metaKey: false,
                    button: 0,
                    relatedTarget: null
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(type, eventProperties.bubbles, eventProperties.cancelable, lib.window,
                eventProperties.detail, eventProperties.screenX, eventProperties.screenY, eventProperties.clientX,
                eventProperties.clientY, eventProperties.ctrlKey, eventProperties.altKey, eventProperties.shiftKey,
                eventProperties.metaKey, eventProperties.button, eventProperties.relatedTarget);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchKeyboardEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    ctrlKey: false,
                    altKey: false,
                    shiftKey: false,
                    metaKey: false,
                    keyCode: 9,
                    charCode: 0
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("KeyboardEvent");
            if (typeof event.initKeyboardEvent === "undefined" && event.initKeyEvent) {
                event.initKeyboardEvent = event.initKeyEvent;
            }

            event.initKeyboardEvent(type, eventProperties.bubbles, eventProperties.cancelable, lib.window,
                eventProperties.ctrlKey, eventProperties.altKey, eventProperties.shiftKey, eventProperties.metaKey,
                eventProperties.keyCode, eventProperties.charCode);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchHTMLEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("HTMLEvents");
            event.initEvent(type, eventProperties.bubbles, eventProperties.cancelable);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchUIEvent: function(target, type, properties) {
            properties = (typeof properties !== "undefined") ? properties : {};
            var eventProperties = {
                    bubbles: true,
                    cancelable: true,
                    detail: null
                },
                customProperties = lib.object.subtract(properties, eventProperties);
            lib.extend(eventProperties, properties || {});

            var event = document.createEvent("UIEvents");
            event.initUIEvent(type, eventProperties.bubbles,
                              eventProperties.cancelable,
                              lib.window,
                              eventProperties.detail);
            lib.extend(event, customProperties);
            return target.dispatchEvent(event);
        },

        dispatchIEEvent: function(target, type, properties) {
            var event, _type = type.toLowerCase();
            if (typeof target.__events === "undefined") {
                if (typeof target["on" + _type] === "object" || typeof target["on" + _type] === "function") {
                    this.addIEAttributeEvent(target, type);
                } else {
                    return;
                }
            }

            if (typeof target.__events[type] === "undefined") {
                return;
            }

            properties = properties || {};
            if (target.__events[type].supported) {
                event = document.createEventObject();
                lib.extend(event, properties);
                return target.fireEvent("on" + type, event);
            } else {
                event = lib.extend(properties, {
                    target: target,
                    type: type,
                    currentTarget: target
                });

                while (target) {
                    if (target.__events && target.__events[type]) {
                        for (var i in target.__events[type].callbacks) {
                            if (typeof properties.safe === "boolean" && properties.safe === true) {
                                target.__events[type].handle.callback = target.__events[type].callbacks[i];
                                target.__events[type].handle.event = event;
                                target.__events[type].handle.dispatched = false;

                                if (event.currentTarget === document) {
                                    document.documentElement.libEvent++;
                                } else {
                                    event.currentTarget.libEvent++;
                                }
                            } else {

                                if (target.__events[type].callbacks[i].call(
                                        target, fixIEEvent(event, target)) === false) {
                                    event.preventDefault();
                                    event.stopPropagation();
                                }
                            }
                        }
                    }
                    target = event.currentTarget = (!event.cancelBubble && target.parentNode);
                }
                return (event.returnValue !== false);
            }
        },

        preventDefault: function preventDefault(event) {
            return event.preventDefault();
        },

        w3c: (document.addEventListener) ? true : false,
        ie: (document.attachEvent && !document.addEventListener) ? true : false,

        types: {
            mouse: 1,
            keyboard: 2,
            html: 3,
            dom: 4,
            wheel: 5
        }
    };

    event.events = {
        click: event.types.mouse,
        dblclick: event.types.mouse,
        mousedown: event.types.mouse,
        mouseenter: event.types.mouse,
        mouseleave: event.types.mouse,
        mouseup: event.types.mouse,
        mouseover: event.types.mouse,
        mousemove: event.types.mouse,
        mouseout: event.types.mouse,
        keypress: event.types.keyboard,
        keydown: event.types.keyboard,
        keyup: event.types.keyboard,
        load: event.types.html,
        unload: event.types.html,
        abort: event.types.html,
        error: event.types.html,
        resize: event.types.html,
        scroll: event.types.html,
        select: event.types.html,
        change: event.types.html,
        submit: event.types.html,
        reset: event.types.html,
        focus: event.types.html,
        blur: event.types.html,
        DOMFocusIn: event.types.dom,
        DOMFocusOut: event.types.dom,
        DOMActivate: event.types.dom,
        DOMSubtreeModified: event.types.dom,
        DOMNodeInserted: event.types.dom,
        DOMNodeRemoved: event.types.dom,
        DOMNodeRemovedFromDocument: event.types.dom,
        DOMNodeInsertedIntoDocument: event.types.dom,
        DOMAttrModified: event.types.dom,
        DOMCharacterDataModified: event.types.dom,
        mousewheel: event.types.wheel,
        DOMMouseScroll: event.types.wheel
    };

    function fixIEEvent(event) {
        event.target = event.target || event.srcElement;
        event.currentTarget = (arguments[1] && arguments[1].nodeName) ? arguments[1] :
                                  (arguments[1] === null) ? null : event.currentTarget;

        if (arguments[1] && arguments[1].nodeName && event.toElement && event.toElement.nodeName) {
            event.relatedTarget = (event.toElement === event.target) ? event.fromElement : event.toElement;
        }

        event.preventDefault = function() {
            event.returnValue = false;
        };

        event.stopPropagation = function() {
            event.cancelBubble = true;
        };

        return event;
    }

    function extendIEEventSafe(target) {
        var props = ["altKey", "attrChange", "attrName", "bubbles", "button", "cancelable", "charCode",
                    "clientX", "clientY", "ctrlKey", "currentTarget", "data", "detail", "eventPhase",
                    "fromElement", "handler", "keyCode", "layerX", "layerY", "metaKey", "newValue",
                    "offsetX", "offsetY", "originalTarget", "pageX", "pageY", "prevValue", "relatedNode",
                    "relatedTarget", "screenX", "screenY", "shiftKey", "srcElement", "target", "toElement",
                    "view", "wheelDelta", "which"];
        for (var i, k = 0; ++k < arguments.length;) {
            for (i in props) {
                if (typeof arguments[k][props[i]] !== "undefined") {
                    target[props[i]] = arguments[k][props[i]];
                }
            }
        }

        target.originalEvent = arguments[1];
        return target;
    }

    lib.event = {
        add: lib.bind(event.add, event),
        remove: lib.bind(event.remove, event),
        dispatch: lib.bind(event.dispatch, event),
        preventDefault: lib.bind(event.preventDefault, event)
    };
})(lib);
<|endoftext|>


<commit_before>"use strict";

import "babel/polyfill";

export default function(grunt) {
  grunt.registerTask('db:version', 'Show the current migration version', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.version().then(function(version) {
        grunt.log.oklns("Migrate version: " + version);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:rollback', 'Rollback the database', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.version().then(function(oldVersion) {
        return api.bookshelf.utils.db.rollback().then(function() {
          return api.bookshelf.utils.db.version().then(function(newVersion) {
            grunt.log.oklns(oldVersion + " to " + newVersion);
            return done();
          });
        });
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate:make', 'Make migrate file (:name)', function(name) {
    var done;
    done = this.async();
    if (name == null) {
      return done(new Error("The file name is required.\nExample: grunt db:migrate:make:create_users"));
    }
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.migrate.make(name).then(function(name) {
        grunt.log.oklns("Make " + name);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate', 'Migrate the database', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.migrate.run().then(function() {
        grunt.log.oklns("Migrate database " + api.config.bookshelf.connection.database + ".");
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:seed:make', 'Make seed file (:name)', function(name) {
    var done;
    done = this.async();
    if (name == null) {
      return done(new Error("The file name is required.\nExample: grunt db:seed:make:countries"));
    }
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.seed.make(name).then(function(name) {
        grunt.log.oklns("Make " + name);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:seed', 'Create the seed data', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.seed.run().then(function() {
        grunt.log.oklns("Seed database " + api.config.bookshelf.connection.database + ".");
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:create', 'Create the database', function() {
    var done, ok;
    done = this.async();
    return grunt.startActionhero(function(api) {
      var ok = "Create database " + api.config.bookshelf.connection.database + ".";
      return api.bookshelf.utils.db.create().then(function() {
        grunt.log.oklns(ok);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:drop', 'Drop the database', function() {
    var done, ok;
    done = this.async();
    return grunt.startActionhero(function(api) {
      ok = "Drop database " + api.config.bookshelf.connection.database + ".";
      return api.bookshelf.utils.db.create().then(function() {
        grunt.log.oklns(ok);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate:reset', 'Runs db:drop db:create db:migrate', ['db:drop', 'db:create', 'db:migrate']);
  grunt.registerTask('db:reset', 'Runs db:migrate:reset db:seed', ['db:migrate:reset', 'db:seed']);

  return true;
};
<commit_msg>(fix) typo<commit_after>"use strict";

import "babel/polyfill";

export default function(grunt) {
  grunt.registerTask('db:version', 'Show the current migration version', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.version().then(function(version) {
        grunt.log.oklns("Migrate version: " + version);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:rollback', 'Rollback the database', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.version().then(function(oldVersion) {
        return api.bookshelf.utils.db.rollback().then(function() {
          return api.bookshelf.utils.db.version().then(function(newVersion) {
            grunt.log.oklns(oldVersion + " to " + newVersion);
            return done();
          });
        });
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate:make', 'Make migrate file (:name)', function(name) {
    var done;
    done = this.async();
    if (name == null) {
      return done(new Error("The file name is required.\nExample: grunt db:migrate:make:create_users"));
    }
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.migrate.make(name).then(function(name) {
        grunt.log.oklns("Make " + name);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate', 'Migrate the database', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.migrate.run().then(function() {
        grunt.log.oklns("Migrate database " + api.config.bookshelf.connection.database + ".");
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:seed:make', 'Make seed file (:name)', function(name) {
    var done;
    done = this.async();
    if (name == null) {
      return done(new Error("The file name is required.\nExample: grunt db:seed:make:countries"));
    }
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.seed.make(name).then(function(name) {
        grunt.log.oklns("Make " + name);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:seed', 'Create the seed data', function() {
    var done;
    done = this.async();
    return grunt.startActionhero(function(api) {
      return api.bookshelf.utils.db.seed.run().then(function() {
        grunt.log.oklns("Seed database " + api.config.bookshelf.connection.database + ".");
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:create', 'Create the database', function() {
    var done, ok;
    done = this.async();
    return grunt.startActionhero(function(api) {
      var ok = "Create database " + api.config.bookshelf.connection.database + ".";
      return api.bookshelf.utils.db.create().then(function() {
        grunt.log.oklns(ok);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:drop', 'Drop the database', function() {
    var done, ok;
    done = this.async();
    return grunt.startActionhero(function(api) {
      ok = "Drop database " + api.config.bookshelf.connection.database + ".";
      return api.bookshelf.utils.db.drop().then(function() {
        grunt.log.oklns(ok);
        return done();
      }).catch(function(err) {
        return done(err);
      });
    });
  });

  grunt.registerTask('db:migrate:reset', 'Runs db:drop db:create db:migrate', ['db:drop', 'db:create', 'db:migrate']);
  grunt.registerTask('db:reset', 'Runs db:migrate:reset db:seed', ['db:migrate:reset', 'db:seed']);

  return true;
};
<|endoftext|>