# Context menu

> A right-click and Shift+F10 menu for headers, cells, rows, group captions and the pager, with built-in and custom items and per-target control.

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

`contextMenu` replaces the browser menu inside the grid. `contextMenu={true}`
shows a default menu per target: auto-size, group, sort and pin items on
headers; edit, copy and export items on cells; page items on the pager.

## Items

An array lists the items in order for every target: built-in ids
and custom `DataGridMenuItem` objects.

- Columns: `autoSize`, `autoSizeAll`, `sortAscending`, `sortDescending`,
  `group`, `ungroup`, `pinStart`, `pinEnd`, `unpin`.
- Rows: `edit`, `delete`, `save`, `cancel`, `copy`.
- Export: `exportExcel`, `exportPdf`, `exportCsv`.
- Pager: `firstPage`, `previousPage`, `nextPage`, `lastPage` (need `paging`).

Built-ins that cannot apply to the target are dropped, for example `edit`,
`delete` and `copy` on a header or the pager, and sort and pin items on the
pager. Page items apply to every target while paging is on; the demo keeps
them on the pager through `onBeforeContextMenuOpen`. Custom items take the
same fields as column menu items (`id`, `label`, `icon`, `disabled`,
`targets`, `href`), with nested `items` for submenus. A submenu
opens when the pointer rests on its item for a moment (200 ms hover
intent) and closes when the pointer rests on a sibling; crossing a sibling
on the way into the submenu keeps it open. From the keyboard, ArrowRight
opens it (ArrowLeft in RTL) and ArrowLeft or Escape closes it.

Edit, copy and export items run UI commands. Without a handler for the
command (`api.registerCommandHandler`) or a module that declares it, the item
is disabled and its tooltip says which feature is missing.

## Targets and events

The menu opens for a header, a cell, a row, a group caption or the pager.
`onBeforeContextMenuOpen` receives that target as a descriptor
(`{ kind: 'cell', rowId, field }`, `{ kind: 'header', field }`, ...) and a
mutable copy of the items: edit `event.items` in place (`splice`,
`push`) to change the menu for this target (the event object is frozen in
development, so never reassign `event.items`), or call `preventDefault()` to keep it closed.
`onBeforeContextMenuClose` can keep it open.

`onContextMenuItemClick` reports the item, the target and `rowIds`: the
target row, or the whole selection when the target row is selected, with
`rows()` to read the row objects. `preventDefault()` skips the built-in
action. `renderContextMenu` replaces the menu and receives the `target`,
the resolved `items`, the `defaultMenu` element and `close()`.

The target is resolved from the row and column ids of the clicked element,
so the menu works the same on virtualized rows and pinned columns.
Shift+F10 and the ContextMenu key open it for the focused cell, header or
group caption, and on a focused pager button for the `pager` target;
Escape closes it and returns focus to that element.

### Live demo: Context menu

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

Right-click (or Shift+F10) a header, cell or the pager over 5,000 rows with a pinned column; the default per-target menus or a custom list with built-ins, a submenu and a custom action; per-target items and cancelation in `onBeforeContextMenuOpen`; disabled export items with a reason.

`Demo.tsx`:

```tsx
'use client';

import { useCallback, useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import {
  DataGrid,
  type DataGridApi,
  type DataGridColumn,
  type DataGridContextMenuItemId,
  type DataGridContextMenuTarget,
  type DataGridMenuItem,
  type DataGridPaging,
  type DataGridSelection,
} from '@salmonui/data-grid';
import type { RowId } from '@salmonui/core/data';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(5_000, 29);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, pinned: 'start' },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'priority', header: 'Priority', width: 100 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
];

const paging: DataGridPaging = { pageSize: 500 };
const selection: DataGridSelection = { multiple: true };

// One list for every target: items that do not apply to the target are dropped
// (sort items on cells, page items off the pager, ...).
const customMenu: readonly (DataGridContextMenuItemId | DataGridMenuItem)[] = [
  'sortAscending',
  'sortDescending',
  'pinStart',
  'unpin',
  { id: 'separator-1', separator: true },
  'copy',
  'exportCsv',
  'exportPdf',
  { id: 'separator-2', separator: true },
  { id: 'flag', label: 'Flag or unflag rows', icon: '⚑' },
  {
    id: 'more',
    label: 'More',
    items: [
      { id: 'logTarget', label: 'Log the target' },
      { id: 'logRows', label: 'Log the customers' },
    ],
  },
  'firstPage',
  'previousPage',
  'nextPage',
  'lastPage',
];

function describeTarget(target: DataGridContextMenuTarget): string {
  switch (target.kind) {
    case 'header':
      return `header ${target.field}`;
    case 'cell':
      return `cell ${String(target.rowId)} / ${target.field}`;
    case 'row':
    case 'groupCaption':
      return `${target.kind} ${String(target.rowId)}`;
    case 'pager':
      return 'pager';
  }
}

export default function ContextMenuDemo() {
  const [useCustom, setUseCustom] = useState(true);
  const [blockHeader, setBlockHeader] = useState(false);
  const [flagged, setFlagged] = useState<ReadonlySet<RowId>>(() => new Set());
  const [log, push] = useEventLog();
  // A stable identity per flag set: an inline function would re-render every cell on each log entry.
  const rowClassName = useCallback((row: Order) => (flagged.has(row.id) ? 'demo-row--flagged' : undefined), [flagged]);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={useCustom} onCheckedChange={(checked) => setUseCustom(checked)}>
          Custom item list (off: the default menu per target)
        </Checkbox>
        <Checkbox checked={blockHeader} onCheckedChange={(checked) => setBlockHeader(checked)}>
          Cancel the menu on headers
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a context menu"
        data={orders}
        columns={columns}
        contextMenu={useCustom ? customMenu : true}
        sorting
        paging={paging}
        selection={selection}
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        rowClassName={rowClassName}
        onReady={(api: DataGridApi<Order>) => {
          // Export items are disabled with a reason until a handler serves the command.
          api.registerCommandHandler('export.csv', () => {
            push('export.csv handler ran');
            return true;
          });
        }}
        onBeforeContextMenuOpen={(event) => {
          if (blockHeader && event.target.kind === 'header') {
            event.preventDefault();
            push(`menu canceled on ${describeTarget(event.target)}`);
            return;
          }
          // Per-target items: page items only on the pager, row items only on rows and cells.
          const onRows = event.target.kind === 'cell' || event.target.kind === 'row';
          const pageItems = new Set(['firstPage', 'previousPage', 'nextPage', 'lastPage']);
          // The event object is frozen in development: edit its items array in place, never reassign it.
          const items = event.items;
          for (let i = items.length - 1; i >= 0; i--) {
            const id = items[i]?.id ?? '';
            if (pageItems.has(id) ? event.target.kind !== 'pager' : (id === 'flag' || id === 'more') && !onRows) items.splice(i, 1);
          }
          push(`menu open (${event.source}): ${describeTarget(event.target)}, ${event.items.filter((item) => !item.separator).length} items`);
        }}
        onContextMenuItemClick={(event) => {
          push(`click (${event.source}): ${event.item.id} on ${describeTarget(event.target)}, ${event.rowIds.length} row(s)`);
          if (event.item.id === 'flag') {
            const next = new Set(flagged);
            for (const id of event.rowIds) {
              if (next.has(id)) next.delete(id);
              else next.add(id);
            }
            setFlagged(next);
          }
          if (event.item.id === 'logRows') push(`customers: ${event.rows().map((row) => row.customer).join(', ') || '-'}`);
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridContextMenuItemId`](https://salmonui.dev/docs/reference/data-grid/DataGridContextMenuItemId)
lists the built-in ids, [`DataGridMenuItem`](https://salmonui.dev/docs/reference/data-grid/DataGridMenuItem)
the custom item fields and
[`DataGridContextMenuTarget`](https://salmonui.dev/docs/reference/data-grid/DataGridContextMenuTarget)
the target descriptors;
[`DataGridContextMenuOpenEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridContextMenuOpenEvent)
and [`DataGridContextMenuItemClickEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridContextMenuItemClickEvent)
are the event payloads.
