-
Notifications
You must be signed in to change notification settings - Fork 0
/
softdom.js
327 lines (304 loc) · 9.37 KB
/
softdom.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
// Adapted from UnDOM (minimal DOM) and Domino (spec compliant DOM)
// They're amazing projects
const NODE_TYPES = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12,
};
const voidElements = new Set([
'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'embed', 'frame', 'hr',
'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr',
]);
function toLower(str) {
return String(str).toLowerCase();
}
function splice(arr, item, add, byValue) {
let i = arr ? findWhere(arr, item, true, byValue) : -1;
if (~i) add ? arr.splice(i, 0, add) : arr.splice(i, 1);
return i;
}
function findWhere(arr, fn, returnIndex, byValue) {
let i = arr.length;
while (i--) if (byValue ? arr[i] === fn : fn(arr[i])) break;
return returnIndex ? i : arr[i];
}
function createAttributeFilter(ns, name) {
return o => o.ns === ns && toLower(o.name) === toLower(name);
}
function serialize(el) {
if (!el)
return '';
switch (el.nodeType) {
case NODE_TYPES.TEXT_NODE: {
return encodeTextSafe(el.textContent);
}
case NODE_TYPES.ELEMENT_NODE: {
const tag = el.nodeName.toLowerCase();
const attrs = el.attributes.map(encodeAttribute).join('');
return voidElements.has(tag)
? `<${tag}${attrs}/>`
: `<${tag}${attrs}>${el.childNodes.map(serialize).join('')}</${tag}>`;
}
case NODE_TYPES.DOCUMENT_FRAGMENT_NODE: {
// As easy as pretending fragments don't exist at all
return el.childNodes.map(serialize).join('');
}
// Not going to support NODE_TYPES.DOCUMENT_NODE for <!DOCTYPE...> etc.
default: {
console.log(el);
throw new Error(`No serializer for NODE_TYPES "${el.nodeType}"`);
}
}
}
const escapeMap = {
'&': '&', '<': '<', '>': '>', '\'': ''', '"': '"',
};
const encodeAttribute = a => ` ${a.name}="${encodeTextSafe(a.value)}"`;
const encodeTextSafe = s => s.replace(/[&<>'"]/g, m => escapeMap[m]);
// To throw errors on property read/write the object is sealed. However, this
// needs to happen at the top of the super() chain.
let preventInstanceObjectSeal = false;
class Node {
constructor(nodeType, nodeName) {
this.nodeType = nodeType;
this.nodeName = nodeName;
this.childNodes = [];
this.parentNode = null;
Object.assign(this, classProperties.Node);
if (!preventInstanceObjectSeal) Object.seal(this);
}
get nextSibling() {
let p = this.parentNode;
if (p) return p.childNodes[findWhere(p.childNodes, this, true, true) + 1];
return null;
}
get previousSibling() {
let p = this.parentNode;
if (p) return p.childNodes[findWhere(p.childNodes, this, true, true) - 1];
return null;
}
get firstChild() {
return this.childNodes[0];
}
get lastChild() {
return this.childNodes[this.childNodes.length - 1];
}
get parentElement() {
return this.parentNode;
}
get isConnected() {
let p = this.parentNode;
while (p) { if (p.nodeName === 'BODY') return true; p = p.parentNode; }
return this.nodeName === 'BODY';
}
hasChildNodes() {
return this.childNodes.length > 0;
}
appendChild(child) {
this.insertBefore(child);
return child;
}
insertBefore(child, ref) {
child.remove();
child.parentNode = this;
if (ref) splice(this.childNodes, ref, child, true);
else this.childNodes.push(child);
return child;
}
replaceChild(child, ref) {
if (ref.parentNode === this) {
this.insertBefore(child, ref);
ref.remove();
return ref;
}
}
removeChild(child) {
splice(this.childNodes, child, false, true);
return child;
}
remove() {
if (this.parentNode) this.parentNode.removeChild(this);
}
}
class Text extends Node {
constructor(text) {
const prev = preventInstanceObjectSeal;
preventInstanceObjectSeal = true;
super(NODE_TYPES.TEXT_NODE, '#text');
preventInstanceObjectSeal = prev;
this.nodeValue = text;
Object.assign(this, classProperties.Text);
if (!preventInstanceObjectSeal) Object.seal(this);
}
set textContent(text) { this.nodeValue = text; }
get textContent() { return this.nodeValue; }
// From abstract CharacterData type but is used by Sinuous for api.insert()
set data(text) { this.nodeValue = text; }
get data() { return this.nodeValue; }
}
class Element extends Node {
constructor(nodeType, nodeName) {
const prev = preventInstanceObjectSeal;
preventInstanceObjectSeal = true;
super(nodeType || NODE_TYPES.ELEMENT_NODE, nodeName);
preventInstanceObjectSeal = prev;
this.attributes = [];
this.__handlers = {};
this.namespace = null;
Object.assign(this, classProperties.Element);
initializeAttributes(this, nodeName);
if (!preventInstanceObjectSeal) Object.seal(this);
}
get tagName() { return this.nodeName; }
get id() { return this.getAttribute('id'); }
set id(val) { this.setAttribute('id', val); }
get className() { return this.getAttribute('class'); }
set className(val) { this.setAttribute('class', val); }
get cssText() { return this.getAttribute('style'); }
set cssText(val) { this.setAttribute('style', val); }
get children() {
return this.childNodes.filter(node =>
node.nodeType === NODE_TYPES.ELEMENT_NODE);
}
setAttribute(key, value) {
this.setAttributeNS(null, key, value);
}
getAttribute(key) {
return this.getAttributeNS(null, key);
}
removeAttribute(key) {
this.removeAttributeNS(null, key);
}
setAttributeNS(ns, name, value) {
let attr = findWhere(this.attributes, createAttributeFilter(ns, name), false, false);
if (!attr) this.attributes.push(attr = { ns, name });
attr.value = String(value);
}
getAttributeNS(ns, name) {
let attr = findWhere(this.attributes, createAttributeFilter(ns, name), false, false);
return attr && attr.value;
}
removeAttributeNS(ns, name) {
splice(this.attributes, createAttributeFilter(ns, name), false, false);
}
addEventListener(type, handler) {
(this.__handlers[toLower(type)] || (this.__handlers[toLower(type)] = [])).push(handler);
}
removeEventListener(type, handler) {
splice(this.__handlers[toLower(type)], handler, false, true);
}
dispatchEvent(event) {
let t = event.target = this,
c = event.cancelable,
l, i;
do {
event.currentTarget = t;
l = t.__handlers && t.__handlers[toLower(event.type)];
if (l) for (i = l.length; i--;) {
if ((l[i].call(t, event) === false || event._end) && c) {
event.defaultPrevented = true;
}
}
} while (event.bubbles && !(c && event._stop) && (t = t.parentNode));
return Boolean(l);
}
get outerHTML() {
return serialize(this);
}
get innerHTML() {
return this.childNodes.map(serialize).join('');
}
}
class DocumentFragment extends Node {
constructor() {
const prev = preventInstanceObjectSeal;
preventInstanceObjectSeal = true;
super(NODE_TYPES.DOCUMENT_FRAGMENT_NODE, '#document-fragment');
preventInstanceObjectSeal = prev;
if (!preventInstanceObjectSeal) Object.seal(this);
}
}
class Document extends Element {
constructor() {
const prev = preventInstanceObjectSeal;
preventInstanceObjectSeal = true;
super(NODE_TYPES.DOCUMENT_NODE, '#document');
preventInstanceObjectSeal = prev;
this.defaultView = null;
this.documentElement = null;
this.head = null;
this.body = null;
Object.assign(this, classProperties.Document);
if (!preventInstanceObjectSeal) Object.seal(this);
}
createElement(type) {
return new Element(null, String(type).toUpperCase());
}
createElementNS(ns, type) {
let element = this.createElement(type);
element.namespace = ns;
return element;
}
createTextNode(text) {
return new Text(text);
}
createDocumentFragment() {
return new DocumentFragment();
}
}
class Event {
constructor(type, opts) {
this.type = type;
this.bubbles = Boolean(opts && opts.bubbles);
this.cancelable = Boolean(opts && opts.cancelable);
Object.assign(this, classProperties.Event);
if (!preventInstanceObjectSeal) Object.seal(this);
}
stopPropagation() {
this._stop = true;
}
stopImmediatePropagation() {
this._end = this._stop = true;
}
preventDefault() {
this.defaultPrevented = true;
}
}
// Note that these attributes don't exist on Element and there's no further
// distinctions such as HTMLAnchorElement, so tack on accessors generically:
// https://github.com/fgnass/domino/blob/master/lib/htmlelts.js
const elementAttributes = {
a: ['href'],
img: ['src'],
label: ['htmlFor'],
input: ['type', 'value', 'placeholder'],
button: ['type', 'value'],
};
function initializeAttributes(instance, nodeName) {
const attributes = elementAttributes[nodeName.toLowerCase()] ?? [];
for (const attr of attributes) {
Object.defineProperty(instance, attr, {
get: function() { return instance.getAttribute(attr); },
set: function(val) { instance.setAttribute(attr, val); },
});
}
}
// Allow people to add properties to classes before their instance is sealed
const classProperties = {
Node: {},
Text: {},
Element: {},
DocumentFragment: {},
Document: {},
Event: {},
}
export { Node, Text, Element, DocumentFragment, Document, Event };
export { classProperties, elementAttributes, preventInstanceObjectSeal }