# Column menu

> A per-header menu with built-in sort, filter, group, auto-size, pin and chooser items, custom items and submenus, per-column items and keyboard access.

Canonical: https://salmonui.dev/docs/data-grid/column-menu

`columnMenu` adds a menu button to every header. A column opts out with `menu: false`.

## Items

`columnMenu={true}` shows the default menu. An array lists the items in
order: built-in ids and custom `DataGridMenuItem` objects.
`autoSizeAll` fits every visible column to its header and rendered cells
in one step, like `api.autoSizeColumns()`
with no argument.

| Id | Action |
| --- | --- |
| `autoSizeAll`, `autoSize` | Fit every column, or this column, to its content; `autoSize` needs a resizable column (grid `resizable`) |
| `group`, `ungroup` | Group or ungroup by this column (needs `grouping`) |
| `sortAscending`, `sortDescending`, `clearSort` | Sort this column (needs `sorting`); `clearSort` is a Salmon UI addition |
| `filter` | Open this column's filter menu (needs `filtering`) |
| `columnChooser` | Open the column chooser |
| `pinStart`, `pinEnd`, `unpin` | Pin or unpin this column (Salmon UI addition) |

Built-in items that do not apply are left out (no sort items on a column
that cannot sort, no group items without grouping), and the item that
matches the current state, such as Sort ascending on an ascending column, is
disabled.

A custom item has an `id`, a `label` and optionally an `icon`, `disabled`
with a `disabledReason` tooltip, `checked` (rendered as a menu checkbox),
`href` to render a link, `render` for custom content, `separator: true`, or
nested `items` for a submenu.

## Events

`onBeforeColumnMenuOpen` receives the column and a mutable copy of its
items: edit `event.items` in place (`splice`, `push`, assign by
index) to hide, add or update items for that column; the event object is
frozen in development, so never reassign `event.items`. Call
`preventDefault()` to keep the menu closed.
`onBeforeColumnMenuClose` can keep it open. `onColumnMenuItemClick` reports
every built-in and custom item with the column; `preventDefault()` skips the
built-in action. `renderColumnMenu` replaces the menu and receives the
resolved items, the default menu element and `close()`.

## Keyboard

On a focused header, Shift+Alt+ArrowDown opens the menu (Alt+ArrowDown too,
when the column has no filter button). Arrow keys move between items,
ArrowRight and ArrowLeft open and close submenus, and Escape closes the menu
and returns focus to the header.

### Live demo: Column menu

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

The header menu with every built-in item (sort, clear sort, filter, group, auto-size, pin, column chooser) in a custom order, a checkbox item and a submenu, per-column items through `onBeforeColumnMenuOpen`, `column.menu: false`, and `onColumnMenuItemClick`.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridColumn, type DataGridColumnMenuItemId, type DataGridFiltering, type DataGridMenuItem } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(2_000, 11);

const columns: DataGridColumn<Order>[] = [
  // `menu: false` opts this header out of the column menu.
  { field: 'id', header: 'Order', primaryKey: true, width: 110, menu: false },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 140 },
  { field: 'category', header: 'Category', width: 140 },
  { field: 'priority', header: 'Priority', width: 130 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 130 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
];

const filtering: DataGridFiltering = { ui: 'menu' };

export default function ColumnMenuDemo() {
  const [customItems, setCustomItems] = useState(true);
  const [highlighted, setHighlighted] = useState<string | null>(null);
  const [log, push] = useEventLog();
  // Built-in ids in a custom order, plus custom items: a checkbox item and a submenu.
  const columnMenu: readonly (DataGridColumnMenuItemId | DataGridMenuItem)[] = [
    'sortAscending',
    'sortDescending',
    'clearSort',
    { id: 'separator-1', separator: true },
    'filter',
    'group',
    'ungroup',
    { id: 'separator-2', separator: true },
    'autoSize',
    'autoSizeAll',
    'pinStart',
    'pinEnd',
    'unpin',
    'columnChooser',
    { id: 'separator-3', separator: true },
    { id: 'highlight', label: 'Highlight column', checked: false },
    {
      id: 'more',
      label: 'More',
      items: [
        { id: 'logField', label: 'Log the column id' },
        { id: 'docs', label: 'Columns guide', href: '/docs/data-grid/columns' },
      ],
    },
  ];
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={customItems} onCheckedChange={(checked) => setCustomItems(checked)}>
          Custom item list (off: the default menu)
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a column menu"
        data={orders}
        columns={columns}
        getCellProps={(ctx) => (ctx.field === highlighted ? { className: 'demo-cell--highlight' } : undefined)}
        columnMenu={customItems ? columnMenu : true}
        sorting
        filtering={filtering}
        grouping
        resizable
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        onBeforeColumnMenuOpen={(event) => {
          // Per-column items: the Amount column cannot be grouped, and the checkbox item reflects state.
          // The event object is read-only (frozen in development); its items array is the mutable copy.
          const items = event.items;
          if (event.field === 'amount') for (let i = items.length - 1; i >= 0; i--) if (items[i]?.id === 'group' || items[i]?.id === 'ungroup') items.splice(i, 1);
          items.forEach((item, i) => {
            if (item.id === 'highlight') items[i] = { ...item, checked: highlighted === event.field };
          });
          push(`menu open (${event.source}): ${event.field}, ${event.items.filter((item) => !item.separator).length} items`);
        }}
        onColumnMenuItemClick={(event) => {
          push(`menu click (${event.source}): ${event.item.id} on ${event.field}`);
          if (event.item.id === 'highlight') setHighlighted((current) => (current === event.field ? null : event.field));
          if (event.item.id === 'logField') push(`column id: ${event.column.id}`);
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridColumnMenuItemId`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnMenuItemId)
lists the built-in ids and [`DataGridMenuItem`](https://salmonui.dev/docs/reference/data-grid/DataGridMenuItem)
the custom item fields;
[`DataGridColumnMenuOpenEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnMenuOpenEvent),
[`DataGridColumnMenuItemClickEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnMenuItemClickEvent)
and [`DataGridColumnMenuContext`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnMenuContext)
are the event and render payloads.
