toGroup method

  1. @override
List<PlutoRow> toGroup({
  1. required Iterable<PlutoRow> rows,
})
override

Handling for grouping rows.

Implementation

@override
List<PlutoRow> toGroup({
  required Iterable<PlutoRow> rows,
}) {
  if (rows.isEmpty) return rows.toList();
  assert(visibleColumns.isNotEmpty);

  final List<PlutoRow> groups = [];
  final List<List<PlutoRow>> groupStack = [];
  final List<PlutoRow> parentStack = [];
  final List<String> groupFields =
      visibleColumns.map((e) => e.field).toList();
  final List<String> groupKeyStack = [];
  final maxDepth = groupFields.length;

  List<PlutoRow>? currentGroups = groups;
  PlutoRow? currentParent;
  int depth = 0;
  int sortIdx = 0;
  List<Iterator<MapEntry<String, List<PlutoRow>>>> stack = [];
  Iterator<MapEntry<String, List<PlutoRow>>>? currentIter;
  currentIter = groupBy<PlutoRow, String>(
    rows,
    (r) => r.cells[groupFields[depth]]!.value.toString(),
  ).entries.iterator;

  while (currentIter != null || stack.isNotEmpty) {
    if (currentIter != null && depth < maxDepth && currentIter.moveNext()) {
      groupKeyStack.add(currentIter.current.key);
      final groupKeys = [
        visibleColumns[depth].field,
        groupKeyStack.join('_'),
        'rowGroup',
      ];

      final row = _createRowGroup(
        groupKeys: groupKeys,
        sortIdx: ++sortIdx,
        sampleRow: currentIter.current.value.first,
      );

      currentParent = parentStack.lastOrNull;
      if (currentParent != null) row.setParent(currentParent);

      parentStack.add(row);
      currentGroups!.add(row);
      stack.add(currentIter);
      groupStack.add(currentGroups);
      currentGroups = row.type.group.children;

      if (depth + 1 < maxDepth) {
        currentIter = groupBy<PlutoRow, String>(
          currentIter.current.value,
          (r) => r.cells[groupFields[depth + 1]]!.value.toString(),
        ).entries.iterator;
      }

      ++depth;
    } else {
      --depth;
      if (depth < 0) break;

      groupKeyStack.removeLast();
      currentParent = parentStack.lastOrNull;
      if (currentParent != null) parentStack.removeLast();
      currentIter = stack.lastOrNull;
      if (currentIter != null) stack.removeLast();

      if (depth + 1 == maxDepth) {
        int sortIdx = 0;
        for (final child in currentIter!.current.value) {
          currentGroups!.add(child);
          child.setParent(currentParent);
          child.sortIdx = ++sortIdx;
        }
      }

      currentGroups = groupStack.lastOrNull;
      if (currentGroups != null) groupStack.removeLast();
    }

    if (depth == 0) groupKeyStack.clear();
  }

  return groups;
}