# Collapsible column groups

> Group related columns under shared headers with ColumnGroupDef, make groups collapsible with columnGroupShow, and open or close them from code.

Wide grids read better when related columns share a header: customer details, pricing, shipping. This recipe groups an order grid's columns and lets users collapse each group to a summary column.

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

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

export const meta = { title: 'Collapsible column groups', height: 440 };

const columns: (ColumnDef<Order> | ColumnGroupDef<Order>)[] = [
  { field: 'id', header: 'Order', width: 110, pinned: 'left' },
  {
    groupId: 'customer',
    header: 'Customer',
    collapsible: true,
    openByDefault: true,
    children: [
      { field: 'customer', header: 'Name', width: 180 },
      { field: 'country', header: 'Country', width: 140, columnGroupShow: 'open' },
      { field: 'region', header: 'Region', width: 140, columnGroupShow: 'open' },
    ],
  },
  {
    groupId: 'pricing',
    header: 'Pricing',
    collapsible: true,
    children: [
      { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
      { field: 'quantity', header: 'Qty', type: 'number', width: 90, columnGroupShow: 'open' },
      {
        field: 'unitPrice',
        header: 'Unit price',
        type: 'number',
        width: 110,
        format: formatCurrency,
        columnGroupShow: 'open',
      },
      {
        field: 'discount',
        header: 'Discount',
        type: 'number',
        width: 100,
        format: (value) => `${Math.round(Number(value) * 100)}%`,
        columnGroupShow: 'open',
      },
    ],
  },
  { field: 'status', header: 'Status', width: 120 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(150, 5),
    getRowId: (order) => order.id,
    theme: docsTheme(),
    ariaLabel: 'Orders with column groups',
  });
  toolbar.append(
    button('Expand pricing', () => grid.setColumnGroupOpen('pricing', true)),
    button('Collapse all groups', () => {
      grid.setColumnGroupOpen('customer', false);
      grid.setColumnGroupOpen('pricing', false);
    }),
  );
  status.textContent = 'Click the toggle in a group header, or focus it and press Enter.';
  const off = grid.on('columnGroupOpened', ({ groupId, open }) => {
    status.textContent = `${groupId} ${open ? 'expanded' : 'collapsed'}: ${grid.getDisplayColumns().length} columns shown.`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}
```

## 1. Define the groups

A `ColumnGroupDef` has a `header` and `children`, which can be columns or further groups. Mix groups and plain columns freely in `columns`:

```ts title="order-columns.ts"
import type { ColumnDef, ColumnGroupDef } from '@birchui/core';
import type { Order } from './orders';

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const money = (value: unknown) => usd.format(Number(value));

export const columns: (ColumnDef<Order> | ColumnGroupDef<Order>)[] = [
  { field: 'id', header: 'Order', width: 110, pinned: 'left' },
  {
    groupId: 'customer',
    header: 'Customer',
    collapsible: true,
    openByDefault: true,
    children: [
      { field: 'customer', header: 'Name', width: 180 },
      { field: 'country', header: 'Country', columnGroupShow: 'open' },
      { field: 'region', header: 'Region', columnGroupShow: 'open' },
    ],
  },
  {
    groupId: 'pricing',
    header: 'Pricing',
    collapsible: true,
    children: [
      { id: 'revenue', header: 'Revenue', type: 'number', valueGetter: (o) => o.quantity * o.unitPrice, format: money },
      { field: 'quantity', header: 'Qty', type: 'number', columnGroupShow: 'open' },
      { field: 'unitPrice', header: 'Unit price', type: 'number', format: money, columnGroupShow: 'open' },
    ],
  },
  { field: 'status', header: 'Status' },
];
```

## 2. Decide what shows when

In a group with `collapsible: true`, each child's `columnGroupShow` decides when it is visible:

| `columnGroupShow` | Visible when the group is |
| --- | --- |
| not set | Open and closed |
| `'open'` | Open only |
| `'closed'` | Closed only |

Use `'closed'` for a summary column that replaces the details, such as a combined address. Groups start closed unless `openByDefault` is `true`. If closing a group would hide every one of its columns, the grid keeps them visible.

## 3. Control groups from code

```ts title="orders-grid.ts"
import { createGrid } from '@birchui/core';
import { columns } from './order-columns';

const grid = createGrid(document.querySelector<HTMLElement>('#orders')!, {
  columns,
  rows: orders,
  getRowId: (order) => order.id,
});

document.querySelector('#show-pricing')!.addEventListener('click', () => grid.setColumnGroupOpen('pricing', true));

grid.on('columnGroupOpened', ({ groupId, open }) => {
  try {
    localStorage.setItem(`orders-group:${groupId}`, String(open));
  } catch {
    // Storage unavailable; the group simply opens with its default next time.
  }
});

for (const group of grid.getColumnGroups()) {
  try {
    const saved = localStorage.getItem(`orders-group:${group.groupId}`);
    if (saved !== null) grid.setColumnGroupOpen(group.groupId, saved === 'true');
  } catch {
    break;
  }
}
```

`getColumnGroups()` returns the resolved groups with their `open` state and the ids of their columns. Group open state is not part of `getState()`, so persist it separately as above.

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

```ts
interface ColumnGroupDef<TRow = RowData> extends Partial< Record<Exclude<keyof ColumnDef<TRow>, 'header' | 'headerClass'>, never> >
```

| Property | Type | Description |
| --- | --- | --- |
| `groupId?` | `string` |  |
| `header` | `string` |  |
| `children` | `(ColumnDef<TRow> \| ColumnGroupDef<TRow>)[]` |  |
| `headerClass?` | `string` |  |
| `collapsible?` | `boolean` |  |
| `openByDefault?` | `boolean` |  |
| `id?` | `undefined` |  |
| `field?` | `undefined` |  |
| `headerTooltip?` | `undefined` |  |
| `type?` | `undefined` |  |
| `width?` | `undefined` |  |
| `minWidth?` | `undefined` |  |
| `maxWidth?` | `undefined` |  |
| `flex?` | `undefined` |  |
| `pinned?` | `undefined` |  |
| `hidden?` | `undefined` |  |
| `sortable?` | `undefined` |  |
| `resizable?` | `undefined` |  |
| `reorderable?` | `undefined` |  |
| `rowHeader?` | `undefined` |  |
| `filter?` | `undefined` |  |
| `editable?` | `undefined` |  |
| `editor?` | `undefined` |  |
| `options?` | `undefined` |  |
| `valueGetter?` | `undefined` |  |
| `valueSetter?` | `undefined` |  |
| `valueParser?` | `undefined` |  |
| `format?` | `undefined` |  |
| `cell?` | `undefined` |  |
| `cellClass?` | `undefined` |  |
| `align?` | `undefined` |  |
| `comparator?` | `undefined` |  |
| `aggFunc?` | `undefined` |  |
| `rowGroup?` | `undefined` |  |
| `rowGroupIndex?` | `undefined` |  |
| `pivot?` | `undefined` |  |
| `pivotIndex?` | `undefined` |  |
| `meta?` | `undefined` |  |
| `columnGroupShow?` | `undefined` |  |
| `autoHeight?` | `undefined` |  |
| `wrapText?` | `undefined` |  |
| `rowDrag?` | `undefined` |  |
| `sparkline?` | `undefined` |  |

## How it works

- The header gets one row per nesting level, and each group header cell spans its visible children.
- A collapsible group shows a toggle button in its header. Users can click it, or focus the header with the arrow keys and press <kbd>Enter</kbd> or <kbd>Space</kbd>.
- `setColumnGroupOpen()` fires `columnGroupOpened`, announces the change to screen readers and moves focus to a visible column if the focused one was hidden.

## Pitfalls

- **Give groups a `groupId`.** Without one the grid generates an id from the group's position, which changes when you reorder `columns`. Duplicate ids are renamed with a warning.
- **Groups have no column properties.** `ColumnGroupDef` only accepts `groupId`, `header`, `children`, `headerClass`, `collapsible` and `openByDefault`; TypeScript rejects `width` or `field` on a group.

## Related

- [Columns](https://docs.birchui.com/grid/columns.md) and [Column operations](https://docs.birchui.com/grid/column-operations.md).
- [Persist grid state](https://docs.birchui.com/recipes/grid-persist-state.md).
