rootsOf<T> function

List<T> rootsOf<T>(
  1. List<T> rows,
  2. Object? parentOf(
    1. T row
    ),
  3. Object keyOf(
    1. T row
    ),
  4. Set<Object> present,
  5. List<T> childrenOf(
    1. T row
    ),
)

The rows to draw at depth zero of a flat, parent-referencing model.

A row is a root when it names no parent, or names one that is not in the result - filtering out a manager leaves their reports visible rather than dropping them. Rows that no root can reach are roots too: a cycle has no root of its own, and its rows would otherwise vanish from the grid altogether. A row drawn at the wrong depth is recoverable; a row that is not drawn at all is not.

Implementation

List<T> rootsOf<T>(
  List<T> rows,
  Object? Function(T row) parentOf,
  Object Function(T row) keyOf,
  Set<Object> present,
  List<T> Function(T row) childrenOf,
) {
  final roots = [
    for (final row in rows)
      if (parentOf(row) == null || !present.contains(parentOf(row))) row,
  ];

  // Reachability ignores expansion: a child hidden under a closed branch is
  // placed, it is just not on screen. Marked with an explicit stack, because
  // this walks the whole tree whether or not anything is open - a collapsed
  // 20,000-deep chain used to overflow here while the grid showed one row.
  final reachable = <Object>{};
  final stack = <T>[...roots];
  while (stack.isNotEmpty) {
    final row = stack.removeLast();
    if (!reachable.add(keyOf(row))) continue;
    stack.addAll(childrenOf(row));
  }
  if (reachable.length == rows.length) return roots;
  return [
    ...roots,
    for (final row in rows)
      if (!reachable.contains(keyOf(row))) row,
  ];
}