-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.mjs
363 lines (289 loc) · 7.54 KB
/
node.mjs
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
354
355
356
357
358
359
360
361
362
363
import {emptyTags} from './parse-tag.mjs'
const nonAttrs = ['nodeName', 'nodeValue', '_closed', 'class']
const printAttrs = node => {
/// Prints a set of attributes as a string.
/// => string
const attrs = []
Object.keys(node).forEach(attr => {
const val = node[attr]
const isString = (typeof val === 'string')
const isAttrName = (isString && !nonAttrs.includes(attr))
if (isAttrName && val) {
if (attr === 'className') {
attrs.push(`class="${val}"`)
} else if (val === 'true') {
attrs.push(attr)
} else {
attrs.push(`${attr}="${val}"`)
}
}
})
return attrs.join(' ')
}
const query = (node, selector) => {
/// Executes the given query on the DOM.
/// => Array<AstNode>
// Should we index classes and ids during parse?
// That would make this massively faster.
// • h1
// • #foo-id
// • .foo-class
// h1.foo-class
// h2#foo-id
// {el}?[attr]
// {el}?[attr=value]
// {sel} {sel}
// {sel}>{sel}
if (typeof selector === 'string') {
let attr = ''
let value = ''
if (selector.startsWith('#')) {
attr = 'id'
value = selector.slice(1).trim()
}
if (selector.startsWith('.')) {
attr = 'className'
value = selector.slice(1).trim()
}
if (selector.startsWith('[')) {
[attr, value] = selector.slice(1,-1).split('=')
value = (value || '')
}
if (!attr) {
attr = 'nodeName'
value = selector
}
selector = {attr, value}
}
const results = []
node.childNodes.forEach(node => {
results.push(...query(node, selector))
})
if (selector.attr === 'className' && node.classList.contains(selector.value)) {
results.push(node)
} else if (selector.attr === 'nodeName' && node.nodeName.toLowerCase() === selector.value) {
results.push(node)
} else if (node[selector.attr] === selector.value) {
results.push(node)
}
return results
}
const addClass = function (className) {
/// Adds the given className to the className prop.
/// Note: Will not add it redundantly.
/// => undefined
className = className.trim()
if (!className) {
return
}
if (!this.classList.contains(className)) {
this.className = ((this.className || '') + ' ' + className).trim()
}
}
const hasClass = function (className) {
/// Indicates whether the given className is in the className prop.
/// Note: Case-sensitive.
/// => boolean
className = className.trim()
if (!className) {
return false
}
if (!(this.className || '').includes(className)) {
return false
}
return (this.className || '').split(' ').includes(className)
}
const removeClass = function (className) {
/// Removes the given className from the className prop.
/// => undefined
className = className.trim()
if (!className) {
return
}
this.className = this.className
.split(' ')
.filter(s => s !== className)
.join(' ')
}
class AstNode {
/// A basic implementation of the core DOM node capabilities.
/// All attributes are understood as optional extensions.
constructor (pos) {
this.onset = pos
this.id = ''
this.className = ''
this.parent = null // AstNode
this.nodeName = ''
this.nodeValue = '' // Only populated for TEXTNODE nodes.
this.childNodes = []
this.classList = {
add: addClass.bind(this),
contains: hasClass.bind(this),
remove: removeClass.bind(this)
}
}
append(...fragments) {
/// Adds the given dom fragments to the end of childNodes.
/// => undefined
fragments.forEach(frag => {
if (typeof frag === 'string') {
const textNode = new AstNode(0)
textNode.nodeName = 'TEXTNODE'
textNode.nodeValue = frag
this.childNodes.push(textNode)
} else {
this.childNodes.push(frag)
}
})
}
cloneNode(deep = false) {
/// Returns an optionally deep clone of the this AstNode.
/// => AstNode
const clone = new AstNode(0)
const classList = clone.classList
Object.assign(clone, {...this, classList, childNodes: []})
if (deep) {
clone.childNodes = this.childNodes.map(node => node.cloneNode(true))
}
return clone
}
insertBefore(node, refNode) {
/// Inserts the given node before the given reference node.
/// => undefined
if (node.constructor !== AstNode) {
throw new TypeError(
'Failed to execute \'insertBefore\': '+
'parameter 1 is not of type \'Node\'.'
)
}
if (refNode.constructor !== AstNode) {
throw new TypeError(
'Failed to execute \'insertBefore\': '+
'parameter 2 is not of type \'Node\'.'
)
}
const pos = this.childNodes.indexOf(refNode)
this.childNodes.splice(pos, 0, node)
}
querySelector(selector) {
/// Returns the first match from the dom.
/// => AstNode?
return (query(this, selector)[0] || null)
}
querySelectorAll(selector) {
/// Returns all matches in the dom.
/// => Array<AstNode>
return query(this, selector)
}
remove() {
/// Removes this node from the tree.
/// => undefined
const i = this.parent.childNodes.indexOf(this)
this.parent.childNodes.splice(i, 1)
}
removeChild(node) {
/// Removes the given node from the document if it is a child
/// of this AstNode.
/// => undefined
if (node.constructor !== AstNode) {
throw new TypeError(
'Failed to execute \'removeChild\': '+
'parameter 1 is not of type \'Node\'.'
)
}
if (!this.parent.childNodes.includes(node)) {
throw new Error(
'Failed to execute \'removeChild\': The node '+
'to be removed is not a child of this node.'
)
}
node.remove()
}
get firstChild() {
/// Read-only calculated property.
/// => AstNode?
return (this.childNodes[0] || null)
}
get innerHTML() {
/// Prints all child nodes as an HTML string.
/// => string
return this.childNodes.reduce((html, node) => (
html + node.outerHTML
), '')
}
get isConnected() {
/// Read-only calculated property.
/// => boolean
return !!this.ownerDocument
}
get lastChild() {
/// Read-only calculated property.
/// => AstNode?
return (this.childNodes.slice(-1)[0] || null)
}
get nextSibling() {
/// Read-only calculated property.
/// => AstNode?
const i = this.parent.childNodes.indexOf(this)
return (this.parent.childNodes[i + 1] || null)
}
get nodeType() {
/// Read-only calculated property.
/// => AstNode?
const name = node.nodeName
if (name === 'TEXTNODE') {
return 'TEXT_NODE'
} else if (name === 'HTML') {
return 'DOCUMENT_NODE'
} else if (name === '!DOCTYPE') {
return 'DOCUMENT_TYPE_NODE'
} else if (name === 'FRAGMENT') {
return 'DOCUMENT_FRAGMENT_NODE'
} else {
return 'ELEMENT_NODE'
}
}
get outerHTML() {
/// Prints a DOM node as an HTML string.
/// => string
if (this.nodeName == 'TEXTNODE') {
return this.nodeValue
}
if (this.nodeName == 'FRAGMENT') {
return this.childNodes.map(node => node.outerHTML).join('')
}
const opening = [
this.nodeName.toLowerCase(),
printAttrs(this)
].filter(s => s).join(' ')
const closing = emptyTags.includes(this.nodeName)
? ''
: `</${this.nodeName.toLowerCase()}>`
return `<${opening}>` +
this.childNodes.map(node => node.outerHTML).join('') +
closing
}
get ownerDocument () {
/// Read-only calculated property.
/// => AstNode?
let parent = this.parent
while (parent.nodeName !== 'HTML') {
parent = parent.parent
}
return (parent || null)
}
get previousSibling() {
/// Read-only calculated property.
/// => AstNode?
const i = this.parent.childNodes.indexOf(this)
return (this.parent.childNodes[i - 1] || null)
}
get textContent () {
/// Read-only calculated property.
/// => AstNode?
this.childNodes.reduce((txt, node) => (
txt + (node.nodeValue || node.textContent)
), '')
}
}
export const createNode = state => new AstNode(state.pos)