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

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

import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Calendar = icon(
  '<path d="M8 2v3" /><path d="M16 2v3" /><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18" />'
)
const Smile = icon(
  '<path d="M15 10V9" /><path d="M16.472 15a6 6 0 01-8.943 0" /><path d="M9 10V9" /><circle cx="12" cy="12" r="10" />'
)
const Calculator = icon(
  '<rect width="16" height="20" x="4" y="2" rx="2" /><line x1="8" x2="16" y1="6" y2="6" /><line x1="16" x2="16" y1="14" y2="18" /><path d="M16 10h.01" /><path d="M12 10h.01" /><path d="M8 10h.01" /><path d="M12 14h.01" /><path d="M8 14h.01" /><path d="M12 18h.01" /><path d="M8 18h.01" />'
)
const User = icon(
  '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />'
)
const CreditCard = icon(
  '<rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /><path d="M6 14h2" />'
)
const Settings = icon(
  '<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" /><circle cx="12" cy="12" r="3" />'
)
const Search = icon(
  '<path d="m21 21-4.34-4.34" /><circle cx="11" cy="11" r="8" />'
)

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

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

function Example() {
  return (
    <Command>
      <div data-slot="row">
        <Search 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>
          <For each={suggestions}>
            {(item) => (
              <CommandItem value={item.value} disabled={item.disabled}>
                <CommandItemIcon>
                  <item.icon />
                </CommandItemIcon>
                <span>{item.label}</span>
              </CommandItem>
            )}
          </For>
        </CommandGroup>
        <CommandSeparator />
        <CommandGroup>
          <CommandGroupLabel>Settings</CommandGroupLabel>
          <For each={settings}>
            {(item) => (
              <CommandItem value={item.value} shortcut={item.shortcut}>
                <CommandItemIcon>
                  <item.icon />
                </CommandItemIcon>
                <span>{item.label}</span>
                <CommandShortcut />
              </CommandItem>
            )}
          </For>
        </CommandGroup>
      </CommandList>
    </Command>
  )
}

export { Example }
输入“bil”找到 Billing。方向键移动高亮;Escape 清空搜索。

安装

npm install @ui-sdk/solid @ui-sdk/core

组合

用下面的组合构建 Command:

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

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

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

用法

导入部件并把它们组合起来:

import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/solid/command"

function Example() {
  return (
    <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>
  )
}

export { Example }

自己构建

@ui-sdk/solid/command 自带一个现成的 Command。如果你想用自己的命名自己构建,可以从 @ui-sdk/core 里的 command 原语(primitive)开始:

palette.ts
import { command } from "@ui-sdk/core/command"
import { createParts } from "@ui-sdk/solid/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 }
<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 运行它。更多内容见渲染和自定义部件。

对话框

把 Command 放进 Dialog 里,做成命令面板。给对话框一个标题,在它的触发器上设置 shortcut="mod+k",并在命令运行时关闭它。对话框会处理关闭,并把焦点返回触发器。

控制台
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
} from "@ui-sdk/solid/command"
import {
  Dialog,
  DialogBackdrop,
  DialogContent,
  DialogShortcut,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/solid/dialog"
import { createSignal, For } from "solid-js"
import { useLog } from "./log"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Calendar = icon(
  '<path d="M8 2v3" /><path d="M16 2v3" /><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18" />'
)
const Smile = icon(
  '<path d="M15 10V9" /><path d="M16.472 15a6 6 0 01-8.943 0" /><path d="M9 10V9" /><circle cx="12" cy="12" r="10" />'
)
const Calculator = icon(
  '<rect width="16" height="20" x="4" y="2" rx="2" /><line x1="8" x2="16" y1="6" y2="6" /><line x1="16" x2="16" y1="14" y2="18" /><path d="M16 10h.01" /><path d="M12 10h.01" /><path d="M8 10h.01" /><path d="M12 14h.01" /><path d="M8 14h.01" /><path d="M12 18h.01" /><path d="M8 18h.01" />'
)
const User = icon(
  '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />'
)
const CreditCard = icon(
  '<rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /><path d="M6 14h2" />'
)
const Settings = icon(
  '<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" /><circle cx="12" cy="12" r="3" />'
)
const Search = icon(
  '<path d="m21 21-4.34-4.34" /><circle cx="11" cy="11" r="8" />'
)

const commands = [
  { value: "calendar", label: "Calendar", icon: Calendar },
  { value: "emoji", label: "Search Emoji", icon: Smile },
  {
    value: "calculator",
    label: "Calculator",
    icon: Calculator,
    disabled: true,
  },
  { value: "profile", label: "Profile", icon: User },
  { value: "billing", label: "Billing", icon: CreditCard },
  { value: "settings", label: "Settings", icon: Settings },
]

function Example() {
  const [open, setOpen] = createSignal(false)
  const log = useLog()
  return (
    <div data-slot="stack">
      <Dialog open={open()} onOpenChange={(next) => setOpen(next)}>
        <DialogTrigger shortcut="mod+k">
          Search…
          <DialogShortcut />
        </DialogTrigger>
        <DialogBackdrop />
        <DialogContent>
          <DialogTitle>Command palette</DialogTitle>
          <Command
            onAction={(value) => {
              log(`Ran ${value}`)
              setOpen(false)
            }}
          >
            <div data-slot="row">
              <Search 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>
                <For each={commands}>
                  {(item) => (
                    <CommandItem value={item.value} disabled={item.disabled}>
                      <CommandItemIcon>
                        <item.icon />
                      </CommandItemIcon>
                      {item.label}
                    </CommandItem>
                  )}
                </For>
              </CommandGroup>
            </CommandList>
          </Command>
        </DialogContent>
      </Dialog>
    </div>
  )
}

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

快捷键

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

控制台
import {
  Command,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandShortcut,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"
import { useLog } from "./log"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const User = icon(
  '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />'
)
const CreditCard = icon(
  '<rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /><path d="M6 14h2" />'
)
const Settings = icon(
  '<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" /><circle cx="12" cy="12" r="3" />'
)

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

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

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

高亮匹配项

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

import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandItemText,
  CommandList,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Calendar = icon(
  '<path d="M8 2v3" /><path d="M16 2v3" /><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18" />'
)
const Smile = icon(
  '<path d="M15 10V9" /><path d="M16.472 15a6 6 0 01-8.943 0" /><path d="M9 10V9" /><circle cx="12" cy="12" r="10" />'
)
const Calculator = icon(
  '<rect width="16" height="20" x="4" y="2" rx="2" /><line x1="8" x2="16" y1="6" y2="6" /><line x1="16" x2="16" y1="14" y2="18" /><path d="M16 10h.01" /><path d="M12 10h.01" /><path d="M8 10h.01" /><path d="M12 14h.01" /><path d="M8 14h.01" /><path d="M12 18h.01" /><path d="M8 18h.01" />'
)
const User = icon(
  '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />'
)
const CreditCard = icon(
  '<rect width="20" height="14" x="2" y="5" rx="2" /><line x1="2" x2="22" y1="10" y2="10" /><path d="M6 14h2" />'
)
const Settings = icon(
  '<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" /><circle cx="12" cy="12" r="3" />'
)
const Search = icon(
  '<path d="m21 21-4.34-4.34" /><circle cx="11" cy="11" r="8" />'
)

const commands = [
  { value: "calendar", label: "Calendar", icon: Calendar },
  { value: "emoji", label: "Search Emoji", icon: Smile },
  {
    value: "calculator",
    label: "Calculator",
    icon: Calculator,
    disabled: true,
  },
  { value: "profile", label: "Profile", icon: User },
  { value: "billing", label: "Billing", icon: CreditCard },
  { value: "settings", label: "Settings", icon: Settings },
]

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

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

过滤与关键词

"fuzzy" 是默认值:nf 能匹配 New file。"contains" 和 "startsWith" 匹配文字本身。自定义函数返回布尔值或分数;返回零会隐藏命令,分数越高排得越前。

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

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

import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/solid/command"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"

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

function Example() {
  const [mode, setMode] = createSignal<Mode>("fuzzy")
  const filter = () => {
    const current = mode()
    return current === "words" ? words : current
  }
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <Select
          items={modes}
          value={mode()}
          onValueChange={(next) => next && setMode(next as Mode)}
        >
          <SelectLabel>Filter</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </SelectTrigger>
          <SelectContent>
            <For each={modes}>
              {(option) => (
                <SelectItem value={option.value}>
                  {option.label}
                  <SelectItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </SelectItemIndicator>
                </SelectItem>
              )}
            </For>
          </SelectContent>
        </Select>
      </div>
      <Command filter={filter()}>
        <CommandInput
          aria-label="Search commands"
          placeholder="Try “nf”, “zo in” or “smiley”"
        />
        <CommandEmpty>No results found.</CommandEmpty>
        <CommandList>
          <For each={commands}>
            {(command) => (
              <CommandItem value={command.label} keywords={command.keywords}>
                {command.label}
              </CommandItem>
            )}
          </For>
        </CommandList>
      </Command>
    </div>
  )
}

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

页面

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

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

import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandItemIcon,
  CommandList,
  CommandPage,
  createCommandController,
} from "@ui-sdk/solid/command"
import { createSignal, For, Show } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Moon = icon(
  '<path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" />'
)
const Users = icon(
  '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><path d="M16 3.128a4 4 0 0 1 0 7.744" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><circle cx="9" cy="7" r="4" />'
)
const ArrowLeft = icon('<path d="m12 19-7-7 7-7" /><path d="M19 12H5" />')

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

function Example() {
  const command = createCommandController()
  const [pages, setPages] = createSignal<string[]>([])
  return (
    <Command
      controller={command}
      pages={pages()}
      onPagesChange={(next) => setPages(next)}
      onAction={(value) => {
        if (value === "back") {
          command.pop()
        }
      }}
    >
      <div data-slot="row">
        <For each={pages()}>
          {(page) => <span data-slot="badge">{page}</span>}
        </For>
      </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>
                <Moon />
              </CommandItemIcon>
              Change theme…
            </CommandItem>
            <CommandItem value="teams" page="teams">
              <CommandItemIcon>
                <Users />
              </CommandItemIcon>
              Switch team…
            </CommandItem>
          </CommandGroup>
        </CommandPage>
        <CommandPage value="theme">
          <For each={themes}>
            {(theme) => (
              <CommandItem value={theme.value}>{theme.label}</CommandItem>
            )}
          </For>
        </CommandPage>
        <CommandPage value="teams">
          <For each={teams}>
            {(team) => (
              <CommandItem value={team.value}>{team.label}</CommandItem>
            )}
          </For>
        </CommandPage>
        <Show when={pages().length > 0}>
          <CommandItem value="back">
            <CommandItemIcon mirror>
              <ArrowLeft />
            </CommandItemIcon>
            Go back
          </CommandItem>
        </Show>
      </CommandList>
    </Command>
  )
}

export { Example }
选择 Change theme 或 Switch team。用 Go back,或在空的搜索框里按 Backspace 返回。

以数据形式提供的条目

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

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

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

<Command
  items={commands}
  emptyItems={[{ type: "group", label: "Suggested", items: recent }]}
/>
控制台
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandGroupLabel,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
  type CommandData,
  type CommandDataItem,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"
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" },
    ],
  },
]

function Example() {
  const log = useLog()
  return (
    <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>{(state) => <Commands items={state.items} />}</CommandList>
      </Command>
    </div>
  )
}

function Commands(props: { items: CommandData }) {
  return (
    <For each={props.items}>
      {(entry) => {
        if (typeof entry !== "string" && "type" in entry) {
          if (entry.type === "separator") {
            return <CommandSeparator />
          }
          return (
            <CommandGroup>
              <CommandGroupLabel>{entry.label}</CommandGroupLabel>
              <Commands items={entry.items} />
            </CommandGroup>
          )
        }
        const command: CommandDataItem =
          typeof entry === "string" ? { value: entry, label: entry } : entry
        return (
          <CommandItem
            value={command.value}
            label={command.label}
            disabled={command.disabled}
            shortcut={command.shortcut}
          >
            {command.label}
            {command.shortcut && <CommandShortcut />}
          </CommandItem>
        )
      }}
    </For>
  )
}

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

异步结果

用异步选项等待输入暂停,并丢弃过期的结果。把查询变化发给 setQuery(),渲染返回的条目,并传入 status。把 filter 设为 false 可以保持服务器的顺序。

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

import { useAsyncOptions } from "@ui-sdk/solid/async-options"
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
  CommandStatus,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"

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

function Example() {
  const issues = useAsyncOptions(searchIssues, {
    debounce: 250,
    immediate: true,
  })

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

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

待处理的动作

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

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

控制台
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/solid/command"
import { Show } from "solid-js"
import { useLog } from "./log"

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

const Spinner = () => (
  <svg
    data-slot="spinner"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d="M21 12a9 9 0 1 1-6.219-8.56" />
  </svg>
)

function Example() {
  const log = useLog()
  return (
    <div data-slot="stack">
      <Command>
        <CommandInput
          aria-label="Search actions"
          placeholder="Search actions…"
        />
        <CommandList>
          <CommandItem
            value="deploy"
            onSelect={async () => {
              await wait(1200)
              log("Deployed to production")
            }}
          >
            {(state) => (
              <>
                Deploy to production
                <Show when={state.pending}>
                  <Spinner />
                </Show>
              </>
            )}
          </CommandItem>
          <CommandItem
            value="sync"
            onSelect={async () => {
              await wait(600)
              log("Couldn't sync: offline")
              throw new Error("Offline")
            }}
          >
            {(state) => (
              <>
                Sync with server
                <Show
                  when={state.pending}
                  fallback={
                    <Show when={state.error !== undefined}>
                      <span data-slot="hint">Failed, try again</span>
                    </Show>
                  }
                >
                  <Spinner />
                </Show>
              </>
            )}
          </CommandItem>
        </CommandList>
      </Command>
    </div>
  )
}

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

虚拟化

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

import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@ui-sdk/solid/command"
import { createSignal, For } from "solid-js"

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

const row = 32
const height = 256

function Example() {
  let scroller: HTMLDivElement | undefined
  const [scrollTop, setScrollTop] = createSignal(0)
  return (
    <Command
      items={commands}
      onValueChange={(value, { index }) => {
        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
        }
      }}
    >
      <CommandInput
        aria-label="Search 10,000 commands"
        placeholder="Search 10,000 commands…"
      />
      <div
        ref={scroller}
        onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
      >
        <CommandList>
          {(state) => {
            const start = Math.max(0, Math.floor(scrollTop() / row) - 4)
            const end = Math.min(
              state.items.length,
              Math.ceil((scrollTop() + height) / row) + 4
            )
            return (
              <div style={{ height: `${state.items.length * row}px` }}>
                <For each={(state.items as typeof commands).slice(start, end)}>
                  {(item, offset) => (
                    <CommandItem
                      value={item.value}
                      label={item.label}
                      index={start + offset()}
                      style={{ top: `${(start + offset()) * row}px` }}
                    >
                      {item.label}
                    </CommandItem>
                  )}
                </For>
              </div>
            )
          }}
        </CommandList>
      </div>
    </Command>
  )
}

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

受控

高亮的命令、搜索文字和页面栈是彼此独立的:

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

传入一个值及其变更回调来控制它,或使用 defaultValue、defaultQuery 和 defaultPages 提供起始状态。变更回调会收到详情;调用 details.cancel() 可以拒绝一次变更。value 是高亮的命令,不是已选中的命令,它会随高亮移动而变化。onAction 报告激活,所以只移动高亮不会运行命令。状态与事件介绍了共享的绑定模式。

控制台
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
  CommandPage,
} from "@ui-sdk/solid/command"
import { createSignal, For } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const [value, setValue] = createSignal<string | null>("dark")
  const [query, setQuery] = createSignal("")
  const [pages, setPages] = createSignal(["theme"])
  const log = useLog()
  return (
    <Command
      value={value()}
      onValueChange={(next, details) => {
        setValue(next)
        log(`Highlighted ${next ?? "nothing"} (${details.reason})`)
      }}
      query={query()}
      onQueryChange={(next, details) => {
        setQuery(next)
        log(`Query “${next}” (${details.reason})`)
      }}
      pages={pages()}
      onPagesChange={(next, details) => {
        setPages(next)
        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">
          <For each={themes}>
            {(theme) => (
              <CommandItem value={theme.value}>{theme.label}</CommandItem>
            )}
          </For>
        </CommandPage>
      </CommandList>
    </Command>
  )
}

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

控制器

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

控制台
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
  CommandPage,
  createCommandController,
} from "@ui-sdk/solid/command"
import { For } from "solid-js"
import { useLog } from "./log"

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

const palette = createCommandController()

function Example() {
  const log = useLog()
  return (
    <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">
            <For each={themes}>
              {(theme) => (
                <CommandItem value={theme.value}>{theme.label}</CommandItem>
              )}
            </For>
          </CommandPage>
        </CommandList>
      </Command>
    </div>
  )
}

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

自定义渲染

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

import {
  Command,
  CommandInput,
  CommandItem,
  CommandItemText,
  CommandList,
} from "@ui-sdk/solid/command"
import { For, Show } from "solid-js"

const pages = ["Composition", "Installation", "Styling"]

function Example() {
  return (
    <Command>
      <CommandInput aria-label="Search docs" placeholder="Search docs…" />
      <CommandList>
        <For each={pages}>
          {(page) => (
            <CommandItem
              value={page}
              render={(props) => (
                <a {...props} href={`#${page.toLowerCase()}`} />
              )}
            >
              {(state) => (
                <>
                  <CommandItemText>
                    {(text) => (
                      <For each={text.segments}>
                        {(segment) =>
                          segment.match ? (
                            <strong>{segment.text}</strong>
                          ) : (
                            segment.text
                          )
                        }
                      </For>
                    )}
                  </CommandItemText>
                  <Show when={state.highlighted}>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 4v7a4 4 0 0 1-4 4H4" />
                      <path d="m9 10-5 5 5 5" />
                    </svg>
                  </Show>
                </>
              )}
            </CommandItem>
          )}
        </For>
      </CommandList>
    </Command>
  )
}

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

样式

每个部件都有一个 data-slot,比如 command-item,并通过数据属性下列出的属性展示状态。

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

数据属性

Command

[data-slot="command"]

属性含义
data-loadingPresent while results load, with status="loading".

CommandInput

CommandList

[data-slot="command-list"]

属性含义
data-has-iconsPresent while any command inside holds an icon part, so items without one can line up.

CommandItem

[data-slot="command-item"]

属性含义
data-disabledPresent when the command can't run. Arrow keys skip it.
data-highlightedPresent on the highlighted command, which Enter runs. Focus stays in the field.
data-pendingPresent while the Promise the command's onSelect or onAction returned is running.
data-has-iconPresent on a command while it holds an icon part.

CommandItemText

[data-slot="command-item-text"]

属性含义
data-matchedPresent on a command's text while the search matched part of it, which is marked.

CommandItemIcon

[data-slot="command-item-icon"]

属性含义
data-mirrorPresent on an icon that flips in right-to-left text, with mirror.

CommandEmpty

[data-slot="command-empty"]

属性含义
data-loadingPresent while results load, with status="loading".
data-emptyPresent while no command matches.

CommandStatus

[data-slot="command-status"]

属性含义
data-loadingPresent while results load, with status="loading".

API 参考

属性和回调与下面相同,都作为 Solid 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" }。

valuestring
Identifies the item, and is what choosing it reports. A string, or any value with itemToValue.
labelstring
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:

pagestring | null
The current page, or null on the first page.
loadingboolean
Whether results are loading.

CommandInput:

pagestring | null
The current page, or null on the first page.

CommandList:

statusAsyncOptionsStatus
Whether results are loading or failed.
itemsCommandData
The visible data commands, ranked, for rendering a virtualized list yourself.

CommandItem:

highlightedboolean
Whether the command is highlighted, by the keyboard, the pointer or typing.
disabledboolean
Whether the command can't run.
pendingboolean
Whether its action's Promise is running.
errorunknown
Why its last action failed, until it runs again.

CommandEmpty:

loadingboolean
Whether results are loading.
emptyboolean
Whether no item matches.
querystring
The text the list is filtered by.

CommandStatus:

status"idle" | "loading" | "error"
Whether results are loading or failed.
loadingboolean
Whether results are loading.
countnumber
How many items are visible.

CommandShortcut:

textstring
The shortcut formatted for this platform: ⌘P on Apple platforms and Ctrl+P elsewhere. Empty without one.

CommandItemText,它没有自己的 props:

segmentsMatchSegment[]
The text in pieces, each marked when it matched. Joined, they're the whole text.
matchedboolean
Whether any piece matched.

CommandItemIcon:

mirrorboolean
Whether it flips in right-to-left text.

原因

高亮的命令为什么变化:

list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
item-hoverPointerEvent
The pointer moved onto an item, which highlighted it, like in a command list.
input-changeEvent
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-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
item-removednone
The selected item left the page, and another was picked.
imperativenone
A controller or api call.

搜索文字为什么变化:

input-changeEvent
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-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
imperativenone
A controller or api call.

以及页面栈为什么变化:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
imperativenone
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.

事件

回调先收到新状态,然后收到详情。

属性所属收到
onValueChangeCommand(value, details):高亮的命令、原因及其 index
onQueryChangeCommand(query, details):新文字、原因以及它是否仍在 composing
onPagesChangeCommand(pages, details):新的栈,以及原因
onActionCommand(value, { event }):运行的命令。返回一个 Promise 让它保持待处理
onLoadMoreCommand(),当到达最后一个命令时
onSelectCommandItem(event):在 onAction 之前。preventDefault() 会跳过它。返回 Promise 会让它保持待处理

无障碍

命令列表遵循 WAI-ARIA 组合框模式,其中的列表始终显示。焦点留在输入框里,输入框用 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.

运行于 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.

运行于 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.

运行于 React、Vue 和 web components。

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

  • Announcements while searching with a keyboard.

运行于 React、Vue 和 web components。