# Command menu

A Cmd+K / Ctrl+K palette: a search field over a list of commands in a modal dialog. Typing filters the commands; Enter runs one. Use it to jump to any page and to reach actions without the mouse.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-command-menu`, `ng-template[vigCommandMenuItem]`
- Source: [libs/ui/src/lib/organisms/command-menu/command-menu.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/command-menu/command-menu.ts)

```typescript title="Import"
import { CommandMenu, CommandMenuItemTemplate } from '@vigdx/ui/command-menu';
```

## Basic

Pass `[commands]`: `{ id, label, run }` plus an optional `group`, `keywords`, `icon`, `shortcut` (shown, not bound) and `disabled`. Matches on the label come first, then keyword matches. Open it with `[(open)]` or the `shortcut` (`mod+k` by default).

```typescript title="command-menu-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { CommandMenu, type CommandItem } from '@vigdx/ui/command-menu';

@Component({
  selector: 'app-command-menu-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, CommandMenu],
  template: `
    <div class="flex flex-wrap items-center gap-3">
      <vig-button label="Open command menu" variant="secondary" (click)="open.set(true)" />
      <span class="text-sm text-muted-foreground">Last command: {{ last() }}</span>
    </div>
    <!-- On this site Ctrl K opens the site search, so the demo has no shortcut. -->
    <vig-command-menu [(open)]="open" [commands]="commands" [shortcut]="false" />
  `,
  host: { class: 'flex flex-col gap-3' },
})
export class CommandMenuBasicDemo {
  protected readonly open = signal(false);
  protected readonly last = signal('none');

  protected readonly commands: CommandItem[] = [
    this.command('new-invoice', 'New invoice', 'Create', 'plus', ['bill'], 'Ctrl I'),
    this.command('new-customer', 'New customer', 'Create', 'user', ['client']),
    this.command('dashboard', 'Dashboard', 'Go to', 'home', ['overview']),
    this.command('inbox', 'Inbox', 'Go to', 'inbox', ['messages']),
    this.command('export', 'Export to CSV', 'Data', 'download', ['spreadsheet']),
    { ...this.command('archive', 'Archive 2024', 'Data', 'file'), disabled: true },
  ];

  private command(
    id: string,
    label: string,
    group: string,
    icon: string,
    keywords: string[] = [],
    shortcut?: string,
  ): CommandItem {
    return { id, label, group, icon, keywords, shortcut, run: () => this.last.set(label) };
  }
}
```

## The keyboard shortcut

`shortcut` takes a combination such as `mod+k` (⌘K on Apple platforms, Ctrl K elsewhere) or `mod+shift+p`; `false` turns it off. Every menu shares one document listener, added with the first and removed with the last. Combinations with Ctrl, ⌘ or Alt work while typing in a field; a plain key such as `/` does not. Pressing it again closes the menu. Name it on the button that opens the menu:

```html
<button type="button" aria-haspopup="dialog" aria-keyshortcuts="Control+K Meta+K"
        (click)="menuOpen.set(true)">Search <kbd aria-hidden="true">Ctrl K</kbd></button>
<vig-command-menu [(open)]="menuOpen" [commands]="commands()" />
```

## Server results and recent commands

`search` receives the query and an `AbortSignal` and returns the commands to add after the local matches. It runs once typing pauses (`searchDebounce`, 250 ms) and the signal aborts when the query changes. `recent` lists ids of `commands` to show first while the field is empty; record them from `(executed)`.

```typescript title="command-menu-async.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { CommandMenu, type CommandItem, type CommandSearch } from '@vigdx/ui/command-menu';

const PEOPLE = ['Ada Lovelace', 'Grace Hopper', 'Katherine Johnson', 'Mary Jackson'];

@Component({
  selector: 'app-command-menu-async',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, CommandMenu],
  template: `
    <div class="flex flex-wrap items-center gap-3">
      <vig-button label="Search people" variant="secondary" (click)="open.set(true)" />
      <span class="text-sm text-muted-foreground">Recent: {{ recent().join(', ') || 'none' }}</span>
    </div>
    <vig-command-menu
      [(open)]="open"
      [commands]="commands"
      [search]="searchPeople"
      [recent]="recent()"
      [shortcut]="false"
      (executed)="remember($event)"
    />
  `,
  host: { class: 'flex flex-col gap-3' },
})
export class CommandMenuAsyncDemo {
  protected readonly open = signal(false);
  /** Ids of the last commands run, newest first; an app would keep them in storage. */
  protected readonly recent = signal<string[]>([]);

  protected readonly commands: CommandItem[] = [
    { id: 'settings', label: 'Settings', group: 'Go to', icon: 'filter', run: () => undefined },
    { id: 'reports', label: 'Reports', group: 'Go to', icon: 'calendar', run: () => undefined },
  ];

  /** A stand-in for `fetch(url, { signal })`: answers after 400 ms unless aborted. */
  protected readonly searchPeople: CommandSearch = (query, signal) =>
    new Promise((resolve, reject) => {
      const timer = setTimeout(
        () =>
          resolve(
            PEOPLE.filter((name) => name.toLowerCase().includes(query.toLowerCase())).map(
              (name): CommandItem => ({
                id: `person:${name}`,
                label: name,
                group: 'People',
                icon: 'user',
                run: () => undefined,
              }),
            ),
          ),
        400,
      );
      signal.addEventListener('abort', () => {
        clearTimeout(timer);
        reject(signal.reason);
      });
    });

  protected remember(command: CommandItem): void {
    this.recent.update((ids) => [command.id, ...ids.filter((id) => id !== command.id)].slice(0, 3));
  }
}
```

## Custom rows

A `vigCommandMenuItem` template renders the inside of each row, with the command as `let-command` and `let-active`. The row itself, an option of the list, stays the kit's. `size` sets the width: `sm`, `md` or `lg` (default).

```typescript title="command-menu-template.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Button } from '@vigdx/ui/button';
import { CommandMenu, CommandMenuItemTemplate, type CommandItem } from '@vigdx/ui/command-menu';
import { Icon } from '@vigdx/ui/icon';

@Component({
  selector: 'app-command-menu-template',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, CommandMenu, CommandMenuItemTemplate, Icon],
  template: `
    <vig-button label="Open with custom rows" variant="secondary" (click)="open.set(true)" />
    <vig-command-menu [(open)]="open" [commands]="commands" [shortcut]="false" size="md">
      <ng-template vigCommandMenuItem let-command let-active="active">
        <vig-icon [name]="command.icon ?? 'file'" class="text-[1.25em] text-muted-foreground" />
        <span class="flex min-w-0 flex-1 flex-col">
          <span class="truncate">{{ command.label }}</span>
          <span class="truncate text-xs text-foreground-soft">{{ command.keywords?.[0] }}</span>
        </span>
        @if (active) {
          <span aria-hidden="true" class="text-xs text-foreground-soft">Enter</span>
        }
      </ng-template>
    </vig-command-menu>
  `,
})
export class CommandMenuTemplateDemo {
  protected readonly open = signal(false);
  protected readonly commands: CommandItem[] = [
    {
      id: 'theme',
      label: 'Switch theme',
      icon: 'eye',
      keywords: ['Light, dark or system'],
      run: () => undefined,
    },
    {
      id: 'language',
      label: 'Change language',
      icon: 'user',
      keywords: ['English or Türkçe'],
      run: () => undefined,
    },
  ];
}
```

## Customize

The width follows the dialog tokens (`--container-dialog-sm`, `-md`, `-lg`) and the corners `--radius-dialog`. For layout tweaks, select a part by scope and name, e.g. `[data-scope="command-menu"][data-part="item"][data-state="active"]`; the styling hooks below list them all.

The [App shell recipe](https://vigdx.com/recipes/app-shell.md) puts the menu together with a sidebar, a top bar and stored recent commands.

## 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="command-menu"][data-part="dialog"] { … }`: 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="command-menu"]`

| Part | Element | data-state |
| --- | --- | --- |
| `dialog` | The native `<dialog>`; style the backdrop with `::backdrop`. | `open, closed` |
| `search` | The row of the search icon and the field. |   |
| `input` | The `role="combobox"` field. |   |
| `list` | The `role="listbox"`. |   |
| `group` | A group of commands (`role="group"`; `presentation` for ungrouped ones). |   |
| `group-heading` | The heading of a named group. |   |
| `item` | A `role="option"` row. | `active, inactive` |
| `item-icon` | The `vig-icon` of a command. |   |
| `item-label` | The label of a command. |   |
| `item-shortcut` | The `<kbd>` of a command's `shortcut`. |   |
| `empty` | The text shown when nothing matches (`emptyLabel`). |   |
| `loading` | The loading text (`loadingLabel`). |   |
| `error` | The text shown when `search` failed (`errorLabel`). |   |
| `status` | The visually hidden live region. |   |

| 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 native modal `<dialog>`: the page behind is inert, focus starts in the field and returns to where it was on close. Escape and a backdrop click (`closeOnBackdropClick`) close it.
- Follows the APG combobox pattern: the field is a `combobox` controlling a `listbox` of options grouped by heading. Focus stays in the field; Arrow Up and Down move the active option (`aria-activedescendant`), wrapping and skipping disabled ones, Home and End jump to the ends, Enter runs it.
- While an input method editor composes text (Japanese, Chinese, Korean), Enter and the arrows belong to it, including Safari's late confirming Enter.
- The number of results is announced politely once typing pauses, from a live region inside the dialog; loading states are shown but not announced.
- Matching is locale-aware and ignores case and accents: in Turkish `istanbul` finds `İstanbul`.
- Every text is a key of the typed `labels` input (`ariaLabel`, `inputAriaLabel`, `placeholder`, `emptyLabel`, `resultsAnnouncement`…), over the locale defaults.

## API

### CommandMenu

Selector: `vig-command-menu` · Kind: component

Command palette (Cmd+K / Ctrl+K): a search field with combobox semantics over a listbox of commands, in a native modal `<dialog>`, following the APG combobox pattern. Typing filters `commands` (label first, then keywords, locale-aware); Arrow keys move the active command, Enter runs it and closes the menu, Escape closes it, and focus returns to where it was.

**Example :**

```html
<vig-command-menu [commands]="commands" (executed)="remember($event)" />
```

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). data-opening data-closing

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `closeOnBackdropClick` | `boolean` | `true` | Close when the backdrop is clicked. Escape always closes. |
| `commands` | `readonly CommandItem[]` | `[]` | The commands, filtered as the user types. |
| `labels` | `Partial<CommandMenuLabels>` | — | Texts of the field, list and status (i18n); locale defaults. |
| `loading` | `boolean` | `false` | Shows the loading state, e.g. while `commands` load. |
| `open` (model) | `boolean` | `false` | Two-way: open from code with `[(open)]`, or with the `shortcut`. |
| `recent` | `readonly string[]` | `[]` | Ids of recently run commands, shown first under the `recentLabel` heading while the field is empty. Keep the list in your app (see `executed`). |
| `search` | `CommandSearch \| undefined` | `undefined` | Loads more commands for a non-empty query (e.g. from a server), shown after the matching `commands`. Called once typing pauses for `searchDebounce` ms; the `signal` aborts when the query changes. |
| `searchDebounce` | `number` | `250` | Pause in typing (ms) before `search` runs. |
| `shortcut` | `CommandMenuShortcut` | `'mod+k'` | Page-wide key combination that toggles the menu; `false` for none. |
| `size` | `CommandMenuSize` | `'lg'` | — |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `executed` | `CommandItem` | A command was chosen (Enter or click) and has run: the menu closes first, then `run()` is called once the dialog has left the top layer (so it can move focus or open another dialog), then this emits. |
| `openChange` | `boolean` | Two-way: open from code with `[(open)]`, or with the `shortcut`. |
| `searchFailed` | `unknown` | `search` rejected (aborted calls excepted); the menu shows `errorLabel`. |

### Templates and directives

| Selector | Export | Description |
| --- | --- | --- |
| `ng-template[vigCommandMenuItem]` | `CommandMenuItemTemplate` | Custom content of each command row, replacing the icon, label and shortcut. The row itself (`role="option"`) stays the kit's. **Example :** `<ng-template vigCommandMenuItem let-command let-active="active">…</ng-template>` |
