# Command

Search commands, run actions, and open pages of more choices.

Command puts a search field over a list of actions. The list stays open while someone searches. You can use it on its own, or put it in a dialog to build a command palette.

```angular-ts title="demo.ts"
import { Component } from "@angular/core"
import {
  LucideCalculator,
  LucideCalendar,
  LucideCreditCard,
  LucideDynamicIcon,
  LucideSearch,
  LucideSettings,
  LucideSmile,
  LucideUser,
} from "@lucide/angular"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandSeparator,
    CommandShortcut,
    LucideDynamicIcon,
    LucideSearch,
  ],
  template: `
    <div uiCommand>
      <div data-slot="row">
        <svg lucideSearch></svg>
        <input
          uiCommandInput
          aria-label="Search commands"
          placeholder="Type a command or search…"
        />
      </div>
      <div uiCommandEmpty>No results found.</div>
      <div uiCommandList>
        <div uiCommandGroup>
          <div uiCommandGroupLabel>Suggestions</div>
          @for (item of suggestions; track item.value) {
            <div uiCommandItem [value]="item.value" [disabled]="item.disabled">
              <span uiCommandItemIcon>
                <svg [lucideIcon]="item.icon"></svg>
              </span>
              <span>{{ item.label }}</span>
            </div>
          }
        </div>
        <div uiCommandSeparator></div>
        <div uiCommandGroup>
          <div uiCommandGroupLabel>Settings</div>
          @for (item of settings; track item.value) {
            <div uiCommandItem [value]="item.value" [shortcut]="item.shortcut">
              <span uiCommandItemIcon>
                <svg [lucideIcon]="item.icon"></svg>
              </span>
              <span>{{ item.label }}</span>
              <span uiCommandShortcut></span>
            </div>
          }
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly suggestions = [
    { value: "calendar", label: "Calendar", icon: LucideCalendar },
    { value: "emoji", label: "Search Emoji", icon: LucideSmile },
    {
      value: "calculator",
      label: "Calculator",
      icon: LucideCalculator,
      disabled: true,
    },
  ]

  readonly settings = [
    { value: "profile", label: "Profile", icon: LucideUser, shortcut: "mod+p" },
    {
      value: "billing",
      label: "Billing",
      icon: LucideCreditCard,
      shortcut: "mod+b",
    },
    {
      value: "settings",
      label: "Settings",
      icon: LucideSettings,
      shortcut: "mod+s",
    },
  ]
}

export { Example }
```

Type “bil” to find Billing. Arrow keys move the highlight; Escape clears the search.

## Installation

```bash
npm install @ui-sdk/angular @ui-sdk/core
```

## Composition

Use the following composition to build Command:

```text
uiCommand
├── uiCommandInput
├── uiCommandEmpty
└── uiCommandList
    ├── uiCommandItem
    └── uiCommandItem
```

Give the input an accessible name and each command a unique value. Keep empty and status messages outside the list, which holds commands and groups. `(action)` reports the value of the command that ran; use it to perform the action.

Use `uiCommandGroup` and `uiCommandGroupLabel` to name related commands, with a `uiCommandSeparator` between groups. Groups and separators disappear when filtering leaves them empty.

## Usage

Import the parts and put them together:

```ts
import { Component } from "@angular/core"
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/angular/command"

@Component({
  selector: "app-example",
  imports: [Command, CommandEmpty, CommandInput, CommandItem, CommandList],
  template: `
    <div uiCommand>
      <input uiCommandInput aria-label="Search commands" />
      <div uiCommandEmpty>No commands found.</div>
      <div uiCommandList>
        <div uiCommandItem value="new-file">New file</div>
        <div uiCommandItem value="new-folder">New folder</div>
      </div>
    </div>
  `,
})
class Example {}

export { Example }
```

## Build Your Own

`@ui-sdk/angular/command` comes with a ready-made Command. If you'd like to build your own, with your own names, start from the `command` primitive in `@ui-sdk/core`:

```ts title="palette.ts"
import { Directive, inject, input } from "@angular/core"
import { command } from "@ui-sdk/core/command"
import { usePart, usePrimitive } from "@ui-sdk/angular/primitive"

@Directive({ selector: "[appPalette]" })
class Palette {
  readonly handle = usePrimitive(command, () => ({}))
}

@Directive({ selector: "[appPaletteSearch]" })
class PaletteSearch {
  readonly state = usePart(inject(Palette).handle, "input").state
}

@Directive({ selector: "[appPaletteEmpty]" })
class PaletteEmpty {
  readonly state = usePart(inject(Palette).handle, "empty").state
}

@Directive({ selector: "[appPaletteList]" })
class PaletteList {
  readonly state = usePart(inject(Palette).handle, "list").state
}

@Directive({ selector: "[appPaletteAction]" })
class PaletteAction {
  readonly value = input.required<string>()
  readonly state = usePart(inject(Palette).handle, "item", () => ({
    value: this.value(),
  })).state
}

export { Palette, PaletteAction, PaletteEmpty, PaletteList, PaletteSearch }
```

```ts
import { Component } from "@angular/core"
import {
  Palette,
  PaletteAction,
  PaletteEmpty,
  PaletteList,
  PaletteSearch,
} from "./palette"

@Component({
  selector: "app-palette-example",
  imports: [Palette, PaletteAction, PaletteEmpty, PaletteList, PaletteSearch],
  template: `
    <ng-container appPalette>
      <input appPaletteSearch aria-label="Search actions" />
      <div appPaletteEmpty>No actions found.</div>
      <div appPaletteList>
        <div appPaletteAction value="new-file">New file</div>
        <div appPaletteAction value="new-folder">New folder</div>
      </div>
    </ng-container>
  `,
})
export class PaletteExample {}
```

Connect the other slots the same way, each with `usePart`. Each part keeps the behavior, state and data attributes of its ready-made counterpart: typing filters the commands, arrow keys move the highlight and Enter runs it. See [Rendering Primitives](/docs/angular/rendering) and [Custom Parts](/docs/angular/custom-parts) for more.

## Dialog

Put Command inside a [Dialog](/docs/angular/components/dialog) for a command palette. Give the dialog a title, put `shortcut="mod+k"` on its trigger, and close it when a command runs. The dialog handles dismissal and returns focus to the trigger.

```angular-ts title="dialog.ts"
import { Component, signal } from "@angular/core"
import {
  LucideCalculator,
  LucideCalendar,
  LucideCreditCard,
  LucideDynamicIcon,
  LucideSearch,
  LucideSettings,
  LucideSmile,
  LucideUser,
} from "@lucide/angular"
import { useLog } from "./log"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
} from "@ui-sdk/angular/command"
import {
  Dialog,
  DialogBackdrop,
  DialogContent,
  DialogShortcut,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/angular/dialog"

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    Dialog,
    DialogBackdrop,
    DialogContent,
    DialogShortcut,
    DialogTitle,
    DialogTrigger,
    LucideDynamicIcon,
    LucideSearch,
  ],
  template: `
    <div data-slot="stack">
      <ng-container uiDialog [(open)]="open">
        <button uiDialogTrigger shortcut="mod+k">
          Search…
          <kbd uiDialogShortcut></kbd>
        </button>
        <div *uiDialogBackdrop></div>
        <div *uiDialogContent>
          <h2 uiDialogTitle>Command palette</h2>
          <div uiCommand (action)="onAction($event.value)">
            <div data-slot="row">
              <svg lucideSearch></svg>
              <input
                uiCommandInput
                aria-label="Search commands"
                placeholder="Type a command or search…"
              />
            </div>
            <div uiCommandEmpty>No results found.</div>
            <div uiCommandList>
              <div uiCommandGroup>
                <div uiCommandGroupLabel>Suggestions</div>
                @for (item of commands; track item.value) {
                  <div
                    uiCommandItem
                    [value]="item.value"
                    [disabled]="item.disabled"
                  >
                    <span uiCommandItemIcon>
                      <svg [lucideIcon]="item.icon"></svg>
                    </span>
                    {{ item.label }}
                  </div>
                }
              </div>
            </div>
          </div>
        </div>
      </ng-container>
    </div>
  `,
})
class Example {
  readonly commands = [
    { value: "calendar", label: "Calendar", icon: LucideCalendar },
    { value: "emoji", label: "Search Emoji", icon: LucideSmile },
    {
      value: "calculator",
      label: "Calculator",
      icon: LucideCalculator,
      disabled: true,
    },
    { value: "profile", label: "Profile", icon: LucideUser },
    { value: "billing", label: "Billing", icon: LucideCreditCard },
    { value: "settings", label: "Settings", icon: LucideSettings },
  ]

  readonly log = useLog()

  readonly open = signal(false)

  onAction(value: string) {
    this.log(`Ran ${value}`)
    this.open.set(false)
  }
}

export { Example }
```

Press Search or use Cmd+K / Ctrl+K. Choose a command to run it and close the palette; the console logs what ran.

## Shortcuts

An item’s `shortcut` can run it while the command list is mounted, even when the search or current page hides it. `uiCommandShortcut` displays the keys for the current platform, and the item gets `aria-keyshortcuts`. Shortcuts inside a dialog run while it is open.

```angular-ts title="shortcuts.ts"
import { Component } from "@angular/core"
import {
  LucideCreditCard,
  LucideDynamicIcon,
  LucideSettings,
  LucideUser,
} from "@lucide/angular"
import { useLog } from "./log"
import {
  Command,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandShortcut,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandShortcut,
    LucideDynamicIcon,
  ],
  template: `
    <div data-slot="stack">
      <div uiCommand (action)="log('Ran ' + $event.value)">
        <input
          uiCommandInput
          aria-label="Search settings"
          placeholder="Search settings…"
        />
        <div uiCommandList>
          <div uiCommandGroup>
            <div uiCommandGroupLabel>Settings</div>
            @for (item of settings; track item.value) {
              <div
                uiCommandItem
                [value]="item.value"
                [shortcut]="item.shortcut"
              >
                <span uiCommandItemIcon>
                  <svg [lucideIcon]="item.icon"></svg>
                </span>
                <span>{{ item.label }}</span>
                <span uiCommandShortcut #commandShortcut="uiCommandShortcut">{{
                  commandShortcut.state().text
                }}</span>
              </div>
            }
          </div>
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly settings = [
    { value: "profile", label: "Profile", icon: LucideUser, shortcut: "mod+p" },
    {
      value: "billing",
      label: "Billing",
      icon: LucideCreditCard,
      shortcut: "mod+b",
    },
    {
      value: "settings",
      label: "Settings",
      icon: LucideSettings,
      shortcut: "mod+s",
    },
  ]

  readonly log = useLog()
}

export { Example }
```

Press Cmd+P / Ctrl+P to run Profile, even when the search hides it. The console logs each command that runs.

## Highlight Matches

`uiCommandItemText` marks the matched text. The default fuzzy filter can match letters that are apart, so one command may have several marked segments.

```angular-ts title="highlight.ts"
import { Component } from "@angular/core"
import {
  LucideCalculator,
  LucideCalendar,
  LucideCreditCard,
  LucideDynamicIcon,
  LucideSearch,
  LucideSettings,
  LucideSmile,
  LucideUser,
} from "@lucide/angular"
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandItemText,
  CommandList,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandItemText,
    CommandList,
    LucideDynamicIcon,
    LucideSearch,
  ],
  template: `
    <div uiCommand>
      <div data-slot="row">
        <svg lucideSearch></svg>
        <input
          uiCommandInput
          aria-label="Search commands"
          placeholder="Try “prf” or “emo”…"
        />
      </div>
      <div uiCommandEmpty>No results found.</div>
      <div uiCommandList>
        @for (item of commands; track item.value) {
          <div uiCommandItem [value]="item.value" [disabled]="item.disabled">
            <span uiCommandItemIcon>
              <svg [lucideIcon]="item.icon"></svg>
            </span>
            <span uiCommandItemText>{{ item.label }}</span>
          </div>
        }
      </div>
    </div>
  `,
})
class Example {
  readonly commands = [
    { value: "calendar", label: "Calendar", icon: LucideCalendar },
    { value: "emoji", label: "Search Emoji", icon: LucideSmile },
    {
      value: "calculator",
      label: "Calculator",
      icon: LucideCalculator,
      disabled: true,
    },
    { value: "profile", label: "Profile", icon: LucideUser },
    { value: "billing", label: "Billing", icon: LucideCreditCard },
    { value: "settings", label: "Settings", icon: LucideSettings },
  ]
}

export { Example }
```

Type “prf” to find Profile. Matching letters are marked even when they are not next to each other.

## Filter and Keywords

`"fuzzy"` is the default: `nf` matches New file. `"contains"` and `"startsWith"` match the text itself. A custom function returns a boolean or a score; zero hides a command and higher scores rank first.

Data commands are sorted by score. Commands written directly in markup keep their order, even though the best match can be highlighted.

`keywords` adds search terms without changing the command's label. Use it for synonyms or names someone might type instead.

```angular-ts title="filter.ts"
import { Component, computed, signal } from "@angular/core"
import { LucideCheck, LucideChevronDown } from "@lucide/angular"
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/angular/command"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/angular/select"

type Mode = "fuzzy" | "contains" | "startsWith" | "words"

function words(item: { label: string }, query: string) {
  return query
    .toLowerCase()
    .split(/\s+/)
    .every((word) =>
      item.label
        .toLowerCase()
        .split(" ")
        .some((part) => part.startsWith(word))
    )
}

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
    Select,
    SelectContent,
    SelectItem,
    SelectItemIndicator,
    SelectLabel,
    SelectTrigger,
    SelectValue,
    LucideCheck,
    LucideChevronDown,
  ],
  template: `
    <div data-slot="stack">
      <div data-slot="controls">
        <ng-container
          uiSelect
          [items]="modes"
          [value]="mode()"
          (beforeValueChange)="$event.value && mode.set($event.value)"
        >
          <div uiSelectLabel>Filter</div>
          <button uiSelectTrigger>
            <span uiSelectValue></span>
            <svg lucideChevronDown></svg>
          </button>
          <div *uiSelectContent>
            @for (option of modes; track option.value) {
              <div uiSelectItem [value]="option.value">
                {{ option.label }}
                <span *uiSelectItemIndicator>
                  <svg lucideCheck></svg>
                </span>
              </div>
            }
          </div>
        </ng-container>
      </div>
      <div uiCommand [filter]="filter()">
        <input
          uiCommandInput
          aria-label="Search commands"
          placeholder="Try “nf”, “zo in” or “smiley”"
        />
        <div uiCommandEmpty>No results found.</div>
        <div uiCommandList>
          @for (command of commands; track command.label) {
            <div
              uiCommandItem
              [value]="command.label"
              [keywords]="command.keywords"
            >
              {{ command.label }}
            </div>
          }
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly commands = [
    { label: "Home" },
    { label: "Inbox", keywords: ["mail", "messages"] },
    { label: "Documents" },
    { label: "Downloads" },
    { label: "New file" },
    { label: "New folder" },
    { label: "Copy" },
    { label: "Paste" },
    { label: "Delete", keywords: ["remove", "trash"] },
    { label: "Zoom in" },
    { label: "Zoom out" },
    { label: "Search emoji", keywords: ["smiley", "face"] },
    { label: "Keyboard shortcuts", keywords: ["hotkeys"] },
    { label: "Settings", keywords: ["preferences"] },
  ]

  readonly modes = [
    { value: "fuzzy", label: "Fuzzy" },
    { value: "contains", label: "Contains" },
    { value: "startsWith", label: "Starts with" },
    { value: "words", label: "Words" },
  ]

  readonly mode = signal<Mode>("fuzzy")

  readonly filter = computed(() => {
    const mode = this.mode()
    return mode === "words" ? words : mode
  })
}

export { Example }
```

Type “nf” with Fuzzy to find New file. Choose Words and type “zo in” for Zoom in, or type “smiley” to find Search emoji through a keyword.

## Pages

Set an item’s `page` to the value of a `uiCommandPage` to open it. An unnamed page holds the first set of commands. The `pages` array records the stack of pages that have been opened.

Backspace in an empty search goes back and restores the previous page’s query. Escape clears the query first, then goes back. A Go back command can call `pop()` on a controller.

```angular-ts title="pages.ts"
import { Component, signal } from "@angular/core"
import { LucideArrowLeft, LucideMoon, LucideUsers } from "@lucide/angular"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandPage,
  createCommandController,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandPage,
    LucideArrowLeft,
    LucideMoon,
    LucideUsers,
  ],
  template: `
    <div
      uiCommand
      [(pages)]="pages"
      [controller]="command"
      (action)="onAction($event.value)"
    >
      <div data-slot="row">
        @for (page of pages(); track page) {
          <span data-slot="badge">{{ page }}</span>
        }
      </div>
      <input
        uiCommandInput
        aria-label="Search commands"
        [placeholder]="
          pages().length
            ? 'Search… (Backspace to go back)'
            : 'What do you need?'
        "
      />
      <div uiCommandEmpty>No results found.</div>
      <div uiCommandList>
        <ng-container *uiCommandPage>
          <div uiCommandGroup>
            <div uiCommandGroupLabel>Workspace</div>
            <div uiCommandItem value="theme" page="theme">
              <span uiCommandItemIcon>
                <svg lucideMoon></svg>
              </span>
              Change theme…
            </div>
            <div uiCommandItem value="teams" page="teams">
              <span uiCommandItemIcon>
                <svg lucideUsers></svg>
              </span>
              Switch team…
            </div>
          </div>
        </ng-container>
        <ng-container *uiCommandPage="'theme'">
          @for (theme of themes; track theme.value) {
            <div uiCommandItem [value]="theme.value">
              {{ theme.label }}
            </div>
          }
        </ng-container>
        <ng-container *uiCommandPage="'teams'">
          @for (team of teams; track team.value) {
            <div uiCommandItem [value]="team.value">
              {{ team.label }}
            </div>
          }
        </ng-container>
        @if (pages().length > 0) {
          <div uiCommandItem value="back">
            <span uiCommandItemIcon mirror>
              <svg lucideArrowLeft></svg>
            </span>
            Go back
          </div>
        }
      </div>
    </div>
  `,
})
class Example {
  readonly themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

  readonly teams = [
    { value: "design", label: "Design" },
    { value: "engineering", label: "Engineering" },
    { value: "marketing", label: "Marketing" },
  ]

  readonly command = createCommandController()

  readonly pages = signal<string[]>([])

  onAction(value: string) {
    if (value === "back") {
      this.command.pop()
    }
  }
}

export { Example }
```

Choose Change theme or Switch team. Use Go back, or press Backspace in an empty search field, to return.

## Items as Data

Pass `items` to provide commands, groups, separators, and pages as `CommandData`. A data command with its own `items` opens a page. Its shortcut still works when another page or filter hides it.

`uiCommandItems` inside the list renders bare parts from the data. For styled commands, render from the list’s `state().items`, which follows the current page and ranked results. The example handles groups and separators as well as commands. [Lists and Menus](/docs/angular/lists-and-menus) covers the shared data format.

Pass `emptyItems` alongside `items` to show suggested or recent commands while the first page's search is empty. Once someone types, the full collection is searched.

```angular-html
<div
  uiCommand
  [items]="commands"
  [emptyItems]="[{ type: 'group', label: 'Suggested', items: recent }]"
></div>
```

```angular-ts title="data.ts"
import { Component } from "@angular/core"
import { useLog } from "./log"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
  type CommandData,
  type CommandDataItem,
} from "@ui-sdk/angular/command"

type Entry =
  | { key: string; type: "separator" }
  | { key: string; type: "group"; label?: string; commands: CommandDataItem[] }
  | { key: string; type: "item"; command: CommandDataItem }

const commands: CommandData = [
  {
    type: "group",
    label: "Navigation",
    items: [
      { value: "home", label: "Go home", keywords: ["start"] },
      { value: "inbox", label: "Open inbox", shortcut: "mod+i" },
    ],
  },
  { type: "separator" },
  {
    type: "group",
    label: "Preferences",
    items: [
      {
        value: "theme",
        label: "Change theme…",
        items: [
          { value: "light", label: "Light" },
          { value: "dark", label: "Dark" },
          { value: "system", label: "System" },
        ],
      },
      {
        value: "language",
        label: "Change language…",
        items: ["English", "Français", "Deutsch", "日本語"],
      },
      { value: "sign-out", label: "Sign out", shortcut: "mod+shift+q" },
    ],
  },
]

function toCommand(entry: CommandDataItem | string) {
  return typeof entry === "string" ? { value: entry, label: entry } : entry
}

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandList,
    CommandSeparator,
    CommandShortcut,
  ],
  template: `
    <div data-slot="stack">
      <div uiCommand [items]="commands" (action)="log('Ran ' + $event.value)">
        <input
          uiCommandInput
          aria-label="Search commands"
          placeholder="Type a command…"
        />
        <div uiCommandEmpty>No results found.</div>
        <div uiCommandList #list="uiCommandList">
          @for (entry of entries(list.state().items); track entry.key) {
            @switch (entry.type) {
              @case ("separator") {
                <div uiCommandSeparator></div>
              }
              @case ("group") {
                <div uiCommandGroup>
                  <div uiCommandGroupLabel>{{ entry.label }}</div>
                  @for (command of entry.commands; track command.value) {
                    <div
                      uiCommandItem
                      [value]="command.value"
                      [label]="command.label"
                      [disabled]="command.disabled"
                      [shortcut]="command.shortcut"
                    >
                      {{ command.label }}
                      @if (command.shortcut) {
                        <span uiCommandShortcut></span>
                      }
                    </div>
                  }
                </div>
              }
              @case ("item") {
                <div
                  uiCommandItem
                  [value]="entry.command.value"
                  [label]="entry.command.label"
                  [disabled]="entry.command.disabled"
                  [shortcut]="entry.command.shortcut"
                >
                  {{ entry.command.label }}
                  @if (entry.command.shortcut) {
                    <span uiCommandShortcut></span>
                  }
                </div>
              }
            }
          }
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly commands = commands

  readonly log = useLog()

  entries(items: unknown) {
    return (items as CommandData).map<Entry>((entry, index) => {
      if (typeof entry !== "string" && "type" in entry) {
        return entry.type === "separator"
          ? { key: `separator-${index}`, type: "separator" }
          : {
              key: `group-${index}`,
              type: "group",
              label: entry.label,
              commands: entry.items.map(toCommand),
            }
      }
      const command = toCommand(entry)
      return { key: command.value, type: "item", command }
    })
  }
}

export { Example }
```

Choose Change theme to open its commands. Press Cmd+I / Ctrl+I to run Open inbox from any page; the console logs what ran.

## Async Results

Use [async options](/docs/angular/utilities/async-options) to wait for typing to pause and discard stale results. Send query changes to `setQuery()`, render the returned items, and pass `status`. Set `filter` to `false` to keep the server’s order.

`uiCommandStatus` describes loading and failures, and the list gets `aria-busy` while loading. `(loadMore)` can request another page when scrolling or highlighting reaches the last command. Without a status part, `announcement` controls the result-count message after typing pauses.

```angular-ts title="async.ts"
import { Component } from "@angular/core"
import { useAsyncOptions } from "@ui-sdk/angular/async-options"
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
  CommandStatus,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
    CommandStatus,
  ],
  template: `
    <div
      uiCommand
      [filter]="false"
      [status]="issues.state().status"
      (beforeQueryChange)="issues.setQuery($event.value)"
      (loadMore)="issues.loadMore()"
    >
      <input
        uiCommandInput
        aria-label="Search issues"
        placeholder="Search issues…"
      />
      <div uiCommandStatus #commandStatus="uiCommandStatus">
        {{
          commandStatus.state().loading
            ? "Searching…"
            : commandStatus.state().count +
              " " +
              (commandStatus.state().count === 1 ? "issue" : "issues")
        }}
      </div>
      <div uiCommandEmpty #commandEmpty="uiCommandEmpty">
        @if (commandEmpty.state().empty && !commandEmpty.state().loading) {
          No issues match “{{ commandEmpty.state().query }}”.
        }
      </div>
      <div uiCommandList>
        @for (issue of issues.state().items; track issue.value) {
          <div uiCommandItem [value]="issue.value" [label]="issue.label">
            {{ issue.label }}
          </div>
        }
      </div>
    </div>
  `,
})
class Example {
  readonly searchIssues = (
    query: string,
    { signal }: { signal: AbortSignal }
  ) => {
    const issues = [
      "Fix login redirect",
      "Dark mode flicker",
      "Add billing page",
      "Search is slow",
      "Update dependencies",
      "Crash on upload",
      "Export to CSV",
      "Keyboard shortcuts help",
    ]
    return new Promise<{ value: string; label: string }[]>(
      (resolve, reject) => {
        const timer = setTimeout(() => {
          const needle = query.trim().toLowerCase()
          resolve(
            issues
              .filter((issue) => issue.toLowerCase().includes(needle))
              .map((issue) => ({
                value: issue.toLowerCase().replaceAll(" ", "-"),
                label: issue,
              }))
          )
        }, 400)
        signal.addEventListener("abort", () => {
          clearTimeout(timer)
          reject(new DOMException("Aborted", "AbortError"))
        })
      }
    )
  }

  readonly issues = useAsyncOptions(this.searchIssues, {
    debounce: 250,
    immediate: true,
  })
}

export { Example }
```

Type “login” and wait for matching issues. Replace the text to start a new search; only the latest results appear.

## Pending Actions

Pass a promise to `$event.waitUntil()` in `(action)` or an item’s `(select)`. The command gets `data-pending`, `aria-busy` and `aria-disabled` until it settles; further presses do not start another run. A rejection becomes the command’s `error` state, which clears when it runs again.

An item’s `(select)` runs before `(action)`. Call `preventDefault()` on its event to stop the action.

```angular-ts title="pending.ts"
import { Component } from "@angular/core"
import { LucideLoaderCircle } from "@lucide/angular"
import { useLog } from "./log"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandInput,
    CommandItem,
    CommandList,
    LucideLoaderCircle,
  ],
  template: `
    <div data-slot="stack">
      <div uiCommand>
        <input
          uiCommandInput
          aria-label="Search actions"
          placeholder="Search actions…"
        />
        <div uiCommandList>
          <div
            uiCommandItem
            #commandItem2="uiCommandItem"
            value="deploy"
            (select)="$event.waitUntil(deploy())"
          >
            Deploy to production
            @if (commandItem2.state().pending) {
              <svg lucideLoaderCircle data-slot="spinner"></svg>
            }
          </div>
          <div
            uiCommandItem
            #commandItem="uiCommandItem"
            value="sync"
            (select)="$event.waitUntil(sync())"
          >
            Sync with server
            @if (commandItem.state().pending) {
              <svg lucideLoaderCircle data-slot="spinner"></svg>
            } @else if (commandItem.state().error !== undefined) {
              <span data-slot="hint">Failed, try again</span>
            }
          </div>
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly wait = (ms: number) =>
    new Promise<void>((resolve) => setTimeout(resolve, ms))

  readonly log = useLog()

  async deploy() {
    await this.wait(1200)
    this.log("Deployed to production")
  }

  async sync() {
    await this.wait(600)
    this.log("Couldn't sync: offline")
    throw new Error("Offline")
  }
}

export { Example }
```

Run Deploy to production and try it again while it's pending. Sync with server fails and can be retried; the console logs each outcome.

## Virtualized

Pass the full `items` collection so filtering and keyboard navigation include commands that are not mounted. Render only visible rows, giving each its index in the current results. `(beforeValueChange)` includes that index so you can scroll a newly highlighted row into view.

```angular-ts title="virtualized.ts"
import { Component, ElementRef, signal, viewChild } from "@angular/core"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/angular/command"

const commands = Array.from({ length: 10_000 }, (_, index) => ({
  value: `command-${index + 1}`,
  label: `Command ${index + 1}`,
}))

@Component({
  imports: [Command, CommandInput, CommandItem, CommandList],
  template: `
    <div
      uiCommand
      [items]="commands"
      (beforeValueChange)="onValueChange($event.value, $event)"
    >
      <input
        uiCommandInput
        aria-label="Search 10,000 commands"
        placeholder="Search 10,000 commands…"
      />
      <div #scroller (scroll)="scrollTop.set(scroller.scrollTop)">
        <div uiCommandList #commandList="uiCommandList">
          <div [style.height.px]="commandList.state().items.length * row">
            @for (
              entry of visible(commandList.state().items);
              track entry.item.value
            ) {
              <div
                uiCommandItem
                [value]="entry.item.value"
                [label]="entry.item.label"
                [index]="entry.index"
                [style.top.px]="entry.index * row"
              >
                {{ entry.item.label }}
              </div>
            }
          </div>
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly commands = commands

  readonly row = 32

  readonly height = 256

  readonly scroller = viewChild<ElementRef<HTMLDivElement>>("scroller")

  readonly scrollTop = signal(0)

  onValueChange(_value: string | null, { index }: { index: number }) {
    const el = this.scroller()?.nativeElement
    if (!el || index < 0) {
      return
    }
    const top = index * this.row
    if (top < el.scrollTop) {
      el.scrollTop = top
    } else if (top + this.row > el.scrollTop + el.clientHeight) {
      el.scrollTop = top + this.row - el.clientHeight
    }
  }

  visible(list: readonly unknown[]) {
    const items = list as typeof commands
    const start = Math.max(0, Math.floor(this.scrollTop() / this.row) - 4)
    const end = Math.min(
      items.length,
      Math.ceil((this.scrollTop() + this.height) / this.row) + 4
    )
    return items
      .slice(start, end)
      .map((item, offset) => ({ item, index: start + offset }))
  }
}

export { Example }
```

Search 10,000 commands or move through them with the arrow keys. Only the rows near the viewport render.

## Controlled

The highlighted command, search text, and page stack are separate:

| Value   | Shape                               | Change Notification   |
| ------- | ----------------------------------- | --------------------- |
| `value` | A command’s string value or `null`. | `(beforeValueChange)` |
| `query` | The search text.                    | `(beforeQueryChange)` |
| `pages` | An array of page values.            | `(beforePagesChange)` |

Bind them with `[(value)]`, `[(query)]` and `[(pages)]`, or use `defaultValue`, `defaultQuery`, and `defaultPages` for starting state. The `before` outputs receive the details; call `$event.cancel()` to reject a change. `value` is the highlighted command, not a chosen one, and it changes as the highlight moves. `(action)` reports activation, so moving the highlight alone does not run a command. [State and Events](/docs/angular/state-and-events) covers the shared binding pattern.

```angular-ts title="controlled.ts"
import { Component, signal } from "@angular/core"
import { useLog } from "./log"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
  CommandPage,
} from "@ui-sdk/angular/command"

@Component({
  imports: [Command, CommandInput, CommandItem, CommandList, CommandPage],
  template: `
    <div
      uiCommand
      [(value)]="value"
      [(query)]="query"
      [(pages)]="pages"
      (beforeValueChange)="
        log(
          'Highlighted ' +
            ($event.value ?? 'nothing') +
            ' (' +
            $event.reason +
            ')'
        )
      "
      (beforeQueryChange)="
        log('Query “' + $event.value + '” (' + $event.reason + ')')
      "
      (beforePagesChange)="
        log('Pages [' + $event.value.join(', ') + '] (' + $event.reason + ')')
      "
      (action)="log('Ran ' + $event.value)"
    >
      <input
        uiCommandInput
        aria-label="Search themes"
        placeholder="Search themes…"
      />
      <div uiCommandList>
        <ng-container *uiCommandPage>
          <div uiCommandItem value="theme" page="theme">Change theme…</div>
        </ng-container>
        <ng-container *uiCommandPage="'theme'">
          @for (theme of themes; track theme.value) {
            <div uiCommandItem [value]="theme.value">
              {{ theme.label }}
            </div>
          }
        </ng-container>
      </div>
    </div>
  `,
})
class Example {
  readonly themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

  readonly log = useLog()

  readonly value = signal<string | null>("dark")

  readonly query = signal("")

  readonly pages = signal(["theme"])
}

export { Example }
```

Open Change theme, search and move the highlight. The console logs each highlight, query and page change with its reason.

## Controller

Create a `createCommandController()` for one instance and pass it as `controller`. It can read and set the highlight, query, and page stack. Use `push()` and `pop()` to navigate pages, `run()` to run the highlighted command or a named one, and `focus()` to focus the search. See [Controllers](/docs/angular/controllers) for setup and lifecycle.

```angular-ts title="controller.ts"
import { Component } from "@angular/core"
import { useLog } from "./log"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
  CommandPage,
  createCommandController,
} from "@ui-sdk/angular/command"

@Component({
  imports: [Command, CommandInput, CommandItem, CommandList, CommandPage],
  template: `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" (click)="palette.push('theme')">
          Open Themes
        </button>
        <button type="button" (click)="palette.pop()">Back</button>
        <button type="button" (click)="palette.setValue('dark')">
          Highlight Dark
        </button>
        <button type="button" (click)="palette.setQuery('li')">
          Search “li”
        </button>
        <button type="button" (click)="palette.run()">Run Highlighted</button>
        <button type="button" (click)="palette.focus()">Focus</button>
      </div>
      <div
        uiCommand
        [controller]="palette"
        (action)="log('Ran ' + $event.value)"
      >
        <input uiCommandInput aria-label="Search commands" />
        <div uiCommandList>
          <ng-container *uiCommandPage>
            <div uiCommandItem value="theme" page="theme">Change theme…</div>
          </ng-container>
          <ng-container *uiCommandPage="'theme'">
            @for (theme of themes; track theme.value) {
              <div uiCommandItem [value]="theme.value">
                {{ theme.label }}
              </div>
            }
          </ng-container>
        </div>
      </div>
    </div>
  `,
})
class Example {
  readonly themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

  readonly palette = createCommandController()

  readonly log = useLog()
}

export { Example }
```

Use the buttons to open pages, search, move the highlight and run it from outside. The console logs each command that runs.

## Custom Rendering

Render a command as an anchor when it should navigate. Enter follows the highlighted link; modified clicks keep their usual browser behavior.

```angular-ts title="custom-rendering.ts"
import { Component } from "@angular/core"
import { LucideCornerDownLeft } from "@lucide/angular"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandItemText,
  CommandList,
} from "@ui-sdk/angular/command"

@Component({
  imports: [
    Command,
    CommandInput,
    CommandItem,
    CommandItemText,
    CommandList,
    LucideCornerDownLeft,
  ],
  template: `
    <div uiCommand>
      <input
        uiCommandInput
        aria-label="Search docs"
        placeholder="Search docs…"
      />
      <div uiCommandList>
        @for (page of pages; track page) {
          <a
            uiCommandItem
            #commandItem="uiCommandItem"
            [value]="page"
            href="#{{ page.toLowerCase() }}"
            ><span uiCommandItemText #commandItemText="uiCommandItemText">
              @for (
                segment of commandItemText.state().segments;
                track index;
                let index = $index
              ) {
                @if (segment.match) {
                  <strong>{{ segment.text }}</strong>
                } @else {
                  <span>{{ segment.text }}</span>
                }
              }
            </span>
            @if (commandItem.state().highlighted) {
              <svg lucideCornerDownLeft></svg>
            }
          </a>
        }
      </div>
    </div>
  `,
})
class Example {
  readonly pages = ["Composition", "Installation", "Styling"]
}

export { Example }
```

Search for Installation and press Enter. The command follows the link to that section on this page.

## Styling

Each part has a `data-slot`, such as `command-item`, and shows its state through the attributes listed under [Data Attributes](#data-attributes).

Use `data-highlighted` for the active command and `data-pending` for an action in progress. Give the list a height limit and `overflow-y: auto` for long lists; keyboard navigation scrolls the highlighted command into view. When mixing commands with and without icons, `data-has-icons` on the list and `data-has-icon` on each item let you reserve matching space with logical padding.

## Data Attributes

### Command
`[data-slot="command"]`

- `data-loading`: Present while results load, with `status="loading"`.

### CommandInput
### CommandList
`[data-slot="command-list"]`

- `data-has-icons`: Present while any command inside holds an icon part, so items without one can line up.

### CommandItem
`[data-slot="command-item"]`

- `data-disabled`: Present when the command can't run. Arrow keys skip it.
- `data-highlighted`: Present on the highlighted command, which Enter runs. Focus stays in the field.
- `data-pending`: Present while the Promise the command's `onSelect` or `onAction` returned is running.
- `data-has-icon`: Present on a command while it holds an icon part.

### CommandItemText
`[data-slot="command-item-text"]`

- `data-matched`: Present on a command's text while the search matched part of it, which is marked.

### CommandItemIcon
`[data-slot="command-item-icon"]`

- `data-mirror`: Present on an icon that flips in right-to-left text, with `mirror`.

### CommandEmpty
`[data-slot="command-empty"]`

- `data-loading`: Present while results load, with `status="loading"`.
- `data-empty`: Present while no command matches.

### CommandStatus
`[data-slot="command-status"]`

- `data-loading`: Present while results load, with `status="loading"`.

## API Reference

Each option below is an input on the directive, and each callback an output. A change callback is two outputs: `(beforeValueChange)`, with the details and `cancel()`, then `(valueChange)` with the new value alone.

### Command

- `value?` (`string | null`): The highlighted command's value. Pass it to control the highlight. `null` highlights nothing.
- `defaultValue?` (`string | null`): The command highlighted at first, when uncontrolled. Without it, the first command is, with `autoHighlight`.
- `(beforeValueChange)`: Runs when the highlight moves: arrow keys, the pointer, typing, a page change or a controller. `details.index` says where the command is, for virtualized lists.
- `query?` (`string`): The search text, which filters the commands. Pass it to control it.
- `defaultQuery?` (`string`): The search text at first, when uncontrolled.
- `(beforeQueryChange)`: Runs when the search text wants to change: typing, opening a page, going back, or a controller.
- `pages?` (`string[]`): The stack of open pages, from the first page opened to the current one. Pass it to control it.
- `defaultPages?` (`string[]`): The pages open at first, when uncontrolled.
- `(beforePagesChange)`: Runs when a page opens or Backspace or Escape goes back.
- `(action)`: Runs when a command runs, with its value: Enter, a click, or its shortcut. Return a Promise to mark the command pending until it settles: it gets `data-pending`, `aria-busy` and `aria-disabled`, and running it again waits. A rejection puts the reason in its `error` state until the next run.
- `pendingAnnouncement?` (`string`): What screen readers hear once a command has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
- `items?` (`CommandData`): The commands as data. Renders them for you, ranked as the user types, with pages for commands that have `items`.
- `emptyItems?` (`CommandData`): Commands shown instead of `items` on the first page while the search is empty, like recent or suggested ones. Groups work, like `{ type: "group", label: "Suggestions", items }`. Needs `items`.
- `filter?` (`SearchFilter<string>`): How typing narrows the list: `"fuzzy"` keeps commands with the text's letters in order, best matches first; `"contains"` and `"startsWith"` match the text itself. A function returns a score (0 hides) or a boolean. `false` keeps every command, for results a server already filtered. Composed commands keep their order, and data commands are ranked by score.
- `autoHighlight?` (`boolean`): Whether the first command is highlighted while nothing else is, and the best match as the user types, so Enter runs it.
- `loop?` (`boolean`): Whether arrow keys wrap from the last command to the first.
- `status?` (`AsyncOptionsStatus`): Whether results are loading or failed, for the empty and status parts. Sets `aria-busy` on the list while loading.
- `(loadMore)`: Runs when the highlight or scrolling reaches the last command, so the next page can load, like `createAsyncOptions`'s `loadMore`. Not again for the same commands, unless the last load failed.
- `announcement?` (`((change: ListAnnouncement) => string | null | undefined)`): What screen readers hear after typing pauses, when no `CommandStatus` is rendered. Return null for nothing.
- `controller?` (`object`): Reads and drives the list from anywhere. Create one with `createCommandController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### CommandInput

The search field. Gets the combobox role.

### CommandStatus

Describes loading and failures. Gets the status role.

### CommandEmpty

Shows while no command matches, and screen readers read it when it appears. Goes on a `div`, which gets the status role.

### CommandList

Holds the commands. Renders a `div` with the listbox role, always shown.

### CommandPage

- `value?` (`string`): The page's name, which a command's `page` opens. Leave it out for the first page.

### CommandGroup

Groups commands under a label. Gets the group role.

### CommandGroupLabel

Names its group. Goes on a `div`.

### CommandItem

- `value?` (`string`): Passed to `(action)` and `(beforeValueChange)`, and identifies the command. Without it, one is generated.
- `label?` (`string`): The text the search matches, when the content isn't plain text. Not the accessible name: use `aria-label` for that.
- `keywords?` (`string[]`): More words the search matches.
- `disabled?` (`boolean`): Keeps the command from running. Arrow keys and the pointer skip it. Sets `data-disabled` and `aria-disabled`.
- `shortcut?` (`string`): A keyboard shortcut that runs the command while it's in the page, like `"mod+p"`. Sets `aria-keyshortcuts`, and a `CommandShortcut` inside shows it.
- `page?` (`string`): The page choosing this command opens, by the `value` of a `CommandPage`.
- `index?` (`number`): The command's position among all visible commands, for virtualized lists that render only some. Sets `aria-posinset` and `aria-setsize`.
- `(select)`: Runs when the command runs, before `(action)`, with the click or key press that ran it, or a new `select` Event for a shortcut or a controller's `run()`. Call `event.preventDefault()` to skip `(action)` and the page. Return a Promise to mark the command pending until it settles, like `(action)`.

### CommandItemIcon

- `mirror?` (`boolean`): Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.

### CommandItemText

Shows its command's label, and marks what matched the search. Goes on a `span`.

### CommandShortcut

- `shortcut?` (`string`): The keys to show, like `"mod+p"`. Inside a command, its `shortcut`.

### CommandSeparator

Separates commands or groups. Gets the separator role.

### Items as Data

Each command in `items`. Groups are `{ type: "group", label, items }` and separators `{ type: "separator" }`.

- `value` (`string`): Identifies the item, and is what choosing it reports. A string, or any value with `itemToValue`.
- `label` (`string`): The text shown and matched by typeahead and filtering. A select's trigger shows it once chosen.
- `keywords?` (`string[]`): More words filtering matches, like `["team"]` for a plan called Pro.
- `disabled?` (`boolean`): Keeps the item from being chosen. The keyboard skips it, like in a native select.
- `shortcut?` (`string`): A keyboard shortcut that runs the command, like `"mod+p"`, while the list is in the page, whatever page it's on. Shows `⌘P` on Apple platforms and `Ctrl+P` elsewhere.
- `items?` (`CommandData`): Commands on a page of their own. Choosing this command opens the page, and Backspace in the empty field goes back.

### State

What each part's `state()` signal holds, per part.

`uiCommand`:

- `page` (`string | null`): The current page, or `null` on the first page.
- `loading` (`boolean`): Whether results are loading.

`uiCommandInput`:

- `page` (`string | null`): The current page, or `null` on the first page.

`uiCommandList`:

- `status` (`AsyncOptionsStatus`): Whether results are loading or failed.
- `items` (`CommandData`): The visible data commands, ranked, for rendering a virtualized list yourself.

`uiCommandItem`:

- `highlighted` (`boolean`): Whether the command is highlighted, by the keyboard, the pointer or typing.
- `disabled` (`boolean`): Whether the command can't run.
- `pending` (`boolean`): Whether its action's Promise is running.
- `error` (`unknown`): Why its last action failed, until it runs again.

`uiCommandEmpty`:

- `loading` (`boolean`): Whether results are loading.
- `empty` (`boolean`): Whether no item matches.
- `query` (`string`): The text the list is filtered by.

`uiCommandStatus`:

- `status` (`"idle" | "loading" | "error"`): Whether results are loading or failed.
- `loading` (`boolean`): Whether results are loading.
- `count` (`number`): How many items are visible.

`uiCommandShortcut`:

- `text` (`string`): The shortcut formatted for this platform: `⌘P` on Apple platforms and `Ctrl+P` elsewhere. Empty without one.

`uiCommandItemText`, which takes no inputs of its own:

- `segments` (`MatchSegment[]`): The text in pieces, each marked when it matched. Joined, they're the whole text.
- `matched` (`boolean`): Whether any piece matched.

`uiCommandItemIcon`:

- `mirror` (`boolean`): Whether it flips in right-to-left text.

### Reasons

Why the highlighted command changed:

- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `item-hover` (`PointerEvent`): The pointer moved onto an item, which highlighted it, like in a command list.
- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `item-removed` (`none`): The selected item left the page, and another was picked.
- `imperative` (`none`): A controller or `api` call.

Why the search text changed:

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `imperative` (`none`): A controller or `api` call.

And why the stack of pages changed:

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `imperative` (`none`): A controller or `api` call.

### Controller

Create one with `createCommandController()` and pass it as `controller`.

- `getValue()` (`() => string | null`): The highlighted command's value, or `null`.
- `setValue(value, options?)` (`(value: string | null, options?: CommandChangeOptions<CommandValueChangeReason> | undefined) => boolean`): Highlights a command, and scrolls it into view. Returns false when the change was canceled or nothing changed.
- `getQuery()` (`() => string`): The search text.
- `setQuery(query, options?)` (`(query: string, options?: CommandChangeOptions<CommandQueryChangeReason> | undefined) => boolean`): Changes the search text, which filters the commands. Returns false when the change was canceled or nothing changed.
- `getPages()` (`() => string[]`): The stack of open pages, from the first page opened to the current one. Empty on the first page.
- `setPages(pages, options?)` (`(pages: string[], options?: CommandChangeOptions<CommandPagesChangeReason> | undefined) => boolean`): Replaces the stack of pages. Returns false when the change was canceled or nothing changed.
- `push(page, options?)` (`(page: string, options?: CommandChangeOptions<CommandPagesChangeReason> | undefined) => boolean`): Opens a page on top of the current one, by the `value` of a `CommandPage` or a data command. Returns false when the change was canceled or nothing changed.
- `pop(options?)` (`(options?: CommandChangeOptions<CommandPagesChangeReason> | undefined) => boolean`): Goes back to the previous page, and puts back the search text typed there. Returns false when the change was canceled or nothing changed.
- `run(value?)` (`(value?: string | undefined) => void`): Runs a command, as Enter would: the highlighted one, or the one with this value.
- `focus()` (`() => void`): Moves focus to the search field.

### Events

A `before` output emits `{ value, reason, event, cancel() }` before the change, and its plain output follows with the value alone. A bound `value`, `query` or `pages` only updates when its change isn't canceled.

| Binding               | On              | Receives                                                                                               |
| --------------------- | --------------- | ------------------------------------------------------------------------------------------------------ |
| `[(value)]`           | `uiCommand`     | The highlighted command                                                                                |
| `[(query)]`           | `uiCommand`     | The search text                                                                                        |
| `[(pages)]`           | `uiCommand`     | The stack of pages                                                                                     |
| `(beforeValueChange)` | `uiCommand`     | `{ value, reason, cancel() }`: the highlighted command, the [reason](#reasons) and its `index`         |
| `(beforeQueryChange)` | `uiCommand`     | `{ value, reason, cancel() }`: the new text, the [reason](#reasons) and whether it's still `composing` |
| `(beforePagesChange)` | `uiCommand`     | `{ value, reason, cancel() }`: the new stack, and the [reason](#reasons)                               |
| `(action)`            | `uiCommand`     | `{ value, event, waitUntil() }`: the command that ran. `waitUntil(promise)` marks it pending           |
| `(loadMore)`          | `uiCommand`     | `()`, when the last command is reached                                                                 |
| `(select)`            | `uiCommandItem` | `{ event, waitUntil() }`: before `(action)`. `$event.event.preventDefault()` skips it                  |

## Accessibility

The command list follows the [WAI-ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) with a listbox that's always shown. Focus stays in the input, which points to the highlighted command with `aria-activedescendant`. Every line below is an automated test.

### Keyboard

| Key                | Does                                                                  |
| ------------------ | --------------------------------------------------------------------- |
| Typing             | Filters the commands and highlights the best match                    |
| ArrowDown, ArrowUp | Moves the highlight. Wraps unless `[loop]="false"`                    |
| Enter              | Runs the highlighted command, or follows it when it renders as a link |
| Escape             | Clears the search, then goes back a page                              |
| Backspace          | In an empty search, goes back a page and restores its query           |
| An item's shortcut | Runs it while the list is mounted, even when hidden by the search     |

The first available command is highlighted by default. Set `autoHighlight` to `false` to wait for an arrow key or pointer movement.

### Tested Behavior

**Field**

- Is a combobox that controls an always-expanded listbox.
- The list is named by the field, not by what's typed.
- The first command is highlighted from the start.

**Filtering**

- Typing keeps the commands that match, ignoring case and accents.
- Groups without a match hide, and the rest keep their labels.
- The first match is highlighted as the text changes, so Enter runs it.
- Deleting text brings back the commands the shorter text matches.
- Commands without a value that mount while the field has text show when they match.
- Going back a page reports the new highlight as back, not as a removal.
- Nothing matching shows the empty message.

**Keyboard**

- Arrow keys move the highlight while focus stays in the field.
- Home and End stay in the field for the caret.
- The highlighted option has the id aria-activedescendant names.
- Enter runs the highlighted command.

**Pointer**

- Clicking a command runs it.
- A disabled command doesn't run.

**AutoHighlight**

- Without autoHighlight, nothing is highlighted until an arrow key.

Runs in React, Vue and web components.

Long lists stay fast and announce their size:

**Virtualized**

- Renders only the rows in view, each with its place in the whole list.
- Arrow keys reach commands that weren't rendered, and the active descendant follows.
- Typing ranks every command, rendered or not, best match first.

Runs in React.

Also tested:

**Enhancements**

- The highlighted command is the selected option, as the APG's list autocomplete marks it.
- Keywords match as well as labels.
- Fuzzy matching finds the letters in order, across words.
- Arrow keys skip disabled commands.
- A command's shortcut runs it and sets aria-keyshortcuts.
- A shortcut runs its command while the search hides it.
- A command is pending while its action's Promise runs, and runs only once.
- A command opens its page, and Backspace in the empty field goes back with the text.
- Escape clears the text, then goes back a page.
- Results that still hold the highlighted command keep the highlight.
- The list is busy while results load.

Runs in React, Vue and web components.

Screen readers hear the same thing in each tested framework, recorded by a virtual screen reader:

- Announcements while searching with a keyboard.

Runs in React, Vue and web components.
