# Context Menu

> ContextMenu opens a Menu family popup at the pointer on right-click, touch long-press, Shift+F10 or the ContextMenu key, with per-target entries, cancellable open and close, collision-aware placement, RTL and focus return.

Canonical: https://salmonui.dev/docs/navigation/context-menu

```tsx
import { ContextMenu, Menu, MenuItem, MenuSeparator, Submenu } from '@salmonui/buttons/menu';
import '@salmonui/buttons/menu/styles.css';

<ContextMenu
  menu={
    <Menu aria-label="Canvas actions">
      <MenuItem id="cut">Cut</MenuItem>
      <MenuItem id="copy">Copy</MenuItem>
      <MenuSeparator />
      <Submenu label="Arrange">
        <MenuItem id="front">Bring to front</MenuItem>
      </Submenu>
    </Menu>
  }
  onAction={(event) => run(event.id)}
>
  <div className="canvas" tabIndex={0}>…</div>
</ContextMenu>
```

`ContextMenu` lives in the Buttons Menu family (`@salmonui/buttons/menu`) and
reuses its list, submenus, hover intent, typeahead and styles; importing
`menu/styles.css` is enough.

## Target

The children are the target: `ContextMenu` wraps them in a
`div.salmon-context-menu` that takes `className`, `style` and DOM props
(`data-open` is set while the menu is open). To attach to an element it
does not wrap, pass `targetRef` and no children; it then renders only the
popup.

## Entries

`menu` takes a `<Menu>` element; its entries, `aria-label`,
`aria-labelledby`, `onAction`, `className` and `style` apply to the popup.
`menu` may also be the entries themselves, or use `items` (with
`renderItem`) for the data form. Entries are the Menu family's: `MenuItem`
(`id`, `icon`, `href`, `disabled`, any `ReactNode` children),
`MenuCheckboxItem`, `MenuRadioGroup`, `MenuGroup`, `MenuSeparator` and
`Submenu`. The application renders every entry, so
per-item customization is ordinary JSX. Without a name from the `Menu`, the popup is named by
`localeText.label` (`CONTEXT_MENU_DEFAULT_LOCALE_TEXT.label`, "Context
menu").

## Opening

- Right-click (`contextmenu`) anywhere in the target.
- Touch long-press: 500 ms, cancelled by moving more than 8 px or lifting
  the finger earlier. The browser's own long-press menu is suppressed.
- Shift+F10 and the ContextMenu key on a focused element inside the target;
  the menu opens at that element's start-bottom corner. Give a target that
  has no focusable content `tabIndex={0}`.
- `disabled` turns all of them off.

The menu opens at a virtual point anchor: the top-start corner of the menu
sits at the pointer, flips above it when there is no room below and shifts
to stay inside the viewport; under `dir="rtl"` the menu extends to the left
of the point and submenus open to the left. Focus moves to the
first item; Escape, Tab, an outside press or a chosen item close the menu,
and focus returns to the element that had it when the menu opened (the
target itself otherwise). A right-click inside an open menu never
shows the browser menu.

## Events

```tsx
const [selection, setSelection] = useState<string | null>(null);

<ContextMenu
  onBeforeOpen={(event) => {
    const row = event.target.closest('[data-row]');
    if (!row) return event.preventDefault(); // keep the browser menu
    setSelection(row.getAttribute('data-row'));
  }}
  onBeforeClose={(event) => {
    if (event.reason === 'outside' && unsaved) event.preventDefault();
  }}
  onOpenChange={(open, { reason, source }) => log(open, reason, source)}
  onAction={(event) => run(event.id, selection)}
  menu={<Menu>{selection ? <MenuItem id="delete">Delete {selection}</MenuItem> : null}</Menu>}
>
  …
</ContextMenu>
```

- `onBeforeOpen({ target, point, source })`: `target` is the element the
  event happened on, `point` the viewport point, `source` `'pointer'`,
  `'touch'` or `'keyboard'`. `preventDefault()` keeps the menu closed and
  lets the browser menu show; checking `event.target.closest(...)` there
  limits the menu to matching elements. Entries that depend on the target come from state the handler
  sets.
- `onBeforeClose({ reason, source })` is cancellable; `onOpenChange(open,
  { reason, source })` follows every change (reasons `trigger`, `escape`,
  `outside`, `action`, `tab`).
- `onAction(event)` reports the chosen item (`event.id`, `event.item` for
  the `items` form, `event.source`); `event.preventDefault()` keeps the
  menu open.

Event objects are only created when a handler is bound and are frozen in
development.

## Controlled

```tsx
<ContextMenu open={open} anchorPoint={{ x: 320, y: 200 }} onOpenChange={setOpen} items={items}>
  …
</ContextMenu>
```

`open` with `anchorPoint` (viewport px) opens and closes the menu from
application state. Without `anchorPoint` a controlled menu opens at the
pointer, or at the target's start-bottom corner when it was opened through
`open`.

## Submenus and long menus

`submenuOpen="click"` opens submenus on click (and keyboard) only;
`hoverDelay` sets the hover intent
(default 200 ms). Both props are also available on `Menu`,
`MenuButton` and `SplitButton`. A long menu caps its block size to the
viewport and scrolls; the keyboard keeps the focused item in view. Menus
are not virtualized: the Menu family's budgets cover 1,000 items; a long pickable list belongs in a Listbox.

## Changing entries

Imperative methods that enable, hide, insert, replace or remove entries are
not offered: the entries belong to the application, and methods
that mutate an internal copy would let the menu and the application state
disagree. Keep the entries in state that the `onBeforeOpen` handler sets and
the children render from (`disabled` on a `MenuItem`, conditional
rendering), as in the [Events](https://salmonui.dev/docs/navigation/context-menu#events) example.

## Keyboard and ARIA

The popup is the Menu family's APG menu (`role="menu"`, `menuitem`,
`menuitemcheckbox`, `menuitemradio`): ArrowDown / ArrowUp move between
entries, Home / End (or PageUp / PageDown) jump to the ends, typing a letter
moves to the next entry that starts with it, ArrowRight opens a submenu and
ArrowLeft closes it (mirrored under `dir="rtl"`), and Enter or Space
chooses the entry or opens its submenu. Escape closes the current submenu,
or the menu at the top level; Tab closes the whole menu. Focus then returns
to the element that opened it.

## Server rendering

The closed menu renders no markup: the server outputs only the target
`div.salmon-context-menu` and its children, and the popup mounts on the
client when the menu opens, so hydration reports no warnings.
`container` sets the element the popup portals into, and
`classNames.menu` / `styles.menu` reach the popup.

## API reference

`ContextMenu`, `CONTEXT_MENU_DEFAULT_LOCALE_TEXT` and the Menu family parts
are in [`@salmonui/buttons/menu`](https://salmonui.dev/docs/reference/buttons/menu).

### Live demo: Context Menu

Live demo: https://salmonui.dev/demos/navigation/context-menu-basics

A ContextMenu on a canvas whose entries change with the right-clicked shape, with a submenu, a disabled item and a vetoed target that keeps the browser menu.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { ContextMenu, Menu, MenuItem, MenuSeparator, Submenu } from '@salmonui/buttons/menu';

const SHAPE = {
  display: 'grid',
  placeItems: 'center',
  inlineSize: 72,
  blockSize: 72,
  fontSize: 'var(--salmon-font-size-sm)',
  color: 'var(--salmon-color-primary-text)',
  background: 'var(--salmon-color-primary-subtle)',
  border: '1px solid var(--salmon-color-primary-border)',
} as const;

export default function ContextMenuBasics() {
  const [shape, setShape] = useState<string | null>(null);
  const [last, setLast] = useState('nothing yet');
  return (
    <div>
      <ContextMenu
        tabIndex={0}
        role="group"
        aria-label="Canvas"
        style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 16, padding: 16, minBlockSize: 140, boxSizing: 'border-box', border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)' }}
        onBeforeOpen={(event) => {
          if (event.target.closest('[data-native]')) {
            event.preventDefault();
            return;
          }
          setShape(event.target.closest('[data-shape]')?.getAttribute('data-shape') ?? null);
        }}
        onAction={(event) => setLast(`${event.id} (${event.source})`)}
        menu={
          <Menu aria-label="Canvas actions">
            {shape ? <MenuItem id={`delete-${shape}`}>Delete {shape}</MenuItem> : null}
            <MenuItem id="cut">Cut</MenuItem>
            <MenuItem id="copy">Copy</MenuItem>
            <MenuItem id="paste" disabled>
              Paste
            </MenuItem>
            <MenuSeparator />
            <Submenu label="Arrange">
              <MenuItem id="front">Bring to front</MenuItem>
              <MenuItem id="back">Send to back</MenuItem>
            </Submenu>
          </Menu>
        }
      >
        <span data-shape="circle" style={{ ...SHAPE, borderRadius: '50%' }}>
          Circle
        </span>
        <span data-shape="square" style={{ ...SHAPE, borderRadius: 'var(--salmon-radius-sm)' }}>
          Square
        </span>
        <span data-native="" style={{ padding: '8px 12px', border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-md)', color: 'var(--salmon-text-secondary)' }}>
          Right-click here for the browser menu
        </span>
      </ContextMenu>
      <p className="demo-status">Right-click a shape or the empty canvas. Last action: {last}</p>
    </div>
  );
}
```

### Live demo: Context menu events

Live demo: https://salmonui.dev/demos/navigation/context-menu-events

A document context menu with rich MenuItem children, entries the application renders per state, onOpenChange and a cancellable onBeforeClose in a log, hover or click submenus with a hover delay, and a 60-entry submenu that scrolls.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { ContextMenu, Menu, MenuItem, MenuSeparator, Submenu, type MenuSubmenuOpen } from '@salmonui/buttons/menu';
import { Select } from '@salmonui/dropdowns/select';

const SUBMENU_OPEN = [
  { value: 'hover', label: 'hover' },
  { value: 'click', label: 'click' },
];
const HOVER_DELAYS = [
  { value: 0, label: '0 ms' },
  { value: 200, label: '200 ms' },
  { value: 800, label: '800 ms' },
];

const symbols = Array.from({ length: 60 }, (_, index) => String.fromCodePoint(0x2190 + index));

const KBD = { marginInlineStart: 'auto', font: 'inherit', fontSize: 'var(--salmon-font-size-sm)', color: 'var(--salmon-text-secondary)' } as const;

function Entry(props: { label: string; hint: string; shortcut?: string }) {
  return (
    <span style={{ display: 'flex', gap: 16, alignItems: 'baseline', inlineSize: '100%' }}>
      <span style={{ display: 'grid' }}>
        <span>{props.label}</span>
        <small style={{ color: 'var(--salmon-text-secondary)' }}>{props.hint}</small>
      </span>
      {props.shortcut ? <kbd style={KBD}>{props.shortcut}</kbd> : null}
    </span>
  );
}

export default function ContextMenuEventsDemo() {
  const [submenuOpen, setSubmenuOpen] = useState<MenuSubmenuOpen>('hover');
  const [hoverDelay, setHoverDelay] = useState(200);
  const [keepOpen, setKeepOpen] = useState(false);
  const [selection, setSelection] = useState(false);
  const [log, setLog] = useState<readonly string[]>([]);
  const add = (entry: string) => setLog((list) => [entry, ...list].slice(0, 6));
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Submenus open on{' '}
          <Select aria-label="Submenus open on" data={SUBMENU_OPEN} value={submenuOpen} onValueChange={(value) => value != null && setSubmenuOpen(value as MenuSubmenuOpen)} />
        </label>
        <label>
          Hover delay{' '}
          <Select aria-label="Hover delay" data={HOVER_DELAYS} value={hoverDelay} onValueChange={(value) => value != null && setHoverDelay(Number(value))} disabled={submenuOpen === 'click'} />
        </label>
        <Checkbox checked={selection} onCheckedChange={(checked) => setSelection(checked)}>
          Text selected
        </Checkbox>
        <Checkbox checked={keepOpen} onCheckedChange={(checked) => setKeepOpen(checked)}>
          Refuse outside close
        </Checkbox>
      </div>
      <ContextMenu
        tabIndex={0}
        role="group"
        aria-label="Document"
        style={{ padding: 16, minBlockSize: 120, border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)' }}
        submenuOpen={submenuOpen}
        hoverDelay={hoverDelay}
        onOpenChange={(open, event) => add(`${open ? 'opened' : 'closed'} (reason ${event.reason}, ${event.source})`)}
        onBeforeClose={(event) => {
          if (keepOpen && event.reason === 'outside') {
            event.preventDefault();
            add('onBeforeClose refused an outside press');
          }
        }}
        onAction={(event) => add(`action ${event.id}`)}
        menu={
          <Menu aria-label="Document actions">
            {/* The application decides which entries render (no beforeItemRender). */}
            {selection ? (
              <MenuItem id="cut" textValue="Cut">
                <Entry label="Cut" hint="Move the selection to the clipboard" shortcut="Ctrl+X" />
              </MenuItem>
            ) : null}
            {selection ? (
              <MenuItem id="copy" textValue="Copy">
                <Entry label="Copy" hint="Copy the selection" shortcut="Ctrl+C" />
              </MenuItem>
            ) : null}
            <MenuItem id="paste" textValue="Paste">
              <Entry label="Paste" hint="Insert the clipboard" shortcut="Ctrl+V" />
            </MenuItem>
            <MenuSeparator />
            <Submenu label="Format">
              <MenuItem id="bold">Bold</MenuItem>
              <MenuItem id="italic">Italic</MenuItem>
              <Submenu label="Case">
                <MenuItem id="upper">UPPERCASE</MenuItem>
                <MenuItem id="lower">lowercase</MenuItem>
              </Submenu>
            </Submenu>
            <Submenu label="Insert symbol">
              {symbols.map((symbol) => (
                <MenuItem key={symbol} id={`symbol-${symbol}`} textValue={`U+${symbol.codePointAt(0)!.toString(16).toUpperCase()}`}>
                  {symbol} U+{symbol.codePointAt(0)!.toString(16).toUpperCase()}
                </MenuItem>
              ))}
            </Submenu>
          </Menu>
        }
      >
        Right-click here, long-press on touch, or focus this box and press Shift+F10.
      </ContextMenu>
      <div className="demo-log" aria-live="polite">
        {log.length ? (
          <ol>
            {log.map((entry, index) => (
              <li key={`${index}-${entry}`}>{entry}</li>
            ))}
          </ol>
        ) : (
          'Events appear here.'
        )}
      </div>
    </div>
  );
}
```

### Live demo: Controlled context menu

Live demo: https://salmonui.dev/demos/navigation/context-menu-controlled

A context menu whose open state lives in the application, opened from code at an anchorPoint or by right-click at the pointer, with collision-aware placement and a right-to-left switch that mirrors the menu and its submenu.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { ContextMenu, Menu, MenuItem, Submenu, type ContextMenuPoint } from '@salmonui/buttons/menu';

export default function ContextMenuControlledDemo() {
  const [open, setOpen] = useState(false);
  const [anchorPoint, setAnchorPoint] = useState<ContextMenuPoint | undefined>(undefined);
  const [rtl, setRtl] = useState(false);
  const [last, setLast] = useState('nothing yet');
  return (
    <div dir={rtl ? 'rtl' : 'ltr'}>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={(event) => {
            // Open from code at the button's corner (viewport coordinates).
            const rect = event.currentTarget.getBoundingClientRect();
            setAnchorPoint({ x: rtl ? rect.right : rect.left, y: rect.bottom });
            setOpen(true);
          }}
        >
          Open from code
        </Button>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left
        </Checkbox>
        {/* English status text keeps its own direction inside the mirrored demo. */}
        <span dir="ltr">
          open = <output>{String(open)}</output>
        </span>
      </div>
      <ContextMenu
        tabIndex={0}
        role="group"
        aria-label="Board"
        style={{ display: 'grid', placeItems: 'end', padding: 16, minBlockSize: 200, border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-lg)' }}
        open={open}
        anchorPoint={anchorPoint}
        onBeforeOpen={() => setAnchorPoint(undefined)}
        onOpenChange={(next, event) => {
          setOpen(next);
          setLast(`${next ? 'opened' : 'closed'} (${event.reason})`);
        }}
        onAction={(event) => setLast(`action ${event.id}`)}
        menu={
          <Menu aria-label="Board actions">
            <MenuItem id="add-card">Add card</MenuItem>
            <MenuItem id="add-list">Add list</MenuItem>
            <Submenu label="Move board">
              <MenuItem id="move-top">To the top</MenuItem>
              <MenuItem id="move-archive">To the archive</MenuItem>
            </Submenu>
            <MenuItem id="close" onAction={() => setOpen(false)}>
              Close menu
            </MenuItem>
          </Menu>
        }
      >
        <span>Right-click near this corner of the page</span>
      </ContextMenu>
      <p className="demo-status" dir="ltr">
        Last change: <output>{last}</output>
      </p>
    </div>
  );
}
```
