refactor: es6 building and linting

This commit is contained in:
harttle
2018-08-16 23:14:12 +08:00
parent 5f634b0b5e
commit 19891b2df0
68 changed files with 1636 additions and 1575 deletions
+14 -14
View File
@@ -3,25 +3,25 @@ const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
const _ = require('./util/underscore.js')
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
let valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function (options) {
options = _.assign({}, options)
var filters = {}
let filters = {}
var _filterInstance = {
let _filterInstance = {
render: function (output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
let args = this.args.map(arg => Syntax.evalValue(arg, scope))
args.unshift(output)
return this.filter.apply(null, args)
},
parse: function (str) {
var match = lexical.filterLine.exec(str)
let match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str)
var name = match[1]
var argList = match[2] || ''
var filter = filters[name]
let name = match[1]
let argList = match[2] || ''
let filter = filters[name]
if (typeof filter !== 'function') {
if (options.strict_filters) {
throw new TypeError(`undefined filter: ${name}`)
@@ -32,12 +32,12 @@ module.exports = function (options) {
return this
}
var args = []
let args = []
while ((match = valueRE.exec(argList.trim()))) {
var v = match[0]
var re = new RegExp(`${v}\\s*:`, 'g')
var keyMatch = re.exec(match.input)
var currentMatchIsKey = keyMatch && keyMatch.index === match.index
let v = match[0]
let re = new RegExp(`${v}\\s*:`, 'g')
let keyMatch = re.exec(match.input)
let currentMatchIsKey = keyMatch && keyMatch.index === match.index
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
}
@@ -50,7 +50,7 @@ module.exports = function (options) {
}
function construct (str) {
var instance = Object.create(_filterInstance)
let instance = Object.create(_filterInstance)
return instance.parse(str)
}
+40 -39
View File
@@ -1,23 +1,22 @@
const Scope = require('./scope')
const _ = require('./util/underscore.js')
const assert = require('./util/assert.js')
const tokenizer = require('./tokenizer.js')
const statFileAsync = require('./util/fs.js').statFileAsync
const readFileAsync = require('./util/fs.js').readFileAsync
const path = require('path')
const url = require('./util/url.js')
const Render = require('./render.js')
const lexical = require('./lexical.js')
const Tag = require('./tag.js')
const Filter = require('./filter.js')
const Parser = require('./parser')
const Syntax = require('./syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const anySeries = require('./util/promise.js').anySeries
const Errors = require('./util/error.js')
import Scope from './scope'
import _ from './util/underscore.js'
import assert from './util/assert.js'
import tokenizer from './tokenizer.js'
import {statFileAsync, readFileAsync} from './util/fs.js'
import path from 'path'
import {valid as isValidUrl, extname, resolve} from './util/url.js'
import lexical from './lexical.js'
import Render from './render.js'
import Tag from './tag.js'
import Filter from './filter.js'
import Parser from './parser'
import {isTruthy, isFalsy, evalExp, evalValue} from './syntax.js'
import tags from './tags'
import filters from './filters'
import {anySeries} from './util/promise.js'
import Errors from './util/error.js'
var _engine = {
let _engine = {
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
@@ -34,12 +33,12 @@ var _engine = {
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
let tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
let scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
@@ -53,7 +52,7 @@ var _engine = {
.then(templates => this.render(templates, ctx, opts))
},
evalValue: function (str, scope) {
var tpl = this.parser.parseValue(str.trim())
let tpl = this.parser.parseValue(str.trim())
return this.renderer.evalValue(tpl, scope)
},
registerFilter: function (name, filter) {
@@ -65,7 +64,7 @@ var _engine = {
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
let paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
@@ -85,7 +84,7 @@ var _engine = {
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
let tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
@@ -98,26 +97,26 @@ var _engine = {
})
},
getTemplateFromUrl: function (filepath, root) {
var fullUrl
if (url.valid(filepath)) {
let fullUrl
if (isValidUrl(filepath)) {
fullUrl = filepath
} else {
if (!url.extname(filepath)) {
if (!extname(filepath)) {
filepath += this.options.extname
}
fullUrl = url.resolve(root || this.options.root, filepath)
fullUrl = resolve(root || this.options.root, filepath)
}
if (this.options.cache) {
var tpl = this.cache[filepath]
let tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
}
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
let xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
var tpl = this.parse(xhr.responseText)
let tpl = this.parse(xhr.responseText)
if (this.options.cache) {
this.cache[filepath] = tpl
}
@@ -135,7 +134,7 @@ var _engine = {
},
express: function (opts) {
opts = opts || {}
var self = this
let self = this
return function (filePath, ctx, callback) {
assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
@@ -163,7 +162,7 @@ function factory (options) {
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
let engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
@@ -174,16 +173,18 @@ function normalizeStringArray (value) {
return []
}
factory.lexical = lexical
factory.isTruthy = Syntax.isTruthy
factory.isFalsy = Syntax.isFalsy
factory.evalExp = Syntax.evalExp
factory.evalValue = Syntax.evalValue
factory.Types = {
const Types = {
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
}
factory.isTruthy = isTruthy
factory.isFalsy = isFalsy
factory.evalExp = evalExp
factory.evalValue = evalValue
factory.Types = Types
factory.lexical = lexical
module.exports = factory
+32 -32
View File
@@ -1,49 +1,49 @@
// quote related
var singleQuoted = /'[^']*'/
var doubleQuoted = /"[^"]*"/
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
let singleQuoted = /'[^']*'/
let doubleQuoted = /"[^"]*"/
let quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
let quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types
var integer = /-?\d+/
var number = /-?\d+\.?\d*|\.?\d+/
var bool = /true|false/
let integer = /-?\d+/
let number = /-?\d+\.?\d*|\.?\d+/
let bool = /true|false/
// peoperty access
var identifier = /[\w-]+[?]?/
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
let identifier = /[\w-]+[?]?/
let subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
let literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
let variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
// range related
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
let rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
let range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
let rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
let value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
// hash related
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
let hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
let hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
var literalLine = new RegExp(`^${literal.source}$`, 'i')
var variableLine = new RegExp(`^${variable.source}$`)
var numberLine = new RegExp(`^${number.source}$`)
var boolLine = new RegExp(`^${bool.source}$`, 'i')
var quotedLine = new RegExp(`^${quoted.source}$`)
var rangeLine = new RegExp(`^${rangeCapture.source}$`)
var integerLine = new RegExp(`^${integer.source}$`)
let tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
let literalLine = new RegExp(`^${literal.source}$`, 'i')
let variableLine = new RegExp(`^${variable.source}$`)
let numberLine = new RegExp(`^${number.source}$`)
let boolLine = new RegExp(`^${bool.source}$`, 'i')
let quotedLine = new RegExp(`^${quoted.source}$`)
let rangeLine = new RegExp(`^${rangeCapture.source}$`)
let integerLine = new RegExp(`^${integer.source}$`)
// filter related
var valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
var filterLine = new RegExp(`^${filterCapture.source}$`)
let valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
let valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
let filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
let filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
let filterLine = new RegExp(`^${filterCapture.source}$`)
var operators = [
let operators = [
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
@@ -70,7 +70,7 @@ function matchValue (str) {
}
function parseLiteral (str) {
var res = str.match(numberLine)
let res = str.match(numberLine)
if (res) {
return Number(str)
}
+11 -11
View File
@@ -3,7 +3,7 @@ const ParseError = require('./util/error.js').ParseError
const assert = require('./util/assert.js')
module.exports = function (Tag, Filter) {
var stream = {
let stream = {
init: function (tokens) {
this.tokens = tokens
this.handlers = {}
@@ -14,7 +14,7 @@ module.exports = function (Tag, Filter) {
return this
},
trigger: function (event, arg) {
var h = this.handlers[event]
let h = this.handlers[event]
if (typeof h === 'function') {
h(arg)
return true
@@ -22,14 +22,14 @@ module.exports = function (Tag, Filter) {
},
start: function () {
this.trigger('start')
var token
let token
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue
if (token.type === 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue
}
var template = parseToken(token, this.tokens)
let template = parseToken(token, this.tokens)
this.trigger('template', template)
}
if (!this.stopRequested) this.trigger('end')
@@ -42,8 +42,8 @@ module.exports = function (Tag, Filter) {
}
function parse (tokens) {
var token
var templates = []
let token
let templates = []
while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens))
}
@@ -52,7 +52,7 @@ module.exports = function (Tag, Filter) {
function parseToken (token, tokens) {
try {
var tpl = null
let tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'value') {
@@ -73,13 +73,13 @@ module.exports = function (Tag, Filter) {
}
function parseValue (str) {
var match = lexical.matchValue(str)
let match = lexical.matchValue(str)
assert(match, `illegal value string: ${str}`)
var initial = match[0]
let initial = match[0]
str = str.substr(match.index + match[0].length)
var filters = []
let filters = []
while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()])
}
@@ -92,7 +92,7 @@ module.exports = function (Tag, Filter) {
}
function parseStream (tokens) {
var s = Object.create(stream)
let s = Object.create(stream)
return s.init(tokens)
}
+3 -3
View File
@@ -5,12 +5,12 @@ const _ = require('./util/underscore.js')
const RenderError = require('./util/error.js').RenderError
const assert = require('./util/assert.js')
var render = {
let render = {
renderTemplates: function (templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined')
var html = ''
let html = ''
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => (html += partial))
@@ -60,7 +60,7 @@ var render = {
}
function factory () {
var instance = Object.create(render)
let instance = Object.create(render)
return instance
}
+5 -5
View File
@@ -3,7 +3,7 @@ const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
var Scope = {
let Scope = {
getAll: function () {
return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
},
@@ -140,8 +140,8 @@ var Scope = {
}
function matchRightBracket (str, begin) {
var stack = 1 // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
let stack = 1 // count of '[' - count of ']'
for (let i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++
}
@@ -156,14 +156,14 @@ function matchRightBracket (str, begin) {
}
exports.factory = function (ctx, opts) {
var defaultOptions = {
let defaultOptions = {
dynamicPartials: true,
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}
var scope = Object.create(Scope)
let scope = Object.create(Scope)
scope.opts = _.assign(defaultOptions, opts)
scope.contexts = [ctx || {}]
return scope
+13 -13
View File
@@ -1,27 +1,27 @@
const operators = require('./operators.js')(isTruthy)
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
const assert = require('./util/assert.js')
function evalExp (exp, scope) {
assert(scope, 'unable to evalExp: scope undefined')
var operatorREs = lexical.operators
var match
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i]
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
let operatorREs = lexical.operators
let match
for (let i = 0; i < operatorREs.length; i++) {
let operatorRE = operatorREs[i]
let expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
if ((match = exp.match(expRE))) {
var l = evalExp(match[1], scope)
var op = operators[match[2].trim()]
var r = evalExp(match[3], scope)
let l = evalExp(match[1], scope)
let op = operators[match[2].trim()]
let r = evalExp(match[3], scope)
return op(l, r)
}
}
if ((match = exp.match(lexical.rangeLine))) {
var low = evalValue(match[1], scope)
var high = evalValue(match[2], scope)
var range = []
for (var j = low; j <= high; j++) {
let low = evalValue(match[1], scope)
let high = evalValue(match[2], scope)
let range = []
for (let j = low; j <= high; j++) {
range.push(j)
}
return range
+4 -5
View File
@@ -1,9 +1,8 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
import {lexical} from '../index'
import assert from '../util/assert.js'
import {types} from '../scope'
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
const assert = require('../util/assert.js')
const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('assign', {
+2 -2
View File
@@ -8,13 +8,13 @@ const types = require('../scope.js').types
module.exports = function (liquid) {
liquid.registerTag('capture', {
parse: function (tagToken, remainTokens) {
var match = tagToken.args.match(re)
let match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
this.templates = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', token => stream.stop())
.on('template', tpl => this.templates.push(tpl))
.on('end', x => {
+7 -7
View File
@@ -1,4 +1,4 @@
const Liquid = require('..')
import Liquid from '..'
module.exports = function (liquid) {
liquid.registerTag('case', {
@@ -8,8 +8,8 @@ module.exports = function (liquid) {
this.cases = []
this.elseTemplates = []
var p = []
var stream = liquid.parser.parseStream(remainTokens)
let p = []
let stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
@@ -27,10 +27,10 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
for (var i = 0; i < this.cases.length; i++) {
var branch = this.cases[i]
var val = Liquid.evalExp(branch.val, scope)
var cond = Liquid.evalExp(this.cond, scope)
for (let i = 0; i < this.cases.length; i++) {
let branch = this.cases[i]
let val = Liquid.evalExp(branch.val, scope)
let cond = Liquid.evalExp(this.cond, scope)
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+1 -1
View File
@@ -1,7 +1,7 @@
module.exports = function (liquid) {
liquid.registerTag('comment', {
parse: function (tagToken, remainTokens) {
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endcomment') stream.stop()
+7 -7
View File
@@ -8,11 +8,11 @@ module.exports = function (liquid) {
liquid.registerTag('cycle', {
parse: function (tagToken, remainTokens) {
var match = groupRE.exec(tagToken.args)
let match = groupRE.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
var candidates = match[2]
let candidates = match[2]
this.candidates = []
@@ -23,17 +23,17 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var group = Liquid.evalValue(this.group, scope)
var fingerprint = `cycle:${group}:` + this.candidates.join(',')
let group = Liquid.evalValue(this.group, scope)
let fingerprint = `cycle:${group}:` + this.candidates.join(',')
var groups = scope.opts.groups = scope.opts.groups || {}
var idx = groups[fingerprint]
let groups = scope.opts.groups = scope.opts.groups || {}
let idx = groups[fingerprint]
if (idx === undefined) {
idx = groups[fingerprint] = 0
}
var candidate = this.candidates[idx]
let candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx
+1 -1
View File
@@ -7,7 +7,7 @@ const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('decrement', {
parse: function (token) {
var match = token.args.match(lexical.identifier)
let match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
+14 -14
View File
@@ -1,9 +1,9 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const mapSeries = require('../util/promise.js').mapSeries
const _ = require('../util/underscore.js')
import {default as Liquid, lexical} from '../index'
import {mapSeries} from '../util/promise.js'
import _ from '../util/underscore.js'
import assert from '../util/assert.js'
const RenderBreakError = Liquid.Types.RenderBreakError
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*` +
@@ -14,7 +14,7 @@ module.exports = function (liquid) {
liquid.registerTag('for', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
let match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
@@ -23,8 +23,8 @@ module.exports = function (liquid) {
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
@@ -37,7 +37,7 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
let collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
@@ -50,14 +50,14 @@ module.exports = function (liquid) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
let offset = hash.offset || 0
let limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
var contexts = collection.map((item, i) => {
var ctx = {}
let contexts = collection.map((item, i) => {
let ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
@@ -71,7 +71,7 @@ module.exports = function (liquid) {
return ctx
})
var html = ''
let html = ''
return mapSeries(contexts, (context) => {
return Promise.resolve()
.then(() => scope.push(context))
+6 -6
View File
@@ -1,4 +1,4 @@
const Liquid = require('..')
import Liquid from '..'
module.exports = function (liquid) {
liquid.registerTag('if', {
@@ -7,8 +7,8 @@ module.exports = function (liquid) {
this.branches = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
@@ -30,9 +30,9 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i]
var cond = Liquid.evalExp(branch.cond, scope)
for (let i = 0; i < this.branches.length; i++) {
let branch = this.branches[i]
let cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+4 -4
View File
@@ -12,7 +12,7 @@ const staticFileRE = /\S+/
module.exports = function (liquid) {
liquid.registerTag('layout', {
parse: function (token, remainTokens) {
var match = staticFileRE.exec(token.args)
let match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
}
@@ -25,7 +25,7 @@ module.exports = function (liquid) {
this.tpls = liquid.parser.parse(remainTokens)
},
render: function (scope, hash) {
var layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
let layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately
@@ -51,11 +51,11 @@ module.exports = function (liquid) {
liquid.registerTag('block', {
parse: function (token, remainTokens) {
var match = /\w+/.exec(token.args)
let match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
+1 -1
View File
@@ -3,7 +3,7 @@ module.exports = function (liquid) {
parse: function (tagToken, remainTokens) {
this.tokens = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
+16 -15
View File
@@ -1,7 +1,8 @@
const Liquid = require('..')
const mapSeries = require('../util/promise.js').mapSeries
import Liquid from '..'
import {mapSeries} from '../util/promise.js'
import assert from '../util/assert.js'
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`)
@@ -10,15 +11,15 @@ module.exports = function (liquid) {
liquid.registerTag('tablerow', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
let match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.templates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
@@ -30,21 +31,21 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope) || []
let collection = Liquid.evalExp(this.collection, scope) || []
var html = ''
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
let html = ''
let offset = hash.offset || 0
let limit = (hash.limit === undefined) ? collection.length : hash.limit
var cols = hash.cols
var row
var col
let cols = hash.cols
let row
let col
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit)
if (!cols) cols = collection.length
var contexts = collection.map((item, i) => {
var ctx = {}
let contexts = collection.map((item, i) => {
let ctx = {}
ctx[this.variable] = item
return ctx
})
+4 -4
View File
@@ -1,12 +1,12 @@
const Liquid = require('..')
import Liquid from '../index'
module.exports = function (liquid) {
liquid.registerTag('unless', {
parse: function (tagToken, remainTokens) {
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', x => {
p = this.templates
this.cond = tagToken.args
@@ -22,7 +22,7 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var cond = Liquid.evalExp(this.cond, scope)
let cond = Liquid.evalExp(this.cond, scope)
return Liquid.isFalsy(cond)
? liquid.renderer.renderTemplates(this.templates, scope)
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
+12 -12
View File
@@ -7,13 +7,13 @@ const assert = require('./util/assert.js')
function parse (input, file, options) {
assert(_.isString(input), 'illegal input')
var rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
var currIndent = 0
var lineNumber = LineNumber(input)
var lastMatchEnd = 0
var tokens = []
let rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
let currIndent = 0
let lineNumber = LineNumber(input)
let lastMatchEnd = 0
let tokens = []
for (var match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
if (match.index > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
}
@@ -28,8 +28,8 @@ function parse (input, file, options) {
return tokens
function parseTagToken (raw, value, pos) {
var match = value.match(lexical.tagLine)
var token = {
let match = value.match(lexical.tagLine)
let token = {
type: 'tag',
indent: currIndent,
line: lineNumber.get(pos),
@@ -62,7 +62,7 @@ function parse (input, file, options) {
}
function parseHTMLToken (begin, end) {
var htmlFragment = input.slice(begin, end)
let htmlFragment = input.slice(begin, end)
currIndent = _.last((htmlFragment).split('\n')).length
return {
@@ -74,12 +74,12 @@ function parse (input, file, options) {
}
function LineNumber (html) {
var parsedLinesCount = 0
var lastMatchBegin = -1
let parsedLinesCount = 0
let lastMatchBegin = -1
return {
get: function (pos) {
var lines = html.slice(lastMatchBegin + 1, pos).split('\n')
let lines = html.slice(lastMatchBegin + 1, pos).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = pos
return parsedLinesCount + 1
+9 -9
View File
@@ -1,4 +1,4 @@
const _ = require('./underscore.js')
import _ from './underscore.js'
function initError () {
this.name = this.constructor.name
@@ -14,7 +14,7 @@ function initLiquidError (err, token) {
this.line = token.line
this.file = token.file
var context = mkContext(token.input, token.line)
let context = mkContext(token.input, token.line)
this.message = mkMessage(err.message, token)
this.stack = context +
'\n' + (this.stack || this.message) +
@@ -64,11 +64,11 @@ AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype.constructor = AssertionError
function mkContext (input, line) {
var lines = input.split('\n')
var begin = Math.max(line - 2, 1)
var end = Math.min(line + 3, lines.length)
let lines = input.split('\n')
let begin = Math.max(line - 2, 1)
let end = Math.min(line + 3, lines.length)
var context = _
let context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
@@ -82,9 +82,9 @@ function mkContext (input, line) {
}
function align (n, max) {
var length = (max + '').length
var str = n + ''
var blank = Array(length - str.length).join(' ')
let length = (max + '').length
let str = n + ''
let blank = Array(length - str.length).join(' ')
return blank + str
}
+3 -3
View File
@@ -5,7 +5,7 @@
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function anySeries (iterable, iteratee) {
var ret = Promise.reject(new Error('init'))
let ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable))
})
@@ -19,8 +19,8 @@ function anySeries (iterable, iteratee) {
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function mapSeries (iterable, iteratee) {
var ret = Promise.resolve('init')
var result = []
let ret = Promise.resolve('init')
let result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
+27 -27
View File
@@ -1,16 +1,16 @@
var monthNames = [
let monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
]
var monthNamesShort = [
let monthNamesShort = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
]
var dayNames = [
let dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
var suffixes = {
let dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
let suffixes = {
1: 'st',
2: 'nd',
3: 'rd',
@@ -18,15 +18,15 @@ var suffixes = {
}
// prototype extensions
var _date = {
let _date = {
daysInMonth: function (d) {
var feb = _date.isLeapYear(d) ? 29 : 28
let feb = _date.isLeapYear(d) ? 29 : 28
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
},
getDayOfYear: function (d) {
var num = 0
for (var i = 0; i < d.getMonth(); ++i) {
let num = 0
for (let i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i]
}
return num + d.getDate()
@@ -36,21 +36,21 @@ var _date = {
// TODO: that comment was retarted. fix it.
getWeekOfYear: function (d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay())
let now = this.getDayOfYear(d) + (startDay - d.getDay())
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1)
var then = (7 - jan1.getDay() + startDay)
let jan1 = new Date(d.getFullYear(), 0, 1)
let then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
},
isLeapYear: function (d) {
var year = d.getFullYear()
let year = d.getFullYear()
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
},
getSuffix: function (d) {
var str = d.getDate().toString()
var index = parseInt(str.slice(-1))
let str = d.getDate().toString()
let index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default']
},
@@ -59,11 +59,11 @@ var _date = {
}
}
var _number = {
let _number = {
pad: function (value, size, ch) {
if (!ch) ch = '0'
var result = value.toString()
var pad = size - result.length
let result = value.toString()
let pad = size - result.length
while (pad-- > 0) {
result = ch + result
@@ -73,7 +73,7 @@ var _number = {
}
}
var formatCodes = {
let formatCodes = {
a: function (d) {
return dayNamesShort[d.getDay()]
},
@@ -162,7 +162,7 @@ var formatCodes = {
return d.getFullYear()
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
let tz = d.getTimezoneOffset() / 60 * 100
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
@@ -172,13 +172,13 @@ var formatCodes = {
formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L
var strftime = function (d, format) {
var output = ''
var remaining = format
let strftime = function (d, format) {
let output = ''
let remaining = format
while (true) {
var r = /%./g
var results = r.exec(remaining)
let r = /%./g
let results = r.exec(remaining)
// No more format codes. Add the remaining text and return
if (!results) {
@@ -190,8 +190,8 @@ var strftime = function (d, format) {
remaining = remaining.slice(r.lastIndex)
// Add the format code
var ch = results[0].charAt(1)
var func = formatCodes[ch]
let ch = results[0].charAt(1)
let func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch
}
}
+9 -10
View File
@@ -1,4 +1,3 @@
'use strict'
const toStr = Object.prototype.toString
/*
@@ -46,7 +45,7 @@ function isArray (value) {
}
function isError (value) {
var signature = Object.prototype.toString.call(value)
let signature = Object.prototype.toString.call(value)
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
@@ -62,7 +61,7 @@ function isError (value) {
*/
function forOwn (object, iteratee) {
object = object || {}
for (var k in object) {
for (let k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break
}
@@ -83,7 +82,7 @@ function forOwn (object, iteratee) {
*/
function assign (object) {
object = isObject(object) ? object : {}
var srcs = Array.prototype.slice.call(arguments, 1)
let srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach((src) => Object.assign(object, src))
return object
}
@@ -93,9 +92,9 @@ function last (arr) {
}
function uniq (arr) {
var u = {}
var a = []
for (var i = 0, l = arr.length; i < l; ++i) {
let u = {}
let a = []
for (let i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue
}
@@ -112,7 +111,7 @@ function uniq (arr) {
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject (value) {
var type = typeof value
let type = typeof value
return value != null && (type === 'object' || type === 'function')
}
@@ -131,8 +130,8 @@ function range (start, stop, step) {
}
step = step || 1
var arr = []
for (var i = start; i < stop; i += step) {
let arr = []
for (let i = start; i < stop; i += step) {
arr.push(i)
}
return arr
+7 -6
View File
@@ -1,24 +1,25 @@
const resolve = require('resolve-url')
import resolveUrl from 'resolve-url'
import _ from './underscore'
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
const _ = require('./underscore')
// https://github.com/jinder/path/blob/master/path.js#L567
exports.extname = function (path) {
export function extname (path) {
return splitPathRe.exec(path).slice(1)[3]
}
// https://www.npmjs.com/package/is-url
exports.valid = function (path) {
export function valid (path) {
return urlRe.test(path)
}
exports.resolve = function (root, path) {
export function resolve (root, path) {
if (Object.prototype.toString.call(root) === '[object Array]') {
root = root[0]
}
if (root && _.last(root) !== '/') {
root += '/'
}
return resolve(root, path)
return resolveUrl(root, path)
}
+3 -3
View File
@@ -2,7 +2,7 @@ const _ = require('./util/underscore.js')
function whiteSpaceCtrl (tokens, options) {
options = _.assign({ greedy: true }, options)
var inRaw = false
let inRaw = false
tokens.forEach((token, i) => {
if (shouldTrimLeft(token, inRaw, options)) {
@@ -33,14 +33,14 @@ function shouldTrimRight (token, inRaw, options) {
function trimLeft (token, greedy) {
if (!token || token.type !== 'html') return
var rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
let rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '')
}
function trimRight (token, greedy) {
if (!token || token.type !== 'html') return
var rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
let rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '')
}