<commit_before>/**
 * This Source Code is licensed under the MIT license. If a copy of the
 * MIT-license was not distributed with this file, You can obtain one at:
 * http://opensource.org/licenses/mit-license.html.
 *
 * @author: Hein Rutjes (IjzerenHein)
 * @license MIT
 * @copyright Gloey Apps, 2014
 */

/*global define*/
/*eslint no-use-before-define:0 */

/**
 * FlowLayoutController transitions renderables smoothly from one
 * layout to another. When the data-source or layout is changed,
 * the renderables are transitioned from their old state (size,
 * transform, origin, etc..) to the new state.
 *
 * Inherited from: [LayoutController](./LayoutController.md)
 * @module
 */
define(function(require, exports, module) {

    // import dependencies
    var LayoutController = require('./LayoutController');
    var OptionsManager = require('famous/core/OptionsManager');
    var ViewSequence = require('famous/core/ViewSequence');
    var FlowLayoutNode = require('./FlowLayoutNode');
    var LayoutUtility = require('./LayoutUtility');
    var PhysicsEngine = require('famous/physics/PhysicsEngine');
    var Transform = require('famous/core/Transform');

    /**
     * @class
     * @extends LayoutController
     * @param {Object} options Options.
     * @param {Function} [options.layout] Layout function to use.
     * @param {Array|ViewSequence|Object} [options.dataSource] Array, ViewSequence or Object.
     * @param {Utility.Direction} [options.direction] Direction to layout into (e.g. Utility.Direction.Y) (when ommited the default direction of the layout is used)
     * @param {Number} [options.showOpacity] Opacity to use when showing renderables (default: 1)
     * @param {Spec} [options.insertSpec] Default spec to use when animating renderables into the scene (default: opacity=0)
     * @param {Spec} [options.removeSpec] Default spec to use when animating renderables out of the scene (default: opacity=0)
     * @alias module:FlowLayoutController
     */
    function FlowLayoutController(options) {
        LayoutController.call(this, options, _createLayoutNode.bind(this));

        // Set options
        this.options = Object.create(FlowLayoutController.DEFAULT_OPTIONS);
        this._optionsManager = new OptionsManager(this.options);
        if (options) {
            this.setOptions(options);
        }

        // Create physics engines
        var mainPE = new PhysicsEngine();
        this._physicsEngines = {
            opacity: mainPE,
            size: mainPE,
            align: mainPE,
            origin: mainPE,
            rotate: mainPE,
            skew: mainPE,
            scale: mainPE,
            translate: new PhysicsEngine()
        };
    }
    FlowLayoutController.prototype = Object.create(LayoutController.prototype);
    FlowLayoutController.prototype.constructor = FlowLayoutController;

    FlowLayoutController.DEFAULT_OPTIONS = {
        /*insertSpec: {
            opacity: undefined,
            size: undefined,
            transform: undefined,
            origin: undefined,
            align: undefined
        },
        removeSpec: {
            opacity: undefined,
            size: undefined,
            transform: undefined,
            origin: undefined,
            align: undefined
        }*/
    };

    /**
     * Creates a new layout-node for a render-node
     */
    function _createLayoutNode (renderNode, spec) {
        return new FlowLayoutNode(renderNode, spec || this.options.insertSpec, this._physicsEngines);
    }

    /**
     * Patches the FlowLayoutController instance's options with the passed-in ones.
     *
     * @param {Options} options An object of configurable options for the FlowLayoutController instance.
     * @param {Number} [options.showOpacity] Opacity to use when showing renderables (default: 1)
     * @param {Spec} [options.insertSpec] Default spec to use when animating renderables into the scene (default: opacity=0)
     * @param {Spec} [options.removeSpec] Default spec to use when animating renderables out of the scene (default: opacity=0)
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.setOptions = function setOptions(options) {
        this._optionsManager.setOptions(options);
        return this;
    };

    /**
     * Inserts a renderable into the data-source. If the renderable is visible
     * then it is inserted using an animation.
     *
     * @param {Number|String} indexOrId Index within dataSource array or id (String)
     * @param {Object} renderable Rendeable to add to the data-source
     * @param {Spec} [spec] Size, transform, etc.. to start with when inserting
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.insert = function(indexOrId, renderable, spec) {

        // Add the renderable in case of an id (String)
        if ((indexOrId instanceof String) || (typeof indexOrId === 'string')) {

            // Create data-source if neccesary
            if (this._dataSource === undefined) {
                this._dataSource = {};
                this._nodesById = this._dataSource._dataSource;
            }

            // Insert renderable
            this._nodesById[indexOrId] = renderable;
        }

        // Add the renderable using an index
        else {

            // Create data-source if neccesary
            if (this._dataSource === undefined) {
                this._dataSource = [];
                this._viewSequence = new ViewSequence(this._dataSource);
            }

            // Using insert in this way, only works when the data-source is an array
            if (!(this._dataSource instanceof Array)) {
                LayoutUtility.error('FlowLayoutController.insert(index) only works when the dataSource is an array');
                return this;
            }

            // Insert into array
            if (indexOrId < 0) {
                this._dataSource.push(renderable);
            }
            else {
                this._dataSource.splice(indexOrId, 0, renderable);
            }
        }

        // When a custom insert-spec was specified, store that in the layout-node
        if (spec) {
            this._nodes.insertNode(_createLayoutNode.call(this, renderable, spec));
        }

        // Force a reflow
        this._isDirty = true;

        return this;
    };

    /**
     * Removes a renderable from the data-source. If the renderable is visible
     * then it will be removed using an animation.
     *
     * @param {Number|String} indexOrId Index within dataSource array or id (String)
     * @param {Spec} [spec] Size, transform, etc.. to end with when removing
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.remove = function(indexOrId, spec) {

        // Remove the renderable in case of an id (String)
        var renderNode;
        if ((indexOrId instanceof String) || (typeof indexOrId === 'string')) {

            // Find and remove renderable from data-source
            renderNode = this._nodesById[indexOrId];
            if (renderNode) {
                delete this._nodesById[indexOrId];
            }
        }

        // Remove the renderable using an index
        else {

            // Using remove in this way, only works when the data-source is an array
            if (!(this._dataSource instanceof Array)) {
                LayoutUtility.error('FlowLayoutController.remove(index) only works when the dataSource is an array');
                return this;
            }

            // Remove from array
            renderNode = this._dataSource.splice(indexOrId, 1)[0];
        }

        // When a custom remove-spec was specified, store that in the layout-node
        if (renderNode && spec) {
            var layoutNode = this._nodes.getNodeByRenderNode(renderNode);
            if (layoutNode) {
                layoutNode.remove(spec || this.options.removeSpec);
            }
        }

        // Force a reflow
        if (renderNode) {
            this._isDirty = true;
        }

        return this;
    };

    /**
     * Apply changes from this component to the corresponding document element.
     * This includes changes to classes, styles, size, content, opacity, origin,
     * and matrix transforms.
     *
     * @private
     * @method commit
     * @param {Context} context commit context
     */
    FlowLayoutController.prototype.commit = function commit(context) {
        var transform = context.transform;
        var origin = context.origin;
        var size = context.size;
        var opacity = context.opacity;

        // When the size or layout function has changed, reflow the layout
        if (size[0] !== this._contextSizeCache[0] ||
            size[1] !== this._contextSizeCache[1] ||
            this._isDirty ||
            this._nodes._trueSizeRequested) {

            // Update state
            this._contextSizeCache[0] = size[0];
            this._contextSizeCache[1] = size[1];
            this._isDirty = false;

            // Prepare for layout
            var layoutContext = this._nodes.prepareForLayout(
                this._viewSequence,     // first node to layout
                this._nodesById, {      // so we can do fast id lookups
                    size: size,
                    direction: this._direction
                }
            );

            // Layout objects
            if (this._layout.function) {
                this._layout.function(
                    layoutContext,          // context which the layout-function can use
                    this._layout.options    // additional layout-options
                );
            }

            // Mark non-invalidated nodes for removal
            this._nodes.removeNonInvalidatedNodes(this.options.removeSpec);
        }

        // Update output
        this._commitOutput.target = this._nodes.buildSpecAndDestroyUnrenderedNodes();

        // Render child-nodes every commit
        for (var i = 0; i < this._commitOutput.target.length; i++) {
            this._commitOutput.target[i].target = this._commitOutput.target[i].renderNode.render();
        }

        // Return
        if (size) {
            transform = Transform.moveThen([-size[0]*origin[0], -size[1]*origin[1], 0], transform);
        }
        this._commitOutput.size = size;
        this._commitOutput.opacity = opacity;
        this._commitOutput.transform = transform;
        return this._commitOutput;
    };

    module.exports = FlowLayoutController;
});
<commit_msg>Fixed DEFAULT_OPTIONS from inherited class not being used<commit_after>/**
 * This Source Code is licensed under the MIT license. If a copy of the
 * MIT-license was not distributed with this file, You can obtain one at:
 * http://opensource.org/licenses/mit-license.html.
 *
 * @author: Hein Rutjes (IjzerenHein)
 * @license MIT
 * @copyright Gloey Apps, 2014
 */

/*global define*/
/*eslint no-use-before-define:0 */

/**
 * FlowLayoutController transitions renderables smoothly from one
 * layout to another. When the data-source or layout is changed,
 * the renderables are transitioned from their old state (size,
 * transform, origin, etc..) to the new state.
 *
 * Inherited from: [LayoutController](./LayoutController.md)
 * @module
 */
define(function(require, exports, module) {

    // import dependencies
    var LayoutController = require('./LayoutController');
    var OptionsManager = require('famous/core/OptionsManager');
    var ViewSequence = require('famous/core/ViewSequence');
    var FlowLayoutNode = require('./FlowLayoutNode');
    var LayoutUtility = require('./LayoutUtility');
    var PhysicsEngine = require('famous/physics/PhysicsEngine');
    var Transform = require('famous/core/Transform');

    /**
     * @class
     * @extends LayoutController
     * @param {Object} options Options.
     * @param {Function} [options.layout] Layout function to use.
     * @param {Array|ViewSequence|Object} [options.dataSource] Array, ViewSequence or Object.
     * @param {Utility.Direction} [options.direction] Direction to layout into (e.g. Utility.Direction.Y) (when ommited the default direction of the layout is used)
     * @param {Number} [options.showOpacity] Opacity to use when showing renderables (default: 1)
     * @param {Spec} [options.insertSpec] Default spec to use when animating renderables into the scene (default: opacity=0)
     * @param {Spec} [options.removeSpec] Default spec to use when animating renderables out of the scene (default: opacity=0)
     * @alias module:FlowLayoutController
     */
    function FlowLayoutController(options) {
        LayoutController.call(this, options, _createLayoutNode.bind(this));

        // Set options
        this.options = Object.create(this.constructor.DEFAULT_OPTIONS || FlowLayoutController.DEFAULT_OPTIONS);
        this._optionsManager = new OptionsManager(this.options);
        if (options) {
            this.setOptions(options);
        }

        // Create physics engines
        var mainPE = new PhysicsEngine();
        this._physicsEngines = {
            opacity: mainPE,
            size: mainPE,
            align: mainPE,
            origin: mainPE,
            rotate: mainPE,
            skew: mainPE,
            scale: mainPE,
            translate: new PhysicsEngine()
        };
    }
    FlowLayoutController.prototype = Object.create(LayoutController.prototype);
    FlowLayoutController.prototype.constructor = FlowLayoutController;

    FlowLayoutController.DEFAULT_OPTIONS = {
        /*insertSpec: {
            opacity: undefined,
            size: undefined,
            transform: undefined,
            origin: undefined,
            align: undefined
        },
        removeSpec: {
            opacity: undefined,
            size: undefined,
            transform: undefined,
            origin: undefined,
            align: undefined
        }*/
    };

    /**
     * Creates a new layout-node for a render-node
     */
    function _createLayoutNode (renderNode, spec) {
        return new FlowLayoutNode(renderNode, spec || this.options.insertSpec, this._physicsEngines);
    }

    /**
     * Patches the FlowLayoutController instance's options with the passed-in ones.
     *
     * @param {Options} options An object of configurable options for the FlowLayoutController instance.
     * @param {Number} [options.showOpacity] Opacity to use when showing renderables (default: 1)
     * @param {Spec} [options.insertSpec] Default spec to use when animating renderables into the scene (default: opacity=0)
     * @param {Spec} [options.removeSpec] Default spec to use when animating renderables out of the scene (default: opacity=0)
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.setOptions = function setOptions(options) {
        this._optionsManager.setOptions(options);
        return this;
    };

    /**
     * Inserts a renderable into the data-source. If the renderable is visible
     * then it is inserted using an animation.
     *
     * @param {Number|String} indexOrId Index within dataSource array or id (String)
     * @param {Object} renderable Rendeable to add to the data-source
     * @param {Spec} [spec] Size, transform, etc.. to start with when inserting
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.insert = function(indexOrId, renderable, spec) {

        // Add the renderable in case of an id (String)
        if ((indexOrId instanceof String) || (typeof indexOrId === 'string')) {

            // Create data-source if neccesary
            if (this._dataSource === undefined) {
                this._dataSource = {};
                this._nodesById = this._dataSource._dataSource;
            }

            // Insert renderable
            this._nodesById[indexOrId] = renderable;
        }

        // Add the renderable using an index
        else {

            // Create data-source if neccesary
            if (this._dataSource === undefined) {
                this._dataSource = [];
                this._viewSequence = new ViewSequence(this._dataSource);
            }

            // Using insert in this way, only works when the data-source is an array
            if (!(this._dataSource instanceof Array)) {
                LayoutUtility.error('FlowLayoutController.insert(index) only works when the dataSource is an array');
                return this;
            }

            // Insert into array
            if (indexOrId < 0) {
                this._dataSource.push(renderable);
            }
            else {
                this._dataSource.splice(indexOrId, 0, renderable);
            }
        }

        // When a custom insert-spec was specified, store that in the layout-node
        if (spec) {
            this._nodes.insertNode(_createLayoutNode.call(this, renderable, spec));
        }

        // Force a reflow
        this._isDirty = true;

        return this;
    };

    /**
     * Removes a renderable from the data-source. If the renderable is visible
     * then it will be removed using an animation.
     *
     * @param {Number|String} indexOrId Index within dataSource array or id (String)
     * @param {Spec} [spec] Size, transform, etc.. to end with when removing
     * @return {FlowLayoutController} this
     */
    FlowLayoutController.prototype.remove = function(indexOrId, spec) {

        // Remove the renderable in case of an id (String)
        var renderNode;
        if ((indexOrId instanceof String) || (typeof indexOrId === 'string')) {

            // Find and remove renderable from data-source
            renderNode = this._nodesById[indexOrId];
            if (renderNode) {
                delete this._nodesById[indexOrId];
            }
        }

        // Remove the renderable using an index
        else {

            // Using remove in this way, only works when the data-source is an array
            if (!(this._dataSource instanceof Array)) {
                LayoutUtility.error('FlowLayoutController.remove(index) only works when the dataSource is an array');
                return this;
            }

            // Remove from array
            renderNode = this._dataSource.splice(indexOrId, 1)[0];
        }

        // When a custom remove-spec was specified, store that in the layout-node
        if (renderNode && spec) {
            var layoutNode = this._nodes.getNodeByRenderNode(renderNode);
            if (layoutNode) {
                layoutNode.remove(spec || this.options.removeSpec);
            }
        }

        // Force a reflow
        if (renderNode) {
            this._isDirty = true;
        }

        return this;
    };

    /**
     * Apply changes from this component to the corresponding document element.
     * This includes changes to classes, styles, size, content, opacity, origin,
     * and matrix transforms.
     *
     * @private
     * @method commit
     * @param {Context} context commit context
     */
    FlowLayoutController.prototype.commit = function commit(context) {
        var transform = context.transform;
        var origin = context.origin;
        var size = context.size;
        var opacity = context.opacity;

        // When the size or layout function has changed, reflow the layout
        if (size[0] !== this._contextSizeCache[0] ||
            size[1] !== this._contextSizeCache[1] ||
            this._isDirty ||
            this._nodes._trueSizeRequested) {

            // Update state
            this._contextSizeCache[0] = size[0];
            this._contextSizeCache[1] = size[1];
            this._isDirty = false;

            // Prepare for layout
            var layoutContext = this._nodes.prepareForLayout(
                this._viewSequence,     // first node to layout
                this._nodesById, {      // so we can do fast id lookups
                    size: size,
                    direction: this._direction
                }
            );

            // Layout objects
            if (this._layout.function) {
                this._layout.function(
                    layoutContext,          // context which the layout-function can use
                    this._layout.options    // additional layout-options
                );
            }

            // Mark non-invalidated nodes for removal
            this._nodes.removeNonInvalidatedNodes(this.options.removeSpec);
        }

        // Update output
        this._commitOutput.target = this._nodes.buildSpecAndDestroyUnrenderedNodes();

        // Render child-nodes every commit
        for (var i = 0; i < this._commitOutput.target.length; i++) {
            this._commitOutput.target[i].target = this._commitOutput.target[i].renderNode.render();
        }

        // Return
        if (size) {
            transform = Transform.moveThen([-size[0]*origin[0], -size[1]*origin[1], 0], transform);
        }
        this._commitOutput.size = size;
        this._commitOutput.opacity = opacity;
        this._commitOutput.transform = transform;
        return this._commitOutput;
    };

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


<commit_before>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                var str = "";
                str += data["name"] + " is a ";
                if (data["fork"] == true) {
                    str += "forked ";
                }
                str += data["language"];
                str += " repo with ";
                str += data["open_issues"] + " unresolved issues. ";
                str += "[" + data["forks"] + "F " + data["watchers"] + "W]";

                event.reply(str);
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 1; i < 10; i++) {
                            if  ((progress / (i*10)) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
       },
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<commit_msg>attempt to add git.io to ~repo<commit_after>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                var str = "";
                str += data["name"] + " is a ";
                if (data["fork"] == true) {
                    str += "forked ";
                }
                str += data["language"];
                str += " repo with ";
                str += data["open_issues"] + " unresolved issues. ";
                str += "[" + data["forks"] + "F " + data["watchers"] + "W]";

                // TODO: move this shizz into an api call
                var longurl = "http://github.com/" + repo;
                request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                    str += " " + response.headers["location"];
                };
                event.reply(str);
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 1; i < 10; i++) {
                            if  ((progress / (i*10)) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
       },
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var markdown = require('node-markdown').Markdown;

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    modules: '', //to be filled in by find-modules task
    tplModules: '', //to be filled in by find-templates task
    ngversion: '1.0.4',
    pkg:'<json:package.json>',
    meta: {
      modules: 'angular.module("ui.bootstrap", [<%= modules %>]);',
      tplmodules: 'angular.module("ui.bootstrap.tpls", [<%= tplModules %>]);',
      all: 'angular.module("ui.bootstrap", ["ui.bootstrap.tpls", <%= modules %>]);'
    },
    lint: {
      files: ['grunt.js','src/**/*.js']
    },
    watch: {
      files: ['<config:lint.files>', 'template/**/*.html'],
      tasks: 'before-test test-run'
    },
    concat: {
      dist: {
        src: ['<banner:meta.modules>', 'src/*/*.js'],
        dest: 'dist/ui-bootstrap-<%= pkg.version %>.js'
      },
      dist_tpls: {
        src: ['<banner:meta.all>', 'src/*/*.js', '<banner:meta.tplmodules>', 'template/**/*.html.js'],
        dest: 'dist/ui-bootstrap-tpls-<%= pkg.version %>.js'
      }
    },
    min: {
      dist:{
        src:['dist/ui-bootstrap-<%= pkg.version %>.js'],
        dest:'dist/ui-bootstrap-<%= pkg.version %>.min.js'
      },
      dist_tpls:{
        src:['dist/ui-bootstrap-tpls-<%= pkg.version %>.js'],
        dest:'dist/ui-bootstrap-tpls-<%= pkg.version %>.min.js'
      }
    },
    html2js: {
      src: ['template/**/*.html']
    },
    jshint: {
      options: {
        curly: true,
        immed: true,
        newcap: true,
        noarg: true,
        sub: true,
        boss: true,
        eqnull: true
      },
      globals: {}
    }
  });

  //register before and after test tasks so we've don't have to change cli options on the goole's CI server
  grunt.registerTask('before-test', 'lint html2js');
  grunt.registerTask('after-test', 'find-modules find-templates concat min site');

  // Default task.
  grunt.registerTask('default', 'before-test test after-test');

  //Common ui.bootstrap module containing all modules
  grunt.registerTask('find-modules', 'Generate ui.bootstrap module depending on all existing directives', function() {
    var modules = grunt.file.expandDirs('src/*').map(function(dir) {
      return '"ui.bootstrap.' + dir.split("/")[1] + '"';
    });
    grunt.config('modules', modules);
  });

  grunt.registerTask('find-templates', 'Generate template modules depending on all existing directives', function() {
    var tplModules = grunt.file.expand('template/**/*.html').map(function(file) {
       return '"'+file+'"';
    });
    grunt.config('tplModules', tplModules);
  });

  grunt.registerTask('site', 'Create grunt demo site from every module\'s files', function() {
    this.requires('find-modules concat html2js');

    function breakup(text, separator) {
      return text.replace(/[A-Z]/g, function (match) {
        return separator + match;
      });
    }

    function ucwords(text) {
      return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
      });
    }

    var modules = grunt.file.expandDirs('src/*').map(function(dir) {

      var moduleName = dir.split("/")[1];
      if (fs.existsSync(dir + "docs")) {
        return {
          name: moduleName,
          displayName: ucwords(breakup(moduleName, ' ')),
          js: grunt.file.expand(dir + "docs/*.js").map(grunt.file.read).join(''),
          html: grunt.file.expand(dir + "docs/*.html").map(grunt.file.read).join(''),
          description: grunt.file.expand(dir + "docs/*.md").map(grunt.file.read).map(markdown).join('')
        };
      }
    }).filter(function(module){
       return module !== undefined;
    });

    var templateFiles = grunt.file.expand("template/**/*.html.js");

    grunt.file.write(
      'dist/index.html',
      grunt.template.process(grunt.file.read('misc/demo-template.html'), {
        modules: modules,
        templateModules: templateFiles.map(function(fileName) {
          return "'"+fileName.substr(0, fileName.length - 3)+"'";
        }),
        templates: templateFiles.map(grunt.file.read).join(''),
        version : grunt.config('pkg.version'),
        ngversion: grunt.config('ngversion')
      })
    );

    grunt.file.expand('misc/demo-assets/*.*').forEach(function(path) {
      grunt.file.copy(path, 'dist/assets/' + path.replace('misc/demo-assets/',''));
    });

    grunt.file.expand('misc/demo-assets/img/*.*').forEach(function(path) {
      grunt.file.copy(path, 'dist/' + path.replace('misc/demo-assets/',''));
    });
  });

  //Html templates to $templateCache for tests
  grunt.registerMultiTask('html2js', 'Generate js versions of html template', function() {
    //Put templates on ng's run function so they are global
    var TPL='angular.module("<%= file %>", []).run(["$templateCache", function($templateCache){\n' +
      '  $templateCache.put("<%= file %>",\n    "<%= content %>");\n' +
      '}]);\n';
    var files = grunt._watch_changed_files || grunt.file.expand(this.data);

    function escapeContent(content) {
      return content.replace(/"/g, '\\"').replace(/\n/g, '" +\n    "').replace(/\r/g, '');
    }
    files.forEach(function(file) {
      grunt.file.write(file + ".js", grunt.template.process(TPL, {
            file: file,
            content: escapeContent(grunt.file.read(file))
      }));
    });
  });

  // Testacular configuration
  function runTestacular(command, options) {
    var testacularCmd = process.platform === 'win32' ? 'testacular.cmd' : 'testacular';
    var args = [command].concat(options);
    var done = grunt.task.current.async();
    var child = grunt.utils.spawn({
        cmd: testacularCmd,
        args: args
    }, function(err, result, code) {
      if (code) {
        done(false);
      } else {
        done();
      }
    });
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
  }

  grunt.registerTask('test', 'run tests on single-run server', function() {
    var options = ['--single-run', '--no-auto-watch', '--log-level=warn'];
    if (process.env.TRAVIS) {
      options =  options.concat(['--browsers=Firefox']);
    } else {
      //Can augment options with command line arguments
      options =  options.concat(this.args);
    }
    runTestacular('start', options);
  });

  grunt.registerTask('server', 'start testacular server', function() {
    var options = ['--no-single-run', '--no-auto-watch'].concat(this.args);
    runTestacular('start', options);
  });

  grunt.registerTask('test-run', 'run tests against continuous testacular server', function() {
    var options = ['--single-run', '--no-auto-watch'].concat(this.args);
    runTestacular('run', options);
  });

  grunt.registerTask('test-watch', 'start testacular server, watch & execute tests', function() {
    var options = ['--no-single-run', '--auto-watch'].concat(this.args);
    runTestacular('start', options);
  });
  };
<commit_msg>demo(*): Add dist and build task, allowing custom builds<commit_after>var fs = require('fs');
var markdown = require('node-markdown').Markdown;

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    ngversion: '1.0.4',
    srcModules: [], //to be filled in by find-modules task
    tplModules: [],
    pkg:'<json:package.json>',
    dist: 'dist',
    filename: 'ui-bootstrap',
    meta: {
      modules: 'angular.module("ui.bootstrap", [<%= srcModules %>]);',
      tplmodules: 'angular.module("ui.bootstrap.tpls", [<%= tplModules %>]);',
      all: 'angular.module("ui.bootstrap", ["ui.bootstrap.tpls", <%= srcModules %>]);'
    },
    lint: {
      files: ['grunt.js','src/**/*.js']
    },
    watch: {
      files: ['<config:lint.files>', 'template/**/*.html'],
      tasks: 'before-test test-run'
    },
    concat: {
      dist: {
        src: ['<banner:meta.modules>'],
        dest: '<%= dist %>/<%= filename %>-<%= pkg.version %>.js'
      },
      dist_tpls: {
        src: ['<banner:meta.all>', '<banner:meta.tplmodules>'],
        dest: '<%= dist %>/<%= filename %>-tpls-<%= pkg.version %>.js'
      }
    },
    min: {
      dist:{
        src:['<%= dist %>/<%= filename %>-<%= pkg.version %>.js'],
        dest:'<%= dist %>/<%= filename %>-<%= pkg.version %>.min.js'
      },
      dist_tpls:{
        src:['<%= dist %>/<%= filename %>-tpls-<%= pkg.version %>.js'],
        dest:'<%= dist %>/<%= filename %>-tpls-<%= pkg.version %>.min.js'
      }
    },
    html2js: {
      src: ['template/**/*.html']
    },
    jshint: {
      options: {
        curly: true,
        immed: true,
        newcap: true,
        noarg: true,
        sub: true,
        boss: true,
        eqnull: true
      },
      globals: {}
    }
  });

  //register before and after test tasks so we've don't have to change cli options on the goole's CI server
  grunt.registerTask('before-test', 'lint html2js');
  grunt.registerTask('after-test', 'find-modules build site');

  // Default task.
  grunt.registerTask('default', 'before-test test after-test');

  //Common ui.bootstrap module containing all modules for src and templates
  //findModule: Adds a given module to config
  function findModule(name) {
    function enquote(str) {
      return '"' + str + '"';
    }
    var tplModules = grunt.config('tplModules');
    var srcModules = grunt.config('srcModules');

    grunt.file.expand('template/' + name + '/*.html').map(function(file) {
      tplModules.push(enquote(file));
    });
    grunt.file.expand('src/' + name + '/*.js').forEach(function(file) {
      srcModules.push(enquote('ui.bootstrap.' + name));
    });

    grunt.config('tplModules', tplModules);
    grunt.config('srcModules', srcModules);
  }
  grunt.registerTask('find-modules', 'Generate ui.bootstrap and template modules depending on all existing directives', function() {
    grunt.file.expandDirs('src/*').forEach(function(dir) {
      findModule(dir.split('/')[1]);
    });
  });

  grunt.registerTask('dist', 'Override dist directory', function() {
    var dir = this.args[0];
    if (dir) { grunt.config('dist', dir); }
  });

  function dependenciesForModule(name) {
    var deps = [];
    grunt.file.expand('src/' + name + '/*.js')
    .map(grunt.file.read)
    .forEach(function(contents) {
      //Strategy: find where module is declared,
      //and from there get everything inside the [] and split them by comma
      var moduleDeclIndex = contents.indexOf('angular.module(');
      var depArrayStart = contents.indexOf('[', moduleDeclIndex);
      var depArrayEnd = contents.indexOf(']', depArrayStart);
      var dependencies = contents.substring(depArrayStart + 1, depArrayEnd);
      dependencies.split(',').forEach(function(dep) {
        if (dep.indexOf('ui.bootstrap.') > -1) {
          var depName = dep.trim().replace('ui.bootstrap.','').replace(/['"]/g,'');
          if (deps.indexOf(depName) < 0) {
            deps.push(depName);
            //Get dependencies for this new dependency
            deps = deps.concat(dependenciesForModule(depName));
          }
        }
      });
    });
    return deps;
  }
  grunt.registerTask('build', 'Create bootstrap build files', function() {
    var srcFiles = [], tplFiles = [];
    if (this.args.length) {
      var modules = [].concat(this.args);
      //Find dependencies
      this.args.forEach(function(name) {
        modules = modules.concat(dependenciesForModule(name));
      });
      srcFiles = modules.map(function(name) {
        return 'src/' + name + '/*.js';
      });
      tplFiles = modules.map(function(name) {
        grunt.file.expand('template/' + name + '/*.html').forEach(html2js);
        return 'template/' + name + '/*.html.js';
      });
      grunt.config('filename', grunt.config('filename')+'-custom');
    } else {
      srcFiles = ['src/*/*.js'];
      tplFiles = ['template/*/*.html.js'];
    }
    grunt.config('concat.dist.src',
                 grunt.config('concat.dist.src').concat(srcFiles));
    grunt.config('concat.dist_tpls.src',
                 grunt.config('concat.dist_tpls.src').concat(srcFiles).concat(tplFiles));
    grunt.task.run('concat min');
  });

  grunt.registerTask('site', 'Create grunt demo site from every module\'s files', function() {
    this.requires('find-modules concat html2js');

    function breakup(text, separator) {
      return text.replace(/[A-Z]/g, function (match) {
        return separator + match;
      });
    }

    function ucwords(text) {
      return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
      });
    }

    var modules = grunt.file.expandDirs('src/*').map(function(dir) {
      var moduleName = dir.split("/")[1];
      if (fs.existsSync(dir + "docs")) {
        return {
          name: moduleName,
          displayName: ucwords(breakup(moduleName, ' ')),
          js: grunt.file.expand(dir + "docs/*.js").map(grunt.file.read).join(''),
          html: grunt.file.expand(dir + "docs/*.html").map(grunt.file.read).join(''),
          description: grunt.file.expand(dir + "docs/*.md").map(grunt.file.read).map(markdown).join('')
        };
      }
    }).filter(function(module){
       return module !== undefined;
    });

    var templateFiles = grunt.file.expand("template/**/*.html.js");

    grunt.file.write(
      'dist/index.html',
      grunt.template.process(grunt.file.read('misc/demo-template.html'), {
        modules: modules,
        templateModules: templateFiles.map(function(fileName) {
          return "'"+fileName.substr(0, fileName.length - 3)+"'";
        }),
        templates: templateFiles.map(grunt.file.read).join(''),
        version : grunt.config('pkg.version'),
        ngversion: grunt.config('ngversion')
      })
    );

    grunt.file.expand('misc/demo-assets/*.*').forEach(function(path) {
      grunt.file.copy(path, 'dist/assets/' + path.replace('misc/demo-assets/',''));
    });

    grunt.file.expand('misc/demo-assets/img/*.*').forEach(function(path) {
      grunt.file.copy(path, 'dist/' + path.replace('misc/demo-assets/',''));
    });
  });

  //Html templates to $templateCache for tests
  var TPL='angular.module("<%= file %>", []).run(["$templateCache", function($templateCache){\n' +
    '  $templateCache.put("<%= file %>",\n    "<%= content %>");\n' +
    '}]);\n';
  function escapeContent(content) {
    return content.replace(/"/g, '\\"').replace(/\n/g, '" +\n    "').replace(/\r/g, '');
  }
  function html2js(template) {
    grunt.file.write(template + ".js", grunt.template.process(TPL, {
      file: template,
      content: escapeContent(grunt.file.read(template))
    }));
  }
  grunt.registerMultiTask('html2js', 'Generate js versions of html template', function() {
    var files = grunt._watch_changed_files || grunt.file.expand(this.data);
    files.forEach(html2js);
  });

  // Testacular configuration
  function runTestacular(command, options) {
    var testacularCmd = process.platform === 'win32' ? 'testacular.cmd' : 'testacular';
    var args = [command].concat(options);
    var done = grunt.task.current.async();
    var child = grunt.utils.spawn({
        cmd: testacularCmd,
        args: args
    }, function(err, result, code) {
      if (code) {
        done(false);
      } else {
        done();
      }
    });
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
  }

  grunt.registerTask('test', 'run tests on single-run server', function() {
    var options = ['--single-run', '--no-auto-watch', '--log-level=warn'];
    if (process.env.TRAVIS) {
      options =  options.concat(['--browsers=Firefox']);
    } else {
      //Can augment options with command line arguments
      options =  options.concat(this.args);
    }
    runTestacular('start', options);
  });

  grunt.registerTask('server', 'start testacular server', function() {
    var options = ['--no-single-run', '--no-auto-watch'].concat(this.args);
    runTestacular('start', options);
  });

  grunt.registerTask('test-run', 'run tests against continuous testacular server', function() {
    var options = ['--single-run', '--no-auto-watch'].concat(this.args);
    runTestacular('run', options);
  });

  grunt.registerTask('test-watch', 'start testacular server, watch & execute tests', function() {
    var options = ['--no-single-run', '--auto-watch'].concat(this.args);
    runTestacular('start', options);
  });

  return grunt;
};
<|endoftext|>


<commit_before>myApp.service('ReportingService', function ($http, $firebaseAuth) {
    const sv = this;
    const auth = $firebaseAuth();
    const database = firebase.database();

    // sv.report = {};
    sv.currentStudent = {
        data: ''
    };
    sv.studiedWords = [];
    sv.wordObj = {
        studentName: sv.currentStudent.data,
        word: '',
        totalAttempts: 0,
        satisfactory: 0,
        prompt: 0,
        unsatisfactory: 0
    };

    sv.opportunityReport = function (studyWord, outcome) {
        // console.log('logging word, student, and outcome -> ', studyWord, sv.currentStudent.data, outcome);
        sv.wordObj.studentName = sv.currentStudent.data;
        sv.wordObj.word = studyWord;
        sv.wordObj.totalAttempts++;
        if (sv.studyWord == sv.studiedWords.data) {
            // console.log('loggin studiedWords[i] -> ', sv.studiedWords[i].word);

            if (outcome === 'satisfactory') {
                sv.wordObj.satisfactory++;
            } else if (outcome === 'prompted') {
                sv.wordObj.prompt++;
            } else if (outcome === 'unsatisfactory') {
                sv.wordObj.unsatisfactory++;
            } else {
                console.log('Not a match in studyword index -> ', i);
            }
        }
        for (let i = 0; i < sv.studiedWords.length; i++) {
            console.log('running for loop');

        }

        // push wordObj into array if it's a new word, otherwise update existing word within array.

        if (sv.studiedWords.length === 0){
            sv.studiedWords.push(sv.wordObj);
        } else {
            for (i=0;i<sv.studiedWords.length;i++) {
                if (sv.studiedWords[i].word === studyWord){
                    sv.studiedWords.splice(index,1, sv.wordObj);
                    // sv.studiedWords.push(sv.wordObj);
                }
            }
        }

    console.log('Studied Words in reporting service -> ', sv.studiedWords);
    };

    // // outcome logic
    // if (outcome === 'satisfactory') {
    //     sv.wordObj.satisfactory++;
    // } else if (outcome === 'prompted') {
    //     sv.wordObj.prompt++;
    // } else if (outcome === 'unsatisfactory') {
    //     sv.wordObj.unsatisfactory++;
    // } else {
    //     console.log('Error logging outcome in reporting.service.js');
    // }

    // console.log('wordObj in reporting service -> ', sv.wordObj);

    // // pushing logic
    // sv.studiedWords.push(sv.wordObj);
    // console.log('Studied Words in reporting service -> ', sv.studiedWords);

// };

sv.studentTracker = function (name) {
    console.log('logging student name', name.name);
    sv.currentStudent.data = name.name;
};

});<commit_msg>put teacher UID into object to send to db.<commit_after>myApp.service('ReportingService', function ($http, $firebaseAuth) {
    const sv = this;
    const auth = $firebaseAuth();
    const database = firebase.database();

    // sv.report = {};
    sv.currentStudent = {
        data: ''
    };
    sv.studiedWords = [];
    sv.wordObj = {
        instructor: '',
        studentName: sv.currentStudent.data,
        word: '',
        totalAttempts: 0,
        satisfactory: 0,
        prompt: 0,
        unsatisfactory: 0
    };

    sv.opportunityReport = function (studyWord, outcome) {
        // console.log('logging word, student, and outcome -> ', studyWord, sv.currentStudent.data, outcome);
        sv.wordObj.instructor = firebase.auth().currentUser.uid;
        sv.wordObj.studentName = sv.currentStudent.data;
        sv.wordObj.word = studyWord;
        sv.wordObj.totalAttempts++;
        if (sv.studyWord == sv.studiedWords.data) {
            // console.log('loggin studiedWords[i] -> ', sv.studiedWords[i].word);

            if (outcome === 'satisfactory') {
                sv.wordObj.satisfactory++;
            } else if (outcome === 'prompted') {
                sv.wordObj.prompt++;
            } else if (outcome === 'unsatisfactory') {
                sv.wordObj.unsatisfactory++;
            } else {
                console.log('Not a match in studyword index -> ', i);
            }
        }
        for (let i = 0; i < sv.studiedWords.length; i++) {
            console.log('running for loop');

        }

        // push wordObj into array if it's a new word, otherwise update existing word within array.

        if (sv.studiedWords.length === 0){
            sv.studiedWords.push(sv.wordObj);
        } else {
            for (i=0;i<sv.studiedWords.length;i++) {
                if (sv.studiedWords[i].word === studyWord){
                    sv.studiedWords.splice(index,1, sv.wordObj);
                    // sv.studiedWords.push(sv.wordObj);
                }
            }
        }

    console.log('Studied Words in reporting service -> ', sv.studiedWords);
    };

    // // outcome logic
    // if (outcome === 'satisfactory') {
    //     sv.wordObj.satisfactory++;
    // } else if (outcome === 'prompted') {
    //     sv.wordObj.prompt++;
    // } else if (outcome === 'unsatisfactory') {
    //     sv.wordObj.unsatisfactory++;
    // } else {
    //     console.log('Error logging outcome in reporting.service.js');
    // }

    // console.log('wordObj in reporting service -> ', sv.wordObj);

    // // pushing logic
    // sv.studiedWords.push(sv.wordObj);
    // console.log('Studied Words in reporting service -> ', sv.studiedWords);

// };

sv.studentTracker = function (name) {
    console.log('logging student name', name.name);
    sv.currentStudent.data = name.name;
};

});<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Oct 05 2013 22:00:14 GMT+0700 (ICT)

module.exports = function(config) {
    config.set({

        // base path, that will be used to resolve files and exclude
        basePath: '../../',

        // frameworks to use
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'public/lib/angular/angular.js',
            'public/lib/angular-mocks/angular-mocks.js',
            'public/lib/angular-cookies/angular-cookies.js',
            'public/lib/angular-resource/angular-resource.js',
            'public/lib/angular-route/angular-route.js',
            'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
            'public/lib/angular-bootstrap/ui-bootstrap.js',
            'public/lib/angular-ui-utils/modules/route/route.js',
            'public/js/app.js',
            'public/js/config.js',
            'public/js/directives.js',
            'public/js/filters.js',
            'public/js/services/global.js',
            'public/js/services/articles.js',
            'public/js/controllers/articles.js',
            'public/js/controllers/index.js',
            'public/js/controllers/header.js',
            'public/js/init.js',
            'test/karma/unit/**/*.js'
        ],

        // list of files to exclude
        exclude: [

        ],

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        //reporters: ['progress'],
        reporters: ['progress', 'coverage'],

        // coverage
        preprocessors: {
            // source files, that you wanna generate coverage for
            // do not include tests or libraries
            // (these files will be instrumented by Istanbul)
            'public/js/controllers/*.js': ['coverage'],
            'public/js/services/*.js': ['coverage']
        },

        coverageReporter: {
            type: 'html',
            dir: 'test/coverage/'
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['PhantomJS'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};<commit_msg>Fixing Travis Stall<commit_after>// Karma configuration
// Generated on Sat Oct 05 2013 22:00:14 GMT+0700 (ICT)

module.exports = function(config) {
    config.set({

        // base path, that will be used to resolve files and exclude
        basePath: '../../',

        // frameworks to use
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'public/lib/angular/angular.js',
            'public/lib/angular-mocks/angular-mocks.js',
            'public/lib/angular-cookies/angular-cookies.js',
            'public/lib/angular-resource/angular-resource.js',
            'public/lib/angular-route/angular-route.js',
            'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
            'public/lib/angular-bootstrap/ui-bootstrap.js',
            'public/lib/angular-ui-utils/modules/route/route.js',
            'public/js/app.js',
            'public/js/config.js',
            'public/js/directives.js',
            'public/js/filters.js',
            'public/js/services/global.js',
            'public/js/services/articles.js',
            'public/js/controllers/articles.js',
            'public/js/controllers/index.js',
            'public/js/controllers/header.js',
            'public/js/init.js',
            'test/karma/unit/**/*.js'
        ],

        // list of files to exclude
        exclude: [

        ],

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        //reporters: ['progress'],
        reporters: ['progress', 'coverage'],

        // coverage
        preprocessors: {
            // source files, that you wanna generate coverage for
            // do not include tests or libraries
            // (these files will be instrumented by Istanbul)
            'public/js/controllers/*.js': ['coverage'],
            'public/js/services/*.js': ['coverage']
        },

        coverageReporter: {
            type: 'html',
            dir: 'test/coverage/'
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['PhantomJS'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: true
    });
};<|endoftext|>


<commit_before>import Ember from 'ember';
import AjaxPromise from '../utils/ajax-promise';
import config from '../config/environment';
import preloadDataMixin from '../mixins/preload_data';
const { getOwner } = Ember;

export default Ember.Route.extend(preloadDataMixin, {
  cordova: Ember.inject.service(),
  i18n: Ember.inject.service(),
  isErrPopUpAlreadyShown: false,
  isOfflineErrAlreadyShown: false,
  logger: Ember.inject.service(),
  messageBox: Ember.inject.service(),

  _loadDataStore: function(){
    return this.preloadData(true).catch(error => {
      if (error.status === 0 || (error.errors && error.errors[0].status === "0")) {
        this.transitionTo("offline");
      } else {
        this.handleError(error);
      }
    }).finally(() => {
      // don't know why but placing this before preloadData on iPhone 6 causes register_device request to fail with status 0
      if (this.session.get('isLoggedIn')) {
        this.get("cordova").appLoad();
      }
    });
  },

  init() {
    var _this = this;
    var storageHandler = function (object) {
      if(!window.localStorage.getItem('authToken')) {
          window.location.reload();
      }
    };
    window.addEventListener("storage", function() {
      storageHandler(_this);
    }, false);
  },

  beforeModel(transition = []) {
    var language;
    try {
      window.localStorage.test = "isSafariPrivateBrowser";
    } catch (e) {
      this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError"));
    }
    window.localStorage.removeItem('test');
    if (transition.queryParams.ln) {
      language = transition.queryParams.ln === "zh-tw" ? "zh-tw" : "en";
      this.set('session.language', language);
    }

    language = this.session.get("language") || "en";
    moment.locale(language);
    this.set("i18n.locale", language);

    Ember.onerror = window.onerror = error => this.handleError(error);
    return this._loadDataStore();
  },

  afterModel() {
    if(this.get("session.isAdminApp")) {
      this.loadStaticData(true).catch(error => {
        if (error.status === 0 || (error.errors && error.errors[0].status === "0")) {
          this.transitionTo("offline");
        } else {
          this.handleError(error);
        }
      });
    }
  },

  renderTemplate() {
    this.render(); // default template

    this.render('notifications', {   // the template to render
      into: 'application',      // the template to render into
      outlet: 'notifications', // the name of the outlet in that template
      controller: 'notifications'   // the controller to use for the template
    });

    if(this.get("session.isAdminApp")){
      this.render('notification_link', {
        into: 'application',
        outlet: 'notification_link',
        controller: 'notification_link'
      });

      this.render('internet_call_status', {
        into: 'application',
        outlet: 'internet_call_status',
        controller: 'internet_call_status'
      });
    }
  },

  offlineError(reason){
    if(!this.get('isOfflineErrAlreadyShown')) {
      this.set('isOfflineErrAlreadyShown', true);
      this.get("messageBox").alert(this.get("i18n").t("offline_error"), () => {
        this.set('isOfflineErrAlreadyShown', false);
      });
      if(!reason.isAdapterError){
        this.get("logger").error(reason);
      }
    }
  },

  quotaExceededError(reason){
    this.get("logger").error(reason);
    this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError"));
  },

  handleError: function(reason) {
    try
    {
      var status;
      try { status = parseInt(reason.errors[0].status, 10); }
      catch (err) { status = reason.status; }

      if(!window.navigator.onLine){
        this.offlineError(reason);
      } else if(reason.name === "QuotaExceededError") {
        this.quotaExceededError(reason);
      } else if (status === 401) {
        if (this.session.get('isLoggedIn')) {
          this.controllerFor("application").send('logMeOut');
        }
      } else if ([403, 404].indexOf(status) >= 0) {
        this.get("logger").error(reason);
        this.get("messageBox").alert(this.get("i18n").t(status+"_error"));
      } else if (status === 0) {
        // status 0 means request was aborted, this could be due to connection failure
        // but can also mean request was manually cancelled
        this.get("messageBox").alert(this.get("i18n").t("offline_error"));
      } else {
        this.get("logger").error(reason);
        if(!this.get('isErrPopUpAlreadyShown')) {
          this.set('isErrPopUpAlreadyShown', true);
          this.get("messageBox").alert(this.get("i18n").t("unexpected_error"), () => {
            this.set('isErrPopUpAlreadyShown', false);
          });
        }
      }
    } catch (err) {
      console.log(err);
    }
  },

  actions: {
    setLang(language) {
      this.session.set("language", language);
      window.location.reload();
    },
    loading() {
      Ember.$(".loading-indicator").remove();
      var view = getOwner(this).lookup('component:loading').append();
      this.router.one('didTransition', view, 'destroy');
    },
    // this is hopefully only triggered from promises from routes
    // so in this scenario redirect to home for 404
    error(reason) {
      try {
        var errorStatus = parseInt(reason.status || reason.errors && reason.errors[0].status, 10)
        if ([403, 404].indexOf(errorStatus) >= 0) {
          this.get("messageBox").alert(this.get("i18n").t(errorStatus+"_error"), () => this.transitionTo("/"));
        } else {
          this.handleError(reason);
        }
      } catch (err) {
        console.log(err);
      }
    },

    willTransition(transition) {
      Ember.run.next(function() {
        // before transitioning close all foundation-dialog box
        Ember.$(".reveal-modal").foundation("reveal", "close");

        // remove joyride-popup if not assigned for page
        if($(".joyride-list").length === 0) {
          Ember.$('.joyride-tip-guide').remove();
        }
      });
    }
  }
});
<commit_msg>fix codeclimate issue in application handleError<commit_after>import Ember from 'ember';
import AjaxPromise from '../utils/ajax-promise';
import config from '../config/environment';
import preloadDataMixin from '../mixins/preload_data';
const { getOwner } = Ember;

export default Ember.Route.extend(preloadDataMixin, {
  cordova: Ember.inject.service(),
  i18n: Ember.inject.service(),
  isErrPopUpAlreadyShown: false,
  isOfflineErrAlreadyShown: false,
  logger: Ember.inject.service(),
  messageBox: Ember.inject.service(),

  _loadDataStore: function(){
    return this.preloadData(true).catch(error => {
      if (error.status === 0 || (error.errors && error.errors[0].status === "0")) {
        this.transitionTo("offline");
      } else {
        this.handleError(error);
      }
    }).finally(() => {
      // don't know why but placing this before preloadData on iPhone 6 causes register_device request to fail with status 0
      if (this.session.get('isLoggedIn')) {
        this.get("cordova").appLoad();
      }
    });
  },

  init() {
    var _this = this;
    var storageHandler = function (object) {
      if(!window.localStorage.getItem('authToken')) {
          window.location.reload();
      }
    };
    window.addEventListener("storage", function() {
      storageHandler(_this);
    }, false);
  },

  beforeModel(transition = []) {
    var language;
    try {
      window.localStorage.test = "isSafariPrivateBrowser";
    } catch (e) {
      this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError"));
    }
    window.localStorage.removeItem('test');
    if (transition.queryParams.ln) {
      language = transition.queryParams.ln === "zh-tw" ? "zh-tw" : "en";
      this.set('session.language', language);
    }

    language = this.session.get("language") || "en";
    moment.locale(language);
    this.set("i18n.locale", language);

    Ember.onerror = window.onerror = error => this.handleError(error);
    return this._loadDataStore();
  },

  afterModel() {
    if(this.get("session.isAdminApp")) {
      this.loadStaticData(true).catch(error => {
        if (error.status === 0 || (error.errors && error.errors[0].status === "0")) {
          this.transitionTo("offline");
        } else {
          this.handleError(error);
        }
      });
    }
  },

  renderTemplate() {
    this.render(); // default template

    this.render('notifications', {   // the template to render
      into: 'application',      // the template to render into
      outlet: 'notifications', // the name of the outlet in that template
      controller: 'notifications'   // the controller to use for the template
    });

    if(this.get("session.isAdminApp")){
      this.render('notification_link', {
        into: 'application',
        outlet: 'notification_link',
        controller: 'notification_link'
      });

      this.render('internet_call_status', {
        into: 'application',
        outlet: 'internet_call_status',
        controller: 'internet_call_status'
      });
    }
  },

  offlineError(reason){
    if(!this.get('isOfflineErrAlreadyShown')) {
      this.set('isOfflineErrAlreadyShown', true);
      this.get("messageBox").alert(this.get("i18n").t("offline_error"), () => {
        this.set('isOfflineErrAlreadyShown', false);
      });
      if(!reason.isAdapterError){
        this.get("logger").error(reason);
      }
    }
  },

  quotaExceededError(reason){
    this.get("logger").error(reason);
    this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError"));
  },

  somethingWentWrong(reason) {
    this.get("logger").error(reason);
    if(!this.get('isErrPopUpAlreadyShown')) {
      this.set('isErrPopUpAlreadyShown', true);
      this.get("messageBox").alert(this.get("i18n").t("unexpected_error"), () => {
        this.set('isErrPopUpAlreadyShown', false);
      });
    }
  },

  quotaExceededError(reason) {
    this.get("logger").error(reason);
    this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError"));
  },

  notFoundError(reason) {
    this.get("logger").error(reason);
    this.get("messageBox").alert(this.get("i18n").t(status+"_error"));
  },

  unauthorizedError() {
    if (this.session.get('isLoggedIn')) {
      this.controllerFor("application").send('logMeOut');
    }
  },

  handleError: function(reason) {
    try
    {
      var status;
      try { status = parseInt(reason.errors[0].status, 10); }
      catch (err) { status = reason.status; }

      if(!window.navigator.onLine){
        this.offlineError(reason);
      } else if(reason.name === "QuotaExceededError") {
        this.quotaExceededError(reason);
      } else if (status === 401) {
        this.unauthorizedError();
      } else if ([403, 404].indexOf(status) >= 0) {
        this.notFoundError(reason);
      } else if (status === 0) {
        // status 0 means request was aborted, this could be due to connection failure
        // but can also mean request was manually cancelled
        this.get("messageBox").alert(this.get("i18n").t("offline_error"));
      } else {
        this.somethingWentWrong(reason);
      }
    } catch (err) {
      console.log(err);
    }
  },

  actions: {
    setLang(language) {
      this.session.set("language", language);
      window.location.reload();
    },
    loading() {
      Ember.$(".loading-indicator").remove();
      var view = getOwner(this).lookup('component:loading').append();
      this.router.one('didTransition', view, 'destroy');
    },
    // this is hopefully only triggered from promises from routes
    // so in this scenario redirect to home for 404
    error(reason) {
      try {
        var errorStatus = parseInt(reason.status || reason.errors && reason.errors[0].status, 10)
        if ([403, 404].indexOf(errorStatus) >= 0) {
          this.get("messageBox").alert(this.get("i18n").t(errorStatus+"_error"), () => this.transitionTo("/"));
        } else {
          this.handleError(reason);
        }
      } catch (err) {
        console.log(err);
      }
    },

    willTransition(transition) {
      Ember.run.next(function() {
        // before transitioning close all foundation-dialog box
        Ember.$(".reveal-modal").foundation("reveal", "close");

        // remove joyride-popup if not assigned for page
        if($(".joyride-list").length === 0) {
          Ember.$('.joyride-tip-guide').remove();
        }
      });
    }
  }
});
<|endoftext|>


<commit_before>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var jsonParse = require('json-stream')
  , through = require('through2')
  , co = require('co')
  , vdom = require('virtual-dom')
  , h = vdom.h
  , Backbone = require('backbone')

module.exports = setup
module.exports.consumes = ['ui', 'editor']
function setup(plugin, imports, register) {
  var ui = imports.ui

  var link = document.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('href', 'static/hive-plugin-presence/css/index.css')
  document.head.appendChild(link)

  ui.page('/:id', function(ctx, next) {
    var broadcast = ctx.broadcast.createDuplexStream(new Buffer('presence'))
      , users = new (Backbone.Collection.extend({model: ctx.models.user}))()

    broadcast.pipe(jsonParse()).pipe(through.obj(function(list, enc, cb) {
      // Update models
      users.set(Object.keys(list).map(function(userId) {return list[userId]}))
      cb()
    }))

    var tree = render()
      , root = vdom.create(tree)
    document.body.insertBefore(root, document.body.firstChild)

    users.on('add remove change', function() {
      // Update display
      var newTree = render()
        , patches = vdom.diff(tree, newTree)
      vdom.patch(root, patches)
      tree = newTree
    })

    function render() {
      return h('div.Presence', [
        h('h5.Presence__Title', [users.length+' Users ', h('small', 'currently viewing this document')]),
        h('ul.Presence__Users.list-unstyled', users.map(function(userId) {
          return renderUser(ctx, users.get(userId))
        }))
      ])
    }

    next()
  })

  register()
}

function renderUser(ctx, user) {
  return h('li.Presence__User'+(ctx.user.get('id') === user.get('id')? '.mark':''), [
    h('span.Presence__User__name', user.get('name'))
  , ctx.user.get('id') === user.get('id')? h('small', h('em', ' this is you')) : ''
  ])
}

function jsonStringify() {
  return through.obj(function(buf, enc, cb) {
    this.push(JSON.stringify(buf)+'\n')
    cb()
  })
}
<commit_msg>Use models.Backbone + expose plugin-presence:renderUser hook<commit_after>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var jsonParse = require('json-stream')
  , through = require('through2')
  , co = require('co')
  , vdom = require('virtual-dom')
  , h = vdom.h

module.exports = setup
module.exports.consumes = ['ui', 'editor', 'models', 'hooks']
function setup(plugin, imports, register) {
  var ui = imports.ui
    , hooks = imports.hooks
    , Backbone = imports.models.Backbone

  var link = document.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('href', 'static/hive-plugin-presence/css/index.css')
  document.head.appendChild(link)

  ui.page('/:id', function(ctx, next) {
    var broadcast = ctx.broadcast.createDuplexStream(new Buffer('presence'))
      , users = new (Backbone.Collection.extend({model: ctx.models.user}))()

    broadcast.pipe(jsonParse()).pipe(through.obj(function(list, enc, cb) {
      // Update models
      users.set(Object.keys(list).map(function(userId) {return list[userId]}))
      cb()
    }))

    var tree, root
    co(function*() {
      tree = yield render()
      root = vdom.create(tree)
      document.body.insertBefore(root, document.body.firstChild)
    }).then(function(){})

    users.on('add remove change', function() {
      co(function*() {
        // Update display
        var newTree = yield render()
          , patches = vdom.diff(tree, newTree)
        vdom.patch(root, patches)
        tree = newTree
      }).then(function(){})
    })

    function* render() {
      return h('div.Presence', [
        h('h5.Presence__Title', [users.length+' Users ', h('small', 'currently viewing this document')]),
        h('ul.Presence__Users.list-unstyled', yield users.map(function*(userId) {
          return yield renderUser(users.get(userId))
        }))
      ])
    }

    function* renderUser(user) {
      var children = [
          h('span.Presence__User__name', user.get('name'))
        , ctx.user.get('id') === user.get('id')? h('small', h('em', ' this is you')) : ''
        ]
      , props = {}
      yield hooks.callHook('plugin-presence:renderUser', user, props, children)
      return h('li.Presence__User'+(ctx.user.get('id') === user.get('id')? '.mark':''), children)
    }

    next()
  })

  register()
}

function jsonStringify() {
  return through.obj(function(buf, enc, cb) {
    this.push(JSON.stringify(buf)+'\n')
    cb()
  })
}
<|endoftext|>


<commit_before>/* global angular, navigator, nw, require, StellarSdk */

angular.module('app', [
	'pascalprecht.translate',
	'ngRoute',
	'ionic'
], function ($compileProvider) {
	'use strict';
	$compileProvider.aHrefSanitizationWhitelist(/^\s*((https?|ftp|mailto|file|chrome-extension|tel):)|#/);
})

.run(function ($ionicPlatform, $rootScope, $route, $window) {
	'use strict';

	$rootScope.goBack = function() {
		$window.history.back();
	};

	$ionicPlatform.registerBackButtonAction(function () {
		if ($route.current.controller !== 'HomeCtrl') {
			$rootScope.goBack();
		} else {
			navigator.app.exitApp();
		}
	}, 100);
})

.run(function (platformInfo) {
	'use strict';

	if (platformInfo.isNW) {

//		nw.Window.get().showDevTools();

		// Load native UI library
		var gui = require('nw.gui');

		// Create menu
		var menu = new gui.Menu({
			type: 'menubar'
		});

		// Append Menu to Window
		gui.Window.get().menu = menu;

		// create MacBuiltin
		try {
			menu.createMacBuiltin('Stargazer', {
				hideEdit: false,
				hideWindow: true
			});
		} catch (e) {}
	}
})

.config(['$translateProvider', function ($translateProvider) {
	'use strict';

	$translateProvider
	.useSanitizeValueStrategy('escape')
	.addInterpolation('$translateMessageFormatInterpolation')
	.fallbackLanguage('en');

	$translateProvider.translations('en', /* @include ../i18n/en.json */);
	$translateProvider.translations('sv', /* @include ../i18n/sv.json */);
}]);
<commit_msg>Enable hardware scrolling<commit_after>/* global angular, navigator, nw, require, StellarSdk */

angular.module('app', [
	'pascalprecht.translate',
	'ngRoute',
	'ionic'
], function ($compileProvider) {
	'use strict';
	$compileProvider.aHrefSanitizationWhitelist(/^\s*((https?|ftp|mailto|file|chrome-extension|tel):)|#/);
})

.run(function ($ionicPlatform, $rootScope, $route, $window) {
	'use strict';

	$rootScope.goBack = function() {
		$window.history.back();
	};

	$ionicPlatform.registerBackButtonAction(function () {
		if ($route.current.controller !== 'HomeCtrl') {
			$rootScope.goBack();
		} else {
			navigator.app.exitApp();
		}
	}, 100);
})

.run(function (platformInfo) {
	'use strict';

	if (platformInfo.isNW) {

//		nw.Window.get().showDevTools();

		// Load native UI library
		var gui = require('nw.gui');

		// Create menu
		var menu = new gui.Menu({
			type: 'menubar'
		});

		// Append Menu to Window
		gui.Window.get().menu = menu;

		// create MacBuiltin
		try {
			menu.createMacBuiltin('Stargazer', {
				hideEdit: false,
				hideWindow: true
			});
		} catch (e) {}
	}
})

.config(function($ionicConfigProvider) {
	'use strict';
	$ionicConfigProvider.scrolling.jsScrolling(false);
})

.config(['$translateProvider', function ($translateProvider) {
	'use strict';

	$translateProvider
	.useSanitizeValueStrategy('escape')
	.addInterpolation('$translateMessageFormatInterpolation')
	.fallbackLanguage('en');

	$translateProvider.translations('en', /* @include ../i18n/en.json */);
	$translateProvider.translations('sv', /* @include ../i18n/sv.json */);
}]);
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d control")
description("This will return the 3d container control")
base_component_id("threedee_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "select_parent_when_child_added",
            name:       "Select Parent Only?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:         "x",
            name:       "Camera X",
            type:       "Number",
            default:    0
        }
        ,
        {
            id:         "y",
            name:       "Camera Y",
            type:       "Number",
            default:    1.6
        }
        ,
        {
            id:         "z",
            name:       "Camera Z",
            type:       "Number",
            default:    1
        }
        ,
        {
            id:         "cameraRight",
            snippet:    `cameraRight(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Right()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraUp",
            snippet:    `cameraUp(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Up()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraLeft",
            snippet:    `cameraLeft(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Left()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraDown",
            snippet:    `cameraDown(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Down()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraBack",
            snippet:    `cameraBack(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Back()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraForward",
            snippet:    `cameraForward(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Forward()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraTo",
            snippet:    `cameraTo({x: , y:, z:})`,
            name:       "Camera To()",
            type:       "Action"
        }

    ]
)//properties
logo_url("/driver_icons/threedee_item.png")
*/

    Vue.component("threedee_control",{
      props: ["args","design_mode", "refresh", "children","delete_design_time_component","select_design_time_component"]
      ,
      template:

`

            3D Scene Detail editor

{{child_item.name}}

                <div    class='btn btn-danger'
                        v-bind:refresh='refresh'
                        v-if='child_item'
                        v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                        "width: 20px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'
                        v-on:click='$event.stopPropagation();delete_design_time_component(child_item.index_in_parent_array)'>

                        X

        3D Scene - {{children.length}} items

            <slot v-bind:refresh='refresh'>
            </slot>

`
         ,

        mounted: function() {
            var mm = this
            registerComponent(this)

            if (!this.design_mode) {
                //var scene = document.querySelector('a-scene');
                //if (isValidObject(scene)) {
                    //scene.addEventListener('click', function () {

                        // Apply impulse;
                        //setTimeout(function () {
                            //var box = document.getElementById('left-box');
                            //var impulse = { x: 0, y: 10, z: 0 };
                            //var point = { x: 0.5, y: 0, z: 0 };
                            //box['physics-body'].applyImpulse(impulse, point);
                        //}, 25);
                    //});
                //}

                setInterval(function(){
                    if (document.fullscreen) {
                        mm.fullscreen = true
                    } else {
                        mm.fullscreen = false
                    }
                },1000)
            }

        }
      ,
      data: function() {
          return {
              msg:              "Hello Yazz!",
              selected_index:   null,
              fullscreen:       false
          }
      }
      ,
      methods: {
          cameraRight: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  x:          this.args.x + amount
              })

          }
          ,
          cameraLeft: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  x:          this.args.x - amount
              })

          }
          ,
          cameraUp: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  y:          this.args.y + amount
              })

          }
          ,
          cameraDown: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  y:          this.args.y - amount
              })

          }
          ,
          cameraBack: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  z:     this.args.z + amount
              })
          }
          ,
          cameraForward: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  z:     this.args.z - amount
              })

          }

          ,
          cameraTo: async function(opts) {

              var mm          = this
              var dd          =  document.querySelector("#camera_rig_3d" )
              var loop        = "0"
              var direction   = "normal"
              var duration    = 2000
              var bounce      = false

              var newX = this.args.x
              var newY = this.args.y
              var newZ = this.args.z
              if (isValidObject(opts.x)) {
                  newX = opts.x
              }
              if (isValidObject(opts.y)) {
                  newY = opts.y
              }
              if (isValidObject(opts.z)) {
                  newZ = opts.z
              }
              var newPosition = newX + " " + newY + " " + newZ

              if (isValidObject(opts.loop)) {
                  loop = opts.loop
              }

              if (isValidObject(opts.bounce) && (opts.bounce == true)) {
                  bounce    = true
                  direction = "alternate"
                  loop      = "1"
              }

              if (isValidObject(opts.duration)) {
                  duration = opts.duration
              }

              //
              // we need Math.random here as otherwise the animation will not get triggered for
              // repeated invocations
              //
              dd.setAttribute("animation",
                      `property: position; to: ${newPosition}; loop: ${loop}; dur: ${duration}; dir: ${direction}; rand: ${Math.random()} `
                  );

              if (!bounce) {
                  setTimeout(function() {
                      mm.args.x = newX
                      mm.args.y = newY
                      mm.args.z = newZ
                  },(duration + 100))
              }

              return {}

          }

      }
    })
}
<commit_msg>Can enter and exit a VR scene programtically now<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d control")
description("This will return the 3d container control")
base_component_id("threedee_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "select_parent_when_child_added",
            name:       "Select Parent Only?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:         "x",
            name:       "Camera X",
            type:       "Number",
            default:    0
        }
        ,
        {
            id:         "y",
            name:       "Camera Y",
            type:       "Number",
            default:    1.6
        }
        ,
        {
            id:         "z",
            name:       "Camera Z",
            type:       "Number",
            default:    1
        }
        ,
        {
            id:         "cameraRight",
            snippet:    `cameraRight(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Right()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraUp",
            snippet:    `cameraUp(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Up()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraLeft",
            snippet:    `cameraLeft(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Left()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraDown",
            snippet:    `cameraDown(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Down()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraBack",
            snippet:    `cameraBack(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Back()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraForward",
            snippet:    `cameraForward(1,[[duration in ms]],[[bounce: true/false]])`,
            name:       "Camera Forward()",
            type:       "Action"
        }
        ,
        {
            id:         "cameraTo",
            snippet:    `cameraTo({x: , y:, z:})`,
            name:       "Camera To()",
            type:       "Action"
        }
        ,
        {
            id:         "enterVR",
            snippet:    `enterVR()`,
            name:       "Enter VR()",
            type:       "Action"
        }
        ,
        {
            id:         "exitVR",
            snippet:    `exitVR()`,
            name:       "Exit VR()",
            type:       "Action"
        }

    ]
)//properties
logo_url("/driver_icons/threedee_item.png")
*/

    Vue.component("threedee_control",{
      props: ["args","design_mode", "refresh", "children","delete_design_time_component","select_design_time_component"]
      ,
      template:

`

            3D Scene Detail editor

{{child_item.name}}

                <div    class='btn btn-danger'
                        v-bind:refresh='refresh'
                        v-if='child_item'
                        v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                        "width: 20px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'
                        v-on:click='$event.stopPropagation();delete_design_time_component(child_item.index_in_parent_array)'>

                        X

        3D Scene - {{children.length}} items

            <slot v-bind:refresh='refresh'>
            </slot>

`
         ,

        mounted: function() {
            var mm = this
            registerComponent(this)

            if (!this.design_mode) {
                //var scene = document.querySelector('a-scene');
                //if (isValidObject(scene)) {
                    //scene.addEventListener('click', function () {

                        // Apply impulse;
                        //setTimeout(function () {
                            //var box = document.getElementById('left-box');
                            //var impulse = { x: 0, y: 10, z: 0 };
                            //var point = { x: 0.5, y: 0, z: 0 };
                            //box['physics-body'].applyImpulse(impulse, point);
                        //}, 25);
                    //});
                //}

                setInterval(function(){
                    if (document.fullscreen) {
                        mm.fullscreen = true
                    } else {
                        mm.fullscreen = false
                    }
                },1000)
            }

        }
      ,
      data: function() {
          return {
              msg:              "Hello Yazz!",
              selected_index:   null,
              fullscreen:       false
          }
      }
      ,
      methods: {
          cameraRight: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  x:          this.args.x + amount
              })

          }
          ,
          cameraLeft: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  x:          this.args.x - amount
              })

          }
          ,
          cameraUp: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  y:          this.args.y + amount
              })

          }
          ,
          cameraDown: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  y:          this.args.y - amount
              })

          }
          ,
          cameraBack: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  z:     this.args.z + amount
              })
          }
          ,
          cameraForward: async function(amount, duration, bounce) {
              await this.cameraTo({
                  duration:   isValidObject(duration)?duration:2000,
                  bounce:     isValidObject(bounce)?bounce:false,
                  z:     this.args.z - amount
              })

          }

          ,
          cameraTo: async function(opts) {

              var mm          = this
              var dd          =  document.querySelector("#camera_rig_3d" )
              var loop        = "0"
              var direction   = "normal"
              var duration    = 2000
              var bounce      = false

              var newX = this.args.x
              var newY = this.args.y
              var newZ = this.args.z
              if (isValidObject(opts.x)) {
                  newX = opts.x
              }
              if (isValidObject(opts.y)) {
                  newY = opts.y
              }
              if (isValidObject(opts.z)) {
                  newZ = opts.z
              }
              var newPosition = newX + " " + newY + " " + newZ

              if (isValidObject(opts.loop)) {
                  loop = opts.loop
              }

              if (isValidObject(opts.bounce) && (opts.bounce == true)) {
                  bounce    = true
                  direction = "alternate"
                  loop      = "1"
              }

              if (isValidObject(opts.duration)) {
                  duration = opts.duration
              }

              //
              // we need Math.random here as otherwise the animation will not get triggered for
              // repeated invocations
              //
              dd.setAttribute("animation",
                      `property: position; to: ${newPosition}; loop: ${loop}; dur: ${duration}; dir: ${direction}; rand: ${Math.random()} `
                  );

              if (!bounce) {
                  setTimeout(function() {
                      mm.args.x = newX
                      mm.args.y = newY
                      mm.args.z = newZ
                  },(duration + 100))
              }

              return {}

          }
          ,
          enterVR: async function() {
            var scene = document.querySelector('#scene');
            scene.enterVR()
          }
          ,
          exitVR: async function() {
              var scene = document.querySelector('#scene');
              scene.exitVR()
          }

      }
    })
}
<|endoftext|>