# Row grouping

> Group rows by one or more columns, let users drag columns into the group panel, control expansion and customise the group column.

Row grouping collapses rows that share a value into expandable group rows, for example sales by region, then by country. Groups nest to any depth, show a child count, and carry [aggregates](https://docs.birchui.com/grid-pro/aggregation.md) such as total revenue.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Row grouping requires `RowGroupingModule` from `@birchui/grid-pro`. Add `AggregationModule` for totals on group rows.

**Live demo: Row grouping with aggregation** (runs on the HTML version of this page). Source of `demos/grouping-aggregation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { AggregationModule, RowGroupingModule } from '@birchui/grid-pro';
import {
  button,
  docsTheme,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Row grouping with aggregation', height: 500 };

const columns: ColumnDef<Order>[] = [
  { field: 'region', header: 'Region', rowGroup: true, rowGroupIndex: 0 },
  { field: 'country', header: 'Country', rowGroup: true, rowGroupIndex: 1 },
  { field: 'customer', header: 'Customer', width: 190 },
  { field: 'product', header: 'Product', width: 180 },
  { field: 'rep', header: 'Sales rep', width: 150 },
  { field: 'quantity', header: 'Units', type: 'number', width: 100, aggFunc: 'sum' },
  {
    id: 'revenue',
    header: 'Revenue',
    type: 'number',
    width: 130,
    valueGetter: revenueOf,
    format: formatCurrency,
    aggFunc: 'sum',
  },
  {
    id: 'avgOrder',
    header: 'Avg order',
    type: 'number',
    width: 120,
    valueGetter: revenueOf,
    format: formatCurrency,
    aggFunc: 'avg',
  },
  { field: 'id', header: 'Orders', width: 100, aggFunc: 'count' },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(5000, 21),
    getRowId: (order) => order.id,
    modules: [RowGroupingModule, AggregationModule],
    groupPanel: true,
    groupDefaultExpanded: 1,
    groupTotals: true,
    defaultColumn: { sortable: true },
    theme: docsTheme(),
    ariaLabel: 'Orders grouped by region and country',
  });
  toolbar.append(
    button('Expand all', () => grid.expandAll()),
    button('Collapse all', () => grid.collapseAll()),
    'Drag a header into the group panel to group by it.',
  );
  const describe = () => {
    const groups = grid.getDisplayRows().filter((row) => row.kind === 'group').length;
    status.textContent = `${groups.toLocaleString()} visible group rows over ${grid.getRows().length.toLocaleString()} orders.`;
  };
  const off = grid.on('modelUpdated', describe);
  describe();
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}
```

## Group by columns

There are two equivalent ways to say which columns to group by. Use whichever fits how you store configuration.

The `groupBy` grid option lists column ids in grouping order:

```ts title="group-by-option.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro';

interface Sale {
  id: string;
  region: string;
  country: string;
  rep: string;
  quarter: 'Q1' | 'Q2' | 'Q3' | 'Q4';
  units: number;
  revenue: number;
}

const columns: ColumnDef<Sale>[] = [
  { field: 'region', header: 'Region' },
  { field: 'country', header: 'Country' },
  { field: 'rep', header: 'Sales rep' },
  { field: 'quarter', header: 'Quarter' },
  { field: 'units', header: 'Units', type: 'number', aggFunc: 'sum' },
  { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' },
];

const api = createGrid(container, {
  columns,
  rows: sales,
  getRowId: (row) => row.id,
  modules: [RowGroupingModule, AggregationModule],
  groupBy: ['region', 'country'],
});
```

Or mark the columns themselves with `rowGroup`, and use `rowGroupIndex` to fix the order. Columns without an index follow in column order. `groupBy`, when set, takes precedence over the column flags.

```ts
const columns: ColumnDef<Sale>[] = [
  { field: 'region', rowGroup: true, rowGroupIndex: 0 },
  { field: 'country', rowGroup: true, rowGroupIndex: 1 },
  { field: 'rep', header: 'Sales rep' },
  { field: 'units', type: 'number', aggFunc: 'sum' },
  { field: 'revenue', type: 'number', aggFunc: 'sum' },
];
```

Group keys are the column's value, so a column with a [`valueGetter`](https://docs.birchui.com/grid/columns.md) groups by the computed value. This is how you group by a derived bucket such as the order month:

```ts
{
  id: 'month',
  header: 'Month',
  valueGetter: (row: Order) => row.orderDate.slice(0, 7),
  rowGroup: true,
}
```

To change grouping from code, call `update()` with a new `groupBy`. Pass an empty array to remove grouping.

```ts
api.update({ groupBy: ['rep'] });
api.update({ groupBy: [] });
```

A column id that does not exist is ignored with a single console warning, so a stale saved layout cannot break the grid.

## How groups are built

- **Keys.** Rows with equal values land in the same group. Dates are compared by time, so two `Date` objects for the same instant share a group.
- **Blanks.** `null`, `undefined`, empty strings, `NaN` and invalid dates all go into a single group labelled `(Blanks)`.
- **Labels.** A group row shows its key formatted by the grouped column's `format` function. Without one, dates show as `YYYY-MM-DD` and other values as text.
- **Order.** Groups are sorted by key in ascending order, according to the grouped column's `type`: numbers numerically, dates by time, and text with a case-insensitive collation for the grid's `locale` that puts `Rep 2` before `Rep 10`. The `(Blanks)` group sorts last.
- **Filtering and sorting** run before grouping. Groups only contain rows that pass the current filters, and leaf rows inside a group keep the current sort.

### Sorting groups

Sorting the group column, or the grouped column itself, reorders the groups by key. Sorting an aggregated column orders groups by their aggregate value, which is how you show the highest-revenue region first:

```ts
api.setSort([{ colId: 'revenue', dir: 'desc' }]);
```

With `multiSort`, sort items are applied in order at every level.

## The group column

When grouping is active the grid adds a group column at the left. It shows the expand toggle, the group label indented by depth, and the number of rows in each group in parentheses. Its defaults are a header of `Group`, a width of 220 pixels, pinned to the left, sortable and resizable. Override any of them with `groupColumn`, which accepts [column definition](https://docs.birchui.com/grid/columns.md) properties:

```ts
createGrid(container, {
  columns,
  rows: sales,
  modules: [RowGroupingModule, AggregationModule],
  groupBy: ['region', 'country'],
  groupColumn: {
    header: 'Region / country',
    width: 260,
  },
});
```

The group column's id is exported as `GROUP_COLUMN_ID`, which you need for `setSort()` or `scrollToColumn()`:

```ts
import { GROUP_COLUMN_ID } from '@birchui/grid-pro';

api.setSort([{ colId: GROUP_COLUMN_ID, dir: 'desc' }]);
```

### Hiding the grouped columns

The grouped columns stay visible by default. Hide them in their definitions, or create the module with `hideGroupedColumns` so whichever columns are grouped at the moment are hidden automatically:

```ts
import { createRowGroupingModule, AggregationModule } from '@birchui/grid-pro';

createGrid(container, {
  columns,
  rows: sales,
  modules: [createRowGroupingModule({ hideGroupedColumns: true }), AggregationModule],
  groupBy: ['region'],
});
```

`RowGroupingModule` is the same module created with default settings.

## Expanding and collapsing

Users expand a group by clicking its toggle. Keyboard users press `Enter` or `Space` on a group row. In the group column, `Arrow Right` expands the focused row and `Arrow Left` collapses it, or moves focus to the parent group when it is already collapsed.

In code, use the expansion API from the grid core:

| Method | Purpose |
| --- | --- |
| `api.setExpanded(rowIds, expanded)` | Expand or collapse one group row, or several at once when you pass an array of ids. |
| `api.isExpanded(rowId, options?)` | Whether a row is expanded, including the effect of `expandAll()`. Pass `{ ignoreExpandAll: true }` to get only the row's own toggle state, or `undefined` if it has none. |
| `api.expandAll()` | Expand every group at every level, discarding individual toggles. |
| `api.collapseAll()` | Collapse every group, discarding individual toggles. |

`setExpanded()` and user toggles fire the `rowExpanded` event with `{ rowId, expanded }`, once for every row whose state changes. Passing an array updates all the rows with a single re-render. `expandAll()` and `collapseAll()` reset every row at once and do not fire a per-row event.

```ts
api.on('rowExpanded', ({ rowId, expanded }) => {
  console.log(`${rowId} is now ${expanded ? 'open' : 'closed'}`);
});
```

Group row ids are stable strings derived from the group path, so the same group keeps its id, and its expanded state, across `setRows()` and `applyTransaction()`. Read ids from the display rows rather than building them by hand:

```ts
const emea = api.getAllDisplayRows().find((row) => row.kind === 'group' && row.group?.key === 'EMEA');
if (emea) api.setExpanded(emea.id, true);

const europeAndAmericas = api
  .getAllDisplayRows()
  .filter((row) => row.kind === 'group' && row.depth === 0 && ['EMEA', 'North America', 'LATAM'].includes(String(row.group?.key)))
  .map((row) => row.id);
api.setExpanded(europeAndAmericas, true);
```

### Default expansion

`groupDefaultExpanded` is the number of grouping levels that start expanded:

| Value | Result |
| --- | --- |
| `0` (default) | Every group starts collapsed. |
| `1` | Top-level groups start open, deeper levels collapsed. |
| `n` | The first `n` levels start open. |
| `-1` | Every level starts open. |

```ts
createGrid(container, {
  columns,
  rows: sales,
  modules: [RowGroupingModule],
  groupBy: ['region', 'country', 'rep'],
  groupDefaultExpanded: 1,
});
```

The default only applies to groups the user has not toggled. Once a group is expanded or collapsed, its state is kept.

### Expand to a level

The module also adds `expandToLevel(level)` to the grid API. It opens every group shallower than `level` and closes the rest, which suits a "Show: Regions | Countries | Reps" control. Pass `-1` to open everything. Like every Pro method it is optional on the `GridApi` type, so call it with `?.`:

```ts
api.expandToLevel?.(2);
```

## The group panel

Set `groupPanel: true` to show a bar above the header where users build the grouping themselves. It reads "Drag a column header here to group" while empty.

- Drag a column header into the panel to group by that column. The drop position sets its level.
- Drag a chip within the panel to change the order.
- Click a chip's remove button to ungroup that column.
- With a chip focused, `Arrow Left` and `Arrow Right` move between chips, `Alt` + arrow moves the chip, and `Delete` or `Backspace` removes it.

Column header menus also gain **Group by this column** and **Ungroup** items whenever the module is installed, with or without the panel.

```ts
const api = createGrid(container, {
  columns,
  rows: sales,
  modules: [RowGroupingModule, AggregationModule],
  groupPanel: true,
  groupBy: ['region'],
});
```

Grouping chosen in the panel or the menu is stored as a runtime override on top of the `groupBy` option. Read the effective grouping with `getGroupBy()`, and change it the same way the panel does with `setGroupBy()`:

```ts
function saveGrouping() {
  localStorage.setItem('sales-grouping', JSON.stringify(api.getGroupBy?.() ?? []));
}

function restoreGrouping() {
  const saved = localStorage.getItem('sales-grouping');
  if (saved) api.setGroupBy?.(JSON.parse(saved));
}
```

`setGroupBy(null)` drops the override and returns to the `groupBy` option. Calling `api.update({ groupBy })` also replaces any override.

## Grand totals

`groupTotals: true` adds a grand total row at the bottom that aggregates every row passing the current filters, using each column's `aggFunc`. Its group column cell reads `Total`. It needs `AggregationModule`, and it also works on a flat grid with no grouping at all.

```ts
createGrid(container, {
  columns,
  rows: sales,
  modules: [RowGroupingModule, AggregationModule],
  groupBy: ['region'],
  groupTotals: true,
});
```

The total row's id is exported as `TOTAL_ROW_ID`.

## Group rows in the API

Grouping changes the display rows, not your data. `api.getRows()` still returns your original row objects. `api.getAllDisplayRows()` returns every display row, and `api.getDisplayRows()` returns the rows of the current page, which is the same list unless [pagination](https://docs.birchui.com/grid/pagination.md) is on. Each entry has a `kind`:

| `kind` | Meaning |
| --- | --- |
| `'data'` | One of your rows. `data` is the row object. |
| `'group'` | A group row. `data` is `undefined`, `group` describes the group and `aggregates` holds its totals. |
| `'total'` | The grand total row from `groupTotals`. |

The `group` property has this shape:

**`DisplayRowGroup`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface DisplayRowGroup<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `colId` | `string` |  |
| `key` | `unknown` |  |
| `label` | `string` |  |
| `childCount` | `number` |  |
| `leaves` | `TRow[]` |  |

`leaves` contains every data row under the group, at any depth, and `childCount` is their number. That makes custom summaries easy:

```ts
for (const row of api.getAllDisplayRows()) {
  if (row.kind !== 'group' || !row.group) continue;
  const reps = new Set(row.group.leaves.map((sale) => sale.rep));
  console.log(`${row.group.label}: ${row.group.childCount} rows, ${reps.size} reps`);
}
```

Use `rowClass` to style group rows by depth:

```ts
createGrid(container, {
  columns,
  rows: sales,
  modules: [RowGroupingModule],
  groupBy: ['region', 'country'],
  rowClass: (row) => (row.kind === 'group' ? `sales-group sales-group-${row.depth}` : undefined),
});
```

## Grouping, tree data and pivot

Grouping, [tree data](https://docs.birchui.com/grid-pro/tree-data.md) and [pivot mode](https://docs.birchui.com/grid-pro/pivoting.md) all reshape rows, so only one is active at a time. Pivot mode wins over tree data, and tree data wins over grouping. While another mode is active, `groupBy` is kept but ignored, and the grouping menu items are hidden.

## Accessibility

A grouped grid follows the WAI-ARIA treegrid pattern. Expandable rows expose `aria-expanded`, rows carry `aria-level` for their depth, and `aria-rowcount` reflects the visible rows, including group rows. The group panel is a labelled group, and each chip announces its position, for example "Country, grouping level 2 of 2". See [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md) for the full key map.

## Options reference

**`GridOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridOptions<TRow = RowData> extends GridFeatureOptions<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `groupBy?` | `string[]` |  |
| `groupDefaultExpanded?` | `number` |  |
| `groupPanel?` | `boolean` |  |
| `groupColumn?` | `Partial<ColumnDef<TRow>>` |  |
| `groupTotals?` | `boolean` |  |

Column properties used by grouping are `rowGroup`, `rowGroupIndex`, `aggFunc`, `type` and `format` on [`ColumnDef`](https://docs.birchui.com/api/core.md#columndef). The extra API methods are optional members of `GridApi`, listed with the module's types in the [`@birchui/grid-pro` reference](https://docs.birchui.com/api/grid-pro.md).
