-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
308 lines (257 loc) · 6.81 KB
/
index.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
const standard = require('standard')
const htmlparser = require('htmlparser2')
const delim = ['{', '}']
const startDelim = delim[0]
const specialEls = ['elseif', 'else']
const specialAttrs = ['if', 'each']
let root, buffer, curr, defaultFnName, defaultFnArgs
function strify (str) {
str = str
? str.replace('\n', '\\\n')
: ''
return '"' + str + '"'
}
function interpolate (text) {
const parts = text.split(/({.*?})/)
text = parts.filter(p => p).map((part, index) => {
if (part.startsWith('{')) {
return `(${part.slice(1, -1)})`
} else {
return strify(part)
}
}).join(' + ')
return text
}
function getIterator (target) {
return `(${target} || [])`
}
function getAttrs (target) {
const attributes = []
for (const name in target.attribs) {
if (specialAttrs.indexOf(name) === -1) {
const value = target.attribs[name]
let val = ''
if (name === 'style' || name.startsWith('on')) {
val = value
} else if (value.indexOf(startDelim) > -1) {
val = interpolate(value)
} else {
val = strify(value)
}
attributes.push({
name: name,
value: val
})
}
}
const attribs = attributes.length
? `{ ${attributes.map(a => `'${a.name}': ${a.value}`).join(', ')} }`
: null
return attribs
}
function getBranches (node, nodeOutput) {
const branches = []
if (node.name === 'if') {
// Element based `if`
let n = node
do {
branches.push({
condition: n.attribs['condition'],
rtn: n.childrenToString(true)
})
n = n.children.find(c => c.name === 'elseif' || c.name === 'else')
} while (n)
} else {
// Attribute based `if`
branches.push({
condition: node.attribs['if'],
rtn: nodeOutput
})
}
return branches
}
class Node {
constructor (parent, name, attribs) {
this.parent = parent
this.name = name
this.attribs = attribs
this.children = []
}
get isSpecial () {
return specialEls.indexOf(this.name) > -1
}
childrenToString (filterSpecial) {
const children = (filterSpecial
? this.children.filter(c => !c.isSpecial)
: this.children).map(c => c.toString())
let childstr = ''
if (children.length) {
childstr = children.length === 1
? children[0]
: '[\n' + children.join(',\n') + '\n]'
}
return childstr
}
toString () {
// Attributes
const attribs = getAttrs(this)
// Children
const childstr = this.childrenToString()
let node
if (this.name === 'script') {
node = this.children.toString()
} else if (this.name === 'function') {
const name = this.attribs.name || defaultFnName
const argstr = this.attribs.args
? buildArgs(this.attribs.args)
: defaultFnArgs
node = `
${wrapFn(name, argstr, this.children.toString().trimLeft())}
`
} else {
const isComponent = /^[A-Z]/.test(this.name)
const name = isComponent ? this.name : `"${this.name}"`
const args = [name]
if (attribs || childstr) {
args.push(attribs || 'null')
if (childstr) {
args.push(childstr)
}
}
node = `h(${args.join(', ')})`
}
if (this.name === 'if') {
const branches = getBranches(this, node)
let str = ''
branches.forEach((branch, index) => {
if (branch.condition) {
str += `${index === 0 ? 'if' : ' else if '} (${branch.condition}) {
return ${branch.rtn}
}`
} else {
str += ` else {
return ${branch.rtn}
}`
}
})
return `(function () {
${str}
}).call(this)`
} else if ('if' in this.attribs) {
return `${this.attribs['if']} ? ${node} : undefined`
} else if ('each' in this.attribs) {
const eachAttr = this.attribs['each']
const eachParts = eachAttr.split(' in ')
const key = eachParts[0]
const target = eachParts[1]
return `${getIterator(target)}.map(function ($value, $index, $target) {\nvar ${key} = $value\nreturn ${node}\n}, this)`
} else {
return node
}
}
}
class Root extends Node {
toString () {
return this.children.map(c => c.toString()).join('\n').trim()
}
}
const handler = {
onopentag: function (name, attribs) {
const newCurr = new Node(curr, name, attribs)
curr.children.push(newCurr)
buffer.push(newCurr)
curr = newCurr
},
ontext: function (text) {
if (!text || !(text = text.trim())) {
return
}
let value
if (curr.name === 'script') {
value = text
} else if (text.indexOf(startDelim) > -1) {
value = interpolate(text)
} else {
value = strify(text)
}
curr.children.push(value)
},
onclosetag: function (name) {
buffer.pop()
curr = buffer[buffer.length - 1]
}
}
function buildArgs (args) {
return args.split(' ').filter(item => {
return item.trim()
}).join(', ')
}
function wrapFn (name, args, value) {
return `function ${name} (${args}) {
return ${value}
}`
}
module.exports = function (tmpl, mode = 'raw', name = 'view', args = 'props state') {
root = new Root()
buffer = [root]
curr = root
defaultFnName = name
defaultFnArgs = buildArgs(args)
const parser = new htmlparser.Parser(handler, {
decodeEntities: false,
lowerCaseAttributeNames: false,
lowerCaseTags: false,
recognizeSelfClosing: true
})
parser.write(tmpl)
parser.end()
const js = root.toString()
let result = ''
try {
if (mode === 'raw') {
result = js
} else {
let wrap = false
let useMode = false
const children = root.children
if (children.length === 1) {
const onlyChild = children[0]
// Only wrap the output if there's a single root
// child and that child is not a <function> tag
if (onlyChild.name !== 'function') {
wrap = true
}
// Only mode the output if there's a single
// root child and that child is not a <script> tag
if (onlyChild.name !== 'script') {
useMode = true
}
}
let value = js
if (wrap) {
value = wrapFn(defaultFnName, defaultFnArgs, js)
}
if (useMode) {
switch (mode) {
case 'esm':
result = `export default ${value}`
break
case 'cjs':
result = `module.exports = ${value}`
break
case 'browser':
result = `window.${name} = ${value}`
break
default:
result = `${mode ? `var ${mode} =` : ''} ${value}`
}
} else {
result = value
}
}
const lintResult = standard.lintTextSync(result, { fix: true })
return lintResult.results[0].output
} catch (err) {
throw new Error(`Error ${err.message}\n${result}\nraw:\n${js}`)
}
}