-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-parser.js
96 lines (88 loc) · 2.51 KB
/
text-parser.js
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
91
92
93
94
95
96
var openChar = '{',
endChar = '}',
ESCAPE_RE = /[-.*+?^${}()|[\]\/\\]/g,
// lazy require
Directive
exports.Regex = buildInterpolationRegex()
function buildInterpolationRegex () {
var open = escapeRegex(openChar),
end = escapeRegex(endChar)
return new RegExp(open + open + open + '?(.+?)' + end + '?' + end + end)
}
function escapeRegex (str) {
return str.replace(ESCAPE_RE, '\\$&')
}
function setDelimiters (delimiters) {
openChar = delimiters[0]
endChar = delimiters[1]
exports.delimiters = delimiters
exports.Regex = buildInterpolationRegex()
}
/**
* Parse a piece of text, return an array of tokens
* token types:
* 1. plain string
* 2. object with key = binding key
* 3. object with key & html = true
*/
function parse (text) {
if (!exports.Regex.test(text)) return null
var m, i, token, match, tokens = []
/* jshint boss: true */
while (m = text.match(exports.Regex)) {
i = m.index
if (i > 0) tokens.push(text.slice(0, i))
token = { key: m[1].trim() }
match = m[0]
token.html =
match.charAt(2) === openChar &&
match.charAt(match.length - 3) === endChar
tokens.push(token)
text = text.slice(i + m[0].length)
}
if (text.length) tokens.push(text)
return tokens
}
/**
* Parse an attribute value with possible interpolation tags
* return a Directive-friendly expression
*
* e.g. a {{b}} c => "a " + b + " c"
*/
function parseAttr (attr) {
Directive = Directive || require('./directive')
var tokens = parse(attr)
if (!tokens) return null
if (tokens.length === 1) return tokens[0].key
var res = [], token
for (var i = 0, l = tokens.length; i < l; i++) {
token = tokens[i]
res.push(
token.key
? inlineFilters(token.key)
: ('"' + token + '"')
)
}
return res.join('+')
}
/**
* Inlines any possible filters in a binding
* so that we can combine everything into a huge expression
*/
function inlineFilters (key) {
if (key.indexOf('|') > -1) {
var dirs = Directive.parse(key),
dir = dirs && dirs[0]
if (dir && dir.filters) {
key = Directive.inlineFilters(
dir.key,
dir.filters
)
}
}
return '(' + key + ')'
}
exports.parse = parse
exports.parseAttr = parseAttr
exports.setDelimiters = setDelimiters
exports.delimiters = [openChar, endChar]