<commit_before>var db = require('./db');
var async = require('async');
/**
 * 分页对象
 * @param {[type]} totalRows   数据总条数
 * @param {[type]} currentPage 当前显示的第几页
 * @param {[type]} pageSize    每页显示的条数
 */
function PagingUtil(currentPage, pageSize) {
    this.currentPage = currentPage === undefined ? 1 : parseInt(currentPage); //当前是第几页,默认为第一页
    this.totalPages = 1; //最多能分多少页
    this.totalRows = 0; //总数据条数
    this.hasNextPage = false; //是否有下一页
    this.hasPrevPage = false; //是否有上一页
    this.pageSize = pageSize === undefined ? 10 : parseInt(pageSize); //每页显示几条数据，默认为10条
    this.startRow = 0; //起始行
    // this.endRow = 0; //结束行
    this.table = ""; //要查询的表
    this.queryFiled = ""; //要查询的字段
    this.condition = ""; //查询条件
    this.orderBy = ""; //排序
    this.countSql = ""; //查询总条数的sql
    this.pagingSql = ""; //分页sql
    this.sortBy = ""; //排序类型
    this.debug = false; //是否开启调试模式
}

/**
 * 排序类型
 * @param {[type]} sortBy [description]
 */
PagingUtil.prototype.setSortBy = function(sortBy) {
    this.sortBy = sortBy;
    return this;
}

/**
 * 设置按照什么字段排序
 * @param {[type]} orderBy [description]
 */
PagingUtil.prototype.setOrderBy = function(orderBy) {
    this.orderBy = orderBy;
    return this;
}

/**
 * 设置要查询的字段
 * @param {[type]} filed [description]
 */
PagingUtil.prototype.setQueryFiled = function(queryFiled) {
    this.queryFiled = queryFiled;
    return this;
}

/**
 * 设置查询条件
 * @param {[type]} condition [description]
 */
PagingUtil.prototype.setCondition = function(condition) {
    this.condition = condition;
    return this;
}

/**
 * 设置要查询的表
 * @param {[type]} table [description]
 */
PagingUtil.prototype.setTable = function(table) {
    this.table = table;
    return this;

}

/**
 * 获取分页sql
 * @return {[type]} [description]
 */
PagingUtil.prototype.getPagingSql = function() {
    this.queryFiled = this.queryFiled || "*";
    this.condition = this.condition || "";
    this.sortBy = this.sortBy || "ASC";
    var orderBy = "";
    if (this.orderBy === "" && this.sortBy === "") {
        orderBy = "";
    } else {
        if (this.orderBy === "") {
            orderBy = "";
        } else {
            orderBy = "ORDER BY " + this.orderBy + " " + this.sortBy;
        }
    }
    this.pagingSql = "SELECT " + this.queryFiled + " FROM " + this.table + " " + this.condition + " " + orderBy + " LIMIT ?,?";
    return this;
}

/**
 * 获取计算总条数的sql
 * @return {[type]} [description]
 */
PagingUtil.prototype.getCountSql = function() {
    this.countSql = "SELECT COUNT(1) AS count FROM " + this.table;
    return this;
}

/**
 * 获取数据
 * @return {[type]} [description]
 */
PagingUtil.prototype.getListData = function() {
    return this.listData;
}

/**
 * 设置每页需要显示的条数
 */
PagingUtil.prototype.setPageSize = function(pageSize) {
    this.pageSize = parseInt(pageSize);
    return this;

}

/**
 * 数据一共能分多少页
 * @param {[type]} num [description]
 */
PagingUtil.prototype.setTotalPages = function() {
    var totalPages = 0;
    totalPages = parseInt((this.totalRows - 1) / this.pageSize) + 1;
    this.totalPages = totalPages;
};

/**
 * 设置当前第几页
 * @param {[type]} currentPage [description]
 */
PagingUtil.prototype.setCurrentPage = function(currentPage) {
    this.currentPage = parseInt(currentPage);
    return this;
}

/**
 * 是否打印sql语句
 * @param {[type]} boolean [description]
 */
PagingUtil.prototype.setDebug = function(boolean) {
    this.debug = boolean;
    return this;

}

/**
 * 计算起始行
 * @return {[type]} [description]
 */
PagingUtil.prototype.computedStartRow = function() {
    if (this.currentPage === 1) { //第一页
        this.startRow = 0; //设置起始条数
        this.hasPrevPage = false;
        if (this.totalPages > 1) {
            this.hasNextPage = true;
        } else {
            this.hasNextPage = false;
        }
    } else if (1 < this.currentPage && this.currentPage < this.totalPages) { //中间页
        this.hasNextPage = true;
        this.hasPrevPage = true;
        this.startRow = (this.currentPage - 1) * this.pageSize;
    } else if (this.currentPage === this.totalPages) { //最后一页
        this.startRow = (this.currentPage - 1) * this.pageSize;
        this.hasNextPage = false;
        this.hasPrevPage = true;
    }
}

/**
 * 分页方法
 * @param  {Function} cb [description]
 * @return {[type]}      [description]
 */
PagingUtil.prototype.paging = function(cb) {
    //获取计算总条数的sql;
    var sql1 = this.getCountSql().countSql;
    var _this = this;
    async.series([function(callback) {
        db.execSql(sql1, null, function(err, result) {
            _this.totalRows = result[0].count; //总条数
            _this.setTotalPages(); //总页数
            _this.computedStartRow(); //计算起始行
            callback();
        });
    }, function(callback) {
        //分页sql语句
        var sql2 = _this.getPagingSql().pagingSql;
        var sqlParam = [_this.startRow, _this.pageSize];
        if (_this.debug) {
            console.warn("分页sql语句>>>:::::::::::::::::::::::::::::::::");
            console.log(sql2);
            console.warn("sql语句参数>>>:::::::::::::::::::::::::::::::::");
            console.log(sqlParam)
        }
        db.execSql(sql2, sqlParam, callback);
    }], function(err, results) {
        if (_this.debug) {
            console.warn("分页数据>>>:::::::::::::::::::::::::::::::::");
            console.log(results[1])
        }
        if (err) {
            cb(err, null)
        } else {
            var pagingData = {
                pagingData: results[1],
                currentPage: _this.currentPage,
                totalPages: _this.totalPages,
                totalRows: _this.totalRows,
                hasNextPage: _this.hasNextPage,
                hasPrevPage: _this.hasPrevPage,
                pageSize: _this.pageSize,
                startRow: _this.startRow
            };
            cb(null, pagingData)
        }
    });
}

module.exports = PagingUtil;
<commit_msg>分页插件统计总条数的时候添加了按条件统计<commit_after>var db = require('./db');
var async = require('async');
/**
 * 分页对象
 * @param {[type]} totalRows   数据总条数
 * @param {[type]} currentPage 当前显示的第几页
 * @param {[type]} pageSize    每页显示的条数
 */
function PagingUtil(currentPage, pageSize) {
    this.currentPage = currentPage === undefined ? 1 : parseInt(currentPage); //当前是第几页,默认为第一页
    this.totalPages = 1; //最多能分多少页
    this.totalRows = 0; //总数据条数
    this.hasNextPage = false; //是否有下一页
    this.hasPrevPage = false; //是否有上一页
    this.pageSize = pageSize === undefined ? 10 : parseInt(pageSize); //每页显示几条数据，默认为10条
    this.startRow = 0; //起始行
    // this.endRow = 0; //结束行
    this.table = ""; //要查询的表
    this.queryFiled = ""; //要查询的字段
    this.condition = ""; //查询条件
    this.orderBy = ""; //排序
    this.countSql = ""; //查询总条数的sql
    this.pagingSql = ""; //分页sql
    this.sortBy = ""; //排序类型
    this.debug = false; //是否开启调试模式
}

/**
 * 排序类型
 * @param {[type]} sortBy [description]
 */
PagingUtil.prototype.setSortBy = function(sortBy) {
    this.sortBy = sortBy;
    return this;
}

/**
 * 设置按照什么字段排序
 * @param {[type]} orderBy [description]
 */
PagingUtil.prototype.setOrderBy = function(orderBy) {
    this.orderBy = orderBy;
    return this;
}

/**
 * 设置要查询的字段
 * @param {[type]} filed [description]
 */
PagingUtil.prototype.setQueryFiled = function(queryFiled) {
    this.queryFiled = queryFiled;
    return this;
}

/**
 * 设置查询条件
 * @param {[type]} condition [description]
 */
PagingUtil.prototype.setCondition = function(condition) {
    this.condition = condition;
    return this;
}

/**
 * 设置要查询的表
 * @param {[type]} table [description]
 */
PagingUtil.prototype.setTable = function(table) {
    this.table = table;
    return this;

}

/**
 * 获取分页sql
 * @return {[type]} [description]
 */
PagingUtil.prototype.getPagingSql = function() {
    this.queryFiled = this.queryFiled || "*";
    this.condition = this.condition || "";
    this.sortBy = this.sortBy || "ASC";
    var orderBy = "";
    if (this.orderBy === "" && this.sortBy === "") {
        orderBy = "";
    } else {
        if (this.orderBy === "") {
            orderBy = "";
        } else {
            orderBy = "ORDER BY " + this.orderBy + " " + this.sortBy;
        }
    }
    this.pagingSql = "SELECT " + this.queryFiled + " FROM " + this.table + " " + this.condition + " " + orderBy + " LIMIT ?,?";
    return this;
}

/**
 * 获取计算总条数的sql
 * @return {[type]} [description]
 */
PagingUtil.prototype.getCountSql = function() {
    this.condition = this.condition || "";
    this.countSql = "SELECT COUNT(1) AS count FROM " + this.table + " " + this.condition;
    return this;
}

/**
 * 获取数据
 * @return {[type]} [description]
 */
PagingUtil.prototype.getListData = function() {
    return this.listData;
}

/**
 * 设置每页需要显示的条数
 */
PagingUtil.prototype.setPageSize = function(pageSize) {
    this.pageSize = parseInt(pageSize);
    return this;

}

/**
 * 数据一共能分多少页
 * @param {[type]} num [description]
 */
PagingUtil.prototype.setTotalPages = function() {
    var totalPages = 0;
    totalPages = parseInt((this.totalRows - 1) / this.pageSize) + 1;
    this.totalPages = totalPages;
};

/**
 * 设置当前第几页
 * @param {[type]} currentPage [description]
 */
PagingUtil.prototype.setCurrentPage = function(currentPage) {
    this.currentPage = parseInt(currentPage);
    return this;
}

/**
 * 是否打印sql语句
 * @param {[type]} boolean [description]
 */
PagingUtil.prototype.setDebug = function(boolean) {
    this.debug = boolean;
    return this;

}

/**
 * 计算起始行
 * @return {[type]} [description]
 */
PagingUtil.prototype.computedStartRow = function() {
    if (this.currentPage === 1) { //第一页
        this.startRow = 0; //设置起始条数
        this.hasPrevPage = false;
        if (this.totalPages > 1) {
            this.hasNextPage = true;
        } else {
            this.hasNextPage = false;
        }
    } else if (1 < this.currentPage && this.currentPage < this.totalPages) { //中间页
        this.hasNextPage = true;
        this.hasPrevPage = true;
        this.startRow = (this.currentPage - 1) * this.pageSize;
    } else if (this.currentPage === this.totalPages) { //最后一页
        this.startRow = (this.currentPage - 1) * this.pageSize;
        this.hasNextPage = false;
        this.hasPrevPage = true;
    }
}

/**
 * 分页方法
 * @param  {Function} cb [description]
 * @return {[type]}      [description]
 */
PagingUtil.prototype.paging = function(cb) {
    //获取计算总条数的sql;
    var sql1 = this.getCountSql().countSql;
    var _this = this;
    async.series([function(callback) {
        db.execSql(sql1, null, function(err, result) {
            _this.totalRows = result[0].count; //总条数
            _this.setTotalPages(); //总页数
            _this.computedStartRow(); //计算起始行
            callback();
        });
    }, function(callback) {
        //分页sql语句
        var sql2 = _this.getPagingSql().pagingSql;
        var sqlParam = [_this.startRow, _this.pageSize];
        if (_this.debug) {
            console.warn("分页sql语句>>>:::::::::::::::::::::::::::::::::");
            console.log(sql2);
            console.warn("sql语句参数>>>:::::::::::::::::::::::::::::::::");
            console.log(sqlParam)
        }
        db.execSql(sql2, sqlParam, callback);
    }], function(err, results) {
        if (_this.debug) {
            console.warn("分页数据>>>:::::::::::::::::::::::::::::::::");
            console.log(results[1])
        }
        if (err) {
            cb(err, null)
        } else {
            var pagingData = {
                pagingData: results[1],
                currentPage: _this.currentPage,
                totalPages: _this.totalPages,
                totalRows: _this.totalRows,
                hasNextPage: _this.hasNextPage,
                hasPrevPage: _this.hasPrevPage,
                pageSize: _this.pageSize,
                startRow: _this.startRow
            };
            cb(null, pagingData)
        }
    });
}

module.exports = PagingUtil;
<|endoftext|>


<commit_before>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var InputStream = require('./InputStream');
var common = require('./common');
var nodes = require('./nodes');
var pexprs = require('./pexprs');

var Node = nodes.Node;
var TerminalNode = nodes.TerminalNode;

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

var applySpaces_ = new pexprs.Apply('spaces_');

function skipSpacesIfAppropriate(state) {
  var currentApplication = state.applicationStack[state.applicationStack.length - 1];
  var ruleName = currentApplication.ruleName || '';
  if (typeof state.inputStream.source === 'string' && common.isSyntactic(ruleName)) {
    skipSpaces(state);
  }
}

function skipSpaces(state) {
  state.ignoreFailures();
  applySpaces_.eval(state);
  state.bindings.pop();
  state.recordFailures();
}

// Evaluate the expression and return true if it succeeded, otherwise false.
// On success, the bindings will have `this.arity` more elements than before,
// and the position could be anywhere. On failure, the bindings and position
// will be unchanged.
pexprs.PExpr.prototype.eval = function(state) {
  var origPos = state.inputStream.pos;
  var origNumBindings = state.bindings.length;
  var origTrace = state.trace;
  if (state.isTracing()) {
    state.trace = [];
  }

  // Do the actual evaluation.
  var ans = this._eval(state, state.inputStream, origPos);

  if (state.isTracing()) {
    var traceEntry = state.getTraceEntry(origPos, this, ans);
    origTrace.push(traceEntry);
    state.trace = origTrace;
  }

  if (!ans) {
    this.maybeRecordFailure(state, origPos);

    // Reset the position and the bindings.
    state.inputStream.pos = origPos;
    while (state.bindings.length > origNumBindings) {
      state.bindings.pop();
    }
  }
  return ans;
};

// Evaluate the expression and return true if it succeeded, otherwise false.
// This should not be called directly except by `eval`.
//
// The contract of this method is as follows:
// * When the return value is true:
//   -- bindings will have expr.arity more elements than before
// * When the return value is false:
//   -- bindings will have exactly the same number of elements as before
//   -- position could be anywhere

pexprs.PExpr.prototype._eval = common.abstract;

pexprs.anything._eval = function(state, inputStream, origPos) {
  var value = inputStream.next();
  if (value === common.fail) {
    return false;
  } else {
    var interval = inputStream.intervalFrom(origPos);
    state.bindings.push(new TerminalNode(state.grammar, value, interval));
    return true;
  }
};

pexprs.end._eval = function(state, inputStream, origPos) {
  if (state.inputStream.atEnd()) {
    var interval = inputStream.intervalFrom(inputStream.pos);
    state.bindings.push(new TerminalNode(state.grammar, undefined, interval));
    return true;
  } else {
    return false;
  }
};

pexprs.Prim.prototype._eval = function(state, inputStream, origPos) {
  if (this.match(inputStream) === common.fail) {
    state.recordFailure(origPos, this);
    return false;
  } else {
    var interval = inputStream.intervalFrom(origPos);
    var primitiveValue = this instanceof pexprs.RegExpPrim ?
        inputStream.source[origPos] :
        this.obj;
    state.bindings.push(new TerminalNode(state.grammar, primitiveValue, interval));
    return true;
  }
};

pexprs.Prim.prototype.match = function(inputStream) {
  return inputStream.matchExactly(this.obj);
};

pexprs.StringPrim.prototype.match = function(inputStream) {
  return inputStream.matchString(this.obj);
};

pexprs.RegExpPrim.prototype.match = function(inputStream) {
  return inputStream.matchRegExp(this.obj);
};

pexprs.Param.prototype._eval = function(state, inputStream, origPos) {
  var currentApplication = state.applicationStack[state.applicationStack.length - 1];
  return currentApplication.params[this.index].eval(state);
};

pexprs.Alt.prototype._eval = function(state, inputStream, origPos) {
  for (var idx = 0; idx < this.terms.length; idx++) {
    if (this.terms[idx].eval(state)) {
      return true;
    }
  }
  return false;
};

pexprs.Seq.prototype._eval = function(state, inputStream, origPos) {
  for (var idx = 0; idx < this.factors.length; idx++) {
    skipSpacesIfAppropriate(state);
    var factor = this.factors[idx];
    if (!factor.eval(state)) {
      return false;
    }
  }
  return true;
};

pexprs.Iter.prototype._eval = function(state, inputStream, origPos) {
  var arity = this.getArity();
  var columns = [];
  while (columns.length < arity) {
    columns.push([]);
  }
  var numMatches = 0;
  var idx;
  while (numMatches < this.maxNumMatches) {
    var backtrackPos = inputStream.pos;
    skipSpacesIfAppropriate(state);
    if (this.expr.eval(state)) {
      numMatches++;
      var row = state.bindings.splice(state.bindings.length - arity, arity);
      for (idx = 0; idx < row.length; idx++) {
        columns[idx].push(row[idx]);
      }
    } else {
      inputStream.pos = backtrackPos;
      break;
    }
  }
  if (numMatches < this.minNumMatches) {
    return false;
  }
  for (idx = 0; idx < columns.length; idx++) {
    var interval = inputStream.intervalFrom(origPos);
    state.bindings.push(new Node(state.grammar, '_iter', columns[idx], interval));
  }
  return true;
};

pexprs.Not.prototype._eval = function(state, inputStream, origPos) {
  // TODO:
  // * Right now we're just throwing away all of the failures that happen inside a `not`,
  //   and recording `this` as a failed expression.
  // * Double negation should be equivalent to lookahead, but that's not the case right now wrt
  //   failures. E.g., ~~'foo' produces a failure for ~~'foo', but maybe it should produce
  //   a failure for 'foo' instead.

  var origNumBindings = state.bindings.length;
  state.ignoreFailures();
  var ans = this.expr.eval(state);
  state.recordFailures();
  if (ans) {
    while (state.bindings.length > origNumBindings) {
      state.bindings.pop();
    }
    return false;
  } else {
    inputStream.pos = origPos;
    return true;
  }
};

pexprs.Lookahead.prototype._eval = function(state, inputStream, origPos) {
  if (this.expr.eval(state)) {
    inputStream.pos = origPos;
    return true;
  } else {
    return false;
  }
};

pexprs.Arr.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (Array.isArray(obj)) {
    var objInputStream = InputStream.newFor(obj);
    state.pushInputStream(objInputStream);
    var ans = this.expr.eval(state) && state.inputStream.atEnd();
    state.popInputStream();
    return ans;
  } else {
    return false;
  }
};

pexprs.Str.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (typeof obj === 'string') {
    var strInputStream = InputStream.newFor(obj);
    state.pushInputStream(strInputStream);
    var ans = this.expr.eval(state) && (skipSpacesIfAppropriate(state), state.inputStream.atEnd());
    state.popInputStream();
    return ans;
  } else {
    return false;
  }
};

pexprs.Obj.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (obj !== common.fail && obj && (typeof obj === 'object' || typeof obj === 'function')) {
    var numOwnPropertiesMatched = 0;
    for (var idx = 0; idx < this.properties.length; idx++) {
      var property = this.properties[idx];
      if (!obj.hasOwnProperty(property.name)) {
        return false;
      }
      var value = obj[property.name];
      var valueInputStream = InputStream.newFor([value]);
      state.pushInputStream(valueInputStream);
      var matched = property.pattern.eval(state) && state.inputStream.atEnd();
      state.popInputStream();
      if (!matched) {
        return false;
      }
      numOwnPropertiesMatched++;
    }
    if (this.isLenient) {
      var remainder = {};
      for (var p in obj) {
        if (obj.hasOwnProperty(p) && this.properties.indexOf(p) < 0) {
          remainder[p] = obj[p];
        }
      }
      var interval = inputStream.intervalFrom(origPos);
      state.bindings.push(new TerminalNode(state.grammar, remainder, interval));
      return true;
    } else {
      return numOwnPropertiesMatched === Object.keys(obj).length;
    }
  } else {
    return false;
  }
};

function useMemoizedResult(state, application, memoRecOrLR) {
  var inputStream = state.inputStream;
  var bindings = state.bindings;

  inputStream.pos = memoRecOrLR.pos;
  if (memoRecOrLR.failureDescriptor) {
    state.recordFailures(memoRecOrLR.failureDescriptor, application);
  }
  if (state.isTracing()) {
    state.trace.push(memoRecOrLR.traceEntry);
  }
  if (memoRecOrLR.value) {
    bindings.push(memoRecOrLR.value);
    return true;
  }
  return false;
}

pexprs.Apply.prototype._eval = function(state, inputStream) {
  var grammar = state.grammar;
  var bindings = state.bindings;

  var actuals = state.applicationStack.length > 1 ?
      state.applicationStack[state.applicationStack.length - 1].params :
      [];
  var app = this.substituteParams(actuals);
  var ruleName = app.ruleName;
  var memoKey = app.toMemoKey();

  if (common.isSyntactic(ruleName)) {
    skipSpaces(state);
  }

  var origPosInfo = state.getCurrentPosInfo();

  var memoRec = origPosInfo.memo[memoKey];
  var currentLR;
  if (memoRec && origPosInfo.shouldUseMemoizedResult(memoRec)) {
    return useMemoizedResult(state, this, memoRec);
  } else if (origPosInfo.isActive(app)) {
    currentLR = origPosInfo.getCurrentLeftRecursion();
    if (currentLR && currentLR.memoKey === memoKey) {
      origPosInfo.updateInvolvedApplications();
      return useMemoizedResult(state, this, currentLR);
    } else {
      origPosInfo.startLeftRecursion(app);
      return false;
    }
  } else {
    var body = grammar.ruleDict[ruleName];
    var origPos = inputStream.pos;
    origPosInfo.enter(app);
    if (body.description) {
      state.ignoreFailures();
    }
    var value = app.evalOnce(body, state, inputStream, origPos);
    currentLR = origPosInfo.getCurrentLeftRecursion();
    if (currentLR) {
      if (currentLR.memoKey === memoKey) {
        value = app.handleLeftRecursion(body, state, origPos, currentLR, value);
        origPosInfo.memo[memoKey] = {
          pos: inputStream.pos,
          value: value,
          involvedApplications: currentLR.involvedApplications
        };
        origPosInfo.endLeftRecursion(app);
      } else if (!currentLR.involvedApplications[memoKey]) {
        // Only memoize if this application is not involved in the current left recursion
        origPosInfo.memo[memoKey] = {pos: inputStream.pos, value: value};
      }
    } else {
      origPosInfo.memo[memoKey] = {pos: inputStream.pos, value: value};
    }
    if (body.description) {
      state.recordFailures();
      if (!value) {
        state.recordFailure(origPos, app);
      }
    }
    // Record trace information in the memo table, so that it is
    // available if the memoized result is used later.
    if (state.isTracing() && origPosInfo.memo[memoKey]) {
      var entry = state.getTraceEntry(origPos, app, value);
      entry.setLeftRecursive(currentLR && (currentLR.memoKey === memoKey));
      origPosInfo.memo[memoKey].traceEntry = entry;
    }
    var ans;
    if (value) {
      bindings.push(value);
      if (state.applicationStack.length === 1) {
        if (common.isSyntactic(ruleName)) {
          skipSpaces(state);
        }
        ans = pexprs.end.eval(state);
        bindings.pop();
      } else {
        ans = true;
      }
    } else {
      ans = false;
    }

    origPosInfo.exit();
    return ans;
  }
};

pexprs.Apply.prototype.evalOnce = function(expr, state, inputStream, origPos) {
  if (expr.eval(state)) {
    var arity = expr.getArity();
    var bindings = state.bindings.splice(state.bindings.length - arity, arity);
    var ans = new Node(state.grammar, this.ruleName, bindings, inputStream.intervalFrom(origPos));
    return ans;
  } else {
    return false;
  }
};

pexprs.Apply.prototype.handleLeftRecursion = function(body, state, origPos, currentLR, seedValue) {
  if (!seedValue) {
    return seedValue;
  }

  var inputStream = state.inputStream;
  var value = seedValue;
  currentLR.value = seedValue;
  currentLR.pos = inputStream.pos;

  while (true) {
    if (state.isTracing()) {
      currentLR.traceEntry = common.clone(state.trace[state.trace.length - 1]);
    }

    inputStream.pos = origPos;
    value = this.evalOnce(body, state, inputStream, origPos);
    if (value && inputStream.pos > currentLR.pos) {
      // The left-recursive result was expanded -- keep looping.
      currentLR.value = value;
      currentLR.pos = inputStream.pos;
    } else {
      // Failed to expand the result.
      inputStream.pos = currentLR.pos;
      if (state.isTracing()) {
        state.trace.pop();  // Drop last trace entry since `value` was unused.
      }
      break;
    }
  }
  return currentLR.value;
};
<commit_msg>nit: renamed skiSpacesIfAppropriate -> skipSpacesIfInsideSyntacticRule<commit_after>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var InputStream = require('./InputStream');
var common = require('./common');
var nodes = require('./nodes');
var pexprs = require('./pexprs');

var Node = nodes.Node;
var TerminalNode = nodes.TerminalNode;

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

var applySpaces_ = new pexprs.Apply('spaces_');

function skipSpacesIfInSyntacticRule(state) {
  var currentApplication = state.applicationStack[state.applicationStack.length - 1];
  var ruleName = currentApplication.ruleName || '';
  if (typeof state.inputStream.source === 'string' && common.isSyntactic(ruleName)) {
    skipSpaces(state);
  }
}

function skipSpaces(state) {
  state.ignoreFailures();
  applySpaces_.eval(state);
  state.bindings.pop();
  state.recordFailures();
}

// Evaluate the expression and return true if it succeeded, otherwise false.
// On success, the bindings will have `this.arity` more elements than before,
// and the position could be anywhere. On failure, the bindings and position
// will be unchanged.
pexprs.PExpr.prototype.eval = function(state) {
  var origPos = state.inputStream.pos;
  var origNumBindings = state.bindings.length;
  var origTrace = state.trace;
  if (state.isTracing()) {
    state.trace = [];
  }

  // Do the actual evaluation.
  var ans = this._eval(state, state.inputStream, origPos);

  if (state.isTracing()) {
    var traceEntry = state.getTraceEntry(origPos, this, ans);
    origTrace.push(traceEntry);
    state.trace = origTrace;
  }

  if (!ans) {
    this.maybeRecordFailure(state, origPos);

    // Reset the position and the bindings.
    state.inputStream.pos = origPos;
    while (state.bindings.length > origNumBindings) {
      state.bindings.pop();
    }
  }
  return ans;
};

// Evaluate the expression and return true if it succeeded, otherwise false.
// This should not be called directly except by `eval`.
//
// The contract of this method is as follows:
// * When the return value is true:
//   -- bindings will have expr.arity more elements than before
// * When the return value is false:
//   -- bindings will have exactly the same number of elements as before
//   -- position could be anywhere

pexprs.PExpr.prototype._eval = common.abstract;

pexprs.anything._eval = function(state, inputStream, origPos) {
  var value = inputStream.next();
  if (value === common.fail) {
    return false;
  } else {
    var interval = inputStream.intervalFrom(origPos);
    state.bindings.push(new TerminalNode(state.grammar, value, interval));
    return true;
  }
};

pexprs.end._eval = function(state, inputStream, origPos) {
  if (state.inputStream.atEnd()) {
    var interval = inputStream.intervalFrom(inputStream.pos);
    state.bindings.push(new TerminalNode(state.grammar, undefined, interval));
    return true;
  } else {
    return false;
  }
};

pexprs.Prim.prototype._eval = function(state, inputStream, origPos) {
  if (this.match(inputStream) === common.fail) {
    state.recordFailure(origPos, this);
    return false;
  } else {
    var interval = inputStream.intervalFrom(origPos);
    var primitiveValue = this instanceof pexprs.RegExpPrim ?
        inputStream.source[origPos] :
        this.obj;
    state.bindings.push(new TerminalNode(state.grammar, primitiveValue, interval));
    return true;
  }
};

pexprs.Prim.prototype.match = function(inputStream) {
  return inputStream.matchExactly(this.obj);
};

pexprs.StringPrim.prototype.match = function(inputStream) {
  return inputStream.matchString(this.obj);
};

pexprs.RegExpPrim.prototype.match = function(inputStream) {
  return inputStream.matchRegExp(this.obj);
};

pexprs.Param.prototype._eval = function(state, inputStream, origPos) {
  var currentApplication = state.applicationStack[state.applicationStack.length - 1];
  return currentApplication.params[this.index].eval(state);
};

pexprs.Alt.prototype._eval = function(state, inputStream, origPos) {
  for (var idx = 0; idx < this.terms.length; idx++) {
    if (this.terms[idx].eval(state)) {
      return true;
    }
  }
  return false;
};

pexprs.Seq.prototype._eval = function(state, inputStream, origPos) {
  for (var idx = 0; idx < this.factors.length; idx++) {
    skipSpacesIfInSyntacticRule(state);
    var factor = this.factors[idx];
    if (!factor.eval(state)) {
      return false;
    }
  }
  return true;
};

pexprs.Iter.prototype._eval = function(state, inputStream, origPos) {
  var arity = this.getArity();
  var columns = [];
  while (columns.length < arity) {
    columns.push([]);
  }
  var numMatches = 0;
  var idx;
  while (numMatches < this.maxNumMatches) {
    var backtrackPos = inputStream.pos;
    skipSpacesIfInSyntacticRule(state);
    if (this.expr.eval(state)) {
      numMatches++;
      var row = state.bindings.splice(state.bindings.length - arity, arity);
      for (idx = 0; idx < row.length; idx++) {
        columns[idx].push(row[idx]);
      }
    } else {
      inputStream.pos = backtrackPos;
      break;
    }
  }
  if (numMatches < this.minNumMatches) {
    return false;
  }
  for (idx = 0; idx < columns.length; idx++) {
    var interval = inputStream.intervalFrom(origPos);
    state.bindings.push(new Node(state.grammar, '_iter', columns[idx], interval));
  }
  return true;
};

pexprs.Not.prototype._eval = function(state, inputStream, origPos) {
  // TODO:
  // * Right now we're just throwing away all of the failures that happen inside a `not`,
  //   and recording `this` as a failed expression.
  // * Double negation should be equivalent to lookahead, but that's not the case right now wrt
  //   failures. E.g., ~~'foo' produces a failure for ~~'foo', but maybe it should produce
  //   a failure for 'foo' instead.

  var origNumBindings = state.bindings.length;
  state.ignoreFailures();
  var ans = this.expr.eval(state);
  state.recordFailures();
  if (ans) {
    while (state.bindings.length > origNumBindings) {
      state.bindings.pop();
    }
    return false;
  } else {
    inputStream.pos = origPos;
    return true;
  }
};

pexprs.Lookahead.prototype._eval = function(state, inputStream, origPos) {
  if (this.expr.eval(state)) {
    inputStream.pos = origPos;
    return true;
  } else {
    return false;
  }
};

pexprs.Arr.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (Array.isArray(obj)) {
    var objInputStream = InputStream.newFor(obj);
    state.pushInputStream(objInputStream);
    var ans = this.expr.eval(state) && state.inputStream.atEnd();
    state.popInputStream();
    return ans;
  } else {
    return false;
  }
};

pexprs.Str.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (typeof obj === 'string') {
    var strInputStream = InputStream.newFor(obj);
    state.pushInputStream(strInputStream);
    var ans =
        this.expr.eval(state) && (skipSpacesIfInSyntacticRule(state), state.inputStream.atEnd());
    state.popInputStream();
    return ans;
  } else {
    return false;
  }
};

pexprs.Obj.prototype._eval = function(state, inputStream, origPos) {
  var obj = inputStream.next();
  if (obj !== common.fail && obj && (typeof obj === 'object' || typeof obj === 'function')) {
    var numOwnPropertiesMatched = 0;
    for (var idx = 0; idx < this.properties.length; idx++) {
      var property = this.properties[idx];
      if (!obj.hasOwnProperty(property.name)) {
        return false;
      }
      var value = obj[property.name];
      var valueInputStream = InputStream.newFor([value]);
      state.pushInputStream(valueInputStream);
      var matched = property.pattern.eval(state) && state.inputStream.atEnd();
      state.popInputStream();
      if (!matched) {
        return false;
      }
      numOwnPropertiesMatched++;
    }
    if (this.isLenient) {
      var remainder = {};
      for (var p in obj) {
        if (obj.hasOwnProperty(p) && this.properties.indexOf(p) < 0) {
          remainder[p] = obj[p];
        }
      }
      var interval = inputStream.intervalFrom(origPos);
      state.bindings.push(new TerminalNode(state.grammar, remainder, interval));
      return true;
    } else {
      return numOwnPropertiesMatched === Object.keys(obj).length;
    }
  } else {
    return false;
  }
};

function useMemoizedResult(state, application, memoRecOrLR) {
  var inputStream = state.inputStream;
  var bindings = state.bindings;

  inputStream.pos = memoRecOrLR.pos;
  if (memoRecOrLR.failureDescriptor) {
    state.recordFailures(memoRecOrLR.failureDescriptor, application);
  }
  if (state.isTracing()) {
    state.trace.push(memoRecOrLR.traceEntry);
  }
  if (memoRecOrLR.value) {
    bindings.push(memoRecOrLR.value);
    return true;
  }
  return false;
}

pexprs.Apply.prototype._eval = function(state, inputStream) {
  var grammar = state.grammar;
  var bindings = state.bindings;

  var actuals = state.applicationStack.length > 1 ?
      state.applicationStack[state.applicationStack.length - 1].params :
      [];
  var app = this.substituteParams(actuals);
  var ruleName = app.ruleName;
  var memoKey = app.toMemoKey();

  if (common.isSyntactic(ruleName)) {
    skipSpaces(state);
  }

  var origPosInfo = state.getCurrentPosInfo();

  var memoRec = origPosInfo.memo[memoKey];
  var currentLR;
  if (memoRec && origPosInfo.shouldUseMemoizedResult(memoRec)) {
    return useMemoizedResult(state, this, memoRec);
  } else if (origPosInfo.isActive(app)) {
    currentLR = origPosInfo.getCurrentLeftRecursion();
    if (currentLR && currentLR.memoKey === memoKey) {
      origPosInfo.updateInvolvedApplications();
      return useMemoizedResult(state, this, currentLR);
    } else {
      origPosInfo.startLeftRecursion(app);
      return false;
    }
  } else {
    var body = grammar.ruleDict[ruleName];
    var origPos = inputStream.pos;
    origPosInfo.enter(app);
    if (body.description) {
      state.ignoreFailures();
    }
    var value = app.evalOnce(body, state, inputStream, origPos);
    currentLR = origPosInfo.getCurrentLeftRecursion();
    if (currentLR) {
      if (currentLR.memoKey === memoKey) {
        value = app.handleLeftRecursion(body, state, origPos, currentLR, value);
        origPosInfo.memo[memoKey] = {
          pos: inputStream.pos,
          value: value,
          involvedApplications: currentLR.involvedApplications
        };
        origPosInfo.endLeftRecursion(app);
      } else if (!currentLR.involvedApplications[memoKey]) {
        // Only memoize if this application is not involved in the current left recursion
        origPosInfo.memo[memoKey] = {pos: inputStream.pos, value: value};
      }
    } else {
      origPosInfo.memo[memoKey] = {pos: inputStream.pos, value: value};
    }
    if (body.description) {
      state.recordFailures();
      if (!value) {
        state.recordFailure(origPos, app);
      }
    }
    // Record trace information in the memo table, so that it is
    // available if the memoized result is used later.
    if (state.isTracing() && origPosInfo.memo[memoKey]) {
      var entry = state.getTraceEntry(origPos, app, value);
      entry.setLeftRecursive(currentLR && (currentLR.memoKey === memoKey));
      origPosInfo.memo[memoKey].traceEntry = entry;
    }
    var ans;
    if (value) {
      bindings.push(value);
      if (state.applicationStack.length === 1) {
        if (common.isSyntactic(ruleName)) {
          skipSpaces(state);
        }
        ans = pexprs.end.eval(state);
        bindings.pop();
      } else {
        ans = true;
      }
    } else {
      ans = false;
    }

    origPosInfo.exit();
    return ans;
  }
};

pexprs.Apply.prototype.evalOnce = function(expr, state, inputStream, origPos) {
  if (expr.eval(state)) {
    var arity = expr.getArity();
    var bindings = state.bindings.splice(state.bindings.length - arity, arity);
    var ans = new Node(state.grammar, this.ruleName, bindings, inputStream.intervalFrom(origPos));
    return ans;
  } else {
    return false;
  }
};

pexprs.Apply.prototype.handleLeftRecursion = function(body, state, origPos, currentLR, seedValue) {
  if (!seedValue) {
    return seedValue;
  }

  var inputStream = state.inputStream;
  var value = seedValue;
  currentLR.value = seedValue;
  currentLR.pos = inputStream.pos;

  while (true) {
    if (state.isTracing()) {
      currentLR.traceEntry = common.clone(state.trace[state.trace.length - 1]);
    }

    inputStream.pos = origPos;
    value = this.evalOnce(body, state, inputStream, origPos);
    if (value && inputStream.pos > currentLR.pos) {
      // The left-recursive result was expanded -- keep looping.
      currentLR.value = value;
      currentLR.pos = inputStream.pos;
    } else {
      // Failed to expand the result.
      inputStream.pos = currentLR.pos;
      if (state.isTracing()) {
        state.trace.pop();  // Drop last trace entry since `value` was unused.
      }
      break;
    }
  }
  return currentLR.value;
};
<|endoftext|>


<commit_before>/* eslint-env browser */
'use strict'

let	d3 = require('d3'),
	tntTree = require('tnt.tree'),
	parser = require('tnt.newick')

let tree = tntTree()

let treeCreated = false
let numCommas = 0
let expandedNode = tntTree.node_display.circle()
let collapsedNode = tntTree.node_display.triangle()

exports.makeTree = function(newickString) {
	console.log(document.getElementsByClassName('tnt_groupDiv'))
	if (document.getElementsByClassName('tnt_groupDiv').length !== 0) {
		let existingTree = document.getElementsByClassName('tnt_groupDiv')[0]
		document.getElementById('treeBox').removeChild(existingTree)
	}

	let treeBox = document.getElementById('treeBox')
	numCommas = 0
	for (let x = 0; x < newickString.length; x++) {
		if (newickString.charAt(x) === ',')
			numCommas++
	}

	let fontSizeOfTreeLeafs = 12

	tree
		.data(parser.parse_newick(newickString))
		.node_display(node_display)
		.label(tntTree.label
			.text()
			.fontsize(fontSizeOfTreeLeafs)
			.height(window.innerHeight * 0.69 / (numCommas + 1))
		)
		.layout(tntTree.layout.vertical()
			.width(window.innerWidth * 0.58)
			.scale(false)
		)
	tree(treeBox)
}

let node_display = tree.node_display()
			.size(3)
			.fill("black")
			.display (function (node) {
			if (node.is_collapsed()) {
				collapsedNode.display().call(this, node)
			} else {
				expandedNode.display().call(this, node)
			}
		})

function resetPar() {
  numOpenPar=0
  numClosedPar=0
}

function submitFile() {
	document.getElementById("errorspot").innerHTML = ""
	let fileInput = document.getElementById("fileInput")
	console.log(fileInput.files[0])
	let newick = ''

	let file = fileInput.files[0]
	let reader = new FileReader()

	reader.onload = function(e) {
		newick = reader.result
		makeTree(newick)
	}
	reader.readAsText(file)
}

function updateVertical() {
	tree.layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false))
	tree.update()
}

function updateRadial()
{
  {
			tree.layout(tnt.tree.layout.radial().width(Math.min(window.innerWidth*0.58, window.innerHeight*0.58)).scale(false))
			tree.update()
		}
}

 function download () {
		let pngExporter = tnt.utils.png()
			.filename("treeSample.png")
		pngExporter(d3.select("svg"))
	}

function fitscreen () {
  tree.node_display(node_display)
		.label (tnt.tree.label.text()
		.fontsize(12)
	 .height(window.innerHeight*0.69/(numCommas+1))
			)
 .layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false))
  tree.update()
}

tree.on('click', function(node) {
	node.toggle()
	tree.update()
})

// module.exports = 'phylogician'
<commit_msg>again removed unnecessary variables<commit_after>/* eslint-env browser */
'use strict'

let	d3 = require('d3'),
	tntTree = require('tnt.tree'),
	parser = require('tnt.newick')

let tree = tntTree()
let numCommas = 0
let expandedNode = tntTree.node_display.circle()
let collapsedNode = tntTree.node_display.triangle()

exports.makeTree = function(newickString) {
	console.log(document.getElementsByClassName('tnt_groupDiv'))
	if (document.getElementsByClassName('tnt_groupDiv').length !== 0) {
		let existingTree = document.getElementsByClassName('tnt_groupDiv')[0]
		document.getElementById('treeBox').removeChild(existingTree)
	}

	let treeBox = document.getElementById('treeBox')
	numCommas = 0
	for (let x = 0; x < newickString.length; x++) {
		if (newickString.charAt(x) === ',')
			numCommas++
	}

	let fontSizeOfTreeLeafs = 12

	tree
		.data(parser.parse_newick(newickString))
		.node_display(node_display)
		.label(tntTree.label
			.text()
			.fontsize(fontSizeOfTreeLeafs)
			.height(window.innerHeight * 0.69 / (numCommas + 1))
		)
		.layout(tntTree.layout.vertical()
			.width(window.innerWidth * 0.58)
			.scale(false)
		)
	tree(treeBox)
}

let node_display = tree.node_display()
			.size(3)
			.fill("black")
			.display (function (node) {
			if (node.is_collapsed()) {
				collapsedNode.display().call(this, node)
			} else {
				expandedNode.display().call(this, node)
			}
		})

function resetPar() {
  numOpenPar=0
  numClosedPar=0
}

function submitFile() {
	document.getElementById("errorspot").innerHTML = ""
	let fileInput = document.getElementById("fileInput")
	console.log(fileInput.files[0])
	let newick = ''

	let file = fileInput.files[0]
	let reader = new FileReader()

	reader.onload = function(e) {
		newick = reader.result
		makeTree(newick)
	}
	reader.readAsText(file)
}

function updateVertical() {
	tree.layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false))
	tree.update()
}

function updateRadial()
{
  {
			tree.layout(tnt.tree.layout.radial().width(Math.min(window.innerWidth*0.58, window.innerHeight*0.58)).scale(false))
			tree.update()
		}
}

 function download () {
		let pngExporter = tnt.utils.png()
			.filename("treeSample.png")
		pngExporter(d3.select("svg"))
	}

function fitscreen () {
  tree.node_display(node_display)
		.label (tnt.tree.label.text()
		.fontsize(12)
	 .height(window.innerHeight*0.69/(numCommas+1))
			)
 .layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false))
  tree.update()
}

tree.on('click', function(node) {
	node.toggle()
	tree.update()
})

// module.exports = 'phylogician'
<|endoftext|>


<commit_before>exports.init = function(grunt) {
  var path = require('path');
  var ast = require('cmd-util').ast;
  var iduri = require('cmd-util').iduri;
  var _ = grunt.util._;

  var exports = {};

  exports.jsParser = function(fileObj, options) {
    grunt.log.writeln('Transport ' + fileObj.src + ' -> ' + fileObj.dest);
    var data = fileObj.srcData || grunt.file.read(fileObj.src);
    var astCache = ast.getAst(data);

    var meta = ast.parseFirst(astCache);

    if (!meta) {
      grunt.log.warn('found non cmd module "' + fileObj.src + '"');
      // do nothing
      return;
    }

    if (meta.id) {
      grunt.log.warn('found id in "' + fileObj.src + '"');
      grunt.file.write(fileObj.dest, data);
      return;
    }
    var deps = parseDependencies(fileObj.src, options);

    if (deps.length) {
      grunt.log.writeln('found dependencies ' + deps);
    } else {
      grunt.log.writeln('found no dependencies');
    }

    astCache = ast.modify(astCache, {
      id: options.idleading + fileObj.name.replace(/\.js$/, ''),
      dependencies: deps,
      require: function(v) {
        return iduri.parseAlias(options, v);
      }
    });
    data = astCache.print_to_string(options.uglify);
    grunt.file.write(fileObj.dest, data);

    if (!options.debug) {
      return;
    }
    var dest = fileObj.dest.replace(/\.js$/, '-debug.js');
    grunt.log.writeln('Creating debug file: ' + dest);

    astCache = ast.modify(data, function(v) {
      var ext = path.extname(v);
      if (ext && options.parsers[ext]) {
        return v.replace(new RegExp('\\' + ext + '$'), '-debug' + ext);
      } else {
        return v + '-debug';
      }
    });
    data = astCache.print_to_string(options.uglify);
    grunt.file.write(dest, data);
  };

  // helpers
  // ----------------
  function moduleDependencies(id, options) {
    var alias = iduri.parseAlias(options, id);

    if (iduri.isAlias(options, id) && alias === id) {
      // usually this is "$"
      return [];
    }

    var file = iduri.appendext(alias);
    if (!/\.js$/.test(file)) return [];

    var fpath;
    options.paths.some(function(base) {
      var filepath = path.join(base, file);
      if (grunt.file.exists(filepath)) {
        grunt.log.verbose.writeln('find module "' + filepath + '"');
        fpath = filepath;
        return true;
      }
    });
    if (!fpath) {
      grunt.log.warn("can't find module " + alias);
      return [];
    }
    var data = grunt.file.read(fpath);
    var parsed = ast.parse(data);
    var deps = [];

    var ids = parsed.map(function(meta) {
      return meta.id;
    });

    parsed.forEach(function(meta) {
      meta.dependencies.forEach(function(dep) {
        dep = iduri.absolute(alias, dep);
        if (!_.contains(deps, dep) && !_.contains(ids, dep) && !_.contains(ids, dep.replace(/\.js$/, ''))) {
          deps.push(dep);
        }
      });
    });
    return deps;
  }

  function parseDependencies(fpath, options) {
    var rootpath = fpath;

    function relativeDependencies(fpath, options, basefile) {
      if (basefile) {
        fpath = path.join(path.dirname(basefile), fpath);
      }
      fpath = iduri.appendext(fpath);

      var deps = [];
      var moduleDeps = {};

      var data = grunt.file.read(fpath);
      var parsed = ast.parseFirst(data);
      parsed.dependencies.forEach(function(id) {

        if (id.charAt(0) === '.') {
          // fix nested relative dependencies
          if (basefile) {
            var altId = path.join(path.dirname(fpath), id);
            altId = path.relative(path.dirname(rootpath), altId);
            altId = altId.replace(/\\/g, '/');
            if (altId.charAt(0) !== '.') {
              altId = './' + altId;
            }
            deps.push(altId);
          } else {
            deps.push(id);
          }
          if (/\.js$/.test(iduri.appendext(id))) {
            deps = grunt.util._.union(deps, relativeDependencies(id, options, fpath));
          }
        } else if (!moduleDeps[id]) {
          var alias = iduri.parseAlias(options, id);
          deps.push(alias);

          // don't parse no javascript dependencies
          var ext = path.extname(alias);
          if (ext && ext !== '.js') return;

          var mdeps = moduleDependencies(id, options);
          moduleDeps[id] = mdeps;
          deps = grunt.util._.union(deps, mdeps);
        }
      });
      return deps;
    }

    return relativeDependencies(fpath, options);
  }

  return exports;
};
<commit_msg>detect if the file exists. fix #17<commit_after>exports.init = function(grunt) {
  var path = require('path');
  var ast = require('cmd-util').ast;
  var iduri = require('cmd-util').iduri;
  var _ = grunt.util._;

  var exports = {};

  exports.jsParser = function(fileObj, options) {
    grunt.log.writeln('Transport ' + fileObj.src + ' -> ' + fileObj.dest);
    var data = fileObj.srcData || grunt.file.read(fileObj.src);
    var astCache = ast.getAst(data);

    var meta = ast.parseFirst(astCache);

    if (!meta) {
      grunt.log.warn('found non cmd module "' + fileObj.src + '"');
      // do nothing
      return;
    }

    if (meta.id) {
      grunt.log.warn('found id in "' + fileObj.src + '"');
      grunt.file.write(fileObj.dest, data);
      return;
    }
    var deps = parseDependencies(fileObj.src, options);

    if (deps.length) {
      grunt.log.writeln('found dependencies ' + deps);
    } else {
      grunt.log.writeln('found no dependencies');
    }

    astCache = ast.modify(astCache, {
      id: options.idleading + fileObj.name.replace(/\.js$/, ''),
      dependencies: deps,
      require: function(v) {
        return iduri.parseAlias(options, v);
      }
    });
    data = astCache.print_to_string(options.uglify);
    grunt.file.write(fileObj.dest, data);

    if (!options.debug) {
      return;
    }
    var dest = fileObj.dest.replace(/\.js$/, '-debug.js');
    grunt.log.writeln('Creating debug file: ' + dest);

    astCache = ast.modify(data, function(v) {
      var ext = path.extname(v);
      if (ext && options.parsers[ext]) {
        return v.replace(new RegExp('\\' + ext + '$'), '-debug' + ext);
      } else {
        return v + '-debug';
      }
    });
    data = astCache.print_to_string(options.uglify);
    grunt.file.write(dest, data);
  };

  // helpers
  // ----------------
  function moduleDependencies(id, options) {
    var alias = iduri.parseAlias(options, id);

    if (iduri.isAlias(options, id) && alias === id) {
      // usually this is "$"
      return [];
    }

    var file = iduri.appendext(alias);
    if (!/\.js$/.test(file)) return [];

    var fpath;
    options.paths.some(function(base) {
      var filepath = path.join(base, file);
      if (grunt.file.exists(filepath)) {
        grunt.log.verbose.writeln('find module "' + filepath + '"');
        fpath = filepath;
        return true;
      }
    });
    if (!fpath) {
      grunt.log.warn("can't find module " + alias);
      return [];
    }
    if (!grunt.file.exists(fpath)) {
      grunt.log.warn("can't find " + fpath);
      return [];
    }
    var data = grunt.file.read(fpath);
    var parsed = ast.parse(data);
    var deps = [];

    var ids = parsed.map(function(meta) {
      return meta.id;
    });

    parsed.forEach(function(meta) {
      meta.dependencies.forEach(function(dep) {
        dep = iduri.absolute(alias, dep);
        if (!_.contains(deps, dep) && !_.contains(ids, dep) && !_.contains(ids, dep.replace(/\.js$/, ''))) {
          deps.push(dep);
        }
      });
    });
    return deps;
  }

  function parseDependencies(fpath, options) {
    var rootpath = fpath;

    function relativeDependencies(fpath, options, basefile) {
      if (basefile) {
        fpath = path.join(path.dirname(basefile), fpath);
      }
      fpath = iduri.appendext(fpath);

      var deps = [];
      var moduleDeps = {};

      if (!grunt.file.exists(fpath)) {
        grunt.log.warn("can't find " + fpath);
        return [];
      }
      var data = grunt.file.read(fpath);
      var parsed = ast.parseFirst(data);
      parsed.dependencies.forEach(function(id) {

        if (id.charAt(0) === '.') {
          // fix nested relative dependencies
          if (basefile) {
            var altId = path.join(path.dirname(fpath), id);
            altId = path.relative(path.dirname(rootpath), altId);
            altId = altId.replace(/\\/g, '/');
            if (altId.charAt(0) !== '.') {
              altId = './' + altId;
            }
            deps.push(altId);
          } else {
            deps.push(id);
          }
          if (/\.js$/.test(iduri.appendext(id))) {
            deps = grunt.util._.union(deps, relativeDependencies(id, options, fpath));
          }
        } else if (!moduleDeps[id]) {
          var alias = iduri.parseAlias(options, id);
          deps.push(alias);

          // don't parse no javascript dependencies
          var ext = path.extname(alias);
          if (ext && ext !== '.js') return;

          var mdeps = moduleDependencies(id, options);
          moduleDeps[id] = mdeps;
          deps = grunt.util._.union(deps, mdeps);
        }
      });
      return deps;
    }

    return relativeDependencies(fpath, options);
  }

  return exports;
};
<|endoftext|>


<commit_before>{
  class Bonsai {
    constructor(e, o) {
      // e:dom element, o:options={children:function(id,callback){...}, click:function(path){...}}
      const bt = this; // bonsai tree
      bt.rebuild = bt.rebuild.bind(bt);
      bt.render = bt.render.bind(bt);
      bt.refresh = bt.refresh.bind(bt);
      bt.childrenCb = o.children;
      bt.valueTipCb = o.valueTip;
      bt.dom = e;
      bt.rebuild();

      bt.dom.onscroll = $.debounce(100, bt.requestValueTips.bind(bt));

      const toggleNode = (tgt) => {
        if (bt.newNodes) return;
        const a = tgt;
        const nodeElement = a.parentNode.parentNode;
        const node = bt.nodes[nodeElement.dataset.id];
        if (!node || !node.expandable) return;
        node.expanded = 1 - !!node.expanded; a.textContent = '+-'[+!!node.expanded];
        nodeElement.className = node.expanded ? '' : 'bt_collapsed';
        if (node.expanded) {
          bt.childrenCb(node.id, (children) => {
            const selected = a.nextSibling.classList.contains('selected');
            node.children = children;
            children.forEach((c) => {
              bt.nodes[c.id] = c;
              c.depth = node.depth + 1;
              c.path = node.path ? `${node.path}.${c.text}` : c.text;
            });
            if (selected) e.getElementsByClassName('selected')[0].focus();
            bt.replaceTree();
          });
        } else {
          bt.replaceTree();
        }
      };

      const selectNode = (tgt, trg) => { // tgt=target,trg=trigger=1or0
        if (tgt.matches('.bt_text')) {
          const [sel] = e.getElementsByClassName('selected');
          sel && sel.classList.remove('selected');
          tgt.classList.add('selected');
          tgt.focus();
          if (o.click && trg) {
            o.click(tgt.dataset.path);
          }
        }
      };

      let clickTimer = 0;
      bt.dom.onclick = (event) => {
        clearTimeout(clickTimer);
        if (event.target.matches('.bt_node_expand')) { toggleNode(event.target); }
        clickTimer = setTimeout(() => {
          selectNode(event.target, 1);
        }, 500);
        return !1;
      };

      bt.dom.ondblclick = (event) => {
        clearTimeout(clickTimer);
        const ps = event.target.previousSibling;
        if (ps && ps.matches('.bt_node_expand')) {
          toggleNode(ps);
          selectNode(event.target, 0);
        } else { selectNode(event.target, 1); }
        return !1;
      };

      bt.dom.onkeydown = (event) => {
        switch (event.which) {
          case 13:// case 37:case 38:case 39:case 40://Enter,Left,Up,Right,Down
            selectNode(event.target, 1);
            break;
          case 40:
          case 38: {
            const sp = [...e.getElementsByTagName('span')].filter(x => !!x.offsetWidth);
            for (let i = 0; i < sp.length; i += 1) {
              if (sp[i].classList.contains('selected')) {
                selectNode(sp[Math.max(0, Math.min(sp.length - 1, (i + event.which) - 39))]); break;
              }
            }
            return !1;
          }
          case 37: case 39: {
            const sel = e.getElementsByClassName('selected')[0];
            const left = event.which === 37;
            if (!!bt.nodes[sel.dataset.id].expanded === left) toggleNode(sel.previousSibling);
            else if (left) { selectNode(sel.parentNode.parentNode.getElementsByClassName('bt_text')[0]); }
            return !1;
          }
          case 116:// F5
            bt.refresh();
            break;
          default: break;
        }
        return !1;
      };
    }

    focus() {
      const [sel] = this.dom.getElementsByClassName('selected');
      sel && sel.focus();
    }

    render(node, selected) {
      const bt = this;
      let children = '';
      let expandable = '';
      if (node.expanded) children = node.children.map(x => bt.render(x)).join('');
      if (node.expandable) expandable = `<a class=bt_node_expand>${'+-'[+!!node.expanded]}</a>`;

      return `<tr data-id="${node.id}" title="${node.value ? node.value.join('\n') : ''}">` +
        `<td style="padding-left:${node.depth}em;">${expandable}<span tabIndex=-1 data-id=${node.id} data-path=${node.path}` +
        ` class="bt_icon_${node.icon} bt_text ${node.selected || selected ? 'selected' : ''}">` +
        `${node.text}</span></td><td class="value_tip">${node.value ? node.value[0]: ''}</td></tr>${children}`;
    }

    rebuild() {
      const bt = this;
      bt.nodes = {
        0: {
          id: 0,
          depth: 0,
          path: '',
          text: '',
          // value: [''],
          expanded: 1,
        }
      };
      bt.refresh();
    }

    refreshNode(node, path, depth) {
      const bt = this;
      const oldNode = bt.nodes[node.id];
      bt.newNodes[node.id] = node;
      node.depth = depth;
      node.path = path ? `${path}.${node.text}` : node.text;
      if (oldNode && oldNode.text === node.text && oldNode.expanded && node.expandable) {
        bt.pendingCalls += 1;
        bt.childrenCb(node.id, (children) => {
          node.expanded = 1;
          node.children = children;
          children.forEach(c => bt.refreshNode(c, node.path, node.depth + 1));
          bt.pendingCalls -= 1;
          !bt.pendingCalls && bt.replaceTree();
        });
      }
    }

    refresh() {
      const bt = this;
      if (bt.newNodes) return;
      bt.newNodes = {};
      bt.pendingCalls = 0;
      bt.refreshNode({
        id: 0,
        text: '',
        expandable: 1,
        icon: '',
      }, '', 0);
    }

    replaceTree() {
      const bt = this;
      if (bt.newNodes) {
        const [sel] = bt.dom.getElementsByClassName('selected');
        const hasFocus = !!$(bt.dom).find(':focus').length > 0;
        if (sel) {
          const n = bt.newNodes[sel.dataset.id];
          n && (n.selected = 1);
        }
        bt.nodes = bt.newNodes;
        hasFocus && bt.focus();
        delete bt.newNodes;
      }
      bt.dom.innerHTML = `<table><tbody>${bt.nodes[0].children.map(x => bt.render(x)).join('')}</tbody></table>`;
      bt.requestValueTips();
    }

    requestValueTip(node) {
      if (node.id < 2) return;
      const bt = this;
      bt.pendingCalls += 1;
      bt.valueTipCb(node, (x) => {
        node.value = x.tip;
        bt.pendingCalls -= 1;
        !bt.pendingCalls && bt.replaceTree();
      });
    }

    requestValueTips() {
      const bt = this;
      const rect = bt.dom.getBoundingClientRect();
      const trs = bt.dom.getElementsByTagName('tr');
      for (const tr of trs) {
        const trrect = tr.getBoundingClientRect();
        const node = bt.nodes[tr.dataset.id];
        if (!node.value && trrect.top > 0 && trrect.bottom < rect.bottom) {
          bt.requestValueTip(node);
        };
      }
    }
  }
  D.Bonsai = Bonsai;
}
<commit_msg>Ensure valuetips only requested once for each node<commit_after>{
  class Bonsai {
    constructor(e, o) {
      // e:dom element, o:options={children:function(id,callback){...}, click:function(path){...}}
      const bt = this; // bonsai tree
      bt.rebuild = bt.rebuild.bind(bt);
      bt.render = bt.render.bind(bt);
      bt.refresh = bt.refresh.bind(bt);
      bt.childrenCb = o.children;
      bt.valueTipCb = o.valueTip;
      bt.dom = e;
      bt.rebuild();

      bt.dom.onscroll = $.debounce(100, bt.requestValueTips.bind(bt));

      const toggleNode = (tgt) => {
        if (bt.newNodes) return;
        const a = tgt;
        const nodeElement = a.parentNode.parentNode;
        const node = bt.nodes[nodeElement.dataset.id];
        if (!node || !node.expandable) return;
        node.expanded = 1 - !!node.expanded; a.textContent = '+-'[+!!node.expanded];
        nodeElement.className = node.expanded ? '' : 'bt_collapsed';
        if (node.expanded) {
          bt.childrenCb(node.id, (children) => {
            const selected = a.nextSibling.classList.contains('selected');
            node.children = children;
            children.forEach((c) => {
              bt.nodes[c.id] = c;
              c.depth = node.depth + 1;
              c.path = node.path ? `${node.path}.${c.text}` : c.text;
            });
            if (selected) e.getElementsByClassName('selected')[0].focus();
            bt.replaceTree();
          });
        } else {
          bt.replaceTree();
        }
      };

      const selectNode = (tgt, trg) => { // tgt=target,trg=trigger=1or0
        if (tgt.matches('.bt_text')) {
          const [sel] = e.getElementsByClassName('selected');
          sel && sel.classList.remove('selected');
          tgt.classList.add('selected');
          tgt.focus();
          if (o.click && trg) {
            o.click(tgt.dataset.path);
          }
        }
      };

      let clickTimer = 0;
      bt.dom.onclick = (event) => {
        clearTimeout(clickTimer);
        if (event.target.matches('.bt_node_expand')) { toggleNode(event.target); }
        clickTimer = setTimeout(() => {
          selectNode(event.target, 1);
        }, 500);
        return !1;
      };

      bt.dom.ondblclick = (event) => {
        clearTimeout(clickTimer);
        const ps = event.target.previousSibling;
        if (ps && ps.matches('.bt_node_expand')) {
          toggleNode(ps);
          selectNode(event.target, 0);
        } else { selectNode(event.target, 1); }
        return !1;
      };

      bt.dom.onkeydown = (event) => {
        switch (event.which) {
          case 13:// case 37:case 38:case 39:case 40://Enter,Left,Up,Right,Down
            selectNode(event.target, 1);
            break;
          case 40:
          case 38: {
            const sp = [...e.getElementsByTagName('span')].filter(x => !!x.offsetWidth);
            for (let i = 0; i < sp.length; i += 1) {
              if (sp[i].classList.contains('selected')) {
                selectNode(sp[Math.max(0, Math.min(sp.length - 1, (i + event.which) - 39))]); break;
              }
            }
            return !1;
          }
          case 37: case 39: {
            const sel = e.getElementsByClassName('selected')[0];
            const left = event.which === 37;
            if (!!bt.nodes[sel.dataset.id].expanded === left) toggleNode(sel.previousSibling);
            else if (left) { selectNode(sel.parentNode.parentNode.getElementsByClassName('bt_text')[0]); }
            return !1;
          }
          case 116:// F5
            bt.refresh();
            break;
          default: break;
        }
        return !1;
      };
    }

    focus() {
      const [sel] = this.dom.getElementsByClassName('selected');
      sel && sel.focus();
    }

    render(node, selected) {
      const bt = this;
      let children = '';
      let expandable = '';
      if (node.expanded) children = node.children.map(x => bt.render(x)).join('');
      if (node.expandable) expandable = `<a class=bt_node_expand>${'+-'[+!!node.expanded]}</a>`;

      return `<tr data-id="${node.id}" title="${node.value ? node.value.join('\n') : ''}">` +
        `<td style="padding-left:${node.depth}em;">${expandable}<span tabIndex=-1 data-id=${node.id} data-path=${node.path}` +
        ` class="bt_icon_${node.icon} bt_text ${node.selected || selected ? 'selected' : ''}">` +
        `${node.text}</span></td><td class="value_tip">${node.value ? node.value[0]: ''}</td></tr>${children}`;
    }

    rebuild() {
      const bt = this;
      bt.nodes = {
        0: {
          id: 0,
          depth: 0,
          path: '',
          text: '',
          expanded: 1,
        }
      };
      bt.refresh();
    }

    refreshNode(node, path, depth) {
      const bt = this;
      const oldNode = bt.nodes[node.id];
      bt.newNodes[node.id] = node;
      node.depth = depth;
      node.path = path ? `${path}.${node.text}` : node.text;
      if (oldNode && oldNode.text === node.text && oldNode.expanded && node.expandable) {
        bt.pendingCalls += 1;
        bt.childrenCb(node.id, (children) => {
          node.expanded = 1;
          node.children = children;
          children.forEach(c => bt.refreshNode(c, node.path, node.depth + 1));
          bt.pendingCalls -= 1;
          !bt.pendingCalls && bt.replaceTree();
        });
      }
    }

    refresh() {
      const bt = this;
      if (bt.newNodes) return;
      bt.newNodes = {};
      bt.pendingCalls = 0;
      bt.refreshNode({
        id: 0,
        text: '',
        expandable: 1,
        icon: '',
      }, '', 0);
    }

    replaceTree() {
      const bt = this;
      if (bt.newNodes) {
        const [sel] = bt.dom.getElementsByClassName('selected');
        const hasFocus = !!$(bt.dom).find(':focus').length > 0;
        if (sel) {
          const n = bt.newNodes[sel.dataset.id];
          n && (n.selected = 1);
        }
        bt.nodes = bt.newNodes;
        hasFocus && bt.focus();
        delete bt.newNodes;
      }
      bt.dom.innerHTML = `<table><tbody>${bt.nodes[0].children.map(x => bt.render(x)).join('')}</tbody></table>`;
      bt.requestValueTips();
    }

    requestValueTip(node) {
      if (node.valueRequested || node.id < 2) return;
      const bt = this;
      node.valueRequested = 1;
      bt.pendingCalls += 1;
      bt.valueTipCb(node, (x) => {
        node.value = x.tip;
        delete node.valueRequested;
        bt.pendingCalls -= 1;
        !bt.pendingCalls && bt.replaceTree();
      });
    }

    requestValueTips() {
      const bt = this;
      const rect = bt.dom.getBoundingClientRect();
      const trs = bt.dom.getElementsByTagName('tr');
      for (const tr of trs) {
        const trrect = tr.getBoundingClientRect();
        const node = bt.nodes[tr.dataset.id];
        if (!node.value && trrect.top > 0 && trrect.bottom < rect.bottom) {
          bt.requestValueTip(node);
        };
      }
    }
  }
  D.Bonsai = Bonsai;
}
<|endoftext|>


<commit_before>/**
 * precompile.js
 * Created by anonymoussc on 08/03/15 20:40.
 */

'use strict';

var moment   = require('moment'),
    S        = require('string'),
    argv     = require('yargs').argv,
    dataSrc  = require('./../config/dataSrc/dataSrc.json'),
    config   = require('./../config/config.js'),
    league   = require('./../templates/league.js'),
    composer = require('./../templates/composer.js'),
    laravel  = require('./../templates/laravel.js');

var
    precompile = {
        dataSrc : {
            author_name        : dataSrc.author_name,
            author_username    : whos_yousername(), //dataSrc.author_username
            author_website     : dataSrc.author_website,
            author_email       : dataSrc.author_email,
            package_name       : dataSrc.package_name,
            package_description: dataSrc.package_description,
            dateTime           : {
                now : moment().format('MMMM Do YYYY, h:mm:ss a'),
                year: moment().format('YYYY')
            },
            author_username_ucf: S(whos_yousername()).capitalize().s, // Upper case first letter
            author_username_sc : S('-' + whos_yousername()).camelize().s, // StudlyCaps
            author_username_cc : S(whos_yousername()).camelize().s, // camelCase
            author_username_alt: whos_yousername(true),
            package_name_ucf   : S(dataSrc.package_name).capitalize().s, // Upper case first letter
            package_name_sc    : S('-' + dataSrc.package_name).camelize().s, // StudlyCaps
            package_name_cc    : S(dataSrc.package_name).camelize().s // camelCase
        },
        config  : config,
        composer: composer,
        laravel : laravel,
        league  : league
    };

function whos_yousername(alt) {
    argv.generator = argv.g ? argv.g : argv.generator;

    if ((argv.generator === league.name) || (config.generator === league.name)) {
        if (((argv.generator === league.name) && (!config.generator)) || ((config.generator === league.name) && (!argv.generator))) {
            if (alt) {
                return 'thephpleague';
            }
            return league.name;
        }
    } else {
        return dataSrc.author_username;
    }

}

module.exports = precompile;<commit_msg>Modified precompile<commit_after>/**
 * precompile.js
 * Created by anonymoussc on 08/03/15 20:40.
 */

'use strict';

var moment   = require('moment'),
    S        = require('string'),
    argv     = require('yargs').argv,
    dataSrc  = require('./../config/dataSrc/dataSrc.json'),
    config   = require('./../config/config.js'),
    league   = require('./../templates/league.js'),
    composer = require('./../templates/composer.js'),
    laravel  = require('./../templates/laravel.js');

var
    precompile = {
        dataSrc : {
            author_name        : dataSrc.author_name,
            author_username    : whos_yousername(), //dataSrc.author_username
            author_website     : dataSrc.author_website,
            author_email       : dataSrc.author_email,
            package_name       : dataSrc.package_name,
            package_description: dataSrc.package_description,
            dateTime           : {
                now : moment().format('MMMM Do YYYY, h:mm:ss a'),
                year: moment().format('YYYY')
            },
            author_username_ucf: S(whos_yousername()).capitalize().s, // Upper case first letter
            author_username_sc : S('-' + whos_yousername()).camelize().s, // StudlyCaps
            author_username_cc : S(whos_yousername()).camelize().s, // camelCase
            author_username_alt: whos_yousername(true),
            package_name_ucf   : S(dataSrc.package_name).capitalize().s, // Upper case first letter
            package_name_sc    : S('-' + dataSrc.package_name).camelize().s, // StudlyCaps
            package_name_cc    : S(dataSrc.package_name).camelize().s // camelCase
        },
        config  : config,
        composer: composer,
        laravel : laravel,
        league  : league
    };

function whos_yousername(alt) {
    argv.generator = argv.g ? argv.g : argv.generator;

    if ((argv.generator === league.name) || (config.generator === league.name)) {
        if (((argv.generator === league.name) && (!config.generator)) || ((config.generator === league.name) && (!argv.generator))) {
            if (alt) {
                return 'thephpleague';
            }
            return league.name;
        }
    } else {
        return dataSrc.author_username;
    }

}

module.exports = precompile;
<|endoftext|>


<commit_before>import 'rxjs/add/operator/map'

import mapValues from 'lodash/mapValues'
import some from 'lodash/some'

import {
  product
} from '../fetch/operators'

import {
  query,
  querySync
} from './query'

function etoo(e, fetch, itok) {
  const data = {}
  let loading = false
  fetch.fetches.forEach((f, i) => {
    data[itok[i]] = e[i]
    loading = loading || e[i] && e[i].loading
  })
  return { loading, data }
}

function _apply(queries, args, _query) {
  const itok = Object.keys(args)
  const fetches = itok.map(k => queries[k])
  const as = itok.map(k => args[k])
  const prod = product(fetches)
  return _query(prod, as).map(e => etoo(e, prod, itok))
}

export function apply(queries, args) {
  return _apply(queries, args, query)
}

export function applySync(queries, args) {
  const data = mapValues(queries, (fetch, queryName) => ({
    loading: false,
    ...querySync(fetch, args[queryName])
  }));
  const loading = some(data, { loading: true });
  return { loading, data }
}
<commit_msg>remove useless indirection in graph/apply<commit_after>import 'rxjs/add/operator/map'

import mapValues from 'lodash/mapValues'
import some from 'lodash/some'

import {
  product
} from '../fetch/operators'

import {
  query,
  querySync
} from './query'

function etoo(e, fetch, itok) {
  const data = {}
  let loading = false
  fetch.fetches.forEach((f, i) => {
    data[itok[i]] = e[i]
    loading = loading || e[i] && e[i].loading
  })
  return { loading, data }
}

export function apply(queries, args) {
  const itok = Object.keys(args)
  const fetches = itok.map(k => queries[k])
  const as = itok.map(k => args[k])
  const prod = product(fetches)
  return query(prod, as).map(e => etoo(e, prod, itok))
}

export function applySync(queries, args) {
  const data = mapValues(queries, (fetch, queryName) => ({
    loading: false,
    ...querySync(fetch, args[queryName])
  }));
  const loading = some(data, { loading: true });
  return { loading, data }
}
<|endoftext|>


<commit_before>/*加载资源*/
var preload = function() { };

/*创建世界*/
var create = function() { };

/*每帧重绘*/
var update = function() { };

/*每帧渲染*/
var render = function() { };

/*第三个参数可以是Phaser.CANVAS，Phaser.WEBGL，或Phaser.AUTO。这个是你想使用的渲染上下文。推荐的参数是Phaser.AUTO，它会自动尝试使用WebGL，如果浏览器或设备不支持它就会回滚成Canvas。*/
var game = new Phaser.Game(800, 600, Phaser.AUTO, '空|id|dom', { preload: preload, create: create, update: update, render: render}, true);
<commit_msg>update phaser game tpl<commit_after>//定义一个游戏
var game = new Phaser.Game(288, 505, Phaser.AUTO, 'mygame');

/*定义游戏场景*/
game.States = {
	//boot场景，用来做一些游戏启动前的准备
	boot : function(){
		this.preload = function(){
			game.load.image('loading', './img/preloader.gif');
		};
		this.create = function(){
			//启动资源加载
			game.state.start('preload');
			//game.world.setBounds(0, 0, 4000, 300);
		};
	},
	//prelaod场景，用来显示资源加载进度
	preload : function(){
		this.preload = function(){
			/*var preloadSprite = game.add.sprite( game.world.centerX, game.world.centerY, 'loading');
			preloadSprite.anchor.set(0.5,0);
			game.load.setPreloadSprite(preloadSprite, 0);*/

			//加载进度
			var text = game.add.text( game.world.centerX, game.world.centerY, "0%",{font:"16px Arial", fill:"#FFFFFF", align: "center"}),
			percent = 0,
			curPercent = 0,
			loadKey,
			_addPrecent = function(from, to){
				if(percent < to){
					if(percent >= from){
						percent++;
					}

					if (percent > 100) {
						percent = 100;
					}

					text.setText(percent + "%");

					if(percent == 100){
						game.time.events.remove(loadKey);
					}
				}
			};
			//文字居中
			text.anchor.set(0.5, 0.5);
			//添加定时器
			loadKey = game.time.events.loop(Phaser.Timer.SECOND / 30, function(){
				_addPrecent(percent , curPercent);
			}, this);
			//绑定
			game.load.onFileComplete.add(function( progress ) {
				curPercent  = progress;
			});

			//加载资源
		};
		this.create = function(){
			//启动菜单场景
			game.state.start('menu');
		};
	},
	//menu场景, 显示菜单
	menu : function(){
		this.create = function(){ };
	},
	//play场景， 游戏场景
	play : function(){
		this.create = function(){ };
		this.update = function(){ };
	}
};

game.main = {
	init : function(){
		//添加场景
		game.state.add('boot', game.States.boot);
		game.state.add('preload', game.States.preload);
		game.state.add('menu', game.States.menu);
		game.state.add('play', game.States.play);

		//调用boot启动游戏
		game.state.start('boot');
	}
};

/*初始化*/
game.main.init();
<|endoftext|>


<commit_before>'use strict';

/*
 * Toggle code visibility
 */
$('.pl-toggle-code').on('click', function () {
    // toggle the sibling pre element
    $(this).parent().next('.pl-preview+pre').toggle(250);
    $(this).toggleClass('active');
});

var autoCollapsed = false;
$('.nav-collapse').on('click', function () {
    autoCollapsed = false;
    $('body').toggleClass('pl-collapsed-nav');
});

/* collapse sidebar when necessary */
var checkNav = function () {
    var collapsed = $('body').hasClass('pl-collapsed-nav'),
        width = $(this).width();

    if (width <= 767 && !collapsed) {
        autoCollapsed = true;
        $('body').addClass('pl-collapsed-nav');
    } else if (width > 767 && autoCollapsed) {
        $('body').removeClass('pl-collapsed-nav');
    }
};

$(window).on('resize', checkNav);
$(document).on('ready', checkNav);

/*
 * Use bootstrap's scrollspy plugin to highlight subnav based on scroll position
 */
$('body').scrollspy({ target: '.pl-sidebar > .active', offset: 125 });

/* enable masks */
$(':input').inputmask();

/* select2 things */
$('.select2').select2({
    minimumResultsForSearch: 4
});

/* enable tooltips */
$('[data-toggle="tooltip"]').tooltip({container: 'body', delay: { show: 200, hide: 0 } });

/* enable datepickers */
$('.datepicker').datepicker({
    // autoSize: true,
    // showButtonPanel: true,
    numberOfMonths: 1,
    showOtherMonths: true
    // changeMonth: true,
    // changeYear: true
});

/* find checkboxes with the indeterminate attr and set the indeterminate property */
$('input[type="checkbox"][indeterminate]').each(function () {
    this.indeterminate = true;
});

/* closable toast examples */
$('.pl-closable-toasts .toast .close').each(function () {
    $(this).on('click', function () {
        $(this).closest('.toast').animate({
            right: "-100%",
            opacity: 0
        }, 150, 'swing', function () {
          $(this).hide(150);
        });
    });
});

/* quick and dirty working toast examples */
$('.show-toasts').each(function () {
    var showToastButton = $(this);

    // get toasts and move to body
    var selector = showToastButton.attr('data-toast-target');
    var toastContainer = $(selector);
    toastContainer.hide();
    $(document.body).append(toastContainer);

    var closers = toastContainer.find('.close');
    var closersCount = closers.length;
    var closedCount = 0;
    closers.each(function () {
        $(this).on('click', function () {
            if (closersCount === ++closedCount) {
                closedCount = 0;
                setTimeout(function () {
                    toastContainer.hide();
                }, 150);
            }
        });
    });

    var showToast = function (toastEl) {
        toastEl.css({right: "-100%", opacity: 0, display: "block"});
        toastEl.animate({
            right: "0",
            opacity: 1
        }, 150, 'swing', function () {
          if (toastEl.next().length) {
                setTimeout(function () {
                    showToast(toastEl.next());
                }, 1000);
            }
        });
    };

    // show the toasts on click
    showToastButton.on('click', function() {
        toastContainer.find('.toast').hide().css({right: 0, opacity: 1});
        toastContainer.toggle();
        if (toastContainer.css('display') === 'block') {
            toastContainer.css({
                position: 'fixed',
                top: '42px',
                right: '0px',
                zIndex: '10000'
            });
            closedCount = 0;
            showToast($(toastContainer.find('.toast')[0]));
        }
    });
});
<commit_msg>Fixes linting for js<commit_after>'use strict';

/*
 * Toggle code visibility
 */
$('.pl-toggle-code').on('click', function () {
    // toggle the sibling pre element
    $(this).parent().next('.pl-preview+pre').toggle(250);
    $(this).toggleClass('active');
});

var autoCollapsed = false;
$('.nav-collapse').on('click', function () {
    autoCollapsed = false;
    $('body').toggleClass('pl-collapsed-nav');
});

/* collapse sidebar when necessary */
var checkNav = function () {
    var collapsed = $('body').hasClass('pl-collapsed-nav'),
        width = $(this).width();

    if (width <= 767 && !collapsed) {
        autoCollapsed = true;
        $('body').addClass('pl-collapsed-nav');
    } else if (width > 767 && autoCollapsed) {
        $('body').removeClass('pl-collapsed-nav');
    }
};

$(window).on('resize', checkNav);
$(document).on('ready', checkNav);

/*
 * Use bootstrap's scrollspy plugin to highlight subnav based on scroll position
 */
$('body').scrollspy({ target: '.pl-sidebar > .active', offset: 125 });

/* enable masks */
$(':input').inputmask();

/* select2 things */
$('.select2').select2({
    minimumResultsForSearch: 4
});

/* enable tooltips */
$('[data-toggle="tooltip"]').tooltip({container: 'body', delay: { show: 200, hide: 0 } });

/* enable datepickers */
$('.datepicker').datepicker({
    // autoSize: true,
    // showButtonPanel: true,
    numberOfMonths: 1,
    showOtherMonths: true
    // changeMonth: true,
    // changeYear: true
});

/* find checkboxes with the indeterminate attr and set the indeterminate property */
$('input[type="checkbox"][indeterminate]').each(function () {
    this.indeterminate = true;
});

/* closable toast examples */
$('.pl-closable-toasts .toast .close').each(function () {
    $(this).on('click', function () {
        $(this).closest('.toast').animate({
            right: '-100%',
            opacity: 0
        }, 150, 'swing', function () {
            $(this).hide(150);
        });
    });
});

/* quick and dirty working toast examples */
$('.show-toasts').each(function () {
    var showToastButton = $(this);

    // get toasts and move to body
    var selector = showToastButton.attr('data-toast-target');
    var toastContainer = $(selector);
    toastContainer.hide();
    $(document.body).append(toastContainer);

    var closers = toastContainer.find('.close');
    var closersCount = closers.length;
    var closedCount = 0;
    closers.each(function () {
        $(this).on('click', function () {
            if (closersCount === ++closedCount) {
                closedCount = 0;
                setTimeout(function () {
                    toastContainer.hide();
                }, 150);
            }
        });
    });

    var showToast = function (toastEl) {
        toastEl.css({right: '-100%', opacity: 0, display: 'block'});
        toastEl.animate({
            right: '0',
            opacity: 1
        }, 150, 'swing', function () {
            if (toastEl.next().length) {
                setTimeout(function () {
                    showToast(toastEl.next());
                }, 1000);
            }
        });
    };

    // show the toasts on click
    showToastButton.on('click', function() {
        toastContainer.find('.toast').hide().css({right: 0, opacity: 1});
        toastContainer.toggle();
        if (toastContainer.css('display') === 'block') {
            toastContainer.css({
                position: 'fixed',
                top: '42px',
                right: '0px',
                zIndex: '10000'
            });
            closedCount = 0;
            showToast($(toastContainer.find('.toast')[0]));
        }
    });
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import HomeFeature from './HomeFeature';
import FullWidthSection from './FullWidthSection';
// Used for donate section button.
// import RaisedButton from 'material-ui/RaisedButton';
import withWidth, {LARGE} from 'material-ui/utils/withWidth';
import spacing from 'material-ui/styles/spacing';
import typography from 'material-ui/styles/typography';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import {darkWhite, white} from 'material-ui/styles/colors';

class HomePage extends Component {

  static propTypes = {
    width: PropTypes.number.isRequired,
  };

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  homePageTitleBanner() {
    const styles = {
      root: {
        backgroundColor: '#00728a',
        overflow: 'hidden',
      },
      svgLogo: {
        marginLeft: window.innerWidth * 0.5 - 130,
        width: 420,
        height: 157,
      },
      tagline: {
        color: '#00728a',
        margin: '16px auto 16px auto',
        textAlign: 'center',
        maxWidth: 900,
        lineHeight: '56px',
      },
      label: {
        // color: lightBaseTheme.palette.primary1Color,
        color: white,
      },
      githubStyle: {
        margin: '16px 32px 0px 8px',
      },
      demoStyle: {
        margin: '16px 32px 0px 32px',
      },
      h1: {
        color: white,
        fontWeight: typography.fontWeightLight,
      },
      h2: {
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 12,
        letterSpacing: 0,
      },
      nowrap: {
        whiteSpace: 'nowrap',
      },
      taglineWhenLarge: {
        marginTop: 12,
      },
      h1WhenLarge: {
        fontSize: 56,
      },
      h2WhenLarge: {
        fontSize: 24,
        lineHeight: '32px',
        paddingTop: 16,
        marginBottom: 12,
      },
      a: {
        color: '#00728a',
      },
    };

    styles.h2 = Object.assign({}, styles.h1, styles.h2);

    if (this.props.width === LARGE) {
      styles.tagline = Object.assign({}, styles.tagline, styles.taglineWhenLarge);
      styles.h1 = Object.assign({}, styles.h1, styles.h1WhenLarge);
      styles.h2 = Object.assign({}, styles.h2, styles.h2WhenLarge);
    }

    return (
      <FullWidthSection style={styles.root}>

MIT App Inventor - Internet of Things

      </FullWidthSection>
    );
  }

  homePurposeAbout() {
    const styles = {
      root: {
        backgroundColor: darkWhite,
      },
      content: {
        maxWidth: 900,
        padding: 0,
        margin: '0 auto',
        fontWeight: typography.fontWeightLight,
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 6,
        letterSpacing: 0,
        color: typography.textDarkBlack,
      },
    };

    return (
      <FullWidthSection
        style={styles.root}
        useContent={true}
        contentStyle={styles.content}
        contentType="p"
        className="home-purpose"
      >

Make apps that connect to the Internet of Things with MIT App Inventor!

        MIT App Inventor helps people around the world build mobile apps that can make a difference for their
        families, schools, and communities— even if they've never programmed before.

        MIT App Inventor is changing how the world creates apps and how kids learn about mobile computing.
        Over 400,000 active inventors a month from 195 countries have created more than 22 million
        apps.

        MIT App Inventor now brings that same power and simplicity of app creation to the Internet of Things (IoT) and
        the universe of connected devices.
        Learn more
      </FullWidthSection>
    );
  }

  homeFeatures() {
    const styles = {
      maxWidth: 900,
      padding: 0,
      margin: '0 auto',
      fontWeight: typography.fontWeightLight,
      fontSize: 20,
      lineHeight: '28px',
      paddingTop: 6,
      marginBottom: 6,
      letterSpacing: 0,
      color: typography.textDarkBlack,
    };

    return (
      <FullWidthSection useContent={true} contentStyle={styles}>
        <HomeFeature
          heading="For Teachers"
          route="/teachers/intro"
          img="images/teachers.jpg"
          firstChild={true}
        />
        <HomeFeature
          heading="For Students"
          route="/students/intro"
          img="images/students.jpg"
        />
        <HomeFeature
          heading="For Makers"
          route="/makers/intro"
          img="images/makers.jpg"
          lastChild={true}
        />
      </FullWidthSection>
    );
  }

  homePurposeIOT() {
    const styles = {
      root: {
        backgroundColor: darkWhite,
      },
      content: {
        maxWidth: 900,
        padding: 0,
        margin: '0 auto',
        fontWeight: typography.fontWeightLight,
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 6, // was 19
        marginBottom: 6,
        letterSpacing: 0,
        color: typography.textDarkBlack,
      },
    };

    return (
      <FullWidthSection
        style={styles.root}
        useContent={true}
        contentStyle={styles.content}
        contentType="p"
        className="home-purpose"
      >

Bring computing off the screen and into the world of everyday things!

        You can develop IoT applications the same way you develop any other MIT App Inventor mobile apps,
        but now you can use the apps to interact with objects all around you.

      </FullWidthSection>
    );
  }

  // homeContribute() {
  //   const styles = {
  //     root: {
  //       backgroundColor: grey200,
  //       textAlign: 'center',
  //     },
  //     h3: {
  //       maxWidth: 900,
  //       padding: 0,
  //       margin: '0 auto',
  //       fontWeight: typography.fontWeightLight,
  //       fontSize: 20,
  //       lineHeight: '28px',
  //       paddingTop: 10,
  //       marginBottom: 5,
  //       letterSpacing: 0,
  //       color: typography.textDarkBlack,
  //     },
  //     button: {
  //       marginTop: 32,
  //     },
  //   };
  //
  //   return (
  //     <FullWidthSection useContent={true} style={styles.root}>
  //
  //

  //         Empower our young people through mobile computing to
  //         impact the world of everyday objects. Please consider supporting this
  //         project.
  //

  //
  //

  //         Thank you, from the MIT App Inventor team.
  //

  //
  //       <RaisedButton
  //         label="Donate"
  //         primary={true}
  //         href="https://github.com/mit-cml"
  //         style={styles.button}
  //       />
  //     </FullWidthSection>
  //   );
  // }

  // handleTouchTapDonate = () => {
  //   this.context.router.push('/components');
  // };

  render() {
    const style = {
      paddingTop: spacing.desktopKeylineIncrement,
    };

    return (

        {this.homePageTitleBanner()}
        {this.homePurposeAbout()}
        {this.homeFeatures()}
        {this.homePurposeIOT()}

    );
  }
}

export default withWidth()(HomePage);
<commit_msg>"Learn More" buttons on home page<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import HomeFeature from './HomeFeature';
import FullWidthSection from './FullWidthSection';
// Used for donate section button.
// import RaisedButton from 'material-ui/RaisedButton';
import withWidth, {LARGE} from 'material-ui/utils/withWidth';
import spacing from 'material-ui/styles/spacing';
import typography from 'material-ui/styles/typography';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import {darkWhite, white} from 'material-ui/styles/colors';
import RaisedButton from 'material-ui/RaisedButton';

class HomePage extends Component {

  static propTypes = {
    width: PropTypes.number.isRequired,
  };

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  homePageTitleBanner() {
    const styles = {
      root: {
        backgroundColor: '#00728a',
        overflow: 'hidden',
      },
      svgLogo: {
        marginLeft: window.innerWidth * 0.5 - 130,
        width: 420,
        height: 157,
      },
      tagline: {
        color: '#00728a',
        margin: '16px auto 16px auto',
        textAlign: 'center',
        maxWidth: 900,
        lineHeight: '56px',
      },
      label: {
        // color: lightBaseTheme.palette.primary1Color,
        color: white,
      },
      githubStyle: {
        margin: '16px 32px 0px 8px',
      },
      demoStyle: {
        margin: '16px 32px 0px 32px',
      },
      h1: {
        color: white,
        fontWeight: typography.fontWeightLight,
      },
      h2: {
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 12,
        letterSpacing: 0,
      },
      nowrap: {
        whiteSpace: 'nowrap',
      },
      taglineWhenLarge: {
        marginTop: 12,
      },
      h1WhenLarge: {
        fontSize: 56,
      },
      h2WhenLarge: {
        fontSize: 24,
        lineHeight: '32px',
        paddingTop: 16,
        marginBottom: 12,
      },
      a: {
        color: '#00728a',
      },
    };

    styles.h2 = Object.assign({}, styles.h1, styles.h2);

    if (this.props.width === LARGE) {
      styles.tagline = Object.assign({}, styles.tagline, styles.taglineWhenLarge);
      styles.h1 = Object.assign({}, styles.h1, styles.h1WhenLarge);
      styles.h2 = Object.assign({}, styles.h2, styles.h2WhenLarge);
    }

    return (
      <FullWidthSection style={styles.root}>

MIT App Inventor - Internet of Things

      </FullWidthSection>
    );
  }

  homePurposeAbout() {
    const styles = {
      root: {
        backgroundColor: darkWhite,
      },
      content: {
        maxWidth: 900,
        padding: 0,
        margin: '0 auto',
        fontWeight: typography.fontWeightLight,
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 19,
        marginBottom: 6,
        letterSpacing: 0,
        color: typography.textDarkBlack,
      },
    };

    return (
      <FullWidthSection
        style={styles.root}
        useContent={true}
        contentStyle={styles.content}
        contentType="p"
        className="home-purpose"
      >

Make apps that connect to the Internet of Things with MIT App Inventor!

        MIT App Inventor helps people around the world build mobile apps that can make a difference for their
        families, schools, and communities— even if they've never programmed before.

        MIT App Inventor is changing how the world creates apps and how kids learn about mobile computing.
        Over 400,000 active inventors a month from 195 countries have created more than 22 million
        apps.

        MIT App Inventor now brings that same power and simplicity of app creation to the Internet of Things (IoT) and
        the universe of connected devices.

            <RaisedButton
              label="Learn more about IoT" href="#LearnMore"
              secondary="true"
            />

            <RaisedButton
              label="Learn more about MIT App Inventor"
              href="http://appinventor.mit.edu" target="_blank"
              primary="true"
            />

      </FullWidthSection>
    );
  }

  homeFeatures() {
    const styles = {
      maxWidth: 900,
      padding: 0,
      margin: '0 auto',
      fontWeight: typography.fontWeightLight,
      fontSize: 20,
      lineHeight: '28px',
      paddingTop: 6,
      marginBottom: 6,
      letterSpacing: 0,
      color: typography.textDarkBlack,
    };

    return (
      <FullWidthSection useContent={true} contentStyle={styles}>
        <HomeFeature
          heading="For Teachers"
          route="/teachers/intro"
          img="images/teachers.jpg"
          firstChild={true}
        />
        <HomeFeature
          heading="For Students"
          route="/students/intro"
          img="images/students.jpg"
        />
        <HomeFeature
          heading="For Makers"
          route="/makers/intro"
          img="images/makers.jpg"
          lastChild={true}
        />
      </FullWidthSection>
    );
  }

  homePurposeIOT() {
    const styles = {
      root: {
        backgroundColor: darkWhite,
      },
      content: {
        maxWidth: 900,
        padding: 0,
        margin: '0 auto',
        fontWeight: typography.fontWeightLight,
        fontSize: 20,
        lineHeight: '28px',
        paddingTop: 6, // was 19
        marginBottom: 6,
        letterSpacing: 0,
        color: typography.textDarkBlack,
      },
    };

    return (
      <FullWidthSection
        style={styles.root}
        useContent={true}
        contentStyle={styles.content}
        contentType="p"
        className="home-purpose"
      >

Bring computing off the screen and into the world of everyday things!

        You can develop IoT applications the same way you develop any other MIT App Inventor mobile apps,
        but now you can use the apps to interact with objects all around you.

      </FullWidthSection>
    );
  }

  // homeContribute() {
  //   const styles = {
  //     root: {
  //       backgroundColor: grey200,
  //       textAlign: 'center',
  //     },
  //     h3: {
  //       maxWidth: 900,
  //       padding: 0,
  //       margin: '0 auto',
  //       fontWeight: typography.fontWeightLight,
  //       fontSize: 20,
  //       lineHeight: '28px',
  //       paddingTop: 10,
  //       marginBottom: 5,
  //       letterSpacing: 0,
  //       color: typography.textDarkBlack,
  //     },
  //     button: {
  //       marginTop: 32,
  //     },
  //   };
  //
  //   return (
  //     <FullWidthSection useContent={true} style={styles.root}>
  //
  //

  //         Empower our young people through mobile computing to
  //         impact the world of everyday objects. Please consider supporting this
  //         project.
  //

  //
  //

  //         Thank you, from the MIT App Inventor team.
  //

  //
  //       <RaisedButton
  //         label="Donate"
  //         primary={true}
  //         href="https://github.com/mit-cml"
  //         style={styles.button}
  //       />
  //     </FullWidthSection>
  //   );
  // }

  // handleTouchTapDonate = () => {
  //   this.context.router.push('/components');
  // };

  render() {
    const style = {
      paddingTop: spacing.desktopKeylineIncrement,
    };

    return (

        {this.homePageTitleBanner()}
        {this.homePurposeAbout()}
        {this.homeFeatures()}
        {this.homePurposeIOT()}

    );
  }
}

export default withWidth()(HomePage);
<|endoftext|>