recalculateListIndicesFor function

void recalculateListIndicesFor(
  1. Root root,
  2. Set<FNode> affectedNodes, {
  3. FluentDocument? document,
})

Recalculates list indices only for lists that contain any of the given affectedNodes (or their ancestors). This avoids walking the entire document tree when only a subset of lists changed.

Implementation

void recalculateListIndicesFor(Root root, Set<FNode> affectedNodes, {FluentDocument? document}) {
  final topLists = <FluentList>{};
  for (final node in affectedNodes) {
    FNode? current = node;
    FluentList? deepestList;
    while (current != null) {
      if (current is FluentList) {
        deepestList = current;
      }
      current = document != null
          ? findParentCached(document, current)
          : findParent(root, current);
    }
    if (deepestList != null) {
      var top = deepestList;
      FNode? parent = document != null
          ? findParentCached(document, top)
          : findParent(root, top);
      while (parent is ListItem) {
        final grand = document != null
            ? findParentCached(document, parent)
            : findParent(root, parent);
        if (grand is FluentList) {
          top = grand;
          parent = document != null
              ? findParentCached(document, grand)
              : findParent(root, grand);
        } else {
          break;
        }
      }
      topLists.add(top);
    }
  }

  void recalculateList(FluentList list, List<int> parentIndices) {
    for (var i = 0; i < list.items.length; i++) {
      final item = list.items[i];
      final newIndexList = [...parentIndices, i + 1];
      item.indexList = newIndexList;
      for (final child in item.children) {
        if (child is FluentList) {
          recalculateList(child, newIndexList);
        }
      }
    }
  }

  for (final list in topLists) {
    recalculateList(list, []);
  }
}