Skip to content

Commit c4d95cc

Browse files
vaadin-botcaalador
andauthored
fix: Break loop in visitor (#13370) (#13378)
Do not constantly add children of a node that has already had all children added once. Fixes #13366 Co-authored-by: caalador <mikael.grankvist@vaadin.com>
1 parent fdf901e commit c4d95cc

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/internal/StateNode.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,15 +705,19 @@ void visitNodeTreeBottomUp(Consumer<StateNode> visitor) {
705705
// not done inside loop to please Sonarcube
706706
forEachChild(stack::addFirst);
707707
StateNode previousParent = this;
708+
Set<StateNode> childrenAdded = new HashSet<>();
708709

709710
while (!stack.isEmpty()) {
710711
StateNode current = stack.getFirst();
711712
assert current != null;
712713
if (current == previousParent) {
713714
visitor.accept(stack.removeFirst());
714715
previousParent = current.getParent();
716+
} else if (childrenAdded.contains(current)) {
717+
previousParent = current;
715718
} else {
716719
current.forEachChild(stack::addFirst);
720+
childrenAdded.add(current);
717721
previousParent = current;
718722
}
719723
}

‎flow-server/src/test/java/com/vaadin/flow/internal/StateNodeTest.java‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package com.vaadin.flow.internal;
1818

19+
import java.lang.reflect.Field;
1920
import java.util.ArrayList;
2021
import java.util.Arrays;
2122
import java.util.HashSet;
@@ -296,6 +297,35 @@ public void nodeTreeOnAttach_bottomUpTraversing_correctOrder() {
296297
data.removeLast()));
297298
}
298299

300+
@Test
301+
public void nodeTreeOnAttach_bottomUpTraversing_brokenParentInChildDoesNotEndInLoop()
302+
throws NoSuchFieldException, IllegalAccessException {
303+
// Set data is used to track the node during debug see
304+
// TestStateNode.toString
305+
TestStateNode root = new TestStateNode();
306+
root.setData(0);
307+
List<Integer> count = new ArrayList<>();
308+
309+
final Field parent = StateNode.class.getDeclaredField("parent");
310+
parent.setAccessible(true);
311+
312+
TestStateNode childOfRoot = new TestStateNode();
313+
childOfRoot.setData(1);
314+
315+
TestStateNode child = new TestStateNode();
316+
child.setData(2);
317+
setParent(child, childOfRoot);
318+
319+
parent.set(child, null);
320+
321+
setParent(childOfRoot, root);
322+
323+
root.visitNodeTreeBottomUp(node -> count.add(1));
324+
325+
Assert.assertEquals("Each node should be visited once", 3,
326+
count.size());
327+
}
328+
299329
@Test
300330
public void attachListener_onSetParent_listenerTriggered() {
301331
StateNode root = new TestStateTree().getRootNode();

0 commit comments

Comments
 (0)