-
Notifications
You must be signed in to change notification settings - Fork 51
/
component.js
98 lines (82 loc) · 2.47 KB
/
component.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
export const freeze = (object, property, value) => {
Object.defineProperty(object, property, {
configurable: true,
get() { return value; },
set(v) { console.warn(`tried to set frozen property ${property} with ${v}`) }
});
};
export const unfreeze = (object, property, value = null) => {
Object.defineProperty(object, property, {
configurable: true,
writable: true,
value: value
});
};
export default {
abstract: true,
name: 'Fragment',
props: {
name: {
type: String,
default: () => Math.floor(Date.now() * Math.random()).toString(16)
},
html: {
type: String,
default: null
}
},
mounted() {
const container = this.$el
const parent = container.parentNode
container.__isFragment = true
container.__isMounted = false
const head = document.createComment(`fragment#${this.name}#head`)
const tail = document.createComment(`fragment#${this.name}#tail`)
container.__head = head
container.__tail = tail
// use document fragment to improve efficiency
let tpl = document.createDocumentFragment()
tpl.appendChild(head)
Array.from(container.childNodes)
.forEach(node => {
// container.appendChild(node, true)
let notFrChild = !node.hasOwnProperty('__isFragmentChild__')
tpl.appendChild(node)
if (notFrChild) {
freeze(node, 'parentNode', container)
freeze(node, '__isFragmentChild__', true)
}
})
tpl.appendChild(tail)
// embed html
if (this.html) {
let template = document.createElement('template')
template.innerHTML = this.html
// copy elements over
Array.from(template.content.childNodes).forEach(node => {
tpl.appendChild(node)
})
}
let next = container.nextSibling
parent.insertBefore(tpl, container, true)
parent.removeChild(container)
freeze(container, 'parentNode', parent)
freeze(container, 'nextSibling', next)
if (next)
freeze(next, 'previousSibling', container)
container.__isMounted = true
},
render(h) {
const children = this.$slots.default
// add fragment attribute on the children
if (children && children.length)
children.forEach(child =>
child.data = { ...child.data, attrs: { fragment: this.name, ...(child.data || {}).attrs } }
)
return h(
"div",
{ attrs: { fragment: this.name } },
children
)
}
};