collectTreePaths<T> function
Every tree path in rows, for collapsing a tree whose branches the user
has never opened.
Implementation
List<String> collectTreePaths<T>({
required List<T> rows,
required TreeSpec<T> spec,
required Object Function(T row) keyOf,
}) {
final out = <String>[];
final seen = <Object>{};
final childrenOf = spec.childrenOf;
final parentOf = spec.parentOf;
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);
}
}
void walk(List<T> roots) {
final stack = <T>[...roots.reversed];
while (stack.isNotEmpty) {
final row = stack.removeLast();
final key = keyOf(row);
if (!seen.add(key)) continue;
out.add(pathKeySegment(key));
final kids =
childrenOf != null ? childrenOf(row) : (byParent[key] ?? const []);
for (var i = kids.length - 1; i >= 0; i--) {
stack.add(kids[i]);
}
}
}
if (parentOf == null) {
walk(rows);
return out;
}
walk(
rootsOf<T>(
rows,
parentOf,
keyOf,
present,
(row) => byParent[keyOf(row)] ?? const [],
),
);
return out;
}