/
if.js
51 lines (39 loc) · 1.06 KB
/
if.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
// Internal use only
import createApp from './nue.js'
export default function(opts) {
const { root, fn, fns, deps, ctx } = opts
const blocks = []
var node = root
var anchor
var next
function addBlock(node, fn) {
opts.processAttrs(node) // run event handlers on the parent context
const impl = createApp({ fns, dom: node }, ctx, deps, ctx)
blocks.push(impl)
impl.fn = fn
}
addBlock(root, fn)
while (node = node.nextElementSibling) {
const val = node.getAttribute(':else-if')
if (val) {
addBlock(node, fns[val])
node.removeAttribute(':else-if')
} else if (node.hasAttribute(':else')) {
addBlock(node, () => true)
node.removeAttribute(':else')
} else {
next = node
break
}
}
function update() {
if (!anchor) {
const wrap = root.parentElement
anchor = new Text('')
wrap.insertBefore(anchor, root)
}
const active = blocks.find(bl => bl.fn(ctx))
blocks.forEach(bl => bl == active ? bl.before(anchor) : bl.unmount())
}
return { update, next }
}