Index: trunk/extensions/VisualEditor/modules/es/bases/es.DocumentBranchNode.js |
— | — | @@ -45,7 +45,18 @@ |
46 | 46 | * @param {Boolean} [reverse] Whether to iterate backwards |
47 | 47 | */ |
48 | 48 | es.DocumentBranchNode.prototype.traverseLeafNodes = function( callback, from, reverse ) { |
49 | | - var indexStack = [], index = 0, node = this, childNode, callbackResult, n, p, i; |
| 49 | + // Stack of indices that lead from this to node |
| 50 | + var indexStack = [], |
| 51 | + // Node whose children we're currently traversing |
| 52 | + node = this, |
| 53 | + // Index of the child node we're currently visiting |
| 54 | + index = reverse ? node.children.length - 1 : 0, |
| 55 | + // Shortcut for node.children[index] |
| 56 | + childNode, |
| 57 | + // Result of the last invocation of the callback |
| 58 | + callbackResult, |
| 59 | + // Variables for the loop that builds indexStack if from is specified |
| 60 | + n, p, i; |
50 | 61 | |
51 | 62 | if ( from !== undefined ) { |
52 | 63 | // Reverse-engineer the index stack by starting at from and |
— | — | @@ -74,6 +85,13 @@ |
75 | 86 | // Set up the variables such that from will be visited next |
76 | 87 | index = indexStack.pop(); |
77 | 88 | node = from.getParent(); // from is a descendant of this so its parent exists |
| 89 | + |
| 90 | + // If we're going in reverse, then we still need to visit from if it's |
| 91 | + // a leaf node, but we should not descend into it |
| 92 | + // So if from is not a leaf node, skip it now |
| 93 | + if ( reverse && from.hasChildren() ) { |
| 94 | + index--; |
| 95 | + } |
78 | 96 | } |
79 | 97 | |
80 | 98 | while ( true ) { |
— | — | @@ -84,7 +102,7 @@ |
85 | 103 | node = node.getParent(); |
86 | 104 | index = indexStack.pop(); |
87 | 105 | // Move to the next child |
88 | | - index++; |
| 106 | + reverse ? index-- : index++; |
89 | 107 | continue; |
90 | 108 | } else { |
91 | 109 | // We can't move up any more, so we're done |
— | — | @@ -97,8 +115,8 @@ |
98 | 116 | node = childNode; |
99 | 117 | // Push our current index onto the stack |
100 | 118 | indexStack.push( index ); |
101 | | - // Set the current index to zero |
102 | | - index = 0; |
| 119 | + // Set the current index to the first element we're visiting |
| 120 | + index = reverse ? node.children.length - 1 : 0; |
103 | 121 | } else { |
104 | 122 | // This is a leaf node, visit it |
105 | 123 | callbackResult = callback( childNode ); // TODO what is index? |
— | — | @@ -107,7 +125,7 @@ |
108 | 126 | return; |
109 | 127 | } |
110 | 128 | // Move to the next child |
111 | | - index++; |
| 129 | + reverse ? index-- : index++; |
112 | 130 | } |
113 | 131 | } |
114 | 132 | }; |