<commit_before>/**
* The `Matter.Composite` module contains methods for creating and manipulating composite bodies.
* A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure.
* It is important to use the functions in this module to modify composites, rather than directly modifying their properties.
* Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`.
*
* 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 Composite
*/

// TODO: composite translate, rotate

var Composite = {};

(function() {

    /**
     * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults.
     * See the properites section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {} [options]
     * @return {composite} A new composite
     */
    Composite.create = function(options) {
        return Common.extend({
            id: Common.nextId(),
            type: 'composite',
            parent: null,
            isModified: false,
            bodies: [],
            constraints: [],
            composites: [],
            label: 'Composite'
        }, options);
    };

    /**
     * Sets the composite's `isModified` flag.
     * If `updateParents` is true, all parents will be set (default: false).
     * If `updateChildren` is true, all children will be set (default: false).
     * @method setModified
     * @param {composite} composite
     * @param {boolean} isModified
     * @param {boolean} [updateParents=false]
     * @param {boolean} [updateChildren=false]
     */
    Composite.setModified = function(composite, isModified, updateParents, updateChildren) {
        composite.isModified = isModified;

        if (updateParents && composite.parent) {
            Composite.setModified(composite.parent, isModified, updateParents, updateChildren);
        }

        if (updateChildren) {
            for(var i = 0; i < composite.composites.length; i++) {
                var childComposite = composite.composites[i];
                Composite.setModified(childComposite, isModified, updateParents, updateChildren);
            }
        }
    };

    /**
     * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite.
     * @method add
     * @param {composite} composite
     * @param {} object
     * @return {composite} The original composite with the objects added
     */
    Composite.add = function(composite, object) {
        var objects = [].concat(object);

        for (var i = 0; i < objects.length; i++) {
            var obj = objects[i];

            switch (obj.type) {

            case 'body':
                Composite.addBody(composite, obj);
                break;
            case 'constraint':
                Composite.addConstraint(composite, obj);
                break;
            case 'composite':
                Composite.addComposite(composite, obj);
                break;
            case 'mouseConstraint':
                Composite.addConstraint(composite, obj.constraint);
                break;

            }
        }

        return composite;
    };

    /**
     * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite.
     * Optionally searching its children recursively.
     * @method remove
     * @param {composite} composite
     * @param {} object
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the objects removed
     */
    Composite.remove = function(composite, object, deep) {
        var objects = [].concat(object);

        for (var i = 0; i < objects.length; i++) {
            var obj = objects[i];

            switch (obj.type) {

            case 'body':
                Composite.removeBody(composite, obj, deep);
                break;
            case 'constraint':
                Composite.removeConstraint(composite, obj, deep);
                break;
            case 'composite':
                Composite.removeComposite(composite, obj, deep);
                break;
            case 'mouseConstraint':
                Composite.removeConstraint(composite, obj.constraint);
                break;

            }
        }

        return composite;
    };

    /**
     * Adds a composite to the given composite
     * @private
     * @method addComposite
     * @param {composite} compositeA
     * @param {composite} compositeB
     * @return {composite} The original compositeA with the objects from compositeB added
     */
    Composite.addComposite = function(compositeA, compositeB) {
        compositeA.composites.push(compositeB);
        compositeB.parent = compositeA;
        Composite.setModified(compositeA, true, true, false);
        return compositeA;
    };

    /**
     * Removes a composite from the given composite, and optionally searching its children recursively
     * @private
     * @method removeComposite
     * @param {composite} compositeA
     * @param {composite} compositeB
     * @param {boolean} [deep=false]
     * @return {composite} The original compositeA with the composite removed
     */
    Composite.removeComposite = function(compositeA, compositeB, deep) {
        var position = compositeA.composites.indexOf(compositeB);
        if (position !== -1) {
            Composite.removeCompositeAt(compositeA, position);
            Composite.setModified(compositeA, true, true, false);
        }

        if (deep) {
            for (var i = 0; i < compositeA.composites.length; i++){
                Composite.removeComposite(compositeA.composites[i], compositeB, true);
            }
        }

        return compositeA;
    };

    /**
     * Removes a composite from the given composite
     * @private
     * @method removeCompositeAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the composite removed
     */
    Composite.removeCompositeAt = function(composite, position) {
        composite.composites.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Adds a body to the given composite
     * @private
     * @method addBody
     * @param {composite} composite
     * @param {body} body
     * @return {composite} The original composite with the body added
     */
    Composite.addBody = function(composite, body) {
        composite.bodies.push(body);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes a body from the given composite, and optionally searching its children recursively
     * @private
     * @method removeBody
     * @param {composite} composite
     * @param {body} body
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the body removed
     */
    Composite.removeBody = function(composite, body, deep) {
        var position = composite.bodies.indexOf(body);
        if (position !== -1) {
            Composite.removeBodyAt(composite, position);
            Composite.setModified(composite, true, true, false);
        }

        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.removeBody(composite.composites[i], body, true);
            }
        }

        return composite;
    };

    /**
     * Removes a body from the given composite
     * @private
     * @method removeBodyAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the body removed
     */
    Composite.removeBodyAt = function(composite, position) {
        composite.bodies.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Adds a constraint to the given composite
     * @private
     * @method addConstraint
     * @param {composite} composite
     * @param {constraint} constraint
     * @return {composite} The original composite with the constraint added
     */
    Composite.addConstraint = function(composite, constraint) {
        composite.constraints.push(constraint);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes a constraint from the given composite, and optionally searching its children recursively
     * @private
     * @method removeConstraint
     * @param {composite} composite
     * @param {constraint} constraint
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the constraint removed
     */
    Composite.removeConstraint = function(composite, constraint, deep) {
        var position = composite.constraints.indexOf(constraint);
        if (position !== -1) {
            Composite.removeConstraintAt(composite, position);
        }

        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.removeConstraint(composite.composites[i], constraint, true);
            }
        }

        return composite;
    };

    /**
     * Removes a body from the given composite
     * @private
     * @method removeConstraintAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the constraint removed
     */
    Composite.removeConstraintAt = function(composite, position) {
        composite.constraints.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes all bodies, constraints and composites from the given composite
     * Optionally clearing its children recursively
     * @method clear
     * @param {world} world
     * @param {boolean} keepStatic
     * @param {boolean} [deep=false]
     */
    Composite.clear = function(composite, keepStatic, deep) {
        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.clear(composite.composites[i], keepStatic, true);
            }
        }

        if (keepStatic) {
            composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; });
        } else {
            composite.bodies.length = 0;
        }

        composite.constraints.length = 0;
        composite.composites.length = 0;
        Composite.setModified(composite, true, true, false);

        return composite;
    };

    /**
     * Returns all bodies in the given composite, including all bodies in its children, recursively
     * @method allBodies
     * @param {composite} composite
     * @return {body[]} All the bodies
     */
    Composite.allBodies = function(composite) {
        var bodies = [].concat(composite.bodies);

        for (var i = 0; i < composite.composites.length; i++)
            bodies = bodies.concat(Composite.allBodies(composite.composites[i]));

        return bodies;
    };

    /**
     * Returns all constraints in the given composite, including all constraints in its children, recursively
     * @method allConstraints
     * @param {composite} composite
     * @return {constraint[]} All the constraints
     */
    Composite.allConstraints = function(composite) {
        var constraints = [].concat(composite.constraints);

        for (var i = 0; i < composite.composites.length; i++)
            constraints = constraints.concat(Composite.allConstraints(composite.composites[i]));

        return constraints;
    };

    /**
     * Returns all composites in the given composite, including all composites in its children, recursively
     * @method allComposites
     * @param {composite} composite
     * @return {composite[]} All the composites
     */
    Composite.allComposites = function(composite) {
        var composites = [].concat(composite.composites);

        for (var i = 0; i < composite.composites.length; i++)
            composites = composites.concat(Composite.allComposites(composite.composites[i]));

        return composites;
    };

    /**
     * Searches the composite recursively for an object matching the type and id supplied, null if not found
     * @method get
     * @param {composite} composite
     * @param {number} id
     * @param {string} type
     * @return {object} The requested object, if found
     */
    Composite.get = function(composite, id, type) {
        var objects,
            object;

        switch (type) {
        case 'body':
            objects = Composite.allBodies(composite);
            break;
        case 'constraint':
            objects = Composite.allConstraints(composite);
            break;
        case 'composite':
            objects = Composite.allComposites(composite).concat(composite);
            break;
        }

        if (!objects)
            return null;

        object = objects.filter(function(object) {
            return object.id.toString() === id.toString();
        });

        return object.length === 0 ? null : object[0];
    };

    /**
     * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add)
     * @method move
     * @param {compositeA} compositeA
     * @param {object[]} objects
     * @param {compositeB} compositeB
     * @return {composite} Returns compositeA
     */
    Composite.move = function(compositeA, objects, compositeB) {
        Composite.remove(compositeA, objects);
        Composite.add(compositeB, objects);
        return compositeA;
    };

    /**
     * Assigns new ids for all objects in the composite, recursively
     * @method rebase
     * @param {composite} composite
     * @return {composite} Returns composite
     */
    Composite.rebase = function(composite) {
        var objects = Composite.allBodies(composite)
                        .concat(Composite.allConstraints(composite))
                        .concat(Composite.allComposites(composite));

        for (var i = 0; i < objects.length; i++) {
            objects[i].id = Common.nextId();
        }

        Composite.setModified(composite, true, true, false);

        return composite;
    };

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
     *
     * @property id
     * @type number
     */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "composite"
     */

    /**
     * An arbitrary `String` name to help the user identify and manage composites.
     *
     * @property label
     * @type string
     * @default "Composite"
     */

    /**
     * A flag that specifies whether the composite has been modified during the current step.
     * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled.
     * If you need to change it manually, you should use the `Composite.setModified` method.
     *
     * @property isModified
     * @type boolean
     * @default false
     */

    /**
     * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods.
     *
     * @property parent
     * @type composite
     * @default null
     */

    /**
     * An array of `Body` that are _direct_ children of this composite.
     * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method.
     *
     * @property bodies
     * @type body[]
     * @default []
     */

    /**
     * An array of `Constraint` that are _direct_ children of this composite.
     * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method.
     *
     * @property constraints
     * @type constraint[]
     * @default []
     */

    /**
     * An array of `Composite` that are _direct_ children of this composite.
     * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method.
     *
     * @property composites
     * @type composite[]
     * @default []
     */

})();<commit_msg>added composite events<commit_after>/**
* The `Matter.Composite` module contains methods for creating and manipulating composite bodies.
* A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure.
* It is important to use the functions in this module to modify composites, rather than directly modifying their properties.
* Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`.
*
* 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 Composite
*/

// TODO: composite translate, rotate

var Composite = {};

(function() {

    /**
     * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults.
     * See the properites section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {} [options]
     * @return {composite} A new composite
     */
    Composite.create = function(options) {
        return Common.extend({
            id: Common.nextId(),
            type: 'composite',
            parent: null,
            isModified: false,
            bodies: [],
            constraints: [],
            composites: [],
            label: 'Composite'
        }, options);
    };

    /**
     * Sets the composite's `isModified` flag.
     * If `updateParents` is true, all parents will be set (default: false).
     * If `updateChildren` is true, all children will be set (default: false).
     * @method setModified
     * @param {composite} composite
     * @param {boolean} isModified
     * @param {boolean} [updateParents=false]
     * @param {boolean} [updateChildren=false]
     */
    Composite.setModified = function(composite, isModified, updateParents, updateChildren) {
        composite.isModified = isModified;

        if (updateParents && composite.parent) {
            Composite.setModified(composite.parent, isModified, updateParents, updateChildren);
        }

        if (updateChildren) {
            for(var i = 0; i < composite.composites.length; i++) {
                var childComposite = composite.composites[i];
                Composite.setModified(childComposite, isModified, updateParents, updateChildren);
            }
        }
    };

    /**
     * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite.
     * Triggers `beforeAdd` and `afterAdd` events on the `composite`.
     * @method add
     * @param {composite} composite
     * @param {} object
     * @return {composite} The original composite with the objects added
     */
    Composite.add = function(composite, object) {
        var objects = [].concat(object);

        Events.trigger(composite, 'beforeAdd', { object: object });

        for (var i = 0; i < objects.length; i++) {
            var obj = objects[i];

            switch (obj.type) {

            case 'body':
                Composite.addBody(composite, obj);
                break;
            case 'constraint':
                Composite.addConstraint(composite, obj);
                break;
            case 'composite':
                Composite.addComposite(composite, obj);
                break;
            case 'mouseConstraint':
                Composite.addConstraint(composite, obj.constraint);
                break;

            }
        }

        Events.trigger(composite, 'afterAdd', { object: object });

        return composite;
    };

    /**
     * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite.
     * Optionally searching its children recursively.
     * Triggers `beforeRemove` and `afterRemove` events on the `composite`.
     * @method remove
     * @param {composite} composite
     * @param {} object
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the objects removed
     */
    Composite.remove = function(composite, object, deep) {
        var objects = [].concat(object);

        Events.trigger(composite, 'beforeRemove', { object: object });

        for (var i = 0; i < objects.length; i++) {
            var obj = objects[i];

            switch (obj.type) {

            case 'body':
                Composite.removeBody(composite, obj, deep);
                break;
            case 'constraint':
                Composite.removeConstraint(composite, obj, deep);
                break;
            case 'composite':
                Composite.removeComposite(composite, obj, deep);
                break;
            case 'mouseConstraint':
                Composite.removeConstraint(composite, obj.constraint);
                break;

            }
        }

        Events.trigger(composite, 'afterRemove', { object: object });

        return composite;
    };

    /**
     * Adds a composite to the given composite
     * @private
     * @method addComposite
     * @param {composite} compositeA
     * @param {composite} compositeB
     * @return {composite} The original compositeA with the objects from compositeB added
     */
    Composite.addComposite = function(compositeA, compositeB) {
        compositeA.composites.push(compositeB);
        compositeB.parent = compositeA;
        Composite.setModified(compositeA, true, true, false);
        return compositeA;
    };

    /**
     * Removes a composite from the given composite, and optionally searching its children recursively
     * @private
     * @method removeComposite
     * @param {composite} compositeA
     * @param {composite} compositeB
     * @param {boolean} [deep=false]
     * @return {composite} The original compositeA with the composite removed
     */
    Composite.removeComposite = function(compositeA, compositeB, deep) {
        var position = compositeA.composites.indexOf(compositeB);
        if (position !== -1) {
            Composite.removeCompositeAt(compositeA, position);
            Composite.setModified(compositeA, true, true, false);
        }

        if (deep) {
            for (var i = 0; i < compositeA.composites.length; i++){
                Composite.removeComposite(compositeA.composites[i], compositeB, true);
            }
        }

        return compositeA;
    };

    /**
     * Removes a composite from the given composite
     * @private
     * @method removeCompositeAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the composite removed
     */
    Composite.removeCompositeAt = function(composite, position) {
        composite.composites.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Adds a body to the given composite
     * @private
     * @method addBody
     * @param {composite} composite
     * @param {body} body
     * @return {composite} The original composite with the body added
     */
    Composite.addBody = function(composite, body) {
        composite.bodies.push(body);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes a body from the given composite, and optionally searching its children recursively
     * @private
     * @method removeBody
     * @param {composite} composite
     * @param {body} body
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the body removed
     */
    Composite.removeBody = function(composite, body, deep) {
        var position = composite.bodies.indexOf(body);
        if (position !== -1) {
            Composite.removeBodyAt(composite, position);
            Composite.setModified(composite, true, true, false);
        }

        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.removeBody(composite.composites[i], body, true);
            }
        }

        return composite;
    };

    /**
     * Removes a body from the given composite
     * @private
     * @method removeBodyAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the body removed
     */
    Composite.removeBodyAt = function(composite, position) {
        composite.bodies.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Adds a constraint to the given composite
     * @private
     * @method addConstraint
     * @param {composite} composite
     * @param {constraint} constraint
     * @return {composite} The original composite with the constraint added
     */
    Composite.addConstraint = function(composite, constraint) {
        composite.constraints.push(constraint);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes a constraint from the given composite, and optionally searching its children recursively
     * @private
     * @method removeConstraint
     * @param {composite} composite
     * @param {constraint} constraint
     * @param {boolean} [deep=false]
     * @return {composite} The original composite with the constraint removed
     */
    Composite.removeConstraint = function(composite, constraint, deep) {
        var position = composite.constraints.indexOf(constraint);
        if (position !== -1) {
            Composite.removeConstraintAt(composite, position);
        }

        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.removeConstraint(composite.composites[i], constraint, true);
            }
        }

        return composite;
    };

    /**
     * Removes a body from the given composite
     * @private
     * @method removeConstraintAt
     * @param {composite} composite
     * @param {number} position
     * @return {composite} The original composite with the constraint removed
     */
    Composite.removeConstraintAt = function(composite, position) {
        composite.constraints.splice(position, 1);
        Composite.setModified(composite, true, true, false);
        return composite;
    };

    /**
     * Removes all bodies, constraints and composites from the given composite
     * Optionally clearing its children recursively
     * @method clear
     * @param {world} world
     * @param {boolean} keepStatic
     * @param {boolean} [deep=false]
     */
    Composite.clear = function(composite, keepStatic, deep) {
        if (deep) {
            for (var i = 0; i < composite.composites.length; i++){
                Composite.clear(composite.composites[i], keepStatic, true);
            }
        }

        if (keepStatic) {
            composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; });
        } else {
            composite.bodies.length = 0;
        }

        composite.constraints.length = 0;
        composite.composites.length = 0;
        Composite.setModified(composite, true, true, false);

        return composite;
    };

    /**
     * Returns all bodies in the given composite, including all bodies in its children, recursively
     * @method allBodies
     * @param {composite} composite
     * @return {body[]} All the bodies
     */
    Composite.allBodies = function(composite) {
        var bodies = [].concat(composite.bodies);

        for (var i = 0; i < composite.composites.length; i++)
            bodies = bodies.concat(Composite.allBodies(composite.composites[i]));

        return bodies;
    };

    /**
     * Returns all constraints in the given composite, including all constraints in its children, recursively
     * @method allConstraints
     * @param {composite} composite
     * @return {constraint[]} All the constraints
     */
    Composite.allConstraints = function(composite) {
        var constraints = [].concat(composite.constraints);

        for (var i = 0; i < composite.composites.length; i++)
            constraints = constraints.concat(Composite.allConstraints(composite.composites[i]));

        return constraints;
    };

    /**
     * Returns all composites in the given composite, including all composites in its children, recursively
     * @method allComposites
     * @param {composite} composite
     * @return {composite[]} All the composites
     */
    Composite.allComposites = function(composite) {
        var composites = [].concat(composite.composites);

        for (var i = 0; i < composite.composites.length; i++)
            composites = composites.concat(Composite.allComposites(composite.composites[i]));

        return composites;
    };

    /**
     * Searches the composite recursively for an object matching the type and id supplied, null if not found
     * @method get
     * @param {composite} composite
     * @param {number} id
     * @param {string} type
     * @return {object} The requested object, if found
     */
    Composite.get = function(composite, id, type) {
        var objects,
            object;

        switch (type) {
        case 'body':
            objects = Composite.allBodies(composite);
            break;
        case 'constraint':
            objects = Composite.allConstraints(composite);
            break;
        case 'composite':
            objects = Composite.allComposites(composite).concat(composite);
            break;
        }

        if (!objects)
            return null;

        object = objects.filter(function(object) {
            return object.id.toString() === id.toString();
        });

        return object.length === 0 ? null : object[0];
    };

    /**
     * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add)
     * @method move
     * @param {compositeA} compositeA
     * @param {object[]} objects
     * @param {compositeB} compositeB
     * @return {composite} Returns compositeA
     */
    Composite.move = function(compositeA, objects, compositeB) {
        Composite.remove(compositeA, objects);
        Composite.add(compositeB, objects);
        return compositeA;
    };

    /**
     * Assigns new ids for all objects in the composite, recursively
     * @method rebase
     * @param {composite} composite
     * @return {composite} Returns composite
     */
    Composite.rebase = function(composite) {
        var objects = Composite.allBodies(composite)
                        .concat(Composite.allConstraints(composite))
                        .concat(Composite.allComposites(composite));

        for (var i = 0; i < objects.length; i++) {
            objects[i].id = Common.nextId();
        }

        Composite.setModified(composite, true, true, false);

        return composite;
    };

    /*
    *
    *  Events Documentation
    *
    */

    /**
    * Fired when a call to `Composite.add` is made, before objects have been added.
    *
    * @event beforeAdd
    * @param {} event An event object
    * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these)
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when a call to `Composite.add` is made, after objects have been added.
    *
    * @event afterAdd
    * @param {} event An event object
    * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these)
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when a call to `Composite.remove` is made, before objects have been removed.
    *
    * @event beforeRemove
    * @param {} event An event object
    * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these)
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when a call to `Composite.remove` is made, after objects have been removed.
    *
    * @event afterRemove
    * @param {} event An event object
    * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these)
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
     *
     * @property id
     * @type number
     */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "composite"
     */

    /**
     * An arbitrary `String` name to help the user identify and manage composites.
     *
     * @property label
     * @type string
     * @default "Composite"
     */

    /**
     * A flag that specifies whether the composite has been modified during the current step.
     * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled.
     * If you need to change it manually, you should use the `Composite.setModified` method.
     *
     * @property isModified
     * @type boolean
     * @default false
     */

    /**
     * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods.
     *
     * @property parent
     * @type composite
     * @default null
     */

    /**
     * An array of `Body` that are _direct_ children of this composite.
     * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method.
     *
     * @property bodies
     * @type body[]
     * @default []
     */

    /**
     * An array of `Constraint` that are _direct_ children of this composite.
     * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method.
     *
     * @property constraints
     * @type constraint[]
     * @default []
     */

    /**
     * An array of `Composite` that are _direct_ children of this composite.
     * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
     * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method.
     *
     * @property composites
     * @type composite[]
     * @default []
     */

})();<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2011 Sebastian Werner
==================================================================================================
*/

(function(document) {

	var root = document.documentElement;
	var request, cancel, is;

	if (root.requestFullScreen)
	{
		/**
		 * Requests full screen mode for given @element {DOMElement?document.documentElement}.
		 */
		request = function(element) {
			(element||root).requestFullScreen();
		};

		/**
		 * Cancels full screen mode.
		 */
		cancel = function() {
			document.cancelFullScreen();
		};

		/**
		 * {Boolean} Returns whether the browser is in full screen mode.
		 */
		is = function() {
			return document.fullScreenElement != null;
		};
	}
	else
	{
		var prefix = core.Env.select("engine", {
			trident: 'ms',
			gecko: 'moz',
			webkit: 'webkit',
			presto: 'o'
		});

		var baseName = "FullScreen";
		var requestName = prefix + "Request" + baseName;

		if (root[requestName])
		{
			var cancelName = prefix + "Cancel" + baseName;
			var hasName = prefix + baseName
			var isName = prefix + "Is" + baseName;

			request = function(element) {
				(element||root)[requestName]();
			};

			cancel = function() {
				document[cancelName]();
			};

			is = function() {
				return document[hasName] || document[isName];
			};
		}
		else
		{
			request = cancel = is = function() {
				return false;
			};
		}
	}

	/**
	 * Collection of methods to deal with different full screen APIs in browsers.
	 */
	core.Module("core.bom.FullScreen", {

		request: request,
		cancel: cancel,
		is: is

	});

})(document);<commit_msg>Minor<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2011 Sebastian Werner
==================================================================================================
*/

(function(document) {

	var root = document.documentElement;
	var request, cancel, is;

	// See also: http://hacks.mozilla.org/2012/01/using-the-fullscreen-api-in-web-browsers/
	if (root.requestFullScreen)
	{
		/**
		 * Requests full screen mode for given @element {DOMElement?document.documentElement}.
		 */
		request = function(element) {
			(element||root).requestFullScreen();
		};

		/**
		 * Cancels full screen mode.
		 */
		cancel = function() {
			document.cancelFullScreen();
		};

		/**
		 * {Boolean} Returns whether the browser is in full screen mode.
		 */
		is = function() {
			return document.fullScreenElement != null;
		};
	}
	else
	{
		var prefix = core.Env.select("engine", {
			trident: 'ms',
			gecko: 'moz',
			webkit: 'webkit',
			presto: 'o'
		});

		var baseName = "FullScreen";
		var requestName = prefix + "Request" + baseName;

		if (root[requestName])
		{
			var cancelName = prefix + "Cancel" + baseName;
			var hasName = prefix + baseName
			var isName = prefix + "Is" + baseName;

			request = function(element) {
				(element||root)[requestName]();
			};

			cancel = function() {
				document[cancelName]();
			};

			is = function() {
				return document[hasName] || document[isName];
			};
		}
		else
		{
			request = cancel = is = function() {
				return false;
			};
		}
	}

	/**
	 * Collection of methods to deal with different full screen APIs in browsers.
	 */
	core.Module("core.bom.FullScreen", {

		request: request,
		cancel: cancel,
		is: is

	});

})(document);<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import chroma from 'chroma-js'
import colors from 'primer-colors'
import titleCase from 'title-case'
import {BorderBox, Box, Flex, Heading, Text} from '@primer/components'

const {black, white} = colors

export const gradientHues = ['gray', 'blue', 'green', 'purple', 'yellow', 'orange', 'red']

export function ColorPalette(props) {
  return (
    <Flex mb={6} className="markdown-no-margin" {...props}>
      {gradientHues.map(hue => {
        const color = colors[hue][5]
        return (
          <Box bg={color} p={3} width={200} mr={2} mb={2} key={hue}>
            <Text fontWeight="bold" color={overlayColor(color)}>
              {titleCase(hue)}
            </Text>
          </Box>
        )
      })}
      <BorderBox bg="white" p={3} width={200} mb={2} borderRadius={0}>
        <Text fontWeight="bold" color="black">
          White
        </Text>
      </BorderBox>
    </Flex>
  )
}

export function ColorVariables(props) {
  return (
    <>
      <Flex flexWrap="wrap" className="gutter" {...props}>
        {gradientHues.map(hue => (
          <ColorVariable id={hue} hue={hue} key={hue} />
        ))}
      </Flex>
      <Flex flexWrap="wrap" {...props}>
        <FadeVariables id="black" hue="black" bg="black" color="white">
          <BorderBox border={0} borderRadius={0} borderTop={1} borderColor="gray.5" mt={1}>
            <Text as="div" fontSize={2} pt={3} mb={0}>
              Black fades apply alpha transparency to the <Var>$black</Var> variable. The black color value has a slight
              blue hue to match our grays.
            </Text>
          </BorderBox>
        </FadeVariables>
        <FadeVariables id="white" hue="white" over={black}>
          <BorderBox border={0} borderRadius={0} borderTop={1} mt={1}>
            <Text as="div" fontSize={2} pt={3} mb={0}>
              White fades apply alpha transparency to the <Var>$white</Var> variable, below these are shown overlaid on
              a dark gray background.
            </Text>
          </BorderBox>
        </FadeVariables>
      </Flex>
    </>
  )
}

export function ColorVariable({hue, ...rest}) {
  const values = colors[hue]
  return (
    <Flex.Item as={Box} minWidth={240} pr={4} mb={6} className="col-12 col-md-6 markdown-no-margin" {...rest}>
      {/* <Heading as="div">{titleCase(hue)}</Heading> */}
      <Box bg={`${hue}.5`} my={2} p={3} color="white">
        <Heading as="div" pb={3} fontSize={56} fontWeight="light">
          {titleCase(hue)}
        </Heading>
        <Flex justifyContent="space-between">
          <Flex.Item as={Var}>${hue}-500</Flex.Item>
          <Flex.Item flex="1 1 auto" ml={3} as={Var}>
            .bg-{hue}-5
          </Flex.Item>
          <Text justifySelf="end" fontFamily="mono">
            {values[5]}
          </Text>
        </Flex>
      </Box>
      {values.map((value, index) => (
        <Swatch name={`${hue}-${index}00`} value={value} key={value} />
      ))}
    </Flex.Item>
  )
}

ColorVariable.propTypes = {
  hue: PropTypes.oneOf(Object.keys(colors)).isRequired
}

export function FadeVariables({hue, color, bg, over, children, ...rest}) {
  const colorValue = colors[hue]
  const alphas = [15, 30, 50, 70, 85]
  const values = alphas.map(alpha => {
    const value = chroma(colorValue)
      .alpha(alpha / 100)
      .css()
    return {
      name: `${hue}-fade-${alpha}`,
      textColor: fadeTextColor(value, over),
      value
    }
  })
  const boxProps = {color, bg}
  return (
    <Flex.Item as={Box} pr={4} mb={6} width={1 / 2} className="markdown-no-margin" {...rest}>
      {/* <Heading as="div">{titleCase(hue)}</Heading> */}
      <Box my={2} p={3} {...boxProps}>
        <Heading as="div" pb={3} fontSize={56} fontWeight="light">
          {titleCase(hue)}
        </Heading>
        <Flex justifyContent="space-between">
          <Flex.Item flex="1 1 auto" as={Var}>
            ${hue}
          </Flex.Item>
          <Text fontFamily="mono">
            {chroma(colorValue).css()}
            {' / '}
            {colorValue}
          </Text>
        </Flex>
        {children}
      </Box>
      <Box bg={over}>
        {values.map(swatchProps => (
          <Swatch {...swatchProps} key={swatchProps.name} />
        ))}
      </Box>
    </Flex.Item>
  )
}

FadeVariables.propTypes = {
  bg: Box.propTypes.color,
  color: Box.propTypes.color,
  hue: PropTypes.oneOf(['black', 'white']),
  over: PropTypes.string
}

function Swatch(props) {
  const {name, index, value, textColor = overlayColor(value), ...rest} = props
  return (
    <Box bg={value} color={textColor} {...rest}>
      <Text as={Flex} fontSize={1} justifyContent="space-between">
        <Box as={Var} p={3}>
          ${name}
        </Box>
        <Box as={Text} fontFamily="mono" p={3}>
          .bg-{name}-{index}
        </Box>
        <Box as={Text} fontFamily="mono" p={3}>
          {value}
        </Box>
      </Text>
    </Box>
  )
}

Swatch.propTypes = {
  name: PropTypes.string.isRequired,
  textColor: PropTypes.string,
  value: PropTypes.string.isRequired
}

function Var(props) {
  // FIXME: fontStyle should be a prop, right?
  return <Text as="var" fontWeight="bold" fontFamily="mono" style={{fontStyle: 'normal'}} {...props} />
}

export function overlayColor(bg) {
  return chroma(bg).luminance() > 0.5 ? black : white
}

function fadeTextColor(fg, bg = white) {
  const rgb = compositeRGB(fg, bg)
  return overlayColor(rgb)
}

/**
 * Composite ("flatten") a foreground RGBA value with an RGB background into an
 * RGB color for the purposes of measuring contrast or luminance.
 */
function compositeRGB(foreground, background) {
  const [fr, fg, fb, fa] = chroma(foreground).rgba()
  const [br, bg, bb] = chroma(background).rgb()
  return chroma([(1 - fa) * br + fa * fr, (1 - fa) * bg + fa * fg, (1 - fa) * bb + fa * fb]).css()
}
<commit_msg>clean up swatches<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import chroma from 'chroma-js'
import colors from 'primer-colors'
import titleCase from 'title-case'
import {BorderBox, Box, Flex, Heading, Text} from '@primer/components'

const {black, white} = colors

export const gradientHues = ['gray', 'blue', 'green', 'purple', 'yellow', 'orange', 'red']

export function ColorPalette(props) {
  return (
    <Flex mb={6} className="markdown-no-margin" {...props}>
      {gradientHues.map(hue => {
        const color = colors[hue][5]
        return (
          <Box bg={color} p={3} width={200} mr={2} mb={2} key={hue}>
            <Text fontWeight="bold" color={overlayColor(color)}>
              {titleCase(hue)}
            </Text>
          </Box>
        )
      })}
      <BorderBox bg="white" p={3} width={200} mb={2} borderRadius={0}>
        <Text fontWeight="bold" color="black">
          White
        </Text>
      </BorderBox>
    </Flex>
  )
}

export function ColorVariables(props) {
  return (
    <>
      <Flex flexWrap="wrap" className="gutter" {...props}>
        {gradientHues.map(hue => (
          <ColorVariable id={hue} hue={hue} key={hue} />
        ))}
      </Flex>
      <Flex flexWrap="wrap" {...props}>
        <FadeVariables id="black" hue="black" bg="black" color="white">
          <BorderBox border={0} borderRadius={0} borderTop={1} borderColor="gray.5" mt={1}>
            <Text as="div" fontSize={2} pt={3} mb={0}>
              Black fades apply alpha transparency to the <Var>$black</Var> variable. The black color value has a slight
              blue hue to match our grays.
            </Text>
          </BorderBox>
        </FadeVariables>
        <FadeVariables id="white" hue="white" over={black}>
          <BorderBox border={0} borderRadius={0} borderTop={1} mt={1}>
            <Text as="div" fontSize={2} pt={3} mb={0}>
              White fades apply alpha transparency to the <Var>$white</Var> variable, below these are shown overlaid on
              a dark gray background.
            </Text>
          </BorderBox>
        </FadeVariables>
      </Flex>
    </>
  )
}

export function ColorVariable({hue, ...rest}) {
  const values = colors[hue]
  return (
    <Flex.Item as={Box} minWidth={240} pr={4} mb={6} className="col-12 col-md-6 markdown-no-margin" {...rest}>
      {/* <Heading as="div">{titleCase(hue)}</Heading> */}
      <Box bg={colors[hue][5]} my={2} p={3} color="white">
        <Heading as="div" pb={3} fontSize={56} fontWeight="light">
          {titleCase(hue)}
        </Heading>
        <Flex justifyContent="space-between">
          <Flex.Item as={Var}>${hue}-500</Flex.Item>
          <Text justifySelf="end" fontFamily="mono">
            {values[5]}
          </Text>
        </Flex>
      </Box>
      {values.map((value, index) => (
        <Swatch name={hue} index={index} value={value} key={value} />
      ))}
    </Flex.Item>
  )
}

ColorVariable.propTypes = {
  hue: PropTypes.oneOf(Object.keys(colors)).isRequired
}

export function FadeVariables({hue, color, bg, over, children, ...rest}) {
  const colorValue = colors[hue]
  const alphas = [15, 30, 50, 70, 85]
  const values = alphas.map(alpha => {
    const value = chroma(colorValue)
      .alpha(alpha / 100)
      .css()
    return {
      name: `${hue}-fade-${alpha}`,
      textColor: fadeTextColor(value, over),
      value
    }
  })
  const boxProps = {color, bg}
  return (
    <Flex.Item as={Box} pr={4} mb={6} width={1 / 2} className="markdown-no-margin" {...rest}>
      {/* <Heading as="div">{titleCase(hue)}</Heading> */}
      <Box my={2} p={3} {...boxProps}>
        <Heading as="div" pb={3} fontSize={56} fontWeight="light">
          {titleCase(hue)}
        </Heading>
        <Flex justifyContent="space-between">
          <Flex.Item flex="1 1 auto" as={Var}>
            ${hue}
          </Flex.Item>
          <Text fontFamily="mono">
            {chroma(colorValue).css()}
            {' / '}
            {colorValue}
          </Text>
        </Flex>
        {children}
      </Box>
      <Box bg={over}>
        {values.map(swatchProps => (
          <Swatch {...swatchProps} key={swatchProps.name} />
        ))}
      </Box>
    </Flex.Item>
  )
}

FadeVariables.propTypes = {
  bg: Box.propTypes.color,
  color: Box.propTypes.color,
  hue: PropTypes.oneOf(['black', 'white']),
  over: PropTypes.string
}

function Swatch(props) {
  const {name, index, value, textColor = overlayColor(value), ...rest} = props
  return (
    <Flex bg={value} color={textColor} {...rest}>
      <Box as={Var} pr={4}>
        ${name}-{index}00
      </Box>
      <Box as={Text} fontFamily="mono">
        {value}
      </Box>
    </Flex>
  )
}

Swatch.defaultProps = {
  flexWrap: 'wrap',
  fontSize: 1,
  justifyContent: 'space-between',
  p: 3
}

Swatch.propTypes = {
  name: PropTypes.string.isRequired,
  index: PropTypes.number.isRequired,
  textColor: PropTypes.string,
  value: PropTypes.string.isRequired
}

function Var(props) {
  // FIXME: fontStyle should be a prop, right?
  return <Text as="var" fontWeight="bold" fontFamily="mono" style={{fontStyle: 'normal'}} {...props} />
}

export function overlayColor(bg) {
  return chroma(bg).luminance() > 0.5 ? black : white
}

function fadeTextColor(fg, bg = white) {
  const rgb = compositeRGB(fg, bg)
  return overlayColor(rgb)
}

/**
 * Composite ("flatten") a foreground RGBA value with an RGB background into an
 * RGB color for the purposes of measuring contrast or luminance.
 */
function compositeRGB(foreground, background) {
  const [fr, fg, fb, fa] = chroma(foreground).rgba()
  const [br, bg, bb] = chroma(background).rgb()
  return chroma([(1 - fa) * br + fa * fr, (1 - fa) * bg + fa * fg, (1 - fa) * bb + fa * fb]).css()
}
<|endoftext|>


<commit_before>import * as sqlectron from 'sqlectron-core';
import config from './config';

// Hack solution to ignore console.error from dtrace imported by bunyan
/* eslint no-console:0 */
const realConsoleError = console.error;
console.error = () => {};
const { createLogger } = require('bunyan');
console.error = realConsoleError;

const dataConfig = config.get();

const loggerConfig = {
  app: 'sqlectron-gui',
  name: 'sqlectron-gui',
  level: dataConfig.log.level,
};

if (dataConfig.log.file) {
  loggerConfig.streams = [{ path: dataConfig.log.path }];
}

const logger = createLogger(loggerConfig);

// Set custom logger for sqlectron-core
sqlectron.setLogger((namespace) => logger.child({ namespace: `sqlectron-core:${namespace}` }));

export default (namespace) => logger.child({ namespace });
<commit_msg>Fix log to allow use console and file at same time<commit_after>import * as sqlectron from 'sqlectron-core';
import config from './config';

// Hack solution to ignore console.error from dtrace imported by bunyan
/* eslint no-console:0 */
const realConsoleError = console.error;
console.error = () => {};
const { createLogger } = require('bunyan');
console.error = realConsoleError;

const dataConfig = config.get();

const loggerConfig = {
  app: 'sqlectron-gui',
  name: 'sqlectron-gui',
  level: dataConfig.log.level,
  streams: [],
};

if (dataConfig.log.console) {
  loggerConfig.streams.push({ stream: process.stdout });
}

if (dataConfig.log.file) {
  loggerConfig.streams.push({ path: dataConfig.log.path });
}

const logger = createLogger(loggerConfig);

// Set custom logger for sqlectron-core
sqlectron.setLogger((namespace) => logger.child({ namespace: `sqlectron-core:${namespace}` }));

export default (namespace) => logger.child({ namespace });
<|endoftext|>


<commit_before>/**
 * Copyright 2015 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org
 */
define( [
   'angular',
   'laxar',
   'laxar-patterns'
], function( ng, ax, patterns ) {
   'use strict';

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   Controller.$inject = [ '$scope', 'axFlowService' ];

   function Controller( $scope, axFlowService ) {
      var userUrl = $scope.features.user.url;

      $scope.authenticated = false;
      $scope.authenticate = function() {
         $scope.eventBus.publish( 'takeActionRequest.' + $scope.features.auth.action, {
            action: $scope.features.auth.action
         } );
      };

      $scope.dropdown = {
         open: false,
         toggle: function() {
            this.open = !this.open;
         },
         click: function( item ) {
            if( item.action ) {
               $scope.eventBus.publish( 'takeActionRequest.' + item.action, {
                  action: item.action,
                  data: item
               } );
               this.open = false;
               return false;
            }
            return true;
         },
         menu: $scope.features.menu.map( function( item ) {
            if( item.place ) {
               item.url = axFlowService.constructAnchor( item.place, item.parameters );
            }
            return item;
         } )
      };

      var userPublisher = patterns.resources.replacePublisherForFeature( $scope, 'user', {
         deliverToSender: true
      } );

      patterns.resources.handlerFor( $scope )
         .registerResourceFromFeature( 'user' )
         .registerResourceFromFeature( 'auth', {
            onReplace: fetchUserData
         } );

      patterns.validation.handlerFor( $scope )
         .registerResourceFromFeature( 'auth', {
            onValidate: authResourceValidator( userUrl )
         } );

      patterns.flags.handlerFor( $scope )
         .registerFlagFromFeature( 'auth.flag', {
            onChange: function( state ) {
               $scope.authenticated = state;
            }
         } );

      function fetchUserData( event ) {
         var headers = {};
         var accessToken = event.data.access_token;

         if( accessToken ) {
            headers[ 'Authorization' ] = 'token ' + accessToken;
         }

         return fetch( userUrl, {
            method: 'get',
            headers: headers
         } ).then( function( response ) {
            ax.log.info( 'Got user data' );
            response.json().then( userPublisher );
         }, function( response ) {
            userPublisher( {} );
         } );
      }
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function authResourceValidator( url ) {
      return function validateAccessToken( resource, data ) {
         var accessToken = (data || {}).access_token;
         var htmlApiLink = 'GitHub API';

         if( !accessToken ) {
            return Promise.resolve( [
               { 'en-US': 'Can\'t connect to ' + htmlApiLink + ' without an access token.' }
            ] );
         }

         return fetch( url, {
            method: 'head',
            headers: {
               'Authorization': 'token ' + accessToken
            }
         } ).then( function( response ) {
            var i18nHtmlMessage = {
               'en-US': 'Successfully validated access token ' + accessToken + '. ' +
                        'Received authentication success from ' + htmlApiLink + '.'
            };
            ax.log.trace( i18nHtmlMessage[ 'en-US' ] );
            return [ i18nHtmlMessage ];
         }, function( response ) {
            var statusText = response.status + ' ' + response.statusText;
            var i18nHtmlMessage = {
               'en-US': 'Validation of GitHub access token ' + accessToken + ' failed. ' +
                        'Received HTTP status ' + statusText + ' from ' + htmlApiLink + '.'
            };
            ax.log.trace( i18nHtmlMessage[ 'en-US' ] );
            return Promise.reject( [ i18nHtmlMessage ] );
         } );

      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function validationHandlerFor( context ) {
      return {
         registerResourceFromFeature: function( featurePath, options ) {
            var feature = context.features[ featurePath ] || {};
            var resource = feature.resource;

            return this.registerResource( resource, options );
         },
         registerResource: function( resource, options ) {
            var eventBus = context.eventBus;
            var validateHandler = options.onValidate;
            var data;

            eventBus.subscribe( 'didReplace.' + resource, function( event ) {
               data = event.data;
            } );

            eventBus.subscribe( 'didUpdate.' + resource, function( event ) {
               patterns.json.applyPatch( data, event.patches );
            } );

            eventBus.subscribe( 'validateRequest.' + resource, function( event ) {
               if( !validateHandler ) {
                  return;
               }

               eventBus.publish( 'willValidate.' + resource );

               validateHandler( resource, data ).then( function( messages ) {
                  return eventBus.publish(
                     'didValidate.' + resource,
                     patterns.validation.successEvent( resource, messages )
                  );
               }, function( messages ) {
                  return eventBus.publish(
                     'didValidate.' + resource,
                     patterns.validation.errorEvent( resource, messages )
                  );
               } );
            } );

            return this;
         }
      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   (function patchPatterns() {
      var original = patterns;
      patterns = Object.create( patterns );
      patterns.validation = Object.create( patterns.validation );
      patterns.validation.handlerFor = validationHandlerFor;
   })();

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   return ng.module( 'githubLoginWidget', [] )
            .controller( 'GithubLoginWidgetController', Controller );

} );
<commit_msg>Check response status when validating the OAuth token<commit_after>/**
 * Copyright 2015 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org
 */
define( [
   'angular',
   'laxar',
   'laxar-patterns'
], function( ng, ax, patterns ) {
   'use strict';

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   Controller.$inject = [ '$scope', 'axFlowService' ];

   function Controller( $scope, axFlowService ) {
      var userUrl = $scope.features.user.url;

      $scope.authenticated = false;
      $scope.authenticate = function() {
         $scope.eventBus.publish( 'takeActionRequest.' + $scope.features.auth.action, {
            action: $scope.features.auth.action
         } );
      };

      $scope.dropdown = {
         open: false,
         toggle: function() {
            this.open = !this.open;
         },
         click: function( item ) {
            if( item.action ) {
               $scope.eventBus.publish( 'takeActionRequest.' + item.action, {
                  action: item.action,
                  data: item
               } );
               this.open = false;
               return false;
            }
            return true;
         },
         menu: $scope.features.menu.map( function( item ) {
            if( item.place ) {
               item.url = axFlowService.constructAnchor( item.place, item.parameters );
            }
            return item;
         } )
      };

      var userPublisher = patterns.resources.replacePublisherForFeature( $scope, 'user', {
         deliverToSender: true
      } );

      patterns.resources.handlerFor( $scope )
         .registerResourceFromFeature( 'user' )
         .registerResourceFromFeature( 'auth', {
            onReplace: fetchUserData
         } );

      patterns.validation.handlerFor( $scope )
         .registerResourceFromFeature( 'auth', {
            onValidate: authResourceValidator( userUrl )
         } );

      patterns.flags.handlerFor( $scope )
         .registerFlagFromFeature( 'auth.flag', {
            onChange: function( state ) {
               $scope.authenticated = state;
            }
         } );

      function fetchUserData( event ) {
         var headers = {};
         var accessToken = event.data.access_token;

         if( accessToken ) {
            headers[ 'Authorization' ] = 'token ' + accessToken;
         }

         return fetch( userUrl, {
            method: 'get',
            headers: headers
         } ).then( function( response ) {
            ax.log.info( 'Got user data' );
            response.json().then( userPublisher );
         }, function( response ) {
            userPublisher( {} );
         } );
      }
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function authResourceValidator( url ) {
      return function validateAccessToken( resource, data ) {
         var accessToken = (data || {}).access_token;
         var htmlApiLink = 'GitHub API';

         if( !accessToken ) {
            return Promise.resolve( [
               { 'en-US': 'Can\'t connect to ' + htmlApiLink + ' without an access token.' }
            ] );
         }

         return fetch( url, {
            method: 'head',
            headers: {
               'Authorization': 'token ' + accessToken
            }
         } ).then( function( response ) {
            if( response.status < 400 ) {
               return response;
            } else {
               return Promise.reject( response );
            }
         } ).then( function( response ) {
            var i18nHtmlMessage = {
               'en-US': 'Successfully validated access token ' + accessToken + '. ' +
                        'Received authentication success from ' + htmlApiLink + '.'
            };
            ax.log.trace( i18nHtmlMessage[ 'en-US' ] );
            return [ i18nHtmlMessage ];
         }, function( response ) {
            var statusText = response.status + ' ' + response.statusText;
            var i18nHtmlMessage = {
               'en-US': 'Validation of GitHub access token ' + accessToken + ' failed. ' +
                        'Received HTTP status ' + statusText + ' from ' + htmlApiLink + '.'
            };
            ax.log.trace( i18nHtmlMessage[ 'en-US' ] );
            return Promise.reject( [ i18nHtmlMessage ] );
         } );

      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function validationHandlerFor( context ) {
      return {
         registerResourceFromFeature: function( featurePath, options ) {
            var feature = context.features[ featurePath ] || {};
            var resource = feature.resource;

            return this.registerResource( resource, options );
         },
         registerResource: function( resource, options ) {
            var eventBus = context.eventBus;
            var validateHandler = options.onValidate;
            var data;

            eventBus.subscribe( 'didReplace.' + resource, function( event ) {
               data = event.data;
            } );

            eventBus.subscribe( 'didUpdate.' + resource, function( event ) {
               patterns.json.applyPatch( data, event.patches );
            } );

            eventBus.subscribe( 'validateRequest.' + resource, function( event ) {
               if( !validateHandler ) {
                  return;
               }

               eventBus.publish( 'willValidate.' + resource );

               validateHandler( resource, data ).then( function( messages ) {
                  return eventBus.publish(
                     'didValidate.' + resource,
                     patterns.validation.successEvent( resource, messages )
                  );
               }, function( messages ) {
                  return eventBus.publish(
                     'didValidate.' + resource,
                     patterns.validation.errorEvent( resource, messages )
                  );
               } );
            } );

            return this;
         }
      };
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   (function patchPatterns() {
      var original = patterns;
      patterns = Object.create( patterns );
      patterns.validation = Object.create( patterns.validation );
      patterns.validation.handlerFor = validationHandlerFor;
   })();

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   return ng.module( 'githubLoginWidget', [] )
            .controller( 'GithubLoginWidgetController', Controller );

} );
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/math/base/random/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var pkg = require( './../package.json' ).name;
var Poisson = require( './../lib' );

// MAIN //

bench( pkg+'::instantiation', function benchmark( b ) {
	var lambda;
	var dist;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		lambda = ( randu() * 10.0 ) + EPS;
		dist = new Poisson( lambda );
		if ( !( dist instanceof Poisson ) ) {
			b.fail( 'should return a distribution instance' );
		}
	}
	b.toc();
	if ( !( dist instanceof Poisson ) ) {
		b.fail( 'should return a distribution instance' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::get:lambda', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y = dist.lambda;
		if ( y !== lambda ) {
			b.fail( 'should return set value' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::set:lambda', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y = ( 10.0*randu() ) + EPS;
		dist.lambda = y;
		if ( dist.lambda !== y ) {
			b.fail( 'should return set value' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':entropy', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.entropy;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':kurtosis', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.kurtosis;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mean', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.mean;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':median', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.median;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mode', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.mode;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':skewness', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.skewness;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':variance', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.variance;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':cdf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.cdf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mgf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.mgf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':pmf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.pmf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':quantile', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.quantile( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<commit_msg>Choose sensible values in benchmarks<commit_after>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/math/base/random/randu' );
var round = require( '@stdlib/math/base/special/round' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var pkg = require( './../package.json' ).name;
var Poisson = require( './../lib' );

// MAIN //

bench( pkg+'::instantiation', function benchmark( b ) {
	var lambda;
	var dist;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		lambda = ( randu() * 10.0 ) + EPS;
		dist = new Poisson( lambda );
		if ( !( dist instanceof Poisson ) ) {
			b.fail( 'should return a distribution instance' );
		}
	}
	b.toc();
	if ( !( dist instanceof Poisson ) ) {
		b.fail( 'should return a distribution instance' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::get:lambda', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y = dist.lambda;
		if ( y !== lambda ) {
			b.fail( 'should return set value' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::set:lambda', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y = ( 10.0*randu() ) + EPS;
		dist.lambda = y;
		if ( dist.lambda !== y ) {
			b.fail( 'should return set value' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':entropy', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.entropy;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':kurtosis', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.kurtosis;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mean', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.mean;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':median', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + EPS;
		y = dist.median;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mode', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.mode;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':skewness', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.skewness;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':variance', function benchmark( b ) {
	var lambda;
	var dist;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		dist.lambda = ( 10.0*randu() ) + 1.0 + EPS;
		y = dist.variance;
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':cdf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu() * 6.0;
		y = dist.cdf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':mgf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.mgf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':pmf', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = round( randu() * 8.0 );
		y = dist.pmf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':quantile', function benchmark( b ) {
	var lambda;
	var dist;
	var x;
	var y;
	var i;

	lambda = 5.54;
	dist = new Poisson( lambda );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu();
		y = dist.quantile( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>import React, { Fragment } from 'react';
import { Helmet } from 'react-helmet';

import md from '../markdown/renderer';

export default function Styles() {
  return (
    <Fragment>
      <Helmet>
        <title>Styles - React Images</title>
        <meta
          name="description"
          content="React-Select offers a flexible, light-weight styling framework which is a thin abstraction over simple javascript objects using glam"
        />
      </Helmet>
      {md`
        # Styles

        React-Select offers a flexible, light-weight styling framework which is
        a thin abstraction over simple javascript objects using
        [glam](https://github.com/threepointone/glam).

        ~~~jsx
        /**
         * @param {Object} base -- the component's default style
         * @param {Object} state -- the component's current state e.g. \`isFocused\`
         * @returns {Object}
         */
        function styleFn(base, state) {
          // optionally spread base styles
          return { ...base, color: state.isFocused ? 'blue' : 'red' };
        }
        ~~~

        ## Style Object

        Each component is keyed, and ships with default styles. The component's
        default style object is passed as the first argument to the function
        when it's resolved.

        The second argument is the current state of the select, features like
        \`isFocused\`, \`isSelected\` etc. allowing you to
        implement dynamic styles for each of the components.

        ###### Style Keys

        \`clearIndicator\` \`container\` \`control\` \`dropdownIndicator\` \`group\`
        \`groupHeading\` \`indicatorsContainer\` \`indicatorSeparator\` \`input\`
        \`loadingIndicator\` \`loadingMessage\` \`menu\` \`menuList\` \`multiValue\`
        \`multiValueLabel\` \`multiValueRemove\` \`noOptionsMessage\` \`option\`
        \`placeholder\` \`singleValue\` \`valueContainer\`

        ## Base and State

        Spreading the base styles into your returned object let's you extend it
        however you like while maintaining existing styles. Alternatively, you
        can omit the base and completely take control of the component's styles.

        ~~~jsx
        const customStyles = {
          option: (base, state) => ({
            ...base,
            borderBottom: '1px dotted pink',
            color: state.isFullscreen ? 'red' : 'blue',
            padding: 20,
          }),
          control: () => ({
            // none of react-selects styles are passed to <View />
            width: 200,
          })
          singleValue: (base, state) => {
            const opacity = state.isDisabled ? 0.5 : 1;
            const transition = 'opacity 300ms';

            return { ...base, opacity, transition };
          }
        }

        const App = () => (
          <Select
            styles={customStyles}
            options={...}
          />
        );
        ~~~
      `}
    </Fragment>
  );
}
<commit_msg>fix typo<commit_after>import React, { Fragment } from 'react';
import { Helmet } from 'react-helmet';

import md from '../markdown/renderer';

export default function Styles() {
  return (
    <Fragment>
      <Helmet>
        <title>Styles - React Select</title>
        <meta
          name="description"
          content="React-Select offers a flexible, light-weight styling framework which is a thin abstraction over simple javascript objects using glam"
        />
      </Helmet>
      {md`
        # Styles

        React-Select offers a flexible, light-weight styling framework which is
        a thin abstraction over simple javascript objects using
        [glam](https://github.com/threepointone/glam).

        ~~~jsx
        /**
         * @param {Object} base -- the component's default style
         * @param {Object} state -- the component's current state e.g. \`isFocused\`
         * @returns {Object}
         */
        function styleFn(base, state) {
          // optionally spread base styles
          return { ...base, color: state.isFocused ? 'blue' : 'red' };
        }
        ~~~

        ## Style Object

        Each component is keyed, and ships with default styles. The component's
        default style object is passed as the first argument to the function
        when it's resolved.

        The second argument is the current state of the select, features like
        \`isFocused\`, \`isSelected\` etc. allowing you to
        implement dynamic styles for each of the components.

        ###### Style Keys

        \`clearIndicator\` \`container\` \`control\` \`dropdownIndicator\` \`group\`
        \`groupHeading\` \`indicatorsContainer\` \`indicatorSeparator\` \`input\`
        \`loadingIndicator\` \`loadingMessage\` \`menu\` \`menuList\` \`multiValue\`
        \`multiValueLabel\` \`multiValueRemove\` \`noOptionsMessage\` \`option\`
        \`placeholder\` \`singleValue\` \`valueContainer\`

        ## Base and State

        Spreading the base styles into your returned object let's you extend it
        however you like while maintaining existing styles. Alternatively, you
        can omit the base and completely take control of the component's styles.

        ~~~jsx
        const customStyles = {
          option: (base, state) => ({
            ...base,
            borderBottom: '1px dotted pink',
            color: state.isFullscreen ? 'red' : 'blue',
            padding: 20,
          }),
          control: () => ({
            // none of react-selects styles are passed to <View />
            width: 200,
          })
          singleValue: (base, state) => {
            const opacity = state.isDisabled ? 0.5 : 1;
            const transition = 'opacity 300ms';

            return { ...base, opacity, transition };
          }
        }

        const App = () => (
          <Select
            styles={customStyles}
            options={...}
          />
        );
        ~~~
      `}
    </Fragment>
  );
}
<|endoftext|>


<commit_before>'use strict';

angular.module('users').controller('ProfileInfoController', [
  '$scope',
  '$http',
  '$location',
  'Users',
  'Authentication',
  'UserApi',
  function ($scope, $http, $location, Users, Authentication, UserApi) {
    $scope.polls = [];
    $scope.cmts = [];
    $scope.votes = [];
    $scope.activitys = [];

    $scope.page = 0;
    $scope.busy = false;
    $scope.stoped = false;

    function get_data() {
      Promise.all([ get_polls(), get_cmts(), get_votes() ])
        .then(res => {
          console.log(res);
          merge_activity();
          console.log($scope.activitys);
        })
        .catch(err => {
          alert(err);
        });
    }

    function get_polls() {
      return new Promise((resolve, reject) => {
        UserApi.get_polls($scope.profile._id, $scope.page)
          .success(res => {
            $scope.polls = res || [];
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_cmts() {
      return new Promise((resolve, reject) => {
        UserApi.get_cmts($scope.profile._id, $scope.page)
          .success(res => {
            $scope.cmts = res || [];
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_votes() {
      return new Promise((resolve, reject) => {
        UserApi.get_votes($scope.profile._id, $scope.page)
          .success(res => {
            $scope.votes = res || [];
            var promises = [];
            $scope.votes.forEach(vote => {
              promises.push(get_opts(vote));
            });
            return Promise.all(promises);
          })
          .then(res => {
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_opts(vote) {
      return new Promise((resolve, reject) => {
        Action.get_opts_for_vote(vote._id)
          .then(res => {
            vote.opts = _.pluck(res.data, 'opt') || [];
            return resolve(vote);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }

    function merge_activity() {
      $scope.polls.forEach(function(poll) {
        if (poll) {
          $scope.activitys.push({
            _id: poll._id,
            title: poll.title,
            body: poll.body,
            created: poll.created,
            isPublic: poll.isPublic,
            opts: null
          });
        }
      });
      $scope.cmts.forEach(function(cmt) {
        if (cmt) {
          $scope.activitys.push({
            _id: (cmt.poll) ? cmt.poll._id : null,
            title: (cmt.poll) ? cmt.poll.title : '',
            body: cmt.body,
            created: cmt.created,
            isPublic: (cmt.poll) ? cmt.poll.isPublic : false,
            opts: null
          });
        }
      });
      $scope.votes.forEach(function(vote) {
        if (vote) {
          $scope.activitys.push({
            _id: (vote.poll) ? vote.poll._id : null,
            title: (vote.poll) ? vote.poll.title : '',
            body: null,
            created: vote.created,
            isPublic: (vote.poll) ? vote.poll.isPublic : false,
            opts: vote.opts
          });
        }
      });
    }

    // $scope.isCurrentOwner = profile._id === Authentication.user._id;
    // $scope.isLogged = (Authentication.user) ? true : false;
    // $scope.page = 0;
    // init();

    // function init() {
    //   get_polls();
    // }

    // function get_polls() {
    //   UserApi.get_polls($scope.profile._id, $scope.page)
    //     .success(res => {
    //       $scope.polls = res || [];
    //     })
    //     .error(err => {
    //       alert(err);
    //     });
    // }

    // $scope.poll_filter = (poll) => {
    //   if (poll.isPublic) {
    //     return true;
    //   } else {
    //     return $scope.isCurrentOwner;
    //   }
    // };
  }
]);
<commit_msg>Commited from lenh at Wed, Jul 05, 2017  4:51:40 PM<commit_after>'use strict';

angular.module('users').controller('ProfileInfoController', [
  '$scope',
  '$http',
  '$location',
  'Users',
  'Authentication',
  'UserApi',
  function ($scope, $http, $location, Users, Authentication, UserApi) {
    $scope.polls = [];
    $scope.cmts = [];
    $scope.votes = [];
    $scope.activitys = [];

    $scope.page = 0;
    $scope.busy = false;
    $scope.stoped = false;

    get_data();
    function get_data() {
      Promise.all([ get_polls(), get_cmts(), get_votes() ])
        .then(res => {
          console.log(res);
          merge_activity();
          console.log($scope.activitys);
        })
        .catch(err => {
          alert(err);
        });
    }

    function get_polls() {
      return new Promise((resolve, reject) => {
        UserApi.get_polls($scope.profile._id, $scope.page)
          .success(res => {
            $scope.polls = res || [];
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_cmts() {
      return new Promise((resolve, reject) => {
        UserApi.get_cmts($scope.profile._id, $scope.page)
          .success(res => {
            $scope.cmts = res || [];
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_votes() {
      return new Promise((resolve, reject) => {
        UserApi.get_votes($scope.profile._id, $scope.page)
          .success(res => {
            $scope.votes = res || [];
            var promises = [];
            $scope.votes.forEach(vote => {
              promises.push(get_opts(vote));
            });
            return Promise.all(promises);
          })
          .then(res => {
            return resolve(res);
          })
          .error(err => {
            return reject(err);
          });
      });
    }
    function get_opts(vote) {
      return new Promise((resolve, reject) => {
        Action.get_opts_for_vote(vote._id)
          .then(res => {
            vote.opts = _.pluck(res.data, 'opt') || [];
            return resolve(vote);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }

    function merge_activity() {
      $scope.polls.forEach(function(poll) {
        if (poll) {
          $scope.activitys.push({
            _id: poll._id,
            title: poll.title,
            body: poll.body,
            created: poll.created,
            isPublic: poll.isPublic,
            opts: null
          });
        }
      });
      $scope.cmts.forEach(function(cmt) {
        if (cmt) {
          $scope.activitys.push({
            _id: (cmt.poll) ? cmt.poll._id : null,
            title: (cmt.poll) ? cmt.poll.title : '',
            body: cmt.body,
            created: cmt.created,
            isPublic: (cmt.poll) ? cmt.poll.isPublic : false,
            opts: null
          });
        }
      });
      $scope.votes.forEach(function(vote) {
        if (vote) {
          $scope.activitys.push({
            _id: (vote.poll) ? vote.poll._id : null,
            title: (vote.poll) ? vote.poll.title : '',
            body: null,
            created: vote.created,
            isPublic: (vote.poll) ? vote.poll.isPublic : false,
            opts: vote.opts
          });
        }
      });
    }

    // $scope.isCurrentOwner = profile._id === Authentication.user._id;
    // $scope.isLogged = (Authentication.user) ? true : false;
    // $scope.page = 0;
    // init();

    // function init() {
    //   get_polls();
    // }

    // function get_polls() {
    //   UserApi.get_polls($scope.profile._id, $scope.page)
    //     .success(res => {
    //       $scope.polls = res || [];
    //     })
    //     .error(err => {
    //       alert(err);
    //     });
    // }

    // $scope.poll_filter = (poll) => {
    //   if (poll.isPublic) {
    //     return true;
    //   } else {
    //     return $scope.isCurrentOwner;
    //   }
    // };
  }
]);
<|endoftext|>


<commit_before>var _perform_ = function (aSTString){
		var theArguments = _toArray(arguments);
		theArguments.shift();
		var aJSString = _jsFunctionNameFor_(_unboxObject(aSTString));
		if(this[aJSString] !== undefined){
			return this[aJSString].apply(this, theArguments);
		} else {
			return this.doesNotUnderstand_(Message.selector_arguments_(aSTString, array(theArguments)));
		}
};

//this function is a paralleled reimplementation of S2JSqueakAstToJsAst class>>#jsFunctionNameFor:
//to avoid filling the global namespace, I wrote a function which invoked will return the right function
var _jsFunctionNameFor_ = (function (){

	var escapeCharForMethod = "_";

	var reservedWords = {
		"abstract": "", "as": "", "boolean": "", "break": "",
		"byte": "", 	"case": "", "catch": "", "char": "",
		"class": "", "continue":	"", "const": "", "debugger": "",
		"default": "", "delete": "", "do": "", "double": "",
		"else": "", "enum": "", "export": "", "extends": "",
		"false": "", "final": "", "finally": "", "float": "",
		"for": "", "function": "", "goto": "", "if": "",
		"implements": "", "import": "", "in": "", "instanceof": "",
		"int": "", "interface": "", "is": "", "long": "",
		"namespace": "", "native": "", "new": "", "null": "",
		"package": "", "private": "", "protected": "", "public": "",
		"return": "", "short": "", "static": "", "super": "",
		"switch": "", "synchronized": "", "this": "", "throw": "",
		"throws": "", "transient": "", "true": "", "try": "",
		"typeof": "", "use": "", "var": "", "void": "",
		"volatile": "", "while": "", "with": "", "arguments": "",
		"Object": "", "Function": "", "Number": "", "Array": "",
		"String": ""
	};

	var escapeReservedWord = function (aString){
			if (aString !== undefined){
				if (reservedWords[aString]){
					return escapeCharForMethod + aString;
				} else {
					return aString;
				}
			}
		};

	var characterList = function (c){
		switch(c){
			case ":": return '';
			case "+": return 'plus';
			case "-": return 'minus';
			case "*": return 'times';
			case "/": return 'slash';
			case "\\": return 'backslash';
			case "~": return 'tilde';
			case "<": return 'less';
			case ">": return 'greater';
			case "=": return 'equals';
			case "@": return 'at';
			case "%": return 'percent';
			case "&": return 'and';
			case "?": return 'question';
			case "!": return 'exclamation';
			case "`": return 'backtick';
			case ",": return 'comma';
			case "±": return 'plusminus';
			case "|": return 'pipe';
			default: return c;
	}};

	return function (aJsString){
		var result = aJsString.replace(/[:+-\/\\~<>=@%&?!`,|±]/g, function (c){
				return escapeCharForMethod + characterList(c);
			});
		return escapeReservedWord(result);
	};
})();
<commit_msg>new helper method for adding doesNotUnderstand stub to dnu class<commit_after>
var _perform_ = function (aSTString){
		var theArguments = _toArray(arguments);
		theArguments.shift();
		var aJSString = _jsFunctionNameFor_(_unboxObject(aSTString));
		if(this[aJSString] !== undefined){
			return this[aJSString].apply(this, theArguments);
		} else {
			return this.doesNotUnderstand_(Message.selector_arguments_(aSTString, array(theArguments)));
		}
};

//this function is a paralleled reimplementation of S2JSqueakAstToJsAst class>>#jsFunctionNameFor:
//to avoid filling the global namespace, I wrote a function which invoked will return the right function
var _jsFunctionNameFor_ = (function (){

	var escapeCharForMethod = "_";

	var reservedWords = {
		"abstract": "", "as": "", "boolean": "", "break": "",
		"byte": "", 	"case": "", "catch": "", "char": "",
		"class": "", "continue":	"", "const": "", "debugger": "",
		"default": "", "delete": "", "do": "", "double": "",
		"else": "", "enum": "", "export": "", "extends": "",
		"false": "", "final": "", "finally": "", "float": "",
		"for": "", "function": "", "goto": "", "if": "",
		"implements": "", "import": "", "in": "", "instanceof": "",
		"int": "", "interface": "", "is": "", "long": "",
		"namespace": "", "native": "", "new": "", "null": "",
		"package": "", "private": "", "protected": "", "public": "",
		"return": "", "short": "", "static": "", "super": "",
		"switch": "", "synchronized": "", "this": "", "throw": "",
		"throws": "", "transient": "", "true": "", "try": "",
		"typeof": "", "use": "", "var": "", "void": "",
		"volatile": "", "while": "", "with": "", "arguments": "",
		"Object": "", "Function": "", "Number": "", "Array": "",
		"String": ""
	};

	var escapeReservedWord = function (aString){
			if (aString !== undefined){
				if (reservedWords[aString]){
					return escapeCharForMethod + aString;
				} else {
					return aString;
				}
			}
		};

	var characterList = function (c){
		switch(c){
			case ":": return '';
			case "+": return 'plus';
			case "-": return 'minus';
			case "*": return 'times';
			case "/": return 'slash';
			case "\\": return 'backslash';
			case "~": return 'tilde';
			case "<": return 'less';
			case ">": return 'greater';
			case "=": return 'equals';
			case "@": return 'at';
			case "%": return 'percent';
			case "&": return 'and';
			case "?": return 'question';
			case "!": return 'exclamation';
			case "`": return 'backtick';
			case ",": return 'comma';
			case "±": return 'plusminus';
			case "|": return 'pipe';
			default: return c;
	}};

	return function (aJsString){
		var result = aJsString.replace(/[:+-\/\\~<>=@%&?!`,|±]/g, function (c){
				return escapeCharForMethod + characterList(c);
			});
		return escapeReservedWord(result);
	};
})();

// This adds a function-name, that is handled by
var _addDoesNotUnderstand = function(methodName) {
	var newMethods = {};
	newMethods[_jsFunctionNameFor_(methodName)] = function() {
		return this.doesNotUnderstand_(
			Message.selector_arguments_(string(methodName), array(_toArray(arguments)))); };
	_DoesNotUnderstandClass_._addInstanceMethods(newMethods);
}
<|endoftext|>