-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
485 lines (436 loc) · 12.6 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/**
* @version 22.9.0
* @date 2022-09-26
* @author Lauri Rooden <lauri@rooden.ee>
* @license MIT License
*/
var boolAttrs = {
async:1, checked:1, defer:1, disabled:1, multiple:1, readonly:1, selected:1
}
, voidElements = {
AREA:1, BASE:1, BR:1, COL:1, EMBED:1, HR:1, IMG:1, INPUT:1,
KEYGEN:1, LINK:1, MENUITEM:1, META:1, PARAM:1, SOURCE:1, TRACK:1, WBR:1
}
, hasOwn = voidElements.hasOwnProperty
, selector = require("./selector.js")
, Node = {
ELEMENT_NODE: 1,
TEXT_NODE: 3,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
nodeName: null,
parentNode: null,
ownerDocument: null,
childNodes: null,
get nodeValue() {
return this.nodeType === 3 || this.nodeType === 8 ? this.data : null
},
set nodeValue(text) {
return this.nodeType === 3 || this.nodeType === 8 ? (this.data = text) : null
},
get textContent() {
return this.hasChildNodes() ? this.childNodes.map(function(child) {
return child[ child.nodeType == 3 ? "data" : "textContent" ]
}).join("") : this.nodeType === 3 ? this.data : ""
},
set textContent(text) {
if (this.nodeType === 3) return (this.data = text)
for (var node = this; node.firstChild;) node.removeChild(node.firstChild)
node.appendChild(node.ownerDocument.createTextNode(text))
},
get firstChild() {
return this.childNodes && this.childNodes[0] || null
},
get lastChild() {
return this.childNodes && this.childNodes[ this.childNodes.length - 1 ] || null
},
get nextSibling() {
return getSibling(this, 1, 0)
},
get previousSibling() {
return getSibling(this, -1, 0)
},
// innerHTML and outerHTML should be extensions to the Element interface
get innerHTML() {
return Node.toString.call(this)
},
set innerHTML(html) {
var match, child
, node = this
, doc = node.ownerDocument || node
, tagRe = /<(!--([\s\S]*?)--!?|!\[[\s\S]*?\]|[?!][\s\S]*?)>|<(\/?)([^ \/>]+)([^>]*?)(\/?)>|[^<]+/g
, attrRe = /([^= ]+)(?:\s*=\s*(("|')((?:\\\3|.)*?)\3|[-.:\w]+)|)/g
for (; node.firstChild; ) node.removeChild(node.firstChild)
for (; (match = tagRe.exec(html)); ) {
if (match[3]) {
node = node.parentNode
} else if (match[4]) {
child = doc.contentType === "text/html" ? doc.createElement(match[4]) : doc.createElementNS(null, match[4])
if (match[5]) {
match[5].replace(attrRe, setAttr)
}
node.appendChild(child)
if (!voidElements[child.tagName] && !match[6]) node = child
} else if (match[2]) {
node.appendChild(doc.createComment(match[2].replace(unescRe, unescFn)))
} else if (match[1]) {
node.appendChild(doc.createDocumentType(match[1]))
} else {
node.appendChild(doc.createTextNode(match[0].replace(unescRe, unescFn)))
}
}
return html
function setAttr(_, name, value, q, qvalue) {
child.setAttribute(name, (q ? qvalue : value || "").replace(unescRe, unescFn))
}
},
get outerHTML() {
return this.toString()
},
set outerHTML(html) {
var frag = this.ownerDocument.createDocumentFragment()
frag.innerHTML = html
this.parentNode.replaceChild(frag, this)
return html
},
get htmlFor() {
return this["for"]
},
set htmlFor(value) {
this["for"] = value
},
get className() {
return this["class"] || ""
},
set className(value) {
this["class"] = value
},
get style() {
return this.styleMap || (this.styleMap = new StyleMap())
},
set style(value) {
this.styleMap = new StyleMap(value)
},
hasChildNodes: function() {
return this.childNodes && this.childNodes.length > 0
},
appendChild: function(el) {
return this.insertBefore(el)
},
insertBefore: function(el, ref) {
var node = this
, childs = node.childNodes
if (el.nodeType == 11) {
while (el.firstChild) node.insertBefore(el.firstChild, ref)
} else {
if (el.parentNode) el.parentNode.removeChild(el)
el.parentNode = node
// If ref is null, insert el at the end of the list of children.
childs.splice(ref ? childs.indexOf(ref) : childs.length, 0, el)
if (node.nodeType == 9) {
ref = node.firstChild
if (ref && ref.nodeType !== 1) ref = ref.nextElementSibling
node.documentElement = ref
node.body = ref ? ref.querySelector("body") : null
}
}
return el
},
removeChild: function(el) {
var node = this
, index = node.childNodes.indexOf(el)
if (index == -1) throw Error("NOT_FOUND_ERR")
node.childNodes.splice(index, 1)
el.parentNode = null
return el
},
replaceChild: function(el, ref) {
this.insertBefore(el, ref)
return this.removeChild(ref)
},
cloneNode: function(deep) {
var key
, node = this
, clone = new node.constructor(node.tagName || node.data)
clone.ownerDocument = node.ownerDocument
if (node.hasAttribute) {
for (key in node) if (node.hasAttribute(key)) clone[key] = node[key].valueOf()
}
if (deep && node.hasChildNodes()) {
node.childNodes.forEach(function(child) {
clone.appendChild(child.cloneNode(deep))
})
}
return clone
},
toString: function(minify) {
return this.hasChildNodes() ? this.childNodes.reduce(function(memo, node) {
return memo + node.toString(minify)
}, "") : ""
}
}
, Element = {
get firstElementChild() {
return getElement(this.childNodes, 0, 1, 1)
},
get lastElementChild() {
return getElement(this.childNodes, this.childNodes.length - 1, -1, 1)
},
get nextElementSibling() {
return getSibling(this, 1, 1)
},
get previousElementSibling() {
return getSibling(this, -1, 1)
},
hasAttribute: function(name) {
name = escapeAttributeName(name)
return name != "style" ? hasOwn.call(this, name) :
!!(this.styleMap && Object.keys(this.styleMap).length)
},
getAttribute: function(name) {
name = escapeAttributeName(name)
return this.hasAttribute(name) ? "" + this[name] : null
},
setAttribute: function(name, value) {
this[escapeAttributeName(name)] = "" + value
},
removeAttribute: function(name) {
name = escapeAttributeName(name)
this[name] = ""
delete this[name]
},
getElementById: function(id) {
return selector.find(this, "#" + id, 1)
},
getElementsByTagName: function(tag) {
return selector.find(this, tag)
},
getElementsByClassName: function(sel) {
return selector.find(this, "." + sel.replace(/\s+/g, "."))
},
querySelector: function(sel) {
return selector.find(this, sel, 1)
},
querySelectorAll: function(sel) {
return selector.find(this, sel)
}
}
, quotRe = /[^-.:\w]/
, escRe = /<|&(?=[a-z#])/gi
, unescRe = /&\w+;|&#(x|)([\da-f]+);/ig
, unescMap = {
"&": "&", "'": "'", "¢": "¢", "©": "©", "¤": "¤",
"°": "°", "€": "€", ">": ">", "<": "<", " ": " ",
"±": "±", "£": "£", """: "\"", "®": "®",
"§": "§", "²": "²", "³": "³", "¥": "¥"
}
function escFn(chr) {
return chr === "<" ? "<" : "&"
}
function unescFn(ent, hex, num) {
return num ? String.fromCharCode(parseInt(num, hex === "" ? 10 : 16)) : unescMap[ent] || ent
}
;["hasAttribute", "getAttribute", "setAttribute", "removeAttribute"].forEach(function(name) {
Element[name + "NS"] = function(ns, a, b) {
return this[name].call(this, a, b)
}
})
function Attr(node, name) {
this.ownerElement = node
this.name = name.toLowerCase()
}
Attr.prototype = {
get value() { return this.ownerElement.getAttribute(this.name) },
set value(val) { this.ownerElement.setAttribute(this.name, val) },
toString: function(minify) {
if (hasOwn.call(boolAttrs, this.name)) return this.name
var value = this.value.replace(escRe, escFn)
if (minify) {
if (!quotRe.test(value)) return this.name + "=" + this.value
if (value.split("\"").length > value.split("'").length) return this.name + "='" + value.replace(/'/g, "'") + "'"
}
return this.name + "=\"" + value.replace(/"/g, """) + "\""
}
}
function StyleMap(style) {
var styleMap = this
if (style) style.split(/\b\s*;\s*/g).forEach(function(val) {
val = val.split(/\b\s*:\s*/)
if (val[1]) styleMap[val[0] == "float" ? "cssFloat" : camelCase(val[0])] = val[1]
})
}
StyleMap.prototype.valueOf = function() {
var styleMap = this
return Object.keys(styleMap).map(function(key) {
return (key == "cssFloat" ? "float: " : hyphenCase(key) + ": ") + styleMap[key]
}).join("; ")
}
function DocumentFragment() {
this.childNodes = []
}
extendNode(DocumentFragment, Element, {
nodeType: 11,
nodeName: "#document-fragment"
})
function HTMLElement(tag) {
var el = this
el.nodeName = el.tagName = tag.toUpperCase()
el.localName = tag.toLowerCase()
el.childNodes = []
}
extendNode(HTMLElement, Element, {
nodeType: 1,
get attributes() {
var key
, attrs = []
, el = this
for (key in el) if (key === escapeAttributeName(key) && el.hasAttribute(key))
attrs.push(new Attr(el, escapeAttributeName(key)))
return attrs
},
matches: function(sel) {
return selector.matches(this, sel)
},
closest: function(sel) {
return selector.closest(this, sel)
},
namespaceURI: "http://www.w3.org/1999/xhtml",
localName: null,
tagName: null,
styleMap: null,
focus: function() {
this.ownerDocument.activeElement = this
},
blur: function() {
this.ownerDocument.activeElement = null
},
toString: function(minify) {
var attrs = (minify ? this.attributes.map(minifyMap) : this.attributes).join(" ")
return "<" + this.localName + (attrs ? " " + attrs : "") + ">" +
(voidElements[this.tagName] ? "" : Node.toString.call(this, minify) + "</" + this.localName + ">")
}
})
function ElementNS(namespace, tag) {
var el = this
el.namespaceURI = namespace
el.nodeName = el.tagName = el.localName = tag
el.childNodes = []
}
ElementNS.prototype = HTMLElement.prototype
function Text(data) {
this.data = data
}
extendNode(Text, {
nodeType: 3,
nodeName: "#text",
toString: function(minify) {
return (minify ? ("" + this.data).trim() : "" + this.data).replace(escRe, escFn)
}
})
function Comment(data) {
this.data = data
}
extendNode(Comment, {
nodeType: 8,
nodeName: "#comment",
toString: function(minify) {
return minify ? "" : "<!--" + this.data + "-->"
}
})
function DocumentType(data) {
this.data = data
}
extendNode(DocumentType, {
nodeType: 10,
toString: function() {
return "<" + this.data + ">"
// var node = document.doctype
// return "<!DOCTYPE " + node.name +
// (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') +
// (!node.publicId && node.systemId ? ' SYSTEM' : '') +
// (node.systemId ? ' "' + node.systemId + '"' : '') + '>'
}
})
function Document() {
this.childNodes = []
this
.appendChild(this.createElement("html"))
.appendChild(this.body = this.createElement("body"))
}
extendNode(Document, Element, {
nodeType: 9,
nodeName: "#document",
contentType: "text/html",
createElement: own(HTMLElement),
createElementNS: own(ElementNS),
createTextNode: own(Text),
createComment: own(Comment),
createDocumentType: own(DocumentType), //Should be document.implementation.createDocumentType(name, publicId, systemId)
createDocumentFragment: own(DocumentFragment)
})
function DOMParser() {}
function XMLSerializer() {}
DOMParser.prototype.parseFromString = function(str, mime) {
var doc = new Document()
doc.contentType = mime
doc.documentElement.outerHTML = str
return doc
}
XMLSerializer.prototype.serializeToString = function(doc) {
return doc.toString()
}
function own(Class) {
return function($1, $2) {
var node = new Class($1, $2)
node.ownerDocument = this
return node
}
}
function extendNode(obj, extras) {
obj.prototype = Object.create(Node)
for (var descriptor, key, i = 1; (extras = arguments[i++]); ) {
for (key in extras) {
descriptor = Object.getOwnPropertyDescriptor(extras, key)
Object.defineProperty(obj.prototype, key, descriptor)
}
}
obj.prototype.constructor = obj
}
function getElement(childs, index, step, type) {
if (childs && index > -1) for (; childs[index]; index += step) {
if (childs[index].nodeType === type) return childs[index]
}
return null
}
function getSibling(node, step, type) {
var silbings = node.parentNode && node.parentNode.childNodes
, index = silbings ? silbings.indexOf(node) : -1
return type > 0 ? getElement(silbings, index + step, step, type) : silbings[index + step] || null
}
function escapeAttributeName(name) {
name = name.toLowerCase()
if (name === "constructor" || name === "attributes") return name.toUpperCase()
return name
}
function camelCase(str) {
return str.replace(/-([a-z])/g, function(_, a) { return a.toUpperCase() })
}
function hyphenCase(str) {
return str.replace(/[A-Z]/g, "-$&").toLowerCase()
}
function minifyMap(item) {
return item.toString(true)
}
module.exports = {
document: new Document(),
DOMParser: DOMParser,
XMLSerializer: XMLSerializer,
StyleMap: StyleMap,
Node: Node,
HTMLElement: HTMLElement,
DocumentFragment: DocumentFragment,
Document: Document
}