# Command

搜索命令、运行动作，打开包含更多选项的页面。

Command 把搜索框放在操作列表之上。搜索期间列表保持打开。你可以单独使用它，或把它放进对话框来构建命令面板。

```svelte title="demo.svelte"
<script lang="ts">
  import {
    CalculatorIcon,
    CalendarIcon,
    CreditCardIcon,
    SearchIcon,
    SettingsIcon,
    SmileIcon,
    UserIcon,
  } from "@lucide/svelte"
  import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandSeparator,
    CommandShortcut,
  } from "@ui-sdk/svelte/command"

  const suggestions = [
    { value: "calendar", label: "Calendar", icon: CalendarIcon },
    { value: "emoji", label: "Search Emoji", icon: SmileIcon },
    {
      value: "calculator",
      label: "Calculator",
      icon: CalculatorIcon,
      disabled: true,
    },
  ]

  const settings = [
    { value: "profile", label: "Profile", icon: UserIcon, shortcut: "mod+p" },
    {
      value: "billing",
      label: "Billing",
      icon: CreditCardIcon,
      shortcut: "mod+b",
    },
    {
      value: "settings",
      label: "Settings",
      icon: SettingsIcon,
      shortcut: "mod+s",
    },
  ]
</script>

<Command>
  <div data-slot="row">
    <SearchIcon aria-hidden="true" />
    <CommandInput
      aria-label="Search commands"
      placeholder="Type a command or search…"
    />
  </div>
  <CommandEmpty>No results found.</CommandEmpty>
  <CommandList>
    <CommandGroup>
      <CommandGroupLabel>Suggestions</CommandGroupLabel>
      {#each suggestions as item (item.value)}
        <CommandItem value={item.value} disabled={item.disabled}>
          <CommandItemIcon>
            <item.icon />
          </CommandItemIcon>
          <span>{item.label}</span>
        </CommandItem>
      {/each}
    </CommandGroup>
    <CommandSeparator />
    <CommandGroup>
      <CommandGroupLabel>Settings</CommandGroupLabel>
      {#each settings as item (item.value)}
        <CommandItem value={item.value} shortcut={item.shortcut}>
          <CommandItemIcon>
            <item.icon />
          </CommandItemIcon>
          <span>{item.label}</span>
          <CommandShortcut />
        </CommandItem>
      {/each}
    </CommandGroup>
  </CommandList>
</Command>
```

输入“bil”找到 Billing。方向键移动高亮；Escape 清空搜索。

## 安装
```bash
npm install @ui-sdk/svelte @ui-sdk/core
```

## 组合
用下面的组合构建 `Command`：

```text
Command
├── CommandInput
├── CommandEmpty
└── CommandList
    ├── CommandItem
    └── CommandItem
```

给输入框一个无障碍名称，并给每个命令一个唯一的值。把空状态和状态消息放在列表之外，列表里放的是命令和分组。`onAction` 报告运行的命令的值；用它来执行动作。

用 `CommandGroup` 和 `CommandGroupLabel` 给相关的命令命名，在分组之间放一个 `CommandSeparator`。当过滤让它们变空时，分组和分隔符会消失。

## 用法
导入部件并把它们组合起来：

```svelte
<script lang="ts">
  import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
  } from "@ui-sdk/svelte/command"
</script>

<Command>
  <CommandInput aria-label="Search commands" />
  <CommandEmpty>No commands found.</CommandEmpty>
  <CommandList>
    <CommandItem value="new-file">New file</CommandItem>
    <CommandItem value="new-folder">New folder</CommandItem>
  </CommandList>
</Command>
```

## 自己构建
`@ui-sdk/svelte/command` 自带一个现成的 Command。如果你想用自己的命名自己构建，可以从 `@ui-sdk/core` 里的 `command` 原语（primitive）开始：

```ts title="palette.ts"
import { command } from "@ui-sdk/core/command"
import { createParts } from "@ui-sdk/svelte/primitive"

const {
  Root: Palette,
  Input: PaletteSearch,
  Empty: PaletteEmpty,
  List: PaletteList,
  Item: PaletteAction,
} = createParts(command, {
  input: "input",
  empty: "div",
  list: "div",
  item: "div",
})

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

```svelte
<Palette>
  <PaletteSearch aria-label="Search actions" />
  <PaletteEmpty>No actions found.</PaletteEmpty>
  <PaletteList>
    <PaletteAction value="new-file">New file</PaletteAction>
    <PaletteAction value="new-folder">New folder</PaletteAction>
  </PaletteList>
</Palette>
```

每个部件都保留其现成对应部件的行为、状态和数据属性：输入会过滤命令，方向键移动高亮，Enter 运行它。更多内容见[渲染](/docs/svelte/rendering)和[自定义部件](/docs/svelte/custom-parts)。

## 对话框
把 Command 放进 [Dialog](/docs/svelte/components/dialog) 里，做成命令面板。给对话框一个标题，在它的触发器上设置 `shortcut="mod+k"`，并在命令运行时关闭它。对话框会处理关闭，并把焦点返回触发器。

```svelte title="dialog.svelte"
<script lang="ts">
  import {
    CalculatorIcon,
    CalendarIcon,
    CreditCardIcon,
    SearchIcon,
    SettingsIcon,
    SmileIcon,
    UserIcon,
  } from "@lucide/svelte"
  import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
  } from "@ui-sdk/svelte/command"
  import {
    Dialog,
    DialogBackdrop,
    DialogContent,
    DialogShortcut,
    DialogTitle,
    DialogTrigger,
  } from "@ui-sdk/svelte/dialog"
  import { useLog } from "./log"

  const commands = [
    { value: "calendar", label: "Calendar", icon: CalendarIcon },
    { value: "emoji", label: "Search Emoji", icon: SmileIcon },
    {
      value: "calculator",
      label: "Calculator",
      icon: CalculatorIcon,
      disabled: true,
    },
    { value: "profile", label: "Profile", icon: UserIcon },
    { value: "billing", label: "Billing", icon: CreditCardIcon },
    { value: "settings", label: "Settings", icon: SettingsIcon },
  ]

  const log = useLog()
  let open = $state(false)

  function onAction(value: string) {
    log(`Ran ${value}`)
    open = false
  }
</script>

<div data-slot="stack">
  <Dialog bind:open>
    <DialogTrigger shortcut="mod+k">
      Search…
      <DialogShortcut />
    </DialogTrigger>
    <DialogBackdrop />
    <DialogContent>
      <DialogTitle>Command palette</DialogTitle>
      <Command {onAction}>
        <div data-slot="row">
          <SearchIcon aria-hidden="true" />
          <CommandInput
            aria-label="Search commands"
            placeholder="Type a command or search…"
          />
        </div>
        <CommandEmpty>No results found.</CommandEmpty>
        <CommandList>
          <CommandGroup>
            <CommandGroupLabel>Suggestions</CommandGroupLabel>
            {#each commands as item (item.value)}
              <CommandItem value={item.value} disabled={item.disabled}>
                <CommandItemIcon>
                  <item.icon />
                </CommandItemIcon>
                {item.label}
              </CommandItem>
            {/each}
          </CommandGroup>
        </CommandList>
      </Command>
    </DialogContent>
  </Dialog>
</div>
```

按 Search，或使用 Cmd+K / Ctrl+K。选择一个命令来运行它并关闭命令面板；控制台会记录运行了什么。

## 快捷键
条目的 `shortcut` 可以在命令列表挂载期间运行它，即使搜索或当前页面把它藏了起来。`CommandShortcut` 显示当前平台的按键，条目会得到 `aria-keyshortcuts`。对话框里的快捷键在它打开期间生效。

```svelte title="shortcuts.svelte"
<script lang="ts">
  import { CreditCardIcon, SettingsIcon, UserIcon } from "@lucide/svelte"
  import {
    Command,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandShortcut,
  } from "@ui-sdk/svelte/command"
  import { useLog } from "./log"

  const settings = [
    { value: "profile", label: "Profile", icon: UserIcon, shortcut: "mod+p" },
    {
      value: "billing",
      label: "Billing",
      icon: CreditCardIcon,
      shortcut: "mod+b",
    },
    {
      value: "settings",
      label: "Settings",
      icon: SettingsIcon,
      shortcut: "mod+s",
    },
  ]

  const log = useLog()
</script>

<div data-slot="stack">
  <Command onAction={(value) => log(`Ran ${value}`)}>
    <CommandInput aria-label="Search settings" placeholder="Search settings…" />
    <CommandList>
      <CommandGroup>
        <CommandGroupLabel>Settings</CommandGroupLabel>
        {#each settings as item (item.value)}
          <CommandItem value={item.value} shortcut={item.shortcut}>
            <CommandItemIcon>
              <item.icon />
            </CommandItemIcon>
            <span>{item.label}</span>
            <CommandShortcut>
              {#snippet children(state)}{state.text}{/snippet}
            </CommandShortcut>
          </CommandItem>
        {/each}
      </CommandGroup>
    </CommandList>
  </Command>
</div>
```

按 Cmd+P / Ctrl+P 运行 Profile，即使搜索把它藏了起来。控制台会记录每个运行的命令。

## 高亮匹配项
`CommandItemText` 会标记匹配的文字。默认的模糊过滤可以匹配分开的字母，所以一个命令可能有多段被标记。

```svelte title="highlight.svelte"
<script lang="ts">
  import {
    CalculatorIcon,
    CalendarIcon,
    CreditCardIcon,
    SearchIcon,
    SettingsIcon,
    SmileIcon,
    UserIcon,
  } from "@lucide/svelte"
  import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandItemText,
    CommandList,
  } from "@ui-sdk/svelte/command"

  const commands = [
    { value: "calendar", label: "Calendar", icon: CalendarIcon },
    { value: "emoji", label: "Search Emoji", icon: SmileIcon },
    {
      value: "calculator",
      label: "Calculator",
      icon: CalculatorIcon,
      disabled: true,
    },
    { value: "profile", label: "Profile", icon: UserIcon },
    { value: "billing", label: "Billing", icon: CreditCardIcon },
    { value: "settings", label: "Settings", icon: SettingsIcon },
  ]
</script>

<Command>
  <div data-slot="row">
    <SearchIcon aria-hidden="true" />
    <CommandInput
      aria-label="Search commands"
      placeholder="Try “prf” or “emo”…"
    />
  </div>
  <CommandEmpty>No results found.</CommandEmpty>
  <CommandList>
    {#each commands as item (item.value)}
      <CommandItem value={item.value} disabled={item.disabled}>
        <CommandItemIcon>
          <item.icon />
        </CommandItemIcon>
        <CommandItemText>{item.label}</CommandItemText>
      </CommandItem>
    {/each}
  </CommandList>
</Command>
```

输入“prf”找到 Profile。即使匹配的字母并不相邻，它们也会被标记。

## 过滤与关键词
`"fuzzy"` 是默认值：`nf` 能匹配 New file。`"contains"` 和 `"startsWith"` 匹配文字本身。自定义函数返回布尔值或分数；返回零会隐藏命令，分数越高排得越前。

数据命令按分数排序。直接写在标记里的命令保持原有顺序，即使最佳匹配仍然会被高亮。

`keywords` 会增加搜索词，但不改变命令的标签。用它来提供同义词，或用户可能改输入的别的名称。

```svelte title="filter.svelte"
<script lang="ts">
  import { CheckIcon, ChevronDownIcon } from "@lucide/svelte"
  import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
  } from "@ui-sdk/svelte/command"
  import {
    Select,
    SelectContent,
    SelectItem,
    SelectItemIndicator,
    SelectLabel,
    SelectTrigger,
    SelectValue,
  } from "@ui-sdk/svelte/select"

  const 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"] },
  ]

  const modes = [
    { value: "fuzzy", label: "Fuzzy" },
    { value: "contains", label: "Contains" },
    { value: "startsWith", label: "Starts with" },
    { value: "words", label: "Words" },
  ]
  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))
      )
  }

  let mode = $state<Mode>("fuzzy")
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <Select
      items={modes}
      value={mode}
      onValueChange={(next) => next && (mode = next as Mode)}
    >
      <SelectLabel>Filter</SelectLabel>
      <SelectTrigger>
        <SelectValue />
        <ChevronDownIcon />
      </SelectTrigger>
      <SelectContent>
        {#each modes as option (option.value)}
          <SelectItem value={option.value}>
            {option.label}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        {/each}
      </SelectContent>
    </Select>
  </div>
  <Command filter={mode === "words" ? words : mode}>
    <CommandInput
      aria-label="Search commands"
      placeholder="Try “nf”, “zo in” or “smiley”"
    />
    <CommandEmpty>No results found.</CommandEmpty>
    <CommandList>
      {#each commands as command (command.label)}
        <CommandItem value={command.label} keywords={command.keywords}>
          {command.label}
        </CommandItem>
      {/each}
    </CommandList>
  </Command>
</div>
```

在 Fuzzy 下输入“nf”找到 New file。选择 Words 并输入“zo in”找到 Zoom in，或输入“smiley”通过关键词找到 Search emoji。

## 页面
把条目的 `page` 设为某个 `CommandPage` 的值即可打开它。没有名称的页面存放第一组命令。`pages` 数组记录已打开页面的栈。

在空的搜索框里按 Backspace 会返回，并恢复上一页的查询。Escape 先清空查询，然后返回。Go back 命令可以调用控制器上的 `pop()`。

```svelte title="pages.svelte"
<script lang="ts">
  import { ArrowLeftIcon, MoonIcon, UsersIcon } from "@lucide/svelte"
  import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandGroupLabel,
    CommandInput,
    CommandItem,
    CommandItemIcon,
    CommandList,
    CommandPage,
    createCommandController,
  } from "@ui-sdk/svelte/command"

  const themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

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

  const command = createCommandController()
  let pages = $state<string[]>([])

  function onAction(value: string) {
    if (value === "back") {
      command.pop()
    }
  }
</script>

<Command bind:pages controller={command} {onAction}>
  <div data-slot="row">
    {#each pages as page (page)}
      <span data-slot="badge">{page}</span>
    {/each}
  </div>
  <CommandInput
    aria-label="Search commands"
    placeholder={pages.length
      ? "Search… (Backspace to go back)"
      : "What do you need?"}
  />
  <CommandEmpty>No results found.</CommandEmpty>
  <CommandList>
    <CommandPage>
      <CommandGroup>
        <CommandGroupLabel>Workspace</CommandGroupLabel>
        <CommandItem value="theme" page="theme">
          <CommandItemIcon>
            <MoonIcon />
          </CommandItemIcon>
          Change theme…
        </CommandItem>
        <CommandItem value="teams" page="teams">
          <CommandItemIcon>
            <UsersIcon />
          </CommandItemIcon>
          Switch team…
        </CommandItem>
      </CommandGroup>
    </CommandPage>
    <CommandPage value="theme">
      {#each themes as theme (theme.value)}
        <CommandItem value={theme.value}>
          {theme.label}
        </CommandItem>
      {/each}
    </CommandPage>
    <CommandPage value="teams">
      {#each teams as team (team.value)}
        <CommandItem value={team.value}>
          {team.label}
        </CommandItem>
      {/each}
    </CommandPage>
    {#if pages.length > 0}
      <CommandItem value="back">
        <CommandItemIcon mirror>
          <ArrowLeftIcon />
        </CommandItemIcon>
        Go back
      </CommandItem>
    {/if}
  </CommandList>
</Command>
```

选择 Change theme 或 Switch team。用 Go back，或在空的搜索框里按 Backspace 返回。

## 以数据形式提供的条目
传入 `items`，以 `CommandData` 的形式提供命令、分组、分隔符和页面。自带 `items` 的数据命令会打开一个页面。即使另一个页面或过滤把它藏了起来，它的快捷键仍然有效。

数据可以为你渲染不带内容的部件。对于要设置样式的命令，从列表的 `state.items` 渲染，它会跟随当前页面和排序后的结果。这个示例同时处理分组、分隔符和命令。[列表与菜单](/docs/svelte/lists-and-menus)介绍了共享的数据格式。

在传入 `items` 的同时传入 `emptyItems`，在第一页搜索为空时显示建议或最近的命令。一旦有人输入，就会搜索整个集合。

```svelte
<Command
  items={commands}
  emptyItems={[{ type: "group", label: "Suggested", items: recent }]}
/>
```

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

  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" },
      ],
    },
  ]

  const log = useLog()
</script>

{#snippet commandList(items: CommandData)}
  {#each items as entry, index (typeof entry === "string" ? entry : "type" in entry ? `${entry.type}-${index}` : entry.value)}
    {#if typeof entry !== "string" && "type" in entry}
      {#if entry.type === "separator"}
        <CommandSeparator />
      {:else}
        <CommandGroup>
          <CommandGroupLabel>{entry.label}</CommandGroupLabel>
          {@render commandList(entry.items)}
        </CommandGroup>
      {/if}
    {:else}
      {@render commandItem(
        typeof entry === "string" ? { value: entry, label: entry } : entry
      )}
    {/if}
  {/each}
{/snippet}

{#snippet commandItem(command: CommandDataItem)}
  <CommandItem
    value={command.value}
    label={command.label}
    disabled={command.disabled}
    shortcut={command.shortcut}
  >
    {command.label}
    {#if command.shortcut}<CommandShortcut />{/if}
  </CommandItem>
{/snippet}

<div data-slot="stack">
  <Command items={commands} onAction={(value) => log(`Ran ${value}`)}>
    <CommandInput aria-label="Search commands" placeholder="Type a command…" />
    <CommandEmpty>No results found.</CommandEmpty>
    <CommandList>
      {#snippet children(state)}
        {@render commandList(state.items)}
      {/snippet}
    </CommandList>
  </Command>
</div>
```

选择 Change theme 打开它的命令。按 Cmd+I / Ctrl+I 从任意页面运行 Open inbox；控制台会记录运行了什么。

## 异步结果
用[异步选项](/docs/svelte/utilities/async-options)等待输入暂停，并丢弃过期的结果。把查询变化发给 `setQuery()`，渲染返回的条目，并传入 `status`。把 `filter` 设为 `false` 可以保持服务器的顺序。

`CommandStatus` 描述加载和失败，加载期间列表会得到 `aria-busy`。当滚动或高亮到达最后一个命令时，`onLoadMore` 可以请求另一页。没有状态部件时，`announcement` 控制输入暂停后的结果数量消息。

```svelte title="async.svelte"
<script lang="ts">
  import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
    CommandStatus,
  } from "@ui-sdk/svelte/command"
  import { useAsyncOptions } from "@ui-sdk/svelte/async-options"

  function 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"))
        })
      }
    )
  }

  const issues = useAsyncOptions(searchIssues, {
    debounce: 250,
    immediate: true,
  })
</script>

<Command
  filter={false}
  status={issues.state.status}
  onQueryChange={(query: string) => issues.setQuery(query)}
  onLoadMore={issues.loadMore}
>
  <CommandInput aria-label="Search issues" placeholder="Search issues…" />
  <CommandStatus>
    {#snippet children(state)}
      {state.loading
        ? "Searching…"
        : `${state.count} ${state.count === 1 ? "issue" : "issues"}`}
    {/snippet}
  </CommandStatus>
  <CommandEmpty>
    {#snippet children(state)}
      {#if state.empty && !state.loading}No issues match “{state.query}”.{/if}
    {/snippet}
  </CommandEmpty>
  <CommandList>
    {#each issues.state.items as issue (issue.value)}
      <CommandItem value={issue.value} label={issue.label}>
        {issue.label}
      </CommandItem>
    {/each}
  </CommandList>
</Command>
```

输入“login”并等待匹配的 issue。替换文字开始新的搜索；只会出现最新的结果。

## 待处理的动作
从 `onAction` 或条目的 `onSelect` 返回一个 promise，会让命令保持待处理（pending）。它会得到 `data-pending`、`aria-busy` 和 `aria-disabled`，直到 promise 结束；再次按压不会开始另一次运行。被拒绝时，它会成为命令的 `error` 状态，再次运行时会清除。

条目的 `onSelect` 在 `onAction` 之前运行。在它的事件上调用 `preventDefault()` 可以阻止这个动作。

```svelte title="pending.svelte"
<script lang="ts">
  import { LoaderCircleIcon } from "@lucide/svelte"
  import {
    Command,
    CommandInput,
    CommandItem,
    CommandList,
  } from "@ui-sdk/svelte/command"
  import { useLog } from "./log"

  const wait = (ms: number) =>
    new Promise<void>((resolve) => setTimeout(resolve, ms))

  const log = useLog()

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

  async function sync() {
    await wait(600)
    log("Couldn't sync: offline")
    throw new Error("Offline")
  }
</script>

<div data-slot="stack">
  <Command>
    <CommandInput aria-label="Search actions" placeholder="Search actions…" />
    <CommandList>
      <CommandItem value="deploy" onSelect={deploy}>
        {#snippet children(state)}
          Deploy to production
          {#if state.pending}<LoaderCircleIcon
              data-slot="spinner"
              aria-hidden="true"
            />{/if}
        {/snippet}
      </CommandItem>
      <CommandItem value="sync" onSelect={sync}>
        {#snippet children(state)}
          Sync with server
          {#if state.pending}
            <LoaderCircleIcon data-slot="spinner" aria-hidden="true" />
          {:else if state.error !== undefined}
            <span data-slot="hint">Failed, try again</span>
          {/if}
        {/snippet}
      </CommandItem>
    </CommandList>
  </Command>
</div>
```

运行 Deploy to production，并在它待处理时再试一次。Sync with server 会失败，并且可以重试；控制台会记录每次结果。

## 虚拟化
传入完整的 `items` 集合，让过滤和键盘导航包含尚未挂载的命令。只渲染可见的行，并给每一行它在当前结果中的索引。`onValueChange` 会带上这个索引，让你能把刚高亮的行滚动到可见区域。

```svelte title="virtualized.svelte"
<script lang="ts">
  import {
    Command,
    CommandInput,
    CommandItem,
    CommandList,
  } from "@ui-sdk/svelte/command"

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

  const row = 32
  const height = 256

  let scroller: HTMLDivElement | undefined = $state()
  let scrollTop = $state(0)

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

  function visible(items: typeof commands) {
    const start = Math.max(0, Math.floor(scrollTop / row) - 4)
    const end = Math.min(
      items.length,
      Math.ceil((scrollTop + height) / row) + 4
    )
    return items
      .slice(start, end)
      .map((item, offset) => ({ item, index: start + offset }))
  }
</script>

<Command items={commands} {onValueChange}>
  <CommandInput
    aria-label="Search 10,000 commands"
    placeholder="Search 10,000 commands…"
  />
  <div
    bind:this={scroller}
    onscroll={(event) => (scrollTop = event.currentTarget.scrollTop)}
  >
    <CommandList>
      {#snippet children(state)}
        <div style="height: {state.items.length * row}px">
          {#each visible(state.items as typeof commands) as { item, index } (item.value)}
            <CommandItem
              value={item.value}
              label={item.label}
              {index}
              style="top: {index * row}px"
            >
              {item.label}
            </CommandItem>
          {/each}
        </div>
      {/snippet}
    </CommandList>
  </div>
</Command>
```

搜索 10,000 个命令，或用方向键在它们之间移动。只有视口附近的行会渲染。

## 受控
高亮的命令、搜索文字和页面栈是彼此独立的：

| 值      | 形状                      | 变更通知        |
| ------- | ------------------------- | --------------- |
| `value` | 命令的字符串值或 `null`。 | `onValueChange` |
| `query` | 搜索文字。                | `onQueryChange` |
| `pages` | 页面值的数组。            | `onPagesChange` |

用 `bind:value`、`bind:query` 和 `bind:pages` 绑定它们，或使用 `defaultValue`、`defaultQuery` 和 `defaultPages` 提供起始状态。变更回调会收到详情；调用 `details.cancel()` 可以拒绝一次变更。`value` 是高亮的命令，不是已选中的命令，它会随高亮移动而变化。`onAction` 报告激活，所以只移动高亮不会运行命令。[状态与事件](/docs/svelte/state-and-events)介绍了共享的绑定模式。

```svelte title="controlled.svelte"
<script lang="ts">
  import {
    Command,
    CommandInput,
    CommandItem,
    CommandList,
    CommandPage,
  } from "@ui-sdk/svelte/command"
  import { useLog } from "./log"

  const themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

  const log = useLog()
  let value = $state<string | null>("dark")
  let query = $state("")
  let pages = $state(["theme"])
</script>

<Command
  bind:value
  bind:query
  bind:pages
  onValueChange={(next, details) =>
    log(`Highlighted ${next ?? "nothing"} (${details.reason})`)}
  onQueryChange={(next, details) => log(`Query “${next}” (${details.reason})`)}
  onPagesChange={(next, details) =>
    log(`Pages [${next.join(", ")}] (${details.reason})`)}
  onAction={(next) => log(`Ran ${next}`)}
>
  <CommandInput aria-label="Search themes" placeholder="Search themes…" />
  <CommandList>
    <CommandPage>
      <CommandItem value="theme" page="theme">Change theme…</CommandItem>
    </CommandPage>
    <CommandPage value="theme">
      {#each themes as theme (theme.value)}
        <CommandItem value={theme.value}>
          {theme.label}
        </CommandItem>
      {/each}
    </CommandPage>
  </CommandList>
</Command>
```

打开 Change theme，搜索并移动高亮。控制台会记录每次高亮、查询和页面变更及其原因。

## 控制器
为一个实例创建一个 `createCommandController()`，并作为 `controller` 传入。它可以读取和设置高亮、查询和页面栈。用 `push()` 和 `pop()` 在页面之间导航，用 `run()` 运行高亮的命令或指定的命令，用 `focus()` 聚焦搜索框。设置和生命周期见[控制器](/docs/svelte/controllers)。

```svelte title="controller.svelte"
<script lang="ts">
  import {
    Command,
    CommandInput,
    CommandItem,
    CommandList,
    CommandPage,
    createCommandController,
  } from "@ui-sdk/svelte/command"
  import { useLog } from "./log"

  const themes = [
    { value: "light", label: "Light" },
    { value: "dark", label: "Dark" },
    { value: "system", label: "System" },
  ]

  const palette = createCommandController()
  const log = useLog()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => palette.push("theme")}>
      Open Themes
    </button>
    <button type="button" onclick={() => palette.pop()}> Back </button>
    <button type="button" onclick={() => palette.setValue("dark")}>
      Highlight Dark
    </button>
    <button type="button" onclick={() => palette.setQuery("li")}>
      Search “li”
    </button>
    <button type="button" onclick={() => palette.run()}>
      Run Highlighted
    </button>
    <button type="button" onclick={() => palette.focus()}> Focus </button>
  </div>
  <Command controller={palette} onAction={(value) => log(`Ran ${value}`)}>
    <CommandInput aria-label="Search commands" />
    <CommandList>
      <CommandPage>
        <CommandItem value="theme" page="theme">Change theme…</CommandItem>
      </CommandPage>
      <CommandPage value="theme">
        {#each themes as theme (theme.value)}
          <CommandItem value={theme.value}>
            {theme.label}
          </CommandItem>
        {/each}
      </CommandPage>
    </CommandList>
  </Command>
</div>
```

用按钮从外部打开页面、搜索、移动高亮并运行它。控制台会记录每个运行的命令。

## 自定义渲染
当命令需要导航时，把它渲染成链接。Enter 会跟随高亮的链接；带修饰键的点击保留浏览器一贯的行为。

```svelte title="custom-rendering.svelte"
<script lang="ts">
  import { CornerDownLeftIcon } from "@lucide/svelte"
  import {
    Command,
    CommandInput,
    CommandItem,
    CommandItemText,
    CommandList,
  } from "@ui-sdk/svelte/command"

  const pages = ["Composition", "Installation", "Styling"]
</script>

<Command>
  <CommandInput aria-label="Search docs" placeholder="Search docs…" />
  <CommandList>
    {#each pages as page (page)}
      <CommandItem value={page}>
        {#snippet render({ props, state, children })}
          <a {...props} href="#{page.toLowerCase()}"
            >{@render children?.(state)}</a
          >
        {/snippet}
        {#snippet children(state)}
          <CommandItemText>
            {#snippet render({ props, state: text })}
              <span {...props}>
                {#each text.segments as segment, index (index)}
                  {#if segment.match}<strong>{segment.text}</strong
                    >{:else}{segment.text}{/if}
                {/each}
              </span>
            {/snippet}
          </CommandItemText>
          {#if state.highlighted}<CornerDownLeftIcon aria-hidden="true" />{/if}
        {/snippet}
      </CommandItem>
    {/each}
  </CommandList>
</Command>
```

搜索 Installation 并按 Enter。命令会跟随链接跳到本页的那个小节。

## 样式
每个部件都有一个 `data-slot`，比如 `command-item`，并通过[数据属性](https://ui-sdk.cn/docs/svelte/components/command#data-attributes)下列出的属性展示状态。

用 `data-highlighted` 表示活动的命令，用 `data-pending` 表示进行中的动作。给列表设置高度限制，长列表再加 `overflow-y: auto`；键盘导航会把高亮的命令滚动到可见区域。混合有图标和没有图标的命令时，列表上的 `data-has-icons` 和每个条目上的 `data-has-icon` 让你可以用逻辑内边距预留对应的空间。

## 数据属性
### 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 参考
属性和回调与下面相同，都作为 Svelte props。

### 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`.
- `onValueChange?` (`((value: string | null, details: CommandValueChangeDetails) => void)`): 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.
- `onQueryChange?` (`((query: string, details: TextChangeDetails<CommandQueryChangeReason>) => void)`): 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.
- `onPagesChange?` (`((pages: string[], details: ChangeDetails<CommandPagesChangeReason>) => void)`): Runs when a page opens or Backspace or Escape goes back.
- `onAction?` (`((value: string, details: CommandActionDetails) => unknown)`): 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.
- `onLoadMore?` (`(() => void)`): 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
搜索框。渲染一个带 combobox 角色的 `input`。

### CommandStatus
描述加载和失败。渲染一个带 status 角色的 `div`。

### CommandEmpty
没有命令匹配时显示。渲染一个 `div`。

### CommandList
容纳命令。渲染一个带 listbox 角色的 `div`，始终显示。

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

### CommandGroup
把命令分组在名称之下。渲染一个带 group 角色的 `div`。

### CommandGroupLabel
为它的分组提供名称。渲染一个 `div`。

### CommandItem
- `value?` (`string`): Passed to `onAction` and `onValueChange`, 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`.
- `onSelect?` (`((event: Event) => unknown)`): Runs when the command runs, before `onAction`, 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 `onAction` and the page. Return a Promise to mark the command pending until it settles, like `onAction`.

### 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
显示命令的标签，并标记搜索匹配的内容。渲染一个 `span`。

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

### CommandSeparator
分隔命令或分组。渲染一个带 separator 角色的 `div`。

### 以数据形式提供的条目
`items` 中的每个命令。分组是 `{ type: "group", label, items }`，分隔符是 `{ 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.

### 状态
每个部件的 `render` 和 `children` snippet 会收到什么。

`Command`:

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

`CommandInput`:

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

`CommandList`:

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

`CommandItem`:

- `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.

`CommandEmpty`:

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

`CommandStatus`:

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

`CommandShortcut`:

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

`CommandItemText`，它没有自己的 props：

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

`CommandItemIcon`:

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

### 原因
高亮的命令为什么变化：

- `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.

搜索文字为什么变化：

- `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.

以及页面栈为什么变化：

- `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.

### 控制器
用 `createCommandController()` 创建一个，并作为 `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.

### 事件
回调先收到新状态，然后收到详情。绑定的 `value`、`query` 或 `pages` 只在它的回调没有被取消时更新。

| 属性            | 所属          | 收到                                                                                      |
| --------------- | ------------- | ----------------------------------------------------------------------------------------- |
| `bind:value`    | `Command`     | 高亮的命令                                                                                |
| `bind:query`    | `Command`     | 搜索文字                                                                                  |
| `bind:pages`    | `Command`     | 页面栈                                                                                    |
| `onValueChange` | `Command`     | `(value, details)`：高亮的命令、[原因](https://ui-sdk.cn/docs/svelte/components/command#reasons)及其 `index`                              |
| `onQueryChange` | `Command`     | `(query, details)`：新文字、[原因](https://ui-sdk.cn/docs/svelte/components/command#reasons)以及它是否仍在 `composing`                    |
| `onPagesChange` | `Command`     | `(pages, details)`：新的栈，以及[原因](https://ui-sdk.cn/docs/svelte/components/command#reasons)                                          |
| `onAction`      | `Command`     | `(value, { event })`：运行的命令。返回一个 Promise 让它保持待处理                         |
| `onLoadMore`    | `Command`     | `()`，当到达最后一个命令时                                                                |
| `onSelect`      | `CommandItem` | `(event)`：在 `onAction` 之前。`preventDefault()` 会跳过它。返回 Promise 会让它保持待处理 |

## 无障碍
命令列表遵循 [WAI-ARIA 组合框模式](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/)，其中的列表始终显示。焦点留在输入框里，输入框用 `aria-activedescendant` 指向高亮的命令。下面每一行都是一个自动化测试。

### 键盘
| 按键               | 作用                                          |
| ------------------ | --------------------------------------------- |
| Typing             | 过滤命令并高亮最佳匹配                        |
| ArrowDown, ArrowUp | 移动高亮。除非 `loop={false}`，到任一端会绕回 |
| Enter              | 运行高亮的命令，或在它渲染成链接时跟随它      |
| Escape             | 清空搜索，然后返回上一页                      |
| Backspace          | 在空的搜索框里，返回上一页并恢复它的查询      |
| An item's shortcut | 在列表挂载期间运行它，即使搜索把它藏了起来    |

默认会高亮第一个可用的命令。把 `autoHighlight` 设为 `false` 可以等待方向键或指针移动。

### 经过测试的行为
**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 和 web components.

长列表保持快速，并播报自己的大小：

**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.

另外也测试了：

**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 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while searching with a keyboard.

Runs in React、Vue 和 web components.
