<commit_before>var request = require("request");
var version = require("../package.json").version;

exports.checkForUpdate = function() {
	request("https://raw.githubusercontent.com/brussell98/BrussellBot/public/package.json", (err, response, body)=>{
		if (err) console.log(cWarn(" WARN ") + " Version check error: " + err);
		else if (response.statusCode == 200) {
			var latest = JSON.parse(body).version;
			if ((version.split(".").join("")) < (latest.split(".").join(""))) console.log("Bot is out of date! (current v" + version + ") (latest v" + latest + ")");
			else if ((version.split(".").join("")) > (latest.split(".").join(""))) console.log("Bot is a development version (v" + version + ")");
			else console.log("BrussellBot is up-to-date (v" + version + ")");
		} else {
			console.log(cWarn(" WARN ") + " Failed to check for new version. Status code: " + response.statusCode);
		}
	});
};
<commit_msg>Fix versioncheck.js using wrong branch<commit_after>var request = require("request");
var version = require("../package.json").version;

exports.checkForUpdate = function() {
	request("https://raw.githubusercontent.com/brussell98/BrussellBot/master/package.json", (err, response, body)=>{
		if (err) console.log(cWarn(" WARN ") + " Version check error: " + err);
		else if (response.statusCode == 200) {
			var latest = JSON.parse(body).version;
			if ((version.split(".").join("")) < (latest.split(".").join(""))) console.log("Bot is out of date! (current v" + version + ") (latest v" + latest + ")");
			else if ((version.split(".").join("")) > (latest.split(".").join(""))) console.log("Bot is a development version (v" + version + ")");
			else console.log("BrussellBot is up-to-date (v" + version + ")");
		} else {
			console.log(cWarn(" WARN ") + " Failed to check for new version. Status code: " + response.statusCode);
		}
	});
};
<|endoftext|>


<commit_before>window.Stoarray = (function(){

  //private variables
  var _name,_type,_autosave,_events;
  var _eventsCallback = {};

  //constructor
  var Stoarray = function(name,opts){
    _name = name;
    _autosave = (opts.autosave === undefined)? true : !!opts.autosave;
    _events = (opts.events === undefined)? true : !!opts.events;

    var ignore = opts.ignore;
    if(opts.debug){
      ignore = true;
      _autosave = false;
    }

    _initData.call(this,opts.defaultValues,ignore);

    _save.call(this);
    return this;
  }

  //private method
  function _initData(d,ignore){
    var fromStorage = (ignore)?null:JSON.parse(localStorage.getItem(_name));
    this.data = fromStorage || d || [];
    return this;
  }

  function _save(){

    if(_events){
      _triggerEvent('change', this.data );
    }

    if(_autosave){
      console.log('autosave')
      this.save();
    }
  }

  //array data methods
  Stoarray.prototype.use = function(method,fn,autre){
    var newData = this.data[method](fn.bind(this),autre);
    if(newData){
      this.data = newData;
    }
    return this;
  }

  Stoarray.prototype.each = function(fn){
    for(var i = 0; i<this.data.length;i++){
      fn.call(this);
    }
    return this;
  }

  Stoarray.prototype.push = function(data){

    if(!(data instanceof Array)){
      data = [data];
    }

    for(var i = 0; i<data.length;i++){
      this.data.push(data[i]);
    }
    _save.call(this);
    _triggerEvent('push',this.data, data );
    return this;
  }

  Stoarray.prototype.map = function(fn){
    this.data = this.data.map(fn.bind(this));
    _save.call(this);
    return this;
  }

  Stoarray.prototype.reduce = function(fn,tab){
    this.data = this.data.reduce(fn.bind(this),tab);
    _save.call(this);
    return this;
  }

  //localStorage methods
  Stoarray.prototype.save = function(){
    var dataString = JSON.stringify(this.data);
    localStorage.setItem(_name,dataString);
    _triggerEvent('saved',this.data);
    return this;
  }

  //helper methods
  Stoarray.prototype.log = function(){
    console.log(this.data);
    return this;
  }

  Stoarray.prototype.addMethod = function(name,method){
    this[name] = function(){
      method.apply(this,arguments);
      _save.call(this);
      return this;
    }.bind(this);
    return this;
  }

  //events methods
  Stoarray.prototype.on = function(eventName,callback){

    if(_eventsCallback[eventName] && _eventsCallback[eventName] instanceof Array){
      _eventsCallback[eventName].push(callback)
    }else{
      _eventsCallback[eventName] = [callback]
    }
    return this;

  }

  function _triggerEvent(eventName,data,changed){

    if(!_events) return;

    if(_eventsCallback[eventName] && _eventsCallback[eventName].length >0){
      for(var i = 0; i<_eventsCallback[eventName].length;i++){
        _eventsCallback[eventName][i].call(null,data,changed)
      }
    }
  }

  return Stoarray;

})();
<commit_msg>make all map,reduce,etc -> use "use" method use method now return a new instance of Stoarray object<commit_after>window.Stoarray = (function(){

  //private variables
  var _name,_autosave,_events;
  var _eventsCallback = {};
  var _addedMethods = []

  //constructor
  var Stoarray = function(name,opts){
    _name = name;
    _autosave = (opts.autosave === undefined)? true : !!opts.autosave;
    _events = (opts.events === undefined)? true : !!opts.events;

    var ignore = opts.ignore;
    if(opts.debug){
      ignore = true;
      _autosave = false;
    }

    _initData.call(this,opts.defaultValues,ignore);

    _save.call(this);
    return this;
  }

  //private method
  function _initData(d,ignore){
    var fromStorage = (ignore)?null:JSON.parse(localStorage.getItem(_name));
    this.data = fromStorage || d || [];
    return this;
  }

  function _save(){

    if(_events){
      _triggerEvent('change', this.data );
    }

    if(_autosave){
      console.log('autosave')
      this.save();
    }
  }

  //array data methods
  Stoarray.prototype.use = function(method,fn,autre){
    var newData = this.data[method](fn.bind(this),autre);

    var newStoarray = new Stoarray(_name, {
      autosave : false,
      events : _events,
      ignore : true,
      defaultValues : newData
    });

    _addedMethods.forEach(function(obj){
      newStoarray.addMethod(obj.name,obj.method)
    })

    return newStoarray;
  }

  Stoarray.prototype.each = function(fn){
    return this.use('forEach',fn);
  }

  Stoarray.prototype.push = function(data){

    if(!(data instanceof Array)){
      data = [data];
    }

    for(var i = 0; i<data.length;i++){
      this.data.push(data[i]);
    }
    _save.call(this);
    _triggerEvent('push',this.data, data );
    return this;
  }

  Stoarray.prototype.map = function(fn){
    return this.use('map',fn);
  }

  Stoarray.prototype.reduce = function(fn,a){
    return this.use('reduce',fn,a);
  }

  //localStorage methods
  Stoarray.prototype.save = function(){
    var dataString = JSON.stringify(this.data);
    localStorage.setItem(_name,dataString);
    _triggerEvent('saved',this.data);
    return this;
  }

  //helper methods
  Stoarray.prototype.log = function(){
    console.log(this.data);
    return this;
  }

  Stoarray.prototype.clean = function(){
    this.data = [];
    this.save();
    return this;
  }

  Stoarray.prototype.addMethod = function(name,method){
    _addedMethods.push({name:name,method,method})
    this[name] = function(){
      method.apply(this,arguments);
      _save.call(this);
      return this;
    }.bind(this);
    return this;
  }

  //events methods
  Stoarray.prototype.on = function(eventName,callback){

    if(_eventsCallback[eventName] && _eventsCallback[eventName] instanceof Array){
      _eventsCallback[eventName].push(callback)
    }else{
      _eventsCallback[eventName] = [callback]
    }
    return this;

  }

  function _triggerEvent(eventName,data,changed){

    if(!_events) return;

    if(_eventsCallback[eventName] && _eventsCallback[eventName].length >0){
      for(var i = 0; i<_eventsCallback[eventName].length;i++){
        _eventsCallback[eventName][i].call(null,data,changed)
      }
    }
  }

  return Stoarray;

})();
<|endoftext|>


<commit_before>/**
 * Hilo
 * Copyright 2015 alibaba.com
 * Licensed under the MIT License
 */

/**
 * @language=en
 * @class Container是所有容器类的基类。每个Container都可以添加其他可视对象为子级。
 * @augments View
 * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
 * @module hilo/view/Container
 * @requires hilo/core/Hilo
 * @requires hilo/core/Class
 * @requires hilo/view/View
 * @property {Array} children 容器的子元素列表。只读。
 * @property {Boolean} pointerChildren 指示容器的子元素是否能响应用户交互事件。默认为true。
 * @property {Boolean} clipChildren 指示是否裁剪超出容器范围的子元素。默认为false。
 */
/**
 * @language=zh
 * @class Container是所有容器类的基类。每个Container都可以添加其他可视对象为子级。
 * @augments View
 * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
 * @module hilo/view/Container
 * @requires hilo/core/Hilo
 * @requires hilo/core/Class
 * @requires hilo/view/View
 * @property {Array} children 容器的子元素列表。只读。
 * @property {Boolean} pointerChildren 指示容器的子元素是否能响应用户交互事件。默认为true。
 * @property {Boolean} clipChildren 指示是否裁剪超出容器范围的子元素。默认为false。
 */
var Container = Class.create(/** @lends Container.prototype */{
    Extends: View,
    constructor: function(properties){
        properties = properties || {};
        this.id = this.id || properties.id || Hilo.getUid("Container");
        Container.superclass.constructor.call(this, properties);

        if(this.children) this._updateChildren();
        else this.children = [];
    },

    children: null,
    pointerChildren: true,
    clipChildren: false,

    /**
     * @language=en
     * 返回容器的子元素的数量。
     * @returns {Uint} 容器的子元素的数量。
     */
    /**
     * @language=zh
     * 返回容器的子元素的数量。
     * @returns {Uint} 容器的子元素的数量。
     */
    getNumChildren: function(){
        return this.children.length;
    },

    /**
     * @language=en
     * 在指定索引位置添加子元素。
     * @param {View} child 要添加的子元素。
     * @param {Number} index 指定的索引位置，从0开始。
     */
    /**
     * @language=zh
     * 在指定索引位置添加子元素。
     * @param {View} child 要添加的子元素。
     * @param {Number} index 指定的索引位置，从0开始。
     */
    addChildAt: function(child, index){
        var children = this.children,
            len = children.length,
            parent = child.parent;

        index = index < 0 ? 0 : index > len ? len : index;
        var childIndex = this.getChildIndex(child);
        if(childIndex == index){
            return this;
        }else if(childIndex >= 0){
            children.splice(childIndex, 1);
            index = index == len ? len - 1 : index;
        }else if(parent){
            parent.removeChild(child);
        }

        children.splice(index, 0, child);

        //直接插入，影响插入位置之后的深度
        if(childIndex < 0){
            this._updateChildren(index);
        }
        //只是移动时影响中间段的深度
        else{
            var startIndex = childIndex < index ? childIndex : index;
            var endIndex = childIndex < index ? index : childIndex;;
            this._updateChildren(startIndex, endIndex + 1);
        }

        return this;
    },

    /**
     * @language=en
     * 在最上面添加子元素。
     * @param {View} child 要添加的子元素。
     */
    /**
     * @language=zh
     * 在最上面添加子元素。
     * @param {View} child 要添加的子元素。
     */
    addChild: function(child){
        var total = this.children.length,
            args = arguments;

        for(var i = 0, len = args.length; i < len; i++){
            this.addChildAt(args[i], total + i);
        }
        return this;
    },

    /**
     * @language=en
     * 在指定索引位置删除子元素。
     * @param {Int} index 指定删除元素的索引位置，从0开始。
     * @returns {View} 被删除的对象。
     */
    /**
     * @language=zh
     * 在指定索引位置删除子元素。
     * @param {Int} index 指定删除元素的索引位置，从0开始。
     * @returns {View} 被删除的对象。
     */
    removeChildAt: function(index){
        var children = this.children;
        if(index < 0 || index >= children.length) return null;

        var child = children[index];
        if(child){
            //NOTE: use `__renderer` for fixing child removal (DOMRenderer and FlashRenderer only).
            //Do `not` use it in any other case.
            if(!child.__renderer){
                var obj = child;
                while(obj = obj.parent){
                    //obj is stage
                    if(obj.renderer){
                        child.__renderer = obj.renderer;
                        break;
                    }
                    else if(obj.__renderer){
                        child.__renderer = obj.__renderer;
                        break;
                    }
                }
            }

            if(child.__renderer){
                child.__renderer.remove(child);
            }

            child.parent = null;
            child.depth = -1;
        }

        children.splice(index, 1);
        this._updateChildren(index);

        return child;
    },

    /**
     * @language=en
     * 删除指定的子元素。
     * @param {View} child 指定要删除的子元素。
     * @returns {View} 被删除的对象。
     */
    /**
     * @language=zh
     * 删除指定的子元素。
     * @param {View} child 指定要删除的子元素。
     * @returns {View} 被删除的对象。
     */
    removeChild: function(child){
        return this.removeChildAt(this.getChildIndex(child));
    },

    /**
     * @language=en
     * 删除指定id的子元素。
     * @param {String} id 指定要删除的子元素的id。
     * @returns {View} 被删除的对象。
     */
    /**
     * @language=zh
     * 删除指定id的子元素。
     * @param {String} id 指定要删除的子元素的id。
     * @returns {View} 被删除的对象。
     */
    removeChildById: function(id){
        var children = this.children, child;
        for(var i = 0, len = children.length; i < len; i++){
            child = children[i];
            if(child.id === id){
                this.removeChildAt(i);
                return child;
            }
        }
        return null;
    },

    /**
     * @language=en
     * 删除所有的子元素。
     * @returns {Container} 容器本身。
     */
    /**
     * @language=zh
     * 删除所有的子元素。
     * @returns {Container} 容器本身。
     */
    removeAllChildren: function(){
        while(this.children.length) this.removeChildAt(0);
        return this;
    },

    /**
     * @language=en
     * 返回指定索引位置的子元素。
     * @param {Number} index 指定要返回的子元素的索引值，从0开始。
     */
    /**
     * @language=zh
     * 返回指定索引位置的子元素。
     * @param {Number} index 指定要返回的子元素的索引值，从0开始。
     */
    getChildAt: function(index){
        var children = this.children;
        if(index < 0 || index >= children.length) return null;
        return children[index];
    },

    /**
     * @language=en
     * 返回指定id的子元素。
     * @param {String} id 指定要返回的子元素的id。
     */
    /**
     * @language=zh
     * 返回指定id的子元素。
     * @param {String} id 指定要返回的子元素的id。
     */
    getChildById: function(id){
        var children = this.children, child;
        for(var i = 0, len = children.length; i < len; i++){
            child = children[i];
            if(child.id === id) return child;
        }
        return null;
    },

    /**
     * @language=en
     * 返回指定子元素的索引值。
     * @param {View} child 指定要返回索引值的子元素。
     */
    /**
     * @language=zh
     * 返回指定子元素的索引值。
     * @param {View} child 指定要返回索引值的子元素。
     */
    getChildIndex: function(child){
        return this.children.indexOf(child);
    },

    /**
     * @language=en
     * 设置子元素的索引位置。
     * @param {View} child 指定要设置的子元素。
     * @param {Number} index 指定要设置的索引值。
     */
    /**
     * @language=zh
     * 设置子元素的索引位置。
     * @param {View} child 指定要设置的子元素。
     * @param {Number} index 指定要设置的索引值。
     */
    setChildIndex: function(child, index){
        var children = this.children,
            oldIndex = children.indexOf(child);

        if(oldIndex >= 0 && oldIndex != index){
            var len = children.length;
            index = index < 0 ? 0 : index >= len ? len - 1 : index;
            children.splice(oldIndex, 1);
            children.splice(index, 0, child);
            this._updateChildren();
        }
        return this;
    },

    /**
     * @language=en
     * 交换两个子元素的索引位置。
     * @param {View} child1 指定要交换的子元素A。
     * @param {View} child2 指定要交换的子元素B。
     */
    /**
     * @language=zh
     * 交换两个子元素的索引位置。
     * @param {View} child1 指定要交换的子元素A。
     * @param {View} child2 指定要交换的子元素B。
     */
    swapChildren: function(child1, child2){
        var children = this.children,
            index1 = this.getChildIndex(child1),
            index2 = this.getChildIndex(child2);

        child1.depth = index2;
        children[index2] = child1;
        child2.depth = index1;
        children[index1] = child2;
    },

    /**
     * @language=en
     * 交换两个指定索引位置的子元素。
     * @param {Number} index1 指定要交换的索引位置A。
     * @param {Number} index2 指定要交换的索引位置B。
     */
    /**
     * @language=zh
     * 交换两个指定索引位置的子元素。
     * @param {Number} index1 指定要交换的索引位置A。
     * @param {Number} index2 指定要交换的索引位置B。
     */
    swapChildrenAt: function(index1, index2){
        var children = this.children,
            child1 = this.getChildAt(index1),
            child2 = this.getChildAt(index2);

        child1.depth = index2;
        children[index2] = child1;
        child2.depth = index1;
        children[index1] = child2;
    },

    /**
     * @language=en
     * 根据指定键值或函数对子元素进行排序。
     * @param {Object} keyOrFunction 如果此参数为String时，则根据子元素的某个属性值进行排序；如果此参数为Function时，则根据此函数进行排序。
     */
    /**
     * @language=zh
     * 根据指定键值或函数对子元素进行排序。
     * @param {Object} keyOrFunction 如果此参数为String时，则根据子元素的某个属性值进行排序；如果此参数为Function时，则根据此函数进行排序。
     */
    sortChildren: function(keyOrFunction){
        var fn = keyOrFunction,
            children = this.children;
        if(typeof fn == "string"){
            var key = fn;
            fn = function(a, b){
                return b[key] - a[key];
            };
        }
        children.sort(fn);
        this._updateChildren();
    },

    /**
     * @language=en
     * 更新子元素。
     * @private
     */
    /**
     * @language=zh
     * 更新子元素。
     * @private
     */
    _updateChildren: function(start, end){
        var children = this.children, child,
            start = start || 0,
            end = end || children.length;
        for(var i = start; i < end; i++){
            child = children[i];
            child.depth = i + 1;
            child.parent = this;
        }
    },

    /**
     * @language=en
     * 返回是否包含参数指定的子元素。
     * @param {View} child 指定要测试的子元素。
     */
    /**
     * @language=zh
     * 返回是否包含参数指定的子元素。
     * @param {View} child 指定要测试的子元素。
     */
    contains: function(child){
        while(child = child.parent){
            if(child === this){
                return true;
            }
        }
        return false;
    },

    /**
     * @language=en
     * 返回由x和y指定的点下的对象。
     * @param {Number} x 指定点的x轴坐标。
     * @param {Number} y 指定点的y轴坐标。
     * @param {Boolean} usePolyCollision 指定是否使用多边形碰撞检测。默认为false。
     * @param {Boolean} global 使用此标志表明将查找所有符合的对象，而不仅仅是第一个，即全局匹配。默认为false。
     * @param {Boolean} eventMode 使用此标志表明将在事件模式下查找对象。默认为false。
     */
    /**
     * @language=zh
     * 返回由x和y指定的点下的对象。
     * @param {Number} x 指定点的x轴坐标。
     * @param {Number} y 指定点的y轴坐标。
     * @param {Boolean} usePolyCollision 指定是否使用多边形碰撞检测。默认为false。
     * @param {Boolean} global 使用此标志表明将查找所有符合的对象，而不仅仅是第一个，即全局匹配。默认为false。
     * @param {Boolean} eventMode 使用此标志表明将在事件模式下查找对象。默认为false。
     */
    getViewAtPoint: function(x, y, usePolyCollision, global, eventMode){
        var result = global ? [] : null,
            children = this.children, child, obj;

        for(var i = children.length - 1; i >= 0; i--){
            child = children[i];
            //skip child which is not shown or pointer enabled
            if(!child || !child.visible || child.alpha <= 0 || (eventMode && !child.pointerEnabled)) continue;
            //find child recursively
            if(child.children && child.children.length && !(eventMode && !child.pointerChildren)){
                obj = child.getViewAtPoint(x, y, usePolyCollision, global, eventMode);
            }

            if(obj){
                if(!global) return obj;
                else if(obj.length) result = result.concat(obj);
            }else if(child.hitTestPoint(x, y, usePolyCollision)){
                if(!global) return child;
                else result.push(child);
            }
        }

        return global && result.length ? result : null;
    },

    /**
     * @language=en
     * 覆盖渲染方法。
     * @private
     */
    /**
     * @language=zh
     * 覆盖渲染方法。
     * @private
     */
    render: function(renderer, delta){
        Container.superclass.render.call(this, renderer, delta);

        var children = this.children.slice(0), i, len, child;
        for(i = 0, len = children.length; i < len; i++){
            child = children[i];
            //NOTE: the child could remove or change it's parent
            if(child.parent === this) child._render(renderer, delta);
        }
    }

});<commit_msg>docs: translate src/view/Container.js comments to English<commit_after>/**
 * Hilo
 * Copyright 2015 alibaba.com
 * Licensed under the MIT License
 */

/**
 * @language=en
 * @class Container is the base class to all container classes. Each Container can add other view object as children.
 * @augments View
 * @param {Object} properties Properties parameters of the object to create. Contains all writable properties of this class.
 * @module hilo/view/Container
 * @requires hilo/core/Hilo
 * @requires hilo/core/Class
 * @requires hilo/view/View
 * @property {Array} children List of children elements of the container, readonly!
 * @property {Boolean} pointerChildren Whether children elements of the container can response to user interactive events, default value is true.
 * @property {Boolean} clipChildren Whether clip children elements which are out of the container, default value is false.
 */
/**
 * @language=zh
 * @class Container是所有容器类的基类。每个Container都可以添加其他可视对象为子级。
 * @augments View
 * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
 * @module hilo/view/Container
 * @requires hilo/core/Hilo
 * @requires hilo/core/Class
 * @requires hilo/view/View
 * @property {Array} children 容器的子元素列表。只读。
 * @property {Boolean} pointerChildren 指示容器的子元素是否能响应用户交互事件。默认为true。
 * @property {Boolean} clipChildren 指示是否裁剪超出容器范围的子元素。默认为false。
 */
var Container = Class.create(/** @lends Container.prototype */{
    Extends: View,
    constructor: function(properties){
        properties = properties || {};
        this.id = this.id || properties.id || Hilo.getUid("Container");
        Container.superclass.constructor.call(this, properties);

        if(this.children) this._updateChildren();
        else this.children = [];
    },

    children: null,
    pointerChildren: true,
    clipChildren: false,

    /**
     * @language=en
     * Return the amount of the children elements of the container.
     * @returns {Uint} The amount of the children elements of the container.
     */
    /**
     * @language=zh
     * 返回容器的子元素的数量。
     * @returns {Uint} 容器的子元素的数量。
     */
    getNumChildren: function(){
        return this.children.length;
    },

    /**
     * @language=en
     * Add child element at given index.
     * @param {View} child Element to add.
     * @param {Number} index The given index position, range from 0.
     */
    /**
     * @language=zh
     * 在指定索引位置添加子元素。
     * @param {View} child 要添加的子元素。
     * @param {Number} index 指定的索引位置，从0开始。
     */
    addChildAt: function(child, index){
        var children = this.children,
            len = children.length,
            parent = child.parent;

        index = index < 0 ? 0 : index > len ? len : index;
        var childIndex = this.getChildIndex(child);
        if(childIndex == index){
            return this;
        }else if(childIndex >= 0){
            children.splice(childIndex, 1);
            index = index == len ? len - 1 : index;
        }else if(parent){
            parent.removeChild(child);
        }

        children.splice(index, 0, child);

        //直接插入，影响插入位置之后的深度
        //Insert directly, this will affect depth of elements after the index.
        if(childIndex < 0){
            this._updateChildren(index);
        }
        //只是移动时影响中间段的深度
        //Will affect depth of elements in the middle during moving
        else{
            var startIndex = childIndex < index ? childIndex : index;
            var endIndex = childIndex < index ? index : childIndex;;
            this._updateChildren(startIndex, endIndex + 1);
        }

        return this;
    },

    /**
     * @language=en
     * Add child element at the top.
     * @param {View} child Elements to add.
     */
    /**
     * @language=zh
     * 在最上面添加子元素。
     * @param {View} child 要添加的子元素。
     */
    addChild: function(child){
        var total = this.children.length,
            args = arguments;

        for(var i = 0, len = args.length; i < len; i++){
            this.addChildAt(args[i], total + i);
        }
        return this;
    },

    /**
     * @language=en
     * Remove element at the index.
     * @param {Int} index Index of the element to remove, range from 0.
     * @returns {View} Element had been removed.
     */
    /**
     * @language=zh
     * 在指定索引位置删除子元素。
     * @param {Int} index 指定删除元素的索引位置，从0开始。
     * @returns {View} 被删除的对象。
     */
    removeChildAt: function(index){
        var children = this.children;
        if(index < 0 || index >= children.length) return null;

        var child = children[index];
        if(child){
            //NOTE: use `__renderer` for fixing child removal (DOMRenderer and FlashRenderer only).
            //Do `not` use it in any other case.
            if(!child.__renderer){
                var obj = child;
                while(obj = obj.parent){
                    //obj is stage
                    if(obj.renderer){
                        child.__renderer = obj.renderer;
                        break;
                    }
                    else if(obj.__renderer){
                        child.__renderer = obj.__renderer;
                        break;
                    }
                }
            }

            if(child.__renderer){
                child.__renderer.remove(child);
            }

            child.parent = null;
            child.depth = -1;
        }

        children.splice(index, 1);
        this._updateChildren(index);

        return child;
    },

    /**
     * @language=en
     * Remove the given child element.
     * @param {View} child The child element to remove.
     * @returns {View} Element had been removed.
     */
    /**
     * @language=zh
     * 删除指定的子元素。
     * @param {View} child 指定要删除的子元素。
     * @returns {View} 被删除的对象。
     */
    removeChild: function(child){
        return this.removeChildAt(this.getChildIndex(child));
    },

    /**
     * @language=en
     * Remove child element by its id.
     * @param {String} id The id of element to remove.
     * @returns {View} Element had been removed.
     */
    /**
     * @language=zh
     * 删除指定id的子元素。
     * @param {String} id 指定要删除的子元素的id。
     * @returns {View} 被删除的对象。
     */
    removeChildById: function(id){
        var children = this.children, child;
        for(var i = 0, len = children.length; i < len; i++){
            child = children[i];
            if(child.id === id){
                this.removeChildAt(i);
                return child;
            }
        }
        return null;
    },

    /**
     * @language=en
     * Remove all children elements.
     * @returns {Container} Container itself.
     */
    /**
     * @language=zh
     * 删除所有的子元素。
     * @returns {Container} 容器本身。
     */
    removeAllChildren: function(){
        while(this.children.length) this.removeChildAt(0);
        return this;
    },

    /**
     * @language=en
     * Return child element at the given index.
     * @param {Number} index The index of the element, range from 0.
     */
    /**
     * @language=zh
     * 返回指定索引位置的子元素。
     * @param {Number} index 指定要返回的子元素的索引值，从0开始。
     */
    getChildAt: function(index){
        var children = this.children;
        if(index < 0 || index >= children.length) return null;
        return children[index];
    },

    /**
     * @language=en
     * Return child element at the given id.
     * @param {String} id The id of child element to return.
     */
    /**
     * @language=zh
     * 返回指定id的子元素。
     * @param {String} id 指定要返回的子元素的id。
     */
    getChildById: function(id){
        var children = this.children, child;
        for(var i = 0, len = children.length; i < len; i++){
            child = children[i];
            if(child.id === id) return child;
        }
        return null;
    },

    /**
     * @language=en
     * Return index value of the given child element.
     * @param {View} child The child element need to get its index.
     */
    /**
     * @language=zh
     * 返回指定子元素的索引值。
     * @param {View} child 指定要返回索引值的子元素。
     */
    getChildIndex: function(child){
        return this.children.indexOf(child);
    },

    /**
     * @language=en
     * Set the index of child element.
     * @param {View} child The child element need to set index.
     * @param {Number} index The index to set to the element.
     */
    /**
     * @language=zh
     * 设置子元素的索引位置。
     * @param {View} child 指定要设置的子元素。
     * @param {Number} index 指定要设置的索引值。
     */
    setChildIndex: function(child, index){
        var children = this.children,
            oldIndex = children.indexOf(child);

        if(oldIndex >= 0 && oldIndex != index){
            var len = children.length;
            index = index < 0 ? 0 : index >= len ? len - 1 : index;
            children.splice(oldIndex, 1);
            children.splice(index, 0, child);
            this._updateChildren();
        }
        return this;
    },

    /**
     * @language=en
     * Swap index between two child elements.
     * @param {View} child1 Child element A.
     * @param {View} child2 Child element B.
     */
    /**
     * @language=zh
     * 交换两个子元素的索引位置。
     * @param {View} child1 指定要交换的子元素A。
     * @param {View} child2 指定要交换的子元素B。
     */
    swapChildren: function(child1, child2){
        var children = this.children,
            index1 = this.getChildIndex(child1),
            index2 = this.getChildIndex(child2);

        child1.depth = index2;
        children[index2] = child1;
        child2.depth = index1;
        children[index1] = child2;
    },

    /**
     * @language=en
     * Swap two children elements at given indexes.
     * @param {Number} index1 Given index A.
     * @param {Number} index2 Given index B.
     */
    /**
     * @language=zh
     * 交换两个指定索引位置的子元素。
     * @param {Number} index1 指定要交换的索引位置A。
     * @param {Number} index2 指定要交换的索引位置B。
     */
    swapChildrenAt: function(index1, index2){
        var children = this.children,
            child1 = this.getChildAt(index1),
            child2 = this.getChildAt(index2);

        child1.depth = index2;
        children[index2] = child1;
        child2.depth = index1;
        children[index1] = child2;
    },

    /**
     * @language=en
     * Sort children elements by the given key or function.
     * @param {Object} keyOrFunction If is String, sort children elements by the given property string; If is Function, sort by the function.
     */
    /**
     * @language=zh
     * 根据指定键值或函数对子元素进行排序。
     * @param {Object} keyOrFunction 如果此参数为String时，则根据子元素的某个属性值进行排序；如果此参数为Function时，则根据此函数进行排序。
     */
    sortChildren: function(keyOrFunction){
        var fn = keyOrFunction,
            children = this.children;
        if(typeof fn == "string"){
            var key = fn;
            fn = function(a, b){
                return b[key] - a[key];
            };
        }
        children.sort(fn);
        this._updateChildren();
    },

    /**
     * @language=en
     * Update children elements.
     * @private
     */
    /**
     * @language=zh
     * 更新子元素。
     * @private
     */
    _updateChildren: function(start, end){
        var children = this.children, child,
            start = start || 0,
            end = end || children.length;
        for(var i = start; i < end; i++){
            child = children[i];
            child.depth = i + 1;
            child.parent = this;
        }
    },

    /**
     * @language=en
     * Return whether this container contains the parameter described child element.
     * @param {View} child The child element to test.
     */
    /**
     * @language=zh
     * 返回是否包含参数指定的子元素。
     * @param {View} child 指定要测试的子元素。
     */
    contains: function(child){
        while(child = child.parent){
            if(child === this){
                return true;
            }
        }
        return false;
    },

    /**
     * @language=en
     * Return object at the point positioned by given values on x axis and y axis.
     * @param {Number} x The point's value on the coordinate's x axis.
     * @param {Number} y The point's value on the coordinate's y asix.
     * @param {Boolean} usePolyCollision Whether use polygon collision detection, default value is false.
     * @param {Boolean} global Whether return all elements that match the condition, default value is false.
     * @param {Boolean} eventMode Whether find elements under event mode, default value is false.
     */
    /**
     * @language=zh
     * 返回由x和y指定的点下的对象。
     * @param {Number} x 指定点的x轴坐标。
     * @param {Number} y 指定点的y轴坐标。
     * @param {Boolean} usePolyCollision 指定是否使用多边形碰撞检测。默认为false。
     * @param {Boolean} global 使用此标志表明将查找所有符合的对象，而不仅仅是第一个，即全局匹配。默认为false。
     * @param {Boolean} eventMode 使用此标志表明将在事件模式下查找对象。默认为false。
     */
    getViewAtPoint: function(x, y, usePolyCollision, global, eventMode){
        var result = global ? [] : null,
            children = this.children, child, obj;

        for(var i = children.length - 1; i >= 0; i--){
            child = children[i];
            //skip child which is not shown or pointer enabled
            if(!child || !child.visible || child.alpha <= 0 || (eventMode && !child.pointerEnabled)) continue;
            //find child recursively
            if(child.children && child.children.length && !(eventMode && !child.pointerChildren)){
                obj = child.getViewAtPoint(x, y, usePolyCollision, global, eventMode);
            }

            if(obj){
                if(!global) return obj;
                else if(obj.length) result = result.concat(obj);
            }else if(child.hitTestPoint(x, y, usePolyCollision)){
                if(!global) return child;
                else result.push(child);
            }
        }

        return global && result.length ? result : null;
    },

    /**
     * @language=en
     * Rewrite render method.
     * @private
     */
    /**
     * @language=zh
     * 覆盖渲染方法。
     * @private
     */
    render: function(renderer, delta){
        Container.superclass.render.call(this, renderer, delta);

        var children = this.children.slice(0), i, len, child;
        for(i = 0, len = children.length; i < len; i++){
            child = children[i];
            //NOTE: the child could remove or change it's parent
            if(child.parent === this) child._render(renderer, delta);
        }
    }

});
<|endoftext|>


<commit_before>"use strict";
/* jslint browser: true, globalstrict: true, devel: true, debug: true */
/* global THREE, THREEx, signals, Stats, Detector */

// For conditions of distribution and use, see copyright notice in LICENSE
/*
 *      @author Erno Kuusela
 *      @author Tapani Jamsa
 */

var useCubes = false;

function ThreeView(scene, camera) {
    this.objectsByEntityId = {};
    this.meshCache = {};

    // SCENE
    this.scene = scene;
    this.camera = camera;

    // STATS
    this.stats = new Stats();
    this.stats.domElement.style.position = 'absolute';
    this.stats.domElement.style.bottom = '0px';
    this.stats.domElement.style.zIndex = 100;

    // RENDERER
    if (Detector.webgl)
        this.renderer = new THREE.WebGLRenderer({
            antialias: true
        });
    else
        this.renderer = new THREE.CanvasRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);

    // EVENTS
    THREEx.WindowResize(this.renderer, this.camera);
    THREEx.FullScreen.bindKey({
        charCode: 'm'.charCodeAt(0)
    });

    // CONTAINER
    this.container = document.getElementById('ThreeJS');
    this.container.appendChild(this.stats.domElement);
    this.container.appendChild(this.renderer.domElement);
    document.body.appendChild(this.container);

    // LIGHT, GEOMETRY AND MATERIAL
    this.cubeGeometry = new THREE.CubeGeometry( 2,2, 2 );
    this.wireframeMaterial = new THREE.MeshBasicMaterial({
        color: 0x00ee00,
        wireframe: true,
        transparent: true
    });

    // PROJECTOR

    this.projector = new THREE.Projector();
    var thisIsThis = this;
    document.addEventListener( 'mousedown', function(event) {
        var camera = thisIsThis.camera;
        var mouse = { x: ( event.clientX / window.innerWidth ) * 2 - 1,
                      y: - ( event.clientY / window.innerHeight ) * 2 + 1, };
        var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
        var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
        var mouseVector = new THREE.Vector3( mouse.x, mouse.y, 1 );
        thisIsThis.projector.unprojectVector( mouseVector, camera );
        var intersects = ray.intersectObjects(attributeValues(thisIsThis.objectsByEntityId));
    }, false );

    // Hack for Physics2 scene
    this.pointLight = new THREE.PointLight(0xffffff);
    this.pointLight.position.set(-100,200,100);
}

ThreeView.prototype = {

    constructor: ThreeView,

    render: function() {
        // checkDefined(this.scene, this.camera);
        this.renderer.render(this.scene, this.camera);
    },

    addOrUpdate: function(entity, placeable, meshComp) {
        checkDefined(entity, placeable, meshComp);
        checkDefined(entity.id);
        var threeObject = this.objectsByEntityId[entity.id];
        var url = meshComp.meshRef.value.ref;
        if (threeObject === undefined) {
            if (useCubes) {
                threeObject = new THREE.Mesh(this.cubeGeometry, this.wireframeMaterial);
                this.objectsByEntityId[entity.id] = threeObject;
                this.scene.add(threeObject);
            } else if (url === 'lightsphere.mesh') {
                this.objectsByEntityId[entity.id] = this.pointLight;
                this.scene.add(this.pointLight);
                this.updateFromTransform(this.pointLight, placeable);
                if (useSignals)
                    this.connectToPlaceable(this, this.pointLight, placeable);
            } else {
                url = url.replace(/\.mesh$/i, ".json")
                var entitiesForUrl = this.meshCache[url];
                var firstRef = false;
                if (entitiesForUrl === undefined) {
                    this.meshCache[url] = entitiesForUrl = [];
                    firstRef = true;
                }
                entitiesForUrl.push(entity);
                if (!firstRef)
                    return;
                console.log("new mesh ref:", url);
                var thisIsThis = this;
                this.jsonLoad(url, function (geometry, material) {
                    thisIsThis.addMeshToEntities(geometry, material, url);
                    console.log("loaded & updated to scene:", url);
                });
            }
        } else {
            this.updateFromTransform(threeObject, placeable);
        }
    },

    addMeshToEntities: function(geometry, material, url) {
        var entities = this.meshCache[url];
        checkDefined(entities);
        //material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5 } );
        for (var i = 0; i < entities.length; i++) {
            var ent = entities[i];
            check(ent instanceof Entity);
            var pl = ent.componentByType(cComponentTypePlaceable);
            var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(material));
            if (useSignals) {
                this.connectToPlaceable(this, mesh, pl);
            } else {
                this.updateFromTransform(mesh, pl);
            }
            this.scene.add(mesh);
            this.objectsByEntityId[ent.id] = mesh;
            mesh.userData.entityId = ent.id;
        }
        entities.length = 0;
    },

    jsonLoad: function(url, addCallback) {
        var loader = new THREE.JSONLoader();
        loader.load(url, function(geometry, material) {
            addCallback(geometry, material);
        });
    },

    copyXyz: function(src, dst) {
        dst.x = src.x;
        dst.y = src.y;
        dst.z = src.z;
    },

    copyXyzMapped: function(src, dst, mapfun) {
        dst.x = mapfun(src.x);
        dst.y = mapfun(src.y);
        dst.z = mapfun(src.z);
    },

    degToRad: function(val) {
        return val * (Math.PI / 180);
    },

    updateFromTransform: function(threeMesh, placeable) {
        checkDefined(placeable, threeMesh);
        this.copyXyz(placeable.transform.value.pos, threeMesh.position);
        this.copyXyz(placeable.transform.value.scale, threeMesh.scale);
        this.copyXyzMapped(placeable.transform.value.rot, threeMesh.rotation, this.degToRad);
        threeMesh.needsUpdate = true;
    },

    connectToPlaceable: function(thisIsThis, threeObject, placeable) {
        thisIsThis.updateFromTransform(threeObject, placeable);
        placeable.attributeChanged.add(function(attr, changeType) {
            thisIsThis.updateFromTransform(threeObject, placeable);
        });
    },
};

<commit_msg>fix cubes mode<commit_after>"use strict";
/* jslint browser: true, globalstrict: true, devel: true, debug: true */
/* global THREE, THREEx, signals, Stats, Detector */

// For conditions of distribution and use, see copyright notice in LICENSE
/*
 *      @author Erno Kuusela
 *      @author Tapani Jamsa
 */

var useCubes = false;

function ThreeView(scene, camera) {
    this.objectsByEntityId = {};
    this.meshCache = {};

    // SCENE
    this.scene = scene;
    this.camera = camera;

    // STATS
    this.stats = new Stats();
    this.stats.domElement.style.position = 'absolute';
    this.stats.domElement.style.bottom = '0px';
    this.stats.domElement.style.zIndex = 100;

    // RENDERER
    if (Detector.webgl)
        this.renderer = new THREE.WebGLRenderer({
            antialias: true
        });
    else
        this.renderer = new THREE.CanvasRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);

    // EVENTS
    THREEx.WindowResize(this.renderer, this.camera);
    THREEx.FullScreen.bindKey({
        charCode: 'm'.charCodeAt(0)
    });

    // CONTAINER
    this.container = document.getElementById('ThreeJS');
    this.container.appendChild(this.stats.domElement);
    this.container.appendChild(this.renderer.domElement);
    document.body.appendChild(this.container);

    // LIGHT, GEOMETRY AND MATERIAL
    this.cubeGeometry = new THREE.CubeGeometry( 2,2, 2 );
    this.wireframeMaterial = new THREE.MeshBasicMaterial({
        color: 0x00ee00,
        wireframe: true,
        transparent: true
    });

    // PROJECTOR

    this.projector = new THREE.Projector();
    var thisIsThis = this;
    document.addEventListener( 'mousedown', function(event) {
        var camera = thisIsThis.camera;
        var mouse = { x: ( event.clientX / window.innerWidth ) * 2 - 1,
                      y: - ( event.clientY / window.innerHeight ) * 2 + 1, };
        var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
        var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
        var mouseVector = new THREE.Vector3( mouse.x, mouse.y, 1 );
        thisIsThis.projector.unprojectVector( mouseVector, camera );
        var intersects = ray.intersectObjects(attributeValues(thisIsThis.objectsByEntityId));
    }, false );

    // Hack for Physics2 scene
    this.pointLight = new THREE.PointLight(0xffffff);
    this.pointLight.position.set(-100,200,100);
}

ThreeView.prototype = {

    constructor: ThreeView,

    render: function() {
        // checkDefined(this.scene, this.camera);
        this.renderer.render(this.scene, this.camera);
    },

    addOrUpdate: function(entity, placeable, meshComp) {
        checkDefined(entity, placeable, meshComp);
        checkDefined(entity.id);
        var threeObject = this.objectsByEntityId[entity.id];
        var url = meshComp.meshRef.value.ref;
        if (threeObject === undefined) {
            if (useCubes) {
                threeObject = new THREE.Mesh(this.cubeGeometry, this.wireframeMaterial);
                this.objectsByEntityId[entity.id] = threeObject;
                this.scene.add(threeObject);
                if (useSignals)
                    this.connectToPlaceable(this, threeObject, placeable);
            } else if (url === 'lightsphere.mesh') {
                this.objectsByEntityId[entity.id] = this.pointLight;
                this.scene.add(this.pointLight);
                this.updateFromTransform(this.pointLight, placeable);
                if (useSignals)
                    this.connectToPlaceable(this, this.pointLight, placeable);
            } else {
                url = url.replace(/\.mesh$/i, ".json")
                var entitiesForUrl = this.meshCache[url];
                var firstRef = false;
                if (entitiesForUrl === undefined) {
                    this.meshCache[url] = entitiesForUrl = [];
                    firstRef = true;
                }
                entitiesForUrl.push(entity);
                if (!firstRef)
                    return;
                console.log("new mesh ref:", url);
                var thisIsThis = this;
                this.jsonLoad(url, function (geometry, material) {
                    thisIsThis.addMeshToEntities(geometry, material, url);
                    console.log("loaded & updated to scene:", url);
                });
            }
        } else {
            this.updateFromTransform(threeObject, placeable);
        }
    },

    addMeshToEntities: function(geometry, material, url) {
        var entities = this.meshCache[url];
        checkDefined(entities);
        //material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5 } );
        for (var i = 0; i < entities.length; i++) {
            var ent = entities[i];
            check(ent instanceof Entity);
            var pl = ent.componentByType(cComponentTypePlaceable);
            var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(material));
            if (useSignals) {
                this.connectToPlaceable(this, mesh, pl);
            } else {
                this.updateFromTransform(mesh, pl);
            }
            this.scene.add(mesh);
            this.objectsByEntityId[ent.id] = mesh;
            mesh.userData.entityId = ent.id;
        }
        entities.length = 0;
    },

    jsonLoad: function(url, addCallback) {
        var loader = new THREE.JSONLoader();
        loader.load(url, function(geometry, material) {
            addCallback(geometry, material);
        });
    },

    copyXyz: function(src, dst) {
        dst.x = src.x;
        dst.y = src.y;
        dst.z = src.z;
    },

    copyXyzMapped: function(src, dst, mapfun) {
        dst.x = mapfun(src.x);
        dst.y = mapfun(src.y);
        dst.z = mapfun(src.z);
    },

    degToRad: function(val) {
        return val * (Math.PI / 180);
    },

    updateFromTransform: function(threeMesh, placeable) {
        checkDefined(placeable, threeMesh);
        this.copyXyz(placeable.transform.value.pos, threeMesh.position);
        this.copyXyz(placeable.transform.value.scale, threeMesh.scale);
        this.copyXyzMapped(placeable.transform.value.rot, threeMesh.rotation, this.degToRad);
        threeMesh.needsUpdate = true;
    },

    connectToPlaceable: function(thisIsThis, threeObject, placeable) {
        thisIsThis.updateFromTransform(threeObject, placeable);
        placeable.attributeChanged.add(function(attr, changeType) {
            thisIsThis.updateFromTransform(threeObject, placeable);
        });
    },
};

<|endoftext|>


<commit_before>/**
 * @file 文本节点类
 * @author errorrik(errorrik@gmail.com)
 */

var inherits = require('../util/inherits');
var each = require('../util/each');
var Node = require('./node');
var isEndStump = require('./is-end-stump');
var warnSetHTML = require('./warn-set-html');
var createANode = require('../parser/create-a-node');
var changeExprCompare = require('../runtime/change-expr-compare');
var removeEl = require('../browser/remove-el');
var ieOldThan9 = require('../browser/ie-old-than-9');

/**
 * 文本节点类
 *
 * @class
 * @param {Object} options 初始化参数
 * @param {ANode} options.aNode 抽象信息节点对象
 * @param {Component} options.owner 所属的组件对象
 */
function TextNode(options) {
    Node.call(this, options);
}

inherits(TextNode, Node);

/**
 * 初始化行为
 *
 * @param {Object} options 初始化参数
 */
TextNode.prototype._init = function (options) {
    Node.prototype._init.call(this, options);

    // #[begin] reverse
    // from el
    if (this.el) {
        this.aNode = createANode({
            isText: 1,
            text: options.stumpText
        });

        this.parent._pushChildANode(this.aNode);

        /* eslint-disable no-constant-condition */
        while (1) {
        /* eslint-enable no-constant-condition */
            var next = options.elWalker.next;
            if (isEndStump(next, 'text')) {
                options.elWalker.goNext();
                removeEl(next);
                break;
            }

            options.elWalker.goNext();
        }

        removeEl(this.el);
        this.el = null;
    }
    // #[end]

    this._static = this.aNode.textExpr.value;
};

/**
 * 生成文本节点的HTML
 *
 * @param {StringBuffer} buf html串存储对象
 */
TextNode.prototype.genHTML = function (buf) {
    buf.push(this.evalExpr(this.aNode.textExpr, 1));
};

/**
 * 刷新文本节点的内容
 */
TextNode.prototype.update = function () {
    var me = this;

    if (!this._located) {
        each(this.parent.childs, function (child, i) {
            if (child === me) {
                me._prev = me.parent.childs[i - 1];
                return false;
            }
        });

        this._located = 1;
    }

    var parentEl = this.parent._getEl();
    var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
    var startRemoveEl = insertBeforeEl;

    while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
        insertBeforeEl = startRemoveEl.nextSibling;
        removeEl(startRemoveEl);
        startRemoveEl = insertBeforeEl;
    }

    var text = this.evalExpr(this.aNode.textExpr, 1);
    if (insertBeforeEl) {
        insertBeforeEl.insertAdjacentHTML('beforebegin', text);
    }
    else if (me._prev) {
        me._prev._getEl().insertAdjacentHTML('afterend', text);
    }
    else {
        // #[begin] error
        warnSetHTML(parentEl);
        // #[end]
        parentEl.innerHTML = text;
    }
};

/**
 * 视图更新函数
 *
 * @param {Array} changes 数据变化信息
 */
TextNode.prototype.updateView = function (changes) {
    var me = this;

    each(changes, function (change) {
        if (changeExprCompare(change.expr, me.aNode.textExpr, me.scope)) {
            me.update();
            return false;
        }
    });
};

exports = module.exports = TextNode;
<commit_msg>little size optimize<commit_after>/**
 * @file 文本节点类
 * @author errorrik(errorrik@gmail.com)
 */

var inherits = require('../util/inherits');
var each = require('../util/each');
var Node = require('./node');
var isEndStump = require('./is-end-stump');
var getNodeStumpParent = require('./get-node-stump-parent');
var warnSetHTML = require('./warn-set-html');
var createANode = require('../parser/create-a-node');
var changeExprCompare = require('../runtime/change-expr-compare');
var removeEl = require('../browser/remove-el');
var ieOldThan9 = require('../browser/ie-old-than-9');

/**
 * 文本节点类
 *
 * @class
 * @param {Object} options 初始化参数
 * @param {ANode} options.aNode 抽象信息节点对象
 * @param {Component} options.owner 所属的组件对象
 */
function TextNode(options) {
    Node.call(this, options);
}

inherits(TextNode, Node);

/**
 * 初始化行为
 *
 * @param {Object} options 初始化参数
 */
TextNode.prototype._init = function (options) {
    Node.prototype._init.call(this, options);

    // #[begin] reverse
    // from el
    if (this.el) {
        this.aNode = createANode({
            isText: 1,
            text: options.stumpText
        });

        this.parent._pushChildANode(this.aNode);

        /* eslint-disable no-constant-condition */
        while (1) {
        /* eslint-enable no-constant-condition */
            var next = options.elWalker.next;
            if (isEndStump(next, 'text')) {
                options.elWalker.goNext();
                removeEl(next);
                break;
            }

            options.elWalker.goNext();
        }

        removeEl(this.el);
        this.el = null;
    }
    // #[end]

    this._static = this.aNode.textExpr.value;
};

/**
 * 生成文本节点的HTML
 *
 * @param {StringBuffer} buf html串存储对象
 */
TextNode.prototype.genHTML = function (buf) {
    buf.push(this.evalExpr(this.aNode.textExpr, 1));
};

/**
 * 刷新文本节点的内容
 */
TextNode.prototype.update = function () {
    var me = this;

    if (!this._located) {
        each(this.parent.childs, function (child, i) {
            if (child === me) {
                me._prev = me.parent.childs[i - 1];
                return false;
            }
        });

        this._located = 1;
    }

    var parentEl = getNodeStumpParent(this);
    var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
    var startRemoveEl = insertBeforeEl;

    while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
        insertBeforeEl = startRemoveEl.nextSibling;
        removeEl(startRemoveEl);
        startRemoveEl = insertBeforeEl;
    }

    var text = this.evalExpr(this.aNode.textExpr, 1);
    if (insertBeforeEl) {
        insertBeforeEl.insertAdjacentHTML('beforebegin', text);
    }
    else if (me._prev) {
        me._prev._getEl().insertAdjacentHTML('afterend', text);
    }
    else {
        // #[begin] error
        warnSetHTML(parentEl);
        // #[end]
        parentEl.innerHTML = text;
    }
};

/**
 * 视图更新函数
 *
 * @param {Array} changes 数据变化信息
 */
TextNode.prototype.updateView = function (changes) {
    var me = this;

    each(changes, function (change) {
        if (changeExprCompare(change.expr, me.aNode.textExpr, me.scope)) {
            me.update();
            return false;
        }
    });
};

exports = module.exports = TextNode;
<|endoftext|>


<commit_before>export default function doubleTapDrag(map) {

	const $map = map._container;

	let isDoubleTap = false;
	let isDragging = false;

	let startZoom = 0;
	let startY = 0;

	$map.addEventListener('touchstart', (e) => {

		// Return early on single tap.
		if (!isDoubleTap) {
			isDoubleTap = true;

			setTimeout(() => {
				isDoubleTap = false;
			}, 300);

			return;

		}

		map.dragging.disable();

		startZoom = map.getZoom();
		startY = e.touches[0].pageY;
		isDragging = true;

	});

	$map.addEventListener('touchend', (e) => {
		map.dragging.enable();
		isDragging = false;
	});

	$map.addEventListener('touchmove', (e) => {

		if (!isDragging) return;

		// Calculate vertical distance from start to finger.
		const y = startY - e.touches[0].pageY;
		const height = $map.getBoundingClientRect().height;

		// Calculate vertical heights from start.
		const posHeight = startY;
		const negHeight = height - posHeight;

		// Equally divide four zoom levels into heights.
		const posStep = posHeight / 4;
		const negStep = negHeight / 4;

		// Increase/Decrease zoom level by step.
		if (y > 0) {
			map.setZoom(startZoom + Math.floor(y / posStep));
		} else {
			map.setZoom(startZoom - Math.floor(-y / negStep));
		}

	});

}
<commit_msg>Cancel double tap drag zoom on multiple fingers (web)<commit_after>export default function doubleTapDrag(map) {

	const $map = map._container;

	let isDoubleTap = false;
	let isDragging = false;

	let startZoom = 0;
	let startY = 0;

	$map.addEventListener('touchstart', (e) => {

		// Return early on single tap.
		if (!isDoubleTap) {
			isDoubleTap = true;

			setTimeout(() => {
				isDoubleTap = false;
			}, 300);

			return;

		}

		map.dragging.disable();

		startZoom = map.getZoom();
		startY = e.touches[0].pageY;
		isDragging = true;

	});

	$map.addEventListener('touchend', (e) => {
		map.dragging.enable();
		isDragging = false;
	});

	$map.addEventListener('touchmove', (e) => {

		if (e.touches.length > 1) return;
		if (!isDragging) return;

		// Calculate vertical distance from start to finger.
		const y = startY - e.touches[0].pageY;
		const height = $map.getBoundingClientRect().height;

		// Calculate vertical heights from start.
		const posHeight = startY;
		const negHeight = height - posHeight;

		// Equally divide four zoom levels into heights.
		const posStep = posHeight / 4;
		const negStep = negHeight / 4;

		// Increase/Decrease zoom level by step.
		if (y > 0) {
			map.setZoom(startZoom + Math.floor(y / posStep));
		} else {
			map.setZoom(startZoom - Math.floor(-y / negStep));
		}

	});

}
<|endoftext|>


<commit_before>Minionette.CollectionView = Minionette.View.extend({
    constructor: function(options) {
        // Initialize a object for our modelViews
        this._modelViews = {};
        // Ensure this has a ModelView to initialize
        // new modelViews from.
        this._ensureModelView(options || {});

        Minionette.View.apply(this, arguments);

        // Make sure we remove our modelViews when this is removed.
        this.listenTo(this, 'remove', this._removeModelViews);
    },

    // Listen to the default events.
    collectionEvents: {
        add: 'addOne',
        remove: 'removeOne',
        reset: 'render',
        sort: 'render'
    },

    // A default useful render function.
    render: function() {
        this.trigger('render', this);

        // Dump all our modelViews.
        this._removeModelViews();

        var $el = this.$el.html(this.template(this._serialize()));
        // Use a DocumentFragment to speed up #render()
        this.$el = $(document.createDocumentFragment());

        // Loop through all our models, and build their view.
        this.collection.each(this.addOne, this);

        // Append the DocumentFragment to the rendered template,
        // and set that as this.$el
        this.$el = $el.append(this.$el);

        this.trigger('rendered', this);

        return this;
    },

    // Add an individual model's view to this.$el.
    addOne: function(model) {
        var view = new this.ModelView({model: model});

        // Add the modelView, and keep track of it.
        this._modelViews[view.cid] = view;
        view._parent = this;

        this.trigger('addOne', view, this);

        this.$el.append(view.render().$el);

        this.trigger('addedOne', view, this);

        return view;
    },

    // Remove an individual model's view from this.$el.
    removeOne: function(model) {
        // This may or may not find a view.
        var view = _.findWhere(this._modelViews, {model: model});

        if (view) {
            this.trigger('removeOne', view, this);
            view.remove();
            this.trigger('removedOne', view, this);
        }

        return view;
    },

    // A hook method that is called during
    // a view#remove().
    _removeView: function(view) {
        delete this._modelViews[view.cid];
    },

    // A callback method bound to the 'remove:before'
    // event. Removes all our modelViews.
    _removeModelViews: function() {
        // Empty the entire $el, that way each individual
        // modelView removal won't trigger a DOM reflow.
        this.$el.empty();
        _.invoke(this._modelViews, 'remove');
    },

    // Sets this.ModelView. Prioritizes instantiated options.ModelView,
    // then a subclass' prototype ModelView, and defaults to Minionette.ModelView
    _ensureModelView: function(options) {
        this.ModelView = options.ModelView || this.ModelView || Minionette.ModelView;
    }
});
<commit_msg>Have CollectionView#render() call View#render()<commit_after>Minionette.CollectionView = Minionette.View.extend({
    constructor: function(options) {
        // Initialize a object for our modelViews
        this._modelViews = {};
        // Ensure this has a ModelView to initialize
        // new modelViews from.
        this._ensureModelView(options || {});

        Minionette.View.apply(this, arguments);

        // Augment #render() with our collection specific items.
        this.on('rendered', this._renderCollectionViews);
        // Make sure we remove our modelViews when this is removed.
        this.on('remove', this._removeModelViews);
    },

    // Listen to the default events.
    collectionEvents: {
        add: 'addOne',
        remove: 'removeOne',
        reset: 'render',
        sort: 'render'
    },

    // A default useful render function.
    render: function() {
        // Remove all our modelViews after the 'render' event is
        // fired. This is set on #render() so that the removing
        // will happen after all other 'render' listeners.
        this.once('render', this._removeModelViews());

        return Minionette.CollectionView.__super__.render.apply(this);
    },

    _renderCollectionViews: function() {
        var $el = this.$el;

        // Use a DocumentFragment to speed up #render()
        this.$el = $(document.createDocumentFragment());

        // Loop through all our models, and build their view.
        this.collection.each(this.addOne, this);

        // Append the DocumentFragment to the rendered template,
        // and set that as this.$el
        this.$el = $el.append(this.$el);

    },

    // Add an individual model's view to this.$el.
    addOne: function(model) {
        var view = new this.ModelView({model: model});

        // Add the modelView, and keep track of it.
        this._modelViews[view.cid] = view;
        view._parent = this;

        this.trigger('addOne', view, this);

        this.$el.append(view.render().$el);

        this.trigger('addedOne', view, this);

        return view;
    },

    // Remove an individual model's view from this.$el.
    removeOne: function(model) {
        // This may or may not find a view.
        var view = _.findWhere(this._modelViews, {model: model});

        if (view) {
            this.trigger('removeOne', view, this);
            view.remove();
            this.trigger('removedOne', view, this);
        }

        return view;
    },

    // A hook method that is called during
    // a view#remove().
    _removeView: function(view) {
        delete this._modelViews[view.cid];
    },

    // A callback method bound to the 'remove:before'
    // event. Removes all our modelViews.
    _removeModelViews: function() {
        // Empty the entire $el, that way each individual
        // modelView removal won't trigger a DOM reflow.
        this.$el.empty();
        _.invoke(this._modelViews, 'remove');
    },

    // Sets this.ModelView. Prioritizes instantiated options.ModelView,
    // then a subclass' prototype ModelView, and defaults to Minionette.ModelView
    _ensureModelView: function(options) {
        this.ModelView = options.ModelView || this.ModelView || Minionette.ModelView;
    }
});
<|endoftext|>


<commit_before>const path = require('path')
const Module = require('module')
const interopRequire = require('interop-require')
const cssHook = require('css-modules-require-hook')
const resolver = require('@sanity/resolver')
const util = require('@sanity/util')

const reduceConfig = util.reduceConfig
const getSanityVersions = util.getSanityVersions

/* eslint-disable no-process-env */
const sanityEnv = process.env.SANITY_ENV
const env = typeof sanityEnv === 'undefined' ? process.env.NODE_ENV : sanityEnv
/* eslint-enable no-process-env */

const configMatcher = /^config:(@?[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+|[A-Za-z0-9_-]+)$/
const resolveParts = resolver.resolveParts
const defaultResult = {
  definitions: {},
  implementations: {},
  plugins: []
}

function registerLoader(options) {
  if (!options) {
    throw new Error('`registerLoader()` requires an options object')
  }

  const basePath = options.basePath || process.cwd()

  // Resolve actual parts only if basePath is set,
  // otherwise use empty defaults
  const parts = options.basePath
    ? resolveParts({basePath, sync: true})
    : Object.assign({}, defaultResult)

  // Configuration files are loaded with a custom prefix
  const configPath = path.join(basePath, 'config')

  // Turn {"partName": [{path: "/foo/bar.js"}]} into {"partName": ["/foo/bar.js"]}
  parts.implementations = Object.keys(parts.implementations).reduce((implementations, part) => {
    implementations[part] = parts.implementations[part].map(impl => impl.path)
    return implementations
  }, {})

  // Allow passing specific overrides for parts
  const overrides = options.overrides
  if (overrides) {
    Object.keys(overrides).forEach(part => {
      if (!Array.isArray(overrides[part])) {
        throw new Error(`Override for part '${part}' is not an array`)
      }
    })

    parts.implementations = Object.assign(parts.implementations, overrides)
  }

  const realResolve = Module._resolveFilename
  Module._resolveFilename = (request, parent) => {
    // `sanity:debug` returns the whole resolve result
    if (request === 'sanity:debug') {
      const debug = Object.assign({}, parts, {basePath})
      require.cache[request] = getModule(request, debug)
      return request
    }

    if (request === 'sanity:versions') {
      const versions = getSanityVersions(basePath)
      require.cache[request] = getModule(request, versions)
      return request
    }

    const configMatch = request.match(configMatcher)
    if (configMatch) {
      const configOverrides = overrides && overrides[request]
      if (configOverrides && configOverrides.length > 0) {
        require.cache[request] = getModule(request, configOverrides[0])
        return request
      }

      const configFor = configMatch[1]
      if (configFor === 'sanity') {
        const sanityConfig = require(path.join(basePath, 'sanity.json'))
        require.cache[request] = getModule(request, reduceConfig(sanityConfig, env))
        return request
      }

      return path.join(configPath, `${configFor}.json`)
    }

    // Should we load all the implementations or just a single one
    const loadAll = request.indexOf('all:') === 0
    const partName = request.replace(/^all:/, '').replace(/\?$/, '')
    const allowUnimplemented = request.match(/\?$/)

    // If we're loading all the implementations of a part, we can't point to
    // one single file - instead we need to manually "construct" a module
    // consisting of an array which holds all the implementations, then add it
    // to the require cache
    if (loadAll) {
      const implementers = parts.implementations[partName] || []

      // Overrides should be plain objects, not paths to modules
      // Actual resolved parts are paths to implementations
      const implementations =
        overrides && overrides[partName] ? implementers : implementers.map(interopRequire)

      require.cache[request] = getModule(request, implementations.reverse())
      return request
    }

    // If we have no implementations of the part, fall back to the default resolver
    // Note that `all:`-requests should return an empty array, not throw
    if (!parts.implementations[partName]) {
      // If using the "allow unimplemented" (?)-postfix, we want to return undefined
      if (allowUnimplemented) {
        require.cache[request] = getModule(request, undefined)
        return request
      }

      if (!options.allowLocalDependencies) {
        return realResolve(request, parent)
      }

      try {
        return realResolve(request, parent)
      } catch (err) {
        /* intentional noop */
      }

      // Attempt local resolve
      try {
        return realResolve(request, module.parent)
      } catch (deepErr) {
        return undefined
      }
    }

    // "Most significant"-imports can be directly resolved to their implementation,
    // HOWEVER; overwritten implementations needs to be put into cache
    const override = overrides && overrides[partName]
    if (override) {
      require.cache[request] = getModule(request, override[0])
      return request
    }

    const partPath = parts.implementations[partName][0]
    return require.resolve(partPath)
  }

  // Register CSS hook
  if (options.stubCss) {
    require.extensions['.css'] = function stubCssHook(mod, filename) {
      return mod._compile(`module.exports = {} `, filename)
    }
  } else {
    const postcss = require('@sanity/webpack-integration/v3')
    cssHook({
      generateScopedName: options.generateScopedName || '[name]__[local]___[hash:base64:5]',
      prepend: postcss
        .getPostcssPlugins({basePath: basePath})
        .filter(plugin => plugin.postcssPlugin !== 'postcss-import')
    })
  }
}

function getModule(request, moduleExports) {
  return {
    id: request,
    filename: request,
    exports: moduleExports,
    parent: null,
    loaded: true
  }
}

module.exports = registerLoader
<commit_msg>[plugin-loader] Fix resolving paths with query strings<commit_after>const path = require('path')
const Module = require('module')
const interopRequire = require('interop-require')
const cssHook = require('css-modules-require-hook')
const resolver = require('@sanity/resolver')
const util = require('@sanity/util')

const reduceConfig = util.reduceConfig
const getSanityVersions = util.getSanityVersions

/* eslint-disable no-process-env */
const sanityEnv = process.env.SANITY_ENV
const env = typeof sanityEnv === 'undefined' ? process.env.NODE_ENV : sanityEnv
/* eslint-enable no-process-env */

const configMatcher = /^config:(@?[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+|[A-Za-z0-9_-]+)$/
const resolveParts = resolver.resolveParts
const defaultResult = {
  definitions: {},
  implementations: {},
  plugins: []
}

function registerLoader(options) {
  if (!options) {
    throw new Error('`registerLoader()` requires an options object')
  }

  const basePath = options.basePath || process.cwd()

  // Resolve actual parts only if basePath is set,
  // otherwise use empty defaults
  const parts = options.basePath
    ? resolveParts({basePath, sync: true})
    : Object.assign({}, defaultResult)

  // Configuration files are loaded with a custom prefix
  const configPath = path.join(basePath, 'config')

  // Turn {"partName": [{path: "/foo/bar.js"}]} into {"partName": ["/foo/bar.js"]}
  parts.implementations = Object.keys(parts.implementations).reduce((implementations, part) => {
    implementations[part] = parts.implementations[part].map(impl => impl.path)
    return implementations
  }, {})

  // Allow passing specific overrides for parts
  const overrides = options.overrides
  if (overrides) {
    Object.keys(overrides).forEach(part => {
      if (!Array.isArray(overrides[part])) {
        throw new Error(`Override for part '${part}' is not an array`)
      }
    })

    parts.implementations = Object.assign(parts.implementations, overrides)
  }

  const realResolve = Module._resolveFilename
  Module._resolveFilename = (request, parent) => {
    // `sanity:debug` returns the whole resolve result
    if (request === 'sanity:debug') {
      const debug = Object.assign({}, parts, {basePath})
      require.cache[request] = getModule(request, debug)
      return request
    }

    if (request === 'sanity:versions') {
      const versions = getSanityVersions(basePath)
      require.cache[request] = getModule(request, versions)
      return request
    }

    const configMatch = request.match(configMatcher)
    if (configMatch) {
      const configOverrides = overrides && overrides[request]
      if (configOverrides && configOverrides.length > 0) {
        require.cache[request] = getModule(request, configOverrides[0])
        return request
      }

      const configFor = configMatch[1]
      if (configFor === 'sanity') {
        const sanityConfig = require(path.join(basePath, 'sanity.json'))
        require.cache[request] = getModule(request, reduceConfig(sanityConfig, env))
        return request
      }

      return path.join(configPath, `${configFor}.json`)
    }

    // Should we load all the implementations or just a single one
    const loadAll = request.indexOf('all:') === 0
    const partName = request.replace(/^all:/, '').replace(/\?$/, '')
    const allowUnimplemented = request.match(/\?$/)

    // If we're loading all the implementations of a part, we can't point to
    // one single file - instead we need to manually "construct" a module
    // consisting of an array which holds all the implementations, then add it
    // to the require cache
    if (loadAll) {
      const implementers = parts.implementations[partName] || []

      // Overrides should be plain objects, not paths to modules
      // Actual resolved parts are paths to implementations
      const implementations =
        overrides && overrides[partName] ? implementers : implementers.map(interopRequire)

      require.cache[request] = getModule(request, implementations.reverse())
      return request
    }

    // If we have no implementations of the part, fall back to the default resolver
    // Note that `all:`-requests should return an empty array, not throw
    if (!parts.implementations[partName]) {
      // If using the "allow unimplemented" (?)-postfix, we want to return undefined
      if (allowUnimplemented) {
        require.cache[request] = getModule(request, undefined)
        return request
      }

      // Strip any query string stuff
      const pathRequest = request.replace(/\?[^\/]*/g, '')

      if (!options.allowLocalDependencies) {
        return realResolve(pathRequest, parent)
      }

      try {
        return realResolve(pathRequest, parent)
      } catch (err) {
        /* intentional noop */
      }

      // Attempt local resolve
      try {
        return realResolve(pathRequest, module.parent)
      } catch (deepErr) {
        return undefined
      }
    }

    // "Most significant"-imports can be directly resolved to their implementation,
    // HOWEVER; overwritten implementations needs to be put into cache
    const override = overrides && overrides[partName]
    if (override) {
      require.cache[request] = getModule(request, override[0])
      return request
    }

    const partPath = parts.implementations[partName][0]
    return require.resolve(partPath)
  }

  // Register CSS hook
  if (options.stubCss) {
    require.extensions['.css'] = function stubCssHook(mod, filename) {
      return mod._compile(`module.exports = {} `, filename)
    }
  } else {
    const postcss = require('@sanity/webpack-integration/v3')
    cssHook({
      generateScopedName: options.generateScopedName || '[name]__[local]___[hash:base64:5]',
      prepend: postcss
        .getPostcssPlugins({basePath: basePath})
        .filter(plugin => plugin.postcssPlugin !== 'postcss-import')
    })
  }
}

function getModule(request, moduleExports) {
  return {
    id: request,
    filename: request,
    exports: moduleExports,
    parent: null,
    loaded: true
  }
}

module.exports = registerLoader
<|endoftext|>


<commit_before>Package.describe({
  summary: "Unstyled version of login widgets"
});

Package.on_use(function (api) {
  api.use(['deps', 'service-configuration', 'accounts-base',
           'underscore', 'templating',
           'handlebars', 'spark', 'session'], 'client');
  // Export Accounts (etc) to packages using this one.
  api.imply('accounts-base', ['client', 'server']);

  // Allow us to call Accounts.oauth.serviceNames, if there are any OAuth
  // services.
  api.use('accounts-oauth', {weak: true});
  // Allow us to directly test if accounts-password (which doesn't use
  // Accounts.oauth.registerService) exists.
  api.use('accounts-password', {weak: true});

  api.add_files([
    'accounts_ui.js',

    'login_buttons.html',
    'login_buttons_single.html',
    'login_buttons_dropdown.html',
    'login_buttons_dialogs.html',

    'login_buttons_session.js',

    'login_buttons.js',
    'login_buttons_single.js',
    'login_buttons_dropdown.js',
    'login_buttons_dialogs.js'], 'client');
});

Package.on_test(function (api) {
  api.use('accounts-ui-unstyled');
  api.use('tinytest');
  api.add_files('accounts_ui_tests.js', 'client');
});
<commit_msg>remove old package dependencies of accounts-ui<commit_after>Package.describe({
  summary: "Unstyled version of login widgets"
});

Package.on_use(function (api) {
  api.use(['deps', 'service-configuration', 'accounts-base',
           'underscore', 'templating', 'session'], 'client');
  // Export Accounts (etc) to packages using this one.
  api.imply('accounts-base', ['client', 'server']);

  // Allow us to call Accounts.oauth.serviceNames, if there are any OAuth
  // services.
  api.use('accounts-oauth', {weak: true});
  // Allow us to directly test if accounts-password (which doesn't use
  // Accounts.oauth.registerService) exists.
  api.use('accounts-password', {weak: true});

  api.add_files([
    'accounts_ui.js',

    'login_buttons.html',
    'login_buttons_single.html',
    'login_buttons_dropdown.html',
    'login_buttons_dialogs.html',

    'login_buttons_session.js',

    'login_buttons.js',
    'login_buttons_single.js',
    'login_buttons_dropdown.js',
    'login_buttons_dialogs.js'], 'client');
});

Package.on_test(function (api) {
  api.use('accounts-ui-unstyled');
  api.use('tinytest');
  api.add_files('accounts_ui_tests.js', 'client');
});
<|endoftext|>


<commit_before>Titanium.include("/aux/functions.js");

Ti.App.background = '#fff';
Ti.App.color = '#000';
Ti.App.button = 'red';
Ti.App.buttoncolor = '#000';

function ApplicationWindow(title,num) {
	var top = 10;
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:Ti.App.background
	});

	if(num == 1) {
		window1(self);
	} else if(num == 2) {
		window2(self);
	} else if(num == 3) {
		window3(self);
	}
	return self;
};

function window1(winorg) {
	Ti.Geolocation.purpose = "Recieve User Location";

	var win = Ti.UI.createScrollView({
		top : 0,
		left : 0,
		width: '100%',
		height: 'auto',
		backgroundColor : Ti.App.background,

	});

	var actind = Ti.UI.createActivityIndicator({
	  color: '#9C9C9C',
	  font: {fontFamily:'Helvetica Neue', fontSize:26, fontWeight:'bold'},
	  message: 'Loading...',
	  top:150,
	  left:80,
	  height:'auto',
	  width:'auto'
	});

	var top = 10;
	createPhotoObj(win, 'img1', top, 10);
	createPhotoObj(win, 'img2', top, 110);
	createPhotoObj(win, 'img3', top, 220);

	top = top + 50;
	createHeader(win,top, 10, 'Pictures');

	top = top + 30;
	maptop = top;
	Ti.Geolocation.purpose = "Recieve User Location";
	Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
	Titanium.Geolocation.distanceFilter = 0;

	function createMapLocation(e) {
		if (!e.success || e.error) {
			createLocation(win,maptop, 0, 200, Ti.App.currentlat, Ti.App.currentlng);
//			var msg = 'error: ' + JSON.stringify(e.error);
//			alert(msg);
		}
		else {
			var accuracy = e.coords.accuracy;
			var timestamp = e.coords.timestamp;
			createLocation(win,maptop, 0, 200, e.coords.latitude, e.coords.longitude);
		}
	}

	Titanium.Geolocation.getCurrentPosition(createMapLocation);

	top = top + 210;
	var location = Titanium.UI.createLabel({top : top+4, left: 10, width: 20, height : 20, text: '', backgroundImage: '/images/location.png'
	});
	Ti.App.addr = createTextInput(win,top, 40, 'no location');

	Ti.App.location = location;
	location.addEventListener('click', function(e) {
		actind.show();
		Titanium.Geolocation.getCurrentPosition(function(e) {

			try {
				var lng = e.coords.longitude;
				var lat = e.coords.latitude;
				var altitude = e.coords.altitude;
				var heading = e.coords.heading;
				var accuracy = e.coords.accuracy;
				var speed = e.coords.speed;
				var timestamp = e.coords.timestamp;
				var altitudeAccuracy = e.coords.altitudeAccuracy;
				Ti.App.currentlat = lat;
				Ti.App.currentlng = lng;

				Titanium.Geolocation.reverseGeocoder(lat,lng,function(evt)
				{
					var place = evt.places[0];
					var address = place.address;
					var addressArry = address.split(',');
					var state = addressArry[(addressArry.length - 3)];
					var street = place.street; // + " " + place.streetname;
					var city = place.city;
					var zip = place.zipcode;
					var totaladdr = street + ", " + city + ", " + state + " " + zip;

					if (evt.success) {
						actind.hide();
						var text = "";
						Ti.App.addr.value = totaladdr;
					} else {
						actind.hide();
						Ti.UI.createAlertDialog({
							title:'Forward geo error',
							message:evt.error
						}).show();
						Ti.API.info("Code translation: "+translateErrorCode(e.code));
					}
				});
			} catch (e) {
				actind.hide();
				mysimpleAlert("","Address not found at this time. Please enter manually");
			}

		});
	});

	win.add(location);

	top = top + 40;
	var desc1 = createTextInput(win, top, 10, 'Description');

	top = top + 40;
	var desc2 = createTextInput(win, top, 10, 'Why');

	top = top + 50;
	var submit = Titanium.UI.createLabel({top : top, left: 26, width: 100, height : 24, text: 'Submit', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	submit.addEventListener('click', function(e) {

		alert("SUBMITTED");
		// var url = "https://api.tropo.com/1.0/sessions?action=create&token=18cdf0354dd2a548ae3633c86b397d7bdcdf6ed1e24b14395a39a19088114c869c9146f6f75eb20b0671deef&numberToDial=4043579411&msg=MESSAGE_GOES_HERE";
		// var client = Ti.Network.createHTTPClient({
			// // function called when the response data is available
			// onload : function(e) {
				// Ti.API.info("Received text: " + this.responseText);
				// //alert('success');
			// },
			// // function called when an error occurs, including a timeout
			// onerror : function(e) {
				// Ti.API.debug(e.error);
				// alert('error');
			// },
			// timeout : 5000 // in milliseconds
		// });
		// // Prepare the connection.
		// client.open("GET", url);
		// // Send the request.
		// client.send();

	});

	win.add(submit);
	var cancel = Titanium.UI.createLabel({top : top, left: 150, width: 100, height : 24, text: 'Cancel', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	cancel.addEventListener('click', function(e) {
		deleteImages(e.source.view);
//		desc1.value='';
	});

	win.add(cancel);

	top = top + 60;
	var but2 = Titanium.UI.createLabel({top : top, left: 26, right: 26, height : 24, text: '',
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}
	});

	win.add(but2);
//	winorg.add(actind);
	winorg.add(win);

}
function window2(win) {
	Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
	Titanium.Geolocation.distanceFilter = 0;

	function createMapLocation(e) {
		if (!e.success || e.error) {

//			createLocation(win,0, 0, 600, Ti.App.currentlat, Ti.App.currentlng);
		}
		else {
			var accuracy = e.coords.accuracy;
			var timestamp = e.coords.timestamp;
//			createLocation(win,0, 0, 600, e.coords.latitude, e.coords.longitude);
		}
	}
	Titanium.Geolocation.getCurrentPosition(createMapLocation);

}

function window3(win) {
	var top = 40;
	var desc1 = createTextInput(win, top, 10, 'Your phone number');
	//desc1.value = '';  // override phone # here for testing

	top = top + 50;
	var submit2 = Titanium.UI.createLabel({top : top, left: 26, width: 100, height : 24, text: 'Submit', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	submit2.addEventListener('click', function(e) {

		var strippedPhoneNum = desc1.value.replace(/[^0-9]/g, '');

		//alert("SUBMITTED");
		// msg_type=sms
		var url = "https://api.tropo.com/1.0/sessions?action=create&token=18cdf0354dd2a548ae3633c86b397d7bdcdf6ed1e24b14395a39a19088114c869c9146f6f75eb20b0671deef&numberToDial="+strippedPhoneNum+"&msg=THANK_YOU_FOR_REPORTING_A_SIDEWALK_HAZARD.,,YOUR_HELP_IS_GREATLY_APPRECIATED.,,PLEASE_PRESS_ONE_TO_CONFIRM_THAT_YOU_INITIATED_THIS_REQUEST&message_type=CALL";
		var client = Ti.Network.createHTTPClient({
			// function called when the response data is available
			onload : function(e) {
				Ti.API.info("Received text: " + this.responseText);
				alert('Thank you.  You will receive a confirmation call shortly.');
			},
			// function called when an error occurs, including a timeout
			onerror : function(e) {
				Ti.API.debug(e.error);
				alert('error');
			},
			timeout : 5000 // in milliseconds
		});
		// Prepare the connection.
		client.open("GET", url);
		// Send the request.
		client.send();

	});
	win.add(submit2);

}
module.exports = ApplicationWindow;
<commit_msg>add blue for phone # field<commit_after>Titanium.include("/aux/functions.js");

Ti.App.background = '#fff';
Ti.App.color = '#000';
Ti.App.button = 'red';
Ti.App.buttoncolor = '#000';

function ApplicationWindow(title,num) {
	var top = 10;
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:Ti.App.background
	});

	if(num == 1) {
		window1(self);
	} else if(num == 2) {
		window2(self);
	} else if(num == 3) {
		window3(self);
	}
	return self;
};

function window1(winorg) {
	Ti.Geolocation.purpose = "Recieve User Location";

	var win = Ti.UI.createScrollView({
		top : 0,
		left : 0,
		width: '100%',
		height: 'auto',
		backgroundColor : Ti.App.background,

	});

	var actind = Ti.UI.createActivityIndicator({
	  color: '#9C9C9C',
	  font: {fontFamily:'Helvetica Neue', fontSize:26, fontWeight:'bold'},
	  message: 'Loading...',
	  top:150,
	  left:80,
	  height:'auto',
	  width:'auto'
	});

	var top = 10;
	createPhotoObj(win, 'img1', top, 10);
	createPhotoObj(win, 'img2', top, 110);
	createPhotoObj(win, 'img3', top, 220);

	top = top + 50;
	createHeader(win,top, 10, 'Pictures');

	top = top + 30;
	maptop = top;
	Ti.Geolocation.purpose = "Recieve User Location";
	Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
	Titanium.Geolocation.distanceFilter = 0;

	function createMapLocation(e) {
		if (!e.success || e.error) {
			createLocation(win,maptop, 0, 200, Ti.App.currentlat, Ti.App.currentlng);
//			var msg = 'error: ' + JSON.stringify(e.error);
//			alert(msg);
		}
		else {
			var accuracy = e.coords.accuracy;
			var timestamp = e.coords.timestamp;
			createLocation(win,maptop, 0, 200, e.coords.latitude, e.coords.longitude);
		}
	}

	Titanium.Geolocation.getCurrentPosition(createMapLocation);

	top = top + 210;
	var location = Titanium.UI.createLabel({top : top+4, left: 10, width: 20, height : 20, text: '', backgroundImage: '/images/location.png'
	});
	Ti.App.addr = createTextInput(win,top, 40, 'no location');

	Ti.App.location = location;
	location.addEventListener('click', function(e) {
		actind.show();
		Titanium.Geolocation.getCurrentPosition(function(e) {

			try {
				var lng = e.coords.longitude;
				var lat = e.coords.latitude;
				var altitude = e.coords.altitude;
				var heading = e.coords.heading;
				var accuracy = e.coords.accuracy;
				var speed = e.coords.speed;
				var timestamp = e.coords.timestamp;
				var altitudeAccuracy = e.coords.altitudeAccuracy;
				Ti.App.currentlat = lat;
				Ti.App.currentlng = lng;

				Titanium.Geolocation.reverseGeocoder(lat,lng,function(evt)
				{
					var place = evt.places[0];
					var address = place.address;
					var addressArry = address.split(',');
					var state = addressArry[(addressArry.length - 3)];
					var street = place.street; // + " " + place.streetname;
					var city = place.city;
					var zip = place.zipcode;
					var totaladdr = street + ", " + city + ", " + state + " " + zip;

					if (evt.success) {
						actind.hide();
						var text = "";
						Ti.App.addr.value = totaladdr;
					} else {
						actind.hide();
						Ti.UI.createAlertDialog({
							title:'Forward geo error',
							message:evt.error
						}).show();
						Ti.API.info("Code translation: "+translateErrorCode(e.code));
					}
				});
			} catch (e) {
				actind.hide();
				mysimpleAlert("","Address not found at this time. Please enter manually");
			}

		});
	});

	win.add(location);

	top = top + 40;
	var desc1 = createTextInput(win, top, 10, 'Description');

	top = top + 40;
	var desc2 = createTextInput(win, top, 10, 'Why');

	top = top + 50;
	var submit = Titanium.UI.createLabel({top : top, left: 26, width: 100, height : 24, text: 'Submit', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	submit.addEventListener('click', function(e) {

		alert("SUBMITTED");
		// var url = "https://api.tropo.com/1.0/sessions?action=create&token=18cdf0354dd2a548ae3633c86b397d7bdcdf6ed1e24b14395a39a19088114c869c9146f6f75eb20b0671deef&numberToDial=4043579411&msg=MESSAGE_GOES_HERE";
		// var client = Ti.Network.createHTTPClient({
			// // function called when the response data is available
			// onload : function(e) {
				// Ti.API.info("Received text: " + this.responseText);
				// //alert('success');
			// },
			// // function called when an error occurs, including a timeout
			// onerror : function(e) {
				// Ti.API.debug(e.error);
				// alert('error');
			// },
			// timeout : 5000 // in milliseconds
		// });
		// // Prepare the connection.
		// client.open("GET", url);
		// // Send the request.
		// client.send();

	});

	win.add(submit);
	var cancel = Titanium.UI.createLabel({top : top, left: 150, width: 100, height : 24, text: 'Cancel', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	cancel.addEventListener('click', function(e) {
		deleteImages(e.source.view);
//		desc1.value='';
	});

	win.add(cancel);

	top = top + 60;
	var but2 = Titanium.UI.createLabel({top : top, left: 26, right: 26, height : 24, text: '',
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}
	});

	win.add(but2);
//	winorg.add(actind);
	winorg.add(win);

}
function window2(win) {
	Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
	Titanium.Geolocation.distanceFilter = 0;

	function createMapLocation(e) {
		if (!e.success || e.error) {

//			createLocation(win,0, 0, 600, Ti.App.currentlat, Ti.App.currentlng);
		}
		else {
			var accuracy = e.coords.accuracy;
			var timestamp = e.coords.timestamp;
//			createLocation(win,0, 0, 600, e.coords.latitude, e.coords.longitude);
		}
	}
	Titanium.Geolocation.getCurrentPosition(createMapLocation);

}

function window3(win) {
	var top = 40;
	var desc1 = createTextInput(win, top, 10, 'Your phone number');
	//desc1.value = '';  // override phone # here for testing

	top = top + 50;
	var submit2 = Titanium.UI.createLabel({top : top, left: 26, width: 100, height : 24, text: 'Submit', backgroundColor: Ti.App.button,
 		textAlign: 'center', font : {fontSize : '16', fontWeight : 'bold', fontFamily : 'Arial'}, color: Ti.App.buttoncolor
	});

	submit2.addEventListener('click', function(e) {

		desc1.blur();

		var strippedPhoneNum = desc1.value.replace(/[^0-9]/g, '');

		//alert("SUBMITTED");
		// msg_type=sms
		var url = "https://api.tropo.com/1.0/sessions?action=create&token=18cdf0354dd2a548ae3633c86b397d7bdcdf6ed1e24b14395a39a19088114c869c9146f6f75eb20b0671deef&numberToDial="+strippedPhoneNum+"&msg=THANK_YOU_FOR_REPORTING_A_SIDEWALK_HAZARD.,,YOUR_HELP_IS_GREATLY_APPRECIATED.,,PLEASE_PRESS_ONE_TO_CONFIRM_THAT_YOU_INITIATED_THIS_REQUEST&message_type=CALL";
		var client = Ti.Network.createHTTPClient({
			// function called when the response data is available
			onload : function(e) {
				Ti.API.info("Received text: " + this.responseText);
				alert('Thank you.  You will receive a confirmation call shortly.');
			},
			// function called when an error occurs, including a timeout
			onerror : function(e) {
				Ti.API.debug(e.error);
				alert('error');
			},
			timeout : 5000 // in milliseconds
		});
		// Prepare the connection.
		client.open("GET", url);
		// Send the request.
		client.send();

	});
	win.add(submit2);

}
module.exports = ApplicationWindow;
<|endoftext|>


<commit_before>(function(undefined) {
    var gaffa = window.gaffa,
        viewType = "checkbox",
		cachedElement;

    function Checkbox(){}
    Checkbox = gaffa.createSpec(Checkbox, gaffa.View);
    Checkbox.prototype.type = viewType;

    Checkbox.prototype.render = function(){
         var classes = viewType;

        var renderedElement = document.createElement('span'),
            label = document.createElement('label'),
            checkboxId = parseInt(Math.random() * 100000), //Dodgy as.... don't like it? submit a pull request.
            checkbox = $(document.createElement('input')).attr('type', 'checkbox').attr('id', checkboxId)[0];

        $(checkbox).bind(this.updateEventName || "change", function(event){
            var viewModel = $(this).parent()[0].viewModel;
            window.gaffa.propertyUpdaters.bool(viewModel, viewModel.checked, $(this).is(":checked"));
        });
        label.setAttribute('for', checkboxId);
        renderedElement.appendChild(checkbox);
        renderedElement.appendChild(label);
        renderedElement.className = classes;

        this.views.content.element = label;

        this.renderedElement = renderedElement;

        this.__super__.render.apply(this, arguments);
    };

    Checkbox.prototype.checked = new gaffa.Property(function() {
        if(this.checked.value){
            $(this.renderedElement).children('input').attr("checked", "checked");
        }else{
            $(this.renderedElement).children('input').removeAttr("checked");
        }
    });
    Checkbox.prototype.text = new gaffa.Property(window.gaffa.propertyUpdaters.string("text", function(viewModel, value){
        if(value !== null && value !== undefined){
            $(viewModel.renderedElement).find('label').text(value);
        }else{
            $(viewModel.renderedElement).find('label').text("");
        }
    }));

    gaffa.views[viewType] = Checkbox;

})();<commit_msg>checkbox bugfix<commit_after>(function(undefined) {
    var gaffa = window.gaffa,
        viewType = "checkbox",
		cachedElement;

    function Checkbox(){
        this.views.content = new gaffa.ViewContainer(this.views.content);
    }
    Checkbox = gaffa.createSpec(Checkbox, gaffa.ContainerView);
    Checkbox.prototype.type = viewType;

    Checkbox.prototype.render = function(){
         var classes = viewType;

        var renderedElement = document.createElement('span'),
            label = document.createElement('label'),
            checkboxId = parseInt(Math.random() * 100000), //Dodgy as.... don't like it? submit a pull request.
            checkbox = $(document.createElement('input')).attr('type', 'checkbox').attr('id', checkboxId)[0];

        $(checkbox).bind(this.updateEventName || "change", function(event){
            var viewModel = $(this).parent()[0].viewModel;
            window.gaffa.propertyUpdaters.bool(viewModel, viewModel.checked, $(this).is(":checked"));
        });
        label.setAttribute('for', checkboxId);
        renderedElement.appendChild(checkbox);
        renderedElement.appendChild(label);
        renderedElement.className = classes;

        this.views.content.element = label;

        this.renderedElement = renderedElement;

        this.__super__.render.apply(this, arguments);
    };

    Checkbox.prototype.checked = new gaffa.Property(function() {
        if(this.checked.value){
            $(this.renderedElement).children('input').attr("checked", "checked");
        }else{
            $(this.renderedElement).children('input').removeAttr("checked");
        }
    });
    Checkbox.prototype.text = new gaffa.Property(window.gaffa.propertyUpdaters.string("text", function(viewModel, value){
        if(value !== null && value !== undefined){
            $(viewModel.renderedElement).find('label').text(value);
        }else{
            $(viewModel.renderedElement).find('label').text("");
        }
    }));

    gaffa.views[viewType] = Checkbox;

})();<|endoftext|>