# Context menu

A menu that opens where the user right-clicks, or at the focused element with Shift+F10 or the ContextMenu key. It takes the same items as the Menu, and passes the thing it opened on to each item's callback.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `[vigContextMenu]`
- Source: [libs/ui/src/lib/organisms/menu/context-menu.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/menu/context-menu.ts)

```typescript title="Import"
import { ContextMenu } from '@vigdx/ui/menu';
```

## Basic

Bind the entries to `vigContextMenu` and the object they act on to `vigContextMenuData`; each item's `run` receives it, typed. The menu opens at the pointer, flips and stays inside the viewport, and closing it returns focus to where it was.

```typescript title="context-menu-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { ContextMenu, type MenuItem } from '@vigdx/ui/menu';

interface Note {
  title: string;
}

@Component({
  selector: 'app-context-menu-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ContextMenu],
  template: `
    <div class="flex flex-col gap-3">
      <div
        tabindex="0"
        class="grid h-32 w-72 place-items-center rounded-card border border-dashed border-border-strong text-sm text-muted-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
        [vigContextMenu]="actions"
        [vigContextMenuData]="note"
      >
        Right-click, or focus and press Shift+F10
      </div>
      <span class="text-sm text-muted-foreground" aria-live="polite">{{ last() }}</span>
    </div>
  `,
})
export class ContextMenuBasicDemo {
  protected readonly note: Note = { title: 'Meeting notes' };
  protected readonly last = signal('');

  // `run` receives `vigContextMenuData`, typed.
  protected readonly actions: (MenuItem<Note> | 'separator')[] = [
    { label: 'Open', shortcut: 'Enter', run: (note) => this.last.set(`Opened ${note.title}`) },
    { label: 'Share', items: [{ label: 'Copy link' }, { label: 'Email' }] },
    'separator',
    { label: 'Delete', danger: true, run: (note) => this.last.set(`Deleted ${note.title}`) },
  ];
}
```

## Table rows

On a `vig-table`, `run` receives the row the menu opened on, by pointer or by Shift+F10 on a control in the row. Outside the rows, the browser's own menu shows. The compiler cannot tie the directive's data type to the table's row type, so type the items with the row type yourself, `MenuItem<FileRow>[]`.

```typescript title="context-menu-table.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { ContextMenu, type MenuItem } from '@vigdx/ui/menu';
import { Table, TableColumn } from '@vigdx/ui/table';

interface FileRow {
  id: number;
  name: string;
  size: string;
}

@Component({
  selector: 'app-context-menu-table',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ContextMenu, Table, TableColumn],
  template: `
    <div class="flex w-full flex-col gap-3">
      <vig-table
        caption="Files"
        [items]="files()"
        [rowId]="rowId"
        selectionMode="multiple"
        [vigContextMenu]="actions"
      >
        <vig-col field="name" header="Name" [rowHeader]="true" />
        <vig-col field="size" header="Size" align="end" />
      </vig-table>
      <span class="text-sm text-muted-foreground" aria-live="polite">{{ last() }}</span>
    </div>
  `,
})
export class ContextMenuTableDemo {
  protected readonly files = signal<FileRow[]>([
    { id: 1, name: 'report.pdf', size: '1.2 MB' },
    { id: 2, name: 'notes.txt', size: '4 KB' },
    { id: 3, name: 'photo.jpg', size: '3.4 MB' },
  ]);
  protected readonly rowId = (file: FileRow) => file.id;
  protected readonly last = signal('');

  // On a table, `run` receives the row the menu opened on.
  protected readonly actions: (MenuItem<FileRow> | 'separator')[] = [
    { label: 'Open', run: (file) => this.last.set(`Opened ${file.name}`) },
    { label: 'Duplicate', run: (file) => this.duplicate(file) },
    'separator',
    { label: 'Delete', danger: true, run: (file) => this.remove(file) },
  ];

  private duplicate(file: FileRow): void {
    this.files.update((list) => [
      ...list,
      { ...file, id: Math.max(...list.map((f) => f.id)) + 1, name: `Copy of ${file.name}` },
    ]);
    this.last.set(`Duplicated ${file.name}`);
  }

  private remove(file: FileRow): void {
    this.files.update((list) => list.filter((f) => f.id !== file.id));
    this.last.set(`Deleted ${file.name}`);
  }
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="menu"][data-part="panel"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="menu"]`

| Part | Element | data-state |
| --- | --- | --- |
| `panel` | A `role="menu"` panel (also each submenu), in the overlay container. |   |
| `item` | A menu item, `<a>` or `<button>`: `open`/`closed` with a submenu, `checked`/`unchecked` when checkable. | `open, closed, checked, unchecked` |
| `icon` | The item icon. |   |
| `label` | The item text. |   |
| `indicator` | The check mark or radio dot of a checkable item. |   |
| `shortcut` | The `<kbd>` of an item's `shortcut`. |   |
| `submenu-indicator` | The chevron of an item that opens a submenu. |   |
| `group` | A `role="group"` of items sharing a `group` heading. |   |
| `group-heading` | The heading of a group. |   |
| `separator` | A separator `<hr>`. |   |

| Attribute | Meaning |
| --- | --- |
| `data-opening` | On the overlay element (panel or `<dialog>`) while its entrance transition plays; removed once it settles (2s at most). Style the entrance with `data-opening:` utilities. |
| `data-closing` | On the overlay element while its exit transition plays, before it closes; removed once it settles (2s at most). Style the closed look with `data-closing:` utilities. |

## Accessibility

- A context menu is a shortcut that many users never find: keep its actions available elsewhere too, for example in a row's actions menu.
- Shift+F10 and the ContextMenu key open it at the focused element with the first item focused. A right-click focuses the menu itself, where the arrow keys start. The menu is a `role="menu"` named by `vigContextMenuLabels.ariaLabel` (“Context menu” by default).
- Inside, it works as the Menu: arrow keys, typeahead, submenus mirrored in right-to-left pages, checkbox and radio items. Escape and activating an item close it and return focus to the element that had it; Tab closes it too.
- It listens on its own element only. Where it has no items (an empty list, or a table's header) the browser's own menu shows; a nested `[vigContextMenu]` wins over an outer one.

## API

### ContextMenu

Selector: `[vigContextMenu]` · Kind: directive

Opens a menu at the pointer on right-click (`contextmenu`), and at the focused element on Shift+F10 or the ContextMenu key. Its items are the same as `vig-menu`'s, with submenus, groups and checkable items; `run` receives `vigContextMenuData`. On a `vig-table`, `run` receives the row the menu opened on, and the page's own menu shows outside the rows. Closing returns focus to where it was. Listens on its own host only.

On a table, `T` is not tied to the table's row type by the compiler (a directive cannot read its host component's type parameter): type the items with the table's row type, `MenuItem<Row>[]`, and they match.

A context menu is a shortcut: keep its actions reachable elsewhere too, e.g. in a row's `vig-menu`.

**Example :**

```html
<vig-table [items]="files" [vigContextMenu]="fileActions">…</vig-table>
<li [vigContextMenu]="actions" [vigContextMenuData]="file">…</li>
```

While it plays its entrance or exit transition, the animating element carries `data-opening` or `data-closing` (stable hooks for styling and for waiting in tests; see the theming guide). panel item icon label shortcut indicator submenu-indicator separator group group-heading menu open closed checked unchecked data-opening data-closing

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigContextMenu` | `readonly (MenuItem<T> \| 'separator')[]` | `[]` | The menu's entries; empty opens nothing (the page's own menu shows). |
| `vigContextMenuData` | `T` | — | Passed to each item's `run`, e.g. the record the host shows. |
| `vigContextMenuLabels` | `Partial<ContextMenuLabels>` | — | Texts of the menu (i18n); locale defaults. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `vigContextMenuCheckedChange` | `MenuCheckedChange<T>` | A checkbox or radio item was activated: update its `checked`. |
| `vigContextMenuSelected` | `MenuItem<T>` | Emitted when an item is activated (its `command` and `run` also run). |

#### Methods

| Signature | Description |
| --- | --- |
| `close(): void` | Closes the menu; focus returns to where it was before it opened. |
