-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnue.js
More file actions
340 lines (259 loc) · 7.76 KB
/
Copy pathnue.js
File metadata and controls
340 lines (259 loc) · 7.76 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
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
import For from './for.js'
import If from './if.js'
const CONTROL_FLOW = { ':if': If, ':for': For } // :if must be first
const CORE_ATTR = ['class', 'style', 'id']
/**
* Creates a new application instance (aka. reactive component)
*
* https://nuejs.org/docs/nuejs/reactive-components.html
*
* @typedef {{ name: string, tagName: string, tmpl: string, ... }} Component
* @param { Component } component - a (compiled) component instance to be mounted
* @param { Object } data? - optional data or data model for the component
* @param { Array<Component> } deps - optional array of nested/dependant components
* @param { Object } $parent - (for internal use only)
*/
export default function createApp(component, data={}, deps=[], $parent={}) {
const { Impl, tmpl, fns=[], dom, inner } = component
const expr = []
function walk(node) {
const type = node.nodeType
// text content
if (type == 3) {
const [_, i] = /:(\d+):/.exec(node.textContent.trim()) || []
const fn = fns[i]
if (fn) expr.push(() => node.textContent = renderVal(fn(ctx)))
}
// element
if (type == 1) {
// loops & conditionals
for (const key in CONTROL_FLOW) {
const fn = fns[node.getAttribute(key)]
// TODO: for + if work reactively on the same node
if (key == ':if' && fn && node.getAttribute(':for')) {
// if (true) -> quick continue
if (fn(ctx)) continue
// if (false) -> disable for loop
else node.removeAttribute(':for')
}
if (fn) {
node.removeAttribute(key)
const ext = CONTROL_FLOW[key]({ root: node, fn, fns, deps, ctx, processAttrs })
expr.push(ext.update || ext)
return ext
}
}
const tagName = node.tagName.toLowerCase()
const next = node.nextSibling
// slot
if (inner && tagName == 'slot') {
inner.replace(node)
return { next }
}
// custom child
const child = deps.find(el => el.name == tagName)
if (child) {
// inner <slot/> content
if (node.firstChild) {
const dom = document.createElement('_')
dom.append(...node.childNodes)
child.inner = createApp({ fns, dom }, ctx, deps)
}
const parent = createParent(node)
const comp = createApp(child, data, deps, parent).mount(node)
// Root node changes -> re-point to the new DOM element
if (dom?.tagName.toLowerCase() == child.name) self.$el = comp.$el
expr.push(() => setAttrs(comp.$el, parent))
// component refs (TODO: into mount?)
self.$refs[node.getAttribute('ref') || tagName] = comp.impl
return { next }
} else {
processAttrs(node)
walkChildren(node, walk)
}
}
}
function processAttrs(node) {
for (const el of [...node.attributes]) {
processAttr(node, el.name, el.value)
}
}
function setAttr(node, key, val) {
const orig = node.getAttribute(key)
if (orig !== val) node.setAttribute(key, val)
}
function processAttr(node, name, value) {
if (name == 'ref' || name == 'name') self.$refs[value] = node
const fn = fns[value]
if (!fn) return
const real = name.slice(1)
const char = name[0]
// remove special attributes
if (':@$'.includes(char)) node.removeAttribute(name)
// set all attributes from object
if (real == 'attr') {
return expr.push(() => {
for (const [name, val] of Object.entries(fn(ctx))) {
setAttr(node, name, val === true ? '' : val)
}
})
}
// dynamic attributes
if (char == ':' && real != 'bind') {
expr.push(() => {
let val = fn(ctx)
setAttr(node, real, renderVal(val))
})
}
// event handler
if (char == '@') {
node[`on${real}`] = evt => {
fn.call(ctx, ctx, evt)
update()
}
}
// boolean attribute
if (char == '$') {
expr.push(() => fn(ctx) ? node[real] = real : node.removeAttribute(real))
}
// html
if (real == 'html') expr.push(() => node.innerHTML = fn(ctx))
}
function walkChildren(node, fn) {
let child = node.firstChild
while (child) {
child = fn(child)?.next || child.nextSibling
}
}
// node[key] --> dataset, node.title = '' -> undefined (to not override :bind)
function getAttr(node, key) {
const fn = fns[node.getAttribute(':' + key)]
return fn ? fn(ctx) : node.getAttribute(key) || node[key] || undefined
}
// non-core (id, class, style) attributes with primitive value
function getAttrs(node) {
const attr = {}
for (const el of [...node.attributes]) {
const name = el.name.replace(':', '')
const val = getAttr(node, name)
if (!CORE_ATTR.includes(name) && typeof(val) != 'object') {
attr[name] = val == null ? true : val
}
}
return attr
}
function createParent(node) {
node.$attrs = getAttrs(node)
return new Proxy(node, {
get(__, key) {
return getAttr(node, key)
}
})
}
function setAttrs(root, parent) {
const arr = mergeVals(getAttr(root, 'class') || [], parent.class)
if (arr[0]) root.className = renderVal(arr, ' ')
const { id, style } = parent
if (style && style.x != '') root.style = renderVal(style)
if (id) root.id = renderVal(id)
}
function update(obj) {
if (obj) Object.assign(impl, obj)
expr.map(el => el())
impl.updated?.call(ctx, ctx)
return self
}
// context
let impl = {}
const self = {
update,
$el: dom,
// root === $el
get root() { return self.$el },
$refs: {},
$parent,
impl,
mount(wrap) {
const root = dom || (self.$el = mkdom(tmpl))
// Isomorphic JSON. Saved for later hot-reloading
let script = wrap.querySelector('script')
if (script) {
Object.assign(data, JSON.parse(script.textContent))
wrap.insertAdjacentElement('afterend', script)
}
// setup refs
// constructor
if (Impl) {
impl = self.impl = new Impl(ctx)
// for
impl.$refs = self.$refs
impl.update = update
}
walk(root)
wrap.replaceWith(root)
// copy root attributes
for (const a of [...wrap.attributes]) setAttr(root, a.name, a.value)
// callback: mounted()
impl.mounted?.call(ctx, ctx)
return update()
},
// used by slots
replace(wrap) {
walk(dom)
wrap.replaceWith(...dom.children)
update()
},
// used by loops and conditionals
before(anchor) {
if (dom) {
self.$el = dom
anchor.before(dom)
if (!dom.walked) { walk(dom); dom.walked = 1 }
return update()
}
},
unmount() {
self.root.remove()
impl.unmounted?.call(ctx, ctx)
update()
}
}
const ctx = new Proxy({}, {
get(__, key) {
// keep this order
for (const el of [self, impl, data, $parent, $parent.bind]) {
const val = el && el[key]
if (val != null) return val
}
},
set(__, key, val) {
// parent key? (loop items)
if ($parent && $parent[key] !== undefined) {
$parent[key] = val
$parent.update()
} else {
self[key] = val
}
return true
}
})
return self
}
// good for async import
export { createApp }
function mkdom(tmpl) {
const el = document.createElement('_')
el.innerHTML = tmpl.trim()
return el.firstChild
}
// render expression return value
function renderVal(val, separ='') {
return val?.join ? val.filter(el => el != null).join(separ).trim().replace(/\s+/g, ' ') : val || ''
}
// to merge the class attribute from original mount point
function mergeVals(a, b) {
if (a == b) return [a]
if (!a.join) a = [a]
if (b && !b.join) b = [b]
return a.concat(b)
}