-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpunybind.js
357 lines (310 loc) · 8.9 KB
/
punybind.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
(function (exports) {
'use strict'
// eslint-disable-next-line no-new-func
const defaultCompiler = expression => new Function(`return function(_){with (_){return ${expression}}}`)()
const safeCompile = (expression, { compiler }) => {
try {
const compiled = compiler(expression)
return function (context) {
let result
try {
result = compiled(context)
} catch (e) {
// ignore
}
if (result === undefined) {
return ''
}
return result
}
} catch (e) {
// ignore
}
}
const safeCompileComposite = (value, options) => {
const parsed = value.split(/{{((?:[^}])+)}}/)
const escape = str => str.replace(/\\|'/g, match => ({ '\\': '\\\\', '\'': '\\\'' }[match]))
if (parsed.length > 1) {
return safeCompile(parsed.map((expr, idx) => idx % 2 ? `(${expr})` : `'${escape(expr)}'`).join('+'), options)
}
}
const ELEMENT_NODE = 1
const TEXT_NODE = 3
const attr = (node, name) => node.getAttribute(name)
const bindTextNode = (node, bindings, options) => {
const valueFactory = safeCompileComposite(node.nodeValue, options)
if (valueFactory) {
const parent = node.parentNode
let value
bindings.push((context, changes) => {
const newValue = valueFactory(context)
if (newValue !== value) {
const newChild = parent.ownerDocument.createTextNode(newValue)
value = newValue
changes.push(() => {
parent.replaceChild(newChild, node)
node = newChild
})
}
})
}
}
const bindAttribute = (node, name, bindings, options) => {
const valueFactory = safeCompileComposite(attr(node, name), options)
if (valueFactory) {
let value
bindings.push((context, changes) => {
const newValue = valueFactory(context)
if (newValue !== value) {
value = newValue
changes.push(() => {
node.setAttribute(name, newValue)
})
}
})
}
}
const addToTemplate = (node, attributeName, template) => {
const { nextElementSibling } = node
template.appendChild(node)
node.removeAttribute(attributeName)
return nextElementSibling
}
const getTemplate = (node, attributeName) => {
const parent = node.parentNode
const template = node.ownerDocument.createElement('template')
parent.insertBefore(template, node)
addToTemplate(node, attributeName, template)
return [parent, template]
}
const CLONE = 0
const BINDINGS = 1
const instantiate = (template, changes, options, index = 0) => {
let elementToClone = template.firstElementChild
while (index-- > 0) {
elementToClone = elementToClone.nextElementSibling
}
const clone = elementToClone.cloneNode(true)
changes.push(function () {
template.parentNode.insertBefore(clone, template)
})
return [
clone,
parse(clone, options)
]
}
const remove = (parent, instances, changes) => {
changes.push(function () {
this.forEach(instance => parent.removeChild(instance[CLONE]))
}.bind(instances))
}
const $for = '{{for}}'
const bindIterator = (node, bindings, options) => {
const forValue = attr(node, $for)
const match = /^\s*(\w+)(?:\s*,\s*(\w+))?\s+of\s(.*)/.exec(forValue)
if (!match) {
return
}
const [, valueName, indexName, iterator] = match
const iteratorFactory = safeCompile(iterator, options)
if (!iteratorFactory) {
return
}
const [parent, template] = getTemplate(node, $for)
const instances = []
bindings.push(async (context, changes) => {
const iterator = iteratorFactory(context)
let index = -1
for await (const item of iterator) {
++index
if (index === instances.length) {
instances.push(instantiate(template, changes, options))
}
await collectChanges(
instances[index][BINDINGS],
{
...context,
[valueName]: item,
[indexName]: index
},
changes
)
}
++index
remove(parent, instances.slice(index), changes)
instances.length = index
})
}
const $if = '{{if}}'
const $elseif = '{{elseif}}'
const $else = '{{else}}'
const INSTANCE = 1
const bindConditional = (node, bindings, options) => {
const valueFactory = safeCompile(attr(node, $if), options)
if (!valueFactory) {
return
}
let nextSibling = node.nextElementSibling
const [parent, template] = getTemplate(node, $if)
const conditionalChain = [[valueFactory]]
while (nextSibling) {
const elseIf = attr(nextSibling, $elseif)
if (elseIf) {
const eiValueFactory = safeCompile(elseIf, options)
if (!eiValueFactory) {
break
}
conditionalChain.push([eiValueFactory])
nextSibling = addToTemplate(nextSibling, $elseif, template)
} else {
if (nextSibling.hasAttribute($else)) {
addToTemplate(nextSibling, $else, template)
conditionalChain.push([() => true])
}
break
}
}
bindings.push(async (context, changes) => {
let searchTrueCondition = true
const instancesToRemove = []
let index = -1
for (const condition of conditionalChain) {
++index
const [valueFactory, instance] = condition
const value = searchTrueCondition && valueFactory(context)
if (value) {
searchTrueCondition = false
if (!instance) {
condition[INSTANCE] = instantiate(template, changes, options, index)
}
await collectChanges(condition[INSTANCE][BINDINGS], context, changes)
} else if (instance) {
instancesToRemove.push(instance)
condition[INSTANCE] = undefined
}
}
remove(parent, instancesToRemove, changes)
})
}
const parse = (root, options) => {
const bindings = []
const traverse = node => {
if (node.nodeType === TEXT_NODE) {
bindTextNode(node, bindings, options)
}
if (node.nodeType === ELEMENT_NODE) {
if (attr(node, $for)) {
bindIterator(node, bindings, options)
return
}
if (attr(node, $if)) {
bindConditional(node, bindings, options)
return
}
for (const attr of node.attributes) {
bindAttribute(node, attr.name, bindings, options)
}
const childNodes = node.childNodes
let index = 0
while (index < childNodes.length) {
traverse(childNodes[index++])
}
}
}
traverse(root)
return bindings
}
const collectChanges = async (bindings, context, changes) => {
for (const binding of bindings) {
await binding(context, changes)
}
}
const observe = (object, refresh) => {
return new Proxy(object, {
get (obj, prop) {
const value = obj[prop]
const type = typeof value
if (type === 'object') {
return observe(value, refresh)
}
return value
},
set (obj, prop, value) {
const previousValue = obj[prop]
if (previousValue !== value) {
obj[prop] = value
refresh()
}
return true
}
})
}
const ro = value => ({
value,
writable: false
})
const assignROProperties = (object, properties) => {
Object.defineProperties(
object,
Object.keys(properties).reduce((dict, property) => {
dict[property] = ro(properties[property])
return dict
}, {})
)
}
async function punybind (root, properties = {}) {
const bindings = parse(root, this)
let done = Promise.resolve()
let succeeded
let failed
let lastContext
const debounced = async () => {
try {
const changes = []
await collectChanges(bindings, lastContext, changes)
for (const change of changes) {
await change()
}
lastContext = undefined
succeeded(changes.length)
} catch (reason) {
failed(reason)
}
}
const update = async (context) => {
if (lastContext === undefined) {
setTimeout(debounced, 0)
done = new Promise((resolve, reject) => {
succeeded = resolve
failed = reject
})
}
lastContext = context
return done
}
await update(properties)
const model = observe(properties, () => {
update(properties)
})
assignROProperties(update, {
bindingsCount: bindings.length,
model,
done: () => done
})
return update
}
const use = (options) => {
const instance = punybind.bind(options)
assignROProperties(instance, {
version: '0.0.0',
use: addOptions => use({
...options,
...addOptions
})
})
return instance
}
exports.punybind = use({
compiler: defaultCompiler
})
}(this))