forked from Polymer/dom5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom5.ts
591 lines (538 loc) · 14.6 KB
/
dom5.ts
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/**
* @license
* Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
/// <reference path="./custom_typings/main.d.ts" />
import * as cloneObject from 'clone';
import * as parse5 from 'parse5';
import {ASTNode as Node} from 'parse5';
export {ASTNode as Node} from 'parse5';
function getAttributeIndex(element: Node, name: string): number {
if (!element.attrs) {
return -1;
}
let n = name.toLowerCase();
for (let i = 0; i < element.attrs.length; i++) {
if (element.attrs[i].name.toLowerCase() === n) {
return i;
}
}
return -1;
}
/**
* @returns `true` iff [element] has the attribute [name], `false` otherwise.
*/
export function hasAttribute(element: Node, name: string): boolean {
return getAttributeIndex(element, name) !== -1;
}
/**
* @returns The string value of attribute `name`, or `null`.
*/
export function getAttribute(element: Node, name: string): string|null {
const i = getAttributeIndex(element, name);
if (i > -1) {
return element.attrs[i].value;
}
return null;
}
export function setAttribute(element: Node, name: string, value: string) {
const i = getAttributeIndex(element, name);
if (i > -1) {
element.attrs[i].value = value;
} else {
element.attrs.push({name: name, value: value});
}
}
export function removeAttribute(element: Node, name: string) {
const i = getAttributeIndex(element, name);
if (i > -1) {
element.attrs.splice(i, 1);
}
}
function hasTagName(name: string): Predicate {
const n = name.toLowerCase();
return function(node) {
if (!node.tagName) {
return false;
}
return node.tagName.toLowerCase() === n;
};
}
/**
* Returns true if `regex.match(tagName)` finds a match.
*
* This will use the lowercased tagName for comparison.
*/
function hasMatchingTagName(regex: RegExp): Predicate {
return function(node) {
if (!node.tagName) {
return false;
}
return regex.test(node.tagName.toLowerCase());
};
}
function hasClass(name: string): Predicate {
return function(node) {
const attr = getAttribute(node, 'class');
if (!attr) {
return false;
}
return attr.split(' ').indexOf(name) > -1;
};
}
function collapseTextRange(parent: Node, start: number, end: number) {
if (!parent.childNodes) {
return;
}
let text = '';
for (let i = start; i <= end; i++) {
text += getTextContent(parent.childNodes[i]);
}
parent.childNodes.splice(start, (end - start) + 1);
if (text) {
const tn = newTextNode(text);
tn.parentNode = parent;
parent.childNodes.splice(start, 0, tn);
}
}
/**
* Normalize the text inside an element
*
* Equivalent to `element.normalize()` in the browser
* See https://developer.mozilla.org/en-US/docs/Web/API/Node/normalize
*/
export function normalize(node: Node) {
if (!(isElement(node) || isDocument(node) || isDocumentFragment(node))) {
return;
}
if (!node.childNodes) {
return;
}
let textRangeStart = -1;
for (let i = node.childNodes.length - 1, n: Node; i >= 0; i--) {
n = node.childNodes[i];
if (isTextNode(n)) {
if (textRangeStart === -1) {
textRangeStart = i;
}
if (i === 0) {
// collapse leading text nodes
collapseTextRange(node, 0, textRangeStart);
}
} else {
// recurse
normalize(n);
// collapse the range after this node
if (textRangeStart > -1) {
collapseTextRange(node, i + 1, textRangeStart);
textRangeStart = -1;
}
}
}
}
/**
* Return the text value of a node or element
*
* Equivalent to `node.textContent` in the browser
*/
export function getTextContent(node: Node): string {
if (isCommentNode(node)) {
return node.data;
}
if (isTextNode(node)) {
return node.value || '';
}
const subtree = nodeWalkAll(node, isTextNode);
return subtree.map(getTextContent).join('');
}
/**
* Set the text value of a node or element
*
* Equivalent to `node.textContent = value` in the browser
*/
export function setTextContent(node: Node, value: string) {
if (isCommentNode(node)) {
node.data = value;
} else if (isTextNode(node)) {
node.value = value;
} else {
const tn = newTextNode(value);
tn.parentNode = node;
node.childNodes = [tn];
}
}
/**
* Match the text inside an element, textnode, or comment
*
* Note: nodeWalkAll with hasTextValue may return an textnode and its parent if
* the textnode is the only child in that parent.
*/
function hasTextValue(value: string): Predicate {
return function(node) {
return getTextContent(node) === value;
};
}
export type Predicate = (node: Node) => boolean;
/**
* OR an array of predicates
*/
function OR(...predicates: Predicate[]): Predicate;
function OR(/* ...rules */): Predicate {
const rules = new Array<Predicate>(arguments.length);
for (let i = 0; i < arguments.length; i++) {
rules[i] = arguments[i];
}
return function(node) {
for (let i = 0; i < rules.length; i++) {
if (rules[i](node)) {
return true;
}
}
return false;
};
}
/**
* AND an array of predicates
*/
function AND(...predicates: Predicate[]): Predicate;
function AND(/* ...rules */): Predicate {
const rules = new Array<Predicate>(arguments.length);
for (let i = 0; i < arguments.length; i++) {
rules[i] = arguments[i];
}
return function(node) {
for (let i = 0; i < rules.length; i++) {
if (!rules[i](node)) {
return false;
}
}
return true;
};
}
/**
* negate an individual predicate, or a group with AND or OR
*/
function NOT(predicateFn: Predicate): Predicate {
return function(node) {
return !predicateFn(node);
};
}
/**
* Returns a predicate that matches any node with a parent matching
* `predicateFn`.
*/
function parentMatches(predicateFn: Predicate): Predicate {
return function(node) {
let parent = node.parentNode;
while (parent !== undefined) {
if (predicateFn(parent)) {
return true;
}
parent = parent.parentNode;
}
return false;
};
}
function hasAttr(attr: string): Predicate {
return function(node) {
return getAttributeIndex(node, attr) > -1;
};
}
function hasAttrValue(attr: string, value: string): Predicate {
return function(node) {
return getAttribute(node, attr) === value;
};
}
export function isDocument(node: Node): boolean {
return node.nodeName === '#document';
}
export function isDocumentFragment(node: Node): boolean {
return node.nodeName === '#document-fragment';
}
export function isElement(node: Node): boolean {
return node.nodeName === node.tagName;
}
export function isTextNode(node: Node): boolean {
return node.nodeName === '#text';
}
export function isCommentNode(node: Node): node is parse5.CommentNode {
return node.nodeName === '#comment';
}
/**
* Applies `mapfn` to `node` and the tree below `node`, returning a flattened
* list of results.
*/
export function treeMap<U>(node: Node, mapfn: (node: Node) => U[]): U[] {
let results: U[] = [];
nodeWalk(node, function(node) {
results = results.concat(mapfn(node));
return false;
});
return results;
}
/**
* Walk the tree down from `node`, applying the `predicate` function.
* Return the first node that matches the given predicate.
*
* @returns `null` if no node matches, parse5 node object if a node matches.
*/
export function nodeWalk(node: Node, predicate: Predicate): Node|null {
if (predicate(node)) {
return node;
}
let match: Node|null = null;
if (node.childNodes) {
for (let i = 0; i < node.childNodes.length; i++) {
match = nodeWalk(node.childNodes[i], predicate);
if (match) {
break;
}
}
}
return match;
}
/**
* Walk the tree down from `node`, applying the `predicate` function.
* All nodes matching the predicate function from `node` to leaves will be
* returned.
*/
export function nodeWalkAll(
node: Node, predicate: Predicate, matches?: Node[]): Node[] {
if (!matches) {
matches = [];
}
if (predicate(node)) {
matches.push(node);
}
if (node.childNodes) {
for (let i = 0; i < node.childNodes.length; i++) {
nodeWalkAll(node.childNodes[i], predicate, matches);
}
}
return matches;
}
function _reverseNodeWalkAll(
node: Node, predicate: Predicate, matches: Node[]): Node[] {
if (!matches) {
matches = [];
}
if (node.childNodes) {
for (let i = node.childNodes.length - 1; i >= 0; i--) {
nodeWalkAll(node.childNodes[i], predicate, matches);
}
}
if (predicate(node)) {
matches.push(node);
}
return matches;
}
/**
* Equivalent to `nodeWalk`, but only returns nodes that are either
* ancestors or earlier cousins/siblings in the document.
*
* Nodes are searched in reverse document order, starting from the sibling
* prior to `node`.
*/
export function nodeWalkPrior(node: Node, predicate: Predicate): Node|
undefined {
// Search our earlier siblings and their descendents.
const parent = node.parentNode;
if (parent) {
const idx = parent.childNodes!.indexOf(node);
const siblings = parent.childNodes!.slice(0, idx);
for (let i = siblings.length - 1; i >= 0; i--) {
const sibling = siblings[i];
if (predicate(sibling)) {
return sibling;
}
const found = nodeWalk(sibling, predicate);
if (found) {
return found;
}
}
if (predicate(parent)) {
return parent;
}
return nodeWalkPrior(parent, predicate);
}
return undefined;
}
/**
* Equivalent to `nodeWalkAll`, but only returns nodes that are either
* ancestors or earlier cousins/siblings in the document.
*
* Nodes are returned in reverse document order, starting from `node`.
*/
export function nodeWalkAllPrior(
node: Node, predicate: Predicate, matches?: Node[]): Node[] {
if (!matches) {
matches = [];
}
if (predicate(node)) {
matches.push(node);
}
// Search our earlier siblings and their descendents.
const parent = node.parentNode;
if (parent) {
const idx = parent.childNodes!.indexOf(node);
const siblings = parent.childNodes!.slice(0, idx);
for (let i = siblings.length - 1; i >= 0; i--) {
_reverseNodeWalkAll(siblings[i], predicate, matches);
}
nodeWalkAllPrior(parent, predicate, matches);
}
return matches;
}
/**
* Equivalent to `nodeWalk`, but only matches elements
*/
export function query(node: Node, predicate: Predicate): Node|null {
const elementPredicate = AND(isElement, predicate);
return nodeWalk(node, elementPredicate);
}
/**
* Equivalent to `nodeWalkAll`, but only matches elements
*/
export function queryAll(
node: Node, predicate: Predicate, matches: Node[]): Node[] {
const elementPredicate = AND(isElement, predicate);
return nodeWalkAll(node, elementPredicate, matches);
}
function newTextNode(value: string): Node {
return {
nodeName: '#text',
value: value,
parentNode: undefined,
attrs: [],
__location: <any>undefined,
};
}
function newCommentNode(comment: string): parse5.CommentNode {
return {
nodeName: '#comment',
data: comment,
parentNode: undefined,
attrs: [],
__location: <any>undefined
};
}
function newElement(tagName: string, namespace: string): Node {
return {
nodeName: tagName,
tagName: tagName,
childNodes: [],
namespaceURI: namespace || 'http://www.w3.org/1999/xhtml',
attrs: [],
parentNode: undefined,
__location: <any>undefined
};
}
function newDocumentFragment() {
return {
nodeName: '#document-fragment',
childNodes: [],
parentNode: null,
quirksMode: false,
};
}
export function cloneNode(node: Node): Node {
// parent is a backreference, and we don't want to clone the whole tree, so
// make it null before cloning.
const parent = node.parentNode;
node.parentNode = undefined;
const clone = cloneObject(node);
node.parentNode = parent;
return clone;
}
/**
* Inserts `newNode` into `parent` at `index`, optionally replaceing the
* current node at `index`. If `newNode` is a DocumentFragment, its childNodes
* are inserted and removed from the fragment.
*/
function insertNode(
parent: Node, index: number, newNode: Node, replace?: boolean) {
if (!parent.childNodes) {
throw new Error(`Parent node has no childNodes, can't insert.`);
}
let newNodes: Node[] = [];
let removedNode = replace ? parent.childNodes[index] : null;
if (newNode) {
if (isDocumentFragment(newNode)) {
newNodes = newNode.childNodes || [];
newNode.childNodes = [];
} else {
newNodes = [newNode];
remove(newNode);
}
}
if (replace) {
removedNode = parent.childNodes[index];
}
Array.prototype.splice.apply(
parent.childNodes, (<any>[index, replace ? 1 : 0]).concat(newNodes));
newNodes.forEach(function(n) {
n.parentNode = parent;
});
if (removedNode) {
removedNode.parentNode = undefined;
}
}
export function replace(oldNode: Node, newNode: Node) {
const parent = oldNode.parentNode;
const index = parent!.childNodes!.indexOf(oldNode);
insertNode(parent!, index, newNode, true);
}
export function remove(node: Node) {
const parent = node.parentNode;
if (parent && parent.childNodes) {
const idx = parent.childNodes.indexOf(node);
parent.childNodes.splice(idx, 1);
}
node.parentNode = undefined;
}
export function insertBefore(parent: Node, oldNode: Node, newNode: Node) {
const index = parent.childNodes!.indexOf(oldNode);
insertNode(parent, index, newNode);
}
export function append(parent: Node, newNode: Node) {
insertNode(parent, parent.childNodes!.length, newNode);
}
export function parse(text: string, options: parse5.ParserOptions) {
const parser = new parse5.Parser(parse5.TreeAdapters.default, options);
return parser.parse(text);
}
export function parseFragment(text: string) {
const parser = new parse5.Parser();
return parser.parseFragment(text);
}
export function serialize(ast: Node) {
const serializer = new parse5.Serializer();
return serializer.serialize(ast);
}
export const predicates = {
hasClass: hasClass,
hasAttr: hasAttr,
hasAttrValue: hasAttrValue,
hasMatchingTagName: hasMatchingTagName,
hasTagName: hasTagName,
hasTextValue: hasTextValue,
AND: AND,
OR: OR,
NOT: NOT,
parentMatches: parentMatches,
};
export const constructors = {
text: newTextNode,
comment: newCommentNode,
element: newElement,
fragment: newDocumentFragment,
};