<commit_before>/*
Fractaltrees.js
By
DevBySam
*/

void function () {
	//Declare variables travel, branchWidth, canvas, and the canvas context
	var travel = 100 , branchWidth = 10
	//Draw canvas and set 2D context
	var canvas = document.getElementById('mycanvas')
	var ctx = canvas.getContext('2d')
	//set width and height of canvas to fill screen
	canvas.width = window.innerWidth
	canvas.height = window.innerHeight
  ctx.globalCompositeOperation; //Sets context
	var fractalTree = function () {
		ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
		//Defines placement of tree relative to window, also
		drawTree(ctx, (window.innerWidth/2), (window.innerHeight/1), 40, -Math.PI/2, travel+10, branchWidth)
		/* fractalTree accesses the clearRect() method of Canvas's 2d API with starting point (0,0) and size
		set to window.innerWidth and .innerHeight
		*/
	}
	//Define drawTree var as function that has following variables as parameters
	var drawTree = function (ctx, startX, startY, length, angle, travel, branchWidth) {
		var rand = Math.random, dept,
			newLength, newAngle,
			mainBranch = 3,
			endX, endY, maxAngle = Math.PI /2;
		//Creates new canvas path
		ctx.beginPath()
		//Sets new trees to defined x and y coordinates - placed in center
		ctx.moveTo(startX, startY)
		//defines x and y end values by start values
		endX = startX + length * Math.cos(angle)
		endY = startY + length * Math.sin(angle)
		//uses lineCap canvas property to round the lines
		ctx.lineCap = 'round'
		ctx.lineWidth = branchWidth
		ctx.lineTo(endX, endY)
		ctx.strokeStyle = '#df800e'
		ctx.stroke()
		newTravel = travel
		if (!newTravel) return
		subBranches = mainBranch -1
		/*This is where the recursion really occurs!
		Each new child branch is .7x the size of its parent branch,
		so they are generated infinitely until they "fizzle out". */
		branchWidth *= .7
		for (var i = 0; i < subBranches; i++) {
			/*set new angles defined by a formula
			that is based on the max angle multiplied by a random value.
			The value can't be negative because the branches will turn in onto themselves!
			*/
			newAngle = angle + rand()*maxAngle - maxAngle*.5
			newLength = length * (.7 + rand()*.5)
			/*uses setTimeout method with input as the drawTree function that draws tree
			and its parameters. Expression is evaluated after 60 ms.
			*/
			setTimeout(function () {
				drawTree(ctx, endX, endY, newLength, newAngle, newTravel, branchWidth);
				}, 60)
		}
	}
	/*adds event listener that detects whether DOM has loaded, runs fractalTree regardless if content has loaded
	so it triggers more quickly */
	document.addEventListener('DOMContentLoaded',function(){
		fractalTree()
	}, false);
}();
<commit_msg>Added recursive call explanation<commit_after>/*
Fractaltrees.js
By
DevBySam
*/

void function () {
	//Declare variables travel, branchWidth, canvas, and the canvas context
	var travel = 100 , branchWidth = 10
	//Draw canvas and set 2D context
	var canvas = document.getElementById('mycanvas')
	var ctx = canvas.getContext('2d')
	//set width and height of canvas to fill screen
	canvas.width = window.innerWidth
	canvas.height = window.innerHeight
  ctx.globalCompositeOperation; //Sets context
	var fractalTree = function () {
		ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
		//Defines placement of tree relative to window, also
		drawTree(ctx, (window.innerWidth/2), (window.innerHeight/1), 40, -Math.PI/2, travel+10, branchWidth)
		/* fractalTree accesses the clearRect() method of Canvas's 2d API with starting point (0,0) and size
		set to window.innerWidth and .innerHeight
		*/
	}
	//Define drawTree var as function that has following variables as parameters
	var drawTree = function (ctx, startX, startY, length, angle, travel, branchWidth) {
		var rand = Math.random, dept,
			newLength, newAngle,
			mainBranch = 3,
			endX, endY, maxAngle = Math.PI /2;
		//Creates new canvas path
		ctx.beginPath()
		//Sets new trees to defined x and y coordinates - placed in center
		ctx.moveTo(startX, startY)
		//defines x and y end values by start values
		endX = startX + length * Math.cos(angle)
		endY = startY + length * Math.sin(angle)
		//uses lineCap canvas property to round the lines
		ctx.lineCap = 'round'
		ctx.lineWidth = branchWidth
		ctx.lineTo(endX, endY)
		ctx.strokeStyle = '#df800e'
		ctx.stroke()
		newTravel = travel
		if (!newTravel) return
		subBranches = mainBranch -1
		//Recursive call to generate child branches
		Each new child branch is .7x the size of its parent branch,
		so they are generated infinitely until they "fizzle out". */
		branchWidth *= .7
		for (var i = 0; i < subBranches; i++) {
			/*set new angles defined by a formula
			that is based on the max angle multiplied by a random value.
			The value can't be negative because the branches will turn in onto themselves!
			*/
			newAngle = angle + rand()*maxAngle - maxAngle*.5
			newLength = length * (.7 + rand()*.5)
			/*uses setTimeout method with input as the drawTree function that draws tree
			and its parameters. Expression is evaluated after 60 ms.
			*/
			setTimeout(function () {
				drawTree(ctx, endX, endY, newLength, newAngle, newTravel, branchWidth);
				}, 60)
		}
	}
	/*adds event listener that detects whether DOM has loaded, runs fractalTree regardless if content has loaded
	so it triggers more quickly */
	document.addEventListener('DOMContentLoaded',function(){
		fractalTree()
	}, false);
}();
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 * @preventMunge
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var Immutable                                    = require('immutable');
var {Vector, Map, OrderedMap, Record}            = Immutable;
var {isSchema, isList, isMapping, isScalar, isDynamic} = require('./schema');
var ValidationResult                             = require('./ValidationResult');
var mergeInto                                    = require('./mergeInto');
var merge                                        = require('./merge');
var invariant                                    = require('./invariant');
var validate                                     = require('./validate');
var emptyFunction                                = require('./emptyFunction');
var toArray                                      = require('./toArray');

var DIRTY_KEY = '__react_forms_dirty__';

/**
 * Serves as a immutable container for form value attributes.
 */
var ValueAttributes = Record({
  schema: null,
  value: null,
  validation: null,
  externalValidation: null,
  serialized: null
}, 'ValueAttributes');

/**
 * Reference to the current form value.
 */
class Value {

  constructor(attributes, root, path) {
    this._attributes = attributes;
    this._root = root;
    this._cache = {};
    this._schema = null;
    this.path = path;
  }

  equals(other) {
    var equals = (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      Immutable.is(this.value, other.value) &&
      Immutable.is(this.serialized, other.serialized) &&
      Immutable.is(this.validation, other.validation) &&
      Immutable.is(this.externalValidation, other.externalValidation) &&
      this.dirty === other.dirty &&
      this._root.get('onUpdate') === other._root.get('onUpdate')
    );
    return equals;
  }

  _child(key, value) {
    if (this._cache[key]) {
      return this._cache[key];
    }

    var schema = this.schema.child(key);
    value = value !== undefined ? value : this.value.get(key);
    if (isDynamic(schema)) {
      schema = schema.instantiate(value);
    }
    var serialized = this.serialized.get(key);
    var validation = this.validation.child(key);
    var externalValidation = this.externalValidation ?
      this.externalValidation.child(key) :
      ValidationResult.success;

    var attributes;
    if (value === undefined) {
      value = _defaultValue(schema);
      attributes = makeAttributes({schema, value, serialized, validation, externalValidation});
    } else {
      attributes = {schema, value, serialized, validation, externalValidation};
    }

    var ctor = _getCtor(schema);
    return (this._cache[key] = new ctor(
      this._attributes.merge(attributes),
      this._root,
      this.path.concat(key)
    ));
  }

  child(...key) {
    var value = this;
    for (var i = 0, len = key.length; i < len; i++) {
      value = value._child(key[i]);
    }
    return value;
  }

  childIn(keyPath) {
    return this.child.apply(this, keyPath);
  }

  update(newValue) {
    var trace = valueTraceByPath(this.root, this.path);
    var attributes;
    for (var i = 0, len = trace.length; i < len; i++) {
      var value = trace[i];
      if (i === 0) {
        var schema = value._attributes.schema.instantiate(newValue);
        var onUpdate = schema.props.get('onUpdate');
        if (onUpdate) {
          newValue = onUpdate(newValue);
        }
        attributes = makeAttributes({schema, value: newValue});
      } else {
        attributes = value.onChildUpdate(prevValue.key, attributes);
      }
      var prevValue = value;
    }
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes.merge(attributes),
      this._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  onChildUpdate(key, {value, validation, serialized}) {
    value = this.value.set(key, value);

    var onUpdate = this.schema.props.get('onUpdate');
    if (onUpdate) {
      value = onUpdate(value);
    }

    var schema = this.schema;
    var newSchema = this._attributes.schema.instantiate(value);
    if (!schema.equals(newSchema)) {
      return makeAttributes({schema: newSchema, value}, {strip: true});
    }
    validation = this.validation.updateChild(key, validation);
    validation = validate(this.schema, value, validation.children).validation;
    serialized = this.serialized.set(key, serialized);
    return this._attributes.merge({value, serialized, validation});
  }

  updateChild(key, newValue) {
    return this.child(key).update(newValue).root();
  }

  updateChildIn(keyPath, newValue) {
    return this.childIn(keyPath).update(newValue).root();
  }

  updateSchema(newSchema) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {value, externalValidation}} = this.root;
    return make(
      newSchema, value, externalValidation,
      this._root.get('onUpdate'),
      this._root.get('dirty'),
      this._root.get('rootRef'));
  }

  updateExternalValidation(newExternalValidation) {
    var root = this.root;
    var externalValidation = root.externalValidation.updateChildIn(this.path, newExternalValidation);
    var pendingRootRef = () => root;
    root = new root.constructor(
      root._attributes.merge({externalValidation}),
      root._root.merge({pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  _makeDirty() {
    var dirty = this._root.get('dirty');
    return dirty.updateIn(this.path.concat(DIRTY_KEY), () => true);
  }

  markDirty() {
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes,
      this.root._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  markAsConsistent() {
    return new this.constructor(
      this._attributes,
      this._root.merge({pendingRootRef: null}),
      this.path
    );
  }

  notify() {
    var onUpdate = this._root.get('onUpdate', emptyFunction);
    onUpdate(this);
    return this;
  }
}

Object.defineProperty(Value.prototype, 'key', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    } else {
      return this.path[this.path.length - 1];
    }
  }
});

Object.defineProperty(Value.prototype, 'root', {
  get: function() {
    var ref = this._root.get('pendingRootRef');
    if (!ref) {
      ref = this._root.get('rootRef');
    }
    if (!ref) {
      return this;
    }
    return ref();
  }
});

Object.defineProperty(Value.prototype, 'parent', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    }
    var path = this.path.slice(0);
    path.pop();
    return this.root.childIn(path);
  }
});

Object.defineProperty(Value.prototype, 'schema', {
  get: function() {
    if (this._schema === null) {
      if (isDynamic(this._attributes.schema)) {
        this._schema = this._attributes.schema.instantiate(this._attributes.value);
      } else {
        this._schema = this._attributes.schema;
      }
    }
    return this._schema;
  }
});

Object.defineProperty(Value.prototype, 'value', {
  get: function() {
    return this._attributes.value;
  }
});

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    var serialized = this._attributes.serialized;
    if (serialized === undefined) {
      return _defaultValue(this._attributes.schema);
    }
    return serialized;
  }
});

Object.defineProperty(Value.prototype, 'validation', {
  get: function() {
    return this._attributes.validation;
  }
});

Object.defineProperty(Value.prototype, 'externalValidation', {
  get: function() {
    return this._attributes.externalValidation;
  }
});

Object.defineProperty(Value.prototype, 'isValid', {
  get: function() {
    return this.validation.isSuccess;
  }
});

Object.defineProperty(Value.prototype, 'isDirty', {
  get: function() {
    var path = this.path;
    var dirty = this._root.get('dirty');
    for (var i = 0, len = path.length; i < len; i++) {
      if (dirty) {
        if (dirty.get(DIRTY_KEY) || dirty.get(path[i])) {
          return true;
        }
      } else {
        return false;
      }
      dirty = dirty.get(path[i]);
    }
    return dirty && (dirty.get(DIRTY_KEY) || dirty.length > 0);
  }
});

function valueTraceByPath(value, path) {
  var trace = [value];
  for (var i = 0, len = path.length; i < len; i++) {
    value = value.child(path[i]);
    trace.unshift(value);
  }
  return trace;
}

class ScalarValue extends Value {

}

class MappingValue extends Value {

  map(func, context) {
    return this.schema.children
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.schema.children.forEach((_, key) => {
      return func.call(context, this.child(key), key);
    });
  }
}

class ListValue extends Value {

  map(func, context) {
    return this.value
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.value.forEach((_, key) => func.call(context, this.child(key), key));
  }

  emptyChild() {
    return _defaultValue(this.schema.children);
  }

  push(value) {
    var newIndex = this.value.length;
    value = Immutable.fromJS(value);
    return this._child(newIndex, value).update(value).parent;
  }

  splice() {
    var newValue = this.value.splice.apply(this.value, toArray(arguments));
    return this.update(newValue);
  }
}

function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

function isScalarValue(value) {
  return value instanceof ScalarValue;
}

function isMappingValue(value) {
  return value instanceof MappingValue;
}

function isListValue(value) {
  return value instanceof ListValue;
}

function make(schema, value, externalValidation, onUpdate, dirty, rootRef) {
  externalValidation = externalValidation || ValidationResult.success;
  dirty = dirty || Map.empty();
  schema = schema.instantiate(value);
  var attributes = makeAttributes({schema, value, externalValidation}, {root: true});
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(attributes, Map({onUpdate, dirty, rootRef}), []);
  return value;
}

function makeAttributes(args, options) {
  var {schema, value} = args;

  invariant(
    isSchema(schema),
    'make(schema, ...) has received not a schema value as its first argument'
  );

  args = merge(args, {schema});
  if (isScalar(schema)) {
    return _makeScalar(args, options);
  } else if (isMapping(schema)) {
    return _makeMapping(args, options);
  } else if (isList(schema)) {
    return _makeList(args, options);
  }
}

function _makeScalar(args) {
  var {value, schema, validation, serialized} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else {
      return undefined;
    }
  }
  if (validation === undefined) {
    var validationResult = validate(schema, value);
    value = validationResult.value;
    validation = validationResult.validation;
  }
  if (serialized === undefined) {
    serialized = schema.type.serialize(value);
  }
  return new ValueAttributes(merge(args, {value, validation, serialized}));
}

function _makeMapping(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue
    } else if (options.root) {
      value = new OrderedMap();
    } else {
      return undefined;
    }
  }
  if (!(value instanceof OrderedMap)) {
    value = OrderedMap.from(value);
  }

  var _value = {};
  var _serialized = {};
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  schema.children.forEach((schema, name) => {
    schema = schema.instantiate(value.get(name));
    var child = makeAttributes({
      schema,
      value: value.get(name)
    }, {strip: options.strip});
    if (child == null || child.value == null) {
      if (schema.props.get('required')) {
        _hasChildError = true;
        _childrenValidation[name] = ValidationResult.failure('value is required');
      }
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value[name] = childValue;
    _serialized[name] = childSerialized;
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schema, _value);
  }
  value = value.merge(_value);
  if (options.strip) {
    value.forEach((_, key) =>{
      if (!schema.children.has(key)) {
        value = value.remove(key);
      }
    });
  }
  serialized = serialized || OrderedMap.from(_serialized);
  validation = validation || _validation;
  return new ValueAttributes({schema, value, serialized, validation, externalValidation});
}

function _makeList(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue
    } else if (options.root) {
      value = new Vector();
    } else {
      return undefined;
    }
  }
  if (!(value instanceof Vector)) {
    value = Vector.from(value);
  }

  var _value = [];
  var _serialized = [];
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  value.forEach((value, name) => {
    var child = makeAttributes({
      schema: schema.child(name).instantiate(value),
      value
    }, {strip: options.strip});
    if (child === undefined) {
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value.push(childValue);
    _serialized.push(childSerialized);
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schema, _value);
  }
  return new ValueAttributes({
    schema,
    value: Vector.from(_value),
    serialized: serialized || Vector.from(_serialized),
    validation: validation || _validation,
    externalValidation
  });
}

/**
 * Get value constructor for given schema node.
 *
 * @private
 * @param {Schema} schema
 * @returns {Constructor}
 */
function _getCtor(schema) {
  var constructor;
  if (isScalar(schema)) {
    constructor = ScalarValue;
  } else if (isMapping(schema)) {
    constructor = MappingValue;
  } else if (isList(schema)) {
    constructor = ListValue;
  } else {
    invariant(false, 'invalid schema node');
  }
  return constructor;
}

function _defaultValue(schema) {
  if (schema.defaultValue !== undefined) {
    return schema.defaultValue;
  } else if (isMapping(schema)) {
    return OrderedMap.empty();
  } else if (isList(schema)) {
    return Vector.empty();
  } else {
    return null;
  }
}

module.exports = make;
mergeInto(module.exports, {
  isValue, isScalarValue, isMappingValue, isListValue
});
<commit_msg>Value: fixes to List push<commit_after>/**
 * @jsx React.DOM
 * @preventMunge
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var Immutable                                    = require('immutable');
var {Vector, Map, OrderedMap, Record}            = Immutable;
var {isSchema, isList, isMapping, isScalar, isDynamic} = require('./schema');
var ValidationResult                             = require('./ValidationResult');
var mergeInto                                    = require('./mergeInto');
var merge                                        = require('./merge');
var invariant                                    = require('./invariant');
var validate                                     = require('./validate');
var emptyFunction                                = require('./emptyFunction');
var toArray                                      = require('./toArray');

var DIRTY_KEY = '__react_forms_dirty__';

/**
 * Serves as a immutable container for form value attributes.
 */
var ValueAttributes = Record({
  schema: null,
  value: null,
  validation: null,
  externalValidation: null,
  serialized: null
}, 'ValueAttributes');

/**
 * Reference to the current form value.
 */
class Value {

  constructor(attributes, root, path) {
    this._attributes = attributes;
    this._root = root;
    this._cache = {};
    this._schema = null;
    this.path = path;
  }

  equals(other) {
    var equals = (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      Immutable.is(this.value, other.value) &&
      Immutable.is(this.serialized, other.serialized) &&
      Immutable.is(this.validation, other.validation) &&
      Immutable.is(this.externalValidation, other.externalValidation) &&
      this.dirty === other.dirty &&
      this._root.get('onUpdate') === other._root.get('onUpdate')
    );
    return equals;
  }

  _child(key, value) {
    if (this._cache[key]) {
      return this._cache[key];
    }

    var schema = this.schema.child(key);
    value = value !== undefined ? value : this.value.get(key);
    if (isDynamic(schema)) {
      schema = schema.instantiate(value);
    }
    var serialized = this.serialized.get(key);
    var validation = this.validation.child(key);
    var externalValidation = this.externalValidation ?
      this.externalValidation.child(key) :
      ValidationResult.success;

    var attributes;
    if (value === undefined) {
      value = _defaultValue(schema);
      attributes = makeAttributes({schema, value, serialized, validation, externalValidation});
    } else {
      attributes = {schema, value, serialized, validation, externalValidation};
    }

    var ctor = _getCtor(schema);
    return (this._cache[key] = new ctor(
      this._attributes.merge(attributes),
      this._root,
      this.path.concat(key)
    ));
  }

  child(...key) {
    var value = this;
    for (var i = 0, len = key.length; i < len; i++) {
      value = value._child(key[i]);
    }
    return value;
  }

  childIn(keyPath) {
    return this.child.apply(this, keyPath);
  }

  update(newValue) {
    var trace = valueTraceByPath(this.root, this.path);
    var attributes;
    for (var i = 0, len = trace.length; i < len; i++) {
      var value = trace[i];
      if (i === 0) {
        var schema = value._attributes.schema.instantiate(newValue);
        var onUpdate = schema.props.get('onUpdate');
        if (onUpdate) {
          newValue = onUpdate(newValue);
        }
        attributes = makeAttributes({schema, value: newValue});
      } else {
        attributes = value.onChildUpdate(prevValue.key, attributes);
      }
      var prevValue = value;
    }
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes.merge(attributes),
      this._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  onChildUpdate(key, {value, validation, serialized}) {
    value = this.value.set(key, value);

    var onUpdate = this.schema.props.get('onUpdate');
    if (onUpdate) {
      value = onUpdate(value);
    }

    var schema = this.schema;
    var newSchema = this._attributes.schema.instantiate(value);
    if (!schema.equals(newSchema)) {
      return makeAttributes({schema: newSchema, value}, {strip: true});
    }
    validation = this.validation.updateChild(key, validation);
    validation = validate(this.schema, value, validation.children).validation;
    serialized = this.serialized.set(key, serialized);
    return this._attributes.merge({value, serialized, validation});
  }

  updateChild(key, newValue) {
    return this.child(key).update(newValue).root();
  }

  updateChildIn(keyPath, newValue) {
    return this.childIn(keyPath).update(newValue).root();
  }

  updateSchema(newSchema) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {value, externalValidation}} = this.root;
    return make(
      newSchema, value, externalValidation,
      this._root.get('onUpdate'),
      this._root.get('dirty'),
      this._root.get('rootRef'));
  }

  updateExternalValidation(newExternalValidation) {
    var root = this.root;
    var externalValidation = root.externalValidation.updateChildIn(this.path, newExternalValidation);
    var pendingRootRef = () => root;
    root = new root.constructor(
      root._attributes.merge({externalValidation}),
      root._root.merge({pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  _makeDirty() {
    var dirty = this._root.get('dirty');
    return dirty.updateIn(this.path.concat(DIRTY_KEY), () => true);
  }

  markDirty() {
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes,
      this.root._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  markAsConsistent() {
    return new this.constructor(
      this._attributes,
      this._root.merge({pendingRootRef: null}),
      this.path
    );
  }

  notify() {
    var onUpdate = this._root.get('onUpdate', emptyFunction);
    onUpdate(this);
    return this;
  }
}

Object.defineProperty(Value.prototype, 'key', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    } else {
      return this.path[this.path.length - 1];
    }
  }
});

Object.defineProperty(Value.prototype, 'root', {
  get: function() {
    var ref = this._root.get('pendingRootRef');
    if (!ref) {
      ref = this._root.get('rootRef');
    }
    if (!ref) {
      return this;
    }
    return ref();
  }
});

Object.defineProperty(Value.prototype, 'parent', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    }
    var path = this.path.slice(0);
    path.pop();
    return this.root.childIn(path);
  }
});

Object.defineProperty(Value.prototype, 'schema', {
  get: function() {
    if (this._schema === null) {
      if (isDynamic(this._attributes.schema)) {
        this._schema = this._attributes.schema.instantiate(this._attributes.value);
      } else {
        this._schema = this._attributes.schema;
      }
    }
    return this._schema;
  }
});

Object.defineProperty(Value.prototype, 'value', {
  get: function() {
    return this._attributes.value;
  }
});

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    var serialized = this._attributes.serialized;
    if (serialized === undefined) {
      return _defaultValue(this._attributes.schema);
    }
    return serialized;
  }
});

Object.defineProperty(Value.prototype, 'validation', {
  get: function() {
    return this._attributes.validation;
  }
});

Object.defineProperty(Value.prototype, 'externalValidation', {
  get: function() {
    return this._attributes.externalValidation;
  }
});

Object.defineProperty(Value.prototype, 'isValid', {
  get: function() {
    return this.validation.isSuccess;
  }
});

Object.defineProperty(Value.prototype, 'isDirty', {
  get: function() {
    var path = this.path;
    var dirty = this._root.get('dirty');
    for (var i = 0, len = path.length; i < len; i++) {
      if (dirty) {
        if (dirty.get(DIRTY_KEY) || dirty.get(path[i])) {
          return true;
        }
      } else {
        return false;
      }
      dirty = dirty.get(path[i]);
    }
    return dirty && (dirty.get(DIRTY_KEY) || dirty.length > 0);
  }
});

function valueTraceByPath(value, path) {
  var trace = [value];
  for (var i = 0, len = path.length; i < len; i++) {
    value = value.child(path[i]);
    trace.unshift(value);
  }
  return trace;
}

class ScalarValue extends Value {

}

class MappingValue extends Value {

  map(func, context) {
    return this.schema.children
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.schema.children.forEach((_, key) => {
      return func.call(context, this.child(key), key);
    });
  }
}

class ListValue extends Value {

  map(func, context) {
    return this.value
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.value.forEach((_, key) => func.call(context, this.child(key), key));
  }

  emptyChild() {
    return _defaultValue(this.schema.children);
  }

  push(value) {
    var newIndex = this.value.length;
    value = Immutable.fromJS(value);
    return this._child(newIndex, value).update(value).parent;
  }

  splice() {
    var newValue = this.value.splice.apply(this.value, toArray(arguments));
    return this.update(newValue);
  }
}

function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

function isScalarValue(value) {
  return value instanceof ScalarValue;
}

function isMappingValue(value) {
  return value instanceof MappingValue;
}

function isListValue(value) {
  return value instanceof ListValue;
}

function make(schema, value, externalValidation, onUpdate, dirty, rootRef) {
  externalValidation = externalValidation || ValidationResult.success;
  dirty = dirty || Map.empty();
  schema = schema.instantiate(value);
  var attributes = makeAttributes({schema, value, externalValidation}, {root: true});
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(attributes, Map({onUpdate, dirty, rootRef}), []);
  return value;
}

function makeAttributes(args, options) {
  var {schema, value} = args;

  invariant(
    isSchema(schema),
    'make(schema, ...) has received not a schema value as its first argument'
  );

  args = merge(args, {schema});
  if (isScalar(schema)) {
    return _makeScalar(args, options);
  } else if (isMapping(schema)) {
    return _makeMapping(args, options);
  } else if (isList(schema)) {
    return _makeList(args, options);
  }
}

function _makeScalar(args) {
  var {value, schema, validation, serialized} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else {
      return undefined;
    }
  }
  if (validation === undefined) {
    var validationResult = validate(schema, value);
    value = validationResult.value;
    validation = validationResult.validation;
  }
  if (serialized === undefined) {
    serialized = schema.type.serialize(value);
  }
  return new ValueAttributes(merge(args, {value, validation, serialized}));
}

function _makeMapping(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue
    } else if (options.root) {
      value = new OrderedMap();
    } else {
      return undefined;
    }
  }
  if (!(value instanceof OrderedMap)) {
    value = OrderedMap.from(value);
  }

  var _value = {};
  var _serialized = {};
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  schema.children.forEach((schema, name) => {
    schema = schema.instantiate(value.get(name));
    var child = makeAttributes({
      schema,
      value: value.get(name)
    }, {strip: options.strip});
    if (child == null || child.value == null) {
      if (schema.props.get('required')) {
        _hasChildError = true;
        _childrenValidation[name] = ValidationResult.failure('value is required');
      }
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value[name] = childValue;
    _serialized[name] = childSerialized;
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schema, _value);
  }
  value = value.merge(_value);
  if (options.strip) {
    value.forEach((_, key) =>{
      if (!schema.children.has(key)) {
        value = value.remove(key);
      }
    });
  }
  serialized = serialized || OrderedMap.from(_serialized);
  validation = validation || _validation;
  return new ValueAttributes({schema, value, serialized, validation, externalValidation});
}

function _makeList(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue
    } else if (options.root) {
      value = new Vector();
    } else {
      return undefined;
    }
  }
  if (!(value instanceof Vector)) {
    value = Vector.from(value);
  }

  var _value = [];
  var _serialized = [];
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  value.forEach((value, name) => {
    value = Immutable.fromJS(value);
    var child = makeAttributes({
      schema: schema.child(name).instantiate(value),
      value
    }, {strip: options.strip});
    if (child === undefined) {
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value.push(childValue);
    _serialized.push(childSerialized);
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schema, _value);
  }
  return new ValueAttributes({
    schema,
    value: Vector.from(_value),
    serialized: serialized || Vector.from(_serialized),
    validation: validation || _validation,
    externalValidation
  });
}

/**
 * Get value constructor for given schema node.
 *
 * @private
 * @param {Schema} schema
 * @returns {Constructor}
 */
function _getCtor(schema) {
  var constructor;
  if (isScalar(schema)) {
    constructor = ScalarValue;
  } else if (isMapping(schema)) {
    constructor = MappingValue;
  } else if (isList(schema)) {
    constructor = ListValue;
  } else {
    invariant(false, 'invalid schema node');
  }
  return constructor;
}

function _defaultValue(schema) {
  if (schema.defaultValue !== undefined) {
    return schema.defaultValue;
  } else if (isMapping(schema)) {
    return OrderedMap.empty();
  } else if (isList(schema)) {
    return Vector.empty();
  } else {
    return null;
  }
}

module.exports = make;
mergeInto(module.exports, {
  isValue, isScalarValue, isMappingValue, isListValue
});
<|endoftext|>


<commit_before>var s = document.createElement('script');
s.src = "https://raw.githack.com/joshisa/huemix-blopscotch/master/js/hopscotch.highlight.js";
//s.onload = function() {
//    this.parentNode.removeChild(this);
//};

(document.head || document.documentElement).appendChild(s);

function ping() {
  chrome.extension.sendMessage({}, function(response) {
      if (chrome.runtime.lastError) {
        //console.log("foo::" + chrome.runtime.lastError.message);
        var readyStateCheckInterval = setInterval(function() {
          if (document.readyState === "complete") {
            clearInterval(readyStateCheckInterval);
            var prefix = "[Huemix Blopscotch on githack]] ";
            console.log(prefix + "current page URL is: " + location.href);
            // https://api.github.com/repos/joshisa/huemix-blopscotch/git/trees/master?recursive=1
            // Array of registered hoplets
            whitelist = ["hoplet/demo.js",
                        "hoplet/cp4mcm.js"];
            console.log(prefix + "Number of Hoplets defined : " + whitelist.length);
            var i = 0;
            while (whitelist[i]) {
                // https://raw.githack.com/joshisa/huemix-blopscotch/master/ + whitelist[i]
                console.log(prefix + "Loading " + whitelist[i]);
                proxyXHR.get('https://raw.githack.com/joshisa/huemix-blopscotch/master/' + whitelist[i]).onSuccess(function (data) {
                    eval(data);
                });
                i++;
            }
            console.log(prefix + "Hopscotch Dependencies successfully injected");
          }
        }, 10);
      }
  });
}

ping();
<commit_msg>Updating MCM hoplet<commit_after>var s = document.createElement('script');
s.src = "https://raw.githack.com/joshisa/huemix-blopscotch/master/js/hopscotch.min.js";
//s.onload = function() {
//    this.parentNode.removeChild(this);
//};

(document.head || document.documentElement).appendChild(s);

function ping() {
  chrome.extension.sendMessage({}, function(response) {
      if (chrome.runtime.lastError) {
        //console.log("foo::" + chrome.runtime.lastError.message);
        var readyStateCheckInterval = setInterval(function() {
          if (document.readyState === "complete") {
            clearInterval(readyStateCheckInterval);
            var prefix = "[Huemix Blopscotch on githack]] ";
            console.log(prefix + "current page URL is: " + location.href);
            // https://api.github.com/repos/joshisa/huemix-blopscotch/git/trees/master?recursive=1
            // Array of registered hoplets
            whitelist = ["hoplet/demo.js",
                        "hoplet/cp4mcm.js"];
            console.log(prefix + "Number of Hoplets defined : " + whitelist.length);
            var i = 0;
            while (whitelist[i]) {
                // https://raw.githack.com/joshisa/huemix-blopscotch/master/ + whitelist[i]
                console.log(prefix + "Loading " + whitelist[i]);
                proxyXHR.get('https://raw.githack.com/joshisa/huemix-blopscotch/master/' + whitelist[i]).onSuccess(function (data) {
                    eval(data);
                });
                i++;
            }
            console.log(prefix + "Hopscotch Dependencies successfully injected");
          }
        }, 10);
      }
  });
}

ping();
<|endoftext|>


<commit_before>/*! ========================================================================
 * Bootstrap Toggle: bootstrap-toggle.js v2.2.0
 * http://www.bootstraptoggle.com
 * ========================================================================
 * Copyright 2014 Min Hur, The New York Times Company
 * Licensed under MIT
 * ======================================================================== */

 +function ($) {
 	'use strict';

	// TOGGLE PUBLIC CLASS DEFINITION
	// ==============================

	var Toggle = function (element, options) {
		this.$element  = $(element)
		this.options   = $.extend({}, this.defaults(), options)
		this.render()
	}

	Toggle.VERSION  = '2.2.0'

	Toggle.DEFAULTS = {
		on: 'On',
		off: 'Off',
		onstyle: 'primary',
		offstyle: 'default',
		size: 'normal',
		style: '',
		width: null,
		height: null
	}

	Toggle.prototype.defaults = function() {
		return {
			on: this.$element.attr('data-on') || Toggle.DEFAULTS.on,
			off: this.$element.attr('data-off') || Toggle.DEFAULTS.off,
			onstyle: this.$element.attr('data-onstyle') || Toggle.DEFAULTS.onstyle,
			offstyle: this.$element.attr('data-offstyle') || Toggle.DEFAULTS.offstyle,
			size: this.$element.attr('data-size') || Toggle.DEFAULTS.size,
			style: this.$element.attr('data-style') || Toggle.DEFAULTS.style,
			width: this.$element.attr('data-width') || Toggle.DEFAULTS.width,
			height: this.$element.attr('data-height') || Toggle.DEFAULTS.height
		}
	}

	Toggle.prototype.render = function () {
		this._onstyle = 'btn-' + this.options.onstyle
		this._offstyle = 'btn-' + this.options.offstyle
		this._indeterminatestyle = 'indeterminate'
		var size = this.options.size === 'large' ? 'btn-lg'
			: this.options.size === 'small' ? 'btn-sm'
			: this.options.size === 'mini' ? 'btn-xs'
			: ''
		var checked = this.isChecked()
		var $toggleOn = $('').html(this.options.on)
			.addClass(this._onstyle + ' ' + size)
		var $toggleOff = $('').html(this.options.off)
			.addClass(this._offstyle + ' ' + size + ' active')
		var $toggleHandle = $('')
			.addClass(size)
		var $toggleGroup = $('
')
			.append($toggleOn, $toggleOff, $toggleHandle)
		var $toggle = $('
')
			.addClass( checked ? this._onstyle : this._offstyle+' off' )
			.addClass(size).addClass(this.options.style)

		this.$element.wrap($toggle)
		$.extend(this, {
			$toggle: this.$element.parent(),
			$toggleOn: $toggleOn,
			$toggleOff: $toggleOff,
			$toggleGroup: $toggleGroup
		})
		this.$toggle.append(this.$element.attr('placeholder'), $toggleGroup)

		var width = this.options.width || Math.max($toggleOn.outerWidth(), $toggleOff.outerWidth())+($toggleHandle.outerWidth()/2)
		var height = this.options.height || Math.max($toggleOn.outerHeight(), $toggleOff.outerHeight())
		$toggleOn.addClass('toggle-on')
		$toggleOff.addClass('toggle-off')
		this.$toggle.css({ width: width, height: height }).toggleClass(this._indeterminatestyle, checked === '')
		if (this.options.height) {
			$toggleOn.css('line-height', $toggleOn.height() + 'px')
			$toggleOff.css('line-height', $toggleOff.height() + 'px')
		}
		this.update(true)
		this.trigger(true)
	}

	Toggle.prototype.isChecked = function () {
		if (this.$element.is(':checkbox')) return this.$element.prop('checked')
		var val = this.$element.val()
		return val === '' ? val : val == 'true'
	}

	Toggle.prototype.setChecked = function (checked) {
		return this.$element.is(':checkbox') ? this.$element.prop('checked', checked) : this.$element.val(checked)
	}

	Toggle.prototype.toggle = function () {
		this._toggle(!this.isChecked())
	}

	Toggle.prototype.on = function (silent) {
		this._toggle(true, silent)
	}

	Toggle.prototype.off = function (silent) {
		this._toggle(false, silent)
	}

	Toggle.prototype._toggle = function (checked, silent) {
		if (this.$element.prop('disabled')) return false
		this.$toggle.removeClass(this._indeterminatestyle).toggleClass(this._onstyle, checked).toggleClass(this._offstyle + ' off', !checked)
		this.setChecked(checked)
		if (!silent) this.trigger()
	}

	Toggle.prototype.enable = function () {
		this.$toggle.removeAttr('disabled')
		this.$element.prop('disabled', false)
	}

	Toggle.prototype.disable = function () {
		this.$toggle.attr('disabled', 'disabled')
		this.$element.prop('disabled', true)
	}

	Toggle.prototype.update = function (silent) {
		if (this.$element.prop('disabled')) this.disable()
		else this.enable()
		var checked = this.isChecked();
		if (checked === true) this.on(silent)
		else if (checked === false) this.off(silent)
	}

	Toggle.prototype.trigger = function (silent) {
		this.$element.off('change.bs.toggle')
		if (!silent) this.$element.change()
		this.$element.on('change.bs.toggle', $.proxy(function() {
			this.update()
		}, this))
	}

	Toggle.prototype.destroy = function() {
		this.$element.off('change.bs.toggle')
		this.$toggleGroup.remove()
		this.$element.removeData('bs.toggle')
		this.$element.unwrap()
	}

	// TOGGLE PLUGIN DEFINITION
	// ========================

	function Plugin(option) {
		return this.each(function () {
			var $this   = $(this)
			var data    = $this.data('bs.toggle')
			var options = typeof option == 'object' && option

			if (!data) $this.data('bs.toggle', (data = new Toggle(this, options)))
			if (typeof option == 'string' && data[option]) data[option]()
		})
	}

	var old = $.fn.bootstrapToggle

	$.fn.bootstrapToggle             = Plugin
	$.fn.bootstrapToggle.Constructor = Toggle

	// TOGGLE NO CONFLICT
	// ==================

	$.fn.toggle.noConflict = function () {
		$.fn.bootstrapToggle = old
		return this
	}

	// TOGGLE DATA-API
	// ===============

	$(function() {
		$('input[type=checkbox][data-toggle^=toggle],input[type=hidden][data-toggle^=toggle]').bootstrapToggle()
	})

	$(document).on('click.bs.toggle', 'div[data-toggle^=toggle]', function(e) {
		var $checkbox = $(this).find('input[type=checkbox],input[type=hidden]')
		$checkbox.bootstrapToggle('toggle')
		e.preventDefault()
	})

}(jQuery);
<commit_msg>handle keyboard return/space<commit_after>/*! ========================================================================
 * Bootstrap Toggle: bootstrap-toggle.js v2.2.0
 * http://www.bootstraptoggle.com
 * ========================================================================
 * Copyright 2014 Min Hur, The New York Times Company
 * Licensed under MIT
 * ======================================================================== */

 +function ($) {
 	'use strict';

	// TOGGLE PUBLIC CLASS DEFINITION
	// ==============================

	var Toggle = function (element, options) {
		this.$element  = $(element)
		this.options   = $.extend({}, this.defaults(), options)
		this.render()
	}

	Toggle.VERSION  = '2.2.0'

	Toggle.DEFAULTS = {
		on: 'On',
		off: 'Off',
		onstyle: 'primary',
		offstyle: 'default',
		size: 'normal',
		style: '',
		width: null,
		height: null
	}

	Toggle.prototype.defaults = function() {
		return {
			on: this.$element.attr('data-on') || Toggle.DEFAULTS.on,
			off: this.$element.attr('data-off') || Toggle.DEFAULTS.off,
			onstyle: this.$element.attr('data-onstyle') || Toggle.DEFAULTS.onstyle,
			offstyle: this.$element.attr('data-offstyle') || Toggle.DEFAULTS.offstyle,
			size: this.$element.attr('data-size') || Toggle.DEFAULTS.size,
			style: this.$element.attr('data-style') || Toggle.DEFAULTS.style,
			width: this.$element.attr('data-width') || Toggle.DEFAULTS.width,
			height: this.$element.attr('data-height') || Toggle.DEFAULTS.height
		}
	}

	Toggle.prototype.render = function () {
		this._onstyle = 'btn-' + this.options.onstyle
		this._offstyle = 'btn-' + this.options.offstyle
		this._indeterminatestyle = 'indeterminate'
		var size = this.options.size === 'large' ? 'btn-lg'
			: this.options.size === 'small' ? 'btn-sm'
			: this.options.size === 'mini' ? 'btn-xs'
			: ''
		var checked = this.isChecked()
		var $toggleOn = $('').html(this.options.on)
			.addClass(this._onstyle + ' ' + size)
		var $toggleOff = $('').html(this.options.off)
			.addClass(this._offstyle + ' ' + size + ' active')
		var $toggleHandle = $('')
			.addClass(size)
		var $toggleGroup = $('
')
			.append($toggleOn, $toggleOff, $toggleHandle)
		var $toggle = $('
')
			.attr('tabindex', this.$element.attr('tabindex') || 0)
			.addClass( checked ? this._onstyle : this._offstyle+' off' )
			.addClass(size).addClass(this.options.style)

		this.$element.wrap($toggle)
		$.extend(this, {
			$toggle: this.$element.parent(),
			$toggleOn: $toggleOn,
			$toggleOff: $toggleOff,
			$toggleGroup: $toggleGroup
		})
		this.$toggle.append(this.$element.attr('placeholder'), $toggleGroup)

		var width = this.options.width || Math.max($toggleOn.outerWidth(), $toggleOff.outerWidth())+($toggleHandle.outerWidth()/2)
		var height = this.options.height || Math.max($toggleOn.outerHeight(), $toggleOff.outerHeight())
		$toggleOn.addClass('toggle-on')
		$toggleOff.addClass('toggle-off')
		this.$toggle.css({ width: width, height: height }).toggleClass(this._indeterminatestyle, checked === '')
		if (this.options.height) {
			$toggleOn.css('line-height', $toggleOn.height() + 'px')
			$toggleOff.css('line-height', $toggleOff.height() + 'px')
		}
		this.update(true)
		this.trigger(true)
	}

	Toggle.prototype.isChecked = function () {
		if (this.$element.is(':checkbox')) return this.$element.prop('checked')
		var val = this.$element.val()
		return val === '' ? val : val == 'true'
	}

	Toggle.prototype.setChecked = function (checked) {
		return this.$element.is(':checkbox') ? this.$element.prop('checked', checked) : this.$element.val(checked)
	}

	Toggle.prototype.toggle = function () {
		this._toggle(!this.isChecked())
	}

	Toggle.prototype.on = function (silent) {
		this._toggle(true, silent)
	}

	Toggle.prototype.off = function (silent) {
		this._toggle(false, silent)
	}

	Toggle.prototype._toggle = function (checked, silent) {
		if (this.$element.prop('disabled')) return false
		this.$toggle.removeClass(this._indeterminatestyle).toggleClass(this._onstyle, checked).toggleClass(this._offstyle + ' off', !checked)
		this.setChecked(checked)
		if (!silent) this.trigger()
	}

	Toggle.prototype.enable = function () {
		this.$toggle.removeAttr('disabled')
		this.$element.prop('disabled', false)
	}

	Toggle.prototype.disable = function () {
		this.$toggle.attr('disabled', 'disabled')
		this.$element.prop('disabled', true)
	}

	Toggle.prototype.update = function (silent) {
		if (this.$element.prop('disabled')) this.disable()
		else this.enable()
		var checked = this.isChecked();
		if (checked === true) this.on(silent)
		else if (checked === false) this.off(silent)
	}

	Toggle.prototype.trigger = function (silent) {
		this.$element.off('change.bs.toggle')
		if (!silent) this.$element.change()
		this.$element.on('change.bs.toggle', $.proxy(function() {
			this.update()
		}, this))
	}

	Toggle.prototype.destroy = function() {
		this.$element.off('change.bs.toggle')
		this.$toggleGroup.remove()
		this.$element.removeData('bs.toggle')
		this.$element.unwrap()
	}

	// TOGGLE PLUGIN DEFINITION
	// ========================

	function Plugin(option) {
		return this.each(function () {
			var $this   = $(this)
			var data    = $this.data('bs.toggle')
			var options = typeof option == 'object' && option

			if (!data) $this.data('bs.toggle', (data = new Toggle(this, options)))
			if (typeof option == 'string' && data[option]) data[option]()
		})
	}

	var old = $.fn.bootstrapToggle

	$.fn.bootstrapToggle             = Plugin
	$.fn.bootstrapToggle.Constructor = Toggle

	// TOGGLE NO CONFLICT
	// ==================

	$.fn.toggle.noConflict = function () {
		$.fn.bootstrapToggle = old
		return this
	}

	// TOGGLE DATA-API
	// ===============

	$(function() {
		$('input[type=checkbox][data-toggle^=toggle],input[type=hidden][data-toggle^=toggle]').bootstrapToggle()
	})

	$(document).on('click.bs.toggle keydown.bs.toggle', 'div[data-toggle^=toggle]', function(e) {
		if (e.type != 'keydown' || e.which === 13 || e.which === 32) { // 13 = Return, 32 = Space
			var $checkbox = $(this).find('input[type=checkbox],input[type=hidden]')
			$checkbox.bootstrapToggle('toggle')
			e.preventDefault()
		}
	})

}(jQuery);
<|endoftext|>


<commit_before>'use strict';

// Declare app level module
var howtc = angular.module('howtc', ['ngRoute', 'ngAutocomplete', 'uiGmapgoogle-maps', 'datePicker']);

var options = {
    apiBaseUrl: 'https://localhost:3000/api'
};

howtc.config(['$routeProvider', '$locationProvider',

    function ($routeProvider, $location) {

        $routeProvider.when('/', {
            templateUrl: 'partials/landing.html',
            controller: 'LandingCtrl'
        });

        $routeProvider.when('/search/:searchText', {
            templateUrl: 'partials/search.html',
            controller: 'SearchCtrl'
        });

        $routeProvider.when('/new', {
            templateUrl: 'partials/new_company.html',
            controller: 'NewCompanyCtrl'
        });

        $routeProvider.when('/company/:companyId', {
            templateUrl: 'partials/company_details.html',
            controller: 'CompanyDetailsCtrl'
        });

        $routeProvider.when('/new-survey/:companyId', {
            templateUrl: 'partials/new_survey.html',
            controller: 'NewSurveyCtrl'
        });

        $routeProvider.when('/404', {
            templateUrl: 'partials/404.html',
            controller: '404Ctrl'
        });

        $routeProvider.otherwise({
            redirectTo: '/404'

        });

  }]);
<commit_msg>fix issue<commit_after>'use strict';

// Declare app level module
var howtc = angular.module('howtc', ['ngRoute', 'ngAutocomplete', 'uiGmapgoogle-maps', 'datePicker']);

var options = {
    apiBaseUrl: 'https://howtheycode.herokuapp.com/api'
};

howtc.config(['$routeProvider', '$locationProvider',

    function ($routeProvider, $location) {

        $routeProvider.when('/', {
            templateUrl: 'partials/landing.html',
            controller: 'LandingCtrl'
        });

        $routeProvider.when('/search/:searchText', {
            templateUrl: 'partials/search.html',
            controller: 'SearchCtrl'
        });

        $routeProvider.when('/new', {
            templateUrl: 'partials/new_company.html',
            controller: 'NewCompanyCtrl'
        });

        $routeProvider.when('/company/:companyId', {
            templateUrl: 'partials/company_details.html',
            controller: 'CompanyDetailsCtrl'
        });

        $routeProvider.when('/new-survey/:companyId', {
            templateUrl: 'partials/new_survey.html',
            controller: 'NewSurveyCtrl'
        });

        $routeProvider.when('/404', {
            templateUrl: 'partials/404.html',
            controller: '404Ctrl'
        });

        $routeProvider.otherwise({
            redirectTo: '/404'

        });

  }]);
<|endoftext|>


<commit_before>export const previewRoomMixin = {
  created () {
  },

  mounted () {
  },

  beforeDestroy () {
  },

  computed: {

    room () {
      return this.previewRoom().room
    },

    joinedRoom () {
      return this.previewRoom().joinedRoom
    }
  },

  methods: {

    previewRoom () {
      // N.B.: computed won't work in this case because it will
      // cache the invalid value before component is rendered.
      return this.$refs[this.previewRoomRef]
    },

    isValidRoomId (value) {
      if (!value || value === 'temp') {
        return false
      }
      return true
    },

    joinRoom () {
      if (!this.previewRoom()) return

      this.$socket.emit('preview-room:join', {
        user_id: this.user.id,
        playlist_id: this.previewRoom().roomId,
        is_playing: this.isPlaying,
        current_entity_index: this.playingEntityIndex,
        current_preview_file_id: this.playingPreviewFileId,
        current_frame: this.currentFrameMovieOrPicture,
        is_repeating: this.isRepeating,
        speed: this.speed,
        comparing: {
          enable: this.isComparing,
          task_type: this.taskTypeToCompare,
          revision: this.revisionToCompare,
          mode: this.comparisonMode,
          comparison_preview_index: this.currentComparisonPreviewIndex
        }
      })
    },

    leaveRoom () {
      if (!this.previewRoom()) return

      this.$socket.emit('preview-room:leave', {
        user_id: this.user.id, playlist_id: this.previewRoom().roomId
      })
    },

    sendUpdatePlayingStatus () {
      if (this.isCurrentPreviewMovie) {
        // we need to wait that the video player finished updating before
        // sending the event on the websocket
        this.onNextTimeUpdateActions.push(this.updatePlayingStatus)
      } else {
        this.updatePlayingStatus()
      }
    },

    updatePlayingStatus () {
      if (!this.previewRoom()) return
      if (!this.joinedRoom) return

      this.$socket.emit('preview-room:update-playing-status', {
        playlist_id: this.previewRoom().roomId,
        is_playing: this.isPlaying,
        current_entity_index: this.playingEntityIndex,
        current_preview_file_id: this.playingPreviewFileId,
        current_frame: this.currentFrameMovieOrPicture,
        is_repeating: this.isRepeating,
        speed: this.speed,
        comparing: {
          enable: this.isComparing,
          task_type: this.taskTypeToCompare,
          revision: this.revisionToCompare,
          mode: this.comparisonMode,
          comparison_preview_index: this.currentComparisonPreviewIndex
        }
      })
    },

    postAnnotationAddition (time, serializedObj) {
      this.$socket.emit('preview-room:add-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    postAnnotationDeletion (time, serializedObj) {
      this.$socket.emit('preview-room:remove-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    postAnnotationUpdate (time, serializedObj) {
      this.$socket.emit('preview-room:update-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    loadRoomCurrentState (eventData) {
      if (eventData.is_playing !== this.isPlaying && !eventData.is_playing) {
        // pause if needed to prevent screen flickering
        this.pause()
      }

      let isEntityChanged = false
      if (
        this.exists(eventData.current_entity_index) &&
        eventData.current_entity_index !== this.playingEntityIndex
      ) {
        this.playEntity(eventData.current_entity_index)
        isEntityChanged = true
      }

      if (
        this.exists(eventData.current_preview_file_id) &&
        eventData.current_preview_file_id !== this.playingPreviewFileId
      ) {
        this.playingPreviewFileId = eventData.current_preview_file_id
        isEntityChanged = true
      }

      if (this.exists(eventData.current_frame)) {
        this.$nextTick(() => {
          this.loadRoomCurrentFrame(eventData)
          if (isEntityChanged) {
            this.$nextTick(() => {
              this.updateProgressBar()
              this.onWindowResize() // needed due to a progress bar display bug
            })
          }
        })
      }

      if (
        this.exists(eventData.is_repeating) &&
        eventData.is_repeating !== this.isRepeating
      ) {
        this.isRepeating = eventData.is_repeating
      }

      if (this.exists(eventData.speed) && eventData.speed !== this.speed) {
        this.speed = eventData.speed
        let rate = 1
        if (this.speed === 2) rate = 0.5
        if (this.speed === 1) rate = 0.25
        this.setPlayerSpeed(rate)
      }

      if (this.exists(eventData.comparing)) {
        this.isComparing = eventData.comparing.enable
        this.taskTypeToCompare = eventData.comparing.task_type
        this.revisionToCompare = eventData.comparing.revision
        this.comparisonMode = eventData.comparing.mode
        this.currentComparisonPreviewIndex =
          eventData.comparing.comparison_preview_index
      }

      if (eventData.is_playing !== this.isPlaying) {
        if (eventData.is_playing) {
          this.play()
        } else {
          this.pause()
        }
      }
    },

    loadRoomCurrentFrame (eventData) {
      if (
        eventData.current_frame !== this.currentFrameMovieOrPicture
      ) {
        const frameNumber = eventData.current_frame
        this.rawPlayer.setCurrentFrame(frameNumber - 1)
        this.currentTimeRaw = (frameNumber - 1) * this.frameDuration + 0.01
        if (this.syncComparisonPlayer) this.syncComparisonPlayer()
        this.updateProgressBar()

        this.clearCanvas()
        const annotation = this.getAnnotation(
          (frameNumber - 1) * this.frameDuration
        )
        if (annotation) this.loadAnnotation(annotation)
      } else if (
        this.isCurrentPreviewPicture &&
        eventData.current_frame !== this.framesSeenOfPicture
      ) {
        this.framesSeenOfPicture = eventData.current_frame
      }
    },

    onPreviousFrameClicked () {
      this.clearFocus()
      this.goPreviousFrame()
      this.sendUpdatePlayingStatus()
    },

    onNextFrameClicked () {
      this.clearFocus()
      this.goNextFrame()
      this.sendUpdatePlayingStatus()
    }
  },

  /* N.B.: socket.events are not part of Vue's mixin boilerplate and
   * must be included explicitly in each component using preview rooms!
   */
  socket: {
    events: {
      'preview-room:room-people-updated' (eventData) {
        // someone joined the room
        if (!this.previewRoom()) return

        if (this.joinedRoom) {
          this.room.people = eventData.people
        } else {
          this.room.people = eventData.people
          if (this.joinedRoom) {
            this.room.newComer = false
            this.loadRoomCurrentState(eventData)
          }
        }
      },

      'preview-room:room-updated' (eventData) {
        if (!this.previewRoom()) return

        this.room.people = eventData.people
        if (!this.joinedRoom) return
        if (eventData.only_newcomer && !this.room.newComer) return
        this.loadRoomCurrentState(eventData)
      },

      'preview-room:add-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const annotation = this.getAnnotation(eventData.time)
        const obj = eventData.data.obj
        this.addObjectToCanvas(annotation, obj)
      },

      'preview-room:remove-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const obj = eventData.data.obj
        this.removeObjectFromCanvas(obj)
      },

      'preview-room:update-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const annotation = this.getAnnotation(eventData.time)
        const obj = eventData.data.obj
        this.updateObjectInCanvas(annotation, obj)
      }
    }
  }
}
<commit_msg>[qa] fix problem with playlist/preview-room when previewRoom not defined<commit_after>export const previewRoomMixin = {
  created () {
  },

  mounted () {
  },

  beforeDestroy () {
  },

  computed: {

    room () {
      return this.previewRoom().room
    },

    joinedRoom () {
      return this.previewRoom().joinedRoom
    }
  },

  methods: {

    previewRoom () {
      // N.B.: computed won't work in this case because it will
      // cache the invalid value before component is rendered.
      return this.$refs[this.previewRoomRef]
    },

    isValidRoomId (value) {
      if (!value || value === 'temp') {
        return false
      }
      return true
    },

    joinRoom () {
      if (!this.previewRoom()) return

      this.$socket.emit('preview-room:join', {
        user_id: this.user.id,
        playlist_id: this.previewRoom().roomId,
        is_playing: this.isPlaying,
        current_entity_index: this.playingEntityIndex,
        current_preview_file_id: this.playingPreviewFileId,
        current_frame: this.currentFrameMovieOrPicture,
        is_repeating: this.isRepeating,
        speed: this.speed,
        comparing: {
          enable: this.isComparing,
          task_type: this.taskTypeToCompare,
          revision: this.revisionToCompare,
          mode: this.comparisonMode,
          comparison_preview_index: this.currentComparisonPreviewIndex
        }
      })
    },

    leaveRoom () {
      if (!this.previewRoom()) return

      this.$socket.emit('preview-room:leave', {
        user_id: this.user.id, playlist_id: this.previewRoom().roomId
      })
    },

    sendUpdatePlayingStatus () {
      if (this.isCurrentPreviewMovie) {
        // we need to wait that the video player finished updating before
        // sending the event on the websocket
        this.onNextTimeUpdateActions.push(this.updatePlayingStatus)
      } else {
        this.updatePlayingStatus()
      }
    },

    updatePlayingStatus () {
      if (!this.previewRoom()) return
      if (!this.joinedRoom) return

      this.$socket.emit('preview-room:update-playing-status', {
        playlist_id: this.previewRoom().roomId,
        is_playing: this.isPlaying,
        current_entity_index: this.playingEntityIndex,
        current_preview_file_id: this.playingPreviewFileId,
        current_frame: this.currentFrameMovieOrPicture,
        is_repeating: this.isRepeating,
        speed: this.speed,
        comparing: {
          enable: this.isComparing,
          task_type: this.taskTypeToCompare,
          revision: this.revisionToCompare,
          mode: this.comparisonMode,
          comparison_preview_index: this.currentComparisonPreviewIndex
        }
      })
    },

    postAnnotationAddition (time, serializedObj) {
      if (!this.previewRoom()) return
      this.$socket.emit('preview-room:add-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    postAnnotationDeletion (time, serializedObj) {
      if (!this.previewRoom()) return
      this.$socket.emit('preview-room:remove-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    postAnnotationUpdate (time, serializedObj) {
      if (!this.previewRoom()) return
      this.$socket.emit('preview-room:update-annotation', {
        playlist_id: this.previewRoom().roomId,
        data: {
          user_id: this.user.id,
          time,
          obj: serializedObj
        }
      })
    },

    loadRoomCurrentState (eventData) {
      if (eventData.is_playing !== this.isPlaying && !eventData.is_playing) {
        // pause if needed to prevent screen flickering
        this.pause()
      }

      let isEntityChanged = false
      if (
        this.exists(eventData.current_entity_index) &&
        eventData.current_entity_index !== this.playingEntityIndex
      ) {
        this.playEntity(eventData.current_entity_index)
        isEntityChanged = true
      }

      if (
        this.exists(eventData.current_preview_file_id) &&
        eventData.current_preview_file_id !== this.playingPreviewFileId
      ) {
        this.playingPreviewFileId = eventData.current_preview_file_id
        isEntityChanged = true
      }

      if (this.exists(eventData.current_frame)) {
        this.$nextTick(() => {
          this.loadRoomCurrentFrame(eventData)
          if (isEntityChanged) {
            this.$nextTick(() => {
              this.updateProgressBar()
              this.onWindowResize() // needed due to a progress bar display bug
            })
          }
        })
      }

      if (
        this.exists(eventData.is_repeating) &&
        eventData.is_repeating !== this.isRepeating
      ) {
        this.isRepeating = eventData.is_repeating
      }

      if (this.exists(eventData.speed) && eventData.speed !== this.speed) {
        this.speed = eventData.speed
        let rate = 1
        if (this.speed === 2) rate = 0.5
        if (this.speed === 1) rate = 0.25
        this.setPlayerSpeed(rate)
      }

      if (this.exists(eventData.comparing)) {
        this.isComparing = eventData.comparing.enable
        this.taskTypeToCompare = eventData.comparing.task_type
        this.revisionToCompare = eventData.comparing.revision
        this.comparisonMode = eventData.comparing.mode
        this.currentComparisonPreviewIndex =
          eventData.comparing.comparison_preview_index
      }

      if (eventData.is_playing !== this.isPlaying) {
        if (eventData.is_playing) {
          this.play()
        } else {
          this.pause()
        }
      }
    },

    loadRoomCurrentFrame (eventData) {
      if (
        eventData.current_frame !== this.currentFrameMovieOrPicture
      ) {
        const frameNumber = eventData.current_frame
        this.rawPlayer.setCurrentFrame(frameNumber - 1)
        this.currentTimeRaw = (frameNumber - 1) * this.frameDuration + 0.01
        if (this.syncComparisonPlayer) this.syncComparisonPlayer()
        this.updateProgressBar()

        this.clearCanvas()
        const annotation = this.getAnnotation(
          (frameNumber - 1) * this.frameDuration
        )
        if (annotation) this.loadAnnotation(annotation)
      } else if (
        this.isCurrentPreviewPicture &&
        eventData.current_frame !== this.framesSeenOfPicture
      ) {
        this.framesSeenOfPicture = eventData.current_frame
      }
    },

    onPreviousFrameClicked () {
      this.clearFocus()
      this.goPreviousFrame()
      this.sendUpdatePlayingStatus()
    },

    onNextFrameClicked () {
      this.clearFocus()
      this.goNextFrame()
      this.sendUpdatePlayingStatus()
    }
  },

  /* N.B.: socket.events are not part of Vue's mixin boilerplate and
   * must be included explicitly in each component using preview rooms!
   */
  socket: {
    events: {
      'preview-room:room-people-updated' (eventData) {
        // someone joined the room
        if (!this.previewRoom()) return

        if (this.joinedRoom) {
          this.room.people = eventData.people
        } else {
          this.room.people = eventData.people
          if (this.joinedRoom) {
            this.room.newComer = false
            this.loadRoomCurrentState(eventData)
          }
        }
      },

      'preview-room:room-updated' (eventData) {
        if (!this.previewRoom()) return

        this.room.people = eventData.people
        if (!this.joinedRoom) return
        if (eventData.only_newcomer && !this.room.newComer) return
        this.loadRoomCurrentState(eventData)
      },

      'preview-room:add-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const annotation = this.getAnnotation(eventData.time)
        const obj = eventData.data.obj
        this.addObjectToCanvas(annotation, obj)
      },

      'preview-room:remove-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const obj = eventData.data.obj
        this.removeObjectFromCanvas(obj)
      },

      'preview-room:update-annotation' (eventData) {
        if (!this.previewRoom()) return

        if (!this.joinedRoom) return
        if (this.user.id === eventData.data.user_id) return
        const annotation = this.getAnnotation(eventData.time)
        const obj = eventData.data.obj
        this.updateObjectInCanvas(annotation, obj)
      }
    }
  }
}
<|endoftext|>


<commit_before>/*global IOC:true*/
/*jshint evil:true*/
IOC.DI = function (ioc) {

  var registry = {};
  var factories = {};

  var _resolveArgs = function (args) {
    var failure = false;
    var resolved = [];
    args.forEach(function (arg) {
      if (typeof arg.value !== 'undefined') {
        resolved.push(arg.value);
      } else if (typeof arg.ref !== 'undefined') {
        var ref = _getInstance(arg.ref);
        if (ref) {
          resolved.push(ref);
        } else {
          failure = true;
        }
      } else if (typeof arg.func !== 'undefined') {
        resolved.push(arg.func);
      } else if (typeof arg.exec !== 'undefined') {
        resolved.push(arg.exec(ioc));
      }
    });
    return failure ? null : resolved;
  };

  var _execFunction = function (instance, func, args) {
    var resolvedFunc = (typeof func === 'function' ? func : ioc.object.get(_getInstance(instance), func));
    if (resolvedFunc) {
      var resolvedArgs = _resolveArgs(args || []);
      if (resolvedArgs) {
        resolvedFunc.apply(resolvedFunc, resolvedArgs);
      } else {
        throw 'Unable to resolve arguments for "' + func + '" of instance "' + instance + '"';
      }
    } else {
      throw 'Unknown function "' + func + '" for instance "' + instance + '"';
    }
  };

  var _addInstance = function (name, instance, factory, args) {
    registry[name] = instance;
    if (factory) {
      factories[name] = args || [];
    }
  };

  var _getInstance = function (name) {
    if (factories.hasOwnProperty(name)) {
      var args = _resolveArgs(factories[name] || []);
      if (args) {
        return registry[name].apply(registry[name], args);
      } else {
        throw 'Unable to resolve arguments for "' + name + '"';
      }
    } else {
      return registry[name];
    }
  };

  var _wire = function (instances) {
    if (!instances) {
      return;
    }

    var instanceKeys = ioc.object.keys(instances);
    var unresolved = {};

    instanceKeys.forEach(function (instance) {
      var func = ioc.object.get(window, instances[instance].namespace);
      if (func) {
        var args = _resolveArgs(instances[instance].args || []);
        if (args) {
          window.console.log(instance, 'wired');
          var actualInstance = instances[instance].factory ? func : func.apply(func, args);
          _addInstance(instance, actualInstance, instances[instance].factory, instances[instance].args || []);
          if (instances[instance].extension) {
            ioc = ioc.object.extend(ioc, actualInstance);
          }
        } else {
          unresolved[instance] = instances[instance];
        }
      } else {
        throw 'Unknown function "' + instances[instance].namespace + '"';
      }
    });

    var unresolvedKeys = ioc.object.keys(unresolved);
    if (unresolvedKeys.length !== ioc.object.keys(instances).length && unresolvedKeys.length > 0) {
      _wire(unresolved);
    } else {
      if (unresolvedKeys.length !== 0) {
        throw 'Make sure you don\'t have circular dependencies, Unable to resolve the following instances: ' + unresolvedKeys.join(", ");
      }
    }
  };

  var _init = function (instances) {
    ioc.object.keys(instances).forEach(function (instance) {
      if (instances[instance].init) {
        _execFunction(instance, instances[instance].init.func, instances[instance].init.args);
      }
    });
  };

  var _start = function (starts) {
    if (!starts) {
      return;
    }
    if (document.readyState !== 'complete') {
      window.setTimeout(function () {
        _start(starts);
      }, 100);
    } else {
      starts.forEach(function (start) {
          _execFunction(start.instance, start.func, start.args);
      });
    }
  };

  var _loadContext = function () {
    if (ioc.config.context) {
      window.console.log('wire instances');
      _wire(ioc.config.context.instances);
      window.console.log('init instances');
      _init(ioc.config.context.instances);
      window.console.log('start instances');
      _start(ioc.config.context.start);
    }
  };

  var _loadAsyncDependencies = function (dependencies) {
    var latch = ioc.async.latch(dependencies.async ? dependencies.async.length : 0, _loadContext, 'dependencies');
    dependencies.async.forEach(function (dep) {
      ioc.loader.loadScript(dep, latch.countDown);
    });
  };

  var _loadSyncDependencies = function () {
    if (!ioc.config.context || !ioc.config.context.dependencies) {
      return _loadContext();
    }

    var dependencies;
    if (!ioc.config.context.dependencies[ioc.config.mode]) {
      dependencies = {sync: [], async: []};
    } else {
      dependencies = ioc.config.context.dependencies[ioc.config.mode];
    }

    var seqLatch = ioc.async.seqLatch(dependencies.sync || [], function (url) {
      ioc.loader.loadScript(url, seqLatch.next);
    }, function () {
      _loadAsyncDependencies(dependencies);
    });
    seqLatch.next();
  };

  var _mergeImports = function (imports) {
    var imp = imports.pop();
    var unloadedImports = [];

    while (imp) {
      if (!ioc.object.get(window, imp.namespace)) {
        unloadedImports.push(imp);
      } else {
        ioc.config = ioc.object.extend(ioc.config, ioc.object.get(window, imp.namespace)());
      }
      imp = imports.pop();
    }

    if (unloadedImports.length !== 0) {
      var latch = ioc.async.latch(unloadedImports.length, function () {
        _mergeImports(unloadedImports);
      }, 'imports');
      unloadedImports.forEach(function (subImp) {
        ioc.loader.loadScript(subImp.url, latch.countDown);
      });
    } else {
      _loadSyncDependencies();
    }
  };

  var _loadConfig = function (config) {
    _addInstance('ioc', ioc);
    ioc.config = config;
    ioc.config.mode = ioc.url.query().env || 'default';
    window.console.log('IOC: Starting in mode', ioc.config.mode);
    if (config.exposeIoc) {
      window.ioc = ioc;
    }

    if (ioc.config.imports) {
      _mergeImports(JSON.parse(JSON.stringify(ioc.config.imports)));
    } else {
      _loadSyncDependencies();
    }
  };

  var _processAnnotations = function (text) {
    var regex = /@ioc-instance\s+["']([^"']+)["']\s*(.*);\s*(@ioc-init\s+["']([^"']+)["']\s*(.*);)*\s*(@ioc-start\s+["']([^"']+)["']\s*(.*);)*\s*\*\/\s*([\w.]+)/g;
    var match;
    while ((match = regex.exec(text))) {
      _processAnnotation(match);
    }
  };

  var _processArgAnnotation = function (match) {
    var args = [];
    var split = match.split(',');
    split.forEach(function (arg) {
      var argPair = arg.split(":");
      var argObj = {};
      argObj[argPair[0].trim()] = argPair[0].trim() === 'ref' ? argPair[1].trim() : eval(argPair[1].trim());
      args.push(argObj);
    });
    return args;
  };

  var _processAnnotation = function (match) {
    var instanceName = match[1];
    var namespace = match[9];

    if (!instanceName) {
      return;
    }
    if (!ioc.config.context) {
      ioc.config.context = {instances: {}};
    }

    //instance
    ioc.config.context.instances[instanceName] = {namespace: namespace};
    if (match[2]) {
      ioc.config.context.instances[instanceName].args = _processArgAnnotation(match[2]);
    }

    // init
    if (match[4]) {
      ioc.config.context.instances[instanceName].init = {func: match[4]};
      if (match[5]) {
        ioc.config.context.instances[instanceName].init.args = _processArgAnnotation(match[5]);
      }
    }

    // start
    if (match[7]) {
      var start = {instance: instanceName, func: match[7]};
      if (match[8]) {
        start.args = _processArgAnnotation(match[8]);
      }
      if (!ioc.config.context.start) {
        ioc.config.context.start = [];
      }
      ioc.config.context.start.push(start);
    }
  };

  return {
    di: {
      loadConfig: _loadConfig,
      getInstance: _getInstance,
      addInstance: _addInstance,
      processAnnotations: _processAnnotations
    }
  };
};<commit_msg>trying out separation of the extensions so they are available earlier<commit_after>/*global IOC:true*/
/*jshint evil:true*/
IOC.DI = function (ioc) {

  var registry = {};
  var factories = {};

  var _resolveArgs = function (args) {
    var failure = false;
    var resolved = [];
    args.forEach(function (arg) {
      if (typeof arg.value !== 'undefined') {
        resolved.push(arg.value);
      } else if (typeof arg.ref !== 'undefined') {
        var ref = _getInstance(arg.ref);
        if (ref) {
          resolved.push(ref);
        } else {
          failure = true;
        }
      } else if (typeof arg.func !== 'undefined') {
        resolved.push(arg.func);
      } else if (typeof arg.exec !== 'undefined') {
        resolved.push(arg.exec(ioc));
      }
    });
    return failure ? null : resolved;
  };

  var _execFunction = function (instance, func, args) {
    var resolvedFunc = (typeof func === 'function' ? func : ioc.object.get(_getInstance(instance), func));
    if (resolvedFunc) {
      var resolvedArgs = _resolveArgs(args || []);
      if (resolvedArgs) {
        resolvedFunc.apply(resolvedFunc, resolvedArgs);
      } else {
        throw 'Unable to resolve arguments for "' + func + '" of instance "' + instance + '"';
      }
    } else {
      throw 'Unknown function "' + func + '" for instance "' + instance + '"';
    }
  };

  var _addInstance = function (name, instance, factory, args) {
    registry[name] = instance;
    if (factory) {
      factories[name] = args || [];
    }
  };

  var _getInstance = function (name) {
    if (factories.hasOwnProperty(name)) {
      var args = _resolveArgs(factories[name] || []);
      if (args) {
        return registry[name].apply(registry[name], args);
      } else {
        throw 'Unable to resolve arguments for "' + name + '"';
      }
    } else {
      return registry[name];
    }
  };

  var _wire = function (instances) {
    if (!instances) {
      return;
    }

    var instanceKeys = ioc.object.keys(instances);
    var unresolved = {};

    instanceKeys.forEach(function (instance) {
      var func = ioc.object.get(window, instances[instance].namespace);
      if (func) {
        var args = _resolveArgs(instances[instance].args || []);
        if (args) {
          window.console.log(instance, 'wired');
          var actualInstance = instances[instance].factory ? func : func.apply(func, args);
          _addInstance(instance, actualInstance, instances[instance].factory, instances[instance].args || []);
          if (instances[instance].extension) {
            ioc = ioc.object.extend(ioc, actualInstance);
          }
        } else {
          unresolved[instance] = instances[instance];
        }
      } else {
        throw 'Unknown function "' + instances[instance].namespace + '"';
      }
    });

    var unresolvedKeys = ioc.object.keys(unresolved);
    if (unresolvedKeys.length !== ioc.object.keys(instances).length && unresolvedKeys.length > 0) {
      _wire(unresolved);
    } else {
      if (unresolvedKeys.length !== 0) {
        throw 'Make sure you don\'t have circular dependencies, Unable to resolve the following instances: ' + unresolvedKeys.join(", ");
      }
    }
  };

  var _init = function (instances) {
    ioc.object.keys(instances).forEach(function (instance) {
      if (instances[instance].init) {
        _execFunction(instance, instances[instance].init.func, instances[instance].init.args);
      }
    });
  };

  var _start = function (starts) {
    if (!starts) {
      return;
    }
    if (document.readyState !== 'complete') {
      window.setTimeout(function () {
        _start(starts);
      }, 100);
    } else {
      starts.forEach(function (start) {
          _execFunction(start.instance, start.func, start.args);
      });
    }
  };

  var _loadContext = function () {
    if (ioc.config.context) {
      window.console.log('wire extensions');
      _wire(ioc.config.context.extensions);
      window.console.log('init extensions');
      _init(ioc.config.context.extensions);
      window.console.log('wire instances');
      _wire(ioc.config.context.instances);
      window.console.log('init instances');
      _init(ioc.config.context.instances);
      window.console.log('start instances');
      _start(ioc.config.context.start);
    }
  };

  var _loadAsyncDependencies = function (dependencies) {
    var latch = ioc.async.latch(dependencies.async ? dependencies.async.length : 0, _loadContext, 'dependencies');
    dependencies.async.forEach(function (dep) {
      ioc.loader.loadScript(dep, latch.countDown);
    });
  };

  var _loadSyncDependencies = function () {
    if (!ioc.config.context || !ioc.config.context.dependencies) {
      return _loadContext();
    }

    var dependencies;
    if (!ioc.config.context.dependencies[ioc.config.mode]) {
      dependencies = {sync: [], async: []};
    } else {
      dependencies = ioc.config.context.dependencies[ioc.config.mode];
    }

    var seqLatch = ioc.async.seqLatch(dependencies.sync || [], function (url) {
      ioc.loader.loadScript(url, seqLatch.next);
    }, function () {
      _loadAsyncDependencies(dependencies);
    });
    seqLatch.next();
  };

  var _mergeImports = function (imports) {
    var imp = imports.pop();
    var unloadedImports = [];

    while (imp) {
      if (!ioc.object.get(window, imp.namespace)) {
        unloadedImports.push(imp);
      } else {
        ioc.config = ioc.object.extend(ioc.config, ioc.object.get(window, imp.namespace)());
      }
      imp = imports.pop();
    }

    if (unloadedImports.length !== 0) {
      var latch = ioc.async.latch(unloadedImports.length, function () {
        _mergeImports(unloadedImports);
      }, 'imports');
      unloadedImports.forEach(function (subImp) {
        ioc.loader.loadScript(subImp.url, latch.countDown);
      });
    } else {
      _loadSyncDependencies();
    }
  };

  var _loadConfig = function (config) {
    _addInstance('ioc', ioc);
    ioc.config = config;
    ioc.config.mode = ioc.url.query().env || 'default';
    window.console.log('IOC: Starting in mode', ioc.config.mode);
    if (config.exposeIoc) {
      window.ioc = ioc;
    }

    if (ioc.config.imports) {
      _mergeImports(JSON.parse(JSON.stringify(ioc.config.imports)));
    } else {
      _loadSyncDependencies();
    }
  };

  var _processAnnotations = function (text) {
    var regex = /@ioc-instance\s+["']([^"']+)["']\s*(.*);\s*(@ioc-init\s+["']([^"']+)["']\s*(.*);)*\s*(@ioc-start\s+["']([^"']+)["']\s*(.*);)*\s*\*\/\s*([\w.]+)/g;
    var match;
    while ((match = regex.exec(text))) {
      _processAnnotation(match);
    }
  };

  var _processArgAnnotation = function (match) {
    var args = [];
    var split = match.split(',');
    split.forEach(function (arg) {
      var argPair = arg.split(":");
      var argObj = {};
      argObj[argPair[0].trim()] = argPair[0].trim() === 'ref' ? argPair[1].trim() : eval(argPair[1].trim());
      args.push(argObj);
    });
    return args;
  };

  var _processAnnotation = function (match) {
    var instanceName = match[1];
    var namespace = match[9];

    if (!instanceName) {
      return;
    }
    if (!ioc.config.context) {
      ioc.config.context = {instances: {}};
    }

    //instance
    ioc.config.context.instances[instanceName] = {namespace: namespace};
    if (match[2]) {
      ioc.config.context.instances[instanceName].args = _processArgAnnotation(match[2]);
    }

    // init
    if (match[4]) {
      ioc.config.context.instances[instanceName].init = {func: match[4]};
      if (match[5]) {
        ioc.config.context.instances[instanceName].init.args = _processArgAnnotation(match[5]);
      }
    }

    // start
    if (match[7]) {
      var start = {instance: instanceName, func: match[7]};
      if (match[8]) {
        start.args = _processArgAnnotation(match[8]);
      }
      if (!ioc.config.context.start) {
        ioc.config.context.start = [];
      }
      ioc.config.context.start.push(start);
    }
  };

  return {
    di: {
      loadConfig: _loadConfig,
      getInstance: _getInstance,
      addInstance: _addInstance,
      processAnnotations: _processAnnotations
    }
  };
};<|endoftext|>


<commit_before>'use strict';

//
// ## exploit require.cache to aglomerate utilities
//    at require('runtime/lib/utils') avoiding madness
//

var gutil = require('gulp-util');
var util = require('runtime/lib/utils');
var runtime = require('runtime').get('gulp');

var _join = [ ].join;
var chalk = gutil.colors;

util.merge(util, {
     log : gutil.log,
  colors : gutil.colors,
    date : gutil.date
});

// save the plugin badge
util.badge = chalk.cyan('gulp-runtime');
util.longBadge = 'From plugin `' + util.badge + '`';

// gutil.log stamp
util.stamp = function(){
  var date = util.date(new Date(), 'HH:MM:ss');
  return '[' + chalk.grey(date) + '] ';
};

// go through the runtime.output
util.log = function(/* arguments */){
  runtime.output.write(
    util.stamp() + _join.call(arguments, ' ').trim() + '\n'
  );
};

// pretty colors for quotes
util.quotify = function(input, color){
  input = util.type(input);
  if( !input.match(/string|array/) ){
    return input;
  }
  input = input.string || input.array.join(' ');
  color = chalk[util.type(color).string] || chalk.cyan;
  return input.replace(/(`|'|")(.*?)(`|'|")/g,
    function($0,$1,$2,$3){
      return $1 + color($2) + $3;
    }
  );
};

util.cmdRE = function(stems){
  var completion = runtime.get(stems || '').completion;
  return new RegExp(completion.join('|'), 'g');
};

util.tasksRE = function(gulpInst){
  var tasks = Object.keys(gulpInst.tasks);
  return new RegExp(tasks.join('|'), 'g');
};

util.merge(util, runtime.require(/^(?!\_)(.*?)\.js/));

//
// ## lazyyyyyy
//

util.archy = function archy(tree){
  return require('archy')(tree);
};

util.tildify = function tildify(pathname){
  return require('tildify')(pathname);
};

util.ansiJS = function(str){
  return require('ansi-highlight')(str);
};
<commit_msg>deleted lib/_main.js<commit_after><|endoftext|>