flattenTree<T> function
Flattens rows into the visible rows of a tree, skipping what is closed.
A row's path is its own key, type-tagged, and not the chain of its ancestors: a row is rendered once whatever claims it, so its key already identifies it, and repeating every ancestor made the paths grow quadratically with depth - 36MB of path characters over a 4,000-deep chain, which is 110ms of flattening spent building strings nobody reads.
A row that is reachable twice - a cycle in a parent reference, or a child listed under two parents - is rendered once, under the first parent that claims it. A grid that hangs is a worse answer to bad data than a grid that is missing a branch.
childComparator orders the children of each row, which is how a sort on
a nested model reaches past its roots: the pipeline only ever sees the
rows the data source holds, so for a childrenOf model it sorts the roots
and nothing else. substitute replaces a row as it is read, so an
optimistic write shows up on a child too.
Implementation
List<GridRow<T>> flattenTree<T>({
required List<T> rows,
required TreeSpec<T> spec,
required Object Function(T row) keyOf,
required GroupExpansionState expansion,
Map<Object, List<T>> loadedChildren = const {},
Set<Object> loadingKeys = const {},
Comparator<T>? childComparator,
T Function(T row)? substitute,
int Function(T row)? sourceIndexOf,
}) {
final out = <GridRow<T>>[];
final seen = <Object>{};
final childrenOf = spec.childrenOf;
final parentOf = spec.parentOf;
// The flat form: index the rows by their parent's key once, rather than
// scanning every row per parent.
final byParent = <Object, List<T>>{};
final present = <Object>{};
if (parentOf != null) {
for (final row in rows) {
present.add(keyOf(row));
}
for (final row in rows) {
final parent = parentOf(row);
if (parent == null || !present.contains(parent)) continue;
byParent.putIfAbsent(parent, () => <T>[]).add(row);
}
}
List<T> rawChildren(T row) {
if (childrenOf != null) return childrenOf(row);
if (spec.isLazy) return loadedChildren[keyOf(row)] ?? const [];
return byParent[keyOf(row)] ?? const [];
}
List<T> children(T row) {
final kids = rawChildren(row);
if (childComparator == null || kids.length < 2) return kids;
// A nested model's children never reach the pipeline, so the sort the
// user asked for is applied to each level here.
return List<T>.of(kids)..sort(childComparator);
}
/// Whether a disclosure control belongs on this row.
///
/// A lazily loaded row may have children nobody has asked for yet, so the
/// spec is asked first and the loaded children are only a fallback.
bool mayHaveChildren(T row, List<T> loaded) {
final declared = spec.hasChildren?.call(row);
if (declared != null) return declared;
return loaded.isNotEmpty;
}
// An explicit stack, not recursion: a folder tree or a bill of materials
// from real data reaches thousands of levels, and the recursive version
// overflowed the stack between 4,500 and 5,000 of them - a crash with no
// bad input to point at.
void walk(List<T> roots) {
final stack = <_Pending<T>>[];
for (var i = roots.length - 1; i >= 0; i--) {
stack.add(_Pending<T>(roots[i], 0));
}
while (stack.isNotEmpty) {
final pending = stack.removeLast();
final row = pending.row;
final key = keyOf(row);
if (!seen.add(key)) continue;
final kids = children(row);
final expanded = expansion.isExpanded(pathKeySegment(key));
out.add(DataGridRow<T>(
index: out.length,
data: substitute == null ? row : substitute(row),
sourceIndexOf: sourceIndexOf,
depth: pending.depth,
tree: TreeRowInfo(
path: pathKeySegment(key),
hasChildren: mayHaveChildren(row, kids),
expanded: expanded,
loading: loadingKeys.contains(key),
),
));
if (kids.isEmpty || !expanded) continue;
for (var i = kids.length - 1; i >= 0; i--) {
stack.add(_Pending<T>(kids[i], pending.depth + 1));
}
}
}
if (parentOf == null) {
walk(rows);
return out;
}
walk(rootsOf<T>(rows, parentOf, keyOf, present, children));
return out;
}