# Grouping

> Group rows by one or more columns from the drop area, the keyboard or methods; virtualized, with preserved expansion.

Canonical: https://salmonui.dev/docs/data-grid/grouping

Grouping is a core pipeline stage. Rows group by any number of
columns; each level sorts ascending or descending and
grouped columns always sort before the user sort. A column can
opt out of grouping. A number or date column with `groupByFormat`
groups by its formatted value, for example by month.

A column's `groupKey(row)` groups by a custom key instead of the cell value:
rows with an equal key (dates by time) form one group, so a key
can bucket numbers into bands or combine fields. Groups order by key in the
column's group direction: blanks first, then booleans, numbers and dates by
value, then strings by the locale collator. The key is the group's `key` in
captions, events, expansion paths and `toggleGroup`. With `groupKey`,
`groupByFormat` no longer decides the buckets: it only formats the caption
with the column formatter (the demo shows "$250" for the 250 band);
otherwise the caption is the key as text. `groupKey` runs once
per row on every regroup and only on local data; lazy (server) grouping
groups by the field.

```tsx
<DataGrid
  data={orders}
  columns={[
    { field: 'country', header: 'Country' },
    { field: 'orderDate', header: 'Month', type: 'date', format: 'yMMM', groupByFormat: true },
    { field: 'amount', header: 'Amount', type: 'number', groupKey: (row) => Math.floor(row.amount / 250) * 250 },
    { field: 'note', header: 'Note', groupable: false },
  ]}
  sorting
  grouping={{ groupBy: ['country'], reorderable: true, showGroupedColumns: true }}
  onGroupChange={(event) => console.log(event.action, event.groupBy)}
/>
```

`grouping.groupBy` lists the grouped fields in order; it is reactive and
part of the server render, so a grid renders already grouped.

## Drop area and chips

The drop area above the header can be hidden with
`grouping.showDropArea: false`. Dragging a header
into it groups by that column. Each grouped column is a chip that
can be reordered by drag or `Alt+Arrow`, flipped between ascending
and descending, and removed. Reordering is opt in
(`grouping.reorderable`); the direction toggle follows `sorting` (shown when
the grid sorts and the column is sortable); `grouping.showRemoveButton`
(default `true`) shows the remove button. `grouping.showHeaderToggle` (opt
in) adds a group toggle button to the header
of every groupable column that groups or ungroups by it. Grouped columns are hidden by default,
and `grouping.showGroupedColumns` keeps them visible. On a
focused chip, Delete or Backspace removes it.

## Captions and expansion

Each group shows a caption row with the column, the key and the item count,
an indent per level and a toggle button that exposes
`aria-expanded`. The caption cell, which takes focus, carries
`aria-expanded` too and describes the level and item count ("Level 2, 15
items", `localeText.groupLevel`); the grid stays a `grid`, so rows carry no
`aria-level`. The drop area renders above the grid element, outside it.
`grouping.renderCaption(ctx)` replaces the caption text and receives the
`field`, `key`, `formattedKey`, `count`, `aggregates`, `expanded` and
`toggle`. Groups start expanded (`grouping.defaultExpanded`,
default `true`) and `onBeforeGroupToggle` / `onGroupToggle` control
expansion; `api.expandAllGroups()`, `api.collapseAllGroups()` and
`api.toggleGroup(target, expanded?)` (by row id, path key or path) expand or
collapse all groups or one. On a focused caption, Enter
toggles the group and ArrowLeft / ArrowRight collapse or expand it. Expansion is keyed by the group path, so it survives
virtual scrolling, sorting and data refreshes.

## Methods, events and keyboard

`api.groupColumn(field, index?)`, `api.ungroupColumn(field)` and
`api.clearGrouping()` group, ungroup and clear.
`onBeforeGroupChange` (cancel with `preventDefault()`) fires before every
grouping change with the `action` (`'group'`, `'ungroup'`, `'move'` or
`'clear'`), the `field` and the proposed `groupBy`, and `onGroupChange`
after it. Ctrl+Space on a focused header groups or ungroups it;
Ctrl/⌘+ArrowUp and Ctrl/⌘+ArrowDown in the body collapse or expand all
groups.

### Live demo: Grouping

Live demo: https://salmonui.dev/demos/data-grid/grouping

Multi-level grouping over 5,000 virtualized rows with the drop area, chips, group-by-format, a custom group key, caption templates, collapse state, cancelable changes, group methods and events.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridSorting } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(5_000, 21);

/** Lower bound of the order's $250 amount band. */
function amountBand(order: Order): number {
  return Math.floor(order.amount / 250) * 250;
}

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, groupable: false },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'city', header: 'City', width: 130 },
  { field: 'category', header: 'Category', width: 140 },
  { field: 'priority', header: 'Priority', width: 100 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
  // Group by the formatted value: one group per month.
  { id: 'month', field: 'placed', header: 'Month', type: 'datetime', format: 'yMMM', groupByFormat: true, width: 110 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  // Custom group key: bands of $250; groupByFormat formats the key with the column format.
  { id: 'band', field: 'amount', header: 'Amount band', type: 'number', format: 'C0', align: 'end', width: 120, groupKey: amountBand, groupByFormat: true },
];

const initialGroups: readonly string[] = ['country', 'category'];
// Group order follows the sort of the grouped field: Category groups descend.
const sorting: DataGridSorting = { sortBy: [{ field: 'category', direction: 'desc' }] };

export default function GroupingDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [groups, setGroups] = useState<readonly string[]>(initialGroups);
  const [showGrouped, setShowGrouped] = useState(true);
  const [collapsed, setCollapsed] = useState(false);
  const [locked, setLocked] = useState(false);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={showGrouped} onCheckedChange={(checked) => setShowGrouped(checked)}>
          Show grouped columns
        </Checkbox>
        <Checkbox checked={collapsed} onCheckedChange={(checked) => setCollapsed(checked)}>
          Start collapsed
        </Checkbox>
        <Checkbox checked={locked} onCheckedChange={(checked) => setLocked(checked)}>
          Cancel grouping changes
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.groupColumn('priority')}>
          Group by Priority
        </Button>
        <Button variant="outline" onClick={() => setGroups(['month'])}>
          Group by month (formatted value)
        </Button>
        <Button variant="outline" onClick={() => setGroups(['band'])}>
          Group by amount band (custom key)
        </Button>
        <Button variant="outline" onClick={() => api.current?.ungroupColumn('category')}>
          Ungroup Category
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearGrouping()}>
          Clear grouping
        </Button>
        <Button variant="outline" onClick={() => api.current?.collapseAllGroups()}>
          Collapse all
        </Button>
        <Button variant="outline" onClick={() => api.current?.expandAllGroups()}>
          Expand all
        </Button>
        <Button variant="outline" onClick={() => api.current?.toggleGroup([{ columnId: 'country', key: 'Japan' }])}>
          Toggle “Japan”
        </Button>
      </div>
      <DataGrid<Order>
        key={String(collapsed)}
        aria-label="Grouped orders"
        data={orders}
        columns={columns}
        sorting={sorting}
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        grouping={{
          groupBy: groups,
          showGroupedColumns: showGrouped,
          showHeaderToggle: true,
          reorderable: true,
          defaultExpanded: !collapsed,
          renderCaption: ({ header, formattedKey, count, expanded }) => (
            <span>
              {header}: <strong>{formattedKey}</strong> — {count} {count === 1 ? 'order' : 'orders'}
              {expanded ? '' : ' (collapsed)'}
            </span>
          ),
        }}
        onBeforeGroupChange={(event) => {
          if (locked) {
            push(`cancelled ${event.action} ${event.field ?? ''}`);
            event.preventDefault();
          }
        }}
        onGroupChange={(event) => {
          setGroups(event.groupBy);
          push(`${event.action} ${event.field ?? ''} (${event.source}) → [${event.groupBy.join(', ')}]`);
        }}
        onGroupToggle={(event) => push(`${event.expanded ? 'expand' : 'collapse'} ${event.path.map((p) => String(p.key)).join(' / ')}`)}
      />
      <p className="demo-status">
        Drag a header into the drop area to group; drag chips to reorder; click a chip to flip its direction. Keyboard: Ctrl+Space on a header
        groups it, Ctrl+Up / Ctrl+Down collapse or expand all, Alt+Arrow moves a focused chip.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## Grouping with column virtualization

Grouping works with row and column virtualization on. Only the visible columns of the
center zone render; the group indent is frozen at the start edge like a
pinned column, and caption text stays in view while the grid scrolls
sideways. Captions span the full row width, so they never depend on which
columns are rendered.

### Live demo: Grouping with column virtualization

Live demo: https://salmonui.dev/demos/data-grid/grouping-wide

20,000 rows by 80 columns grouped by two levels with row and column virtualization on; the group indent and captions stay at the start edge while scrolling sideways.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { createWideRows, type WideRow } from '../../lib/fixtures';
import { createWideColumns } from '../../lib/wide';

const rows = createWideRows(20_000);
const REGIONS = ['North', 'East', 'South', 'West'];
const TEAMS = ['Atlas', 'Borealis', 'Cobalt'];

// 80 columns: the center zone is column-virtualized while rows are grouped. The # column is
// pinned to the start; Region and Team are computed group keys.
const [first, ...rest] = createWideColumns(80);
const columns: DataGridColumn<WideRow>[] = [
  { ...(first as DataGridColumn<WideRow>), pinned: 'start' },
  { id: 'region', header: 'Region', width: 110, valueGetter: (row) => REGIONS[row.id % REGIONS.length] as string },
  { id: 'team', header: 'Team', width: 110, valueGetter: (row) => TEAMS[Math.floor(row.id / 4) % TEAMS.length] as string },
  ...rest,
];

// Initial grouping; a constant (the options prop is reactive).
const grouping = { groupBy: ['region', 'team'] };

export default function GroupingWideDemo() {
  const api = useRef<DataGridApi<WideRow> | null>(null);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('n70')}>
          Scroll to column 70
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('row')}>
          Back to the first column
        </Button>
      </div>
      <DataGrid<WideRow>
        aria-label="20,000 grouped rows by 80 columns"
        data={rows}
        columns={columns}
        grouping={grouping}
        height={400}
        rowHeight={32}
        locale="en-US"
        ref={api}
      />
      <p className="demo-status">Scroll sideways: the group indent, the captions and the pinned # column stay in place while only the visible columns render.</p>
    </>
  );
}
```

## API reference

See [`DataGridGrouping`](https://salmonui.dev/docs/reference/data-grid/DataGridGrouping),
[`DataGridGroupCaptionContext`](https://salmonui.dev/docs/reference/data-grid/DataGridGroupCaptionContext),
[`DataGridGroupChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridGroupChangeEvent)
and [`DataGridGroupToggleEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridGroupToggleEvent)
in the API reference, and [Lazy load grouping](https://salmonui.dev/docs/data-grid/lazy-grouping)
for server-side grouping.
