-
Notifications
You must be signed in to change notification settings - Fork 1
/
InnerTemplatePart.ts
72 lines (61 loc) · 1.85 KB
/
InnerTemplatePart.ts
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
import TemplatePart from "./TemplatePart.js";
import Anchor from "./Anchor.js";
import defaultTemplateProcessor from "./defaultTemplateProcessor.js";
import createInstance from "./createInstance.js";
export default class InnerTemplatePart extends TemplatePart {
private _templateElement: HTMLTemplateElement
private _anchor: Anchor
private _replacementNodes: Array<ChildNode>
constructor(templateElement: HTMLTemplateElement, anchor: Anchor) {
super()
this._templateElement = templateElement
this._anchor = anchor
this._replacementNodes = []
}
private _replaceNodes(): void {
if (this._anchor.isConnected) {
const referenceNode = this._anchor.nextSibling
for (const node of this._replacementNodes) {
this._anchor.parentNode!.insertBefore(node, referenceNode)
}
}
}
get directive() {
return this._templateElement.getAttribute('type')
}
get replacementNodes() {
return this._replacementNodes
}
get template() {
return this._templateElement
}
replace(nodes: Array<string | ChildNode>) {
const newReplacementNodes = [...nodes]
.map(value => {
if (typeof value === 'string') {
return new Text(value)
} else {
return value
}
})
for (const node of this._replacementNodes) {
node.remove()
}
this._replacementNodes = newReplacementNodes
this._replaceNodes()
}
replaceHTML(html: string) {
const templateElement = document.createElement('template')
templateElement.innerHTML = html
const nodes = [...templateElement.content.childNodes]
this._replacementNodes = nodes
this._replaceNodes()
}
replaceInstance(state: any, processor=defaultTemplateProcessor) {
const nodes = createInstance(this._templateElement, {
state,
processor,
}).childNodes
this.replace([...nodes])
}
}