fix: bug on node iterator with nested nodes (#1986)

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.
This commit is contained in:
Mohammad Zolfaghari 2023-03-14 07:07:42 +03:30 committed by GitHub
parent 23d0493027
commit 7be7c2a7a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 16 deletions

View File

@ -27,10 +27,10 @@ class NodeIterator implements Iterator<Node> {
return true; return true;
} }
final node = _currentNode; if (_currentNode == null) {
if (node == null) {
return false; return false;
} }
Node node = _currentNode!;
if (endNode != null && endNode == node) { if (endNode != null && endNode == node) {
_currentNode = null; _currentNode = null;
@ -38,16 +38,19 @@ class NodeIterator implements Iterator<Node> {
} }
if (node.children.isNotEmpty) { if (node.children.isNotEmpty) {
_currentNode = _findLeadingChild(node); _currentNode = node.children.first;
} else if (node.next != null) { } else if (node.next != null) {
_currentNode = node.next!; _currentNode = node.next!;
} else { } else {
final parent = node.parent!; while (node.parent != null) {
final nextOfParent = parent.next; node = node.parent!;
if (nextOfParent == null) { final nextOfParent = node.next;
_currentNode = null; if (nextOfParent == null) {
} else { _currentNode = null;
_currentNode = nextOfParent; } else {
_currentNode = nextOfParent;
break;
}
} }
} }
@ -61,11 +64,4 @@ class NodeIterator implements Iterator<Node> {
} }
return result; return result;
} }
Node _findLeadingChild(Node node) {
while (node.children.isNotEmpty) {
node = node.children.first;
}
return node;
}
} }

View File

@ -28,5 +28,29 @@ void main() async {
} }
expect(nodes.moveNext(), false); 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);
});
}); });
} }