collapseNode<T> static method

({int index, List<FlatNode<T>> list})? collapseNode<T>({
  1. required List<FlatNode<T>> currentList,
  2. required String nodeId,
})

Incrementally collapse a node: remove all descendants that follow it. Returns the new list and the index of the collapsed node, or null if the node was not found (caller should fall back to 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
  }

  final result = List<FlatNode<T>>.of(currentList);
  result.removeRange(idx + 1, endIdx);
  return (list: result, index: idx);
}