mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-16 04:40:39 -07:00
refactor: import rollup
This commit is contained in:
+18
-18
@@ -1,17 +1,17 @@
|
||||
const lexical = require('./lexical.js')
|
||||
const Syntax = require('./syntax.js')
|
||||
const assert = require('./util/assert.js')
|
||||
const _ = require('./util/underscore.js')
|
||||
import * as lexical from './lexical.js'
|
||||
import {evalValue} from './syntax.js'
|
||||
import assert from './util/assert.js'
|
||||
import {assign} from './util/underscore.js'
|
||||
|
||||
let valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||
const valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||
|
||||
module.exports = function (options) {
|
||||
options = _.assign({}, options)
|
||||
export default function (options) {
|
||||
options = assign({}, options)
|
||||
let filters = {}
|
||||
|
||||
let _filterInstance = {
|
||||
const _filterInstance = {
|
||||
render: function (output, scope) {
|
||||
let args = this.args.map(arg => Syntax.evalValue(arg, scope))
|
||||
const args = this.args.map(arg => evalValue(arg, scope))
|
||||
args.unshift(output)
|
||||
return this.filter.apply(null, args)
|
||||
},
|
||||
@@ -19,9 +19,9 @@ module.exports = function (options) {
|
||||
let match = lexical.filterLine.exec(str)
|
||||
assert(match, 'illegal filter: ' + str)
|
||||
|
||||
let name = match[1]
|
||||
let argList = match[2] || ''
|
||||
let filter = filters[name]
|
||||
const name = match[1]
|
||||
const argList = match[2] || ''
|
||||
const 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
|
||||
}
|
||||
|
||||
let args = []
|
||||
const args = []
|
||||
while ((match = valueRE.exec(argList.trim()))) {
|
||||
let v = match[0]
|
||||
let re = new RegExp(`${v}\\s*:`, 'g')
|
||||
let keyMatch = re.exec(match.input)
|
||||
let currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
||||
const v = match[0]
|
||||
const re = new RegExp(`${v}\\s*:`, 'g')
|
||||
const keyMatch = re.exec(match.input)
|
||||
const currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
||||
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ module.exports = function (options) {
|
||||
}
|
||||
|
||||
function construct (str) {
|
||||
let instance = Object.create(_filterInstance)
|
||||
const instance = Object.create(_filterInstance)
|
||||
return instance.parse(str)
|
||||
}
|
||||
|
||||
|
||||
+15
-17
@@ -1,16 +1,15 @@
|
||||
'use strict'
|
||||
const strftime = require('./util/strftime.js')
|
||||
const _ = require('./util/underscore.js')
|
||||
const isTruthy = require('./syntax.js').isTruthy
|
||||
import strftime from './util/strftime.js'
|
||||
import * as _ from './util/underscore.js'
|
||||
import {isTruthy} from './syntax.js'
|
||||
|
||||
let escapeMap = {
|
||||
const escapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}
|
||||
let unescapeMap = {
|
||||
const unescapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
@@ -18,7 +17,7 @@ let unescapeMap = {
|
||||
''': "'"
|
||||
}
|
||||
|
||||
let filters = {
|
||||
const filters = {
|
||||
'abs': v => Math.abs(v),
|
||||
'append': (v, arg) => v + arg,
|
||||
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
|
||||
@@ -57,7 +56,7 @@ let filters = {
|
||||
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
|
||||
'reverse': v => v.reverse(),
|
||||
'round': (v, arg) => {
|
||||
let amp = Math.pow(10, arg || 0)
|
||||
const amp = Math.pow(10, arg || 0)
|
||||
return Math.round(v * amp, arg) / amp
|
||||
},
|
||||
'rstrip': str => stringify(str).replace(/\s+$/, ''),
|
||||
@@ -79,13 +78,13 @@ let filters = {
|
||||
},
|
||||
'truncatewords': (v, l, o) => {
|
||||
if (o === undefined) o = '...'
|
||||
let arr = v.split(' ')
|
||||
const arr = v.split(' ')
|
||||
let ret = arr.slice(0, l).join(' ')
|
||||
if (arr.length > l) ret += o
|
||||
return ret
|
||||
},
|
||||
'uniq': function (arr) {
|
||||
let u = {}
|
||||
const u = {}
|
||||
return (arr || []).filter(val => {
|
||||
if (u.hasOwnProperty(val)) {
|
||||
return false
|
||||
@@ -107,7 +106,7 @@ function unescape (str) {
|
||||
}
|
||||
|
||||
function getFixed (v) {
|
||||
let p = (v + '').split('.')
|
||||
const p = (v + '').split('.')
|
||||
return (p.length > 1) ? p[1].length : 0
|
||||
}
|
||||
|
||||
@@ -121,18 +120,17 @@ function stringify (obj) {
|
||||
|
||||
function bindFixed (cb) {
|
||||
return (l, r) => {
|
||||
let f = getMaxFixed(l, r)
|
||||
const f = getMaxFixed(l, r)
|
||||
return cb(l, r).toFixed(f)
|
||||
}
|
||||
}
|
||||
|
||||
function registerAll (liquid) {
|
||||
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
|
||||
}
|
||||
|
||||
function isValidDate (date) {
|
||||
return date instanceof Date && !isNaN(date.getTime())
|
||||
}
|
||||
|
||||
export default function registerAll (liquid) {
|
||||
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
|
||||
}
|
||||
|
||||
registerAll.filters = filters
|
||||
module.exports = registerAll
|
||||
|
||||
+73
-90
@@ -1,22 +1,24 @@
|
||||
import Scope from './scope'
|
||||
import _ from './util/underscore.js'
|
||||
import 'regenerator-runtime/runtime'
|
||||
import * as Scope from './scope'
|
||||
import {get as httpGet} from './util/http.js'
|
||||
import * as _ from './util/underscore.js'
|
||||
import assert from './util/assert.js'
|
||||
import tokenizer from './tokenizer.js'
|
||||
import * as 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 * as 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 {ParseError, TokenizationEroor, RenderBreakError, AssertionError} from './util/error.js'
|
||||
import {ParseError, TokenizationError, RenderBreakError, AssertionError} from './util/error.js'
|
||||
import tags from './tags/index.js'
|
||||
import filters from './filters.js'
|
||||
|
||||
let _engine = {
|
||||
const _engine = {
|
||||
init: function (tag, filter, options) {
|
||||
if (options.cache) {
|
||||
this.cache = {}
|
||||
@@ -27,32 +29,31 @@ let _engine = {
|
||||
this.parser = Parser(tag, filter)
|
||||
this.renderer = Render()
|
||||
|
||||
tags(this)
|
||||
filters(this)
|
||||
tags(this, Liquid)
|
||||
filters(this, Liquid)
|
||||
|
||||
return this
|
||||
},
|
||||
parse: function (html, filepath) {
|
||||
let tokens = tokenizer.parse(html, filepath, this.options)
|
||||
const tokens = tokenizer.parse(html, filepath, this.options)
|
||||
return this.parser.parse(tokens)
|
||||
},
|
||||
render: function (tpl, ctx, opts) {
|
||||
opts = _.assign({}, this.options, opts)
|
||||
let scope = Scope.factory(ctx, opts)
|
||||
const scope = Scope.factory(ctx, opts)
|
||||
return this.renderer.renderTemplates(tpl, scope)
|
||||
},
|
||||
parseAndRender: function (html, ctx, opts) {
|
||||
return Promise.resolve()
|
||||
.then(() => this.parse(html))
|
||||
.then(tpl => this.render(tpl, ctx, opts))
|
||||
parseAndRender: async function (html, ctx, opts) {
|
||||
const tpl = await this.parse(html)
|
||||
return this.render(tpl, ctx, opts)
|
||||
},
|
||||
renderFile: function (filepath, ctx, opts) {
|
||||
renderFile: async function (filepath, ctx, opts) {
|
||||
opts = _.assign({}, opts)
|
||||
return this.getTemplate(filepath, opts.root)
|
||||
.then(templates => this.render(templates, ctx, opts))
|
||||
const templates = await this.getTemplate(filepath, opts.root)
|
||||
return this.render(templates, ctx, opts)
|
||||
},
|
||||
evalValue: function (str, scope) {
|
||||
let tpl = this.parser.parseValue(str.trim())
|
||||
const tpl = this.parser.parseValue(str.trim())
|
||||
return this.renderer.evalValue(tpl, scope)
|
||||
},
|
||||
registerFilter: function (name, filter) {
|
||||
@@ -64,39 +65,33 @@ let _engine = {
|
||||
lookup: function (filepath, root) {
|
||||
root = this.options.root.concat(root || [])
|
||||
root = _.uniq(root)
|
||||
let paths = root.map(root => path.resolve(root, filepath))
|
||||
return anySeries(paths, path => statFileAsync(path).then(() => path))
|
||||
.catch((e) => {
|
||||
const paths = root.map(root => path.resolve(root, filepath))
|
||||
return anySeries(paths, async path => {
|
||||
try {
|
||||
await statFileAsync(path)
|
||||
return path
|
||||
} catch (e) {
|
||||
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
|
||||
throw e
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
getTemplate: function (filepath, root) {
|
||||
return typeof XMLHttpRequest === 'undefined'
|
||||
? this.getTemplateFromFile(filepath, root)
|
||||
: this.getTemplateFromUrl(filepath, root)
|
||||
},
|
||||
getTemplateFromFile: function (filepath, root) {
|
||||
getTemplateFromFile: async function (filepath, root) {
|
||||
if (!path.extname(filepath)) {
|
||||
filepath += this.options.extname
|
||||
}
|
||||
return this
|
||||
.lookup(filepath, root)
|
||||
.then(filepath => {
|
||||
if (this.options.cache) {
|
||||
let tpl = this.cache[filepath]
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl)
|
||||
}
|
||||
return readFileAsync(filepath)
|
||||
.then(str => this.parse(str))
|
||||
.then(tpl => (this.cache[filepath] = tpl))
|
||||
} else {
|
||||
return readFileAsync(filepath).then(str => this.parse(str, filepath))
|
||||
}
|
||||
})
|
||||
filepath = await this.lookup(filepath, root)
|
||||
return this.respectCache(filepath, async () => {
|
||||
const str = await readFileAsync(filepath)
|
||||
return this.parse(str, filepath)
|
||||
})
|
||||
},
|
||||
getTemplateFromUrl: function (filepath, root) {
|
||||
getTemplateFromUrl: async function (filepath, root) {
|
||||
let fullUrl
|
||||
if (isValidUrl(filepath)) {
|
||||
fullUrl = filepath
|
||||
@@ -106,47 +101,41 @@ let _engine = {
|
||||
}
|
||||
fullUrl = resolve(root || this.options.root, filepath)
|
||||
}
|
||||
if (this.options.cache) {
|
||||
let tpl = this.cache[filepath]
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl)
|
||||
}
|
||||
return this.respectCache(
|
||||
filepath,
|
||||
async () => this.parse(await httpGet(fullUrl))
|
||||
)
|
||||
},
|
||||
respectCache: async function (key, getter) {
|
||||
const cacheEnabled = this.options.cache
|
||||
if (cacheEnabled && this.cache[key]) {
|
||||
return this.cache[key]
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
let xhr = new XMLHttpRequest()
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
let tpl = this.parse(xhr.responseText)
|
||||
if (this.options.cache) {
|
||||
this.cache[filepath] = tpl
|
||||
}
|
||||
resolve(tpl)
|
||||
} else {
|
||||
reject(new Error(xhr.statusText))
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('An error occurred whilst sending the response.'))
|
||||
}
|
||||
xhr.open('GET', fullUrl)
|
||||
xhr.send()
|
||||
})
|
||||
const value = await getter()
|
||||
if (cacheEnabled) {
|
||||
this.cache[key] = value
|
||||
}
|
||||
return value
|
||||
},
|
||||
express: function (opts) {
|
||||
opts = opts || {}
|
||||
let self = this
|
||||
return function (filePath, ctx, callback) {
|
||||
const self = this
|
||||
return function (filePath, ctx, cb) {
|
||||
assert(Array.isArray(this.root) || _.isString(this.root),
|
||||
'illegal views root, are you using express.js?')
|
||||
opts.root = this.root
|
||||
self.renderFile(filePath, ctx, opts)
|
||||
.then(html => callback(null, html))
|
||||
.catch(e => callback(e))
|
||||
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function factory (options) {
|
||||
function normalizeStringArray (value) {
|
||||
if (Array.isArray(value)) return value
|
||||
if (_.isString(value)) return [value]
|
||||
return []
|
||||
}
|
||||
|
||||
export default function Liquid (options) {
|
||||
options = _.assign({
|
||||
root: ['.'],
|
||||
cache: false,
|
||||
@@ -162,29 +151,23 @@ function factory (options) {
|
||||
}, options)
|
||||
options.root = normalizeStringArray(options.root)
|
||||
|
||||
let engine = Object.create(_engine)
|
||||
const engine = Object.create(_engine)
|
||||
engine.init(Tag(), Filter(options), options)
|
||||
return engine
|
||||
}
|
||||
|
||||
function normalizeStringArray (value) {
|
||||
if (Array.isArray(value)) return value
|
||||
if (_.isString(value)) return [value]
|
||||
return []
|
||||
}
|
||||
|
||||
const Types = {
|
||||
Liquid.isTruthy = isTruthy
|
||||
Liquid.isFalsy = isFalsy
|
||||
Liquid.evalExp = evalExp
|
||||
Liquid.evalValue = evalValue
|
||||
Liquid.Types = {
|
||||
ParseError,
|
||||
TokenizationEroor,
|
||||
TokenizationError,
|
||||
RenderBreakError,
|
||||
AssertionError
|
||||
AssertionError,
|
||||
AssignScope: Object.create(null),
|
||||
CaptureScope: Object.create(null),
|
||||
IncrementScope: Object.create(null),
|
||||
DecrementScope: Object.create(null)
|
||||
}
|
||||
|
||||
factory.isTruthy = isTruthy
|
||||
factory.isFalsy = isFalsy
|
||||
factory.evalExp = evalExp
|
||||
factory.evalValue = evalValue
|
||||
factory.Types = Types
|
||||
factory.lexical = lexical
|
||||
|
||||
module.exports = factory
|
||||
Liquid.lexical = lexical
|
||||
|
||||
+37
-67
@@ -1,75 +1,75 @@
|
||||
// quote related
|
||||
let singleQuoted = /'[^']*'/
|
||||
let doubleQuoted = /"[^"]*"/
|
||||
let quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
|
||||
let quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
|
||||
const singleQuoted = /'[^']*'/
|
||||
const doubleQuoted = /"[^"]*"/
|
||||
export const quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
|
||||
export const quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
|
||||
|
||||
// basic types
|
||||
let integer = /-?\d+/
|
||||
let number = /-?\d+\.?\d*|\.?\d+/
|
||||
let bool = /true|false/
|
||||
export const integer = /-?\d+/
|
||||
export const number = /-?\d+\.?\d*|\.?\d+/
|
||||
export const bool = /true|false/
|
||||
|
||||
// peoperty access
|
||||
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})*`)
|
||||
export const identifier = /[\w-]+[?]?/
|
||||
export const subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
|
||||
export const literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
|
||||
export const variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
|
||||
|
||||
// range related
|
||||
let rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
|
||||
let range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
|
||||
let rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
|
||||
export const rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
|
||||
export const range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
|
||||
export const rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
|
||||
|
||||
let value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
|
||||
export const value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
|
||||
|
||||
// hash related
|
||||
let hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
|
||||
let hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
|
||||
export const hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
|
||||
export const hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
|
||||
|
||||
// full match
|
||||
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}$`)
|
||||
export const tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
|
||||
export const literalLine = new RegExp(`^${literal.source}$`, 'i')
|
||||
export const variableLine = new RegExp(`^${variable.source}$`)
|
||||
export const numberLine = new RegExp(`^${number.source}$`)
|
||||
export const boolLine = new RegExp(`^${bool.source}$`, 'i')
|
||||
export const quotedLine = new RegExp(`^${quoted.source}$`)
|
||||
export const rangeLine = new RegExp(`^${rangeCapture.source}$`)
|
||||
export const integerLine = new RegExp(`^${integer.source}$`)
|
||||
|
||||
// filter related
|
||||
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}$`)
|
||||
export const valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
|
||||
export const valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
|
||||
export const filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
|
||||
export const filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
|
||||
export const filterLine = new RegExp(`^${filterCapture.source}$`)
|
||||
|
||||
let operators = [
|
||||
export const operators = [
|
||||
/\s+or\s+/,
|
||||
/\s+and\s+/,
|
||||
/==|!=|<=|>=|<|>|\s+contains\s+/
|
||||
]
|
||||
|
||||
function isInteger (str) {
|
||||
export function isInteger (str) {
|
||||
return integerLine.test(str)
|
||||
}
|
||||
|
||||
function isLiteral (str) {
|
||||
export function isLiteral (str) {
|
||||
return literalLine.test(str)
|
||||
}
|
||||
|
||||
function isRange (str) {
|
||||
export function isRange (str) {
|
||||
return rangeLine.test(str)
|
||||
}
|
||||
|
||||
function isVariable (str) {
|
||||
export function isVariable (str) {
|
||||
return variableLine.test(str)
|
||||
}
|
||||
|
||||
function matchValue (str) {
|
||||
export function matchValue (str) {
|
||||
return value.exec(str)
|
||||
}
|
||||
|
||||
function parseLiteral (str) {
|
||||
export function parseLiteral (str) {
|
||||
let res = str.match(numberLine)
|
||||
if (res) {
|
||||
return Number(str)
|
||||
@@ -84,33 +84,3 @@ function parseLiteral (str) {
|
||||
}
|
||||
throw new TypeError(`cannot parse '${str}' as literal`)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
quoted,
|
||||
number,
|
||||
bool,
|
||||
literal,
|
||||
filter,
|
||||
integer,
|
||||
hash,
|
||||
hashCapture,
|
||||
range,
|
||||
rangeCapture,
|
||||
identifier,
|
||||
value,
|
||||
quoteBalanced,
|
||||
operators,
|
||||
quotedLine,
|
||||
numberLine,
|
||||
boolLine,
|
||||
rangeLine,
|
||||
literalLine,
|
||||
filterLine,
|
||||
tagLine,
|
||||
isLiteral,
|
||||
isVariable,
|
||||
parseLiteral,
|
||||
isRange,
|
||||
matchValue,
|
||||
isInteger
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
module.exports = function (isTruthy) {
|
||||
export default function (isTruthy) {
|
||||
return {
|
||||
'==': (l, r) => l === r,
|
||||
'!=': (l, r) => l !== r,
|
||||
|
||||
+11
-11
@@ -1,9 +1,9 @@
|
||||
const lexical = require('./lexical.js')
|
||||
const ParseError = require('./util/error.js').ParseError
|
||||
const assert = require('./util/assert.js')
|
||||
import * as lexical from './lexical.js'
|
||||
import {ParseError} from './util/error.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
module.exports = function (Tag, Filter) {
|
||||
let stream = {
|
||||
export default function (Tag, Filter) {
|
||||
const stream = {
|
||||
init: function (tokens) {
|
||||
this.tokens = tokens
|
||||
this.handlers = {}
|
||||
@@ -14,7 +14,7 @@ module.exports = function (Tag, Filter) {
|
||||
return this
|
||||
},
|
||||
trigger: function (event, arg) {
|
||||
let h = this.handlers[event]
|
||||
const h = this.handlers[event]
|
||||
if (typeof h === 'function') {
|
||||
h(arg)
|
||||
return true
|
||||
@@ -29,7 +29,7 @@ module.exports = function (Tag, Filter) {
|
||||
this.trigger(`tag:${token.name}`, token)) {
|
||||
continue
|
||||
}
|
||||
let template = parseToken(token, this.tokens)
|
||||
const template = parseToken(token, this.tokens)
|
||||
this.trigger('template', template)
|
||||
}
|
||||
if (!this.stopRequested) this.trigger('end')
|
||||
@@ -43,7 +43,7 @@ module.exports = function (Tag, Filter) {
|
||||
|
||||
function parse (tokens) {
|
||||
let token
|
||||
let templates = []
|
||||
const templates = []
|
||||
while ((token = tokens.shift())) {
|
||||
templates.push(parseToken(token, tokens))
|
||||
}
|
||||
@@ -76,10 +76,10 @@ module.exports = function (Tag, Filter) {
|
||||
let match = lexical.matchValue(str)
|
||||
assert(match, `illegal value string: ${str}`)
|
||||
|
||||
let initial = match[0]
|
||||
const initial = match[0]
|
||||
str = str.substr(match.index + match[0].length)
|
||||
|
||||
let filters = []
|
||||
const filters = []
|
||||
while ((match = lexical.filter.exec(str))) {
|
||||
filters.push([match[0].trim()])
|
||||
}
|
||||
@@ -92,7 +92,7 @@ module.exports = function (Tag, Filter) {
|
||||
}
|
||||
|
||||
function parseStream (tokens) {
|
||||
let s = Object.create(stream)
|
||||
const s = Object.create(stream)
|
||||
return s.init(tokens)
|
||||
}
|
||||
|
||||
|
||||
+36
-41
@@ -1,67 +1,62 @@
|
||||
const Syntax = require('./syntax.js')
|
||||
const mapSeries = require('./util/promise.js').mapSeries
|
||||
const RenderBreakError = require('./util/error.js').RenderBreakError
|
||||
const _ = require('./util/underscore.js')
|
||||
const RenderError = require('./util/error.js').RenderError
|
||||
const assert = require('./util/assert.js')
|
||||
import {evalExp} from './syntax.js'
|
||||
import {RenderBreakError, RenderError} from './util/error.js'
|
||||
import {stringify} from './util/underscore.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
let render = {
|
||||
|
||||
renderTemplates: function (templates, scope) {
|
||||
const render = {
|
||||
renderTemplates: async function (templates, scope) {
|
||||
assert(scope, 'unable to evalTemplates: scope undefined')
|
||||
|
||||
let html = ''
|
||||
return mapSeries(templates, (tpl) => {
|
||||
return renderTemplate.call(this, tpl)
|
||||
.then(partial => (html += partial))
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
e.resolvedHTML = html
|
||||
throw e
|
||||
}
|
||||
throw new RenderError(e, tpl)
|
||||
})
|
||||
}).then(() => html)
|
||||
|
||||
function renderTemplate (template) {
|
||||
if (template.type === 'tag') {
|
||||
return this.renderTag(template, scope)
|
||||
.then(partial => partial === undefined ? '' : partial)
|
||||
} else if (template.type === 'value') {
|
||||
return this.renderValue(template, scope)
|
||||
} else { // template.type === 'html'
|
||||
return Promise.resolve(template.value)
|
||||
for (const tpl of templates) {
|
||||
try {
|
||||
html += await renderTemplate.call(this, tpl)
|
||||
} catch (e) {
|
||||
if (e instanceof RenderBreakError) {
|
||||
e.resolvedHTML = html
|
||||
throw e
|
||||
}
|
||||
throw new RenderError(e, tpl)
|
||||
}
|
||||
}
|
||||
return html
|
||||
|
||||
async function renderTemplate (template) {
|
||||
if (template.type === 'tag') {
|
||||
const partial = await this.renderTag(template, scope)
|
||||
return partial === undefined ? '' : partial
|
||||
}
|
||||
if (template.type === 'value') {
|
||||
return this.renderValue(template, scope)
|
||||
}
|
||||
return template.value
|
||||
}
|
||||
},
|
||||
|
||||
renderTag: function (template, scope) {
|
||||
renderTag: async function (template, scope) {
|
||||
if (template.name === 'continue') {
|
||||
return Promise.reject(new RenderBreakError('continue'))
|
||||
throw new RenderBreakError('continue')
|
||||
}
|
||||
if (template.name === 'break') {
|
||||
return Promise.reject(new RenderBreakError('break'))
|
||||
throw new RenderBreakError('break')
|
||||
}
|
||||
return template.render(scope)
|
||||
},
|
||||
|
||||
renderValue: function (template, scope) {
|
||||
return Promise.resolve()
|
||||
.then(() => this.evalValue(template, scope))
|
||||
.then(partial => partial === undefined ? '' : _.stringify(partial))
|
||||
renderValue: async function (template, scope) {
|
||||
const partial = this.evalValue(template, scope)
|
||||
return partial === undefined ? '' : stringify(partial)
|
||||
},
|
||||
|
||||
evalValue: function (template, scope) {
|
||||
assert(scope, 'unable to evalValue: scope undefined')
|
||||
return template.filters.reduce(
|
||||
(prev, filter) => filter.render(prev, scope),
|
||||
Syntax.evalExp(template.initial, scope))
|
||||
evalExp(template.initial, scope))
|
||||
}
|
||||
}
|
||||
|
||||
function factory () {
|
||||
let instance = Object.create(render)
|
||||
export default function () {
|
||||
const instance = Object.create(render)
|
||||
return instance
|
||||
}
|
||||
|
||||
module.exports = factory
|
||||
|
||||
+14
-22
@@ -1,19 +1,18 @@
|
||||
'use strict'
|
||||
const _ = require('./util/underscore.js')
|
||||
const lexical = require('./lexical.js')
|
||||
const assert = require('./util/assert.js')
|
||||
import * as _ from './util/underscore.js'
|
||||
import * as lexical from './lexical.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
let Scope = {
|
||||
const Scope = {
|
||||
getAll: function () {
|
||||
return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
|
||||
},
|
||||
get: function (path) {
|
||||
let paths = this.propertyAccessSeq(path)
|
||||
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||
const paths = this.propertyAccessSeq(path)
|
||||
const scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||
return paths.reduce((value, key) => this.readProperty(value, key), scope)
|
||||
},
|
||||
set: function (path, v) {
|
||||
let paths = this.propertyAccessSeq(path)
|
||||
const paths = this.propertyAccessSeq(path)
|
||||
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||
paths.some((key, i) => {
|
||||
if (!_.isObject(scope)) {
|
||||
@@ -39,7 +38,7 @@ let Scope = {
|
||||
if (!arguments.length) {
|
||||
return this.contexts.pop()
|
||||
}
|
||||
let i = this.contexts.findIndex(scope => scope === ctx)
|
||||
const i = this.contexts.findIndex(scope => scope === ctx)
|
||||
if (i === -1) {
|
||||
throw new TypeError('scope not found, cannot pop')
|
||||
}
|
||||
@@ -48,7 +47,7 @@ let Scope = {
|
||||
findContextFor: function (key, filter) {
|
||||
filter = filter || (() => true)
|
||||
for (let i = this.contexts.length - 1; i >= 0; i--) {
|
||||
let candidate = this.contexts[i]
|
||||
const candidate = this.contexts[i]
|
||||
if (!filter(candidate)) continue
|
||||
if (key in candidate) {
|
||||
return candidate
|
||||
@@ -89,7 +88,7 @@ let Scope = {
|
||||
*/
|
||||
propertyAccessSeq: function (str) {
|
||||
str = String(str)
|
||||
let seq = []
|
||||
const seq = []
|
||||
let name = ''
|
||||
let j
|
||||
let i = 0
|
||||
@@ -98,7 +97,7 @@ let Scope = {
|
||||
case '[':
|
||||
push()
|
||||
|
||||
let delemiter = str[i + 1]
|
||||
const delemiter = str[i + 1]
|
||||
if (/['"]/.test(delemiter)) { // foo["bar"]
|
||||
j = str.indexOf(delemiter, i + 2)
|
||||
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
|
||||
@@ -155,23 +154,16 @@ function matchRightBracket (str, begin) {
|
||||
return -1
|
||||
}
|
||||
|
||||
exports.factory = function (ctx, opts) {
|
||||
let defaultOptions = {
|
||||
export function factory (ctx, opts) {
|
||||
const defaultOptions = {
|
||||
dynamicPartials: true,
|
||||
strict_variables: false,
|
||||
strict_filters: false,
|
||||
blocks: {},
|
||||
root: []
|
||||
}
|
||||
let scope = Object.create(Scope)
|
||||
const scope = Object.create(Scope)
|
||||
scope.opts = _.assign(defaultOptions, opts)
|
||||
scope.contexts = [ctx || {}]
|
||||
return scope
|
||||
}
|
||||
|
||||
exports.types = {
|
||||
AssignScope: Object.create(null),
|
||||
CaptureScope: Object.create(null),
|
||||
IncrementScope: Object.create(null),
|
||||
DecrementScope: Object.create(null)
|
||||
}
|
||||
|
||||
+18
-20
@@ -1,26 +1,28 @@
|
||||
const operators = require('./operators.js')(isTruthy)
|
||||
const lexical = require('./lexical.js')
|
||||
const assert = require('./util/assert.js')
|
||||
import Operators from './operators.js'
|
||||
import * as lexical from './lexical.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
function evalExp (exp, scope) {
|
||||
const operators = Operators(isTruthy)
|
||||
|
||||
export function evalExp (exp, scope) {
|
||||
assert(scope, 'unable to evalExp: scope undefined')
|
||||
let operatorREs = lexical.operators
|
||||
const 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})$`)
|
||||
const operatorRE = operatorREs[i]
|
||||
const expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
|
||||
if ((match = exp.match(expRE))) {
|
||||
let l = evalExp(match[1], scope)
|
||||
let op = operators[match[2].trim()]
|
||||
let r = evalExp(match[3], scope)
|
||||
const l = evalExp(match[1], scope)
|
||||
const op = operators[match[2].trim()]
|
||||
const r = evalExp(match[3], scope)
|
||||
return op(l, r)
|
||||
}
|
||||
}
|
||||
|
||||
if ((match = exp.match(lexical.rangeLine))) {
|
||||
let low = evalValue(match[1], scope)
|
||||
let high = evalValue(match[2], scope)
|
||||
let range = []
|
||||
const low = evalValue(match[1], scope)
|
||||
const high = evalValue(match[2], scope)
|
||||
const range = []
|
||||
for (let j = low; j <= high; j++) {
|
||||
range.push(j)
|
||||
}
|
||||
@@ -30,7 +32,7 @@ function evalExp (exp, scope) {
|
||||
return evalValue(exp, scope)
|
||||
}
|
||||
|
||||
function evalValue (str, scope) {
|
||||
export function evalValue (str, scope) {
|
||||
str = str && str.trim()
|
||||
if (!str) return undefined
|
||||
|
||||
@@ -43,14 +45,10 @@ function evalValue (str, scope) {
|
||||
throw new TypeError(`cannot eval '${str}' as value`)
|
||||
}
|
||||
|
||||
function isTruthy (val) {
|
||||
export function isTruthy (val) {
|
||||
return !isFalsy(val)
|
||||
}
|
||||
|
||||
function isFalsy (val) {
|
||||
export function isFalsy (val) {
|
||||
return val === false || undefined === val || val === null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
evalExp, evalValue, isTruthy, isFalsy
|
||||
}
|
||||
|
||||
+18
-19
@@ -1,38 +1,37 @@
|
||||
'use strict'
|
||||
const lexical = require('./lexical.js')
|
||||
const Syntax = require('./syntax.js')
|
||||
const assert = require('./util/assert.js')
|
||||
import {hashCapture} from './lexical.js'
|
||||
import {evalValue} from './syntax.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
function hash (markup, scope) {
|
||||
let obj = {}
|
||||
const obj = {}
|
||||
let match
|
||||
lexical.hashCapture.lastIndex = 0
|
||||
while ((match = lexical.hashCapture.exec(markup))) {
|
||||
let k = match[1]
|
||||
let v = match[2]
|
||||
obj[k] = Syntax.evalValue(v, scope)
|
||||
hashCapture.lastIndex = 0
|
||||
while ((match = hashCapture.exec(markup))) {
|
||||
const k = match[1]
|
||||
const v = match[2]
|
||||
obj[k] = evalValue(v, scope)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
module.exports = function () {
|
||||
export default function () {
|
||||
let tagImpls = {}
|
||||
|
||||
let _tagInstance = {
|
||||
render: function (scope) {
|
||||
let obj = hash(this.token.args, scope)
|
||||
let impl = this.tagImpl
|
||||
const _tagInstance = {
|
||||
render: async function (scope) {
|
||||
const obj = hash(this.token.args, scope)
|
||||
const impl = this.tagImpl
|
||||
if (typeof impl.render !== 'function') {
|
||||
return Promise.resolve('')
|
||||
return ''
|
||||
}
|
||||
return Promise.resolve().then(() => impl.render(scope, obj))
|
||||
return impl.render(scope, obj)
|
||||
},
|
||||
parse: function (token, tokens) {
|
||||
this.type = 'tag'
|
||||
this.token = token
|
||||
this.name = token.name
|
||||
|
||||
let tagImpl = tagImpls[this.name]
|
||||
const tagImpl = tagImpls[this.name]
|
||||
assert(tagImpl, `tag ${this.name} not found`)
|
||||
this.tagImpl = Object.create(tagImpl)
|
||||
if (this.tagImpl.parse) {
|
||||
@@ -46,7 +45,7 @@ module.exports = function () {
|
||||
}
|
||||
|
||||
function construct (token, tokens) {
|
||||
let instance = Object.create(_tagInstance)
|
||||
const instance = Object.create(_tagInstance)
|
||||
instance.parse(token, tokens)
|
||||
return instance
|
||||
}
|
||||
|
||||
+6
-6
@@ -1,19 +1,19 @@
|
||||
import {lexical} from '../index'
|
||||
import assert from '../util/assert.js'
|
||||
import {types} from '../scope'
|
||||
|
||||
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
|
||||
export default function (liquid, Liquid) {
|
||||
const rIdentifier = Liquid.lexical.identifier
|
||||
const re = new RegExp(`(${rIdentifier.source})\\s*=(.*)`)
|
||||
const {AssignScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('assign', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(re)
|
||||
const match = token.args.match(re)
|
||||
assert(match, `illegal token ${token.raw}`)
|
||||
this.key = match[1]
|
||||
this.value = match[2]
|
||||
},
|
||||
render: function (scope) {
|
||||
let ctx = Object.create(types.AssignScope)
|
||||
const ctx = Object.create(AssignScope)
|
||||
ctx[this.key] = liquid.evalValue(this.value, scope)
|
||||
scope.push(ctx)
|
||||
return Promise.resolve('')
|
||||
|
||||
+13
-16
@@ -1,20 +1,19 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`(${lexical.identifier.source})`)
|
||||
const assert = require('../util/assert.js')
|
||||
const types = require('../scope.js').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const rIdentifier = Liquid.lexical.identifier
|
||||
const re = new RegExp(`(${rIdentifier.source})`)
|
||||
const {CaptureScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('capture', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let match = tagToken.args.match(re)
|
||||
const match = tagToken.args.match(re)
|
||||
assert(match, `${tagToken.args} not valid identifier`)
|
||||
|
||||
this.variable = match[1]
|
||||
this.templates = []
|
||||
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream.on('tag:endcapture', token => stream.stop())
|
||||
.on('template', tpl => this.templates.push(tpl))
|
||||
.on('end', x => {
|
||||
@@ -22,13 +21,11 @@ module.exports = function (liquid) {
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
return liquid.renderer.renderTemplates(this.templates, scope)
|
||||
.then((html) => {
|
||||
let ctx = Object.create(types.CaptureScope)
|
||||
ctx[this.variable] = html
|
||||
scope.push(ctx)
|
||||
})
|
||||
render: async function (scope, hash) {
|
||||
const html = await liquid.renderer.renderTemplates(this.templates, scope)
|
||||
const ctx = Object.create(CaptureScope)
|
||||
ctx[this.variable] = html
|
||||
scope.push(ctx)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+5
-7
@@ -1,6 +1,4 @@
|
||||
import Liquid from '..'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('case', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -9,7 +7,7 @@ module.exports = function (liquid) {
|
||||
this.elseTemplates = []
|
||||
|
||||
let p = []
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('tag:when', token => {
|
||||
this.cases.push({
|
||||
val: token.args,
|
||||
@@ -28,9 +26,9 @@ module.exports = function (liquid) {
|
||||
|
||||
render: function (scope, hash) {
|
||||
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)
|
||||
const branch = this.cases[i]
|
||||
const val = Liquid.evalExp(branch.val, scope)
|
||||
const cond = Liquid.evalExp(this.cond, scope)
|
||||
if (val === cond) {
|
||||
return liquid.renderer.renderTemplates(branch.templates, scope)
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid) {
|
||||
liquid.registerTag('comment', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream
|
||||
.on('token', token => {
|
||||
if (token.name === 'endcomment') stream.stop()
|
||||
|
||||
+12
-12
@@ -1,10 +1,10 @@
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`)
|
||||
const candidatesRE = new RegExp(lexical.value.source, 'g')
|
||||
const assert = require('../util/assert.js')
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const rValue = Liquid.lexical.value
|
||||
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
|
||||
const candidatesRE = new RegExp(rValue.source, 'g')
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('cycle', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -12,7 +12,7 @@ module.exports = function (liquid) {
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
|
||||
this.group = match[1] || ''
|
||||
let candidates = match[2]
|
||||
const candidates = match[2]
|
||||
|
||||
this.candidates = []
|
||||
|
||||
@@ -23,21 +23,21 @@ module.exports = function (liquid) {
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
let group = Liquid.evalValue(this.group, scope)
|
||||
let fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
const group = Liquid.evalValue(this.group, scope)
|
||||
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
|
||||
let groups = scope.opts.groups = scope.opts.groups || {}
|
||||
const groups = scope.opts.groups = scope.opts.groups || {}
|
||||
let idx = groups[fingerprint]
|
||||
|
||||
if (idx === undefined) {
|
||||
idx = groups[fingerprint] = 0
|
||||
}
|
||||
|
||||
let candidate = this.candidates[idx]
|
||||
const candidate = this.candidates[idx]
|
||||
idx = (idx + 1) % this.candidates.length
|
||||
groups[fingerprint] = idx
|
||||
|
||||
return Promise.resolve(Liquid.evalValue(candidate, scope))
|
||||
return Liquid.evalValue(candidate, scope)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+9
-10
@@ -1,13 +1,12 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const assert = require('../util/assert.js')
|
||||
const types = require('../scope').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const {CaptureScope, AssignScope, DecrementScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('decrement', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(lexical.identifier)
|
||||
const match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
@@ -15,12 +14,12 @@ module.exports = function (liquid) {
|
||||
let context = scope.findContextFor(
|
||||
this.variable,
|
||||
ctx => {
|
||||
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== types.AssignScope
|
||||
return Object.getPrototypeOf(ctx) !== CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== AssignScope
|
||||
}
|
||||
)
|
||||
if (!context) {
|
||||
context = Object.create(types.DecrementScope)
|
||||
context = Object.create(DecrementScope)
|
||||
scope.unshift(context)
|
||||
}
|
||||
if (typeof context[this.variable] !== 'number') {
|
||||
|
||||
+82
-85
@@ -1,96 +1,93 @@
|
||||
import {default as Liquid, lexical} from '../index'
|
||||
import {mapSeries} from '../util/promise.js'
|
||||
import _ from '../util/underscore.js'
|
||||
import {isString, isObject} from '../util/underscore.js'
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*` +
|
||||
`(?:\\s+(reversed))?` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
export default function (liquid, Liquid) {
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*` +
|
||||
`(?:\\s+(reversed))?` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('for', {
|
||||
liquid.registerTag('for', {parse, render})
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
this.variable = match[1]
|
||||
this.collection = match[2]
|
||||
this.reversed = !!match[3]
|
||||
function parse (tagToken, remainTokens) {
|
||||
const match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
this.variable = match[1]
|
||||
this.collection = match[2]
|
||||
this.reversed = !!match[3]
|
||||
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => (p = this.templates))
|
||||
.on('tag:else', () => (p = this.elseTemplates))
|
||||
.on('tag:endfor', () => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
.on('end', () => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||
})
|
||||
|
||||
stream.start()
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
let collection = Liquid.evalExp(this.collection, scope)
|
||||
|
||||
if (!Array.isArray(collection)) {
|
||||
if (_.isString(collection) && collection.length > 0) {
|
||||
collection = [collection]
|
||||
} else if (_.isObject(collection)) {
|
||||
collection = Object.keys(collection).map((key) => [key, collection[key]])
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(collection) || !collection.length) {
|
||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
let contexts = collection.map((item, i) => {
|
||||
let ctx = {}
|
||||
ctx[this.variable] = item
|
||||
ctx.forloop = {
|
||||
first: i === 0,
|
||||
index: i + 1,
|
||||
index0: i,
|
||||
last: i === collection.length - 1,
|
||||
length: collection.length,
|
||||
rindex: collection.length - i,
|
||||
rindex0: collection.length - i - 1
|
||||
}
|
||||
return ctx
|
||||
let p
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => (p = this.templates))
|
||||
.on('tag:else', () => (p = this.elseTemplates))
|
||||
.on('tag:endfor', () => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
.on('end', () => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||
})
|
||||
|
||||
let html = ''
|
||||
return mapSeries(contexts, (context) => {
|
||||
return Promise.resolve()
|
||||
.then(() => scope.push(context))
|
||||
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
|
||||
.then(partial => (html += partial))
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
html += e.resolvedHTML
|
||||
if (e.message === 'continue') return
|
||||
}
|
||||
throw e
|
||||
})
|
||||
.then(() => scope.pop(context))
|
||||
}).catch((e) => {
|
||||
if (e instanceof RenderBreakError && e.message === 'break') {
|
||||
return
|
||||
}
|
||||
throw e
|
||||
}).then(() => html)
|
||||
stream.start()
|
||||
}
|
||||
async function render (scope, hash) {
|
||||
let collection = Liquid.evalExp(this.collection, scope)
|
||||
|
||||
if (!Array.isArray(collection)) {
|
||||
if (isString(collection) && collection.length > 0) {
|
||||
collection = [collection]
|
||||
} else if (isObject(collection)) {
|
||||
collection = Object.keys(collection).map((key) => [key, collection[key]])
|
||||
}
|
||||
}
|
||||
})
|
||||
if (!Array.isArray(collection) || !collection.length) {
|
||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
}
|
||||
|
||||
const offset = hash.offset || 0
|
||||
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (this.reversed) collection.reverse()
|
||||
|
||||
const contexts = collection.map((item, i) => {
|
||||
const ctx = {}
|
||||
ctx[this.variable] = item
|
||||
ctx.forloop = {
|
||||
first: i === 0,
|
||||
index: i + 1,
|
||||
index0: i,
|
||||
last: i === collection.length - 1,
|
||||
length: collection.length,
|
||||
rindex: collection.length - i,
|
||||
rindex0: collection.length - i - 1
|
||||
}
|
||||
return ctx
|
||||
})
|
||||
|
||||
let html = ''
|
||||
let finished = false
|
||||
await mapSeries(contexts, async context => {
|
||||
if (finished) return
|
||||
|
||||
scope.push(context)
|
||||
try {
|
||||
html += await liquid.renderer.renderTemplates(this.templates, scope)
|
||||
} catch (e) {
|
||||
if (e instanceof RenderBreakError) {
|
||||
html += e.resolvedHTML
|
||||
if (e.message === 'break') {
|
||||
finished = true
|
||||
}
|
||||
} else throw e
|
||||
}
|
||||
scope.pop(context)
|
||||
})
|
||||
return html
|
||||
}
|
||||
}
|
||||
|
||||
+4
-7
@@ -1,6 +1,4 @@
|
||||
import Liquid from '..'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('if', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -8,7 +6,7 @@ module.exports = function (liquid) {
|
||||
this.elseTemplates = []
|
||||
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => this.branches.push({
|
||||
cond: tagToken.args,
|
||||
templates: (p = [])
|
||||
@@ -30,9 +28,8 @@ module.exports = function (liquid) {
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
for (let i = 0; i < this.branches.length; i++) {
|
||||
let branch = this.branches[i]
|
||||
let cond = Liquid.evalExp(branch.cond, scope)
|
||||
for (const branch of this.branches) {
|
||||
const cond = Liquid.evalExp(branch.cond, scope)
|
||||
if (Liquid.isTruthy(cond)) {
|
||||
return liquid.renderer.renderTemplates(branch.templates, scope)
|
||||
}
|
||||
|
||||
+28
-35
@@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
|
||||
const staticFileRE = /[^\s,]+/
|
||||
const assert = require('../util/assert.js')
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const staticFileRE = /[^\s,]+/
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('include', {
|
||||
parse: function (token) {
|
||||
let match = staticFileRE.exec(token.args)
|
||||
@@ -23,42 +23,35 @@ module.exports = function (liquid) {
|
||||
this.with = match[1]
|
||||
}
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
let pFilepath
|
||||
render: async function (scope, hash) {
|
||||
let filepath
|
||||
if (scope.opts.dynamicPartials) {
|
||||
if (lexical.quotedLine.exec(this.value)) {
|
||||
let template = this.value.slice(1, -1)
|
||||
pFilepath = liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
||||
const template = this.value.slice(1, -1)
|
||||
filepath = await liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
||||
} else {
|
||||
pFilepath = Promise.resolve(Liquid.evalValue(this.value, scope))
|
||||
filepath = Liquid.evalValue(this.value, scope)
|
||||
}
|
||||
} else {
|
||||
pFilepath = Promise.resolve(this.staticValue)
|
||||
filepath = this.staticValue
|
||||
}
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
|
||||
let originBlocks = scope.opts.blocks
|
||||
let originBlockMode = scope.opts.blockMode
|
||||
const originBlocks = scope.opts.blocks
|
||||
const originBlockMode = scope.opts.blockMode
|
||||
|
||||
return pFilepath
|
||||
.then(filepath => {
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
scope.opts.blocks = {}
|
||||
scope.opts.blockMode = 'output'
|
||||
if (this.with) {
|
||||
hash[filepath] = Liquid.evalValue(this.with, scope)
|
||||
}
|
||||
return liquid.getTemplate(filepath, scope.opts.root)
|
||||
})
|
||||
.then(templates => {
|
||||
scope.push(hash)
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
.then((html) => {
|
||||
scope.pop(hash)
|
||||
scope.opts.blocks = originBlocks
|
||||
scope.opts.blockMode = originBlockMode
|
||||
return html
|
||||
})
|
||||
scope.opts.blocks = {}
|
||||
scope.opts.blockMode = 'output'
|
||||
if (this.with) {
|
||||
hash[filepath] = Liquid.evalValue(this.with, scope)
|
||||
}
|
||||
const templates = await liquid.getTemplate(filepath, scope.opts.root)
|
||||
scope.push(hash)
|
||||
const html = await liquid.renderer.renderTemplates(templates, scope)
|
||||
scope.pop(hash)
|
||||
scope.opts.blocks = originBlocks
|
||||
scope.opts.blockMode = originBlockMode
|
||||
return html
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+10
-10
@@ -1,12 +1,12 @@
|
||||
const Liquid = require('../index')
|
||||
const assert = require('../util/assert.js')
|
||||
const lexical = Liquid.lexical
|
||||
const types = require('../scope').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const {CaptureScope, AssignScope, IncrementScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('increment', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(lexical.identifier)
|
||||
const match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
@@ -14,18 +14,18 @@ module.exports = function (liquid) {
|
||||
let context = scope.findContextFor(
|
||||
this.variable,
|
||||
ctx => {
|
||||
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== types.AssignScope
|
||||
return Object.getPrototypeOf(ctx) !== CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== AssignScope
|
||||
}
|
||||
)
|
||||
if (!context) {
|
||||
context = Object.create(types.IncrementScope)
|
||||
context = Object.create(IncrementScope)
|
||||
scope.unshift(context)
|
||||
}
|
||||
if (typeof context[this.variable] !== 'number') {
|
||||
context[this.variable] = 0
|
||||
}
|
||||
let val = context[this.variable]
|
||||
const val = context[this.variable]
|
||||
context[this.variable]++
|
||||
return val
|
||||
}
|
||||
|
||||
+30
-15
@@ -1,16 +1,31 @@
|
||||
module.exports = function (engine) {
|
||||
require('./assign.js')(engine)
|
||||
require('./capture.js')(engine)
|
||||
require('./case.js')(engine)
|
||||
require('./comment.js')(engine)
|
||||
require('./cycle.js')(engine)
|
||||
require('./decrement.js')(engine)
|
||||
require('./for.js')(engine)
|
||||
require('./if.js')(engine)
|
||||
require('./include.js')(engine)
|
||||
require('./increment.js')(engine)
|
||||
require('./layout.js')(engine)
|
||||
require('./raw.js')(engine)
|
||||
require('./tablerow.js')(engine)
|
||||
require('./unless.js')(engine)
|
||||
import For from './for.js'
|
||||
import Assign from './assign.js'
|
||||
import Capture from './capture.js'
|
||||
import Case from './case.js'
|
||||
import Comment from './comment.js'
|
||||
import Include from './include.js'
|
||||
import Decrement from './decrement.js'
|
||||
import Cycle from './cycle.js'
|
||||
import If from './if.js'
|
||||
import Increment from './increment.js'
|
||||
import Layout from './layout.js'
|
||||
import Raw from './raw.js'
|
||||
import Tablerow from './tablerow.js'
|
||||
import Unless from './unless.js'
|
||||
|
||||
export default function (engine, Liquid) {
|
||||
Assign(engine, Liquid)
|
||||
Capture(engine, Liquid)
|
||||
Case(engine, Liquid)
|
||||
Comment(engine, Liquid)
|
||||
Cycle(engine, Liquid)
|
||||
Decrement(engine, Liquid)
|
||||
For(engine, Liquid)
|
||||
If(engine, Liquid)
|
||||
Include(engine, Liquid)
|
||||
Increment(engine, Liquid)
|
||||
Layout(engine, Liquid)
|
||||
Raw(engine, Liquid)
|
||||
Tablerow(engine, Liquid)
|
||||
Unless(engine, Liquid)
|
||||
}
|
||||
|
||||
+33
-40
@@ -1,7 +1,4 @@
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const assert = require('../util/assert.js')
|
||||
const staticFileRE = /\S+/
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
/*
|
||||
* blockMode:
|
||||
@@ -9,7 +6,10 @@ const staticFileRE = /\S+/
|
||||
* * "output": output rendered html
|
||||
*/
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
const rValue = Liquid.lexical.value
|
||||
const staticFileRE = /\S+/
|
||||
|
||||
liquid.registerTag('layout', {
|
||||
parse: function (token, remainTokens) {
|
||||
let match = staticFileRE.exec(token.args)
|
||||
@@ -17,45 +17,41 @@ module.exports = function (liquid) {
|
||||
this.staticLayout = match[0]
|
||||
}
|
||||
|
||||
match = lexical.value.exec(token.args)
|
||||
match = rValue.exec(token.args)
|
||||
if (match) {
|
||||
this.layout = match[0]
|
||||
}
|
||||
|
||||
this.tpls = liquid.parser.parse(remainTokens)
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
let layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
|
||||
render: async function (scope, hash) {
|
||||
const layout = scope.opts.dynamicPartials
|
||||
? Liquid.evalValue(this.layout, scope)
|
||||
: this.staticLayout
|
||||
assert(layout, `cannot apply layout with empty filename`)
|
||||
|
||||
// render the remaining tokens immediately
|
||||
scope.opts.blockMode = 'store'
|
||||
return liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
.then(html => {
|
||||
if (scope.opts.blocks[''] === undefined) {
|
||||
scope.opts.blocks[''] = html
|
||||
}
|
||||
return liquid.getTemplate(layout, scope.opts.root)
|
||||
})
|
||||
.then(templates => {
|
||||
scope.push(hash)
|
||||
scope.opts.blockMode = 'output'
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
.then(partial => {
|
||||
scope.pop(hash)
|
||||
return partial
|
||||
})
|
||||
const html = await liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
if (scope.opts.blocks[''] === undefined) {
|
||||
scope.opts.blocks[''] = html
|
||||
}
|
||||
const templates = await liquid.getTemplate(layout, scope.opts.root)
|
||||
scope.push(hash)
|
||||
scope.opts.blockMode = 'output'
|
||||
const partial = await liquid.renderer.renderTemplates(templates, scope)
|
||||
scope.pop(hash)
|
||||
return partial
|
||||
}
|
||||
})
|
||||
|
||||
liquid.registerTag('block', {
|
||||
parse: function (token, remainTokens) {
|
||||
let match = /\w+/.exec(token.args)
|
||||
const match = /\w+/.exec(token.args)
|
||||
this.block = match ? match[0] : ''
|
||||
|
||||
this.tpls = []
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('tag:endblock', () => stream.stop())
|
||||
.on('template', tpl => this.tpls.push(tpl))
|
||||
.on('end', () => {
|
||||
@@ -63,20 +59,17 @@ module.exports = function (liquid) {
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope) {
|
||||
return Promise.resolve(scope.opts.blocks[this.block])
|
||||
.then(html => html === undefined
|
||||
// render default block
|
||||
? liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
// use child-defined block
|
||||
: html)
|
||||
.then(html => {
|
||||
if (scope.opts.blockMode === 'store') {
|
||||
scope.opts.blocks[this.block] = html
|
||||
return ''
|
||||
}
|
||||
return html
|
||||
})
|
||||
render: async function (scope) {
|
||||
const childDefined = scope.opts.blocks[this.block]
|
||||
const html = childDefined !== undefined
|
||||
? childDefined
|
||||
: await liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
|
||||
if (scope.opts.blockMode === 'store') {
|
||||
scope.opts.blocks[this.block] = html
|
||||
return ''
|
||||
}
|
||||
return html
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid) {
|
||||
liquid.registerTag('raw', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.tokens = []
|
||||
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream
|
||||
.on('token', token => {
|
||||
if (token.name === 'endraw') stream.stop()
|
||||
|
||||
+34
-47
@@ -1,17 +1,16 @@
|
||||
import Liquid from '..'
|
||||
import {mapSeries} from '../util/promise.js'
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('tablerow', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let match = re.exec(tagToken.args)
|
||||
const match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
|
||||
this.variable = match[1]
|
||||
@@ -19,7 +18,7 @@ module.exports = function (liquid) {
|
||||
this.templates = []
|
||||
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => (p = this.templates))
|
||||
.on('tag:endtablerow', token => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
@@ -30,54 +29,42 @@ module.exports = function (liquid) {
|
||||
stream.start()
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
render: async function (scope, hash) {
|
||||
let collection = Liquid.evalExp(this.collection, scope) || []
|
||||
const offset = hash.offset || 0
|
||||
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
let html = ''
|
||||
let offset = hash.offset || 0
|
||||
let limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
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
|
||||
let contexts = collection.map((item, i) => {
|
||||
let ctx = {}
|
||||
const cols = hash.cols || collection.length
|
||||
const contexts = collection.map((item, i) => {
|
||||
const ctx = {}
|
||||
ctx[this.variable] = item
|
||||
return ctx
|
||||
})
|
||||
|
||||
return mapSeries(contexts,
|
||||
(context, idx) => {
|
||||
row = Math.floor(idx / cols) + 1
|
||||
col = (idx % cols) + 1
|
||||
if (col === 1) {
|
||||
if (row !== 1) {
|
||||
html += '</tr>'
|
||||
}
|
||||
html += `<tr class="row${row}">`
|
||||
}
|
||||
|
||||
html += `<td class="col${col}">`
|
||||
scope.push(context)
|
||||
return liquid.renderer
|
||||
.renderTemplates(this.templates, scope)
|
||||
.then((partial) => {
|
||||
scope.pop(context)
|
||||
html += partial
|
||||
html += '</td>'
|
||||
return html
|
||||
})
|
||||
})
|
||||
.then(() => {
|
||||
if (row > 0) {
|
||||
let row
|
||||
let html = ''
|
||||
await mapSeries(contexts, async (context, idx) => {
|
||||
row = Math.floor(idx / cols) + 1
|
||||
const col = (idx % cols) + 1
|
||||
if (col === 1) {
|
||||
if (row !== 1) {
|
||||
html += '</tr>'
|
||||
}
|
||||
return html
|
||||
})
|
||||
html += `<tr class="row${row}">`
|
||||
}
|
||||
|
||||
html += `<td class="col${col}">`
|
||||
scope.push(context)
|
||||
html += await liquid.renderer.renderTemplates(this.templates, scope)
|
||||
html += '</td>'
|
||||
scope.pop(context)
|
||||
return html
|
||||
})
|
||||
if (row > 0) {
|
||||
html += '</tr>'
|
||||
}
|
||||
return html
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+3
-5
@@ -1,12 +1,10 @@
|
||||
import Liquid from '../index'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('unless', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', x => {
|
||||
p = this.templates
|
||||
this.cond = tagToken.args
|
||||
@@ -22,7 +20,7 @@ module.exports = function (liquid) {
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
let cond = Liquid.evalExp(this.cond, scope)
|
||||
const cond = Liquid.evalExp(this.cond, scope)
|
||||
return Liquid.isFalsy(cond)
|
||||
? liquid.renderer.renderTemplates(this.templates, scope)
|
||||
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
|
||||
+15
-16
@@ -1,17 +1,19 @@
|
||||
const lexical = require('./lexical.js')
|
||||
const TokenizationError = require('./util/error.js').TokenizationError
|
||||
const _ = require('./util/underscore.js')
|
||||
const whiteSpaceCtrl = require('./whitespace-ctrl.js')
|
||||
const assert = require('./util/assert.js')
|
||||
import * as lexical from './lexical.js'
|
||||
import {TokenizationError} from './util/error.js'
|
||||
import * as _ from './util/underscore.js'
|
||||
import assert from './util/assert.js'
|
||||
import whiteSpaceCtrl from './whitespace-ctrl.js'
|
||||
|
||||
function parse (input, file, options) {
|
||||
export {default as whiteSpaceCtrl} from './whitespace-ctrl.js'
|
||||
|
||||
export function parse (input, file, options) {
|
||||
assert(_.isString(input), 'illegal input')
|
||||
|
||||
let rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
||||
const rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
||||
let currIndent = 0
|
||||
let lineNumber = LineNumber(input)
|
||||
const lineNumber = LineNumber(input)
|
||||
let lastMatchEnd = 0
|
||||
let tokens = []
|
||||
const tokens = []
|
||||
|
||||
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
|
||||
if (match.index > lastMatchEnd) {
|
||||
@@ -28,8 +30,8 @@ function parse (input, file, options) {
|
||||
return tokens
|
||||
|
||||
function parseTagToken (raw, value, pos) {
|
||||
let match = value.match(lexical.tagLine)
|
||||
let token = {
|
||||
const match = value.match(lexical.tagLine)
|
||||
const token = {
|
||||
type: 'tag',
|
||||
indent: currIndent,
|
||||
line: lineNumber.get(pos),
|
||||
@@ -62,7 +64,7 @@ function parse (input, file, options) {
|
||||
}
|
||||
|
||||
function parseHTMLToken (begin, end) {
|
||||
let htmlFragment = input.slice(begin, end)
|
||||
const htmlFragment = input.slice(begin, end)
|
||||
currIndent = _.last((htmlFragment).split('\n')).length
|
||||
|
||||
return {
|
||||
@@ -79,13 +81,10 @@ function LineNumber (html) {
|
||||
|
||||
return {
|
||||
get: function (pos) {
|
||||
let lines = html.slice(lastMatchBegin + 1, pos).split('\n')
|
||||
const lines = html.slice(lastMatchBegin + 1, pos).split('\n')
|
||||
parsedLinesCount += lines.length - 1
|
||||
lastMatchBegin = pos
|
||||
return parsedLinesCount + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.parse = parse
|
||||
exports.whiteSpaceCtrl = whiteSpaceCtrl
|
||||
|
||||
+2
-4
@@ -1,10 +1,8 @@
|
||||
const AssertionError = require('./error.js').AssertionError
|
||||
import {AssertionError} from './error.js'
|
||||
|
||||
function assert (predicate, message) {
|
||||
export default function (predicate, message) {
|
||||
if (!predicate) {
|
||||
message = message || `expect ${predicate} to be true`
|
||||
throw new AssertionError(message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = assert
|
||||
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
import _ from './underscore.js'
|
||||
import * as _ 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
|
||||
|
||||
let context = mkContext(token.input, token.line)
|
||||
const 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) {
|
||||
let lines = input.split('\n')
|
||||
let begin = Math.max(line - 2, 1)
|
||||
let end = Math.min(line + 3, lines.length)
|
||||
const lines = input.split('\n')
|
||||
const begin = Math.max(line - 2, 1)
|
||||
const end = Math.min(line + 3, lines.length)
|
||||
|
||||
let context = _
|
||||
const context = _
|
||||
.range(begin, end + 1)
|
||||
.map(l => [
|
||||
(l === line) ? '>> ' : ' ',
|
||||
@@ -82,9 +82,9 @@ function mkContext (input, line) {
|
||||
}
|
||||
|
||||
function align (n, max) {
|
||||
let length = (max + '').length
|
||||
let str = n + ''
|
||||
let blank = Array(length - str.length).join(' ')
|
||||
const length = (max + '').length
|
||||
const str = n + ''
|
||||
const blank = Array(length - str.length).join(' ')
|
||||
return blank + str
|
||||
}
|
||||
|
||||
|
||||
+3
-8
@@ -1,6 +1,6 @@
|
||||
const fs = require('fs')
|
||||
import fs from 'fs'
|
||||
|
||||
function readFileAsync (filepath) {
|
||||
export function readFileAsync (filepath) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.readFile(filepath, 'utf8', function (err, content) {
|
||||
err ? reject(err) : resolve(content)
|
||||
@@ -8,13 +8,8 @@ function readFileAsync (filepath) {
|
||||
})
|
||||
};
|
||||
|
||||
function statFileAsync (path) {
|
||||
export function statFileAsync (path) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
|
||||
})
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
readFileAsync,
|
||||
statFileAsync
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export function get (url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(xhr.responseText)
|
||||
} else {
|
||||
reject(new Error(xhr.statusText))
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('An error occurred whilst sending the response.'))
|
||||
}
|
||||
xhr.open('GET', url)
|
||||
xhr.send()
|
||||
})
|
||||
}
|
||||
+3
-6
@@ -4,7 +4,7 @@
|
||||
* @param {Array} iteratee returns a new promise.
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
*/
|
||||
function anySeries (iterable, iteratee) {
|
||||
export function anySeries (iterable, iteratee) {
|
||||
let ret = Promise.reject(new Error('init'))
|
||||
iterable.forEach(function (item, idx) {
|
||||
ret = ret.catch(e => iteratee(item, idx, iterable))
|
||||
@@ -18,9 +18,9 @@ function anySeries (iterable, iteratee) {
|
||||
* @param {Array} iteratee returns a new promise.
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
*/
|
||||
function mapSeries (iterable, iteratee) {
|
||||
export function mapSeries (iterable, iteratee) {
|
||||
let ret = Promise.resolve('init')
|
||||
let result = []
|
||||
const result = []
|
||||
iterable.forEach(function (item, idx) {
|
||||
ret = ret
|
||||
.then(() => iteratee(item, idx, iterable))
|
||||
@@ -28,6 +28,3 @@ function mapSeries (iterable, iteratee) {
|
||||
})
|
||||
return ret.then(() => result)
|
||||
}
|
||||
|
||||
exports.anySeries = anySeries
|
||||
exports.mapSeries = mapSeries
|
||||
|
||||
+21
-23
@@ -1,16 +1,16 @@
|
||||
let monthNames = [
|
||||
const monthNames = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
|
||||
'September', 'October', 'November', 'December'
|
||||
]
|
||||
let monthNamesShort = [
|
||||
const monthNamesShort = [
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
|
||||
'Nov', 'Dec'
|
||||
]
|
||||
let dayNames = [
|
||||
const dayNames = [
|
||||
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
|
||||
]
|
||||
let dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
let suffixes = {
|
||||
const dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
const suffixes = {
|
||||
1: 'st',
|
||||
2: 'nd',
|
||||
3: 'rd',
|
||||
@@ -18,9 +18,9 @@ let suffixes = {
|
||||
}
|
||||
|
||||
// prototype extensions
|
||||
let _date = {
|
||||
const _date = {
|
||||
daysInMonth: function (d) {
|
||||
let feb = _date.isLeapYear(d) ? 29 : 28
|
||||
const feb = _date.isLeapYear(d) ? 29 : 28
|
||||
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
},
|
||||
|
||||
@@ -36,21 +36,21 @@ let _date = {
|
||||
// TODO: that comment was retarted. fix it.
|
||||
getWeekOfYear: function (d, startDay) {
|
||||
// Skip to startDay of this week
|
||||
let now = this.getDayOfYear(d) + (startDay - d.getDay())
|
||||
const now = this.getDayOfYear(d) + (startDay - d.getDay())
|
||||
// Find the first startDay of the year
|
||||
let jan1 = new Date(d.getFullYear(), 0, 1)
|
||||
let then = (7 - jan1.getDay() + startDay)
|
||||
const jan1 = new Date(d.getFullYear(), 0, 1)
|
||||
const then = (7 - jan1.getDay() + startDay)
|
||||
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
|
||||
},
|
||||
|
||||
isLeapYear: function (d) {
|
||||
let year = d.getFullYear()
|
||||
const year = d.getFullYear()
|
||||
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
|
||||
},
|
||||
|
||||
getSuffix: function (d) {
|
||||
let str = d.getDate().toString()
|
||||
let index = parseInt(str.slice(-1))
|
||||
const str = d.getDate().toString()
|
||||
const index = parseInt(str.slice(-1))
|
||||
return suffixes[index] || suffixes['default']
|
||||
},
|
||||
|
||||
@@ -59,7 +59,7 @@ let _date = {
|
||||
}
|
||||
}
|
||||
|
||||
let _number = {
|
||||
const _number = {
|
||||
pad: function (value, size, ch) {
|
||||
if (!ch) ch = '0'
|
||||
let result = value.toString()
|
||||
@@ -73,7 +73,7 @@ let _number = {
|
||||
}
|
||||
}
|
||||
|
||||
let formatCodes = {
|
||||
const formatCodes = {
|
||||
a: function (d) {
|
||||
return dayNamesShort[d.getDay()]
|
||||
},
|
||||
@@ -162,7 +162,7 @@ let formatCodes = {
|
||||
return d.getFullYear()
|
||||
},
|
||||
z: function (d) {
|
||||
let tz = d.getTimezoneOffset() / 60 * 100
|
||||
const tz = d.getTimezoneOffset() / 60 * 100
|
||||
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
|
||||
},
|
||||
'%': function () {
|
||||
@@ -172,13 +172,13 @@ let formatCodes = {
|
||||
formatCodes.h = formatCodes.b
|
||||
formatCodes.N = formatCodes.L
|
||||
|
||||
let strftime = function (d, format) {
|
||||
export default function (d, format) {
|
||||
let output = ''
|
||||
let remaining = format
|
||||
|
||||
while (true) {
|
||||
let r = /%./g
|
||||
let results = r.exec(remaining)
|
||||
const r = /%./g
|
||||
const results = r.exec(remaining)
|
||||
|
||||
// No more format codes. Add the remaining text and return
|
||||
if (!results) {
|
||||
@@ -190,10 +190,8 @@ let strftime = function (d, format) {
|
||||
remaining = remaining.slice(r.lastIndex)
|
||||
|
||||
// Add the format code
|
||||
let ch = results[0].charAt(1)
|
||||
let func = formatCodes[ch]
|
||||
const ch = results[0].charAt(1)
|
||||
const func = formatCodes[ch]
|
||||
output += func ? func.call(this, d) : '%' + ch
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = strftime
|
||||
|
||||
+19
-36
@@ -5,11 +5,11 @@ const toStr = Object.prototype.toString
|
||||
* @param {any} value The value to check.
|
||||
* @return {Boolean} Returns true if value is a string, else false.
|
||||
*/
|
||||
function isString (value) {
|
||||
export function isString (value) {
|
||||
return toStr.call(value) === '[object String]'
|
||||
}
|
||||
|
||||
function stringify (value) {
|
||||
export function stringify (value) {
|
||||
if (isNil(value)) {
|
||||
return String(value)
|
||||
}
|
||||
@@ -23,7 +23,7 @@ function stringify (value) {
|
||||
return value
|
||||
}
|
||||
|
||||
let cache = []
|
||||
const cache = []
|
||||
return JSON.stringify(value, (key, value) => {
|
||||
if (isObject(value)) {
|
||||
if (cache.indexOf(value) !== -1) {
|
||||
@@ -35,17 +35,17 @@ function stringify (value) {
|
||||
})
|
||||
}
|
||||
|
||||
function isNil (value) {
|
||||
export function isNil (value) {
|
||||
return value === null || value === undefined
|
||||
}
|
||||
|
||||
function isArray (value) {
|
||||
export function isArray (value) {
|
||||
// be compatible with IE 8
|
||||
return toStr.call(value) === '[object Array]'
|
||||
}
|
||||
|
||||
function isError (value) {
|
||||
let signature = Object.prototype.toString.call(value)
|
||||
export function isError (value) {
|
||||
const signature = Object.prototype.toString.call(value)
|
||||
// [object XXXError]
|
||||
return signature.substr(-6, 5) === 'Error' ||
|
||||
(typeof value.message === 'string' && typeof value.name === 'string')
|
||||
@@ -59,9 +59,9 @@ function isError (value) {
|
||||
* @param {Function} iteratee The function invoked per iteration.
|
||||
* @return {Object} Returns object.
|
||||
*/
|
||||
function forOwn (object, iteratee) {
|
||||
export function forOwn (object, iteratee) {
|
||||
object = object || {}
|
||||
for (let k in object) {
|
||||
for (const k in object) {
|
||||
if (object.hasOwnProperty(k)) {
|
||||
if (iteratee(object[k], k, object) === false) break
|
||||
}
|
||||
@@ -80,20 +80,20 @@ function forOwn (object, iteratee) {
|
||||
* @param {...Object} sources The source objects.
|
||||
* @return {Object} Returns object.
|
||||
*/
|
||||
function assign (object) {
|
||||
export function assign (object) {
|
||||
object = isObject(object) ? object : {}
|
||||
let srcs = Array.prototype.slice.call(arguments, 1)
|
||||
const srcs = Array.prototype.slice.call(arguments, 1)
|
||||
srcs.forEach((src) => Object.assign(object, src))
|
||||
return object
|
||||
}
|
||||
|
||||
function last (arr) {
|
||||
export function last (arr) {
|
||||
return arr[arr.length - 1]
|
||||
}
|
||||
|
||||
function uniq (arr) {
|
||||
let u = {}
|
||||
let a = []
|
||||
export function uniq (arr) {
|
||||
const u = {}
|
||||
const a = []
|
||||
for (let i = 0, l = arr.length; i < l; ++i) {
|
||||
if (u.hasOwnProperty(arr[i])) {
|
||||
continue
|
||||
@@ -110,8 +110,8 @@ function uniq (arr) {
|
||||
* @param {any} value The value to check.
|
||||
* @return {Boolean} Returns true if value is an object, else false.
|
||||
*/
|
||||
function isObject (value) {
|
||||
let type = typeof value
|
||||
export function isObject (value) {
|
||||
const type = typeof value
|
||||
return value != null && (type === 'object' || type === 'function')
|
||||
}
|
||||
|
||||
@@ -123,33 +123,16 @@ function isObject (value) {
|
||||
* Note that ranges that stop before they start are considered to be zero-length instead of
|
||||
* negative — if you'd like a negative range, use a negative step.
|
||||
*/
|
||||
function range (start, stop, step) {
|
||||
export function range (start, stop, step) {
|
||||
if (arguments.length === 1) {
|
||||
stop = start
|
||||
start = 0
|
||||
}
|
||||
step = step || 1
|
||||
|
||||
let arr = []
|
||||
const arr = []
|
||||
for (let i = start; i < stop; i += step) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
// lang
|
||||
exports.isString = isString
|
||||
exports.isObject = isObject
|
||||
exports.isArray = isArray
|
||||
exports.isNil = isNil
|
||||
exports.isError = isError
|
||||
|
||||
// array
|
||||
exports.range = range
|
||||
exports.last = last
|
||||
|
||||
// object
|
||||
exports.forOwn = forOwn
|
||||
exports.assign = assign
|
||||
exports.uniq = uniq
|
||||
exports.stringify = stringify
|
||||
|
||||
+20
-4
@@ -1,5 +1,4 @@
|
||||
import resolveUrl from 'resolve-url'
|
||||
import _ from './underscore'
|
||||
import {last, isArray} from './underscore'
|
||||
|
||||
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
|
||||
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
|
||||
@@ -15,11 +14,28 @@ export function valid (path) {
|
||||
}
|
||||
|
||||
export function resolve (root, path) {
|
||||
if (Object.prototype.toString.call(root) === '[object Array]') {
|
||||
if (isArray(root)) {
|
||||
root = root[0]
|
||||
}
|
||||
if (root && _.last(root) !== '/') {
|
||||
if (root && last(root) !== '/') {
|
||||
root += '/'
|
||||
}
|
||||
return resolveUrl(root, path)
|
||||
}
|
||||
|
||||
function resolveUrl (root, path) {
|
||||
const base = document.createElement('base')
|
||||
base.href = arguments[0]
|
||||
|
||||
const head = document.getElementsByTagName('head')[0]
|
||||
head.insertBefore(base, head.firstChild)
|
||||
|
||||
const a = document.createElement('a')
|
||||
a.href = path
|
||||
const resolved = a.href
|
||||
base.href = resolved
|
||||
|
||||
head.removeChild(base)
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const _ = require('./util/underscore.js')
|
||||
import {assign} from './util/underscore.js'
|
||||
|
||||
function whiteSpaceCtrl (tokens, options) {
|
||||
options = _.assign({ greedy: true }, options)
|
||||
export default function whiteSpaceCtrl (tokens, options) {
|
||||
options = assign({ greedy: true }, options)
|
||||
let inRaw = false
|
||||
|
||||
tokens.forEach((token, i) => {
|
||||
@@ -33,15 +33,13 @@ function shouldTrimRight (token, inRaw, options) {
|
||||
function trimLeft (token, greedy) {
|
||||
if (!token || token.type !== 'html') return
|
||||
|
||||
let rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
|
||||
const rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
|
||||
token.value = token.value.replace(rLeft, '')
|
||||
}
|
||||
|
||||
function trimRight (token, greedy) {
|
||||
if (!token || token.type !== 'html') return
|
||||
|
||||
let rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
|
||||
const rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
|
||||
token.value = token.value.replace(rRight, '')
|
||||
}
|
||||
|
||||
module.exports = whiteSpaceCtrl
|
||||
|
||||
Reference in New Issue
Block a user