refactor: strictly typed

This commit is contained in:
harttle
2019-02-23 00:49:54 +08:00
parent 51f7e66f60
commit 5b6100d12b
86 changed files with 2630 additions and 2590 deletions
+12 -13
View File
@@ -1,24 +1,23 @@
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) => {
'join': (v: any[], arg: string) => v.join(arg === undefined ? ' ' : arg),
'last': <T>(v: T[]): T => last(v),
'first': <T>(v: T[]): T => v[0],
'map': <T1, T2>(arr: {[key: string]: T1}[], arg: string): T1[] => arr.map(v => v[arg]),
'reverse': (v: any[]) => v.reverse(),
'sort': <T>(v: T[], arg: (lhs: T, rhs: T) => number) => v.sort(arg),
'size': (v: string | any[]) => v.length,
'concat': <T1, T2>(v: T1[], arg: T2[] | T2): Array<T1 | T2> => Array.prototype.concat.call(v, arg),
'slice': <T>(v: T[], begin: number, length: number): T[] => {
if (length === undefined) length = 1
return v.slice(begin, begin + length)
},
'uniq': function (arr) {
'uniq': function<T> (arr: T[]): T[] {
const u = {}
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false
}
u[val] = true
if (u.hasOwnProperty(String(val))) return false
u[String(val)] = true
return true
})
}
+2 -2
View File
@@ -2,7 +2,7 @@ import strftime from 'src/util/strftime'
import { isString } from 'src/util/underscore'
export default {
'date': (v, arg) => {
'date': (v: string | Date, arg: string) => {
let date = v
if (v === 'now') {
date = new Date()
@@ -13,6 +13,6 @@ export default {
}
}
function isValidDate (date) {
function isValidDate (date: any): date is Date {
return date instanceof Date && !isNaN(date.getTime())
}
+5 -5
View File
@@ -13,17 +13,17 @@ const unescapeMap = {
'&#39;': "'"
}
function escape (str) {
function escape (str: string) {
return String(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
}
function unescape (str) {
function unescape (str: string) {
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, '')
'escape_once': (str: string) => escape(unescape(str)),
'newline_to_br': (v: string) => v.replace(/\n/g, '<br />'),
'strip_html': (v: string) => v.replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, '')
}
+13 -13
View File
@@ -1,25 +1,25 @@
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)
'abs': (v: number) => Math.abs(v),
'ceil': (v: number) => Math.ceil(v),
'divided_by': (v: number, arg: number) => v / arg,
'floor': (v: number) => Math.floor(v),
'minus': bindFixed((v: number, arg: number) => v - arg),
'modulo': bindFixed((v: number, arg: number) => v % arg),
'round': (v: number, arg: number = 0) => {
const amp = Math.pow(10, arg)
return Math.round(v * amp) / amp
},
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
'times': (v, arg) => v * arg
'plus': bindFixed((v: number, arg: number) => Number(v) + Number(arg)),
'times': (v: number, arg: number) => v * arg
}
function getFixed (v) {
function getFixed (v: number) {
const p = String(v).split('.')
return (p.length > 1) ? p[1].length : 0
}
function bindFixed (cb) {
return (l, r) => {
function bindFixed (cb: (v: number, arg: number) => number) {
return (l: number, r: number) => {
const f = Math.max(getFixed(l), getFixed(r))
return cb(l, r).toFixed(f)
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { isTruthy } from 'src/render/syntax'
export default {
'default': (v, arg) => isTruthy(v) ? v : arg
'default': <T1, T2>(v: T1, arg: T2): T1 | T2 => isTruthy(v) ? v : arg
}
+19 -21
View File
@@ -1,32 +1,30 @@
import FilterImpl from "src/template/filter/filter-impl";
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) =>
'append': (v: string, arg: string) => v + arg,
'prepend': (v: string, arg: string) => arg + v,
'capitalize': (str: string) => String(str).charAt(0).toUpperCase() + str.slice(1),
'lstrip': (v: string) => String(v).replace(/^\s+/, ''),
'downcase': (v: string) => v.toLowerCase(),
'upcase': (str: string) => String(str).toUpperCase(),
'remove': (v: string, arg: string) => v.split(arg).join(''),
'remove_first': (v: string, l: string) => v.replace(l, ''),
'replace': (v: string, pattern: string, replacement: string) =>
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) => {
'replace_first': (v: string, arg1: string, arg2: string) => String(v).replace(arg1, arg2),
'rstrip': (str: string) => String(str).replace(/\s+$/, ''),
'split': (v: string, arg: string) => String(v).split(arg),
'strip': (v: string) => String(v).trim(),
'strip_newlines': (v: string) => String(v).replace(/\n/g, ''),
'truncate': (v: string, l: number = 16, o: string = '...') => {
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 = '...'
'truncatewords': (v: string, l: number = v.length, o: string = '...') => {
const arr = v.split(' ')
let ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o
return ret
}
}
} as {[key: string]: FilterImpl}
+3 -3
View File
@@ -1,4 +1,4 @@
export default {
'url_decode': x => x.split('+').map(decodeURIComponent).join(' '),
'url_encode': x => x.split(' ').map(encodeURIComponent).join('+')
}
'url_decode': (x: string) => x.split('+').map(decodeURIComponent).join(' '),
'url_encode': (x: string) => x.split(' ').map(encodeURIComponent).join('+')
}
+7 -4
View File
@@ -1,20 +1,23 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { AssignScope } from 'src/scope/scopes'
import TagToken from 'src/parser/tag-token';
import Scope from 'src/scope/scope';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
const re = new RegExp(`(${identifier.source})\\s*=([^]*)`)
export default {
parse: function (token) {
const match = token.args.match(re)
parse: function (token: TagToken) {
const match = token.args.match(re) as RegExpMatchArray
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
render: function (scope: Scope) {
const ctx = new AssignScope()
ctx[this.key] = this.liquid.evalValue(this.value, scope)
scope.push(ctx)
return Promise.resolve('')
}
}
} as ITagImplOptions
+12 -7
View File
@@ -1,20 +1,25 @@
import BlockMode from 'src/scope/block-mode'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import ITemplate from 'src/template/itemplate'
import Scope from 'src/scope/scope';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
export default {
parse: function (token, remainTokens) {
parse: function (token: TagToken, remainTokens: Token[]) {
const match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
const stream = this.liquid.parser.parseStream(remainTokens)
this.tpls = [] as ITemplate[]
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('template', (tpl: ITemplate) => this.tpls.push(tpl))
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
})
stream.start()
},
render: async function (scope) {
render: async function (scope: Scope) {
const childDefined = scope.blocks[this.block]
const html = childDefined !== undefined
? childDefined
@@ -26,4 +31,4 @@ export default {
}
return html
}
}
} as ITagImplOptions
+4 -3
View File
@@ -4,12 +4,13 @@ import { CaptureScope } from 'src/scope/scopes'
import TagToken from 'src/parser/tag-token'
import Token from 'src/parser/token'
import Scope from 'src/scope/scope'
import ITagImplOptions from 'src/template/tag/itag-impl-options';
const re = new RegExp(`(${identifier.source})`)
export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) {
const match = tagToken.args.match(re)
const match = tagToken.args.match(re) as RegExpMatchArray
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
@@ -17,7 +18,7 @@ export default {
const stream = this.liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', () => stream.stop())
.on('template', tpl => this.templates.push(tpl))
.on('template', (tpl) => this.templates.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
@@ -29,4 +30,4 @@ export default {
ctx[this.variable] = html
scope.push(ctx)
}
}
} as ITagImplOptions
+13 -7
View File
@@ -1,14 +1,20 @@
import { evalExp } from 'src/render/syntax'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import Scope from 'src/scope/scope';
import ITemplate from 'src/template/itemplate';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
export default {
parse: function (tagToken, remainTokens) {
parse: function (tagToken: TagToken, remainTokens: Token[]) {
this.cond = tagToken.args
this.cases = []
this.elseTemplates = []
let p = []
const stream = this.liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
let p: ITemplate[] = []
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('tag:when', (token: TagToken) => {
this.cases.push({
val: token.args,
templates: p = []
@@ -16,7 +22,7 @@ export default {
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endcase', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('template', (tpl: ITemplate) => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
@@ -24,7 +30,7 @@ export default {
stream.start()
},
render: function (scope) {
render: function (scope: Scope) {
for (let i = 0; i < this.cases.length; i++) {
const branch = this.cases[i]
const val = evalExp(branch.val, scope)
@@ -35,4 +41,4 @@ export default {
}
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}
} as ITagImplOptions
+7 -3
View File
@@ -1,8 +1,12 @@
import TagToken from "src/parser/tag-token";
import Token from "src/parser/token";
import ITagImplOptions from "src/template/tag/itag-impl-options";
export default {
parse: function (tagToken, remainTokens) {
parse: function (tagToken: TagToken, remainTokens: Token[]) {
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
.on('token', (token: TagToken) => {
if (token.name === 'endcomment') stream.stop()
})
.on('end', () => {
@@ -10,4 +14,4 @@ export default {
})
stream.start()
}
}
} as ITagImplOptions
+9 -7
View File
@@ -1,13 +1,16 @@
import assert from 'src/util/assert'
import { value as rValue } from 'src/parser/lexical'
import { evalValue } from 'src/render/syntax'
import TagToken from 'src/parser/tag-token';
import Scope from 'src/scope/scope';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(rValue.source, 'g')
export default {
parse: function (tagToken) {
let match = groupRE.exec(tagToken.args)
export default <ITagImplOptions>{
parse: function (tagToken: TagToken) {
let match: RegExpExecArray | null = groupRE.exec(tagToken.args) as RegExpExecArray
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
@@ -21,11 +24,10 @@ export default {
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
},
render: function (scope) {
render: function (scope: Scope) {
const group = evalValue(this.group, scope)
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
const groups = scope.opts.groups = scope.opts.groups || {}
const groups = scope.groups
let idx = groups[fingerprint]
if (idx === undefined) {
@@ -38,4 +40,4 @@ export default {
return evalValue(candidate, scope)
}
}
}
+3 -2
View File
@@ -3,10 +3,11 @@ import { identifier } from 'src/parser/lexical'
import { CaptureScope, AssignScope, DecrementScope } from 'src/scope/scopes'
import TagToken from 'src/parser/tag-token'
import Scope from 'src/scope/scope'
import ITagImplOptions from 'src/template/tag/itag-impl-options';
export default {
parse: function (token: TagToken) {
const match = token.args.match(identifier)
const match = token.args.match(identifier) as RegExpMatchArray
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
@@ -26,4 +27,4 @@ export default {
}
return --context[this.variable]
}
}
} as ITagImplOptions
+85 -79
View File
@@ -3,7 +3,13 @@ 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'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import Scope from 'src/scope/scope';
import Hash from 'src/template/tag/hash';
import ITemplate from 'src/template/itemplate';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` +
@@ -11,83 +17,83 @@ const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(?:\\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`)
export default <ITagImplOptions>{
type: 'block',
parse: function (tagToken: TagToken, remainTokens: Token[]) {
const match = re.exec(tagToken.args) as RegExpExecArray
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: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
.on('template', (tpl: ITemplate) => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: async function (scope: Scope, hash: Hash) {
let collection = evalExp(this.collection, scope)
if (!isArray(collection)) {
if (isString(collection) && collection.length > 0) {
collection = [collection] as string[]
} else if (isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]]) as Array<[string, any]>
}
}
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: string, i: number) => {
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
})
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]])
}
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.name === 'RenderBreakError') {
html += e.resolvedHTML
if (e.message === 'break') {
finished = true
}
} else throw e
}
scope.pop(context)
})
return html
}
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 }
}
+12 -6
View File
@@ -1,17 +1,23 @@
import { evalExp, isTruthy } from 'src/render/syntax'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import Scope from 'src/scope/scope';
import ITemplate from 'src/template/itemplate';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
export default {
parse: function (tagToken, remainTokens) {
parse: function (tagToken: TagToken, remainTokens: Token[]) {
this.branches = []
this.elseTemplates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
}))
.on('tag:elsif', token => {
.on('tag:elsif', (token: TagToken) => {
this.branches.push({
cond: token.args,
templates: p = []
@@ -19,7 +25,7 @@ export default {
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endif', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('template', (tpl: ITemplate) => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
@@ -27,7 +33,7 @@ export default {
stream.start()
},
render: function (scope) {
render: function (scope: Scope) {
for (const branch of this.branches) {
const cond = evalExp(branch.cond, scope)
if (isTruthy(cond)) {
@@ -36,4 +42,4 @@ export default {
}
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}
} as ITagImplOptions
+7 -3
View File
@@ -2,12 +2,16 @@ 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'
import TagToken from 'src/parser/tag-token';
import Scope from 'src/scope/scope';
import Hash from 'src/template/tag/hash';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
const staticFileRE = /[^\s,]+/
const withRE = new RegExp(`with\\s+(${value.source})`)
export default {
parse: function (token) {
export default <ITagImplOptions>{
parse: function (token: TagToken) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticValue = match[0]
@@ -23,7 +27,7 @@ export default {
this.with = match[1]
}
},
render: async function (scope, hash) {
render: async function (scope: Scope, hash: Hash) {
let filepath
if (scope.opts.dynamicPartials) {
if (quotedLine.exec(this.value)) {
+3 -2
View File
@@ -1,12 +1,13 @@
import assert from 'src/util/assert'
import { identifier } from 'src/parser/lexical'
import { CaptureScope, AssignScope, IncrementScope } from 'src/scope/scopes'
import ITagImplOptions from 'src/template/tag/itag-impl-options';
export default {
parse: function (token) {
const match = token.args.match(identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
this.variable = match![0]
},
render: function (scope) {
let context = scope.findContextFor(
@@ -26,4 +27,4 @@ export default {
context[this.variable]++
return val
}
}
} as ITagImplOptions
+8 -3
View File
@@ -2,11 +2,16 @@ 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'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import Scope from 'src/scope/scope';
import Hash from 'src/template/tag/hash';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
const staticFileRE = /\S+/
export default {
parse: function (token, remainTokens) {
parse: function (token: TagToken, remainTokens: Token[]) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
@@ -19,7 +24,7 @@ export default {
this.tpls = this.liquid.parser.parse(remainTokens)
},
render: async function (scope, hash) {
render: async function (scope: Scope, hash: Hash) {
const layout = scope.opts.dynamicPartials
? evalValue(this.layout, scope)
: this.staticLayout
@@ -38,4 +43,4 @@ export default {
scope.pop(hash)
return partial
}
}
} as ITagImplOptions
+8 -4
View File
@@ -1,10 +1,14 @@
export default {
parse: function (tagToken, remainTokens) {
import TagToken from "src/parser/tag-token";
import Token from "src/parser/token";
import ITagImplOptions from "src/template/tag/itag-impl-options";
export default <ITagImplOptions>{
parse: function (tagToken: TagToken, remainTokens: Token[]) {
this.tokens = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
.on('token', (token: TagToken) => {
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
@@ -14,6 +18,6 @@ export default {
stream.start()
},
render: function () {
return this.tokens.map(token => token.raw).join('')
return this.tokens.map((token: Token) => token.raw).join('')
}
}
+15 -8
View File
@@ -2,14 +2,21 @@ 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'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import ITemplate from 'src/template/itemplate';
import Scope from 'src/scope/scope';
import Hash from 'src/template/tag/hash';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
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)
parse: function (tagToken: TagToken, remainTokens: Token[]) {
const match = re.exec(tagToken.args) as RegExpExecArray
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
@@ -17,10 +24,10 @@ export default {
this.templates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('template', (tpl: ITemplate) => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
@@ -28,20 +35,20 @@ export default {
stream.start()
},
render: async function (scope, hash) {
render: async function (scope: Scope, hash: 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 => {
const contexts = collection.map((item: any) => {
const ctx = {}
ctx[this.variable] = item
return ctx
})
let row
let row: number = 0
let html = ''
await mapSeries(contexts, async (context, idx) => {
row = Math.floor(idx / cols) + 1
@@ -65,4 +72,4 @@ export default {
}
return html
}
}
} as ITagImplOptions
+10 -4
View File
@@ -1,11 +1,17 @@
import { evalExp, isFalsy } from 'src/render/syntax'
import TagToken from 'src/parser/tag-token';
import Token from 'src/parser/token';
import ITemplate from 'src/template/itemplate';
import Scope from 'src/scope/scope';
import ITagImplOptions from 'src/template/tag/itag-impl-options';
import ParseStream from 'src/parser/parse-stream';
export default {
parse: function (tagToken, remainTokens) {
parse: function (tagToken: TagToken, remainTokens: Token[]) {
this.templates = []
this.elseTemplates = []
let p
const stream = this.liquid.parser.parseStream(remainTokens)
const stream: ParseStream = this.liquid.parser.parseStream(remainTokens)
.on('start', () => {
p = this.templates
this.cond = tagToken.args
@@ -20,10 +26,10 @@ export default {
stream.start()
},
render: function (scope) {
render: function (scope: Scope) {
const cond = evalExp(this.cond, scope)
return isFalsy(cond)
? this.liquid.renderer.renderTemplates(this.templates, scope)
: this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
}
} as ITagImplOptions