Browse Source

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.
Mohammad Zolfaghari 2 năm trước cách đây
mục cha
commit
7be7c2a7a0

+ 12 - 16
frontend/appflowy_flutter/packages/appflowy_editor/lib/src/core/document/node_iterator.dart

@@ -27,10 +27,10 @@ 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;
@@ -38,16 +38,19 @@ class NodeIterator implements Iterator<Node> {
     }
 
     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;
+        }
       }
     }
 
@@ -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;
-  }
 }

+ 24 - 0
frontend/appflowy_flutter/packages/appflowy_editor/test/core/document/node_iterator_test.dart

@@ -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);
+    });
   });
 }