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

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

import "@ui-sdk/web/command"
import {
  Calculator,
  Calendar,
  createElement,
  CreditCard,
  Search,
  Settings,
  Smile,
  User,
} from "lucide"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command>
      <div data-slot="row">
          ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
          <ui-command-input>
            <input aria-label="Search commands" placeholder="Type a command or search…" />
          </ui-command-input>
      </div>
      <ui-command-empty>No results found.</ui-command-empty>
      <ui-command-list>
        <ui-command-group>
          <ui-command-group-label>Suggestions</ui-command-group-label>
          ${suggestions
            .map(
              (item) => `
                <ui-command-item value="${item.value}" ${item.disabled ? "disabled" : ""}>
                  <ui-command-item-icon>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
                  <span>${item.label}</span>
                </ui-command-item>
              `
            )
            .join("")}
        </ui-command-group>
        <ui-command-separator></ui-command-separator>
        <ui-command-group>
          <ui-command-group-label>Settings</ui-command-group-label>
          ${settings
            .map(
              (item) => `
                <ui-command-item value="${item.value}" shortcut="${item.shortcut}">
                  <ui-command-item-icon>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
                  <span>${item.label}</span>
                  <ui-command-shortcut></ui-command-shortcut>
                </ui-command-item>
              `
            )
            .join("")}
        </ui-command-group>
      </ui-command-list>
    </ui-command>
  `
}

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

安装

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

在应用里导入一次元素定义:

import "@ui-sdk/web/command"

组合

用下面的组合构建 ui-command:

ui-command
├── ui-command-input
│   └── input
├── ui-command-empty
└── ui-command-list
    ├── ui-command-item
    └── ui-command-item

给输入框一个无障碍名称,并给每个命令一个唯一的值。ui-command-input 包装一个原生输入框。把空状态和状态消息放在列表之外,列表里放的是命令和分组。action 事件在 event.detail.value 中报告运行的命令的值;用它来执行动作。

用 ui-command-group 和 ui-command-group-label 给相关的命令命名,在分组之间放一个 ui-command-separator。当过滤让它们变空时,分组和分隔符会消失。

用法

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

<script type="module">
  import "@ui-sdk/web/command"
</script>

<ui-command>
  <ui-command-input><input aria-label="Search commands" /></ui-command-input>
  <ui-command-empty>No commands found.</ui-command-empty>
  <ui-command-list>
    <ui-command-item value="new-file">New file</ui-command-item>
    <ui-command-item value="new-folder">New folder</ui-command-item>
  </ui-command-list>
</ui-command>

自己构建

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

palette-elements.ts
import { command } from "@ui-sdk/core/command"
import { createParts, wrappedChild } from "@ui-sdk/web"

createParts(command, {
  root: "command-palette",
  input: {
    tag: "palette-search",
    target: wrappedChild("input"),
    display: "contents",
  },
  empty: "palette-empty",
  list: "palette-list",
  item: "palette-action",
})
<command-palette>
  <palette-search><input aria-label="Search actions" /></palette-search>
  <palette-empty>No actions found.</palette-empty>
  <palette-list>
    <palette-action value="new-file">New file</palette-action>
    <palette-action value="new-folder">New folder</palette-action>
  </palette-list>
</command-palette>

每个元素都保留其现成对应元素的行为、状态和数据属性:输入会过滤命令,方向键移动高亮,Enter 运行它。更多内容见渲染和自定义部件。

对话框

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

控制台
import "@ui-sdk/web/command"
import "@ui-sdk/web/dialog"
import {
  Calculator,
  Calendar,
  createElement,
  CreditCard,
  Search,
  Settings,
  Smile,
  User,
} from "lucide"
import { log } from "./log"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-dialog>
        <ui-dialog-trigger shortcut="mod+k">
          <button>
            Search…
            <ui-dialog-shortcut></ui-dialog-shortcut>
          </button>
        </ui-dialog-trigger>
        <ui-dialog-backdrop hidden></ui-dialog-backdrop>
        <ui-dialog-content hidden>
          <ui-dialog-title>Command palette</ui-dialog-title>
          <ui-command>
            <div data-slot="row">
              ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
              <ui-command-input>
                <input aria-label="Search commands" placeholder="Type a command or search…" />
              </ui-command-input>
            </div>
            <ui-command-empty>No results found.</ui-command-empty>
            <ui-command-list>
              <ui-command-group>
                <ui-command-group-label>Suggestions</ui-command-group-label>
                ${commands
                  .map(
                    (item) => `
                      <ui-command-item value="${item.value}" ${item.disabled ? "disabled" : ""}>
                        <ui-command-item-icon>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
                        ${item.label}
                      </ui-command-item>
                    `
                  )
                  .join("")}
              </ui-command-group>
            </ui-command-list>
          </ui-command>
        </ui-dialog-content>
      </ui-dialog>
    </div>
  `
  const dialog = root.querySelector("ui-dialog")!
  root.querySelector("ui-command")!.addEventListener("action", (event) => {
    log(root, `Ran ${event.detail.value}`)
    dialog.open = false
  })
}

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

快捷键

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

控制台
import "@ui-sdk/web/command"
import { createElement, CreditCard, Settings, User } from "lucide"
import { log } from "./log"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-command>
        <ui-command-input>
          <input aria-label="Search settings" placeholder="Search settings…" />
        </ui-command-input>
        <ui-command-list>
          <ui-command-group>
            <ui-command-group-label>Settings</ui-command-group-label>
            ${settings
              .map(
                (item) => `
                  <ui-command-item value="${item.value}" shortcut="${item.shortcut}">
                    <ui-command-item-icon>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
                    <span>${item.label}</span>
                    <ui-command-shortcut></ui-command-shortcut>
                  </ui-command-item>
                `
              )
              .join("")}
          </ui-command-group>
        </ui-command-list>
      </ui-command>
    </div>
  `
  root
    .querySelector("ui-command")!
    .addEventListener("action", (event) =>
      log(root, `Ran ${event.detail.value}`)
    )
}

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

高亮匹配项

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

import "@ui-sdk/web/command"
import {
  Calculator,
  Calendar,
  createElement,
  CreditCard,
  Search,
  Settings,
  Smile,
  User,
} from "lucide"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command>
      <div data-slot="row">
          ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
          <ui-command-input>
            <input aria-label="Search commands" placeholder="Try “prf” or “emo”…" />
          </ui-command-input>
      </div>
      <ui-command-empty>No results found.</ui-command-empty>
      <ui-command-list>
        ${commands
          .map(
            (item) => `
              <ui-command-item value="${item.value}" ${item.disabled ? "disabled" : ""}>
                <ui-command-item-icon>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
                <ui-command-item-text>${item.label}</ui-command-item-text>
              </ui-command-item>
            `
          )
          .join("")}
      </ui-command-list>
    </ui-command>
  `
}

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

过滤与关键词

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

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

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

import "@ui-sdk/web/command"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <ui-select default-value="fuzzy">
          <ui-select-label>Filter</ui-select-label>
          <ui-select-trigger>
            <button>
              <ui-select-value></ui-select-value>
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-select-trigger>
          <ui-select-content hidden>
            ${modes
              .map(
                (option) => `
                  <ui-select-item value="${option.value}">
                    ${option.label}
                    <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                  </ui-select-item>
                `
              )
              .join("")}
          </ui-select-content>
        </ui-select>
      </div>
      <ui-command>
        <ui-command-input>
          <input aria-label="Search commands" placeholder="Try “nf”, “zo in” or “smiley”" />
        </ui-command-input>
        <ui-command-empty>No results found.</ui-command-empty>
        <ui-command-list>
          ${commands
            .map(
              (command) =>
                `<ui-command-item value="${command.label}"${command.keywords ? ` keywords="${command.keywords.join(",")}"` : ""}>${command.label}</ui-command-item>`
            )
            .join("")}
        </ui-command-list>
      </ui-command>
    </div>
  `
  const command = root.querySelector("ui-command")!
  root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
    const mode = event.detail.value as Mode | null
    if (mode) {
      command.filter = mode === "words" ? words : mode
    }
  })
}

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

页面

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

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

import "@ui-sdk/web/command"
import { ArrowLeft, createElement, Moon, Users } from "lucide"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command>
      <div data-slot="row"></div>
      <ui-command-input>
        <input aria-label="Search commands" placeholder="What do you need?" />
      </ui-command-input>
      <ui-command-empty>No results found.</ui-command-empty>
      <ui-command-list>
        <ui-command-page>
          <ui-command-group>
            <ui-command-group-label>Workspace</ui-command-group-label>
            <ui-command-item value="theme" page="theme">
              <ui-command-item-icon>${createElement(Moon, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
              Change theme…
            </ui-command-item>
            <ui-command-item value="teams" page="teams">
              <ui-command-item-icon>${createElement(Users, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>
              Switch team…
            </ui-command-item>
          </ui-command-group>
        </ui-command-page>
        <ui-command-page value="theme">
          ${themes
            .map(
              (theme) =>
                `<ui-command-item value="${theme.value}">${theme.label}</ui-command-item>`
            )
            .join("")}
        </ui-command-page>
        <ui-command-page value="teams">
          ${teams
            .map(
              (team) =>
                `<ui-command-item value="${team.value}">${team.label}</ui-command-item>`
            )
            .join("")}
        </ui-command-page>
      </ui-command-list>
    </ui-command>
  `
  const command = root.querySelector("ui-command") as HTMLElement & {
    api: { pop: () => void }
  }
  const breadcrumb = command.querySelector("div")!
  const input = command.querySelector("input")!
  const list = command.querySelector("ui-command-list")!
  const back = document.createElement("ui-command-item")
  back.setAttribute("value", "back")
  back.innerHTML = `<ui-command-item-icon mirror>${createElement(ArrowLeft, { "aria-hidden": "true" }).outerHTML}</ui-command-item-icon>Go back`
  command.addEventListener("action", (event) => {
    if ((event as CustomEvent<{ value: string }>).detail.value === "back") {
      command.api.pop()
    }
  })
  command.addEventListener("pageschange", (event) => {
    const pages = (event as CustomEvent<{ value: string[] }>).detail.value
    breadcrumb.innerHTML = pages
      .map((page) => `<span data-slot="badge">${page}</span>`)
      .join("")
    input.placeholder = pages.length
      ? "Search… (Backspace to go back)"
      : "What do you need?"
    if (!pages.length) {
      back.remove()
    } else if (!back.isConnected) {
      list.append(back)
    }
  })
}

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

以数据形式提供的条目

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

元素会为你渲染不带内容的部件,并跟随当前页面和排序后的结果。对于要设置样式的命令,在元素内部用一个 <template> 为生成的部件提供标记。这个示例同时处理分组、分隔符和命令。列表与菜单介绍了共享的数据格式。

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

const command = document.querySelector("ui-command")!
command.items = commands
command.emptyItems = [{ type: "group", label: "Suggested", items: recent }]
控制台
import type { CommandData } from "@ui-sdk/core/command"
import "@ui-sdk/web/command"
import { log } 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 mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-command>
        <ui-command-input>
          <input aria-label="Search commands" placeholder="Type a command…" />
        </ui-command-input>
        <ui-command-empty>No results found.</ui-command-empty>
        <template>
          <ui-command-list>
            <ui-command-group>
              <ui-command-group-label></ui-command-group-label>
              <ui-command-item>
                <ui-command-shortcut></ui-command-shortcut>
              </ui-command-item>
            </ui-command-group>
            <ui-command-separator></ui-command-separator>
          </ui-command-list>
        </template>
      </ui-command>
    </div>
  `
  const command = root.querySelector("ui-command")!
  command.items = commands
  command.addEventListener("action", (event) =>
    log(root, `Ran ${event.detail.value}`)
  )
}

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

异步结果

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

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

import { createAsyncOptions } from "@ui-sdk/core/async-options"
import "@ui-sdk/web/command"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command filter="false">
      <ui-command-input>
        <input aria-label="Search issues" placeholder="Search issues…" />
      </ui-command-input>
      <ui-command-status></ui-command-status>
      <ui-command-empty>No issues match “<span></span>”.</ui-command-empty>
      <ui-command-list></ui-command-list>
      <template>
        <ui-command-item>
        </ui-command-item>
      </template>
    </ui-command>
  `
  const command = root.querySelector("ui-command")!
  const status = root.querySelector("ui-command-status")!
  const query = root.querySelector("ui-command-empty span")!
  const issues = createAsyncOptions(searchIssues, {
    debounce: 250,
    immediate: true,
  })
  const update = () => {
    const { items, status: loading } = issues.getState()
    command.items = items
    command.setAttribute("status", loading)
    status.textContent =
      loading === "loading"
        ? "Searching…"
        : `${items.length} ${items.length === 1 ? "issue" : "issues"}`
  }
  issues.subscribe(update)
  update()
  command.addEventListener("querychange", (event) => {
    query.textContent = event.detail.value
    issues.setQuery(event.detail.value)
  })
  command.addEventListener("loadmore", () => issues.loadMore())
}

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

待处理的动作

在 action 监听器里把一个 promise 传给 event.detail.waitUntil(),会让命令保持待处理(pending)。它会得到 data-pending、aria-busy 和 aria-disabled,直到 promise 结束;再次按压不会开始另一次运行。被拒绝时,它会成为命令的 error 状态,再次运行时会清除。

条目的 select 事件在 action 之前触发。在它上面调用 preventDefault() 可以阻止这个动作。

控制台
import "@ui-sdk/web/command"
import { createElement, LoaderCircle } from "lucide"
import { log } from "./log"

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

function mount(root: HTMLElement) {
  const spinner = createElement(LoaderCircle, {
    "data-slot": "spinner",
    "aria-hidden": "true",
  }).outerHTML
  root.innerHTML = `
    <div data-slot="stack">
      <ui-command>
        <ui-command-input>
          <input aria-label="Search actions" placeholder="Search actions…" />
        </ui-command-input>
        <ui-command-list>
          <ui-command-item value="deploy" label="Deploy to production">
            Deploy to production
            ${spinner}
          </ui-command-item>
          <ui-command-item value="sync" label="Sync with server">
            Sync with server
            ${spinner}
            <span data-slot="hint" data-error hidden>Failed, try again</span>
          </ui-command-item>
        </ui-command-list>
      </ui-command>
    </div>
  `
  const error = root.querySelector<HTMLElement>("[data-error]")!
  root.querySelector("ui-command")!.addEventListener("action", (event) => {
    const { value, waitUntil } = event.detail
    if (value === "deploy") {
      waitUntil(wait(1200).then(() => log(root, "Deployed to production")))
    }
    if (value === "sync") {
      error.hidden = true
      const sync = wait(600).then(() => {
        log(root, "Couldn't sync: offline")
        throw new Error("Offline")
      })
      waitUntil(sync)
      sync.catch(() => (error.hidden = false))
    }
  })
}

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

虚拟化

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

import { fuzzyScore } from "@ui-sdk/core/text-match"
import "@ui-sdk/web/command"

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

const row = 32

function rank(query: string) {
  if (!query.trim()) {
    return commands
  }
  return commands
    .map((item) => ({ item, score: fuzzyScore(item.label, query) }))
    .filter((entry) => entry.score > 0)
    .sort((a, b) => b.score - a.score)
    .map((entry) => entry.item)
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command>
      <ui-command-input>
        <input aria-label="Search 10,000 commands" placeholder="Search 10,000 commands…" />
      </ui-command-input>
      <ui-command-list>
        <div aria-hidden="true"></div>
      </ui-command-list>
    </ui-command>
  `
  const command = root.querySelector("ui-command") as HTMLElement & {
    items: typeof commands
  }
  const list = root.querySelector<HTMLElement>("ui-command-list")!
  const spacer = list.querySelector<HTMLElement>("div")!

  let matches = commands

  const rendered = new Map<string, HTMLElement>()
  const render = () => {
    spacer.style.height = `${matches.length * row}px`
    const start = Math.max(0, Math.floor(list.scrollTop / row) - 4)
    const end = Math.min(
      matches.length,
      Math.ceil((list.scrollTop + list.clientHeight) / row) + 4
    )
    const visible = new Map(
      matches
        .slice(start, end)
        .map((item, offset) => [item.value, start + offset])
    )
    for (const [value, el] of rendered) {
      if (visible.has(value)) {
        continue
      }
      el.remove()
      rendered.delete(value)
    }
    for (const [value, index] of visible) {
      const existing = rendered.get(value)
      if (existing) {
        existing.setAttribute("index", String(index))
        existing.style.top = `${index * row}px`
        continue
      }
      const item = matches[index]
      list.insertAdjacentHTML(
        "beforeend",
        `<ui-command-item value="${item.value}" label="${item.label}" index="${index}" style="top: ${index * row}px">${item.label}</ui-command-item>`
      )
      rendered.set(value, list.lastElementChild as HTMLElement)
    }
  }
  render()
  command.items = commands
  list.addEventListener("scroll", render)
  command.addEventListener("querychange", (event) => {
    matches = rank((event as CustomEvent<{ value: string }>).detail.value)
    render()
  })
  command.addEventListener("valuechange", (event) => {
    const { index } = (
      event as CustomEvent<{ value: string | null; index: number }>
    ).detail
    if (index < 0) {
      return
    }
    const top = index * row
    if (top < list.scrollTop) {
      list.scrollTop = top
    } else if (top + row > list.scrollTop + list.clientHeight) {
      list.scrollTop = top + row - list.clientHeight
    }
    render()
  })
}

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

受控

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

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

在元素上读取或写入这些 property,并使用 default-value、default-query 和 default-pages 提供起始状态。变更事件在 event.detail.value 中带上新值,原因就在它旁边;调用 event.preventDefault() 可以拒绝一次变更。value 是高亮的命令,不是已选中的命令,它会随高亮移动而变化。action 报告激活,所以只移动高亮不会运行命令。状态与事件介绍了共享的绑定模式。

控制台
import "@ui-sdk/web/command"
import { log } from "./log"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command default-value="dark" default-pages="theme">
      <ui-command-input>
        <input aria-label="Search themes" placeholder="Search themes…" />
      </ui-command-input>
      <ui-command-list>
        <ui-command-page>
          <ui-command-item value="theme" page="theme">Change theme…</ui-command-item>
        </ui-command-page>
        <ui-command-page value="theme">
          ${themes
            .map(
              (theme) =>
                `<ui-command-item value="${theme.value}">${theme.label}</ui-command-item>`
            )
            .join("")}
        </ui-command-page>
      </ui-command-list>
    </ui-command>
  `
  const command = root.querySelector("ui-command")!
  command.addEventListener("valuechange", (event) =>
    log(
      root,
      `Highlighted ${event.detail.value ?? "nothing"} (${event.detail.reason})`
    )
  )
  command.addEventListener("querychange", (event) =>
    log(root, `Query “${event.detail.value}” (${event.detail.reason})`)
  )
  command.addEventListener("pageschange", (event) =>
    log(
      root,
      `Pages [${event.detail.value.join(", ")}] (${event.detail.reason})`
    )
  )
  command.addEventListener("action", (event) =>
    log(root, `Ran ${event.detail.value}`)
  )
}

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

控制器

使用元素的 api property。它可以读取和设置高亮、查询和页面栈。用 push() 和 pop() 在页面之间导航,用 run() 运行高亮的命令或指定的命令,用 focus() 聚焦搜索框。设置和生命周期见控制器。

控制台
import "@ui-sdk/web/command"
import { log } from "./log"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="push">Open Themes</button>
        <button type="button" data-action="pop">Back</button>
        <button type="button" data-action="highlight">Highlight Dark</button>
        <button type="button" data-action="search">Search “li”</button>
        <button type="button" data-action="run">Run Highlighted</button>
        <button type="button" data-action="focus">Focus</button>
      </div>
      <ui-command>
        <ui-command-input>
          <input aria-label="Search commands" />
        </ui-command-input>
        <ui-command-list>
          <ui-command-page>
            <ui-command-item value="theme" page="theme">Change theme…</ui-command-item>
          </ui-command-page>
          <ui-command-page value="theme">
            ${themes
              .map(
                (theme) =>
                  `<ui-command-item value="${theme.value}">${theme.label}</ui-command-item>`
              )
              .join("")}
          </ui-command-page>
        </ui-command-list>
      </ui-command>
    </div>
  `
  const command = root.querySelector("ui-command")!
  const palette = command.api
  const actions: Record<string, () => void> = {
    push: () => palette.push("theme"),
    pop: () => palette.pop(),
    highlight: () => palette.setValue("dark"),
    search: () => palette.setQuery("li"),
    run: () => palette.run(),
    focus: () => palette.focus(),
  }
  for (const button of root.querySelectorAll<HTMLElement>("[data-action]")) {
    button.addEventListener("click", () => actions[button.dataset.action!]())
  }
  command.addEventListener("action", (event) =>
    log(root, `Ran ${event.detail.value}`)
  )
}

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

自定义渲染

当命令需要导航时,在它里面放一个链接并加上 as-child:命令会绑定这个链接。Enter 会跟随高亮的链接;带修饰键的点击保留浏览器一贯的行为。

import "@ui-sdk/web/command"
import { CornerDownLeft, createElement } from "lucide"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-command>
      <ui-command-input>
        <input aria-label="Search docs" placeholder="Search docs…" />
      </ui-command-input>
      <ui-command-list>
        ${pages
          .map(
            (page) => `
              <ui-command-item value="${page}" label="${page}" as-child>
                <a href="#${page.toLowerCase()}">
                  <ui-command-item-text>${page}</ui-command-item-text>
                  ${createElement(CornerDownLeft, { "aria-hidden": "true" }).outerHTML}
                </a>
              </ui-command-item>
            `
          )
          .join("")}
      </ui-command-list>
    </ui-command>
  `
}

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

样式

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

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

数据属性

<ui-command>

[data-slot="command"]

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

<ui-command-input>

<ui-command-list>

[data-slot="command-list"]

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

<ui-command-item>

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

<ui-command-item-text>

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

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

<ui-command-item-icon>

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

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

<ui-command-empty>

[data-slot="command-empty"]

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

<ui-command-status>

[data-slot="command-status"]

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

API 参考

attribute 使用 kebab-case,比如 default-pages 和 auto-highlight:"false" 表示 false。filter 接受 fuzzy、contains、startsWith 或 false。items、emptyItems、announcement 和 filter 函数都是 property。回调是 DOM 事件。

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.
valuechange event
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.
querychange event
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.
pageschange event
Runs when a page opens or Backspace or Escape goes back.
action event
Runs when a command runs, with its value: Enter, a click, or its shortcut. Return a Promise to mark the command pending until it settles: it gets data-pending, aria-busy and aria-disabled, and running it again waits. A rejection puts the reason in its error state until the next run.
pendingAnnouncement?string
What screen readers hear once a command has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
items?CommandData
The commands as data. Renders them for you, ranked as the user types, with pages for commands that have items.
emptyItems?CommandData
Commands shown instead of items on the first page while the search is empty, like recent or suggested ones. Groups work, like { type: "group", label: "Suggestions", items }. Needs items.
filter?SearchFilter<string>
How typing narrows the list: "fuzzy" keeps commands with the text's letters in order, best matches first; "contains" and "startsWith" match the text itself. A function returns a score (0 hides) or a boolean. false keeps every command, for results a server already filtered. Composed commands keep their order, and data commands are ranked by score.
autoHighlight?boolean
Whether the first command is highlighted while nothing else is, and the best match as the user types, so Enter runs it.
loop?boolean
Whether arrow keys wrap from the last command to the first.
status?AsyncOptionsStatus
Whether results are loading or failed, for the empty and status parts. Sets aria-busy on the list while loading.
loadmore event
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

搜索框。<ui-command-input> 包装一个原生 input,它得到 combobox 角色。

CommandStatus

描述加载和失败。<ui-command-status> 带 status 角色。

CommandEmpty

没有命令匹配时显示。有匹配时 <ui-command-empty> 保持隐藏。

CommandList

容纳命令。<ui-command-list> 带 listbox 角色,始终显示。

CommandPage

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

CommandGroup

把命令分组在名称之下。<ui-command-group> 带 group 角色。

CommandGroupLabel

为它的分组提供名称。<ui-command-group-label> 用名称标注分组。

CommandItem

value?string
Passed to action and valuechange, 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
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

显示命令的标签,并在 <mark> 中标记搜索匹配的内容。<ui-command-item-text> 只容纳文字。

CommandShortcut

shortcut?string
The keys to show, like "mod+p". Inside a command, its shortcut.

CommandSeparator

分隔命令或分组。<ui-command-separator> 带 separator 角色。

以数据形式提供的条目

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.

原因

event.detail.reason 说明高亮的命令为什么变化:

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.

控制器

元素的 api property 拥有相同的方法。

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.

事件

事件在各自的元素上触发,不冒泡,新状态在 event.detail.value 中,reason 和 event 就在它旁边。在变更事件上调用 preventDefault() 可以取消它。

成员所属说明
value propertyui-command高亮的命令。设置它会像控制器那样移动高亮
query propertyui-command搜索文字
pages propertyui-command页面栈
api propertyui-command控制器
valuechange eventui-commanddetail: { value, reason, event, source, index }
querychange eventui-commanddetail: { value: query, reason, event, source, composing }
pageschange eventui-commanddetail: { value: pages, reason, event, source }
action eventui-commanddetail: { value, waitUntil(promise) },当命令运行时
loadmore eventui-command当到达最后一个命令时
select eventui-command-item在 action 之前。preventDefault() 会跳过 action 事件

无障碍

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

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