chore(TypeScript): refactor objects into classes

fix: `Nil`(null, undefined) now renders as empty string
change: `parser.parseValue()` renamed to `parser.parseOutput`
change: registered tags/filters become static and shared across different liquid instances
This commit is contained in:
harttle
2019-02-17 04:55:30 +08:00
parent b51b0dabca
commit 677e8511e6
134 changed files with 3327 additions and 3858 deletions
+25
View File
@@ -0,0 +1,25 @@
import { last } from 'src/util/underscore'
export default {
'join': (v, arg) => v.join(arg === undefined ? ' ' : arg),
'last': v => last(v),
'first': v => v[0],
'map': (arr, arg) => arr.map(v => v[arg]),
'reverse': v => v.reverse(),
'sort': (v, arg) => v.sort(arg),
'size': v => v.length,
'slice': (v, begin, length) => {
if (length === undefined) length = 1
return v.slice(begin, begin + length)
},
'uniq': function (arr) {
const u = {}
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false
}
u[val] = true
return true
})
}
}
+18
View File
@@ -0,0 +1,18 @@
import strftime from 'src/util/strftime'
import { isString } from 'src/util/underscore'
export default {
'date': (v, arg) => {
let date = v
if (v === 'now') {
date = new Date()
} else if (isString(v)) {
date = new Date(v)
}
return isValidDate(date) ? strftime(date, arg) : v
}
}
function isValidDate (date) {
return date instanceof Date && !isNaN(date.getTime())
}
+29
View File
@@ -0,0 +1,29 @@
const escapeMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
}
const unescapeMap = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&#34;': '"',
'&#39;': "'"
}
function escape (str) {
return String(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
}
function unescape (str) {
return String(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
}
export default {
'escape': escape,
'escape_once': str => escape(unescape(str)),
'newline_to_br': v => v.replace(/\n/g, '<br />'),
'strip_html': v => String(v).replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, ''),
}
+12
View File
@@ -0,0 +1,12 @@
import { assign } from 'src/util/underscore'
import html from './html'
import str from './string'
import math from './math'
import url from './url'
import array from './array'
import date from './date'
import obj from './object'
const filters = assign({}, html, str, math, url, date, obj, array)
export default filters
+26
View File
@@ -0,0 +1,26 @@
export default {
'abs': v => Math.abs(v),
'ceil': v => Math.ceil(v),
'divided_by': (v, arg) => v / arg,
'floor': v => Math.floor(v),
'minus': bindFixed((v, arg) => v - arg),
'modulo': bindFixed((v, arg) => v % arg),
'round': (v, arg) => {
const amp = Math.pow(10, arg || 0)
return Math.round(v * amp) / amp
},
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
'times': (v, arg) => v * arg,
}
function getFixed (v) {
const p = String(v).split('.')
return (p.length > 1) ? p[1].length : 0
}
function bindFixed (cb) {
return (l, r) => {
const f = Math.max(getFixed(l), getFixed(r))
return cb(l, r).toFixed(f)
}
}
+5
View File
@@ -0,0 +1,5 @@
import { isTruthy } from 'src/render/syntax'
export default {
'default': (v, arg) => isTruthy(v) ? v : arg
}
+32
View File
@@ -0,0 +1,32 @@
export default {
'append': (v, arg) => v + arg,
'prepend': (v, arg) => arg + v,
'capitalize': str => String(str).charAt(0).toUpperCase() + str.slice(1),
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
'lstrip': v => String(v).replace(/^\s+/, ''),
'downcase': v => v.toLowerCase(),
'upcase': str => String(str).toUpperCase(),
'remove': (v, arg) => v.split(arg).join(''),
'remove_first': (v, l) => v.replace(l, ''),
'replace': (v, pattern, replacement) =>
String(v).split(pattern).join(replacement),
'replace_first': (v, arg1, arg2) => String(v).replace(arg1, arg2),
'rstrip': str => String(str).replace(/\s+$/, ''),
'split': (v, arg) => String(v).split(arg),
'strip': (v) => String(v).trim(),
'strip_newlines': v => String(v).replace(/\n/g, ''),
'truncate': (v, l, o) => {
v = String(v)
o = (o === undefined) ? '...' : o
l = l || 16
if (v.length <= l) return v
return v.substr(0, l - o.length) + o
},
'truncatewords': (v, l, o) => {
if (o === undefined) o = '...'
const arr = v.split(' ')
let ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o
return ret
},
}
+4
View File
@@ -0,0 +1,4 @@
export default {
'url_decode': x => x.split('+').map(decodeURIComponent).join(' '),
'url_encode': x => x.split(' ').map(encodeURIComponent).join('+')
}
+20
View File
@@ -0,0 +1,20 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { AssignScope } from 'src/scope/scopes'
const re = new RegExp(`(${identifier.source})\\s*=([^]*)`)
export default {
parse: function (token) {
const match = token.args.match(re)
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
const ctx = new AssignScope()
ctx[this.key] = this.liquid.evalValue(this.value, scope)
scope.push(ctx)
return Promise.resolve('')
}
}
+29
View File
@@ -0,0 +1,29 @@
import BlockMode from 'src/scope/block-mode'
export default {
parse: function (token, remainTokens) {
const match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
const stream = this.liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
})
stream.start()
},
render: async function (scope) {
const childDefined = scope.blocks[this.block]
const html = childDefined !== undefined
? childDefined
: await this.liquid.renderer.renderTemplates(this.tpls, scope)
if (scope.blockMode === BlockMode.STORE) {
scope.blocks[this.block] = html
return ''
}
return html
}
}
+7
View File
@@ -0,0 +1,7 @@
import { RenderBreakError } from 'src/util/error'
export default {
render: async function (scope) {
throw new RenderBreakError('break')
}
}
+29
View File
@@ -0,0 +1,29 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { CaptureScope } from 'src/scope/scopes'
const re = new RegExp(`(${identifier.source})`)
export default {
parse: function (tagToken, remainTokens) {
const match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
this.templates = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', token => stream.stop())
.on('template', tpl => this.templates.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: async function (scope, hash) {
const html = await this.liquid.renderer.renderTemplates(this.templates, scope)
const ctx = new CaptureScope()
ctx[this.variable] = html
scope.push(ctx)
}
}
+38
View File
@@ -0,0 +1,38 @@
import { evalExp } from 'src/render/syntax'
export default {
parse: function (tagToken, remainTokens) {
this.cond = tagToken.args
this.cases = []
this.elseTemplates = []
let p = []
const stream = this.liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endcase', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
for (let i = 0; i < this.cases.length; i++) {
const branch = this.cases[i]
const val = evalExp(branch.val, scope)
const cond = evalExp(this.cond, scope)
if (val === cond) {
return this.liquid.renderer.renderTemplates(branch.templates, scope)
}
}
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}
+13
View File
@@ -0,0 +1,13 @@
export default {
parse: function (tagToken, remainTokens) {
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endcomment') stream.stop()
})
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
}
}
+7
View File
@@ -0,0 +1,7 @@
import { RenderBreakError } from 'src/util/error'
export default {
render: async function (scope) {
throw new RenderBreakError('continue')
}
}
+41
View File
@@ -0,0 +1,41 @@
import assert from 'src/util/assert'
import { value as rValue } from 'src/parser/lexical'
import { evalValue } from 'src/render/syntax'
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(rValue.source, 'g')
export default {
parse: function (tagToken, remainTokens) {
let match = groupRE.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
const candidates = match[2]
this.candidates = []
while ((match = candidatesRE.exec(candidates))) {
this.candidates.push(match[0])
}
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
},
render: function (scope, hash) {
const group = evalValue(this.group, scope)
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
const groups = scope.opts.groups = scope.opts.groups || {}
let idx = groups[fingerprint]
if (idx === undefined) {
idx = groups[fingerprint] = 0
}
const candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx
return evalValue(candidate, scope)
}
}
+27
View File
@@ -0,0 +1,27 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { CaptureScope, AssignScope, DecrementScope } from 'src/scope/scopes'
export default {
parse: function (token) {
const match = token.args.match(identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
return !(ctx instanceof CaptureScope) && !(ctx instanceof AssignScope)
}
)
if (!context) {
context = new DecrementScope()
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
return --context[this.variable]
}
}
+93
View File
@@ -0,0 +1,93 @@
import { mapSeries } from 'src/util/promise'
import { isString, isObject, isArray } from 'src/util/underscore'
import { evalExp } from 'src/render/syntax'
import assert from 'src/util/assert'
import { identifier, value, hash } from 'src/parser/lexical'
import { RenderBreakError } from 'src/util/error'
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` +
`(?:\\s+${hash.source})*` +
`(?:\\s+(reversed))?` +
`(?:\\s+${hash.source})*$`)
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 = []
let p
const stream = this.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()
}
async function render (scope, hash) {
let collection = evalExp(this.collection, scope)
if (!isArray(collection)) {
if (isString(collection) && collection.length > 0) {
collection = [collection]
} else if (isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
}
if (!isArray(collection) || !collection.length) {
return this.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 this.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
}
export default { parse, render }
+39
View File
@@ -0,0 +1,39 @@
import { evalExp, isTruthy } from 'src/render/syntax'
export default {
parse: function (tagToken, remainTokens) {
this.branches = []
this.elseTemplates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
}))
.on('tag:elsif', token => {
this.branches.push({
cond: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endif', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
for (const branch of this.branches) {
const cond = evalExp(branch.cond, scope)
if (isTruthy(cond)) {
return this.liquid.renderer.renderTemplates(branch.templates, scope)
}
}
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}
+56
View File
@@ -0,0 +1,56 @@
import assert from 'src/util/assert'
import { value, quotedLine } from 'src/parser/lexical'
import { evalValue } from 'src/render/syntax'
import BlockMode from 'src/scope/block-mode'
const staticFileRE = /[^\s,]+/
const withRE = new RegExp(`with\\s+(${value.source})`)
export default {
parse: function (token) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticValue = match[0]
}
match = value.exec(token.args)
if (match) {
this.value = match[0]
}
match = withRE.exec(token.args)
if (match) {
this.with = match[1]
}
},
render: async function (scope, hash) {
let filepath
if (scope.opts.dynamicPartials) {
if (quotedLine.exec(this.value)) {
const template = this.value.slice(1, -1)
filepath = await this.liquid.parseAndRender(template, scope.getAll(), scope.opts)
} else {
filepath = evalValue(this.value, scope)
}
} else {
filepath = this.staticValue
}
assert(filepath, `cannot include with empty filename`)
const originBlocks = scope.blocks
const originBlockMode = scope.blockMode
scope.blocks = {}
scope.blockMode = BlockMode.OUTPUT
if (this.with) {
hash[filepath] = evalValue(this.with, scope)
}
const templates = await this.liquid.getTemplate(filepath, scope.opts.root)
scope.push(hash)
const html = await this.liquid.renderer.renderTemplates(templates, scope)
scope.pop(hash)
scope.blocks = originBlocks
scope.blockMode = originBlockMode
return html
}
}
+29
View File
@@ -0,0 +1,29 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { CaptureScope, AssignScope, IncrementScope } from 'src/scope/scopes'
export default {
parse: function (token) {
const match = token.args.match(identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
return !(ctx instanceof CaptureScope) && !(ctx instanceof AssignScope)
}
)
if (!context) {
context = new IncrementScope()
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
const val = context[this.variable]
context[this.variable]++
return val
}
}
+21
View File
@@ -0,0 +1,21 @@
import assign from './assign'
import For from './for'
import capture from './capture'
import Case from './case'
import comment from './comment'
import include from './include'
import decrement from './decrement'
import cycle from './cycle'
import If from './if'
import increment from './increment'
import layout from './layout'
import block from './block'
import raw from './raw'
import tablerow from './tablerow'
import unless from './unless'
import Break from './break'
import Continue from './continue'
export default {
assign, 'for': For, capture, 'case': Case, comment, include, decrement, increment, cycle, 'if': If, layout, block, raw, tablerow, unless, 'break': Break, 'continue': Continue
}
+41
View File
@@ -0,0 +1,41 @@
import assert from 'src/util/assert'
import { value as rValue } from 'src/parser/lexical'
import { evalValue } from 'src/render/syntax'
import BlockMode from 'src/scope/block-mode'
const staticFileRE = /\S+/
export default {
parse: function (token, remainTokens) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
}
match = rValue.exec(token.args)
if (match) {
this.layout = match[0]
}
this.tpls = this.liquid.parser.parse(remainTokens)
},
render: async function (scope, hash) {
const layout = scope.opts.dynamicPartials
? evalValue(this.layout, scope)
: this.staticLayout
assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately
scope.blockMode = BlockMode.STORE
const html = await this.liquid.renderer.renderTemplates(this.tpls, scope)
if (scope.blocks[''] === undefined) {
scope.blocks[''] = html
}
const templates = await this.liquid.getTemplate(layout, scope.opts.root)
scope.push(hash)
scope.blockMode = BlockMode.OUTPUT
const partial = await this.liquid.renderer.renderTemplates(templates, scope)
scope.pop(hash)
return partial
}
}
+19
View File
@@ -0,0 +1,19 @@
export default {
parse: function (tagToken, remainTokens) {
this.tokens = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
return this.tokens.map(token => token.raw).join('')
}
}
+68
View File
@@ -0,0 +1,68 @@
import { mapSeries } from 'src/util/promise'
import assert from 'src/util/assert'
import { evalExp } from 'src/render/syntax'
import { identifier, value, hash } from 'src/parser/lexical'
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` +
`(?:\\s+${hash.source})*$`)
export default {
parse: function (tagToken, remainTokens) {
const match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.templates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: async function (scope, hash) {
let collection = evalExp(this.collection, scope) || []
const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
const cols = hash.cols || collection.length
const contexts = collection.map((item, i) => {
const ctx = {}
ctx[this.variable] = item
return ctx
})
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>'
}
html += `<tr class="row${row}">`
}
html += `<td class="col${col}">`
scope.push(context)
html += await this.liquid.renderer.renderTemplates(this.templates, scope)
html += '</td>'
scope.pop(context)
return html
})
if (row > 0) {
html += '</tr>'
}
return html
}
}
+29
View File
@@ -0,0 +1,29 @@
import { evalExp, isFalsy } from 'src/render/syntax'
export default {
parse: function (tagToken, remainTokens) {
this.templates = []
this.elseTemplates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
.on('start', x => {
p = this.templates
this.cond = tagToken.args
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endunless', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
const cond = evalExp(this.cond, scope)
return isFalsy(cond)
? this.liquid.renderer.renderTemplates(this.templates, scope)
: this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}