collapseNode<T> static method
Incrementally collapse a node: remove all descendants that follow it.
Mutates currentList in place (caller-owned) to avoid copying the whole
list, and returns that same list with the index of the collapsed node.
Returns null if the node was not found (caller should fall back to a full
rebuild).
Implementation
static ({List<FlatNode<T>> list, int index})? collapseNode<T>({
required List<FlatNode<T>> currentList,
required String nodeId,
}) {
final idx = currentList.indexWhere((fn) => fn.node.id == nodeId);
if (idx == -1) return null;
final parentDepth = currentList[idx].depth;
// Find the end of descendants: all consecutive items with depth > parentDepth
int endIdx = idx + 1;
while (endIdx < currentList.length &&
currentList[endIdx].depth > parentDepth) {
endIdx++;
}
if (endIdx == idx + 1) {
return (list: currentList, index: idx); // Nothing to remove
}
// Remove the descendant range in place.
currentList.removeRange(idx + 1, endIdx);
return (list: currentList, index: idx);
}