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

var {Vector, Map, OrderedMap, Record}            = require('immutable');
var {isSchema, isList, isMapping, isScalar}      = 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,
  onUpdate: emptyFunction,
  dirty: Map.empty(),
  rootRef: null
}, 'ValueAttributes');

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

  constructor(attributes, path) {
    this._attributes = attributes;
    this.path = path;
  }

  equals(other) {
    return (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      (
        this.value && this.value.equals ?
        this.value.equals(other.value) :
        this.value === other.value
      ) &&
      (
        this.serialized && this.serialized.equals ?
        this.serialized.equals(other.serialized) :
        this.serialized === other.serialized
      ) &&
      this.validation.equals(other.validation) &&
      (
        this.externalValidation && this.externalValidation.equals ?
        this.externalValidation.equals(other.externalValidation) :
        this.externalValidation === other.externalValidation
      ) &&
      this.dirty === other.dirty &&
      this._attributes.onUpdate === other._attributes.onUpdate
    );
  }

  child(...key) {
    var schema = this.schema.childIn(key);
    var value = getValueByPath(this.schema, this.value, key);
    var serialized = key.length > 0 && this.serialized !== undefined ?
      this.serialized.getIn(key) : this.serialized;
    var validation = this.validation.childIn(key);
    var externalValidation = this.externalValidation ?
      this.externalValidation.childIn(key) :
      null;
    var ctor = _getCtor(schema);
    var attributes = this._attributes.merge({
      schema, value, serialized, validation, externalValidation
    });
    return new ctor(attributes, this.path.concat(key));
  }

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

  update(newValue) {
    var update = this._update(newValue);
    var {value, serialized, validation, schema} = this.root;
    var path = this.path.slice();

    while (true) {
      if (path.length === this.path.length) {
        // only first update updates value and serialized
        if (path.length > 0) {
          value = value.updateIn(path, () => update.value);
          serialized = serialized.updateIn(path, () => update.serialized);
          validation = validation.updateChildIn(path, update.validation);
        } else {
          value = update.value;
          serialized = update.serialized;
          validation = update.validation;
        }

      } else if (validation.isSuccess) {
        // we need to update validation along the path if previou validation was
        // successful
        validation = validation.updateChildIn(
          path,
          validate(schema.childIn(path), value.getIn(path)).validation
        );
      }
      if (path.length === 0) {
        break;
      } else {
        path.pop();
      }
    }
    var dirty = this._makeDirty();
    return new this.root.constructor(
      this.root._attributes.merge({value, serialized, validation, dirty}),
      []
    );
  }

  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, dirty, onUpdate, rootRef}} = this.root;
    return make(newSchema, value, externalValidation, onUpdate, dirty, rootRef);
  }

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

  _makeDirty() {
    var {_attributes: {dirty}, path} = this;
    return dirty.updateIn(path.concat(DIRTY_KEY), () => true);
  }

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

  notify() {
    this._attributes.onUpdate(this);
    return this;
  }
}

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

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

function getValueByPath(schema, value, path) {
  if (value === undefined) {
    return _defaultValue(schema);
  }
  if (path.length > 0) {
    for (var i = 0, len = path.length; i < len; i++) {
      schema = schema.child(path[i]);
      value = value.get(path[i], schema.defaultValue);
      if (value === undefined) {
        return _defaultValue(schema);
      }
    }
    return value;
  } else {
    return value;
  }
}

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

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    return this._attributes.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 {_attributes: {dirty}, path} = this;
    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);
  }
});

class ScalarValue extends Value {

  _update(newValue) {
    var {value, validation} = validate(this.schema, newValue);
    var serialized = this.schema.type.serialize(value);
    return {value, validation, serialized};
  }
}

class MappingValue extends Value {

  _update(value) {
    var {schema} = this;
    return _makeMapping({schema, value});
  }

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

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

class ListValue extends Value {

  _update(value) {
    var {schema} = this;
    return _makeList({schema, 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(...values) {
    var newValue = this.value.push.apply(this.value, values);
    return this.update(newValue);
  }

  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();
  var params = _make({schema, value, externalValidation}, true);
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(new ValueAttributes(merge(params, {onUpdate, dirty, rootRef})), []);
  return value;
}

function _make(args, root) {
  var {schema, value} = args;

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

  if (isScalar(schema)) {
    if (value === undefined) {
      if (schema.defaultValue !== undefined) {
        value = schema.defaultValue;
      } else {
        return undefined;
      }
    }
    var {value, validation} = validate(schema, value);
    var serialized = schema.type.serialize(value);
    return merge(args, {value, validation, serialized});
  } else if (isMapping(schema)) {
    return _makeMapping(args, root);
  } else if (isList(schema)) {
    return _makeList(args, root);
  }
}

function _makeMapping(args, root) {
  var {schema, value, externalValidation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else if (root) {
      value = {};
    } 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) => {
    var child = _make({
      schema,
      value: value.get(name)
    });
    if (child === undefined) {
      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);
  }
  return {
    schema,
    value: value.merge(_value),
    serialized: OrderedMap.from(_serialized),
    validation: _validation,
    externalValidation
  };
}

function _makeList(args, root) {
  var {schema, value, externalValidation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else if (root) {
      value = [];
    } 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 = _make({
      schema: schema.child(name),
      value
    });
    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 {
    schema,
    value: Vector.from(_value),
    serialized: Vector.from(_serialized),
    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);
  }
  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>Parent ref<commit_after>/**
 * @jsx React.DOM
 * @preventMunge
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var {Vector, Map, OrderedMap, Record}            = require('immutable');
var {isSchema, isList, isMapping, isScalar}      = 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,
  onUpdate: emptyFunction,
  dirty: Map.empty(),
  rootRef: null
}, 'ValueAttributes');

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

  constructor(attributes, path) {
    this._attributes = attributes;
    this.path = path;
  }

  equals(other) {
    return (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      (
        this.value && this.value.equals ?
        this.value.equals(other.value) :
        this.value === other.value
      ) &&
      (
        this.serialized && this.serialized.equals ?
        this.serialized.equals(other.serialized) :
        this.serialized === other.serialized
      ) &&
      this.validation.equals(other.validation) &&
      (
        this.externalValidation && this.externalValidation.equals ?
        this.externalValidation.equals(other.externalValidation) :
        this.externalValidation === other.externalValidation
      ) &&
      this.dirty === other.dirty &&
      this._attributes.onUpdate === other._attributes.onUpdate
    );
  }

  child(...key) {
    var schema = this.schema.childIn(key);
    var value = getValueByPath(this.schema, this.value, key);
    var serialized = key.length > 0 && this.serialized !== undefined ?
      this.serialized.getIn(key) : this.serialized;
    var validation = this.validation.childIn(key);
    var externalValidation = this.externalValidation ?
      this.externalValidation.childIn(key) :
      null;
    var ctor = _getCtor(schema);
    var attributes = this._attributes.merge({
      schema, value, serialized, validation, externalValidation
    });
    return new ctor(attributes, this.path.concat(key));
  }

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

  update(newValue) {
    var update = this._update(newValue);
    var {value, serialized, validation, schema} = this.root;
    var path = this.path.slice();

    while (true) {
      if (path.length === this.path.length) {
        // only first update updates value and serialized
        if (path.length > 0) {
          value = value.updateIn(path, () => update.value);
          serialized = serialized.updateIn(path, () => update.serialized);
          validation = validation.updateChildIn(path, update.validation);
        } else {
          value = update.value;
          serialized = update.serialized;
          validation = update.validation;
        }

      } else if (validation.isSuccess) {
        // we need to update validation along the path if previou validation was
        // successful
        validation = validation.updateChildIn(
          path,
          validate(schema.childIn(path), value.getIn(path)).validation
        );
      }
      if (path.length === 0) {
        break;
      } else {
        path.pop();
      }
    }
    var dirty = this._makeDirty();
    return new this.root.constructor(
      this.root._attributes.merge({value, serialized, validation, dirty}),
      []
    );
  }

  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, dirty, onUpdate, rootRef}} = this.root;
    return make(newSchema, value, externalValidation, onUpdate, dirty, rootRef);
  }

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

  _makeDirty() {
    var {_attributes: {dirty}, path} = this;
    return dirty.updateIn(path.concat(DIRTY_KEY), () => true);
  }

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

  notify() {
    this._attributes.onUpdate(this);
    return this;
  }
}

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

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() {
    return this._attributes.schema;
  }
});

function getValueByPath(schema, value, path) {
  if (value === undefined) {
    return _defaultValue(schema);
  }
  if (path.length > 0) {
    for (var i = 0, len = path.length; i < len; i++) {
      schema = schema.child(path[i]);
      value = value.get(path[i], schema.defaultValue);
      if (value === undefined) {
        return _defaultValue(schema);
      }
    }
    return value;
  } else {
    return value;
  }
}

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

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    return this._attributes.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 {_attributes: {dirty}, path} = this;
    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);
  }
});

class ScalarValue extends Value {

  _update(newValue) {
    var {value, validation} = validate(this.schema, newValue);
    var serialized = this.schema.type.serialize(value);
    return {value, validation, serialized};
  }
}

class MappingValue extends Value {

  _update(value) {
    var {schema} = this;
    return _makeMapping({schema, value});
  }

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

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

class ListValue extends Value {

  _update(value) {
    var {schema} = this;
    return _makeList({schema, 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(...values) {
    var newValue = this.value.push.apply(this.value, values);
    return this.update(newValue);
  }

  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();
  var params = _make({schema, value, externalValidation}, true);
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(new ValueAttributes(merge(params, {onUpdate, dirty, rootRef})), []);
  return value;
}

function _make(args, root) {
  var {schema, value} = args;

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

  if (isScalar(schema)) {
    if (value === undefined) {
      if (schema.defaultValue !== undefined) {
        value = schema.defaultValue;
      } else {
        return undefined;
      }
    }
    var {value, validation} = validate(schema, value);
    var serialized = schema.type.serialize(value);
    return merge(args, {value, validation, serialized});
  } else if (isMapping(schema)) {
    return _makeMapping(args, root);
  } else if (isList(schema)) {
    return _makeList(args, root);
  }
}

function _makeMapping(args, root) {
  var {schema, value, externalValidation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else if (root) {
      value = {};
    } 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) => {
    var child = _make({
      schema,
      value: value.get(name)
    });
    if (child === undefined) {
      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);
  }
  return {
    schema,
    value: value.merge(_value),
    serialized: OrderedMap.from(_serialized),
    validation: _validation,
    externalValidation
  };
}

function _makeList(args, root) {
  var {schema, value, externalValidation} = args;
  if (value === undefined) {
    if (schema.defaultValue !== undefined) {
      value = schema.defaultValue;
    } else if (root) {
      value = [];
    } 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 = _make({
      schema: schema.child(name),
      value
    });
    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 {
    schema,
    value: Vector.from(_value),
    serialized: Vector.from(_serialized),
    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);
  }
  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>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Terminal control")
description("This will return the terminal control")
base_component_id("terminal_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "Terminal connecter",
            type:       "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    100,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    50,
            type:       "Number"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "execCmd",
            pre_snippet:    `await `,
            snippet:    `execCmd('ls')`,
            name:       "Execute Command",
            type:       "Action"
        }
    ]
)//properties
logo_url("/driver_icons/terminal.png")
*/

    Vue.component("terminal_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        {{args.text}}

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

`

        ,

        data: function() {
            return {
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            if (!this.design_mode) {
                var x = await this.readFromTerminal()
                this.args.container_list = x
            }
        }
        ,

        methods: {
            readFromTerminal: async function(cmdString) {
                var result = await callFunction(
                {
                    driver_name: "serverTerminalStuff",
                    method_name: "serverTerminalStuff"
                }
                ,
                {
                    cmd_string:    cmdString
                })

                if (result.value) {
                    return result.value
                }
                return null
            }
            ,

            execCmd: async function(cmdString) {
                var qwe = await this.readFromTerminal(cmdString)
                return qwe
            }

        }

    })
}
<commit_msg>Mad ethe terminal control a little prettier<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Terminal control")
description("This will return the terminal control")
base_component_id("terminal_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "Terminal connecter",
            type:       "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    130,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    40,
            type:       "Number"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "execCmd",
            pre_snippet:    `await `,
            snippet:    `execCmd('ls')`,
            name:       "Execute Command",
            type:       "Action"
        }
    ]
)//properties
logo_url("/driver_icons/terminal.png")
*/

    Vue.component("terminal_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        {{args.text}}

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

`

        ,

        data: function() {
            return {
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            if (!this.design_mode) {
                var x = await this.readFromTerminal()
                this.args.container_list = x
            }
        }
        ,

        methods: {
            readFromTerminal: async function(cmdString) {
                var result = await callFunction(
                {
                    driver_name: "serverTerminalStuff",
                    method_name: "serverTerminalStuff"
                }
                ,
                {
                    cmd_string:    cmdString
                })

                if (result.value) {
                    return result.value
                }
                return null
            }
            ,

            execCmd: async function(cmdString) {
                var qwe = await this.readFromTerminal(cmdString)
                return qwe
            }

        }

    })
}
<|endoftext|>


<commit_before>'use strict';

const Wreck = require('@hapi/wreck');
const PkgDir = require('pkg-dir');
const Pluralize = require('pluralize');
const Somever = require('@hapi/somever');
const Print = require('../print');
const Helpers = require('../helpers');
const DisplayError = require('../display-error');

const internals = {};

module.exports = async (cwd, pkg, version, query, itemQuery, ctx) => {

    const root = await PkgDir(cwd);

    if (!version && root && internals.pkgScope[pkg]) {

        version = internals.getPkgVersion(root, `@${internals.pkgScope[pkg]}/${pkg}`);
    }

    if (!version && root) {

        version = internals.getPkgVersion(root, pkg);
    }

    query = query.toLowerCase();

    let parsedVersion;

    try {
        parsedVersion = Somever.version(version);
    }
    catch (ignoreErr) {}

    const ref = parsedVersion ? `v${parsedVersion.version}` : (version || 'master');
    const owner = internals.pkgOwners[pkg] || 'hapijs';

    ctx.options.out.write(ctx.colors.grey(`Searching docs from ${owner}/${pkg} @ ${ref}...\n\n`));

    const getAPI = async () => {

        try {
            return await internals.getPkgAPI(owner, pkg, ref);
        }
        catch (err) {
            if (err.isBoom && err.output.statusCode === 404) {
                throw new DisplayError(ctx.colors.red(`Couldn\'t find docs for that version of ${pkg}. Are you sure ${owner}/${pkg} @ ${ref} exists?`));
            }

            if (err.syscall === 'getaddrinfo' && err.code === 'ENOTFOUND') {
                throw new DisplayError(ctx.colors.red(`Could not fetch the ${pkg} docs. It seems you may be offline– ensure you have a connection then try again.`));
            }

            throw new DisplayError(ctx.colors.red(`Could not fetch the ${pkg} docs: ${err.message}`));
        }
    };

    const getManifest = async () => {

        if (!root) {
            return null;
        }

        try {
            return await Helpers.getManifest(root, ctx, true);
        }
        catch (err) {
            // If we can't get the manifest for some reason we're aware of, that's okay
            if (err instanceof DisplayError) {
                return null;
            }

            throw err;
        }
    };

    const [api, manifest] = await Promise.all([getAPI(), getManifest()]);

    const pluralQuery = manifest && Pluralize.plural(query);
    const item = manifest && (manifest.find((m) => m.place === query) || manifest.find((m) => m.place === pluralQuery));
    const methodMatch = query.match(/^([a-z\.]+)/);
    const method = methodMatch && methodMatch[1];
    const headingMatchers = ([
        item && `server.${item.method}(`,
        method && `${method}(`,
        (query.length >= 3) && query
    ])
        .filter((x) => !!x)
        .map((match) => {

            return (section) => {

                if (match[0] === '#') {
                    return internals.anchorize(section)
                        .some((anchor) => ~anchor.indexOf(match));
                }

                return ~section.toLowerCase().indexOf(match);
            };
        });

    if (!itemQuery) {
        return Print.markdownSection(api, headingMatchers);
    }

    const itemQueryEsc = internals.regEscape(itemQuery);
    const itemRegExp = new RegExp(`^\s*\`?${itemQueryEsc}\`? -`, 'i');
    const listItemMatcher = (listItem) => itemRegExp.test(listItem);

    return Print.markdownListItem(api, headingMatchers, listItemMatcher);
};

internals.getPkgVersion = (root, pkg) => {

    try {
        // In node v8.9+ will be able to use require.resolve()'s { paths } option
        return require(`${root}/node_modules/${pkg}/package.json`).version;
    }
    catch (err) {

        if (err.code === 'MODULE_NOT_FOUND') {
            return null;
        }

        throw err;
    }
};

internals.getPkgAPI = async (owner, pkg, ref) => {

    const { payload } = await Wreck.get(`https://raw.githubusercontent.com/${owner}/${pkg}/${ref}/API.md`);

    return payload.toString();
};

internals.pkgScope = {
    accept: 'hapi',
    address: 'hapi',
    ammo: 'hapi',
    b64: 'hapi',
    basic: 'hapi',
    bell: 'hapi',
    boom: 'hapi',
    bossy: 'hapi',
    bounce: 'hapi',
    call: 'hapi',
    catbox: 'hapi',
    'catbox-memecached': 'hapi',
    'catbox-memory': 'hapi',
    'catbox-redis': 'hapi',
    code: 'hapi',
    content: 'hapi',
    cookie: 'hapi',
    crumb: 'hapi',
    cryptiles: 'hapi',
    glue: 'hapi',
    good: 'hapi',
    'good-console': 'hapi',
    'good-squeeze': 'hapi',
    h2o2: 'hapi',
    hapi: 'hapi',
    hawk: 'hapi',
    heavy: 'hapi',
    hoek: 'hapi',
    inert: 'hapi',
    iron: 'hapi',
    joi: 'hapi',
    'joi-date': 'hapi',
    lab: 'hapi',
    mimos: 'hapi',
    nes: 'hapi',
    nigel: 'hapi',
    oppsy: 'hapi',
    pez: 'hapi',
    podium: 'hapi',
    scooter: 'hapi',
    shot: 'hapi',
    sntp: 'hapi',
    somever: 'hapi',
    statehood: 'hapi',
    subtext: 'hapi',
    teamwork: 'hapi',
    topo: 'hapi',
    vise: 'hapi',
    vision: 'hapi',
    wreck: 'hapi',
    yar: 'hapi'
};

internals.pkgOwners = {
    schwifty: 'hapipal',
    schmervice: 'hapipal',
    toys: 'hapipal',
    'haute-couture': 'hapipal',
    hodgepodge: 'hapipal',
    underdog: 'hapipal',
    hecks: 'hapipal',
    lalalambda: 'hapipal'
};

internals.anchorize = (str) => {

    str = str.toLowerCase();

    const anchors = [];
    const tag = str.match(Print.headingAnchorTagRegex);

    if (tag) {
        str = str.replace(tag[0], '-');
        anchors.push(`#${tag[1]}`);
    }

    anchors.push('#' + str.replace(/[^a-z0-9\s-]/ig, '').trim().replace(/\s/g, '-'));

    return anchors;
};

internals.regEscape = (str) => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
<commit_msg>Add avocat to docs command<commit_after>'use strict';

const Wreck = require('@hapi/wreck');
const PkgDir = require('pkg-dir');
const Pluralize = require('pluralize');
const Somever = require('@hapi/somever');
const Print = require('../print');
const Helpers = require('../helpers');
const DisplayError = require('../display-error');

const internals = {};

module.exports = async (cwd, pkg, version, query, itemQuery, ctx) => {

    const root = await PkgDir(cwd);

    if (!version && root && internals.pkgScope[pkg]) {

        version = internals.getPkgVersion(root, `@${internals.pkgScope[pkg]}/${pkg}`);
    }

    if (!version && root) {

        version = internals.getPkgVersion(root, pkg);
    }

    query = query.toLowerCase();

    let parsedVersion;

    try {
        parsedVersion = Somever.version(version);
    }
    catch (ignoreErr) {}

    const ref = parsedVersion ? `v${parsedVersion.version}` : (version || 'master');
    const owner = internals.pkgOwners[pkg] || 'hapijs';

    ctx.options.out.write(ctx.colors.grey(`Searching docs from ${owner}/${pkg} @ ${ref}...\n\n`));

    const getAPI = async () => {

        try {
            return await internals.getPkgAPI(owner, pkg, ref);
        }
        catch (err) {
            if (err.isBoom && err.output.statusCode === 404) {
                throw new DisplayError(ctx.colors.red(`Couldn\'t find docs for that version of ${pkg}. Are you sure ${owner}/${pkg} @ ${ref} exists?`));
            }

            if (err.syscall === 'getaddrinfo' && err.code === 'ENOTFOUND') {
                throw new DisplayError(ctx.colors.red(`Could not fetch the ${pkg} docs. It seems you may be offline– ensure you have a connection then try again.`));
            }

            throw new DisplayError(ctx.colors.red(`Could not fetch the ${pkg} docs: ${err.message}`));
        }
    };

    const getManifest = async () => {

        if (!root) {
            return null;
        }

        try {
            return await Helpers.getManifest(root, ctx, true);
        }
        catch (err) {
            // If we can't get the manifest for some reason we're aware of, that's okay
            if (err instanceof DisplayError) {
                return null;
            }

            throw err;
        }
    };

    const [api, manifest] = await Promise.all([getAPI(), getManifest()]);

    const pluralQuery = manifest && Pluralize.plural(query);
    const item = manifest && (manifest.find((m) => m.place === query) || manifest.find((m) => m.place === pluralQuery));
    const methodMatch = query.match(/^([a-z\.]+)/);
    const method = methodMatch && methodMatch[1];
    const headingMatchers = ([
        item && `server.${item.method}(`,
        method && `${method}(`,
        (query.length >= 3) && query
    ])
        .filter((x) => !!x)
        .map((match) => {

            return (section) => {

                if (match[0] === '#') {
                    return internals.anchorize(section)
                        .some((anchor) => ~anchor.indexOf(match));
                }

                return ~section.toLowerCase().indexOf(match);
            };
        });

    if (!itemQuery) {
        return Print.markdownSection(api, headingMatchers);
    }

    const itemQueryEsc = internals.regEscape(itemQuery);
    const itemRegExp = new RegExp(`^\s*\`?${itemQueryEsc}\`? -`, 'i');
    const listItemMatcher = (listItem) => itemRegExp.test(listItem);

    return Print.markdownListItem(api, headingMatchers, listItemMatcher);
};

internals.getPkgVersion = (root, pkg) => {

    try {
        // In node v8.9+ will be able to use require.resolve()'s { paths } option
        return require(`${root}/node_modules/${pkg}/package.json`).version;
    }
    catch (err) {

        if (err.code === 'MODULE_NOT_FOUND') {
            return null;
        }

        throw err;
    }
};

internals.getPkgAPI = async (owner, pkg, ref) => {

    const { payload } = await Wreck.get(`https://raw.githubusercontent.com/${owner}/${pkg}/${ref}/API.md`);

    return payload.toString();
};

internals.pkgScope = {
    accept: 'hapi',
    address: 'hapi',
    ammo: 'hapi',
    b64: 'hapi',
    basic: 'hapi',
    bell: 'hapi',
    boom: 'hapi',
    bossy: 'hapi',
    bounce: 'hapi',
    call: 'hapi',
    catbox: 'hapi',
    'catbox-memecached': 'hapi',
    'catbox-memory': 'hapi',
    'catbox-redis': 'hapi',
    code: 'hapi',
    content: 'hapi',
    cookie: 'hapi',
    crumb: 'hapi',
    cryptiles: 'hapi',
    glue: 'hapi',
    good: 'hapi',
    'good-console': 'hapi',
    'good-squeeze': 'hapi',
    h2o2: 'hapi',
    hapi: 'hapi',
    hawk: 'hapi',
    heavy: 'hapi',
    hoek: 'hapi',
    inert: 'hapi',
    iron: 'hapi',
    joi: 'hapi',
    'joi-date': 'hapi',
    lab: 'hapi',
    mimos: 'hapi',
    nes: 'hapi',
    nigel: 'hapi',
    oppsy: 'hapi',
    pez: 'hapi',
    podium: 'hapi',
    scooter: 'hapi',
    shot: 'hapi',
    sntp: 'hapi',
    somever: 'hapi',
    statehood: 'hapi',
    subtext: 'hapi',
    teamwork: 'hapi',
    topo: 'hapi',
    vise: 'hapi',
    vision: 'hapi',
    wreck: 'hapi',
    yar: 'hapi'
};

internals.pkgOwners = {
    schwifty: 'hapipal',
    schmervice: 'hapipal',
    toys: 'hapipal',
    'haute-couture': 'hapipal',
    hodgepodge: 'hapipal',
    underdog: 'hapipal',
    hecks: 'hapipal',
    lalalambda: 'hapipal',
    avocat: 'hapipal'
};

internals.anchorize = (str) => {

    str = str.toLowerCase();

    const anchors = [];
    const tag = str.match(Print.headingAnchorTagRegex);

    if (tag) {
        str = str.replace(tag[0], '-');
        anchors.push(`#${tag[1]}`);
    }

    anchors.push('#' + str.replace(/[^a-z0-9\s-]/ig, '').trim().replace(/\s/g, '-'));

    return anchors;
};

internals.regEscape = (str) => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
<|endoftext|>


<commit_before>"use strict"

const fs       = require("fs")
const path     = require("path")
const argv     = require("yargs").argv
const mkdirp   = require("mkdirp-bluebird")

const gulp     = require("gulp")
const gulpIf   = require("gulp-if")
const eslint   = require("gulp-eslint")
const mocha    = require("gulp-mocha")
const size     = require("gulp-size")

const jsdoc    = require("gulp-jsdoc3")

const fix = !!argv.fix
const grep = argv.grep

const jsdocConfig = require("./.jsdocrc.js")

gulp.task("default", ["lint", "test"])
gulp.task("build", ["build:node"])

const paths = {
	"test": [
		"test/**/*.test.js",
		"test/**/*.spec.js",
		"test/**/*.integration.js",
		"examples/**/*.js",
	],
}

gulp.task("doc", function X() {
	const jsdoc2md = require('jsdoc-to-markdown')
	const docDir = path.join(__dirname, "book", "en", "code")

	return mkdirp(docDir)
		.then( () => {
			return jsdoc2md.render({
				files: 'src/**/*.js',
				"name-format": false,
				"module-index-format": "none",
				"global-index-format": "table",
				//"configure": ".jsdocrc.json",
				"plugin": "dmd-gitbook",
				"no-scope": false,
			})
		})
		.then(output => {
			return fs.writeFile(path.join(docDir, 'api.md'), output)
		})
})

gulp.task("docold", function D() {           // eslint-disable-line prefer-arrow-callback
	// TODO: remove this task
	return gulp.src(
		"README.md", {
			read: false,
		})
		.pipe(jsdoc(jsdocConfig))
})

gulp.task("lint", function L() {          // eslint-disable-line prefer-arrow-callback
	return gulp.src([
		"./src/**/*.js",
		"./test/**/*.js",
		"./examples/**/*.js",
	], { "base": "./" })
		.pipe(eslint({
			fix,
		}))
		.pipe(eslint.format())
		.pipe(gulpIf(fix, gulp.dest("./")))
		.pipe(eslint.failAfterError())
})

gulp.task("test", function T() {          // eslint-disable-line prefer-arrow-callback
	return gulp.src(paths.test, { read: false })
		.pipe(mocha({
			// reporter: "list",
			ignoreLeaks: false,
			ui: "bdd",
			require: ["./test/bootstrap"],
			grep,
		}))
})

gulp.task("build:node", function BN() {      // eslint-disable-line prefer-arrow-callback
	return gulp.src("./src/**/*.js")
		.pipe(size({ title: "build:node", showFiles: true }))
		.pipe(gulp.dest("dist/"))
})
<commit_msg>New toolchain for building local docs<commit_after>"use strict"

const fs       = require("fs")
const path     = require("path")
const argv     = require("yargs").argv
const mkdirp   = require("mkdirp-bluebird")
const Promise  = require("bluebird")
const gulp     = require("gulp")
const util     = require("gulp-util")
const gulpIf   = require("gulp-if")
const eslint   = require("gulp-eslint")
const mocha    = require("gulp-mocha")
const size     = require("gulp-size")

// TODO: disable:
const jsdoc    = require("gulp-jsdoc3")

const jsdoc2md = require("jsdoc-to-markdown")

const fix = !!argv.fix
const grep = argv.grep

const jsdocConfig = require("./.jsdocrc.js")

gulp.task("default", ["lint", "test"])
gulp.task("build", ["build:node"])

const paths = {
	"test": [
		"test/**/*.test.js",
		"test/**/*.spec.js",
		"test/**/*.integration.js",
		"examples/**/*.js",
	],
}

gulp.task("doc", function X() {
	const docDir = path.join(__dirname, "book", "en", "code")

	const parentsTree = {}

	return mkdirp(docDir)
		.then(() => jsdoc2md.getTemplateData({
			files: "src/**/*.js",
		}))
		.each((item) => {
			parentsTree[item.id] = item
		})
		.reduce((acc, item) => {
			let ancestor = item
			while (ancestor && "undefined" !== typeof ancestor.memberof) {
				ancestor = parentsTree[ancestor.memberof]
			}
			let category = ancestor && ancestor.category

			if ("undefined" === typeof category) {
				category = "Uncategorized"
			}
			if (!acc.has(category)) {
				acc.set(category, [])
			}

			acc.get(category).push(item)

			return acc
		}, new Map())

		// render all categories:
		.map((item) => {
			const category = item[0]
			const data = item[1]

			return Promise.props({
				category,
				output: jsdoc2md.render({
					data,
					"name-format": false,
					"module-index-format": "none",
					"global-index-format": "table",
					// "configure": ".jsdocrc.json",
					"plugin": "dmd-gitbook",
					"no-scope": false,
				})
			})
		})
		// write to file:
		.map((item) => {
			const fn = path.join(docDir, `${item.category}.md`)
			util.log("DOC, saving to file", fn)
			return fs.writeFile(fn, item.output)
		})
})

gulp.task("docold", function D() {           // eslint-disable-line prefer-arrow-callback
	// TODO: remove this task
	return gulp.src(
		"README.md", {
			read: false,
		})
		.pipe(jsdoc(jsdocConfig))
})

gulp.task("lint", function L() {          // eslint-disable-line prefer-arrow-callback
	return gulp.src([
		"./src/**/*.js",
		"./test/**/*.js",
		"./examples/**/*.js",
	], { "base": "./" })
		.pipe(eslint({
			fix,
		}))
		.pipe(eslint.format())
		.pipe(gulpIf(fix, gulp.dest("./")))
		.pipe(eslint.failAfterError())
})

gulp.task("test", function T() {          // eslint-disable-line prefer-arrow-callback
	return gulp.src(paths.test, { read: false })
		.pipe(mocha({
			// reporter: "list",
			ignoreLeaks: false,
			ui: "bdd",
			require: ["./test/bootstrap"],
			grep,
		}))
})

gulp.task("build:node", function BN() {      // eslint-disable-line prefer-arrow-callback
	return gulp.src("./src/**/*.js")
		.pipe(size({ title: "build:node", showFiles: true }))
		.pipe(gulp.dest("dist/"))
})
<|endoftext|>


<commit_before>var _ = require('underscore');
var util = require('util');
var path = require('path');
var fs = require('fs');
var _DEBUG = false;
var ejs = require('ejs');
var hm = require('hive-menu');

/* ************************************
 *
 * ************************************ */

/* ******* CLOSURE ********* */

var _sidebar;

/* ********* EXPORTS ******** */

module.exports = function (apiary, cb) {

	fs.readFile(path.resolve(__dirname, 'sidebar_template.html'), 'utf8', function(err, txt){

		_sidebar = ejs.compile(txt);

		var helper = {

			name: 'main_menu',

			test: function (ctx, output) {
                // note there are other places that layout name can be specified
                // so this is a "lazy test" to make sure that another layout wasn't named.
				return (!output.layout_name) || (output.layout_name == 'bootstrap');
			},

			weight: -55,

			respond: function (ctx, output, done) {
				if (!output.helpers){
					output.helpers = {};
				}

				var site_menu = new hm.Menu({
					name: 'site',
					title: 'Site',
					items: [
						{name: 'home', title: 'Home', link: '/', weight: -1000000},
                        {name: 'another_page', title: 'A page in your site', link: '/a_page', weight: 0}
					]
				})

				var menu = new hm.Menu({name: 'sidebar', title: '', items: [
					site_menu
				]});

				output.helpers.sidebar_menu_data = menu;
                output.helpers.site_menu = site_menu;

				output.helpers.sidebar_menu = function(){
					return _sidebar(output.helpers.sidebar_menu_data.toJSON());
				};

			}
		};

		cb(null, helper);

	})

};<commit_msg>fixing bad callback on main_menu.js<commit_after>var _ = require('underscore');
var util = require('util');
var path = require('path');
var fs = require('fs');
var _DEBUG = false;
var ejs = require('ejs');
var hm = require('hive-menu');

/* ************************************
 *
 * ************************************ */

/* ******* CLOSURE ********* */

var _sidebar;
var SIDEBAR_TEMPLATE = path.resolve(__dirname, 'sidebar_template.html');

/* ********* EXPORTS ******** */

module.exports = function (apiary, cb) {

    if (_DEBUG) console.log('reading %s', SIDEBAR_TEMPLATE);
	fs.readFile(SIDEBAR_TEMPLATE, 'utf8', function(err, txt){

		_sidebar = ejs.compile(txt);
        if (_DEBUG) console.log('... loaded and compiled sidebar template.');

		var helper = {

			name: 'main_menu',

			test: function (ctx, output) {
                // note there are other places that layout name can be specified
                // so this is a "lazy test" to make sure that another layout wasn't named.
				return (!output.layout_name) || (output.layout_name == 'bootstrap');
			},

			weight: -55,

			respond: function (ctx, output, done) {
				if (!output.helpers){
					output.helpers = {};
				}

				var site_menu = new hm.Menu({
					name: 'site',
					title: 'Site',
					items: [
						{name: 'home', title: 'Home', link: '/', weight: -1000000},
                        {name: 'another_page', title: 'A page in your site', link: '/a_page', weight: 0}
					]
				})

				var menu = new hm.Menu({name: 'sidebar', title: '', items: [
					site_menu
				]});

				output.helpers.sidebar_menu_data = menu;
                output.helpers.site_menu = site_menu;

				output.helpers.sidebar_menu = function(){
					return _sidebar(output.helpers.sidebar_menu_data.toJSON());
				};

                done();
			}
		};

		cb(null, helper);

	})

};<|endoftext|>


<commit_before>console.log('Yooooooooooo, I am front.js, I am pretty!! ')

// $.ajax({
//   url: "/users/monthly_data",
//   data: {
//     year: 2013,
//     month: 12
//   },
//   async: false,
//   dataType: 'json',
//   success: function(data) {
//     console.log(data);
//   },
//   error: function(data) { }
// });

$.getJSON('http://graph.facebook.com/100000202897569?fields=id,name')
.success(function(data){
  console.log(data);
});<commit_msg>front.js, 移除不用的code<commit_after>console.log('Yooooooooooo, I am front.js, I am pretty!! ')

// $.ajax({
//   url: "/users/monthly_data",
//   data: {
//     year: 2013,
//     month: 12
//   },
//   async: false,
//   dataType: 'json',
//   success: function(data) {
//     console.log(data);
//   },
//   error: function(data) { }
// });
<|endoftext|>


<commit_before>/* eslint-env jest */

import React from 'react';
import { mount } from 'enzyme';

import ToastContainer from './../ToastContainer';
import toaster from './../toaster';
import EventManager from './../util/EventManager';
import config from './../config';

jest.useFakeTimers();

describe('toastify', () => {
  it("Should emit notification only if a container is mounted", () => {
    const spy = jest.fn();

    EventManager.on(config.ACTION.SHOW, spy);
    toaster('hello');
    expect(spy).not.toHaveBeenCalled();

    mount(<ToastContainer />);
    jest.runAllTimers();

    expect(spy).toHaveBeenCalled();
  });

  it("Should return a new id each time we emit a notification", () => {
    const firstId = toaster('Hello');
    const secondId = toaster('Hello');

    expect(firstId).not.toEqual(secondId);
  });

  it("Can remove toast programmatically", () => {
    const component = mount(<ToastContainer autoClose={false} />);
    const id = toaster('hello');

    jest.runAllTimers();
    expect(component.state('toast')[0]).toBe(id);

    toaster.dismiss(id);
    jest.runAllTimers();
    expect(component.state('toast').length).toBe(0);
  });

  it("Can tell if a toast is active based on the id", () => {
    mount(<ToastContainer autoClose={false} />);
    const id = toaster('hello');

    jest.runAllTimers();
    expect(toaster.isActive(id)).toBe(true);
  });

  it("Can overwrite classNames", () => {
    const component = mount(<ToastContainer />);
    toaster('hello', {
      className: 'class1',
      bodyClassName: 'class2',
      progressClassName: 'class3'
    });

    jest.runAllTimers();

    expect(component.find('.toastify-content').hasClass('class1')).toBe(true);
    expect(component.find('.toastify__body').hasClass('class2')).toBe(true);
    expect(component.find('.toastify__progress').hasClass('class3')).toBe(true);
  });
});
<commit_msg>Fix toaster test<commit_after>/* eslint-env jest */

import React from 'react';
import { mount } from 'enzyme';

import ToastContainer from './../ToastContainer';
import toaster from './../toaster';
import EventManager from './../util/EventManager';
import config from './../config';

jest.useFakeTimers();

describe('toastify', () => {
  it("Should emit notification only if a container is mounted", () => {
    const spy = jest.fn();

    EventManager.on(config.ACTION.SHOW, spy);
    toaster('hello');
    expect(spy).not.toHaveBeenCalled();

    mount(<ToastContainer />);
    jest.runAllTimers();

    expect(spy).toHaveBeenCalled();
  });

  it("Should return a new id each time we emit a notification", () => {
    const firstId = toaster('Hello');
    const secondId = toaster('Hello');

    expect(firstId).not.toEqual(secondId);
  });

  it("Can remove toast programmatically", () => {
    const component = mount(<ToastContainer autoClose={false} />);
    const id = toaster('hello');

    jest.runAllTimers();
    expect(component.state('toast')[0]).toBe(id);

    toaster.dismiss(id);
    jest.runAllTimers();
    expect(component.state('toast').length).toBe(0);
  });

  it("Can tell if a toast is active based on the id", () => {
    mount(<ToastContainer autoClose={false} />);
    const id = toaster('hello');

    jest.runAllTimers();
    expect(toaster.isActive(id)).toBe(true);
  });

  it("Can append classNames", () => {
    const component = mount(<ToastContainer />);
    toaster('hello', {
      className: 'class1',
      bodyClassName: 'class2',
      progressClassName: 'class3'
    });

    jest.runAllTimers();
    expect(component.render().find('.toastify-content').hasClass('class1')).toBe(true);
    expect(component.render().find('.toastify__body').hasClass('class2')).toBe(true);
    expect(component.render().find('.toastify__progress').hasClass('class3')).toBe(true);
  });
});
<|endoftext|>


<commit_before>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",

cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",

defaults = {
	'format': 'text',
	'flavor': 'latin',
	'sentences_per_paragraph': [3, 5],
	'words_per_sentence': [10, 31],
	'commas_per_sentence': [0, 4]
},

config = {},

punct = [',','.',';',':','?','!'],

punct_reg = new RegExp('[' + punct.join('') + ']*','g'),

flavors = {
	'latin': dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') )
},

dimsum = global.dimsum = module.exports = exports = function(num_paragraphs, options) {
	return dimsum.generate(num_paragraphs, options);
};

/**
 * The standard Lorem Ipsum passage.
 */
dimsum.classic = function() {
	return classic;
};

/**
 * Section 1.10.32 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero32 = function() {
	return cicero_1_10_32;
};

/**
 * Section 1.10.33 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero33 = function() {
	return cicero_1_10_33;
};

/**
 * Restore default configuration.
 */
dimsum.initialize = function() {
	return this.configure(defaults);
};

/**
 * Override the current configuration.
 *
 * @param options
 *		An object containing new config values.
 */
dimsum.configure = function(options) {
	config = shallow_copy(config, options);
	return this;
};

/**
 * @return A list of flavors that are currently available.
 */
dimsum.flavors = function() {
	return Object.keys(flavors);
};

/**
 * Creates a flavor out of the ingredients.
 *
 * @return An array containing the words used in this flavor.
 */
dimsum.flavor = function(name, ingredients) {

	if (arguments.length == 0) {
		return;
	}
	else if (arguments.length == 1) {

		if (name.match(/\s/)) {
			return dedupe( normify([name]).split(' ') );
		}
		else {
			return flavors[name];
		}
	}
	else {
		flavors[name] = (typeof ingredients == 'Array') ? ingredients : dedupe( normify([ingredients]).split(' ') );
		return flavors[name];
	}
};

/**
 * Create a random chunk of lipsum. Returns a string containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs
 * 		How many paragraphs to generate.
 *
 * @param options
 *		An object containing new config values. The new options
 *		will only apply to this one execution.
 */
dimsum.generate = function(num_paragraphs, options) {

	var config_1 = config,
		sentences = [],
		paragraphs = [],
		result = '',
		num_paragraphs = num_paragraphs || 1;

	// Temporarily overwrite the configuration
	this.configure(options);

	// Add some paragraphs
	while (paragraphs.length < num_paragraphs) {
		paragraphs.push(this.paragraph());
	}

	// Make it pretty
	switch(config.format) {
		case 'text':
			result = paragraphs.join("\r\n\r\n");
			break;
		case 'html':
			result = '
' + paragraphs.join('

') + '
';
			break;
	}

	// Restore the original configuration
	config = config_1;

	return result;
};

/**
 * Create a single sentence of random lipsum.
 */
dimsum.sentence = function() {

	var word = '',
		words = [],
		num_words = range(config.words_per_sentence[0], config.words_per_sentence[1]),
		num_commas = range(config.commas_per_sentence[0], config.commas_per_sentence[1]),
		flavor = flavors[config.flavor];

	// Get some words
	while (words.length < num_words) {
		word = flavor[ range(0, flavor.length -1) ];
		words.push(word);
	}

	// Add some commas
	for (var i = 0; i < num_commas; i++) {
		word = range(4, words.length - 3);
		if (!words[word]) {
			break;
		}
		else if (words[word].match(',')) {
			i--;
		}
		else {
			words[word] += ',';
		}
	}

	// Capitalize the first word
	words = words.join(' ');
	words = words.replace(/^[a-z]/i, words[0].toUpperCase());

	// Punctuate and return
	return words + '.';
};

/**
 * Create a single paragraph of random lipsum.
 */
dimsum.paragraph = function() {

	var sentences = [],
		num_sentences = range(config.sentences_per_paragraph[0], config.sentences_per_paragraph[1]);

	while (sentences.length < num_sentences) {
		sentences.push(this.sentence());
	}
	return sentences.join(' ');
};

dimsum.initialize();

/** Utils **/
function normify(strings) {
	return strings.join(' ')
			.toLowerCase()
			.replace(punct_reg, '');
};

function dedupe(array) {

	var obj = {},
		result = [];

	for (var i = 0; i < array.length; i++) {
		obj[array[i]] = null;
	}
	for (key in obj) {
		result.push(key);
	}
	return result;
};

function range(min, max) {
	return min + Math.random() * (max - min) << 0;
};

function shallow_copy() {

	var i, key, result = {},
		args = Array.prototype.slice.call(arguments);

	for (i = 0; i < args.length; i++) {
		for (key in args[i]) {
			result[key] = args[i][key];
		}
	}
	return result;
};

/* Debug */
// dimsum.normify = normify;
// dimsum.dedupe = dedupe;
// dimsum.range = range;
// dimsum.shallow_copy = shallow_copy;

}(this));<commit_msg>Fixnig a client-side support issue<commit_after>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",

cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",

defaults = {
	'format': 'text',
	'flavor': 'latin',
	'sentences_per_paragraph': [3, 5],
	'words_per_sentence': [10, 31],
	'commas_per_sentence': [0, 4]
},

config = {},

punct = [',','.',';',':','?','!'],

punct_reg = new RegExp('[' + punct.join('') + ']*','g'),

flavors = {
	'latin': dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') )
},

dimsum = global.dimsum = exports = function(num_paragraphs, options) {
	return dimsum.generate(num_paragraphs, options);
};

// For client-side compatibility
if (module) module.exports = dimsum;

/**
 * The standard Lorem Ipsum passage.
 */
dimsum.classic = function() {
	return classic;
};

/**
 * Section 1.10.32 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero32 = function() {
	return cicero_1_10_32;
};

/**
 * Section 1.10.33 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero33 = function() {
	return cicero_1_10_33;
};

/**
 * Restore default configuration.
 */
dimsum.initialize = function() {
	return this.configure(defaults);
};

/**
 * Override the current configuration.
 *
 * @param options
 *		An object containing new config values.
 */
dimsum.configure = function(options) {
	config = shallow_copy(config, options);
	return this;
};

/**
 * @return A list of flavors that are currently available.
 */
dimsum.flavors = function() {
	return Object.keys(flavors);
};

/**
 * Creates a flavor out of the ingredients.
 *
 * @return An array containing the words used in this flavor.
 */
dimsum.flavor = function(name, ingredients) {

	if (arguments.length == 0) {
		return;
	}
	else if (arguments.length == 1) {

		if (name.match(/\s/)) {
			return dedupe( normify([name]).split(' ') );
		}
		else {
			return flavors[name];
		}
	}
	else {
		flavors[name] = (typeof ingredients == 'Array') ? ingredients : dedupe( normify([ingredients]).split(' ') );
		return flavors[name];
	}
};

/**
 * Create a random chunk of lipsum. Returns a string containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs
 * 		How many paragraphs to generate.
 *
 * @param options
 *		An object containing new config values. The new options
 *		will only apply to this one execution.
 */
dimsum.generate = function(num_paragraphs, options) {

	var config_1 = config,
		sentences = [],
		paragraphs = [],
		result = '',
		num_paragraphs = num_paragraphs || 1;

	// Temporarily overwrite the configuration
	this.configure(options);

	// Add some paragraphs
	while (paragraphs.length < num_paragraphs) {
		paragraphs.push(this.paragraph());
	}

	// Make it pretty
	switch(config.format) {
		case 'text':
			result = paragraphs.join("\r\n\r\n");
			break;
		case 'html':
			result = '
' + paragraphs.join('

') + '
';
			break;
	}

	// Restore the original configuration
	config = config_1;

	return result;
};

/**
 * Create a single sentence of random lipsum.
 */
dimsum.sentence = function() {

	var word = '',
		words = [],
		num_words = range(config.words_per_sentence[0], config.words_per_sentence[1]),
		num_commas = range(config.commas_per_sentence[0], config.commas_per_sentence[1]),
		flavor = flavors[config.flavor];

	// Get some words
	while (words.length < num_words) {
		word = flavor[ range(0, flavor.length -1) ];
		words.push(word);
	}

	// Add some commas
	for (var i = 0; i < num_commas; i++) {
		word = range(4, words.length - 3);
		if (!words[word]) {
			break;
		}
		else if (words[word].match(',')) {
			i--;
		}
		else {
			words[word] += ',';
		}
	}

	// Capitalize the first word
	words = words.join(' ');
	words = words.replace(/^[a-z]/i, words[0].toUpperCase());

	// Punctuate and return
	return words + '.';
};

/**
 * Create a single paragraph of random lipsum.
 */
dimsum.paragraph = function() {

	var sentences = [],
		num_sentences = range(config.sentences_per_paragraph[0], config.sentences_per_paragraph[1]);

	while (sentences.length < num_sentences) {
		sentences.push(this.sentence());
	}
	return sentences.join(' ');
};

dimsum.initialize();

/** Utils **/
function normify(strings) {
	return strings.join(' ')
			.toLowerCase()
			.replace(punct_reg, '');
};

function dedupe(array) {

	var obj = {},
		result = [];

	for (var i = 0; i < array.length; i++) {
		obj[array[i]] = null;
	}
	for (key in obj) {
		result.push(key);
	}
	return result;
};

function range(min, max) {
	return min + Math.random() * (max - min) << 0;
};

function shallow_copy() {

	var i, key, result = {},
		args = Array.prototype.slice.call(arguments);

	for (i = 0; i < args.length; i++) {
		for (key in args[i]) {
			result[key] = args[i][key];
		}
	}
	return result;
};

/* Debug */
// dimsum.normify = normify;
// dimsum.dedupe = dedupe;
// dimsum.range = range;
// dimsum.shallow_copy = shallow_copy;

}(this));<|endoftext|>


<commit_before>module.directive('partyEditAccountForm', [
	'pageService', function (page) {
		var link = function ($scope) {
			var form = $scope.partyEditAccountForm;

			form.data = {};
			form.authors = [];
			var backup = {};

			form.saveFn = undefined;
			form.resetFn = undefined;
			form.successFn = undefined;
			form.errorFn = undefined;

			//

			form.init = function (party) {
				form.party = form.party || party;
				form.data = {
					email: party.email,
				};

				backup = $.extend(true, {}, form.data);
			};

			$scope.$watch('partyEditAccountForm.data.password.again', function () {
				form['password.again'].$setValidity('match', !form.data.password || form.data.password.once == form.data.password.again);
			});

			//

			form.save = function () {
				if (angular.isFunction(form.saveFn)) {
					form.saveFn(form);
				}

				page.models.Party.save({
						id: form.party.id,
					}, form.data,
					function (res) {
						form.validator.server({});

						form.messages.add({
							type: 'green',
							countdown: 3000,
							body: page.constants.message('party.edit.profile.success'),
						});

						backup = $.extend(true, {}, form.data);

						if (angular.isFunction(form.successFn)) {
							form.successFn(form, res);
						}

						form.$setPristine();
						page.models.party.$cache.removeAll();
						form.clearPasswordFields();
					}, function (res) {
						form.validator.server(res);
						page.display.scrollTo(form.$element);

						if (angular.isFunction(form.errorFn)) {
							form.errorFn(form, res);
						}
					});
			};

			form.reset = function () {
				if (angular.isFunction(form.resetFn)) {
					form.resetFn(form);
				}

				form.validator.clearServer();

				form.data = $.extend(true, {}, backup);
				form.$setPristine();
			};

			form.ready = function () {
				return form.$dirty && form.$valid && form.data.auth && form.data.password && (form.data.password.once == form.data.password.again);
			};

			//

			form.validator.client({
				email: {
					tips: page.constants.message('party.edit.email.help'),
					errors: page.constants.message('login.email.error'),
				},
				password: {
					tips: page.constants.message('party.edit.password.help'),
				},
				'password.again': {
					tips: page.constants.message('party.edit.password.again.help'),
					errors: page.constants.message('party.edit.password.again.error'),
				},
				auth: {
					tips: page.constants.message('party.edit.auth.help'),
				},
			}, true);

			form.clearPasswordFields = function(){
				form.data.auth = undefined;
				form.data.password.again = undefined;
				form.data.password.once = undefined;
			};

			//

			page.events.talk('partyEditAccountForm-init', form, $scope);
		};

		//

		return {
			restrict: 'E',
			templateUrl: 'partyEditAccountForm.html',
			scope: false,
			replace: true,
			link: link
		};
	}
]);
<commit_msg>slight changes to prev<commit_after>module.directive('partyEditAccountForm', [
	'pageService', function (page) {
		var link = function ($scope) {
			var form = $scope.partyEditAccountForm;

			form.data = {};
			form.authors = [];
			var backup = {};

			form.saveFn = undefined;
			form.resetFn = undefined;
			form.successFn = undefined;
			form.errorFn = undefined;

			//

			form.init = function (party) {
				form.party = form.party || party;
				form.data = {
					email: party.email,
				};

				backup = $.extend(true, {}, form.data);
			};

			$scope.$watch('partyEditAccountForm.data.password.again', function () {
				form['password.again'].$setValidity('match', !form.data.password || form.data.password.once == form.data.password.again);
			});

			//

			form.save = function () {
				if (angular.isFunction(form.saveFn)) {
					form.saveFn(form);
				}

				page.models.Party.save({
						id: form.party.id,
					}, form.data,
					function (res) {
						form.validator.server({});

						form.messages.add({
							type: 'green',
							countdown: 3000,
							body: page.constants.message('party.edit.profile.success'),
						});

						backup = $.extend(true, {}, form.data);

						if (angular.isFunction(form.successFn)) {
							form.successFn(form, res);
						}

						form.$setPristine();
						page.models.party.$cache.removeAll();
						form.clearPasswordFields();
					}, function (res) {
						form.validator.server(res);
						page.display.scrollTo(form.$element);

						if (angular.isFunction(form.errorFn)) {
							form.errorFn(form, res);
						}
					});
			};

			form.reset = function () {
				if (angular.isFunction(form.resetFn)) {
					form.resetFn(form);
				}

				form.validator.clearServer();

				form.data = $.extend(true, {}, backup);
				form.$setPristine();
			};

			form.ready = function () {
				return form.$dirty && form.$valid && form.data.auth && (!form.data.password || (!form.data.password.once || form.data.password.once == form.data.password.again));
			};

			//

			form.validator.client({
				email: {
					tips: page.constants.message('party.edit.email.help'),
					errors: page.constants.message('login.email.error'),
				},
				password: {
					tips: page.constants.message('party.edit.password.help'),
				},
				'password.again': {
					tips: page.constants.message('party.edit.password.again.help'),
					errors: page.constants.message('party.edit.password.again.error'),
				},
				auth: {
					tips: page.constants.message('party.edit.auth.help'),
				},
			}, true);

			form.clearPasswordFields = function(){
				form.data.auth = undefined;
				if(form.data.password)
				{
					form.data.password.again = undefined;
					form.data.password.once = undefined;
				}
			};

			//

			page.events.talk('partyEditAccountForm-init', form, $scope);
		};

		//

		return {
			restrict: 'E',
			templateUrl: 'partyEditAccountForm.html',
			scope: false,
			replace: true,
			link: link
		};
	}
]);
<|endoftext|>


<commit_before>

ap.speed = 0.07;				// How much we increase 'global time' per 'animation frame'
ap.useTransforms = false;		// Pod transforms (swap axis, translate, scale)
ap.usePodUniforms = false;		// Allow u_pos_id uniforms to update a pod position by id

ap.pointCloud = {};				// Main point cloud that displays node colors
ap.pointGeometry = {};			// The geometry of the point cloud that displays the node colors
ap.pointMaterial = {};			// Shader of the point cloud that displays the node colors

ap.material = false;			// Main shader referenced here, set false initially to flag that its not ready

ap.init = function(scene, renderer, maxNodeCount){

	 // Tag each shader with a incremental id, for easy lookup later
	var i = 0;
	for (var property in ap.clips) {
		if (ap.clips.hasOwnProperty(property)) {
			ap.clips[property].id = i;
			i++;
		}
	}

	// Maintain the lowest possible power of 2 texture size based on maxNodeCount
	maxNodeCount = maxNodeCount || Math.pow(128, 2); 	// Default: 16384 (128*128)
	ap.simSize = 4;										// Minimum: 16 (4*4)
	while(Math.pow(ap.simSize, 2) < maxNodeCount){
		ap.simSize *= 2;
	}

	ap.ports = new ap.PortManager();
	ap.hardware = new ap.HardwareManager();
	ap.channels = new ap.ChannelManager();
	ap.app = new ap.AppManager(scene, renderer);

	ap.ports.init();
	ap.hardware.init();
	ap.channels.init();
	ap.app.init();

	// If size not yet been defined, do it with some defaults
	if(!ap.appSize){
		ap.setSize(600, 400);
	}

};

// Set this to store a [uniform float array] with specified length
// Can be referenced later in shaders, and ap.set/get as 'data'
ap.dataSetLength = null;

ap.updateShader = false;
ap.updateFresh = false;
ap.updateShaderLimiter = 0;
ap.update = function() {

	//if(frameCount % 30 == 1){ // Slow framerate testing

	if(!ap.app){

		console.log("AP Error: Need to call ap.init before ap.update.");

	}else if(ap.ready){

		// Update everything else if we don't have to update the shader this frame
		if((!ap.updateShader || ap.updateShaderLimiter < 4) && ap.updateShaderLimiter > 0){

			// ** Main loop update
			ap.app.update();
			ap.ports.update();
			ap.hardware.update();
			ap.channels.update();

		}else{

			// Shader needs update
			ap.app.updateMainSourceShader();
			ap.app.update();
			ap.updateShaderLimiter = 0;
			ap.updateShader = false;
			ap.updateFresh = false;
		}
		ap.updateShaderLimiter++;

	}
};

ap.pointPosition = [-400, -400, 0]; // Defaults
ap.setPointPosition = function(x, y, z) {
	ap.pointPosition = [x, y, z];
	if(ap.pointCloud.position){
		ap.pointCloud.position = {x: x, y: y, z: z};
	}
};

ap.appSize;
ap.setSize = function(width, height) {

	ap.appSize = [width, height];

	if(ap.app){

		ap.app.glWidth = width;
		ap.app.glHeight = height;

		if(ap.app.readPixels){
			ap.app.pixels = new Uint8Array(4 * ap.app.glWidth * ap.app.glHeight);
		}

		ap.app.renderer.setSize( ap.app.glWidth, ap.app.glHeight );

	}
};

ap.importShader = function (name, shaderTxt) {

	var brackStatus = 0;
	var grab = false;
	var grabTxt = "";
	var defintions = "";
	var f = 0;
	var c = 0;

	var shader = {};
	shader.constants = [];
	shader.fragmentFunctions = [];

	// Split shader by line breaks
	var results = shaderTxt.split("\n");
	for (var i = 0; i < results.length; i++) {

		var l = results[i].trim();
		l = l.replace(/ +(?= )/g,''); // remove multiple spaces

		if(l.length > 0){

			// Detect how many open and closed brackets
			var brackOpen  = l.replace(/[^{]/g, "").length;
			var brackClose = l.replace(/[^}]/g, "").length;
			brackStatus += brackOpen;
			brackStatus -= brackClose;

			// If we have a open bracket
			if(brackStatus > 0){
				grab = true;
			}

			if(grab){
				grabTxt += l + "\n";

				// If we have a closed bracket while we are open, close
				if(brackStatus === 0){
					grab = false;

					if(grabTxt.localeCompare("void main(") > -1){

						// Main function: add it to the sorce method
						shader.fragmentMain = grabTxt;
					}else{

						// Normal function: add it to the list
						shader.fragmentFunctions[f] = grabTxt;
						f++;
					}

					grabTxt = "";
				}

			// If the constant is not blacklisted add it
			}else if(!blackList(l)){

				shader.constants[c] = l;
				c++;
			}

		}

	};

	function blackList(msg){
		if(msg.localeCompare("#ifdef GL_ES") > -1){return true;}
		if(msg.localeCompare("#endif") > -1){return true;}
		if(msg.localeCompare("uniform float time") > -1){return true;}
		if(msg.localeCompare("uniform vec2 resolution") > -1){return true;}
		if(msg.localeCompare("precision highp float") > -1){return true;}
		return false;
	}

	// TODO only show inside of shader.fragmentMain {brackets}

	//console.log(defintions);
	console.log(shader);
	//console.log(grabTxt);

};

ap.generateShader = function () {

	ap.app.updateMainSourceShader();

};

ap.updateNodePoints = function () {

	ap.app.updateGeometry();
	ap.app.generateCoordsMap();
	ap.app.createNodePointCloud();

};

ap.get = function(uniform, channel, pod, clip) {
	if(!channel){
		return ap.material.uniforms[uniform].value;
	}else{
		return ap.getUniform(uniform, channel, pod, clip).value;
	}
};

ap.set = function(uniform, value, channel, pod, clip) {
	if(!channel){
		ap.material.uniforms[uniform].value = value;
	}else{
		ap.getUniform(uniform, channel, pod, clip).value = value;
		ap.setObjProperty(uniform, value, channel, pod, clip);
	}
};

ap.getUniform = function(uniform, channel, pod, clip) {
	var addy = "_" + channel;
	if(pod){ addy += "_" + pod;
	if(clip){ addy += "_" + clip; }}
	return ap.material.uniforms[addy + "_" + uniform];
};

ap.getObj = function(channel, pod, clip) {
	var obj = ap.channels.channels[channel-1];
	if(pod){ obj = obj.pods[pod-1];
	if(clip){ obj = obj.clips[clip-1]; }}
	return obj;
};

ap.setObj = function(newObj, channel, pod, clip) {
	if(!pod){
		ap.channels.channels[channel-1] = newObj;
	}else if(!clip){
		ap.channels.channels[channel-1].pods[pod-1] = newObj;
	}else{
		ap.channels.channels[channel-1].pods[pod-1].clips[clip-1] = newObj;
	}
};

ap.getObjProperty = function(property, channel, pod, clip) {
	var obj = ap.getObj(channel, pod, clip);
	return obj[property];
};

ap.setObjProperty = function(property, value, channel, pod, clip) {
	var obj = ap.getObj(channel, pod, clip);
	obj[property] = value;
};

ap.load = function(json){
	ap.channels.channels = json;
	ap.updateShader = true;
	ap.updateFresh = true;
};

ap.stringify = function(){
	return JSON.stringify(ap.channels.channels);
};<commit_msg>glsl fragment shader importer p2<commit_after>

ap.speed = 0.07;				// How much we increase 'global time' per 'animation frame'
ap.useTransforms = false;		// Pod transforms (swap axis, translate, scale)
ap.usePodUniforms = false;		// Allow u_pos_id uniforms to update a pod position by id

ap.pointCloud = {};				// Main point cloud that displays node colors
ap.pointGeometry = {};			// The geometry of the point cloud that displays the node colors
ap.pointMaterial = {};			// Shader of the point cloud that displays the node colors

ap.material = false;			// Main shader referenced here, set false initially to flag that its not ready

ap.init = function(scene, renderer, maxNodeCount){

	 // Tag each shader with a incremental id, for easy lookup later
	var i = 0;
	for (var property in ap.clips) {
		if (ap.clips.hasOwnProperty(property)) {
			ap.clips[property].id = i;
			i++;
		}
	}

	// Maintain the lowest possible power of 2 texture size based on maxNodeCount
	maxNodeCount = maxNodeCount || Math.pow(128, 2); 	// Default: 16384 (128*128)
	ap.simSize = 4;										// Minimum: 16 (4*4)
	while(Math.pow(ap.simSize, 2) < maxNodeCount){
		ap.simSize *= 2;
	}

	ap.ports = new ap.PortManager();
	ap.hardware = new ap.HardwareManager();
	ap.channels = new ap.ChannelManager();
	ap.app = new ap.AppManager(scene, renderer);

	ap.ports.init();
	ap.hardware.init();
	ap.channels.init();
	ap.app.init();

	// If size not yet been defined, do it with some defaults
	if(!ap.appSize){
		ap.setSize(600, 400);
	}

};

// Set this to store a [uniform float array] with specified length
// Can be referenced later in shaders, and ap.set/get as 'data'
ap.dataSetLength = null;

ap.updateShader = false;
ap.updateFresh = false;
ap.updateShaderLimiter = 0;
ap.update = function() {

	//if(frameCount % 30 == 1){ // Slow framerate testing

	if(!ap.app){

		console.log("AP Error: Need to call ap.init before ap.update.");

	}else if(ap.ready){

		// Update everything else if we don't have to update the shader this frame
		if((!ap.updateShader || ap.updateShaderLimiter < 4) && ap.updateShaderLimiter > 0){

			// ** Main loop update
			ap.app.update();
			ap.ports.update();
			ap.hardware.update();
			ap.channels.update();

		}else{

			// Shader needs update
			ap.app.updateMainSourceShader();
			ap.app.update();
			ap.updateShaderLimiter = 0;
			ap.updateShader = false;
			ap.updateFresh = false;
		}
		ap.updateShaderLimiter++;

	}
};

ap.pointPosition = [-400, -400, 0]; // Defaults
ap.setPointPosition = function(x, y, z) {
	ap.pointPosition = [x, y, z];
	if(ap.pointCloud.position){
		ap.pointCloud.position = {x: x, y: y, z: z};
	}
};

ap.appSize;
ap.setSize = function(width, height) {

	ap.appSize = [width, height];

	if(ap.app){

		ap.app.glWidth = width;
		ap.app.glHeight = height;

		if(ap.app.readPixels){
			ap.app.pixels = new Uint8Array(4 * ap.app.glWidth * ap.app.glHeight);
		}

		ap.app.renderer.setSize( ap.app.glWidth, ap.app.glHeight );

	}
};

ap.importShader = function (name, shaderTxt) {

	var brackStatus = 0;
	var grab = false;
	var grabTxt = "";
	var defintions = "";
	var f = 0;
	var c = 0;

	var shader = {};
	shader.constants = [];
	shader.fragmentFunctions = [];

	// Split shader by line breaks
	var results = shaderTxt.split("\n");
	for (var i = 0; i < results.length; i++) {

		var l = results[i].trim();
		l = l.replace(/ +(?= )/g,''); // remove multiple spaces

		if(l.length > 0){

			// Detect how many open and closed brackets
			var brackOpen  = l.replace(/[^{]/g, "").length;
			var brackClose = l.replace(/[^}]/g, "").length;
			brackStatus += brackOpen;
			brackStatus -= brackClose;

			// If we have a open bracket
			if(brackStatus > 0){
				grab = true;
			}

			if(grab){
				grabTxt += l + "\n";

				// If we have a closed bracket while we are open, close
				if(brackStatus === 0){
					grab = false;

					if(grabTxt.localeCompare("void main(") > -1){

						// Main function: Grab text between main brackets and add it to the sorce method
						shader.fragmentMain = grabTxt.slice(grabTxt.indexOf("{") + 1, grabTxt.lastIndexOf("}"));

					}else{

						// Normal function: add it to the list
						shader.fragmentFunctions[f] = grabTxt;
						f++;
					}

					grabTxt = "";
				}

			// If the constant is not blacklisted add it
			}else if(!blackList(l)){

				shader.constants[c] = l;
				c++;
			}

		}

	};

	function blackList(msg){
		if(msg.localeCompare("#ifdef GL_ES") > -1){return true;}
		if(msg.localeCompare("#endif") > -1){return true;}
		if(msg.localeCompare("uniform float time") > -1){return true;}
		if(msg.localeCompare("uniform vec2 resolution") > -1){return true;}
		if(msg.localeCompare("precision highp float") > -1){return true;}
		return false;
	}

	//console.log(defintions);
	console.log(shader);
	//console.log(grabTxt);

};

ap.generateShader = function () {

	ap.app.updateMainSourceShader();

};

ap.updateNodePoints = function () {

	ap.app.updateGeometry();
	ap.app.generateCoordsMap();
	ap.app.createNodePointCloud();

};

ap.get = function(uniform, channel, pod, clip) {
	if(!channel){
		return ap.material.uniforms[uniform].value;
	}else{
		return ap.getUniform(uniform, channel, pod, clip).value;
	}
};

ap.set = function(uniform, value, channel, pod, clip) {
	if(!channel){
		ap.material.uniforms[uniform].value = value;
	}else{
		ap.getUniform(uniform, channel, pod, clip).value = value;
		ap.setObjProperty(uniform, value, channel, pod, clip);
	}
};

ap.getUniform = function(uniform, channel, pod, clip) {
	var addy = "_" + channel;
	if(pod){ addy += "_" + pod;
	if(clip){ addy += "_" + clip; }}
	return ap.material.uniforms[addy + "_" + uniform];
};

ap.getObj = function(channel, pod, clip) {
	var obj = ap.channels.channels[channel-1];
	if(pod){ obj = obj.pods[pod-1];
	if(clip){ obj = obj.clips[clip-1]; }}
	return obj;
};

ap.setObj = function(newObj, channel, pod, clip) {
	if(!pod){
		ap.channels.channels[channel-1] = newObj;
	}else if(!clip){
		ap.channels.channels[channel-1].pods[pod-1] = newObj;
	}else{
		ap.channels.channels[channel-1].pods[pod-1].clips[clip-1] = newObj;
	}
};

ap.getObjProperty = function(property, channel, pod, clip) {
	var obj = ap.getObj(channel, pod, clip);
	return obj[property];
};

ap.setObjProperty = function(property, value, channel, pod, clip) {
	var obj = ap.getObj(channel, pod, clip);
	obj[property] = value;
};

ap.load = function(json){
	ap.channels.channels = json;
	ap.updateShader = true;
	ap.updateFresh = true;
};

ap.stringify = function(){
	return JSON.stringify(ap.channels.channels);
};<|endoftext|>


<commit_before>Rickshaw.namespace('Rickshaw.Graph.Renderer.Bar');

Rickshaw.Graph.Renderer.Bar = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {

	name: 'bar',

	defaults: function($super) {

		var defaults = Rickshaw.extend( $super(), {
			gapSize: 0.05,
			unstack: false,
			opacity: 1.0
		} );

		delete defaults.tension;
		return defaults;
	},

	initialize: function($super, args) {
		args = args || {};
		this.gapSize = args.gapSize || this.gapSize;
		$super(args);
	},

	domain: function($super) {

		var domain = $super();

		var frequentInterval = this._frequentInterval(this.graph.stackedData.slice(-1).shift());
		domain.x[1] += Number(frequentInterval.magnitude);

		return domain;
	},

	barWidth: function(series) {

		var frequentInterval = this._frequentInterval(series.stack);
		var barWidth = this.graph.x.magnitude(frequentInterval.magnitude) * (1 - this.gapSize);

		return barWidth;
	},

	render: function(args) {

		args = args || {};

		var graph = this.graph;
		var series = args.series || graph.series;

		var vis = args.vis || graph.vis;
		vis.selectAll('*').remove();

		var barWidth = this.barWidth(series.active()[0]);
		var barXOffset = 0;

		var activeSeriesCount = series.filter( function(s) { return !s.disabled; } ).length;
		var seriesBarWidth = this.unstack ? barWidth / activeSeriesCount : barWidth;

		var transform = function(d) {
			// add a matrix transform for negative values
			var matrix = [ 1, 0, 0, (d.y < 0 ? -1 : 1), 0, (d.y < 0 ? graph.y.magnitude(Math.abs(d.y)) * 2 : 0) ];
			return "matrix(" + matrix.join(',') + ")";
		};

		series.forEach( function(series) {

			if (series.disabled) return;

			var barWidth = this.barWidth(series);

			var nodes = vis.selectAll("path")
				.data(series.stack.filter( function(d) { return d.y !== null } ))
				.enter().append("svg:rect")
				.attr("x", function(d) { return graph.x(d.x) + barXOffset })
				.attr("y", function(d) { return (graph.y(d.y0 + Math.abs(d.y))) * (d.y < 0 ? -1 : 1 ) })
				.attr("width", seriesBarWidth)
				.attr("height", function(d) { return graph.y.magnitude(Math.abs(d.y)) })
				.attr("opacity", series.opacity)
				.attr("transform", transform);

			Array.prototype.forEach.call(nodes[0], function(n) {
				n.setAttribute('fill', series.color);
			} );

			if (this.unstack) barXOffset += seriesBarWidth;

		}, this );
	},

	_frequentInterval: function(data) {

		var intervalCounts = {};

		for (var i = 0; i < data.length - 1; i++) {
			var interval = data[i + 1].x - data[i].x;
			intervalCounts[interval] = intervalCounts[interval] || 0;
			intervalCounts[interval]++;
		}

		var frequentInterval = { count: 0, magnitude: 1 };

		// Sorting object's keys returned to guarantee consistency when iterating over
		// Keys order in `for .. in` loop is not specified and browsers behave differently here
		// This results with different invterval value being calculated for different browsers
		// See last but one section here: http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4
		var keysSorted = Rickshaw.keys(intervalCounts).sort(function asc(a, b) { return Number(a) - Number(b); });
		keysSorted.forEach( function(i) {
			if (frequentInterval.count < intervalCounts[i]) {
				frequentInterval = {
					count: intervalCounts[i],
					magnitude: i
				};
			}
		} );

		return frequentInterval;
	}
} );

<commit_msg>docs: Fix typo (#630)<commit_after>Rickshaw.namespace('Rickshaw.Graph.Renderer.Bar');

Rickshaw.Graph.Renderer.Bar = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {

	name: 'bar',

	defaults: function($super) {

		var defaults = Rickshaw.extend( $super(), {
			gapSize: 0.05,
			unstack: false,
			opacity: 1.0
		} );

		delete defaults.tension;
		return defaults;
	},

	initialize: function($super, args) {
		args = args || {};
		this.gapSize = args.gapSize || this.gapSize;
		$super(args);
	},

	domain: function($super) {

		var domain = $super();

		var frequentInterval = this._frequentInterval(this.graph.stackedData.slice(-1).shift());
		domain.x[1] += Number(frequentInterval.magnitude);

		return domain;
	},

	barWidth: function(series) {

		var frequentInterval = this._frequentInterval(series.stack);
		var barWidth = this.graph.x.magnitude(frequentInterval.magnitude) * (1 - this.gapSize);

		return barWidth;
	},

	render: function(args) {

		args = args || {};

		var graph = this.graph;
		var series = args.series || graph.series;

		var vis = args.vis || graph.vis;
		vis.selectAll('*').remove();

		var barWidth = this.barWidth(series.active()[0]);
		var barXOffset = 0;

		var activeSeriesCount = series.filter( function(s) { return !s.disabled; } ).length;
		var seriesBarWidth = this.unstack ? barWidth / activeSeriesCount : barWidth;

		var transform = function(d) {
			// add a matrix transform for negative values
			var matrix = [ 1, 0, 0, (d.y < 0 ? -1 : 1), 0, (d.y < 0 ? graph.y.magnitude(Math.abs(d.y)) * 2 : 0) ];
			return "matrix(" + matrix.join(',') + ")";
		};

		series.forEach( function(series) {

			if (series.disabled) return;

			var barWidth = this.barWidth(series);

			var nodes = vis.selectAll("path")
				.data(series.stack.filter( function(d) { return d.y !== null } ))
				.enter().append("svg:rect")
				.attr("x", function(d) { return graph.x(d.x) + barXOffset })
				.attr("y", function(d) { return (graph.y(d.y0 + Math.abs(d.y))) * (d.y < 0 ? -1 : 1 ) })
				.attr("width", seriesBarWidth)
				.attr("height", function(d) { return graph.y.magnitude(Math.abs(d.y)) })
				.attr("opacity", series.opacity)
				.attr("transform", transform);

			Array.prototype.forEach.call(nodes[0], function(n) {
				n.setAttribute('fill', series.color);
			} );

			if (this.unstack) barXOffset += seriesBarWidth;

		}, this );
	},

	_frequentInterval: function(data) {

		var intervalCounts = {};

		for (var i = 0; i < data.length - 1; i++) {
			var interval = data[i + 1].x - data[i].x;
			intervalCounts[interval] = intervalCounts[interval] || 0;
			intervalCounts[interval]++;
		}

		var frequentInterval = { count: 0, magnitude: 1 };

		// Sorting object's keys returned to guarantee consistency when iterating over
		// Keys order in `for .. in` loop is not specified and browsers behave differently here
		// This results with different interval value being calculated for different browsers
		// See last but one section here: http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4
		var keysSorted = Rickshaw.keys(intervalCounts).sort(function asc(a, b) { return Number(a) - Number(b); });
		keysSorted.forEach( function(i) {
			if (frequentInterval.count < intervalCounts[i]) {
				frequentInterval = {
					count: intervalCounts[i],
					magnitude: i
				};
			}
		} );

		return frequentInterval;
	}
} );

<|endoftext|>


<commit_before>// REMOVE THIS LINE BEFORE EDITING THIS FILE
/* eslint-disable  */
import { FormattedMessage } from 'react-intl'
import PropTypes from 'prop-types'
import React from 'react'

/**
 * Returns a FormattedMessage component for date time preview strings such that i18n IDs
 * are hardcoded and can be kept track of by format.js CLI tools
 */
const FormattedDateTimePreview = ({
  departArrive,
  endTime,
  routingType,
  startTime,
  time
}) => {
  if (routingType === 'ITINERARY') {
    if (departArrive === 'NOW') {
      return <FormattedMessage id="components.DateTimePreview.leaveNow" />
    } else if (departArrive === 'ARRIVE') {
      return (
        <FormattedMessage
          id="components.DateTimePreview.arriveAt"
          values={{ arriveTime: time }}
        />
      )
    } else if (departArrive === 'DEPART') {
      return (
        <FormattedMessage
          id="components.DateTimePreview.departAt"
          values={{ departTime: time }}
        />
      )
    }
  } else if (routingType === 'PROFILE') {
    return (
      <FormattedMessage
        id="components.DateTimePreview.range"
        values={{ endTime, startTime }}
      />
    )
  }
}

FormattedDateTimePreview.propTypes = {
  departArrive: PropTypes.string.isRequired,
  routingType: PropTypes.string.isRequired
}

export default FormattedDateTimePreview
<commit_msg>fix(formatted-date-time-preview): don't crash on missing route mode<commit_after>// REMOVE THIS LINE BEFORE EDITING THIS FILE
/* eslint-disable  */
import { FormattedMessage } from 'react-intl'
import PropTypes from 'prop-types'
import React from 'react'

/**
 * Returns a FormattedMessage component for date time preview strings such that i18n IDs
 * are hardcoded and can be kept track of by format.js CLI tools
 */
const FormattedDateTimePreview = ({
  departArrive,
  endTime,
  routingType,
  startTime,
  time
}) => {
  if (routingType === 'ITINERARY') {
    if (departArrive === 'NOW') {
      return <FormattedMessage id="components.DateTimePreview.leaveNow" />
    } else if (departArrive === 'ARRIVE') {
      return (
        <FormattedMessage
          id="components.DateTimePreview.arriveAt"
          values={{ arriveTime: time }}
        />
      )
    } else if (departArrive === 'DEPART') {
      return (
        <FormattedMessage
          id="components.DateTimePreview.departAt"
          values={{ departTime: time }}
        />
      )
    }
  } else if (routingType === 'PROFILE') {
    return (
      <FormattedMessage
        id="components.DateTimePreview.range"
        values={{ endTime, startTime }}
      />
    )
  }
  return null
}

FormattedDateTimePreview.propTypes = {
  departArrive: PropTypes.string.isRequired,
  routingType: PropTypes.string.isRequired
}

export default FormattedDateTimePreview
<|endoftext|>