How the treeWalker algorithm works
mainThe treeWalker is a generator function that builds the tree's internal representation. It follows a specific lifecycle:
- Initialization: The first
yieldmust provide the root nodes of the tree. - The Loop: A
while(true)loop is used to process the rest of the tree. - Parent-Child Interaction: Inside the loop, the generator calls
yield. This pauses the generator and sends the current state to the tree component. In exchange, the tree component sends back aparentobject. - Yielding Children: The generator iterates through the
parent.node.childrenand yields data for each child. - Iteration: Once all children of a node are yielded, the loop continues, and the next
yieldwill receive the next node to process (either a sibling, a child of a sibling, or an ancestor's sibling).
Important: The treeWalker function is re-run whenever the treeWalker prop changes. To avoid performance issues, always memoize the function (e.g., with useCallback).
function* treeWalker() {
// 1. Yield root nodes
yield getNodeData(rootNode, 0);
while (true) {
// 2. Receive a node to expand
const parent = yield;
// 3. Yield its children
for (const child of parent.node.children) {
yield getNodeData(child, parent.nestingLevel + 1);
}
}
}