UNPKG

2.08 kBJavaScriptView Raw
1"use strict";
2/* exported NodeTraversal */
3var NodeTraversal = module.exports = {
4 nextSkippingChildren: nextSkippingChildren,
5 nextAncestorSibling: nextAncestorSibling,
6 next: next,
7 previous: previous,
8 deepLastChild: deepLastChild
9};
10
11/**
12 * @based on WebKit's NodeTraversal::nextSkippingChildren
13 * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L109
14 */
15function nextSkippingChildren(node, stayWithin) {
16 if (node === stayWithin) {
17 return null;
18 }
19 if (node.nextSibling !== null) {
20 return node.nextSibling;
21 }
22 return nextAncestorSibling(node, stayWithin);
23}
24
25/**
26 * @based on WebKit's NodeTraversal::nextAncestorSibling
27 * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.cpp?rev=179143#L93
28 */
29function nextAncestorSibling(node, stayWithin) {
30 for (node = node.parentNode; node !== null; node = node.parentNode) {
31 if (node === stayWithin) {
32 return null;
33 }
34 if (node.nextSibling !== null) {
35 return node.nextSibling;
36 }
37 }
38 return null;
39}
40
41/**
42 * @based on WebKit's NodeTraversal::next
43 * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L99
44 */
45function next(node, stayWithin) {
46 var n;
47 n = node.firstChild;
48 if (n !== null) {
49 return n;
50 }
51 if (node === stayWithin) {
52 return null;
53 }
54 n = node.nextSibling;
55 if (n !== null) {
56 return n;
57 }
58 return nextAncestorSibling(node, stayWithin);
59}
60
61/**
62 * @based on WebKit's NodeTraversal::deepLastChild
63 * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.cpp?rev=179143#L116
64 */
65function deepLastChild(node) {
66 while (node.lastChild) {
67 node = node.lastChild;
68 }
69 return node;
70}
71
72/**
73 * @based on WebKit's NodeTraversal::previous
74 * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L121
75 */
76function previous(node, stayWithin) {
77 var p;
78 p = node.previousSibling;
79 if (p !== null) {
80 return deepLastChild(p);
81 }
82 p = node.parentNode;
83 if (p === stayWithin) {
84 return null;
85 }
86 return p;
87}