-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNodeTemplatePart.ts
More file actions
98 lines (83 loc) · 2.31 KB
/
Copy pathNodeTemplatePart.ts
File metadata and controls
98 lines (83 loc) · 2.31 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
import TemplatePart from "./TemplatePart.js";
import Anchor from "./Anchor.js";
export default class NodeTemplatePart extends TemplatePart {
private _expression: string
private _anchor: Node
private _replacementNodes: Array<ChildNode>
constructor(expression: string, anchorNode: Anchor) {
super()
this._expression = expression
this._anchor = anchorNode
this._replacementNodes = []
anchorNode.addEventListener('connected', () => {
this._replaceNodes()
})
anchorNode.addEventListener('disconnected', () => {
if (!this._anchor.isConnected) {
for (const node of this._replacementNodes) {
node.remove()
}
}
})
this._replaceNodes()
}
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 expression() {
return this._expression
}
get replacementNodes() {
return this._replacementNodes
}
get value() {
let value = ''
for (const node of this._replacementNodes) {
value += node.textContent
}
return value
}
set value(value) {
const singleTextNode
= this._replacementNodes.length === 1
&& this._replacementNodes[0] instanceof Text
if (singleTextNode) {
const firstNode = <Text>this._replacementNodes[0]
firstNode.data = value
} else {
for (const node of this._replacementNodes) {
node.remove()
}
const text = new Text(value)
this._replacementNodes = [text]
this._replaceNodes()
}
}
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()
}
}