Skip to content

Commit

Permalink
fix: bug on node iterator with nested nodes (#1986)
Browse files Browse the repository at this point in the history
When we have more than two level nodes nested (as children)
the node iterator misses the first parent, because it goes as
deep as possible at first.
  • Loading branch information
zoli authored Mar 14, 2023
1 parent 23d0493 commit 7be7c2a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,27 +27,30 @@ class NodeIterator implements Iterator<Node> {
return true;
}

final node = _currentNode;
if (node == null) {
if (_currentNode == null) {
return false;
}
Node node = _currentNode!;

if (endNode != null && endNode == node) {
_currentNode = null;
return false;
}

if (node.children.isNotEmpty) {
_currentNode = _findLeadingChild(node);
_currentNode = node.children.first;
} else if (node.next != null) {
_currentNode = node.next!;
} else {
final parent = node.parent!;
final nextOfParent = parent.next;
if (nextOfParent == null) {
_currentNode = null;
} else {
_currentNode = nextOfParent;
while (node.parent != null) {
node = node.parent!;
final nextOfParent = node.next;
if (nextOfParent == null) {
_currentNode = null;
} else {
_currentNode = nextOfParent;
break;
}
}
}

Expand All @@ -61,11 +64,4 @@ class NodeIterator implements Iterator<Node> {
}
return result;
}

Node _findLeadingChild(Node node) {
while (node.children.isNotEmpty) {
node = node.children.first;
}
return node;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,29 @@ void main() async {
}
expect(nodes.moveNext(), false);
});

test('toList - when we have at least three level nested nodes (children)',
() {
final root = Node(type: 'root'),
n1 = Node(type: 'node_1'),
n2 = Node(type: 'node_2');

root.insert(n1);
root.insert(n2);
n1.insert(Node(type: 'node_1_1'));
n1.insert(Node(type: 'node_1_2'));
n1.childAtIndex(0)?.insert(Node(type: 'node_1_1_1'));
n1.childAtIndex(1)?.insert(Node(type: 'node_1_2_1'));

final nodes = NodeIterator(
document: Document(root: root),
startNode: root.childAtPath([0])!,
endNode: root.childAtPath([1]),
).toList();

expect(nodes[0].id, n1.id);
expect(nodes[1].id, n1.childAtIndex(0)!.id);
expect(nodes[nodes.length - 1].id, n2.id);
});
});
}

0 comments on commit 7be7c2a

Please sign in to comment.