forked from hapjs-platform/hap-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexp.js
More file actions
90 lines (81 loc) · 2.29 KB
/
Copy pathexp.js
File metadata and controls
90 lines (81 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* Copyright (c) 2021-present, the hapjs-platform Project Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import expParser from './lib/expression'
import textParser from './lib/text'
import parseFilter from './lib/filter-parser'
// 去除字符串头部空格或指定字符
function trimhtml(str) {
// 2个空格以上, 仅保留一个空格
str = str.replace(/^\s\s+/, ' ')
if (str.length <= 1) {
return str
}
const startSpace = str.charAt(0) === ' ' ? 1 : 0
const oldLength = str.length
str = str.trim()
// 尾部多余1个空格
if (oldLength - str.length - startSpace >= 1) {
str = str + ' '
}
return (startSpace ? ' ' : '') + str
}
/**
* 表达式转换
* @param expContent
* @param toFunc
* @param isLite is lite card
* @returns {*}
*/
function transExpr(expContent, toFunc, isLite, isCard) {
let ret
const trimExpContent = expContent.trim()
if (!textParser.isExpr(trimExpContent)) {
ret = trimhtml(expContent)
} else if (isLite) {
ret = trimExpContent // lite card template value
} else {
ret = []
const tokens = textParser.parseText(trimExpContent)
const isSingle = tokens.length === 1
tokens.forEach(function (token) {
if (token.tag) {
let res = expParser.parseExpression(parseFilter(token.value))
if (!isSingle) {
res = '(' + res + ')'
}
ret.push(res)
} else {
ret.push("'" + token.value + "'")
}
})
// 确保多个插值表达式相邻时,是字符串拼接,而不是数值相加,例如:{{number1}}{{number2}}
if (!isSingle) {
ret.unshift("''")
}
ret = ret.join(' + ')
if (toFunc !== false) {
try {
if (isCard) {
ret = 'function () {return ' + ret + '}'
} else {
/* eslint-disable no-eval */
ret = eval('(function () {return ' + ret + '})')
}
/* eslint-enable no-eval */
} catch (err) {
err.isExpressionError = true
err.expression = trimExpContent
throw err
}
}
}
return ret
}
transExpr.isExpr = textParser.isExpr
transExpr.parseText = textParser.parseText
transExpr.singleExpr = textParser.singleExpr
transExpr.removeExprffix = textParser.removeExprffix
transExpr.addExprffix = textParser.addExprffix
module.exports = transExpr