Пример #1
0
Converter.prototype.obj2tsv = function (data) {
    var scope = {};
    if (!_isObject(data)) {
        try {
            scope.data = _parse(data);
        } catch (e) {
            throw new Error("JSON data error - " + e.message)
        }
    }
    scope.buffer = {};
    scope.langs = _keys(scope.data);
    scope.out = this.frc.toUpperCase();
    _each(scope.langs, function (l) {
        scope.out += '\t' + String(l).toUpperCase();
        _each(scope.data[l], function (v, n) {
            if (!scope.buffer[n]) scope.buffer[n] = {};
            scope.buffer[n][l] = v;
        });
    });
    scope.out += '\n';
    _each(scope.buffer, function (d, k) {
        scope.out += k;
        _each(scope.langs, function (l) {
            scope.out += '\t' + String(d[l] || "");
        });
        scope.out += '\n';
    });
    return scope.out;
};
Пример #2
0
  this.onDocumentChange = function(change) {
    var cells = [];
    var doc = this.props.doc;
    each(change.created, function(nodeData) {
      if (nodeData.type === 'sheet-cell') {
        cells.push(nodeData);
      }
    });
    each(change.deleted, function(nodeData) {
      if (nodeData.type === 'sheet-cell') {
        cells.push(nodeData);
      }
    });
    each(change.updated, function(props, id) {
      var cell = doc.get(id);
      if (cell && cell.type === 'sheet-cell') {
        cells.push(cell);
      }
    });
    if (cells.length > 0) {
      this.send('updateCells', cells);
    }

    // We update the selection on each document change
    // E.g. this solves the situation where we update the display
    // mode using the DisplayMode tool where no selection update
    // is triggered.
    this._rerenderSelection();  
  };
Пример #3
0
 _each(_rest(scope.schema), function (l) {
     var i = scope.schema.indexOf(l), b = scope.out[l] = {};
     _each(scope.data, function (a, k) {
         if (k <= 0 || a[0].length <= 0 || !a[i]) return;
         b[a[0]] = a[i];
     });
 });
Пример #4
0
 _each(scope.buffer, function (d, k) {
     scope.out += k;
     _each(scope.langs, function (l) {
         scope.out += '\t' + String(d[l] || "");
     });
     scope.out += '\n';
 });
Пример #5
0
 _each(scope.langs, function (l) {
     scope.out += '\t' + String(l).toUpperCase();
     _each(scope.data[l], function (v, n) {
         if (!scope.buffer[n]) scope.buffer[n] = {};
         scope.buffer[n][l] = v;
     });
 });
Пример #6
0
File.prototype.buildTransformers = function () {
  var file = this;

  var transformers = {};

  var secondaryStack = [];
  var stack = [];

  each(transform.transformers, function (transformer, key) {
    var pass = transformers[key] = transformer.buildPass(file);

    if (pass.canRun(file)) {
      stack.push(pass);

      if (transformer.secondPass) {
        secondaryStack.push(pass);
      }

      if (transformer.manipulateOptions) {
        transformer.manipulateOptions(file.opts, file);
      }
    }
  });

  this.transformerStack = stack.concat(secondaryStack);
  this.transformers = transformers;
};
Пример #7
0
  CodeGenerator.prototype.printJoin = function printJoin(print, nodes, opts) {
    var _this = this;

    if (!nodes || !nodes.length) return;

    if (!opts) opts = {};

    var len = nodes.length;

    if (opts.indent) this.indent();

    each(nodes, function (node, i) {
      print(node, {
        statement: opts.statement,
        addNewlines: opts.addNewlines,
        after: function () {
          if (opts.iterator) {
            opts.iterator(node, i);
          }

          if (opts.separator && i < len - 1) {
            _this.push(opts.separator);
          }
        }
      });
    });

    if (opts.indent) this.dedent();
  };
Пример #8
0
exports.ImportDeclaration = function (node, print) {
  var self = this;

  this.push("import ");

  var specfiers = node.specifiers;
  if (specfiers && specfiers.length) {
    var foundImportSpecifier = false;

    each(node.specifiers, function (spec, i) {
      if (+i > 0) {
        self.push(", ");
      }

      var isDefault = t.isSpecifierDefault(spec);

      if (!isDefault && spec.type !== "ImportBatchSpecifier" && !foundImportSpecifier) {
        foundImportSpecifier = true;
        self.push("{ ");
      }

      print(spec);
    });

    if (foundImportSpecifier) {
      this.push(" }");
    }

    this.push(" from ");
  }

  print(node.source);
  this.semicolon();
};
Пример #9
0
export function toClassObject(mutatorMap: Object): Object {
  let objExpr = t.objectExpression([]);

  each(mutatorMap, function (map) {
    let mapNode = t.objectExpression([]);

    let propNode = t.objectProperty(map._key, mapNode, map._computed);

    each(map, function (node, key) {
      if (key[0] === "_") return;

      let inheritNode = node;
      if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value;

      let prop = t.objectProperty(t.identifier(key), node);
      t.inheritsComments(prop, inheritNode);
      t.removeComments(inheritNode);

      mapNode.properties.push(prop);
    });

    objExpr.properties.push(propNode);
  });

  return objExpr;
}
Пример #10
0
Transformer.prototype.normalize = function (transformer) {
  var self = this;

  if (isFunction(transformer)) {
    transformer = { ast: transformer };
  }

  traverse.explode(transformer);

  each(transformer, function (fns, type) {
    // hidden property
    if (type[0] === "_") {
      self[type] = fns;
      return;
    }

    if (type === "enter" || type === "exit") return;

    if (isFunction(fns)) fns = { enter: fns };

    if (!isObject(fns)) return;

    if (!fns.enter) fns.enter = function () { };
    if (!fns.exit) fns.exit = function () { };

    transformer[type] = fns;
  });

  return transformer;
};
Пример #11
0
function recordPlaceholders( mutation ) { 
	var nodes = [];

	if ( mutation.attributeName === 'class' ) { // mutation.type === 'attributes' is redundant
		nodes = [mutation.target];
	} else if ( mutation.type === 'childList' && mutation.addedNodes.length > 0 ) {
		nodes = mutation.addedNodes;
	} else {
		return;
	}

	each( nodes, function( node ) {

		if ( isPlaceholder( node ) ) {
			recordPlaceholderNode( node );
		}

		// we need to find matching children because the mutation observer
		// only fires for the top element of an added subtree
		if ( node.querySelectorAll ) {
			// funky syntax because NodeList walks like an array but doesn't quack like one
			each( node.querySelectorAll(PLACEHOLDER_MATCHER), recordPlaceholderNode );
		}
	} );
}
Пример #12
0
 optionalAttributes: function(object, attr, keys) {
   each(keys, function(attribute, variable) {
     if(object.vars[variable]) {
       attr[attribute] = this.s(object.vars[variable]);
     }
   }, this);
 },
Пример #13
0
  normalize(transformer: Object): Object {
    if (isFunction(transformer)) {
      transformer = { ast: transformer };
    }

    traverse.explode(transformer);

    each(transformer, (fns, type) => {
      // hidden property
      if (type[0] === "_") {
        this[type] = fns;
        return;
      }

      if (type === "enter" || type === "exit") return;

      if (isFunction(fns)) fns = { enter: fns };

      if (!isObject(fns)) return;

      if (!fns.enter) fns.enter = function () { };
      if (!fns.exit) fns.exit = function () { };

      transformer[type] = fns;
    });

    return transformer;
  }
Пример #14
0
  /**
   * Destroy a collection instance, cleaning up any events added to it or that
   * it added to its models.
   */
  destroy() {
    each(this.models_, (model) =>
        model.removeListener('change', this.handleChange_));

    this.removeAllListeners();
    this.models_ = null;
  }
Пример #15
0
    each(schema, (definition, fieldRef) => {
      const { label, required, type, validate, error } = definition
      const fieldValue = formValues[fieldRef]
      const fieldValueExists = isDefined(formValues[fieldRef])


      // required is active if it is `true` or a function that returns
      // true when passed the form values as an argument. This allows
      // you to perform conditional requires based on other values in
      // the form
      const isRequired = required &&
        (required === true) ||
        (isFunction(required) && required(formValues))

      // validate required
      if (isRequired && !fieldValueExists) {
        const message = error || errorMessageGenerator(errorMessages, 'required', label)
        addErrorToField(errors, fieldRef, message)
      }

      // validate simple type validators
      if (fieldValueExists && type && !validates(type, fieldValue)) {
        // use custom error message or fallback to default
        const message = error || errorMessageGenerator(errorMessages, type, label)
        addErrorToField(errors, fieldRef, message)
      }

      // validate complex validations
      if (validate) {

        // only validate if rule doesnt exist, or rule exists and the
        // function returns true when passed formValues

        each(validate, (opts, id) => {
          // TODO support array of validate's which will allow multiple
          // rule based validations

          // skip validation if we have no field value
          if (!fieldValueExists) {
            return
          }

          let isValid
          const customValidator = isFunction(opts) && opts

          if (customValidator) {
            isValid = customValidator(formValues, fieldValue)
          } else {
            isValid = validates(id, fieldValue, opts)
          }

          if (!isValid) {
            // use custom error message or fallback to default
            const message = error || errorMessageGenerator(errorMessages, id, label, opts)
            addErrorToField(errors, fieldRef, message)
          }
        })
      }

    })
Пример #16
0
t.toSequenceExpression = function (nodes, scope) {
  var exprs = [];

  each(nodes, function (node) {
    if (t.isExpression(node)) {
      exprs.push(node);
    } if (t.isExpressionStatement(node)) {
      exprs.push(node.expression);
    } else if (t.isVariableDeclaration(node)) {
      each(node.declarations, function (declar) {
        scope.push({
          kind: node.kind,
          key: declar.id.name,
          id: declar.id
        });
        exprs.push(t.assignmentExpression("=", declar.id, declar.init));
      });
    }
  });

  if (exprs.length === 1) {
    return exprs[0];
  } else {
    return t.sequenceExpression(exprs);
  }
};
Пример #17
0
var hookExtensions = function (_exts) {
  each(oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  each(_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
};
Пример #18
0
  printJoin(print, nodes, opts = {}) {
    if (!nodes || !nodes.length) return;

    var len = nodes.length;

    if (opts.indent) this.indent();

    each(nodes, (node, i) => {
      print(node, {
        statement: opts.statement,
        addNewlines: opts.addNewlines,
        after: () => {
          if (opts.iterator) {
            opts.iterator(node, i);
          }

          if (opts.separator && i < len - 1) {
            this.push(opts.separator);
          }
        }
      });
    });

    if (opts.indent) this.dedent();
  }
Пример #19
0
  CodeGenerator.prototype._printComments = function _printComments(comments) {
    var _this = this;

    if (this.format.compact) return;

    if (!this.format.comments) return;
    if (!comments || !comments.length) return;

    each(comments, function (comment) {
      var skip = false;

      // find the original comment in the ast and set it as displayed
      each(_this.ast.comments, function (origComment) {
        if (origComment.start === comment.start) {
          // comment has already been output
          if (origComment._displayed) skip = true;

          origComment._displayed = true;
          return false;
        }
      });

      if (skip) return;

      // whitespace before
      _this.newline(_this.whitespace.getNewlinesBefore(comment));

      var column = _this.position.column;
      var val = _this.generateComment(comment);

      if (column && !_this.isLast(["\n", " ", "[", "{"])) {
        _this._push(" ");
        column++;
      }

      //

      if (comment.type === "Block" && _this.format.indent.adjustMultilineComment) {
        var offset = comment.loc.start.column;
        if (offset) {
          var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
          val = val.replace(newlineRegex, "\n");
        }

        var indent = Math.max(_this.indentSize(), column);
        val = val.replace(/\n/g, "\n" + repeating(" ", indent));
      }

      if (column === 0) {
        val = _this.getIndent() + val;
      }

      //

      _this._push(val);

      // whitespace after
      _this.newline(_this.whitespace.getNewlinesAfter(comment));
    });
  };
Пример #20
0
 _deleteUnvisitedCacheEntries() {
     each(this._spriteCache, (entry, key) => {
         if (!entry.visited) {
             this._entityLayer.removeChild(entry.sprite);
             delete this._spriteCache[key];
         }
     });
 }
Пример #21
0
 each(obj, function (val, keys) {
   var partitions = keys.split(separator)
   var result = newObj
   var len = partitions.length - 1
   each(partitions, function (keys, i) {
     result = result[keys] = (i === len ? val : (result[keys] || {}))
   })
 })
 function onAnimEnd() {
   console.log('done animating part one');
   detailPanel.classList.remove('animating');
   targetBackground.classList.remove('animating');
   spriteFacade.classList.remove('animating');
   detailBackButton.classList.remove('animating');
   targetBackground.style.transform = '';
   detailPanel.style.transform = '';
   detailViewContainer.classList.add('hidden');
   spriteFacade.classList.add('hidden');
   detailSprite.style.opacity = 1;
   // clean up any expanded move lists
   each(detailView.querySelectorAll('.moves-row-detail'), el => el.classList.add('hidden'));
   each(detailView.querySelectorAll('.dropdown-button-image'), el => el.style.transform = '');
   targetBackground.removeEventListener('transitionend', onAnimEnd);
   targetBackground.style.willChange = '';
 }
Пример #23
0
Amygdala.prototype.ajax = function ajax(method, url, options) {
   // Sends an Ajax request, converting the data into a querystring if the
   // method is GET.
   //
   // params:
   // -method (string): GET, POST, PUT, DELETE
   // -url (string): The url to send the request to.
   // -options (Object)
   //
   // options
   // - data (Object): Will be converted to a querystring for GET requests.
   // - contentType (string): A value for the Content-Type request header.
   // - headers (Object): Additional headers to add to the request.
  var query;
  options = options || {};

  if (!isEmpty(options.data) && method === 'GET') {
    query = this.serialize(options.data);
    url = url + '?' + query;
  }

  var request = new XMLHttpRequest();
  var deferred = Q.defer();

  request.open(method, url, true);

  request.onload = function() {
    // status 200 OK, 201 CREATED, 20* ALL OK
    if (request.status.toString().substr(0, 2) === '20') {
      deferred.resolve(request);
    } else {
      deferred.reject(request);
    }
  };

  request.onerror = function() {
    deferred.reject(new Error('Unabe to send request to ' + JSON.stringify(url)));
  };

  if (!isEmpty(options.contentType)) {
    request.setRequestHeader('Content-Type', options.contentType);
  }

  if (!isEmpty(options.headers)) {
    each(options.headers, function(value, key) {
      if (isFunction(value)) {
        request.setRequestHeader(key,value());
      }
      else {
        request.setRequestHeader(key, value);
      }
    });
  }

  request.send(method === 'GET' ? null : options.data);

  return deferred.promise;
}
Пример #24
0
    each(comments, (comment) => {
      var skip = false;

      // find the original comment in the ast and set it as displayed
      each(this.ast.comments, function (origComment) {
        if (origComment.start === comment.start) {
          // comment has already been output
          if (origComment._displayed) skip = true;

          origComment._displayed = true;
          return false;
        }
      });

      if (skip) return;

      this.catchUp(comment);

      // whitespace before
      this.newline(this.whitespace.getNewlinesBefore(comment));

      var column = this.position.column;
      var val    = this.generateComment(comment);

      if (column && !this.isLast(["\n", " ", "[", "{"])) {
        this._push(" ");
        column++;
      }

      //
      if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
        var offset = comment.loc.start.column;
        if (offset) {
          var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
          val = val.replace(newlineRegex, "\n");
        }

        var indent = Math.max(this.indentSize(), column);
        val = val.replace(/\n/g, `\n${repeating(" ", indent)}`);
      }

      if (column === 0) {
        val = this.getIndent() + val;
      }

      // force a newline for line comments when retainLines is set in case the next printed node
      // doesn't catch up
      if (this.format.retainLines && comment.type === "Line") {
        val += "\n";
      }

      //
      this._push(val);

      // whitespace after
      this.newline(this.whitespace.getNewlinesAfter(comment));
    });
Пример #25
0
each(t.VISITOR_KEYS, function (keys, type) {
  if (t.BUILDER_KEYS[type]) return;

  var defs = {};
  each(keys, function (key) {
    defs[key] = null;
  });
  t.BUILDER_KEYS[type] = defs;
});
Пример #26
0
  function convert(nodes) {
    var ensureLastUndefined = false;
    var exprs   = [];

    for (let i = 0; i < nodes.length; i++) {
      var node = nodes[i];
      if (t.isExpression(node)) {
        exprs.push(node);
      } else if (t.isExpressionStatement(node)) {
        exprs.push(node.expression);
      } else if (t.isVariableDeclaration(node)) {
        if (node.kind !== "var") return bailed = true; // bailed

        each(node.declarations, function (declar) {
          var bindings = t.getBindingIdentifiers(declar);
          for (var key in bindings) {
            declars.push({
              kind: node.kind,
              id: bindings[key]
            });
          }

          if (declar.init) {
            exprs.push(t.assignmentExpression("=", declar.id, declar.init));
          }
        });

        ensureLastUndefined = true;
        continue;
      } else if (t.isIfStatement(node)) {
        var consequent = node.consequent ? convert([node.consequent]) : t.identifier("undefined");
        var alternate = node.alternate ? convert([node.alternate]) : t.identifier("undefined");
        if (!consequent || !alternate) return bailed = true;

        exprs.push(t.conditionalExpression(node.test, consequent, alternate));
      } else if (t.isBlockStatement(node)) {
        exprs.push(convert(node.body));
      } else {
        // bailed, we can't understand this
        return bailed = true;
      }

      ensureLastUndefined = false;
    }

    if (ensureLastUndefined) {
      exprs.push(t.identifier("undefined"));
    }

    //

    if (exprs.length === 1) {
      return exprs[0];
    } else {
      return t.sequenceExpression(exprs);
    }
  }
Пример #27
0
  /**
   * Create a new collect instance with the specified models.
   * @constructor
   * @param {Array<Model>} props The initial props for the model.
   * @return {Collection}
   */
  constructor(models) {
    this.models_ = [];

    // Create a reference to a bound function to handle change events.
    // A reference is need so it can be removed later.
    this.handleChange_ = (model) => this.emit('change', model);

    each(models, (model) => this.add(model));
  }
Пример #28
0
export function toDefineObject(mutatorMap: Object): Object {
  each(mutatorMap, function (map) {
    if (map.value) map.writable = t.booleanLiteral(true);
    map.configurable = t.booleanLiteral(true);
    map.enumerable = t.booleanLiteral(true);
  });

  return toClassObject(mutatorMap);
}
Пример #29
0
function buildHelpers(body, namespace, whitelist) {
  each(helpers.list, function (name) {
    if (whitelist && whitelist.indexOf(name) < 0) return;

    let key = t.identifier(name);
    body.push(t.expressionStatement(
      t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))
    ));
  });
}
Пример #30
0
function buildHelpers(body, namespace, whitelist = []) {
  each(File.helpers, function (name) {
    if (whitelist.length && whitelist.indexOf(name) === -1) return;

    var key = t.identifier(t.toIdentifier(name));
    body.push(t.expressionStatement(
      t.assignmentExpression("=", t.memberExpression(namespace, key), util.template("helper-" + name))
    ));
  });
}