-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
353 lines (279 loc) · 7.88 KB
/
index.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
export default () => {
const document = new Document(), html = document.createElement('html')
document.appendChild(document.documentElement = html)
html.appendChild(document.head = document.createElement('head'))
html.appendChild(document.body = document.createElement('body'))
Object.assign(document, document.defaultView = { document, Node, Element, Attr, Text, Event, Document })
return document
}
const
s = Symbol,
TYPE = s(), NAME = s(), VALUE = s(), ATTRS = s(), PARENT = s(), CHILDREN = s(), START = s(), PREV = s(), NEXT = s(), END = s(), LISTENERS = s(), STOP = s(),
isVoid = tag => /^area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr$/i.test(tag),
isEmptiable = name => /^allowfullscreen|allowpaymentrequest|async|autofocus|autoplay|checked|class|contenteditable|controls|default|defer|disabled|draggable|formnovalidate|hidden|id|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected|style|truespee$/i.test(name),
replacements = { '\xA0': ' ', '&': '&', '<': '<', '>': '>' },
getEnd = node => node[END] ?? node,
setAdjacent = (prev, next) => {
if (prev) prev[NEXT] = next
if (next) next[PREV] = prev
},
setSiblings = (prev, node, next) => {
setAdjacent(prev, node)
setAdjacent(node, next)
},
setBoundaries = (prev, node, next) => {
setAdjacent(prev, node)
setAdjacent(getEnd(node), next)
},
getAttr = ({ [NEXT]: node }, name) => {
while (node[TYPE] === Node.ATTRIBUTE_NODE) {
if (node[NAME] === name) return node
node = node[NEXT]
}
},
Node = class {
static ELEMENT_NODE = 1
static ATTRIBUTE_NODE = 2
static TEXT_NODE = 3
static DOCUMENT_NODE = 9
constructor(type, name) {
this[TYPE] = type
this[NAME] = name
this[PARENT] = null
this[PREV] = null
this[NEXT] = null
}
*[CHILDREN]({ filter = () => true, map = v => v } = {}) {
let { firstChild: child } = this
while (child) {
if (filter(child)) yield map(child)
child = child.nextSibling
}
}
get nodeType() {
return this[TYPE]
}
get nodeName() {
return this[NAME]
}
get parentNode() {
return this[PARENT]
}
get nextSibling() {
const next = getEnd(this)[NEXT]
return next?.[TYPE] === END ? null : next
}
get previousSibling() {
const { [PREV]: prev } = this
switch (prev?.[TYPE]) {
case END:
return prev[START]
case Node.TEXT_NODE:
return prev
}
return null
}
get firstChild() {
let { [NEXT]: next, [END]: end } = this
while (next?.[TYPE] === Node.ATTRIBUTE_NODE) next = next[NEXT]
return next === end ? null : next
}
get lastChild() {
const prev = this[END]?.[PREV]
switch (prev?.[TYPE]) {
case END:
return prev[START]
case Node.ATTRIBUTE_NODE:
return null
}
return prev === this ? null : prev
}
get childNodes() {
return [...this[CHILDREN]()]
}
appendChild(child) {
return this.insertBefore(child, this[END])
}
insertBefore(child, ref) {
if (child === ref) return child
if (child === this) throw new Error('The new child element contains the parent') // Note: A node is contained inside itself.
ref ??= this[END]
switch (child?.[TYPE]) {
case Node.ELEMENT_NODE:
child.remove()
child[PARENT] = this
setBoundaries(ref[PREV], child, ref)
break
case Node.TEXT_NODE:
child.remove()
default:
child[PARENT] = this
setSiblings(ref[PREV], child, ref)
break
}
return child
}
removeChild(child) {
if (child?.[PARENT] !== this) throw new Error('The node to be removed is not a child of this node.')
child.remove()
return child
}
remove() {
setAdjacent(this[PREV], getEnd(this)[NEXT])
this[PARENT] = this[PREV] = getEnd(this)[NEXT] = null
}
replaceChildren(...nodes) {
let { firstChild: next } = this, after
while (next !== null) {
after = next.nextSibling
next.remove()
next = after
}
for (const node of nodes) this.appendChild(node)
}
},
Element = class extends Node {
constructor(nodeType, nodeName) {
super(nodeType ?? Node.ELEMENT_NODE, nodeName)
this[NEXT] = this[END] = { [TYPE]: END, [START]: this, [PREV]: this, [NEXT]: null }
this[LISTENERS] = null
}
*[ATTRS]({ filter = () => true, map = v => v } = {}) {
let { [NEXT]: next } = this
while (next[TYPE] === Node.ATTRIBUTE_NODE) {
if (filter(next)) yield map(next)
next = next[NEXT]
}
}
get localName() {
return this[NAME].toLowerCase()
}
get innerHTML() {
return this.childNodes.join('')
}
get outerHTML() {
return this.toString()
}
get attributes() {
return [...this[ATTRS]()]
}
get children() {
return [...this[CHILDREN]({ filter: node => node[TYPE] === Node.ELEMENT_NODE })]
}
hasAttributes() {
return this[NEXT][TYPE] === Node.ATTRIBUTE_NODE
}
getAttributeNames() {
return [...this[ATTRS]({ map: attr => attr.name })]
}
setAttribute(name, value) {
const attr = getAttr(this, name)
if (attr) attr[VALUE] = value
else setSiblings(this, new Attr(name, value), this[NEXT])
}
getAttribute(name) {
return getAttr(this, name)?.[VALUE]
}
removeAttribute(name) {
const attr = getAttr(this, name)
attr && setAdjacent(attr[PREV], attr[NEXT])
}
cloneNode(deep = false) {
const clone = new Element(this.nodeType, this.nodeName)
for (const attr of this.attributes) clone.setAttribute(attr.name, attr.value)
if (deep) for (const child of this.childNodes) clone.appendChild(child.cloneNode(deep))
return clone
}
addEventListener(type, handler) {
((this[LISTENERS] ??= {})[type] ??= new Set()).add(handler)
}
removeEventListener(type, handler) {
this[LISTENERS]?.[type]?.delete(handler)
}
dispatchEvent(event) {
let target = event.target = this, cancelable = event.cancelable, listener
do {
event.currentTarget = target
listener = target[LISTENERS]?.[event.type]
if (listener && listener.size) {
listener = Array.from(listener)
for (let i = listener.length; i--;) {
if ((listener[i].call(target, event) === false || event[END]) && cancelable) event.defaultPrevented = true
}
}
} while (event.bubbles && !(cancelable && event[STOP]) && (target = target.parentNode))
return listener != null
}
toString() {
const tag = this.nodeName.toLowerCase()
return `<${tag}${this.hasAttributes() ? ' ' : ''}${this.attributes.join(' ')}>${isVoid(tag) ? '' : `${this.innerHTML}</${tag}>`}`
}
},
Attr = class extends Node {
constructor(name, value) {
super(Node.ATTRIBUTE_NODE, name)
this[VALUE] = value
}
get name() {
return this[NAME]
}
get value() {
return this[VALUE]
}
cloneNode() {
return new Attr(this.name, this.value)
}
toString() {
const { name, value } = this
return isEmptiable(name) && !value ? name : `${name}="${String(value).replace(/"/g, '"')}"`
}
},
Text = class extends Node {
constructor(text) {
super(Node.TEXT_NODE, '#text')
this[VALUE] = text
}
set data(text) {
this[VALUE] = text
}
get data() {
return this[VALUE]
}
cloneNode() {
return new Text(this.data)
}
toString() {
return String(this.data).replace(/[<>&\xA0]/g, c => replacements[c])
}
},
Event = class {
constructor(type, options) {
this.type = type
this.bubbles = Boolean(options?.bubbles)
this.cancelable = Boolean(options?.cancelable)
this.defaultPrevented = this[STOP] = this[END] = false
}
stopPropagation() {
this[STOP] = true
}
stopImmediatePropagation() {
this[END] = this[STOP] = true
}
preventDefault() {
this.defaultPrevented = true
}
},
Document = class extends Element {
constructor() {
super(Node.DOCUMENT_NODE, '#document')
}
createElement(type) {
return new Element(null, String(type).toUpperCase())
}
createTextNode(text) {
return new Text(text)
}
toString() {
return `<!DOCTYPE html>${this.childNodes}`
}
}