|
1 /** |
|
2 * TreeWalker.js |
|
3 * |
|
4 * Copyright, Moxiecode Systems AB |
|
5 * Released under LGPL License. |
|
6 * |
|
7 * License: http://www.tinymce.com/license |
|
8 * Contributing: http://www.tinymce.com/contributing |
|
9 */ |
|
10 |
|
11 /** |
|
12 * TreeWalker class enables you to walk the DOM in a linear manner. |
|
13 * |
|
14 * @class tinymce.dom.TreeWalker |
|
15 * @example |
|
16 * var walker = new tinymce.dom.TreeWalker(startNode); |
|
17 * |
|
18 * do { |
|
19 * console.log(walker.current()); |
|
20 * } while (walker.next()); |
|
21 */ |
|
22 define("tinymce/dom/TreeWalker", [], function() { |
|
23 /** |
|
24 * Constructs a new TreeWalker instance. |
|
25 * |
|
26 * @constructor |
|
27 * @method TreeWalker |
|
28 * @param {Node} startNode Node to start walking from. |
|
29 * @param {node} rootNode Optional root node to never walk out of. |
|
30 */ |
|
31 return function(startNode, rootNode) { |
|
32 var node = startNode; |
|
33 |
|
34 function findSibling(node, startName, siblingName, shallow) { |
|
35 var sibling, parent; |
|
36 |
|
37 if (node) { |
|
38 // Walk into nodes if it has a start |
|
39 if (!shallow && node[startName]) { |
|
40 return node[startName]; |
|
41 } |
|
42 |
|
43 // Return the sibling if it has one |
|
44 if (node != rootNode) { |
|
45 sibling = node[siblingName]; |
|
46 if (sibling) { |
|
47 return sibling; |
|
48 } |
|
49 |
|
50 // Walk up the parents to look for siblings |
|
51 for (parent = node.parentNode; parent && parent != rootNode; parent = parent.parentNode) { |
|
52 sibling = parent[siblingName]; |
|
53 if (sibling) { |
|
54 return sibling; |
|
55 } |
|
56 } |
|
57 } |
|
58 } |
|
59 } |
|
60 |
|
61 /** |
|
62 * Returns the current node. |
|
63 * |
|
64 * @method current |
|
65 * @return {Node} Current node where the walker is. |
|
66 */ |
|
67 this.current = function() { |
|
68 return node; |
|
69 }; |
|
70 |
|
71 /** |
|
72 * Walks to the next node in tree. |
|
73 * |
|
74 * @method next |
|
75 * @return {Node} Current node where the walker is after moving to the next node. |
|
76 */ |
|
77 this.next = function(shallow) { |
|
78 node = findSibling(node, 'firstChild', 'nextSibling', shallow); |
|
79 return node; |
|
80 }; |
|
81 |
|
82 /** |
|
83 * Walks to the previous node in tree. |
|
84 * |
|
85 * @method prev |
|
86 * @return {Node} Current node where the walker is after moving to the previous node. |
|
87 */ |
|
88 this.prev = function(shallow) { |
|
89 node = findSibling(node, 'lastChild', 'previousSibling', shallow); |
|
90 return node; |
|
91 }; |
|
92 }; |
|
93 }); |