feat: with & for in render tag, closes #195

This commit is contained in:
harttle
2020-03-04 07:08:54 +08:00
parent aa27a6cd7b
commit 6ea6881f08
67 changed files with 1108 additions and 724 deletions
+6 -62
View File
@@ -1,6 +1,7 @@
import { Expression } from '../render/expression'
import { Tokenizer } from '../parser/tokenizer'
import { FilterMap } from '../template/filter/filter-map'
import { FilterArgs, Filter } from './filter/filter'
import { Filter } from './filter/filter'
import { Context } from '../context/context'
export class Value {
@@ -8,43 +9,12 @@ export class Value {
public readonly initial: string
/**
* @param str value string, like: "i have a dream | truncate: 3
* @param str the value to be valuated, eg.: "foobar" | truncate: 3
*/
public constructor (str: string, private readonly filterMap: FilterMap) {
const tokens = Value.tokenize(str)
this.initial = tokens[0]
this.parseFilters(tokens, 1)
}
private parseFilters (tokens: string[], begin: number) {
let i = begin
while (i < tokens.length) {
if (tokens[i] !== '|') {
i++
continue
}
const j = ++i
while (i < tokens.length && tokens[i] !== '|') i++
this.parseFilter(tokens, j, i)
}
}
private parseFilter (tokens: string[], begin: number, end: number) {
const name = tokens[begin]
const args: FilterArgs = []
let argName, argValue
for (let i = begin + 1; i < end + 1; i++) {
if (i === end || tokens[i] === ',') {
if (argName || argValue) {
args.push(argName ? [argName, argValue] : argValue as string)
}
argValue = argName = undefined
} else if (tokens[i] === ':') {
argName = argValue
argValue = undefined
} else if (argValue === undefined) {
argValue = tokens[i]
}
}
this.filters.push(new Filter(name, this.filterMap.get(name), args))
const tokenizer = new Tokenizer(str)
this.initial = tokenizer.readValue()
this.filters = tokenizer.readFilterTokens().map(({ name, args }) => new Filter(name, this.filterMap.get(name), args))
}
public * value (ctx: Context) {
let val = yield new Expression(this.initial).evaluate(ctx)
@@ -53,30 +23,4 @@ export class Value {
}
return val
}
public static tokenize (str: string): ('|' | ',' | ':' | string)[] {
const tokens = []
let i = 0
while (i < str.length) {
const ch = str[i]
if (ch === '"' || ch === "'") {
const j = i
for (i += 2; i < str.length && str[i - 1] !== ch; ++i);
tokens.push(str.slice(j, i))
} else if (/\s/.test(ch)) {
i++
} else if (/[|,:]/.test(ch)) {
tokens.push(str[i++])
} else {
const j = i++
let ch
for (; i < str.length && !/[|,:\s]/.test(ch = str[i]); ++i) {
if (ch === '"' || ch === "'") {
for (i += 2; i < str.length && str[i - 1] !== ch; ++i);
}
}
tokens.push(str.slice(j, i))
}
}
return tokens
}
}