-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom-inspector.js
485 lines (462 loc) · 15 KB
/
dom-inspector.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
485
class VDOM {
/**
* @constructor
* @param {Object} rootNode - A tree exported through Observer.tree().
* @param {Object} options - Configuration options:
* - mutationCallback(update, target): optional. A callback to be called whenever the vDOM is updated.
* - validateView(node): optional. A function which can modify the node's Node
* object accessible through its `view` property.
* @return {VDOM} The created DOMInspector.VDOM object.
*/
constructor(rootNode, options = {}) {
this.rootNode = rootNode;
this.mutationCallback = options.mutationCallback;
this.validateView = options.validateView;
this.selfClosingTags = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
}
/**
* Get the path for the given node.
* An exception is thrown if the node does not belong to the vDOM.
* @param {Object} node - A node in the vDOM.
* @return {String} The path to the node.
*/
pathForNode(node) {
var id, index;
if (node === this.rootNode) {
return '';
// } else if (node.id) {
// return `#${node.id}`;
// } else if (node.nodeName === 'head' || node.nodeName === 'body') {
// return node.nodeName;
} else if (node.parentNode && (index = node.parentNode.childNodes.indexOf(node)) !== -1) {
return `${this.pathForNode(node.parentNode)}/${index}`;
}
throw 'Invalid node';
}
/**
* Get the node at the given path.
* An exception is thrown if the path is invalid.
* @param {String} path - A path to a node in the vDOM.
* @return {Object} The node at the given path.
*/
nodeAtPath(path, parent) {
if (typeof(path) === 'string') {
path = path.split('/');
}
if (path.length > 0) {
var index = path[0], child;
if (index === '') {
child = this.rootNode;
// } else if (index === 'head') {
// child = this.head;
// } else if (index === 'body') {
// child = this.body;
} else if (parent.childNodes && index < parent.childNodes.length) {
child = parent.childNodes[index];
} else {
throw 'Invalid path';
}
path.splice(0, 1);
return this.nodeAtPath(path, child);
}
return parent;
}
/**
* Update the vDOM with the given array of updates.
* @param {Array} updates - An array of updates generated by Observer.
*/
ingestUpdates(updates) {
for (var update of updates) {
var target = this.nodeAtPath(update.target);
if (update.attribute) {
var {name, value} = update.attribute;
var index = target.attributes.map((attr) => attr.name).indexOf(name);
if (value) {
if (index === -1) {
target.attributes.push({name, value});
} else {
target.attributes[index].value = value;
}
} else {
target.attributes.splice(index, 1);
}
// update the view
if (target.view) {
var attributes = target.view.getElementsByClassName('attributes')[0];
attributes.parentNode.replaceChild(this._viewAttributes(target), attributes);
}
}
if (update.removedNodes) {
var {index, length} = update.removedNodes;
for (var i = 0; i < length; i += 1) {
delete target.childNodes[index + i].parentNode;
}
target.childNodes.splice(index, length);
// update the view
if (target.view) {
var children = target.view.getElementsByClassName('children')[0];
for (var i = 0; i < length; i += 1) {
children.removeChild(children.childNodes[index]);
}
}
}
if (update.addedNodes) {
if (!target.childNodes) {
target.childNodes = [];
}
var {index, nodes} = update.addedNodes;
target.childNodes.splice(index, 0, ...nodes);
for (var node of nodes) {
node.parentNode = target;
}
// update the view
if (target.view) {
var children = target.view.getElementsByClassName('children')[0];
if (children) {
for (var node of nodes.slice().reverse()) {
children.insertBefore(this.view(node), children.childNodes[index]);
}
} else {
target.view.appendChild(this._viewChildNodes(target));
}
}
}
if (this.mutationCallback) {
this.mutationCallback(update, target);
}
}
}
_viewIndent(node, level) {
for (var i = 0; i < level; i += 1) {
var indent = document.createElement('span');
indent.classList.add('indent');
node.insertBefore(indent, node.firstChild);
}
}
_viewAttributes(node) {
var attributes = document.createElement('span');
attributes.classList.add('attributes');
attributes.innerHTML = ' ' + node.attributes.map((attr) => `<span class="name">${attr.name}</span>` + (attr.value ? `="<span class="value">${attr.value}</span>"` : '')).join(' ');
return attributes;
}
_viewOpenTag(node) {
var openTag = document.createElement('a');
openTag.classList.add('opentag');
openTag.innerHTML = `<<span class="name">${node.nodeName}</span>>`;
if (node.attributes) {
openTag.getElementsByClassName('name')[0].appendChild(this._viewAttributes(node));
}
if (node.nodeValue) {
var value = document.createElement('span');
value.classList.add('value');
value.innerHTML = node.nodeValue;
openTag.appendChild(nodeValue);
}
this._viewIndent(openTag, node.level);
if (node.childNodes) {
var placeholder = document.createElement('span');
placeholder.classList.add('placeholder');
placeholder.innerHTML = `...</${node.nodeName}>`;
openTag.append(placeholder);
} else if (!this.selfClosingTags.has(node.nodeName)) {
openTag.appendChild(document.createTextNode(`</${node.nodeName}>`));
}
return openTag;
}
_viewChildNodes(node) {
var children = document.createElement('div');
children.classList.add('children');
for (var child of node.childNodes) {
children.appendChild(this.view(child));
}
var closeTag = document.createElement('a');
closeTag.classList.add('closetag');
closeTag.innerHTML = `</${node.nodeName}>`;
this._viewIndent(closeTag, node.level);
children.appendChild(closeTag);
return children;
}
_viewText(node) {
var text = document.createElement('a');
text.classList.add('text');
var temp = document.createElement('textarea');
temp.textContent = node.nodeValue;
text.innerHTML = temp.innerHTML;
this._viewIndent(text, node.level);
return text;
}
/**
* Generate a view visualizing the given node (or the root node if no node is specified).
* The hierarchy looks like this:
* - text node: `<a class="node text">nodeValue</a>`
* - element node:
* `<div class="node">
* <a class="opentag">
* <span class="name">nodeName</span>
* <span class="attributes">
* <span class="name">attributeName</span>
* <span class="value">attributeValue</span>
* </span>
* <span class="value">nodeValue</span>
* <span class="placeholder">... nodeName</span>
* </a>
* <div class="children">
* {sequence of nodes}
* <a class="closetag">nodeName</a>
* </div>
* </div>`
* When the vDOM is updated, the nodes are updated as well.
* @param {Object} node - A node in the vDOM. The default value is the root node.
* @return {Node} A DOM node visualizing the vDOM as an outline view.
*/
view(node) {
if (!node) {
node = this.rootNode;
this.nodeMap = {};
this.nextNodeId = 1;
}
var view;
if (node.nodeName === '#text') {
view = this._viewText(node);
} else {
view = document.createElement('div');
view.appendChild(this._viewOpenTag(node));
if (node.childNodes) {
view.appendChild(this._viewChildNodes(node));
}
}
view.classList.add('node');
view.dataset.nodeId = this.nextNodeId;
this.nodeMap[this.nextNodeId] = node;
this.nextNodeId += 1;
node.view = view;
if (this.validateView) {
this.validateView(node);
}
return view;
}
/**
* Returns the node object associated with the given DOM Node, previously generated
* by the `view()` method.
* @return {Object} The node object associated with the given DOM Node.
*/
nodeForView(view) {
while (!view.classList || !view.classList.contains('node')) {
if (view.parentNode) {
view = view.parentNode;
} else {
throw 'Invalid view.';
}
}
return this.nodeMap[view.dataset.nodeId];
}
}
class Observer {
/**
* @constructor
* @param {Document} document - A HTML document whose contents are to be observed.
* @param {Object} options - Configuration options:
* - highlightClass: string. A class name to be added to highlighted elements.
* @return {Observer} The created DOMInspector.Observer object.
*/
constructor(document, options = {}) {
this.document = document;
this.highlightClass = options.highlightClass;
}
/**
* Get the path for the given node.
* An exception is thrown if the node does not belong to the document.
* @param {Object} node - A node in the document.
* @return {String} The path to the node.
*/
pathForNode(node) {
var id, index;
if (node === this.document.documentElement) {
return '';
// } else if (node.id) {
// return `#${id}`;
// } else if (node === this.document.head || node === this.document.body) {
// return node.nodeName.toLowerCase();
} else if (node.parentNode && (index = Array.from(node.parentNode.childNodes).indexOf(node)) !== -1) {
return `${this.pathForNode(node.parentNode)}/${index}`;
}
throw 'Invalid node';
}
/**
* Get the node at the given path.
* An exception is thrown if the path is invalid.
* @param {String} path - A path to a node in the document.
* @return {Node} The node at the given path.
*/
nodeAtPath(path, parent) {
if (typeof(path) === 'string') {
path = path.split('/');
}
if (path.length > 0) {
var index = path[0], child;
if (index === '') {
child = this.document.documentElement;
// } else if (index === 'head') {
// child = this.document.head;
// } else if (index === 'body') {
// child = this.document.body;
} else if (index < parent.childNodes.length) {
child = parent.childNodes[index];
} else {
throw 'Invalid path';
}
path.splice(0, 1);
return this.nodeAtPath(path, child);
}
return parent;
}
/**
* Generate a JSON object from the given node or the root node if no node is specified.
* @param {Node} node - A node in the document. The default value is the root node.
* @return {Object} The tree corresponding to the document, as a JSON object.
*/
tree(node, level = 0) {
node = node || this.document.documentElement;
var tree = {nodeName: node.nodeName.toLowerCase(), level};
if (node.id) {
tree.id = node.id;
}
if (node.nodeValue) {
tree.nodeValue = node.nodeValue;
}
if (node.attributes && node.attributes.length > 0) {
tree.attributes = [];
for (var attribute of Array.from(node.attributes)) {
var name = attribute.nodeName, value = attribute.nodeValue;
// remove the custom highlight class
if (name === 'class') {
value = value.replace(this.highlightClass, '').trim();
if (value.length === 0) {
continue;
}
}
tree.attributes.push({name, value});
}
}
if (node.childNodes && node.childNodes.length > 0) {
tree.childNodes = Array.from(node.childNodes).map((child) => this.tree(child, level + 1));
tree.childNodes.forEach((child) => child.parentNode = tree);
}
return tree;
}
/**
* Initialize the mutation observer for the document.
* To actually begin observing, call `Observer.startMutationObserver()`.
* @param {Function} mutationCallback - An optional callback to be called whenever the document changes.
*/
initMutationObserver(mutationCallback) {
this.mutationCallback = mutationCallback;
this.mutationObserver = new MutationObserver((mutations) => {
// oldParents and oldChildren keep track of the modified targets
var oldParents = [], oldChildren = [];
// make a copy of all the modified targets' childNodes
for (var mutation of mutations) {
var target = mutation.target;
if (oldParents.indexOf(target) === -1) {
oldParents.push(target);
oldChildren.push(Array.from(target.childNodes));
}
}
var updates = [];
// enumerate all mutations in reverse order to go back in time
for (var mutation of mutations.slice().reverse()) {
// find the first modified ancestor
var target = mutation.target, ancestor = target, pathSuffix = [], found;
do {
found = false;
for (var i in oldChildren) {
var index = oldChildren[i].indexOf(ancestor);
if (index !== -1) {
pathSuffix.push(index);
ancestor = oldParents[i];
found = true;
}
}
} while (found);
var level = pathSuffix.length;
pathSuffix = pathSuffix.reverse().join('/');
var update = {target: this.pathForNode(ancestor) + (pathSuffix ? `/${pathSuffix}` : '')};
while ((ancestor = ancestor.parentNode)) {
level += 1;
}
// attribute change
if (mutation.attributeName) {
update.attribute = {name: mutation.attributeName};
var attribute = target.attributes.getNamedItem(mutation.attributeName);
if (attribute) {
update.attribute.value = attribute.value;
}
}
// remove added children
var children = oldChildren[oldParents.indexOf(target)];
if (mutation.addedNodes.length > 0) {
// the index of the first added node, the other ones are consecutive
var index = children.indexOf(mutation.addedNodes[0]);
children.splice(index, mutation.addedNodes.length);
update.addedNodes = {index, nodes: Array.from(mutation.addedNodes).map((node) => this.tree(node, level))};
}
// add removed children back
if (mutation.removedNodes.length > 0) {
// the index of the first removed node, the other ones are consecutive
var index = (mutation.nextSibling ? children.indexOf(mutation.nextSibling) : mutation.previousSibling ? children.indexOf(mutation.previousSibling) + 1 : 0);
children.splice(index, 0, ...mutation.removedNodes);
update.removedNodes = {index, length: mutation.removedNodes.length};
}
updates.push(update);
}
updates.reverse();
if (this.mutationCallback) {
this.mutationCallback(updates);
}
});
}
/**
* Start observing the document for mutations.
*/
startMutationObserver() {
this.mutationObserver.observe(this.document, {attributes: true, childList: true, subtree: true});
}
/**
* Stop observing the document for mutations.
*/
stopMutationObserver() {
this.mutationObserver.disconnect();
}
/**
* Highlight the given element in the document.
* @param {Node|String} element - The element, or the path to the element, to be highlighted.
*/
highlightElement(element) {
if (typeof(element) === 'string') {
try {
element = this.nodeAtPath(element);
} catch (e) {
console.error(e.message);
return;
}
}
// stop the mutation observer in order to avoid triggering a mutation
if (this.mutationObserver) {
this.stopMutationObserver();
}
// unhighlight the previous element
if (this.highlightedElement) {
this.highlightedElement.classList.remove(this.highlightClass);
}
// highlight the given element
if (element && element.classList) {
element.classList.add(this.highlightClass);
this.highlightedElement = element;
}
// restart the mutation observer
if (this.mutationObserver) {
this.startMutationObserver();
}
}
}
module.exports = {VDOM, Observer};