<commit_before>
'use strict';

/**
 * StyleSheets represents the StyleSheets found in the source code.
 * @constructor
 */
function StyleSheets() {
  this.styleSheets = {};
}

/**
 * Add adds a StyleSheet to our StyleSheets collections.
 *
 * @param {string} styleSheetName - The name of the StyleSheet.
 * @param {object} properties - The collection of rules in the styleSheet.
 */
StyleSheets.prototype.add = function (styleSheetName, properties) {
  this.styleSheets[styleSheetName] = properties;
};

/**
 * MarkAsUsed marks a rule as used in our source code by removing it from the
 * specified StyleSheet rules.
 *
 * @param {string} fullyQualifiedName - The fully qualified name of the rule.
 * for example 'styles.text'
 */
StyleSheets.prototype.markAsUsed = function (fullyQualifiedName) {
  const nameSplit = fullyQualifiedName.split('.');
  const styleSheetName = nameSplit[0];
  const styleSheetProperty = nameSplit[1];

  if (this.styleSheets[styleSheetName]) {
    this.styleSheets[styleSheetName] = this
        .styleSheets[styleSheetName]
        .filter(property => property.key.name !== styleSheetProperty);
  }
};

/**
 * GetUnusedReferences returns all collected StyleSheets and their
 * unmarked rules.
 */
StyleSheets.prototype.getUnusedReferences = function () {
  return this.styleSheets;
};

/**
 * AddColorLiterals adds an array of expressions that contain color literals
 * to the ColorLiterals collection
 * @param {array} expressions - an array of expressions containing color literals
 */
StyleSheets.prototype.addColorLiterals = function (expressions) {
  if (!this.colorLiterals) {
    this.colorLiterals = [];
  }
  this.colorLiterals = this.colorLiterals.concat(expressions);
};

/**
 * GetColorLiterals returns an array of collected color literals expressions
 * @returns {Array}
 */
StyleSheets.prototype.getColorLiterals = function () {
  return this.colorLiterals;
};

/**
 * AddObjectexpressions adds an array of expressions to the ObjectExpressions collection
 * @param {Array} expressions - an array of expressions containing ObjectExpressions in
 * inline styles
 */
StyleSheets.prototype.addObjectExpressions = function (expressions) {
  if (!this.objectExpressions) {
    this.objectExpressions = [];
  }
  this.objectExpressions = this.objectExpressions.concat(expressions);
};

/**
 * GetObjectExpressions returns an array of collected object expressiosn used in inline styles
 * @returns {Array}
 */
StyleSheets.prototype.getObjectExpressions = function () {
  return this.objectExpressions;
};

let currentContent;
const getSourceCode = node => currentContent
  .getSourceCode(node)
  .getText(node);

const astHelpers = {
  containsStyleSheetObject: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.object &&
      node.init.callee.object.name === 'StyleSheet'
    );
  },

  containsCreateCall: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.property &&
      node.init.callee.property.name === 'create'
    );
  },

  isStyleSheetDeclaration: function (node) {
    return Boolean(
      astHelpers.containsStyleSheetObject(node) &&
      astHelpers.containsCreateCall(node)
    );
  },

  getStyleSheetName: function (node) {
    if (
      node &&
      node.id
    ) {
      return node.id.name;
    }
  },

  getStyleDeclarations: function (node) {
    if (
      node &&
      node.init &&
      node.init.arguments &&
      node.init.arguments[0] &&
      node.init.arguments[0].properties
    ) {
      return node
        .init
        .arguments[0]
        .properties;
    }

    return [];
  },

  isStyleAttribute: function (node) {
    return Boolean(
      node.type === 'JSXAttribute' &&
      node.name &&
      node.name.name &&
      node.name.name.toLowerCase().includes('style')
    );
  },

  collectStyleObjectExpressions: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectStyleObjectExpressionFromContainers(
          styleReferenceContainers
      );
    }

    return astHelpers.getStyleObjectExpressionFromNode(node.expression);
  },

  collectColorLiterals: function (node, context) {
    if (!node) {
      return [];
    }

    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectColorLiteralsFromContainers(
          styleReferenceContainers
      );
    }

    if (node.type === 'ObjectExpression') {
      return astHelpers.getColorLiteralsFromNode(node);
    }

    return astHelpers.getColorLiteralsFromNode(node.expression);
  },

  collectStyleObjectExpressionFromContainers: function (nodes) {
    let objectExpressions = [];
    nodes.forEach((node) => {
      objectExpressions = objectExpressions
          .concat(astHelpers.getStyleObjectExpressionFromNode(node));
    });

    return objectExpressions;
  },

  collectColorLiteralsFromContainers: function (nodes) {
    let colorLiterals = [];
    nodes.forEach((node) => {
      colorLiterals = colorLiterals
          .concat(astHelpers.getColorLiteralsFromNode(node));
    });

    return colorLiterals;
  },

  getStyleReferenceFromNode: function (node) {
    let styleReference;
    let leftStyleReferences;
    let rightStyleReferences;

    if (!node) {
      return [];
    }

    switch (node.type) {
      case 'MemberExpression':
        styleReference = astHelpers.getStyleReferenceFromExpression(node);
        return [styleReference];
      case 'LogicalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.left);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.right);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      case 'ConditionalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.consequent);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.alternate);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      default:
        return [];
    }
  },

  getStyleObjectExpressionFromNode: function (node) {
    let leftStyleObjectExpression;
    let rightStyleObjectExpression;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getStyleObjectFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.left);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.right);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      case 'ConditionalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.consequent);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.alternate);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      default:
        return [];
    }
  },

  getColorLiteralsFromNode: function (node) {
    let leftColorLiterals;
    let rightColorLiterals;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getColorLiteralsFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.left);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.right);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      case 'ConditionalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.consequent);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.alternate);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      default:
        return [];
    }
  },

  hasArrayOfStyleReferences: function (node) {
    return node && Boolean(
      node.type === 'JSXExpressionContainer' &&
      node.expression &&
      node.expression.type === 'ArrayExpression'
    );
  },

  getStyleReferenceFromExpression: function (node) {
    const result = [];
    const name = astHelpers.getObjectName(node);
    if (name) {
      result.push(name);
    }

    const property = astHelpers.getPropertyName(node);
    if (property) {
      result.push(property);
    }

    return result.join('.');
  },

  getStyleObjectFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach((p) => {
        if (!p.value || !p.key) {
          return;
        }
        if (p.value.type === 'Literal') {
          invalid = true;
          obj[p.key.name] = p.value.value;
        } else if (p.value.type === 'ConditionalExpression') {
          const innerNode = p.value;
          if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = getSourceCode(innerNode);
          }
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '-') {
          invalid = true;
          obj[p.key.name] = -1 * p.value.argument.value;
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '+') {
          invalid = true;
          obj[p.key.name] = p.value.argument.value;
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getColorLiteralsFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach((p) => {
        if (p.key && p.key.name && p.key.name.toLowerCase().indexOf('color') !== -1) {
          if (p.value.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = p.value.value;
          } else if (p.value.type === 'ConditionalExpression') {
            const innerNode = p.value;
            if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
              invalid = true;
              obj[p.key.name] = getSourceCode(innerNode);
            }
          }
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getObjectName: function (node) {
    if (
      node &&
      node.object &&
      node.object.name
    ) {
      return node.object.name;
    }
  },

  getPropertyName: function (node) {
    if (
      node &&
      node.property &&
      node.property.name
    ) {
      return node.property.name;
    }
  },

  getPotentialStyleReferenceFromMemberExpression: function (node) {
    if (
      node &&
      node.object &&
      node.object.type === 'Identifier' &&
      node.object.name &&
      node.property &&
      node.property.type === 'Identifier' &&
      node.property.name &&
      node.parent.type !== 'MemberExpression'
    ) {
      return [node.object.name, node.property.name].join('.');
    }
  },
};

module.exports.astHelpers = astHelpers;
module.exports.StyleSheets = StyleSheets;
<commit_msg>Fix #109, prevent crash when node is undefined<commit_after>
'use strict';

/**
 * StyleSheets represents the StyleSheets found in the source code.
 * @constructor
 */
function StyleSheets() {
  this.styleSheets = {};
}

/**
 * Add adds a StyleSheet to our StyleSheets collections.
 *
 * @param {string} styleSheetName - The name of the StyleSheet.
 * @param {object} properties - The collection of rules in the styleSheet.
 */
StyleSheets.prototype.add = function (styleSheetName, properties) {
  this.styleSheets[styleSheetName] = properties;
};

/**
 * MarkAsUsed marks a rule as used in our source code by removing it from the
 * specified StyleSheet rules.
 *
 * @param {string} fullyQualifiedName - The fully qualified name of the rule.
 * for example 'styles.text'
 */
StyleSheets.prototype.markAsUsed = function (fullyQualifiedName) {
  const nameSplit = fullyQualifiedName.split('.');
  const styleSheetName = nameSplit[0];
  const styleSheetProperty = nameSplit[1];

  if (this.styleSheets[styleSheetName]) {
    this.styleSheets[styleSheetName] = this
        .styleSheets[styleSheetName]
        .filter(property => property.key.name !== styleSheetProperty);
  }
};

/**
 * GetUnusedReferences returns all collected StyleSheets and their
 * unmarked rules.
 */
StyleSheets.prototype.getUnusedReferences = function () {
  return this.styleSheets;
};

/**
 * AddColorLiterals adds an array of expressions that contain color literals
 * to the ColorLiterals collection
 * @param {array} expressions - an array of expressions containing color literals
 */
StyleSheets.prototype.addColorLiterals = function (expressions) {
  if (!this.colorLiterals) {
    this.colorLiterals = [];
  }
  this.colorLiterals = this.colorLiterals.concat(expressions);
};

/**
 * GetColorLiterals returns an array of collected color literals expressions
 * @returns {Array}
 */
StyleSheets.prototype.getColorLiterals = function () {
  return this.colorLiterals;
};

/**
 * AddObjectexpressions adds an array of expressions to the ObjectExpressions collection
 * @param {Array} expressions - an array of expressions containing ObjectExpressions in
 * inline styles
 */
StyleSheets.prototype.addObjectExpressions = function (expressions) {
  if (!this.objectExpressions) {
    this.objectExpressions = [];
  }
  this.objectExpressions = this.objectExpressions.concat(expressions);
};

/**
 * GetObjectExpressions returns an array of collected object expressiosn used in inline styles
 * @returns {Array}
 */
StyleSheets.prototype.getObjectExpressions = function () {
  return this.objectExpressions;
};

let currentContent;
const getSourceCode = node => currentContent
  .getSourceCode(node)
  .getText(node);

const astHelpers = {
  containsStyleSheetObject: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.object &&
      node.init.callee.object.name === 'StyleSheet'
    );
  },

  containsCreateCall: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.property &&
      node.init.callee.property.name === 'create'
    );
  },

  isStyleSheetDeclaration: function (node) {
    return Boolean(
      astHelpers.containsStyleSheetObject(node) &&
      astHelpers.containsCreateCall(node)
    );
  },

  getStyleSheetName: function (node) {
    if (
      node &&
      node.id
    ) {
      return node.id.name;
    }
  },

  getStyleDeclarations: function (node) {
    if (
      node &&
      node.init &&
      node.init.arguments &&
      node.init.arguments[0] &&
      node.init.arguments[0].properties
    ) {
      return node
        .init
        .arguments[0]
        .properties;
    }

    return [];
  },

  isStyleAttribute: function (node) {
    return Boolean(
      node.type === 'JSXAttribute' &&
      node.name &&
      node.name.name &&
      node.name.name.toLowerCase().includes('style')
    );
  },

  collectStyleObjectExpressions: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectStyleObjectExpressionFromContainers(
          styleReferenceContainers
      );
    } else if (node && node.expression) {
      return astHelpers.getStyleObjectExpressionFromNode(node.expression);
    }

    return [];
  },

  collectColorLiterals: function (node, context) {
    if (!node) {
      return [];
    }

    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectColorLiteralsFromContainers(
          styleReferenceContainers
      );
    }

    if (node.type === 'ObjectExpression') {
      return astHelpers.getColorLiteralsFromNode(node);
    }

    return astHelpers.getColorLiteralsFromNode(node.expression);
  },

  collectStyleObjectExpressionFromContainers: function (nodes) {
    let objectExpressions = [];
    nodes.forEach((node) => {
      objectExpressions = objectExpressions
          .concat(astHelpers.getStyleObjectExpressionFromNode(node));
    });

    return objectExpressions;
  },

  collectColorLiteralsFromContainers: function (nodes) {
    let colorLiterals = [];
    nodes.forEach((node) => {
      colorLiterals = colorLiterals
          .concat(astHelpers.getColorLiteralsFromNode(node));
    });

    return colorLiterals;
  },

  getStyleReferenceFromNode: function (node) {
    let styleReference;
    let leftStyleReferences;
    let rightStyleReferences;

    if (!node) {
      return [];
    }

    switch (node.type) {
      case 'MemberExpression':
        styleReference = astHelpers.getStyleReferenceFromExpression(node);
        return [styleReference];
      case 'LogicalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.left);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.right);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      case 'ConditionalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.consequent);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.alternate);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      default:
        return [];
    }
  },

  getStyleObjectExpressionFromNode: function (node) {
    let leftStyleObjectExpression;
    let rightStyleObjectExpression;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getStyleObjectFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.left);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.right);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      case 'ConditionalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.consequent);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.alternate);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      default:
        return [];
    }
  },

  getColorLiteralsFromNode: function (node) {
    let leftColorLiterals;
    let rightColorLiterals;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getColorLiteralsFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.left);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.right);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      case 'ConditionalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.consequent);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.alternate);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      default:
        return [];
    }
  },

  hasArrayOfStyleReferences: function (node) {
    return node && Boolean(
      node.type === 'JSXExpressionContainer' &&
      node.expression &&
      node.expression.type === 'ArrayExpression'
    );
  },

  getStyleReferenceFromExpression: function (node) {
    const result = [];
    const name = astHelpers.getObjectName(node);
    if (name) {
      result.push(name);
    }

    const property = astHelpers.getPropertyName(node);
    if (property) {
      result.push(property);
    }

    return result.join('.');
  },

  getStyleObjectFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach((p) => {
        if (!p.value || !p.key) {
          return;
        }
        if (p.value.type === 'Literal') {
          invalid = true;
          obj[p.key.name] = p.value.value;
        } else if (p.value.type === 'ConditionalExpression') {
          const innerNode = p.value;
          if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = getSourceCode(innerNode);
          }
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '-') {
          invalid = true;
          obj[p.key.name] = -1 * p.value.argument.value;
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '+') {
          invalid = true;
          obj[p.key.name] = p.value.argument.value;
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getColorLiteralsFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach((p) => {
        if (p.key && p.key.name && p.key.name.toLowerCase().indexOf('color') !== -1) {
          if (p.value.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = p.value.value;
          } else if (p.value.type === 'ConditionalExpression') {
            const innerNode = p.value;
            if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
              invalid = true;
              obj[p.key.name] = getSourceCode(innerNode);
            }
          }
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getObjectName: function (node) {
    if (
      node &&
      node.object &&
      node.object.name
    ) {
      return node.object.name;
    }
  },

  getPropertyName: function (node) {
    if (
      node &&
      node.property &&
      node.property.name
    ) {
      return node.property.name;
    }
  },

  getPotentialStyleReferenceFromMemberExpression: function (node) {
    if (
      node &&
      node.object &&
      node.object.type === 'Identifier' &&
      node.object.name &&
      node.property &&
      node.property.type === 'Identifier' &&
      node.property.name &&
      node.parent.type !== 'MemberExpression'
    ) {
      return [node.object.name, node.property.name].join('.');
    }
  },
};

module.exports.astHelpers = astHelpers;
module.exports.StyleSheets = StyleSheets;
<|endoftext|>


<commit_before>import Graph from '../views/Graph';

class Histogram extends Graph {
    constructor(options) {
        super(options);
        this.color = options.color;
    }

    draw() {
        var bars = this.d3Svg.selectAll('rect.bar')
                        .data(this.dataSeries.data);

        bars.enter().append('rect')
            .attr('class', 'bar')
            .attr('fill', this.color);

        bars.call(this._applyInserts.bind(this));

        bars.attr('y', d => this.yRange(d.y))
            .attr('x', d => this.xRange(d.x_low))
            .attr('width', d => this.xRange(d.x_high) - this.xRange(d.x_low))
            .attr('height', d => {
                var yMin = this.yRange.domain()[0];
                return this.yRange(yMin) - this.yRange(d.y);
            });

        bars.exit().remove();
    }
}

export default Histogram;
<commit_msg>Make a 0 return<commit_after>import Graph from '../views/Graph';

class Histogram extends Graph {
    constructor(options) {
        super(options);
        this.color = options.color;
    }

    draw() {
        var bars = this.d3Svg.selectAll('rect.bar')
                        .data(this.dataSeries.data);

        bars.enter().append('rect')
            .attr('class', 'bar')
            .attr('fill', this.color);

        bars.call(this._applyInserts.bind(this));

        bars.attr('y', d => this.yRange(d.y))
            .attr('x', d => this.xRange(d.x_low))
            .attr('width', d => this.xRange(d.x_high) - this.xRange(d.x_low))
            .attr('height', d => {
                var yMin = Math.max(this.yRange.domain()[0], 0);
                var height =  this.yRange(yMin) - this.yRange(d.y);
                return Math.max(height, 0);
            });

        bars.exit().remove();
    }
}

export default Histogram;
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
/* global define, Mousetrap, Handlebars  */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading options.ui.js ...');
  var TSCORE = require('tscore');
  require(['libs/filesaver.js/FileSaver.js'], function() {});

  function generateSelectOptions(parent, data, selectedId, helpI18NString) {
    parent.empty();
    if (!helpI18NString) {
      helpI18NString = "";
    }
    parent.append($('<option>')
      .text('')
      .attr("data-i18n", helpI18NString)
      .val('false'));
    data.forEach(function(value) {
      if (selectedId === value) {
        parent.append($('<option>').attr('selected', 'selected').text(value).val(value));
      } else {
        parent.append($('<option>').text(value).val(value));
      }
    });
  }

  function addPerspective(parent, perspectiveId) {
    var perspectiveControl = $('
')
      .append($('
')
        .append($('<select class="form-control flexMaxWidth"></select>'))
        .append($('<button class="btn btn-link" style="width: 40px" data-i18n="[title]ns.dialogs:removePerspectiveTooltip"></button>')
          .click(function() {
            var row4Remove = $(this).parent().parent();
            TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this perspective?", function() {
              row4Remove.remove();
            });
          })));
    generateSelectOptions(perspectiveControl.find('select'), TSCORE.Config.getPerspectiveExtensions(), perspectiveId, "ns.dialogs:choosePerspective");
    perspectiveControl.i18n();
    parent.append(perspectiveControl);
  }

  function addFileType(parent, fileext, viewerId, editorId) {
    var fileTypeControl = $('
')
      .append($('
')
        .append($('<input style="width: 80px" type="text" class="form-control" data-i18n="[placeholder]ns.dialogs:fileExtensionPlaceholder">').val(fileext))
        .append($('<select class="ftviewer form-control flexMaxWidth"></select>'))
        .append($('<select class="fteditor form-control flexMaxWidth"></select>'))
        .append($('<button style="width: 30px" class="btn btn-link" data-i18n="[title]ns.dialogs:removeFileTypeTooltip"></button>')
        .click(function() {
          var row4Remove = $(this).parent().parent();
          TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this file type?", function() {
            row4Remove.remove();
          });
        })));
    generateSelectOptions(fileTypeControl.find('.ftviewer'), TSCORE.Config.getViewerExtensions(), viewerId, "ns.dialogs:chooseFileViewer");
    generateSelectOptions(fileTypeControl.find('.fteditor'), TSCORE.Config.getEditorExtensions(), editorId, "ns.dialogs:chooseFileEditor");
    fileTypeControl.i18n();
    parent.prepend(fileTypeControl);
  }

  function enableMetaData() {
    if (!TSCORE.PRO) {
      return;
    }
    var isMetaEnabled = $('#enableMetaData').is(':checked');
    if (!isMetaEnabled) {
      $('#writeMetaToSidecarFile').attr('checked', false);
      TSCORE.Config.setWriteMetaToSidecarFile(false);
    }
    $('#writeMetaToSidecarFile').attr('disabled', !isMetaEnabled);
  }

  function initUI() {
    $('#addFileTypeButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addFileType($('#fileTypesList'), '', '', '');
      //$('#fileTypesList').parent().animate({ scrollTop: ($('#fileTypesList').height()) }, 'slow');
    });
    $('#addPerspectiveButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addPerspective($('#perspectiveList'), '');
    });
    $('#saveSettingsButton').click(function() {
      updateSettings();
      $('#dialogOptions').modal('hide');
    });
    $('#saveSettingsRestartButton').click(function() {
      updateSettings();
      TSCORE.reloadUI();
    });
    $('#defaultSettingsButton').click(function() {
      TSCORE.showConfirmDialog(
          $.i18n.t('ns.dialogs:restoreDefaulSettingTitleConfirm'),
          $.i18n.t('ns.dialogs:restoreDefaulSettingMessageConfirm'), function() {
        TSCORE.Config.loadDefaultSettings();
      });
    });
    $('#keyBindingInstructions').toggle();
    $('#keyBindingInstructionsToggle').on('click', function() {
      $('#keyBindingInstructions').toggle();
      return false;
    });
    if (isCordova) {
      $('#exportTagGroupsButton').hide();
      $('#showMainMenuCheckbox').parent().hide();
    }
    $('#exportTagGroupsButton').click(function() {
      var jsonFormat = '{ "appName": "' + TSCORE.Config.DefaultSettings.appName +
        '", "appVersion": "' + TSCORE.Config.DefaultSettings.appVersion +
        '", "appBuild": "' + TSCORE.Config.DefaultSettings.appBuild +
        '", "settingsVersion": ' + TSCORE.Config.DefaultSettings.settingsVersion +
        ', "tagGroups": ';
      var blob = new Blob([jsonFormat + JSON.stringify(TSCORE.Config.getAllTagGroupData()) + '}'], {
        type: 'application/json'
      });
      saveAs(blob, 'tsm[' + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + '].json');
      console.log('Group Data Saved...');
    });

    $('#enableMetaData').change(function() {
      enableMetaData();
    });
  }

  function reInitUI() {
    $('#extensionsPathInput').val(TSCORE.Config.getExtensionPath());
    $('#showHiddenFilesCheckbox').attr('checked', TSCORE.Config.getShowUnixHiddenEntries());
    $('#showMainMenuCheckbox').attr('checked', TSCORE.Config.getShowMainMenu());
    $('#checkforUpdatesCheckbox').attr('checked', TSCORE.Config.getCheckForUpdates());
    $('#calculateTagsCheckbox').attr('checked', TSCORE.Config.getCalculateTags());
    $('#loadLocationMetaData').attr('checked', TSCORE.Config.getLoadLocationMeta());
    $('#tagsDelimiterInput').val(TSCORE.Config.getTagDelimiter());
    $('#prefixTagContainerInput').val(TSCORE.Config.getPrefixTagContainer());
    $('#nextDocumentKeyBinding').val(TSCORE.Config.getNextDocumentKeyBinding());
    $('#prevDocumentKeyBinding').val(TSCORE.Config.getPrevDocumentKeyBinding());
    $('#closeDocumentKeyBinding').val(TSCORE.Config.getCloseViewerKeyBinding());
    $('#addRemoveTagsKeyBinding').val(TSCORE.Config.getAddRemoveTagsKeyBinding());
    $('#editDocumentKeyBinding').val(TSCORE.Config.getEditDocumentKeyBinding());
    $('#reloadDocumentKeyBinding').val(TSCORE.Config.getReloadDocumentKeyBinding());
    $('#saveDocumentKeyBinding').val(TSCORE.Config.getSaveDocumentKeyBinding());
    $('#documentPropertiesKeyBinding').val(TSCORE.Config.getPropertiesDocumentKeyBinding());
    $('#showSearchKeyBinding').val(TSCORE.Config.getSearchKeyBinding());
    $('#perspectiveList').empty();
    $('#writeMetaToSidecarFile').attr('checked', TSCORE.Config.getWriteMetaToSidecarFile());
    $('#useDefaultLocationCheckbox').attr('checked', TSCORE.Config.getUseDefaultLocation());
    $('#selectAllKeyBinding').val(TSCORE.Config.getSelectAllKeyBinding());
    $('#enableMetaData').attr('checked', TSCORE.Config.getEnableMetaData());
    enableMetaData();
    TSCORE.Config.getPerspectives().forEach(function(value) {
      addPerspective($('#perspectiveList'), value.id);
    });
    var $languagesDropdown = $('#languagesList');
    $languagesDropdown.empty();
    TSCORE.Config.getSupportedLanguages().forEach(function(value) {
      if (TSCORE.Config.getInterfaceLangauge() === value.iso) {
        $languagesDropdown.append($('<option>').attr('selected', 'selected').text(value.title).val(value.iso));
      } else {
        $languagesDropdown.append($('<option>').text(value.title).val(value.iso));
      }
    });
    $('#fileTypesList').empty();

    TSCORE.Config.getSupportedFileTypes().sort(function(a, b) {
      if (a.type > b.type) {
        return -1;
      }
      if (a.type = 0) {
      keybinding = keybinding.split(',');
    }
    return keybinding;
  }

  function updateSettings() {
    TSCORE.Config.setExtensionPath($('#extensionsPathInput').val());
    TSCORE.Config.setShowUnixHiddenEntries($('#showHiddenFilesCheckbox').is(':checked'));
    TSCORE.Config.setShowMainMenu($('#showMainMenuCheckbox').is(':checked'));
    TSCORE.Config.setCheckForUpdates($('#checkforUpdatesCheckbox').is(':checked'));
    TSCORE.Config.setCalculateTags($('#calculateTagsCheckbox').is(':checked'));
    TSCORE.Config.setTagDelimiter($('#tagsDelimiterInput').val());
    TSCORE.Config.setPrefixTagContainer($('#prefixTagContainerInput').val());
    TSCORE.Config.setLoadLocationMeta($('#loadLocationMetaData').is(':checked'));
    TSCORE.Config.setNextDocumentKeyBinding(parseKeyBinding($('#nextDocumentKeyBinding').val()));
    TSCORE.Config.setPrevDocumentKeyBinding(parseKeyBinding($('#prevDocumentKeyBinding').val()));
    TSCORE.Config.setCloseViewerKeyBinding(parseKeyBinding($('#closeDocumentKeyBinding').val()));
    TSCORE.Config.setAddRemoveTagsKeyBinding(parseKeyBinding($('#addRemoveTagsKeyBinding').val()));
    TSCORE.Config.setEditDocumentKeyBinding(parseKeyBinding($('#editDocumentKeyBinding').val()));
    TSCORE.Config.setReloadDocumentKeyBinding(parseKeyBinding($('#reloadDocumentKeyBinding').val()));
    TSCORE.Config.setSaveDocumentKeyBinding(parseKeyBinding($('#saveDocumentKeyBinding').val()));
    TSCORE.Config.setPropertiesDocumentKeyBinding(parseKeyBinding($('#documentPropertiesKeyBinding').val()));
    TSCORE.Config.setSearchKeyBinding(parseKeyBinding($('#showSearchKeyBinding').val()));
    TSCORE.Config.setSelectAllKeyBinding(parseKeyBinding($('#selectAllKeyBinding').val()));
    TSCORE.Config.setEnableMetaData($('#enableMetaData').is(':checked'));
    var interfaceLang = $('#languagesList').val();
    TSCORE.Config.setInterfaceLangauge(interfaceLang);
    TSCORE.switchInterfaceLanguage(interfaceLang);
    TSCORE.Config.setPerspectives(collectPerspectivesData());
    TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());
    TSCORE.Config.setWriteMetaToSidecarFile($('#writeMetaToSidecarFile').is(':checked'));
    TSCORE.Config.setUseDefaultLocation($('#useDefaultLocationCheckbox').is(':checked'));
    TSCORE.Config.saveSettings();
  }

  function collectPerspectivesData() {
    var data = [];
    $('#perspectiveList').children().each(function(index, element) {
      if ($(element).find('select').val() != 'false') {
        data.push({
          'id': $(element).find('select').val()
        });
      }
    });
    return data;
  }

  function collectSupportedFileTypesData() {
    var data = [];
    $('#fileTypesList').children().each(function(index, element) {
      data.push({
        'type': $(element).find('input').val(),
        'viewer': $(element).find('.ftviewer').val(),
        'editor': $(element).find('.fteditor').val()
      });
    });
    return data;
  }

  // Public Methods
  exports.initUI = initUI;
  exports.reInitUI = reInitUI;
});
<commit_msg>save trash settings<commit_after>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
/* global define, Mousetrap, Handlebars  */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading options.ui.js ...');
  var TSCORE = require('tscore');
  require(['libs/filesaver.js/FileSaver.js'], function() {});

  function generateSelectOptions(parent, data, selectedId, helpI18NString) {
    parent.empty();
    if (!helpI18NString) {
      helpI18NString = "";
    }
    parent.append($('<option>')
      .text('')
      .attr("data-i18n", helpI18NString)
      .val('false'));
    data.forEach(function(value) {
      if (selectedId === value) {
        parent.append($('<option>').attr('selected', 'selected').text(value).val(value));
      } else {
        parent.append($('<option>').text(value).val(value));
      }
    });
  }

  function addPerspective(parent, perspectiveId) {
    var perspectiveControl = $('
')
      .append($('
')
        .append($('<select class="form-control flexMaxWidth"></select>'))
        .append($('<button class="btn btn-link" style="width: 40px" data-i18n="[title]ns.dialogs:removePerspectiveTooltip"></button>')
          .click(function() {
            var row4Remove = $(this).parent().parent();
            TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this perspective?", function() {
              row4Remove.remove();
            });
          })));
    generateSelectOptions(perspectiveControl.find('select'), TSCORE.Config.getPerspectiveExtensions(), perspectiveId, "ns.dialogs:choosePerspective");
    perspectiveControl.i18n();
    parent.append(perspectiveControl);
  }

  function addFileType(parent, fileext, viewerId, editorId) {
    var fileTypeControl = $('
')
      .append($('
')
        .append($('<input style="width: 80px" type="text" class="form-control" data-i18n="[placeholder]ns.dialogs:fileExtensionPlaceholder">').val(fileext))
        .append($('<select class="ftviewer form-control flexMaxWidth"></select>'))
        .append($('<select class="fteditor form-control flexMaxWidth"></select>'))
        .append($('<button style="width: 30px" class="btn btn-link" data-i18n="[title]ns.dialogs:removeFileTypeTooltip"></button>')
        .click(function() {
          var row4Remove = $(this).parent().parent();
          TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this file type?", function() {
            row4Remove.remove();
          });
        })));
    generateSelectOptions(fileTypeControl.find('.ftviewer'), TSCORE.Config.getViewerExtensions(), viewerId, "ns.dialogs:chooseFileViewer");
    generateSelectOptions(fileTypeControl.find('.fteditor'), TSCORE.Config.getEditorExtensions(), editorId, "ns.dialogs:chooseFileEditor");
    fileTypeControl.i18n();
    parent.prepend(fileTypeControl);
  }

  function enableMetaData() {
    if (!TSCORE.PRO) {
      return;
    }
    var isMetaEnabled = $('#enableMetaData').is(':checked');
    if (!isMetaEnabled) {
      $('#writeMetaToSidecarFile').attr('checked', false);
      TSCORE.Config.setWriteMetaToSidecarFile(false);
    }
    $('#writeMetaToSidecarFile').attr('disabled', !isMetaEnabled);
  }

  function initUI() {
    $('#addFileTypeButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addFileType($('#fileTypesList'), '', '', '');
      //$('#fileTypesList').parent().animate({ scrollTop: ($('#fileTypesList').height()) }, 'slow');
    });
    $('#addPerspectiveButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addPerspective($('#perspectiveList'), '');
    });
    $('#saveSettingsButton').click(function() {
      updateSettings();
      $('#dialogOptions').modal('hide');
    });
    $('#saveSettingsRestartButton').click(function() {
      updateSettings();
      TSCORE.reloadUI();
    });
    $('#defaultSettingsButton').click(function() {
      TSCORE.showConfirmDialog(
          $.i18n.t('ns.dialogs:restoreDefaulSettingTitleConfirm'),
          $.i18n.t('ns.dialogs:restoreDefaulSettingMessageConfirm'), function() {
        TSCORE.Config.loadDefaultSettings();
      });
    });
    $('#keyBindingInstructions').toggle();
    $('#keyBindingInstructionsToggle').on('click', function() {
      $('#keyBindingInstructions').toggle();
      return false;
    });
    if (isCordova) {
      $('#exportTagGroupsButton').hide();
      $('#showMainMenuCheckbox').parent().hide();
    }
    $('#exportTagGroupsButton').click(function() {
      var jsonFormat = '{ "appName": "' + TSCORE.Config.DefaultSettings.appName +
        '", "appVersion": "' + TSCORE.Config.DefaultSettings.appVersion +
        '", "appBuild": "' + TSCORE.Config.DefaultSettings.appBuild +
        '", "settingsVersion": ' + TSCORE.Config.DefaultSettings.settingsVersion +
        ', "tagGroups": ';
      var blob = new Blob([jsonFormat + JSON.stringify(TSCORE.Config.getAllTagGroupData()) + '}'], {
        type: 'application/json'
      });
      saveAs(blob, 'tsm[' + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + '].json');
      console.log('Group Data Saved...');
    });

    $('#enableMetaData').change(function() {
      enableMetaData();
    });
  }

  function reInitUI() {
    $('#extensionsPathInput').val(TSCORE.Config.getExtensionPath());
    $('#showHiddenFilesCheckbox').attr('checked', TSCORE.Config.getShowUnixHiddenEntries());
    $('#showMainMenuCheckbox').attr('checked', TSCORE.Config.getShowMainMenu());
    $('#checkforUpdatesCheckbox').attr('checked', TSCORE.Config.getCheckForUpdates());
    $('#calculateTagsCheckbox').attr('checked', TSCORE.Config.getCalculateTags());
    $('#loadLocationMetaData').attr('checked', TSCORE.Config.getLoadLocationMeta());
    $('#tagsDelimiterInput').val(TSCORE.Config.getTagDelimiter());
    $('#prefixTagContainerInput').val(TSCORE.Config.getPrefixTagContainer());
    $('#nextDocumentKeyBinding').val(TSCORE.Config.getNextDocumentKeyBinding());
    $('#prevDocumentKeyBinding').val(TSCORE.Config.getPrevDocumentKeyBinding());
    $('#closeDocumentKeyBinding').val(TSCORE.Config.getCloseViewerKeyBinding());
    $('#addRemoveTagsKeyBinding').val(TSCORE.Config.getAddRemoveTagsKeyBinding());
    $('#editDocumentKeyBinding').val(TSCORE.Config.getEditDocumentKeyBinding());
    $('#reloadDocumentKeyBinding').val(TSCORE.Config.getReloadDocumentKeyBinding());
    $('#saveDocumentKeyBinding').val(TSCORE.Config.getSaveDocumentKeyBinding());
    $('#documentPropertiesKeyBinding').val(TSCORE.Config.getPropertiesDocumentKeyBinding());
    $('#showSearchKeyBinding').val(TSCORE.Config.getSearchKeyBinding());
    $('#perspectiveList').empty();
    $('#writeMetaToSidecarFile').attr('checked', TSCORE.Config.getWriteMetaToSidecarFile());
    $('#useDefaultLocationCheckbox').attr('checked', TSCORE.Config.getUseDefaultLocation());
    $('#selectAllKeyBinding').val(TSCORE.Config.getSelectAllKeyBinding());
    if (TSCORE.PRO) {
      $('#enableMetaData').attr('checked', TSCORE.Config.getEnableMetaData());
      $('#useTrashCan').attr('checked', TSCORE.Config.getUseTrashCan());
      enableMetaData();
    }
    TSCORE.Config.getPerspectives().forEach(function(value) {
      addPerspective($('#perspectiveList'), value.id);
    });
    var $languagesDropdown = $('#languagesList');
    $languagesDropdown.empty();
    TSCORE.Config.getSupportedLanguages().forEach(function(value) {
      if (TSCORE.Config.getInterfaceLangauge() === value.iso) {
        $languagesDropdown.append($('<option>').attr('selected', 'selected').text(value.title).val(value.iso));
      } else {
        $languagesDropdown.append($('<option>').text(value.title).val(value.iso));
      }
    });
    $('#fileTypesList').empty();

    TSCORE.Config.getSupportedFileTypes().sort(function(a, b) {
      if (a.type > b.type) {
        return -1;
      }
      if (a.type = 0) {
      keybinding = keybinding.split(',');
    }
    return keybinding;
  }

  function updateSettings() {
    TSCORE.Config.setExtensionPath($('#extensionsPathInput').val());
    TSCORE.Config.setShowUnixHiddenEntries($('#showHiddenFilesCheckbox').is(':checked'));
    TSCORE.Config.setShowMainMenu($('#showMainMenuCheckbox').is(':checked'));
    TSCORE.Config.setCheckForUpdates($('#checkforUpdatesCheckbox').is(':checked'));
    TSCORE.Config.setCalculateTags($('#calculateTagsCheckbox').is(':checked'));
    TSCORE.Config.setTagDelimiter($('#tagsDelimiterInput').val());
    TSCORE.Config.setPrefixTagContainer($('#prefixTagContainerInput').val());
    TSCORE.Config.setLoadLocationMeta($('#loadLocationMetaData').is(':checked'));
    TSCORE.Config.setNextDocumentKeyBinding(parseKeyBinding($('#nextDocumentKeyBinding').val()));
    TSCORE.Config.setPrevDocumentKeyBinding(parseKeyBinding($('#prevDocumentKeyBinding').val()));
    TSCORE.Config.setCloseViewerKeyBinding(parseKeyBinding($('#closeDocumentKeyBinding').val()));
    TSCORE.Config.setAddRemoveTagsKeyBinding(parseKeyBinding($('#addRemoveTagsKeyBinding').val()));
    TSCORE.Config.setEditDocumentKeyBinding(parseKeyBinding($('#editDocumentKeyBinding').val()));
    TSCORE.Config.setReloadDocumentKeyBinding(parseKeyBinding($('#reloadDocumentKeyBinding').val()));
    TSCORE.Config.setSaveDocumentKeyBinding(parseKeyBinding($('#saveDocumentKeyBinding').val()));
    TSCORE.Config.setPropertiesDocumentKeyBinding(parseKeyBinding($('#documentPropertiesKeyBinding').val()));
    TSCORE.Config.setSearchKeyBinding(parseKeyBinding($('#showSearchKeyBinding').val()));
    TSCORE.Config.setSelectAllKeyBinding(parseKeyBinding($('#selectAllKeyBinding').val()));
    if (TSCORE.PRO) {
      TSCORE.Config.setEnableMetaData($('#enableMetaData').is(':checked'));
      TSCORE.Config.setUseTrashCan($('#useTrashCan').is(':checked'));
    }
    var interfaceLang = $('#languagesList').val();
    TSCORE.Config.setInterfaceLangauge(interfaceLang);
    TSCORE.switchInterfaceLanguage(interfaceLang);
    TSCORE.Config.setPerspectives(collectPerspectivesData());
    TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());
    TSCORE.Config.setWriteMetaToSidecarFile($('#writeMetaToSidecarFile').is(':checked'));
    TSCORE.Config.setUseDefaultLocation($('#useDefaultLocationCheckbox').is(':checked'));
    TSCORE.Config.saveSettings();
  }

  function collectPerspectivesData() {
    var data = [];
    $('#perspectiveList').children().each(function(index, element) {
      if ($(element).find('select').val() != 'false') {
        data.push({
          'id': $(element).find('select').val()
        });
      }
    });
    return data;
  }

  function collectSupportedFileTypesData() {
    var data = [];
    $('#fileTypesList').children().each(function(index, element) {
      data.push({
        'type': $(element).find('input').val(),
        'viewer': $(element).find('.ftviewer').val(),
        'editor': $(element).find('.fteditor').val()
      });
    });
    return data;
  }

  // Public Methods
  exports.initUI = initUI;
  exports.reInitUI = reInitUI;
});
<|endoftext|>


<commit_before>import RSVP from 'rsvp';
import TV4 from 'tv4';

import FlowUtil from './util/flow';
import LangUtil from './util/lang';
import Flox     from './flox';

const exists       = LangUtil.exists;
const mergeDict    = LangUtil.mergeDict;
const getNode      = FlowUtil.getNode;
const getEntryNode = FlowUtil.getEntryNode;
const getNodeType  = FlowUtil.getNodeType;

const expressionRE = Flox.expressionRE;

function allBranchesHaveNodes(flow) {
  const branches = flow.branches || []; // XXX This should be caught by schema validation!
  const res = branches.filter(
    (branch) => {
      return (
        exists(getNode(branch.branch[0], flow.nodes)) &&
        exists(getNode(branch.branch[1], flow.nodes))
      );
    }
  );
  return (res.length === branches.length);
}

function hasOneEntryNode(flow) {
  let res = true;
  try {
    res = getEntryNode(flow.nodes);
  } catch (e) {
    res = false;
  }
  return res;
}

function hasTerminalNodes(flow) {
  const termNodes = getNodeType(flow.nodes, 'flow', 'end');
  return (termNodes.length !== 0);
}

function expressionsReferenceKnownVariables(flow) {
  let flowVars      = {};
  let unMatchedVars = [];

  const getVar = (el)=> { flowVars[el.name] = false; };

  flow.signature.in.forEach(getVar);
  flow.variables.forEach(getVar);

  const expressions = getNodeType(flow.nodes, 'flox').map(
    (node) => node.parameters.expression
  );

  expressions.forEach(
    (expr)=> {
      const refs = (expr.match(expressionRE) || []);
      refs.forEach((ref)=> {
        if (exists(flowVars[ref])) {
          flowVars[ref] = true;
        } else {
          unMatchedVars.push(ref);
        }
      });
    }
  );

  return (unMatchedVars.length === 0);
}

class XFlowValidator {
  constructor(flowJson, schemaJson) {

    if (!exists(flowJson)) {
      throw new Error('XFlowValidator : No valid flow data found');
    }

    if (!exists(schemaJson)) {
      throw new Error('XFlowValidator : No schema passed');
    }

    this.flow   = flowJson;
    this.schema = schemaJson;
  }

  validate() {
    const res = [
      allBranchesHaveNodes(this.flow),
      hasOneEntryNode(this.flow),
      hasTerminalNodes(this.flow),
      expressionsReferenceKnownVariables(this.flow),
      TV4.validate(this.flow, this.schema)
    ];

    return (res.filter((x)=> !x)).length === 0;
  }

}

export default XFlowValidator;
<commit_msg>Fix token checking in validation, require valid schema structure before processing content<commit_after>import RSVP from 'rsvp';
import TV4 from 'tv4';

import FlowUtil from './util/flow';
import LangUtil from './util/lang';
import Flox     from './flox';

const exists       = LangUtil.exists;
const mergeDict    = LangUtil.mergeDict;
const getNode      = FlowUtil.getNode;
const getEntryNode = FlowUtil.getEntryNode;
const getNodeType  = FlowUtil.getNodeType;

const expressionRE = Flox.expressionRE;
const whitespaceRE = Flox.whitespaceRE;

function allBranchesHaveNodes(flow) {
  const branches = flow.branches || []; // XXX This should be caught by schema validation!
  const res = branches.filter(
    (branch) => {
      return (
        exists(getNode(branch.branch[0], flow.nodes)) &&
        exists(getNode(branch.branch[1], flow.nodes))
      );
    }
  );
  return (res.length === branches.length);
}

function hasOneEntryNode(flow) {
  let res = true;
  try {
    res = getEntryNode(flow.nodes);
  } catch (e) {
    res = false;
  }
  return res;
}

function hasTerminalNodes(flow) {
  const termNodes = getNodeType(flow.nodes, 'flow', 'end');
  return (termNodes.length !== 0);
}

function expressionsReferenceKnownVariables(flow) {
  let flowVars      = {};
  let unMatchedVars = [];

  const getVar = (el)=> { flowVars[el.name] = false; };

  flow.signature.in.forEach(getVar);
  flow.variables.forEach(getVar);

  const expressions = getNodeType(flow.nodes, 'flow', 'flox').map(
    (node) => node.parameters.expression
  );

  expressions.forEach(
    (expr)=> {
      const refs = (expr.replace(whitespaceRE, '').match(expressionRE) || []);
      refs.forEach((ref)=> {
        ref = ref.slice(1, ref.length); // Remove '$'
        if (exists(flowVars[ref])) {
          flowVars[ref] = true;
        } else {
          unMatchedVars.push(ref);
        }
      });
    }
  );

  return (unMatchedVars.length === 0);
}

function isSchemaValid(flow, schema) {
  const res = TV4.validate(flow, schema, true, true);
  if (res === false) {
    console.log('XFlowValidator.isSchemaValid validation error ', TV4.error);
  }
  return res;
}

class XFlowValidator {
  constructor(flowJson, schemaJson) {

    if (!exists(flowJson)) {
      throw new Error('XFlowValidator : No valid flow data found');
    }

    if (!exists(schemaJson)) {
      throw new Error('XFlowValidator : No schema passed');
    }

    this.flow   = flowJson;
    this.schema = schemaJson;
  }

  validate() {
    if (!isSchemaValid(this.flow, this.schema)) {
      return false;
    } else {
      const res = [
        allBranchesHaveNodes(this.flow),
        hasOneEntryNode(this.flow),
        hasTerminalNodes(this.flow),
        expressionsReferenceKnownVariables(this.flow)
      ];

      return (res.filter((x)=> !x)).length === 0;
    }
  }

}

export default XFlowValidator;
<|endoftext|>


<commit_before>/* jshint curly: false */

/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* A collection of easing methods defining ease-in and ease-out curves.
*
* @class Phaser.Easing
*/
Phaser.Easing = {

    /**
    * Linear easing.
    *
    * @class Phaser.Easing.Linear
    */
    Linear: {

        /**
        * Linear Easing (no variation).
        *
        * @method Phaser.Easing.Linear#None
        * @param {number} k - The value to be tweened.
        * @returns {number} k.
        */
        None: function (k)
        {

            return k;

        }

    },

    /**
    * Quadratic easing.
    *
    * @class Phaser.Easing.Quadratic
    */
    Quadratic: {

        /**
        * Ease-in.
        *
        * @method Phaser.Easing.Quadratic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} k^2.
        */
        In: function (k)
        {

            return k * k;

        },

        /**
        * Ease-out.
        *
        * @method Phaser.Easing.Quadratic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} k* (2-k).
        */
        Out: function (k)
        {

            return k * (2 - k);

        },

        /**
        * Ease-in/out.
        *
        * @method Phaser.Easing.Quadratic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k; }
            return - 0.5 * (--k * (k - 2) - 1);

        }

    },

    /**
    * Cubic easing.
    *
    * @class Phaser.Easing.Cubic
    */
    Cubic: {

        /**
        * Cubic ease-in.
        *
        * @method Phaser.Easing.Cubic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k;

        },

        /**
        * Cubic ease-out.
        *
        * @method Phaser.Easing.Cubic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return --k * k * k + 1;

        },

        /**
        * Cubic ease-in/out.
        *
        * @method Phaser.Easing.Cubic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k; }
            return 0.5 * ((k -= 2) * k * k + 2);

        }

    },

    /**
    * Quartic easing.
    *
    * @class Phaser.Easing.Quartic
    */
    Quartic: {

        /**
        * Quartic ease-in.
        *
        * @method Phaser.Easing.Quartic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k * k;

        },

        /**
        * Quartic ease-out.
        *
        * @method Phaser.Easing.Quartic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return 1 - (--k * k * k * k);

        },

        /**
        * Quartic ease-in/out.
        *
        * @method Phaser.Easing.Quartic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k * k; }
            return - 0.5 * ((k -= 2) * k * k * k - 2);

        }

    },

    /**
    * Quintic easing.
    *
    * @class Phaser.Easing.Quintic
    */
    Quintic: {

        /**
        * Quintic ease-in.
        *
        * @method Phaser.Easing.Quintic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k * k * k;

        },

        /**
        * Quintic ease-out.
        *
        * @method Phaser.Easing.Quintic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return --k * k * k * k * k + 1;

        },

        /**
        * Quintic ease-in/out.
        *
        * @method Phaser.Easing.Quintic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; }
            return 0.5 * ((k -= 2) * k * k * k * k + 2);

        }

    },

    /**
    * Sinusoidal easing.
    *
    * @class Phaser.Easing.Sinusoidal
    */
    Sinusoidal: {

        /**
        * Sinusoidal ease-in.
        *
        * @method Phaser.Easing.Sinusoidal#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return 1 - Math.cos(k * Math.PI / 2);

        },

        /**
        * Sinusoidal ease-out.
        *
        * @method Phaser.Easing.Sinusoidal#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return Math.sin(k * Math.PI / 2);

        },

        /**
        * Sinusoidal ease-in/out.
        *
        * @method Phaser.Easing.Sinusoidal#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return 0.5 * (1 - Math.cos(Math.PI * k));

        }

    },

    /**
    * Exponential easing.
    *
    * @class Phaser.Easing.Exponential
    */
    Exponential: {

        /**
        * Exponential ease-in.
        *
        * @method Phaser.Easing.Exponential#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k === 0 ? 0 : Math.pow(1024, k - 1);

        },

        /**
        * Exponential ease-out.
        *
        * @method Phaser.Easing.Exponential#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);

        },

        /**
        * Exponential ease-in/out.
        *
        * @method Phaser.Easing.Exponential#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); }
            return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);

        }

    },

    /**
    * Circular easing.
    *
    * @class Phaser.Easing.Circular
    */
    Circular: {

        /**
        * Circular ease-in.
        *
        * @method Phaser.Easing.Circular#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return 1 - Math.sqrt(1 - k * k);

        },

        /**
        * Circular ease-out.
        *
        * @method Phaser.Easing.Circular#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return Math.sqrt(1 - (--k * k));

        },

        /**
        * Circular ease-in/out.
        *
        * @method Phaser.Easing.Circular#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return - 0.5 * (Math.sqrt(1 - k * k) - 1); }
            return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);

        }

    },

    /**
    * Elastic easing.
    *
    * @class Phaser.Easing.Elastic
    */
    Elastic: {

        /**
        * Elastic ease-in.
        *
        * @method Phaser.Easing.Elastic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            var s,
                a = 0.1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            if (!a || a < 1) { a = 1; s = p / 4; }
            else { s = p * Math.asin(1 / a) / (2 * Math.PI); }
            return - (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));

        },

        /**
        * Elastic ease-out.
        *
        * @method Phaser.Easing.Elastic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            var s,
                a = 0.1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            if (!a || a < 1) { a = 1; s = p / 4; }
            else { s = p * Math.asin(1 / a) / (2 * Math.PI); }
            return (a * Math.pow(2, - 10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1);

        },

        /**
        * Elastic ease-in/out.
        *
        * @method Phaser.Easing.Elastic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            var s,
                a = 0.1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            if (!a || a < 1) { a = 1; s = p / 4; }
            else { s = p * Math.asin(1 / a) / (2 * Math.PI); }
            if ((k *= 2) < 1) { return - 0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); }
            return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;

        }

    },

    /**
    * Back easing.
    *
    * @class Phaser.Easing.Back
    */
    Back: {

        /**
        * Back ease-in.
        *
        * @method Phaser.Easing.Back#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            var s = 1.70158;
            return k * k * ((s + 1) * k - s);

        },

        /**
        * Back ease-out.
        *
        * @method Phaser.Easing.Back#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            var s = 1.70158;
            return --k * k * ((s + 1) * k + s) + 1;

        },

        /**
        * Back ease-in/out.
        *
        * @method Phaser.Easing.Back#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            var s = 1.70158 * 1.525;
            if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); }
            return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);

        }

    },

    /**
    * Bounce easing.
    *
    * @class Phaser.Easing.Bounce
    */
    Bounce: {

        /**
        * Bounce ease-in.
        *
        * @method Phaser.Easing.Bounce#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return 1 - Phaser.Easing.Bounce.Out(1 - k);

        },

        /**
        * Bounce ease-out.
        *
        * @method Phaser.Easing.Bounce#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            if (k < (1 / 2.75))
            {

                return 7.5625 * k * k;

            }
            else if (k < (2 / 2.75))
            {

                return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;

            }
            else if (k < (2.5 / 2.75))
            {

                return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;

            }
            else
            {

                return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;

            }

        },

        /**
        * Bounce ease-in/out.
        *
        * @method Phaser.Easing.Bounce#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k < 0.5) { return Phaser.Easing.Bounce.In(k * 2) * 0.5; }
            return Phaser.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;

        }

    }

};

Phaser.Easing.Default = Phaser.Easing.Linear.None;
Phaser.Easing.Power0 = Phaser.Easing.Linear.None;
Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out;
Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out;
Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out;
Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out;
<commit_msg>Fix elastic easings<commit_after>/* jshint curly: false */

/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* A collection of easing methods defining ease-in and ease-out curves.
*
* @class Phaser.Easing
*/
Phaser.Easing = {

    /**
    * Linear easing.
    *
    * @class Phaser.Easing.Linear
    */
    Linear: {

        /**
        * Linear Easing (no variation).
        *
        * @method Phaser.Easing.Linear#None
        * @param {number} k - The value to be tweened.
        * @returns {number} k.
        */
        None: function (k)
        {

            return k;

        }

    },

    /**
    * Quadratic easing.
    *
    * @class Phaser.Easing.Quadratic
    */
    Quadratic: {

        /**
        * Ease-in.
        *
        * @method Phaser.Easing.Quadratic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} k^2.
        */
        In: function (k)
        {

            return k * k;

        },

        /**
        * Ease-out.
        *
        * @method Phaser.Easing.Quadratic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} k* (2-k).
        */
        Out: function (k)
        {

            return k * (2 - k);

        },

        /**
        * Ease-in/out.
        *
        * @method Phaser.Easing.Quadratic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k; }
            return - 0.5 * (--k * (k - 2) - 1);

        }

    },

    /**
    * Cubic easing.
    *
    * @class Phaser.Easing.Cubic
    */
    Cubic: {

        /**
        * Cubic ease-in.
        *
        * @method Phaser.Easing.Cubic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k;

        },

        /**
        * Cubic ease-out.
        *
        * @method Phaser.Easing.Cubic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return --k * k * k + 1;

        },

        /**
        * Cubic ease-in/out.
        *
        * @method Phaser.Easing.Cubic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k; }
            return 0.5 * ((k -= 2) * k * k + 2);

        }

    },

    /**
    * Quartic easing.
    *
    * @class Phaser.Easing.Quartic
    */
    Quartic: {

        /**
        * Quartic ease-in.
        *
        * @method Phaser.Easing.Quartic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k * k;

        },

        /**
        * Quartic ease-out.
        *
        * @method Phaser.Easing.Quartic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return 1 - (--k * k * k * k);

        },

        /**
        * Quartic ease-in/out.
        *
        * @method Phaser.Easing.Quartic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k * k; }
            return - 0.5 * ((k -= 2) * k * k * k - 2);

        }

    },

    /**
    * Quintic easing.
    *
    * @class Phaser.Easing.Quintic
    */
    Quintic: {

        /**
        * Quintic ease-in.
        *
        * @method Phaser.Easing.Quintic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k * k * k * k * k;

        },

        /**
        * Quintic ease-out.
        *
        * @method Phaser.Easing.Quintic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return --k * k * k * k * k + 1;

        },

        /**
        * Quintic ease-in/out.
        *
        * @method Phaser.Easing.Quintic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; }
            return 0.5 * ((k -= 2) * k * k * k * k + 2);

        }

    },

    /**
    * Sinusoidal easing.
    *
    * @class Phaser.Easing.Sinusoidal
    */
    Sinusoidal: {

        /**
        * Sinusoidal ease-in.
        *
        * @method Phaser.Easing.Sinusoidal#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return 1 - Math.cos(k * Math.PI / 2);

        },

        /**
        * Sinusoidal ease-out.
        *
        * @method Phaser.Easing.Sinusoidal#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return Math.sin(k * Math.PI / 2);

        },

        /**
        * Sinusoidal ease-in/out.
        *
        * @method Phaser.Easing.Sinusoidal#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            return 0.5 * (1 - Math.cos(Math.PI * k));

        }

    },

    /**
    * Exponential easing.
    *
    * @class Phaser.Easing.Exponential
    */
    Exponential: {

        /**
        * Exponential ease-in.
        *
        * @method Phaser.Easing.Exponential#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return k === 0 ? 0 : Math.pow(1024, k - 1);

        },

        /**
        * Exponential ease-out.
        *
        * @method Phaser.Easing.Exponential#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);

        },

        /**
        * Exponential ease-in/out.
        *
        * @method Phaser.Easing.Exponential#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); }
            return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);

        }

    },

    /**
    * Circular easing.
    *
    * @class Phaser.Easing.Circular
    */
    Circular: {

        /**
        * Circular ease-in.
        *
        * @method Phaser.Easing.Circular#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return 1 - Math.sqrt(1 - k * k);

        },

        /**
        * Circular ease-out.
        *
        * @method Phaser.Easing.Circular#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            return Math.sqrt(1 - (--k * k));

        },

        /**
        * Circular ease-in/out.
        *
        * @method Phaser.Easing.Circular#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if ((k *= 2) < 1) { return - 0.5 * (Math.sqrt(1 - k * k) - 1); }
            return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);

        }

    },

    /**
    * Elastic easing.
    *
    * @class Phaser.Easing.Elastic
    */
    Elastic: {

        /**
        * Elastic ease-in.
        *
        * @method Phaser.Easing.Elastic#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            var s,
                a = 1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            s = p / 4;
            return - (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));

        },

        /**
        * Elastic ease-out.
        *
        * @method Phaser.Easing.Elastic#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            var s,
                a = 1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            s = p / 4;
            return (a * Math.pow(2, - 10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1);

        },

        /**
        * Elastic ease-in/out.
        *
        * @method Phaser.Easing.Elastic#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            var s,
                a = 1,
                p = 0.4;
            if (k === 0) { return 0; }
            if (k === 1) { return 1; }
            s = p / 4;
            if ((k *= 2) < 1) { return - 0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); }
            return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;

        }

    },

    /**
    * Back easing.
    *
    * @class Phaser.Easing.Back
    */
    Back: {

        /**
        * Back ease-in.
        *
        * @method Phaser.Easing.Back#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            var s = 1.70158;
            return k * k * ((s + 1) * k - s);

        },

        /**
        * Back ease-out.
        *
        * @method Phaser.Easing.Back#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            var s = 1.70158;
            return --k * k * ((s + 1) * k + s) + 1;

        },

        /**
        * Back ease-in/out.
        *
        * @method Phaser.Easing.Back#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            var s = 1.70158 * 1.525;
            if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); }
            return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);

        }

    },

    /**
    * Bounce easing.
    *
    * @class Phaser.Easing.Bounce
    */
    Bounce: {

        /**
        * Bounce ease-in.
        *
        * @method Phaser.Easing.Bounce#In
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        In: function (k)
        {

            return 1 - Phaser.Easing.Bounce.Out(1 - k);

        },

        /**
        * Bounce ease-out.
        *
        * @method Phaser.Easing.Bounce#Out
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        Out: function (k)
        {

            if (k < (1 / 2.75))
            {

                return 7.5625 * k * k;

            }
            else if (k < (2 / 2.75))
            {

                return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;

            }
            else if (k < (2.5 / 2.75))
            {

                return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;

            }
            else
            {

                return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;

            }

        },

        /**
        * Bounce ease-in/out.
        *
        * @method Phaser.Easing.Bounce#InOut
        * @param {number} k - The value to be tweened.
        * @returns {number} The tweened value.
        */
        InOut: function (k)
        {

            if (k < 0.5) { return Phaser.Easing.Bounce.In(k * 2) * 0.5; }
            return Phaser.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;

        }

    }

};

Phaser.Easing.Default = Phaser.Easing.Linear.None;
Phaser.Easing.Power0 = Phaser.Easing.Linear.None;
Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out;
Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out;
Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out;
Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out;
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

var Component = this.Component = Base.extend(Callback, /** @lends Component# */{
	_events: [ 'onChange', 'onClick' ],

	_types: {
		'boolean': {
			type: 'checkbox',
			value: 'checked'
		},

		string: {
			type: 'text'
		},

		number: {
			type: 'number'
		},

		button: {
			type: 'button'
		},

		text: {
			tag: 'div',
			value: 'text'
		},

		slider: {
			type: 'range',
			number: true
		},

		list: {
			tag: 'select',

			options: function() {
				DomElement.removeChildren(this._inputItem);
				DomElement.create(Base.each(this._options, function(option) {
					this.push('option', { value: option, text: option });
				}, []), this._inputItem);
			},

			value: function(value) {
				DomElement.set(
					DomElement.find('option[value="' + value + '"]', this._inputItem),
					'selected', true);
			}
		}
	},

	initialize: function(obj) {
		this._type = obj.type
			|| ('options' in obj
				? 'list'
				: 'onClick' in obj
					? 'button'
					: typeof value);
		this._info = this._types[this._type] || { type: this._type };
		var that = this,
			fireChange = false;
		this._inputItem = DomElement.create(this._info.tag || 'input', {
			type: this._info.type,
			events: {
				change: function() {
					var key = that._info.value;
					if (typeof key === 'function')
						key = null;
					var value = DomElement.get(this, key || 'value');
					if (fireChange) {
						that.palette.fire('change', that, that.name, value);
						that.fire('change', value);
					}
				},
				click: function() {
					that.fire('click');
				}
			}
		});
		this._element = DomElement.create('tr', [
			this._labelItem = DomElement.create('td'),
			'td', this._inputItem
		]);
		Base.each(obj, function(value, key) {
			this[key] = value;
		}, this);
		this._defaultValue = this._value;
		// Only fire change events after we have initalized
		fireChange = true;
	},

	getType: function() {
		return this._type;
	},

	getLabel: function() {
		return this._label;
	},

	setLabel: function(label) {
		this._label = label;
		DomElement.set(this._labelItem, 'text', label + ':');
	},

	getOptions: function() {
		return this._options;
	},

	setOptions: function(options) {
		this._options = options;
		if (this._info.options)
			this._info.options.call(this);
	},

	getValue: function() {
		return this._value;
	},

	setValue: function(value) {
		var key = this._info.value;
		if (typeof key === 'function')
			key.call(this, value);
		else
			DomElement.set(this._inputItem, key || 'value', value);
		this._value = value;
	},

	getRange: function() {
		return [toFloat(DomElement.get(this._inputItem, 'min')),
				toFloat(DomElement.get(this._inputItem, 'max'))];
	},

	setRange: function(min, max) {
		var range = Array.isArray(min) ? min : [min, max];
		DomElement.set(this._inputItem, { min: range[0], max: range[1] });
	},

	getMin: function() {
		return getRange()[0];
	},

	setMin: function(min) {
		this.setRange(min, getMax());
	},

	getMax: function() {
		return getRange()[1];
	},

	setMax: function(max) {
		this.setRange(getMin(), max);
	},

	getStep: function() {
		return toFloat(DomElement.get(this._inputItem, 'step'));
	},

	setStep: function(step) {
		DomElement.set(this._inputItem, 'step', step);
	},

	reset: function() {
		this.setValue(this._defaultValue);
	}
});<commit_msg>Convert values of numeric items to numbers.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

var Component = this.Component = Base.extend(Callback, /** @lends Component# */{
	_events: [ 'onChange', 'onClick' ],

	_types: {
		'boolean': {
			type: 'checkbox',
			value: 'checked'
		},

		string: {
			type: 'text'
		},

		number: {
			type: 'number',
			number: true
		},

		button: {
			type: 'button'
		},

		text: {
			tag: 'div',
			value: 'text'
		},

		slider: {
			type: 'range',
			number: true
		},

		list: {
			tag: 'select',

			options: function() {
				DomElement.removeChildren(this._inputItem);
				DomElement.create(Base.each(this._options, function(option) {
					this.push('option', { value: option, text: option });
				}, []), this._inputItem);
			},

			value: function(value) {
				DomElement.set(
					DomElement.find('option[value="' + value + '"]', this._inputItem),
					'selected', true);
			}
		}
	},

	initialize: function(obj) {
		this._type = obj.type
			|| ('options' in obj
				? 'list'
				: 'onClick' in obj
					? 'button'
					: typeof value);
		this._info = this._types[this._type] || { type: this._type };
		var that = this,
			fireChange = false;
		this._inputItem = DomElement.create(this._info.tag || 'input', {
			type: this._info.type,
			events: {
				change: function() {
					var key = that._info.value;
					if (typeof key === 'function')
						key = null;
					var value = DomElement.get(this, key || 'value');
					if (that._info.number)
						value = Base.toFloat(value);
					if (fireChange) {
						that.palette.fire('change', that, that.name, value);
						that.fire('change', value);
					}
				},
				click: function() {
					that.fire('click');
				}
			}
		});
		this._element = DomElement.create('tr', [
			this._labelItem = DomElement.create('td'),
			'td', this._inputItem
		]);
		Base.each(obj, function(value, key) {
			this[key] = value;
		}, this);
		this._defaultValue = this._value;
		// Only fire change events after we have initalized
		fireChange = true;
	},

	getType: function() {
		return this._type;
	},

	getLabel: function() {
		return this._label;
	},

	setLabel: function(label) {
		this._label = label;
		DomElement.set(this._labelItem, 'text', label + ':');
	},

	getOptions: function() {
		return this._options;
	},

	setOptions: function(options) {
		this._options = options;
		if (this._info.options)
			this._info.options.call(this);
	},

	getValue: function() {
		return this._value;
	},

	setValue: function(value) {
		var key = this._info.value;
		if (typeof key === 'function')
			key.call(this, value);
		else
			DomElement.set(this._inputItem, key || 'value', value);
		this._value = value;
	},

	getRange: function() {
		return [toFloat(DomElement.get(this._inputItem, 'min')),
				toFloat(DomElement.get(this._inputItem, 'max'))];
	},

	setRange: function(min, max) {
		var range = Array.isArray(min) ? min : [min, max];
		DomElement.set(this._inputItem, { min: range[0], max: range[1] });
	},

	getMin: function() {
		return getRange()[0];
	},

	setMin: function(min) {
		this.setRange(min, getMax());
	},

	getMax: function() {
		return getRange()[1];
	},

	setMax: function(max) {
		this.setRange(getMin(), max);
	},

	getStep: function() {
		return toFloat(DomElement.get(this._inputItem, 'step'));
	},

	setStep: function(step) {
		DomElement.set(this._inputItem, 'step', step);
	},

	reset: function() {
		this.setValue(this._defaultValue);
	}
});<|endoftext|>


<commit_before>/*jshint regexp:false*/

/**
 *
 */
define([

], function () {

    'use strict';

    if (typeof(window.console) === 'undefined') {
        var emptyFunc = function () { },
            keys = [
                'log',
                'debug',
                'info',
                'warn',
                'error',
                'assert',
                'clear',
                'dir',
                'dirxml',
                'trace',
                'group',
                'groupCollapsed',
                'groupEnd',
                'time',
                'timeEnd',
                'profile',
                'profileEnd',
                'count',
                'exception',
                'table'
            ],
            i = keys.length;

        while (i--) {
            window.console[keys[i]] = emptyFunc;
        }

    }
});<commit_msg>Create empty object.<commit_after>/*jshint regexp:false*/

/**
 *
 */
define([

], function () {

    'use strict';

    if (typeof(window.console) === 'undefined') {
        var emptyFunc = function () { },
            keys = [
                'log',
                'debug',
                'info',
                'warn',
                'error',
                'assert',
                'clear',
                'dir',
                'dirxml',
                'trace',
                'group',
                'groupCollapsed',
                'groupEnd',
                'time',
                'timeEnd',
                'profile',
                'profileEnd',
                'count',
                'exception',
                'table'
            ],
            i = keys.length;

        window.console = { };
        while (i--) {
            window.console[keys[i]] = emptyFunc;
        }

    }
});<|endoftext|>