# Command

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

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

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

<template>
  <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>
        <CommandItem
          v-for="item in suggestions"
          :key="item.value"
          :value="item.value"
          :disabled="item.disabled"
        >
          <CommandItemIcon>
            <component :is="item.icon" />
          </CommandItemIcon>
          <span>{{ item.label }}</span>
        </CommandItem>
      </CommandGroup>
      <CommandSeparator />
      <CommandGroup>
        <CommandGroupLabel>Settings</CommandGroupLabel>
        <CommandItem
          v-for="item in settings"
          :key="item.value"
          :value="item.value"
          :shortcut="item.shortcut"
        >
          <CommandItemIcon>
            <component :is="item.icon" />
          </CommandItemIcon>
          <span>{{ item.label }}</span>
          <CommandShortcut />
        </CommandItem>
      </CommandGroup>
    </CommandList>
  </Command>
</template>
```

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

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

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

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

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

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

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

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

<template>
  <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>
</template>
```

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

```ts title="palette.ts"
import { command } from "@ui-sdk/core/command"
import { createParts } from "@ui-sdk/vue/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 }
```

```vue
<template>
  <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>
</template>
```

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

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

```vue title="dialog.vue"
<script setup lang="ts">
import {
  CalculatorIcon,
  CalendarIcon,
  CreditCardIcon,
  SearchIcon,
  SettingsIcon,
  SmileIcon,
  UserIcon,
} from "@lucide/vue"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
} from "@ui-sdk/vue/command"
import {
  Dialog,
  DialogBackdrop,
  DialogContent,
  DialogShortcut,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/vue/dialog"
import { ref } from "vue"
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 open = ref(false)
const log = useLog()

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

<template>
  <div data-slot="stack">
    <Dialog v-model:open="open">
      <DialogTrigger shortcut="mod+k">
        Search…
        <DialogShortcut />
      </DialogTrigger>
      <DialogBackdrop />
      <DialogContent>
        <DialogTitle>Command palette</DialogTitle>
        <Command @action="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>
              <CommandItem
                v-for="item in commands"
                :key="item.value"
                :value="item.value"
                :disabled="item.disabled"
              >
                <CommandItemIcon>
                  <component :is="item.icon" />
                </CommandItemIcon>
                {{ item.label }}
              </CommandItem>
            </CommandGroup>
          </CommandList>
        </Command>
      </DialogContent>
    </Dialog>
  </div>
</template>
```

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

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

```vue title="shortcuts.vue"
<script setup lang="ts">
import { CreditCardIcon, SettingsIcon, UserIcon } from "@lucide/vue"
import {
  Command,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandShortcut,
} from "@ui-sdk/vue/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>

<template>
  <div data-slot="stack">
    <Command @action="(value: string) => log(`Ran ${value}`)">
      <CommandInput
        aria-label="Search settings"
        placeholder="Search settings…"
      />
      <CommandList>
        <CommandGroup>
          <CommandGroupLabel>Settings</CommandGroupLabel>
          <CommandItem
            v-for="item in settings"
            :key="item.value"
            :value="item.value"
            :shortcut="item.shortcut"
          >
            <CommandItemIcon>
              <component :is="item.icon" />
            </CommandItemIcon>
            <span>{{ item.label }}</span>
            <CommandShortcut v-slot="{ state }">{{
              state.text
            }}</CommandShortcut>
          </CommandItem>
        </CommandGroup>
      </CommandList>
    </Command>
  </div>
</template>
```

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

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

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

<template>
  <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>
      <CommandItem
        v-for="item in commands"
        :key="item.value"
        :value="item.value"
        :disabled="item.disabled"
      >
        <CommandItemIcon>
          <component :is="item.icon" />
        </CommandItemIcon>
        <CommandItemText>{{ item.label }}</CommandItemText>
      </CommandItem>
    </CommandList>
  </Command>
</template>
```

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

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

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

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

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

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

const mode = ref<Mode>("fuzzy")
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <Select
        :items="modes"
        :value="mode"
        @value-change="(next) => next && (mode = next as Mode)"
      >
        <SelectLabel>Filter</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in modes"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        </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>
        <CommandItem
          v-for="command in commands"
          :key="command.label"
          :value="command.label"
          :keywords="command.keywords"
        >
          {{ command.label }}
        </CommandItem>
      </CommandList>
    </Command>
  </div>
</template>
```

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

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

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

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

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()
const pages = ref<string[]>([])

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

<template>
  <Command v-model:pages="pages" :controller="command" @action="onAction">
    <div data-slot="row">
      <span v-for="page in pages" :key="page" data-slot="badge">{{
        page
      }}</span>
    </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">
        <CommandItem
          v-for="theme in themes"
          :key="theme.value"
          :value="theme.value"
        >
          {{ theme.label }}
        </CommandItem>
      </CommandPage>
      <CommandPage value="teams">
        <CommandItem
          v-for="team in teams"
          :key="team.value"
          :value="team.value"
        >
          {{ team.label }}
        </CommandItem>
      </CommandPage>
      <CommandItem v-if="pages.length > 0" value="back">
        <CommandItemIcon mirror>
          <ArrowLeftIcon />
        </CommandItemIcon>
        Go back
      </CommandItem>
    </CommandList>
  </Command>
</template>
```

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

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

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

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

```vue
<Command
  :items="commands"
  :empty-items="[{ type: 'group', label: 'Suggested', items: recent }]"
/>
```

```vue title="data.vue"
<script setup lang="ts">
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
  type CommandData,
  type CommandDataItem,
} from "@ui-sdk/vue/command"
import { h, type FunctionalComponent } from "vue"
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 Commands: FunctionalComponent<{ items: CommandData }> = ({ items }) =>
  items.map((entry, index) => {
    if (typeof entry !== "string" && "type" in entry) {
      if (entry.type === "separator") {
        return h(CommandSeparator, { key: `separator-${index}` })
      }
      return h(CommandGroup, { key: entry.label }, () => [
        h(CommandGroupLabel, () => entry.label),
        h(Commands, { items: entry.items }),
      ])
    }
    const command: CommandDataItem =
      typeof entry === "string" ? { value: entry, label: entry } : entry
    return h(
      CommandItem,
      {
        key: command.value,
        value: command.value,
        label: command.label,
        disabled: command.disabled,
        shortcut: command.shortcut,
      },
      () => [command.label, command.shortcut && h(CommandShortcut)]
    )
  })

const log = useLog()
</script>

<template>
  <div data-slot="stack">
    <Command :items="commands" @action="(value: string) => log(`Ran ${value}`)">
      <CommandInput
        aria-label="Search commands"
        placeholder="Type a command…"
      />
      <CommandEmpty>No results found.</CommandEmpty>
      <CommandList v-slot="{ state }">
        <Commands :items="state.items" />
      </CommandList>
    </Command>
  </div>
</template>
```

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

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

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

```vue title="async.vue"
<script setup lang="ts">
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
  CommandStatus,
} from "@ui-sdk/vue/command"
import { useAsyncOptions } from "@ui-sdk/vue/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 {
  state: issues,
  setQuery,
  loadMore,
} = useAsyncOptions(searchIssues, { debounce: 250, immediate: true })
</script>

<template>
  <Command
    :filter="false"
    :status="issues.status"
    @query-change="(query: string) => setQuery(query)"
    @load-more="loadMore"
  >
    <CommandInput aria-label="Search issues" placeholder="Search issues…" />
    <CommandStatus v-slot="{ state }">
      {{
        state.loading
          ? "Searching…"
          : `${state.count} ${state.count === 1 ? "issue" : "issues"}`
      }}
    </CommandStatus>
    <CommandEmpty v-slot="{ state }">
      <template v-if="state.empty && !state.loading"
        >No issues match “{{ state.query }}”.</template
      >
    </CommandEmpty>
    <CommandList>
      <CommandItem
        v-for="issue in issues.items"
        :key="issue.value"
        :value="issue.value"
        :label="issue.label"
      >
        {{ issue.label }}
      </CommandItem>
    </CommandList>
  </Command>
</template>
```

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

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

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

```vue title="pending.vue"
<script setup lang="ts">
import { LoaderCircleIcon } from "@lucide/vue"
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/vue/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>

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

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

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

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

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

const row = 32
const height = 256

const scroller = ref<HTMLDivElement | null>(null)
const scrollTop = ref(0)

function onValueChange(_value: string | null, { index }: { index: number }) {
  const el = scroller.value
  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.value / row) - 4)
  const end = Math.min(
    items.length,
    Math.ceil((scrollTop.value + height) / row) + 4
  )
  return items
    .slice(start, end)
    .map((item, offset) => ({ item, index: start + offset }))
}
</script>

<template>
  <Command :items="commands" @value-change="onValueChange">
    <CommandInput
      aria-label="Search 10,000 commands"
      placeholder="Search 10,000 commands…"
    />
    <div
      ref="scroller"
      @scroll="scrollTop = ($event.currentTarget as HTMLDivElement).scrollTop"
    >
      <CommandList v-slot="{ state }">
        <div :style="{ height: `${state.items.length * row}px` }">
          <CommandItem
            v-for="{ item, index } in visible(state.items as typeof commands)"
            :key="item.value"
            :value="item.value"
            :label="item.label"
            :index="index"
            :style="{ top: `${index * row}px` }"
          >
            {{ item.label }}
          </CommandItem>
        </div>
      </CommandList>
    </div>
  </Command>
</template>
```

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

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

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

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

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

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

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

<template>
  <Command
    v-model:value="value"
    v-model:query="query"
    v-model:pages="pages"
    @value-change="
      (next: string | null, details: { reason: string }) =>
        log(`Highlighted ${next ?? 'nothing'} (${details.reason})`)
    "
    @query-change="
      (next: string, details: { reason: string }) =>
        log(`Query “${next}” (${details.reason})`)
    "
    @pages-change="
      (next: string[], details: { reason: string }) =>
        log(`Pages [${next.join(', ')}] (${details.reason})`)
    "
    @action="(next: string) => 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">
        <CommandItem
          v-for="theme in themes"
          :key="theme.value"
          :value="theme.value"
        >
          {{ theme.label }}
        </CommandItem>
      </CommandPage>
    </CommandList>
  </Command>
</template>
```

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

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

```vue title="controller.vue"
<script setup lang="ts">
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
  CommandPage,
  createCommandController,
} from "@ui-sdk/vue/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>

<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>
    <Command
      :controller="palette"
      @action="(value: string) => log(`Ran ${value}`)"
    >
      <CommandInput aria-label="Search commands" />
      <CommandList>
        <CommandPage>
          <CommandItem value="theme" page="theme">Change theme…</CommandItem>
        </CommandPage>
        <CommandPage value="theme">
          <CommandItem
            v-for="theme in themes"
            :key="theme.value"
            :value="theme.value"
          >
            {{ theme.label }}
          </CommandItem>
        </CommandPage>
      </CommandList>
    </Command>
  </div>
</template>
```

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

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

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

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

<template>
  <Command>
    <CommandInput aria-label="Search docs" placeholder="Search docs…" />
    <CommandList>
      <CommandItem v-for="page in pages" :key="page" :value="page">
        <template #render="{ props, children }">
          <a v-bind="props" :href="`#${page.toLowerCase()}`"
            ><component :is="children"
          /></a>
        </template>
        <template #default="{ state }">
          <CommandItemText v-slot="{ state: text }">
            <template v-for="(segment, index) in text.segments" :key="index">
              <strong v-if="segment.match">{{ segment.text }}</strong>
              <template v-else>{{ segment.text }}</template>
            </template>
          </CommandItemText>
          <CornerDownLeftIcon v-if="state.highlighted" aria-hidden="true" />
        </template>
      </CommandItem>
    </CommandList>
  </Command>
</template>
```

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

## 样式
每个部件都有一个 `data-slot`，比如 `command-item`，并通过[数据属性](https://ui-sdk.cn/docs/vue/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 参考
属性与下面相同，回调是事件，但 `onAction` 和 `onSelect` 例外，它们是函数 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`.
- `@value-change` (`((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.
- `@query-change` (`((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.
- `@pages-change` (`((pages: string[], details: ChangeDetails<CommandPagesChangeReason>) => void)`): Runs when a page opens or Backspace or Escape goes back.
- `@action` (`((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.
- `@load-more` (`(() => 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 `@action` and `@value-change`, 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` (`((event: Event) => unknown)`): 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
显示命令的标签，并标记搜索匹配的内容。渲染一个 `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.

### 状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。

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

### 事件
事件先收到新状态，然后收到详情。`v-model` 只在变更事件没有被取消时更新。

| 绑定            | 所属          | 收到                                                                                                |
| --------------- | ------------- | --------------------------------------------------------------------------------------------------- |
| `v-model:value` | `Command`     | 高亮的命令                                                                                          |
| `v-model:query` | `Command`     | 搜索文字                                                                                            |
| `v-model:pages` | `Command`     | 页面栈                                                                                              |
| `@value-change` | `Command`     | `(value, details)`：高亮的命令、[原因](https://ui-sdk.cn/docs/vue/components/command#reasons)及其 `index`                                        |
| `@query-change` | `Command`     | `(query, details)`：新文字、[原因](https://ui-sdk.cn/docs/vue/components/command#reasons)以及它是否仍在 `composing`                              |
| `@pages-change` | `Command`     | `(pages, details)`：新的栈，以及[原因](https://ui-sdk.cn/docs/vue/components/command#reasons)                                                    |
| `@action`       | `Command`     | `(value, { event })`，函数 prop。返回一个 Promise 让命令保持待处理                                  |
| `@load-more`    | `Command`     | 当到达最后一个命令时                                                                                |
| `@select`       | `CommandItem` | `(event)`，函数 prop，在 `@action` 之前。`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 | 在列表挂载期间运行它，即使搜索把它藏了起来     |

默认会高亮第一个可用的命令。设置 `:auto-highlight="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.
