# Combobox

搜索选项列表，选择一个或多个值。

当人们需要通过输入来查找选项时，用 Combobox。先从一个输入框和一个列表开始，再按需加上标签片（chip）、服务器结果，或新建选项的能力。

```ts title="demo.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Framework</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Select a framework" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show frameworks">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks
            .map(
              (framework) => `
                <ui-combobox-item value="${framework.value}" label="${framework.label}">
                  ${framework.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

输入 “sv” 找到 SvelteKit。按 Down Arrow 高亮它，再按 Enter 选择。

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

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

```ts
import "@ui-sdk/web/combobox"
```

## 组合
用下面的组合构建 `ui-combobox`：

```text
ui-combobox
├── ui-combobox-label
├── ui-combobox-input
│   └── input
└── ui-combobox-content
    └── ui-combobox-list
        ├── ui-combobox-item
        └── ui-combobox-item
```

给输入框命名，给每个选项一个唯一的值，并把选项放进浮层里的列表。`ui-combobox-input` 包装一个原生输入框。标签为输入框提供名称；选择一个选项会把它的标签文字放进输入框。

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

```html
<script type="module">
  import "@ui-sdk/web/combobox"
</script>

<ui-combobox>
  <ui-combobox-label>Fruit</ui-combobox-label>
  <ui-combobox-input><input placeholder="Search fruits…" /></ui-combobox-input>
  <ui-combobox-content hidden>
    <ui-combobox-list>
      <ui-combobox-item value="apple">Apple</ui-combobox-item>
      <ui-combobox-item value="banana">Banana</ui-combobox-item>
    </ui-combobox-list>
  </ui-combobox-content>
</ui-combobox>
```

## Autocomplete 与 Combobox
两者都会在你输入时过滤列表。区别在于值是什么。

- **Combobox**：值是列表中的一个选项，使用 `multiple` 时则是多个。文字只是查询；未选择就关闭会恢复已选中项的标签文字，表单提交的是值，不是文字。用于国家、负责人或一组标签。
- **[Autocomplete](/docs/web-components/components/autocomplete)**：值就是文字。建议帮助你把它填完，输入的任何内容都有效。用于搜索框、地址或自由输入字段。

`allow-custom-value` 让 Combobox 接受不匹配任何选项的文字，就像 datalist。从列表中选择是主要路径时用它；自由输入是主要路径时改用 autocomplete。

## 自己构建
`@ui-sdk/web/combobox` 自带现成的 `ui-combobox` 元素。如果你想用自己的元素名自己构建，从 `@ui-sdk/core` 的 `combobox` 原语（primitive）开始：

```ts title="country-picker-elements.ts"
import { combobox } from "@ui-sdk/core/combobox"
import { createParts, wrappedChild } from "@ui-sdk/web"

createParts(combobox, {
  root: "country-picker",
  label: "country-label",
  input: {
    tag: "country-input",
    target: wrappedChild("input"),
    display: "contents",
  },
  content: "country-popup",
  list: "country-list",
  item: "country-option",
  empty: "country-empty",
})
```

```html
<country-picker>
  <country-label>Country</country-label>
  <country-input><input /></country-input>
  <country-popup hidden>
    <country-empty>No countries found.</country-empty>
    <country-list>
      <country-option value="fr" label="France">France</country-option>
      <country-option value="jp" label="Japan">Japan</country-option>
    </country-list>
  </country-popup>
</country-picker>
```

每个元素都保留它对应的现成元素的行为、状态和数据属性：输入会过滤选项，方向键移动高亮，浮层在顶层打开。更多内容见[渲染](/docs/web-components/rendering)和[自定义部件](/docs/web-components/custom-parts)。

## 禁用
禁用的组合框无法聚焦或修改，也不会提交任何内容。只读的组合框仍可聚焦并提交它的值，但不会打开或接受修改。键盘导航会跳过禁用的选项，也无法选择它。

```ts title="disabled.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

const variants = [
  { label: "Billing country", attributes: 'default-value="fr" disabled' },
  { label: "Shipping from", attributes: 'default-value="fr" read-only' },
  { label: "Shipping to", attributes: "" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${variants
        .map(
          (variant) => `
            <ui-combobox ${variant.attributes}>
              <div data-slot="stack">
                <ui-combobox-label>${variant.label}</ui-combobox-label>
                <div data-slot="row">
                  <ui-combobox-input>
                    <input placeholder="Search countries…" />
                  </ui-combobox-input>
                  <ui-combobox-trigger>
                    <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
                  </ui-combobox-trigger>
                </div>
              </div>
              <ui-combobox-content hidden>
                <ui-combobox-empty>No countries found.</ui-combobox-empty>
                <ui-combobox-list>
                  ${countries
                    .map(
                      (country) => `
                        <ui-combobox-item value="${country.value}" label="${country.label}" ${country.value === "dk" ? "disabled" : ""}>
                          ${country.label}
                          <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                        </ui-combobox-item>
                      `
                    )
                    .join("")}
                </ui-combobox-list>
              </ui-combobox-content>
            </ui-combobox>
          `
        )
        .join("")}
    </div>
  `
  for (const combobox of root.querySelectorAll<
    HTMLElement & { itemToLabel: (value: string) => string }
  >("ui-combobox")) {
    combobox.itemToLabel = countryLabel
  }
}

export { mount }
```

Billing country 处于禁用状态，Shipping from 是只读的。打开 Shipping to：方向键会跳过 Denmark，它不能被选择。

## 清除与触发器
`ui-combobox-clear` 同时清除选择和查询，然后把焦点留在输入框里。只要两者中有一个有值，它就会出现。当有人删掉全部文字时，单选会立即清除，而不是等到列表关闭。列表还开着时，Escape 会把选择带回来；用其他方式关闭列表则保持已清除的状态。

```ts title="clear.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement, X } from "lucide"
import { log } from "./log"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

const frameworkLabel = (value: string) =>
  frameworks.find((framework) => framework.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox default-value="sveltekit">
      <div data-slot="stack">
        <ui-combobox-label>Framework</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Select a framework" />
          </ui-combobox-input>
          <ui-combobox-clear>
            <button aria-label="Clear framework">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-clear>
          <ui-combobox-trigger>
            <button aria-label="Show frameworks">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks
            .map(
              (framework) => `
                <ui-combobox-item value="${framework.value}" label="${framework.label}">
                  ${framework.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  combobox.itemToLabel = (value) => frameworkLabel(value as string)
  combobox.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(
      root,
      `${value ? frameworkLabel(value as string) : "Cleared"} (${reason})`
    )
  })
}

export { mount }
```

选择一个框架，然后按清除按钮。选择和文字被清除，焦点留在输入框里，控制台会记录每次变更。

## 自动高亮
加上 `auto-highlight`，在输入时高亮第一个匹配项，这样按 Enter 就能立即选中。使用 `auto-highlight="always"` 时，打开列表也会高亮已选中的项，没有已选项则高亮第一项，方向键就从那里开始移动。`auto-highlight="selected"` 只在列表打开时高亮已选中的项，没有已选项时不亮。它放置的高亮会随着选项到达而跟随列表，用户移动过的高亮则会在它的项仍然存在时保持不动。

```ts title="auto-highlight.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox auto-highlight>
      <div data-slot="stack">
        <ui-combobox-label>Country</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Type “sw” and press Enter" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list>
          ${countries
            .map(
              (country) => `
                <ui-combobox-item value="${country.value}" label="${country.label}">
                  ${country.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

输入 “sw” 并按 Enter。第一个匹配的国家已经处于高亮状态。

## 高亮匹配项
`ui-combobox-item-text` 会标记匹配的文字。匹配使用当前 locale 忽略大小写和变音符号，而标签保留原来的拼写。每个匹配都是一个 `<mark>`，可以自己设样式。

```ts title="highlight.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina", keywords: ["república argentina"] },
  { value: "au", label: "Australia", keywords: ["oz"] },
  { value: "at", label: "Austria", keywords: ["österreich"] },
  { value: "be", label: "Belgium", keywords: ["belgië", "belgique"] },
  { value: "br", label: "Brazil", keywords: ["brasil"] },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark", keywords: ["danmark"] },
  { value: "fi", label: "Finland", keywords: ["suomi"] },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany", keywords: ["deutschland"] },
  { value: "gr", label: "Greece", keywords: ["hellas", "ελλάδα"] },
  { value: "jp", label: "Japan", keywords: ["nippon", "日本"] },
  { value: "nl", label: "Netherlands", keywords: ["holland", "nederland"] },
  { value: "es", label: "Spain", keywords: ["españa"] },
  { value: "se", label: "Sweden", keywords: ["sverige"] },
  {
    value: "ch",
    label: "Switzerland",
    keywords: ["schweiz", "suisse", "svizzera"],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Country</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search countries…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list>
          ${countries
            .map(
              (country) => `
                <ui-combobox-item value="${country.value}" label="${country.label}" ${country.keywords ? `keywords="${country.keywords.join(",")}"` : ""}>
                  <ui-combobox-item-text>${country.label}</ui-combobox-item-text>
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

输入 “an”。匹配的字母会被标记，每个国家仍保留原来的拼写。

## 过滤与关键词
`filter` 接受 `"contains"`（默认值）、`"startsWith"`、一个以项和查询为参数的函数，或 `false`（结果已由服务器过滤）。函数可以返回分数而不是 `true` 或 `false`，通过 `items` 传入的项会按这个分数排序，最优在前。`@ui-sdk/core/text-match` 的 `fuzzyScore` 完全匹配的得分高于前缀匹配，前缀匹配又高于标签内部的匹配。把函数赋给 `filter` property。

用 `keywords` 提供能参与匹配、但不显示在标签里的文字，比如用户名或一个国家的本地名称。

```ts title="filter.ts"
import "@ui-sdk/web/combobox"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina", keywords: ["república argentina"] },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria", keywords: ["österreich"] },
  { value: "be", label: "Belgium", keywords: ["belgië", "belgique"] },
  { value: "br", label: "Brazil", keywords: ["brasil"] },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark", keywords: ["danmark"] },
  { value: "fi", label: "Finland", keywords: ["suomi"] },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany", keywords: ["deutschland"] },
  { value: "gr", label: "Greece", keywords: ["hellas", "ελλάδα"] },
  { value: "jp", label: "Japan", keywords: ["nippon", "日本"] },
  { value: "nl", label: "Netherlands", keywords: ["holland", "nederland"] },
  { value: "es", label: "Spain", keywords: ["españa"] },
  { value: "se", label: "Sweden", keywords: ["sverige"] },
  {
    value: "ch",
    label: "Switzerland",
    keywords: ["schweiz", "suisse", "svizzera"],
  },
]

function fuzzy(item: { label: string }, query: string) {
  let at = 0
  for (const char of item.label.toLowerCase()) {
    if (char === query[at]?.toLowerCase()) {
      at++
    }
  }
  return at === query.length
}

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <ui-select default-value="contains">
          <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-combobox filter="contains">
        <div data-slot="stack">
          <ui-combobox-label>Country</ui-combobox-label>
          <div data-slot="row">
            <ui-combobox-input>
              <input placeholder="Try “an”, “swd” or “deutschland”" />
            </ui-combobox-input>
            <ui-combobox-trigger>
              <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
            </ui-combobox-trigger>
          </div>
        </div>
        <ui-combobox-content hidden>
          <ui-combobox-empty>No countries found.</ui-combobox-empty>
          <ui-combobox-list>
            ${countries
              .map(
                (country) => `
                  <ui-combobox-item value="${country.value}" label="${country.label}"${country.keywords ? ` keywords="${country.keywords.join(",")}"` : ""}>
                    ${country.label}
                    <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                  </ui-combobox-item>
                `
              )
              .join("")}
          </ui-combobox-list>
        </ui-combobox-content>
      </ui-combobox>
    </div>
  `
  const combobox = root.querySelector("ui-combobox")!
  root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
    const mode = event.detail.value
    if (!mode) {
      return
    }
    if (mode === "fuzzy") {
      combobox.filter = fuzzy
    } else {
      combobox.filter = undefined
      combobox.setAttribute("filter", String(mode))
    }
  })
}

export { mount }
```

输入 “an”，在 Filter 的 Contains 和 Starts with 之间切换。选择 Fuzzy 并输入 “swd” 找到 Sweden，或输入 “deutschland” 通过关键词找到 Germany。

## 分组
用 `ui-combobox-group` 和 `ui-combobox-group-label` 给分组命名。随着分组里的项消失，过滤会隐藏空分组和分隔线。

```ts title="groups.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const timezones = [
  {
    label: "Americas",
    items: [
      { value: "America/New_York", label: "New York" },
      { value: "America/Chicago", label: "Chicago" },
      { value: "America/Denver", label: "Denver" },
      { value: "America/Los_Angeles", label: "Los Angeles" },
      { value: "America/Sao_Paulo", label: "São Paulo" },
    ],
  },
  {
    label: "Europe",
    items: [
      { value: "Europe/London", label: "London" },
      { value: "Europe/Paris", label: "Paris" },
      { value: "Europe/Berlin", label: "Berlin" },
      { value: "Europe/Madrid", label: "Madrid" },
    ],
  },
  {
    label: "Asia & Pacific",
    items: [
      { value: "Asia/Tokyo", label: "Tokyo" },
      { value: "Asia/Singapore", label: "Singapore" },
      { value: "Asia/Kolkata", label: "Kolkata" },
      { value: "Australia/Sydney", label: "Sydney" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Timezone</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search cities…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show timezones">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No cities found.</ui-combobox-empty>
        <ui-combobox-list>
          ${timezones
            .map(
              (group, index) => `
                ${index > 0 ? `<ui-combobox-separator></ui-combobox-separator>` : ""}
                <ui-combobox-group>
                  <ui-combobox-group-label>${group.label}</ui-combobox-group-label>
                  ${group.items
                    .map(
                      (item) => `
                        <ui-combobox-item value="${item.value}" label="${item.label}">
                          ${item.label}
                          <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                        </ui-combobox-item>
                      `
                    )
                    .join("")}
                </ui-combobox-group>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

输入 “chic”。Chicago 留在 Americas 分组里；没有匹配项的分组会消失。

## 图标
`ui-combobox-item-icon` 让装饰性图标不进入无障碍名称、过滤和匹配标记。`ui-combobox-value-icon` 把选中项的图标显示在输入框旁边；它不接受 children，且只用于单选。

把输入框和图标包在一起，再把这个包装元素作为浮层的 `anchor`。方向性图标加上 `mirror`。只有图标的选项仍然需要 `aria-label`。

```ts title="icons.ts"
import "@ui-sdk/web/combobox"
import {
  ArrowRight,
  Check,
  ChevronDown,
  Circle,
  CircleCheck,
  CircleX,
  createElement,
} from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Status</ui-combobox-label>
        <div id="combobox-icons-field" data-slot="row">
          <ui-combobox-value-icon></ui-combobox-value-icon>
          <ui-combobox-input>
            <input placeholder="Select a status" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show statuses">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden anchor="#combobox-icons-field">
        <ui-combobox-empty>No statuses found.</ui-combobox-empty>
        <ui-combobox-list>
          <ui-combobox-item value="backlog" label="Backlog">
            <ui-combobox-item-icon>${createElement(Circle, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-icon>
            <ui-combobox-item-text>Backlog</ui-combobox-item-text>
            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
          </ui-combobox-item>
          <ui-combobox-item value="in-progress" label="In progress">
            <ui-combobox-item-icon mirror>${createElement(ArrowRight, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-icon>
            <ui-combobox-item-text>In progress</ui-combobox-item-text>
            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
          </ui-combobox-item>
          <ui-combobox-item value="done" label="Done">
            <ui-combobox-item-icon>${createElement(CircleCheck, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-icon>
            <ui-combobox-item-text>Done</ui-combobox-item-text>
            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
          </ui-combobox-item>
          <ui-combobox-item value="canceled" label="Canceled">
            <ui-combobox-item-icon>${createElement(CircleX, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-icon>
            <ui-combobox-item-text>Canceled</ui-combobox-item-text>
            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
          </ui-combobox-item>
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

选择 Done。它的图标会出现在输入框旁边，也会出现在列表里。

## 自定义选项
在标签旁显示有用的上下文，比如用户名或角色。显式设置 `label`，让过滤和输入框使用预期的文字，并把额外的搜索词放进 `keywords`。

```ts title="custom-items.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const users = [
  { id: 1, name: "Hollis Grant", username: "hollis", role: "Owner" },
  { id: 2, name: "Inès Moreau", username: "ines", role: "Admin" },
  { id: 3, name: "Kofi Mensah", username: "kofi", role: "Member" },
  { id: 4, name: "Wren Takahashi", username: "wren", role: "Member" },
  { id: 5, name: "Tomasz Wójcik", username: "tomasz", role: "Guest" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Owner</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search people…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show people">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No people found.</ui-combobox-empty>
        <ui-combobox-list>
          ${users
            .map(
              (user) => `
                <ui-combobox-item value="${user.username}" label="${user.name}" keywords="${user.username}">
                  <span data-slot="badge">${user.name.slice(0, 1)}</span>
                  <span data-slot="stack">
                    <span>${user.name}</span>
                    <span data-slot="hint">@${user.username}</span>
                  </span>
                  <span data-slot="hint">${user.role}</span>
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

搜索某个人的姓名或用户名。选择一个结果，把那个人的姓名放进输入框。

## 以数据形式提供的选项
当 Combobox 需要整个集合时，比如最近使用的项、服务器结果或虚拟化，传入 `items`。把它赋为 property；元素会为你渲染不带内容的部件，`<template>` 为它们设样式。每一项的 `label` 提供用于过滤和输入框的文字；`keywords` 和 `disabled` 与你自己渲染的项用法相同。`ListData` 格式见[列表与菜单](/docs/web-components/lists-and-menus)。

```ts
const combobox = document.querySelector("ui-combobox")!
combobox.items = [
  { value: "apple", label: "Apple" },
  { value: "cherry", label: "Cherry", keywords: ["red"] },
  {
    type: "group",
    label: "Citrus",
    items: [{ value: "lemon", label: "Lemon" }],
  },
]
```

列表打开期间，项可以变化。选择和当前高亮会留在各自的项上；移除高亮所在的项会清除高亮。

## 最近使用的项
查询为空时，`emptyItems` 提供建议。把它和 `items` 搭配，覆盖完整的可搜索集合。把两者都赋为 property；模板会渲染当前活跃的集合。

```ts title="recent.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina", keywords: ["república argentina"] },
  { value: "au", label: "Australia", keywords: ["oz"] },
  { value: "at", label: "Austria", keywords: ["österreich"] },
  { value: "be", label: "Belgium", keywords: ["belgië", "belgique"] },
  { value: "br", label: "Brazil", keywords: ["brasil"] },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark", keywords: ["danmark"] },
  { value: "fi", label: "Finland", keywords: ["suomi"] },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany", keywords: ["deutschland"] },
  { value: "gr", label: "Greece", keywords: ["hellas", "ελλάδα"] },
  { value: "jp", label: "Japan", keywords: ["nippon", "日本"] },
  { value: "nl", label: "Netherlands", keywords: ["holland", "nederland"] },
  { value: "es", label: "Spain", keywords: ["españa"] },
  { value: "se", label: "Sweden", keywords: ["sverige"] },
  {
    value: "ch",
    label: "Switzerland",
    keywords: ["schweiz", "suisse", "svizzera"],
  },
]

const recentCountries = [
  {
    type: "group" as const,
    label: "Recent",
    items: [countries[9], countries[12], countries[15]],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Country</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search countries…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list></ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-group>
          <ui-combobox-group-label></ui-combobox-group-label>
          <ui-combobox-item>
            <ui-combobox-item-text></ui-combobox-item-text>
            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
          </ui-combobox-item>
        </ui-combobox-group>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  combobox.emptyItems = recentCountries
  combobox.announcement = (change) =>
    change.type === "results" ? `${change.count} countries match` : null
  combobox.items = countries
}

export { mount }
```

打开空的输入框，看到 Recent。开始输入以搜索所有国家；清空文字回到 Recent。

## 对象值
用 `itemToValue` property 提供对象的字符串标识和表单值，用 `itemToLabel` 提供显示的文字，当两个不同的对象可能代表同一个选项时用 `isItemEqualToValue`。

```html
<ui-combobox name="reviewer">…</ui-combobox>

<script type="module">
  const reviewer = document.querySelector("ui-combobox[name=reviewer]")
  reviewer.itemToValue = (person) => String(person.id)
  reviewer.itemToLabel = (person) => person.name
  reviewer.isItemEqualToValue = (person, value) => person.id === value.id
</script>
```

## 多选
加上 `multiple` 让值变成数组。选择选项会切换它，保持列表打开并清空查询。把输入框放进 `ui-combobox-chips`；元素会把每个值渲染成一个标签片，带一个移除按钮，你写 `<template>` 时它会复制其中的 `ui-combobox-chip`。

在空输入框里按 Backspace，一次按压就移除最后一个标签片。与 [Token Input](https://ui-sdk.cn/docs/web-components/components/token-input#deleting-tokens) 不同，没有先选中再删除的 `token-deletion` 选项。方向键在标签片之间移动。如果起始值还没有从渲染的项里得到标签，把 `itemToLabel` 设为 property。

加上 `keep-query`，连续选择多个匹配项而不用重新输入查询。

```ts title="multiple.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

const frameworkLabel = (value: string) =>
  frameworks.find((framework) => framework.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox multiple default-value="next, astro">
      <div data-slot="stack">
        <ui-combobox-label>Frameworks</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-chips>
            <ui-combobox-input>
              <input placeholder="Add a framework…" />
            </ui-combobox-input>
          </ui-combobox-chips>
          <ui-combobox-trigger>
            <button aria-label="Show frameworks">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks
            .map(
              (framework) => `
                <ui-combobox-item value="${framework.value}" label="${framework.label}">
                  ${framework.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-chip>
          <ui-combobox-chip-remove><button type="button">×</button></ui-combobox-chip-remove>
        </ui-combobox-chip>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox") as HTMLElement & {
    itemToLabel: (value: string) => string
  }
  combobox.itemToLabel = frameworkLabel
}

export { mount }
```

选择多个框架。用标签片上的按钮移除一个，或在空的输入框里按 Backspace 移除最后一个标签片。

## 全选
`ui-combobox-select-all` 切换所有匹配且启用的选项。在分组内，它只影响该分组。它加入键盘导航，并在部分选项被选中时报告混合状态。

```ts title="select-all.ts"
import "@ui-sdk/web/combobox"
import { Check, createElement, Minus } from "lucide"

const timezones = [
  {
    label: "Americas",
    items: [
      { value: "America/New_York", label: "New York" },
      { value: "America/Chicago", label: "Chicago" },
      { value: "America/Denver", label: "Denver" },
      { value: "America/Los_Angeles", label: "Los Angeles" },
      { value: "America/Sao_Paulo", label: "São Paulo" },
    ],
  },
  {
    label: "Europe",
    items: [
      { value: "Europe/London", label: "London" },
      { value: "Europe/Paris", label: "Paris" },
      { value: "Europe/Berlin", label: "Berlin" },
      { value: "Europe/Madrid", label: "Madrid" },
    ],
  },
  {
    label: "Asia & Pacific",
    items: [
      { value: "Asia/Tokyo", label: "Tokyo" },
      { value: "Asia/Singapore", label: "Singapore" },
      { value: "Asia/Kolkata", label: "Kolkata" },
      { value: "Australia/Sydney", label: "Sydney" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox multiple default-value="Europe/Paris">
      <div data-slot="stack">
        <ui-combobox-label>Timezones</ui-combobox-label>
        <ui-combobox-chips>
          <ui-combobox-input>
            <input placeholder="Add timezones…" />
          </ui-combobox-input>
        </ui-combobox-chips>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No timezones found.</ui-combobox-empty>
        <ui-combobox-list>
          <ui-combobox-select-all>
            <span>
              ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </span>
            Select all
          </ui-combobox-select-all>
          ${timezones
            .map(
              (group) => `
                <ui-combobox-group>
                  <ui-combobox-group-label>${group.label}</ui-combobox-group-label>
                  <ui-combobox-select-all>
                    <span data-hide="checked">Select all in ${group.label}</span>
                    <span data-show="checked">Clear ${group.label}</span>
                  </ui-combobox-select-all>
                  ${group.items
                    .map(
                      (zone) => `
                        <ui-combobox-item value="${zone.value}" label="${zone.label}">
                          <span>
                            <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                          </span>
                          ${zone.label}
                        </ui-combobox-item>
                      `
                    )
                    .join("")}
                </ui-combobox-group>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-chip>
          <ui-combobox-chip-remove><button type="button">×</button></ui-combobox-chip-remove>
        </ui-combobox-chip>
      </template>
    </ui-combobox>
  `
}

export { mount }
```

打开列表，选择一个分组的全选选项。输入以缩小匹配范围，然后对这批结果使用主全选选项。

## 会折叠的标签片
加上 `ui-combobox-chips-overflow`，让标签片保持在一行。它会测量哪些标签片放得下，隐藏其余的，并暴露它们的数量和标签。另外，`valuechange` 事件给你所选内容，用来做简短文字摘要。

```ts title="chips-overflow.ts"
import "@ui-sdk/web/combobox"
import { Check, createElement } from "lucide"

const countries = [
  { value: "ar", label: "Argentina", keywords: ["república argentina"] },
  { value: "au", label: "Australia", keywords: ["oz"] },
  { value: "at", label: "Austria", keywords: ["österreich"] },
  { value: "be", label: "Belgium", keywords: ["belgië", "belgique"] },
  { value: "br", label: "Brazil", keywords: ["brasil"] },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark", keywords: ["danmark"] },
  { value: "fi", label: "Finland", keywords: ["suomi"] },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany", keywords: ["deutschland"] },
  { value: "gr", label: "Greece", keywords: ["hellas", "ελλάδα"] },
  { value: "jp", label: "Japan", keywords: ["nippon", "日本"] },
  { value: "nl", label: "Netherlands", keywords: ["holland", "nederland"] },
  { value: "es", label: "Spain", keywords: ["españa"] },
  { value: "se", label: "Sweden", keywords: ["sverige"] },
  {
    value: "ch",
    label: "Switzerland",
    keywords: ["schweiz", "suisse", "svizzera"],
  },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox multiple default-value="fr, jp, se, de, ch">
      <div data-slot="stack">
        <ui-combobox-label>Countries</ui-combobox-label>
        <ui-combobox-chips>
          <ui-combobox-chips-overflow></ui-combobox-chips-overflow>
          <ui-combobox-input>
            <input placeholder="Add…" />
          </ui-combobox-input>
        </ui-combobox-chips>
        <p data-slot="hint"></p>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list>
          ${countries
            .map(
              (country) => `
                <ui-combobox-item value="${country.value}" label="${country.label}">
                  ${country.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-chip>
          <ui-combobox-chip-remove><button type="button">×</button></ui-combobox-chip-remove>
        </ui-combobox-chip>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  combobox.itemToLabel = (value) => countryLabel(value as string)
  const summary = root.querySelector("p")!
  const list = new Intl.ListFormat(document.documentElement.lang || undefined, {
    type: "conjunction",
  })
  const show = (value: string[]) => {
    const labels = value.map(countryLabel)
    summary.textContent = list.format(
      labels.length > 2
        ? [...labels.slice(0, 2), `${labels.length - 2} more`]
        : labels
    )
  }
  show(["fr", "jp", "se", "de", "ch"])
  combobox.addEventListener("valuechange", (event) =>
    show(event.detail.value as string[])
  )
}

export { mount }
```

添加或移除国家。不再放得下的标签片会被一个溢出计数取代；下面的摘要列出前两个。

## 最多可选数
`max-selected` 限制多选的数量。达到上限后，其他选项会变成禁用状态；它们的 `maxReached` 状态说明了原因。

```ts title="max-selected.ts"
import "@ui-sdk/web/combobox"
import { Check, createElement } from "lucide"

const labels = [
  "Bug",
  "Feature",
  "Documentation",
  "Design",
  "Performance",
  "Security",
  "Testing",
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox multiple max-selected="3" default-value="Bug, Design">
      <div data-slot="stack">
        <ui-combobox-label>Labels (up to 3)</ui-combobox-label>
        <ui-combobox-chips>
          <ui-combobox-input>
            <input placeholder="Add labels…" />
          </ui-combobox-input>
        </ui-combobox-chips>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-list>
          ${labels
            .map(
              (label) => `
                <ui-combobox-item value="${label}" label="${label}">
                  ${label}
                  <span data-slot="hint" data-show="disabled">Limit reached</span>
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-chip>
          <ui-combobox-chip-remove><button type="button">×</button></ui-combobox-chip-remove>
        </ui-combobox-chip>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")
}

export { mount }
```

选择第三个标签。其他未选中的标签会变得不可用，直到你移除一个。

## 新建选项
当没有标签精确匹配查询，且查询满足 `min-length` 时，`ui-combobox-create` 会提供这个查询作为选项。处理它的 `create` 事件来保存它；异步操作把 promise 传给 `event.detail.waitUntil()`。创建本身不会改变选择：保存之后再把新项加进来并选中它。

保存期间，这个选项会报告 `data-pending`、`aria-busy` 和 `aria-disabled`。被拒绝的 promise 可以通过它的错误状态拿到。

```ts title="create.ts"
import "@ui-sdk/web/combobox"
import { Check, createElement, LoaderCircle, Plus } from "lucide"

const labels = [
  "Bug",
  "Feature",
  "Documentation",
  "Design",
  "Performance",
  "Security",
  "Testing",
]

function saveLabel(name: string) {
  return new Promise<void>((resolve, reject) =>
    setTimeout(
      () =>
        name.length > 20
          ? reject(new Error("Labels are 20 characters at most."))
          : resolve(),
      800
    )
  )
}

const item = (label: string) => `
  <ui-combobox-item value="${label}">
    ${label}
    <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
  </ui-combobox-item>
`

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox multiple default-value="Bug">
      <div data-slot="stack">
        <ui-combobox-label>Labels</ui-combobox-label>
        <ui-combobox-chips>
          <ui-combobox-input>
            <input placeholder="Add or create a label…" />
          </ui-combobox-input>
        </ui-combobox-chips>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-list>
          ${labels.map(item).join("")}
          <ui-combobox-create min-length="2">
            ${createElement(LoaderCircle, { "data-slot": "spinner", "data-show": "pending", "aria-hidden": "true" }).outerHTML}
            <span data-show="pending">Creating “<span data-query></span>”…</span>
            ${createElement(Plus, { "data-hide": "pending", "aria-hidden": "true" }).outerHTML}
            <span data-slot="stack" data-hide="pending">
              <span>Create “<span data-query></span>”</span>
              <span data-error data-slot="hint"></span>
            </span>
          </ui-combobox-create>
        </ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-chip>
          <ui-combobox-chip-remove><button type="button">×</button></ui-combobox-chip-remove>
        </ui-combobox-chip>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox") as HTMLElement & {
    value: string[]
  }
  const error = root.querySelector("[data-error]")!
  combobox.addEventListener("querychange", (event) => {
    const query = (event as CustomEvent<{ value: string }>).detail.value.trim()
    for (const span of root.querySelectorAll("[data-query]")) {
      span.textContent = query
    }
  })
  combobox.addEventListener("create", (event) => {
    const { value, waitUntil } = (
      event as CustomEvent<{
        value: string
        waitUntil: (promise: Promise<unknown>) => void
      }>
    ).detail
    error.textContent = ""
    waitUntil(
      saveLabel(value).then(
        () => {
          root
            .querySelector("ui-combobox-create")!
            .insertAdjacentHTML("beforebegin", item(value))
          combobox.value = [...combobox.value, value]
        },
        (reason: Error) => {
          error.textContent = reason.message
          throw reason
        }
      )
    )
  })
}

export { mount }
```

输入一个新标签并选择 Create。保存后它会变成一个选中的标签片；超过 20 个字符的标签会显示错误。

## 自定义值
当建议是可选的，比如 datalist，用 `allow-custom-value`。没有高亮项时按 Enter，或列表关闭时，不匹配的文字会成为值。这不会在集合里创建新项。

```ts title="custom-value.ts"
import "@ui-sdk/web/combobox"
import { Check, createElement } from "lucide"
import { log } from "./log"

const titles = [
  "Designer",
  "Engineer",
  "Engineering manager",
  "Product manager",
  "Researcher",
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox allow-custom-value>
      <div data-slot="stack">
        <ui-combobox-label>Job title</ui-combobox-label>
        <ui-combobox-input>
          <input placeholder="Type any title…" />
        </ui-combobox-input>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>Press Enter to use “<span></span>”.</ui-combobox-empty>
        <ui-combobox-list>
          ${titles
            .map(
              (title) => `
                <ui-combobox-item value="${title}">
                  ${title}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  const query = root.querySelector("ui-combobox-empty span")!
  combobox.addEventListener(
    "querychange",
    (event) => (query.textContent = event.detail.value)
  )
  combobox.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(root, `${value ? `“${value}”` : "No title"} (${reason})`)
  })
}

export { mount }
```

输入一个不在建议里的职位名称，然后在没有高亮选项时按 Enter，或离开字段。文字会成为值，控制台会记录它。

## 浮层里的输入框
输入框也可以放在浮层里，由一个显示当前值的按钮打开。这时按钮会留在 Tab 顺序里。把内容锚定到它，打开时清空查询，关闭后把焦点还给它，就像这个示例一样。

```ts title="popup.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement, Search } from "lucide"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox default-value="jp">
      <ui-combobox-trigger>
        <button id="combobox-popup-button" aria-label="Country">
          <span>Japan</span>
          ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
        </button>
      </ui-combobox-trigger>
      <ui-combobox-content hidden anchor="#combobox-popup-button">
        <div data-slot="row">
          ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
          <ui-combobox-input>
            <input autofocus aria-label="Search countries" placeholder="Search…" />
          </ui-combobox-input>
        </div>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list>
          ${countries
            .map(
              (country) => `
                <ui-combobox-item value="${country.value}" label="${country.label}">
                  ${country.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox") as HTMLElement & {
    query: string
    itemToLabel: (value: string) => string
  }
  const button = root.querySelector<HTMLButtonElement>(
    "#combobox-popup-button"
  )!
  combobox.itemToLabel = countryLabel
  combobox.addEventListener("valuechange", (event) => {
    const { value } = (event as CustomEvent<{ value: string | null }>).detail
    button.querySelector("span")!.textContent = value
      ? countryLabel(value)
      : "Select a country"
  })
  combobox.addEventListener("openchange", (event) => {
    if ((event as CustomEvent<{ value: boolean }>).detail.value) {
      combobox.query = ""
    }
  })
  combobox.addEventListener("openchangecomplete", (event) => {
    if (!(event as CustomEvent<{ value: boolean }>).detail.value) {
      button.focus()
    }
  })
}

export { mount }
```

按 Country 打开浮层里的搜索字段。选择一个国家；关闭浮层会把焦点还给按钮。

## 异步搜索
用 [createAsyncOptions](/docs/web-components/utilities/async-options) 对搜索进行 debounce，并丢弃过期的结果。把它的 `items` 和 `status` 传给 Combobox，把 `filter` 设为 `false`，并把查询变化发送给加载函数。

`ui-combobox-status` 和 `ui-combobox-empty` 提供加载中、错误和空消息。没有自定义状态时，输入暂停后 Combobox 会播报结果数量。

```ts title="async.ts"
import { createAsyncOptions } from "@ui-sdk/core/async-options"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const movieTitles = [
  "The Shawshank Redemption",
  "The Godfather",
  "The Dark Knight",
  "Pulp Fiction",
  "Schindler's List",
  "The Lord of the Rings",
  "Fight Club",
  "Forrest Gump",
  "Inception",
  "The Matrix",
  "Goodfellas",
  "Interstellar",
  "Parasite",
  "Spirited Away",
  "Whiplash",
  "The Prestige",
  "The Departed",
  "Gladiator",
  "Alien",
  "Casablanca",
  "Amélie",
  "Arrival",
]

function searchMovies(query: string, { signal }: { signal: AbortSignal }) {
  return new Promise<{ value: string; label: string }[]>((resolve, reject) => {
    const timer = setTimeout(() => {
      const needle = query.trim().toLowerCase()
      resolve(
        movieTitles
          .filter((title) => title.toLowerCase().includes(needle))
          .map((title) => ({
            value: title.toLowerCase().replace(/\W+/g, "-"),
            label: title,
          }))
      )
    }, 500)
    signal.addEventListener("abort", () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox filter="false" default-query="the">
      <div data-slot="stack">
        <ui-combobox-label>Movie</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search movies…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show movies">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-status></ui-combobox-status>
        <ui-combobox-empty>No movies match “<span>the</span>”.</ui-combobox-empty>
        <ui-combobox-list></ui-combobox-list>
      </ui-combobox-content>
      <template>
        <ui-combobox-item>
          <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
        </ui-combobox-item>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  const status = root.querySelector("ui-combobox-status")!
  const query = root.querySelector("ui-combobox-empty span")!
  const movies = createAsyncOptions(searchMovies, {
    debounce: 300,
    query: "the",
    immediate: true,
  })
  const update = () => {
    const { items, status: loading } = movies.getState()
    combobox.items = items
    combobox.setAttribute("status", loading)
    status.textContent =
      loading === "error"
        ? "Couldn't load movies."
        : loading === "loading"
          ? "Searching…"
          : `${items.length} ${items.length === 1 ? "movie" : "movies"}`
  }
  movies.subscribe(update)
  update()
  combobox.addEventListener("querychange", (event) => {
    query.textContent = event.detail.value
    movies.setQuery(event.detail.value)
  })
}

export { mount }
```

把 “the” 换成另一个电影标题。状态会显示正在进行的搜索，然后是最近的结果。

## 加载更多
当滚动或高亮到达最后一个选项时，`loadmore` 事件会触发，每页一次，且页正在加载时不触发。把它连接到异步加载函数的 `loadMore()`；每页返回 `{ items, hasMore }`。

```ts title="infinite.ts"
import { createAsyncOptions } from "@ui-sdk/core/async-options"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const movieTitles = [
  "The Shawshank Redemption",
  "The Godfather",
  "The Dark Knight",
  "Pulp Fiction",
  "Schindler's List",
  "The Lord of the Rings",
  "Fight Club",
  "Forrest Gump",
  "Inception",
  "The Matrix",
  "Goodfellas",
  "Interstellar",
  "Parasite",
  "Spirited Away",
  "Whiplash",
  "The Prestige",
  "The Departed",
  "Gladiator",
  "Alien",
  "Casablanca",
  "Amélie",
  "Arrival",
]

function searchMoviePages(
  query: string,
  { signal, page }: { signal: AbortSignal; page: number }
) {
  return new Promise<{
    items: { value: string; label: string }[]
    hasMore: boolean
  }>((resolve, reject) => {
    const timer = setTimeout(() => {
      const needle = query.trim().toLowerCase()
      const found = movieTitles
        .filter((title) => title.toLowerCase().includes(needle))
        .map((title) => ({
          value: title.toLowerCase().replace(/\W+/g, "-"),
          label: title,
        }))
      resolve({
        items: found.slice(page * 5, page * 5 + 5),
        hasMore: found.length > page * 5 + 5,
      })
    }, 500)
    signal.addEventListener("abort", () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox filter="false">
      <div data-slot="stack">
        <ui-combobox-label>Movie</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search movies…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show movies">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No movies found.</ui-combobox-empty>
        <ui-combobox-list></ui-combobox-list>
        <ui-combobox-status></ui-combobox-status>
      </ui-combobox-content>
      <template>
        <ui-combobox-item>
          <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
        </ui-combobox-item>
      </template>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox")!
  const status = root.querySelector("ui-combobox-status")!
  const movies = createAsyncOptions(searchMoviePages, { immediate: true })
  const update = () => {
    const { items, status: loading, hasMore } = movies.getState()
    combobox.items = items
    combobox.setAttribute("status", loading)
    status.textContent =
      loading === "loading"
        ? "Loading more…"
        : hasMore
          ? `${items.length} loaded`
          : `All ${items.length}`
  }
  movies.subscribe(update)
  update()
  combobox.addEventListener("querychange", (event) =>
    movies.setQuery(event.detail.value)
  )
  combobox.addEventListener("loadmore", () => movies.loadMore())
}

export { mount }
```

打开电影列表，滚动或用方向键移动到最后一个结果。下一页会加载，同时现有结果保持可用。

## 虚拟化
提供 `items`，让过滤和键盘导航知道每一个选项，即使只渲染少数几行。`highlight` 事件报告要显示的行，每个已渲染项的 `index` 把它在完整列表中的位置告诉屏幕阅读器。

这个示例对 10,000 项做窗口化。让实际行高与虚拟化器的测量保持一致，并在显示某一行时使用滚动容器的可见高度。

```ts title="virtualized.ts"
import "@ui-sdk/web/combobox"
import { ChevronDown, createElement } from "lucide"

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

function visibleRows(
  scrollTop: number,
  height: number,
  count: number,
  row: number
) {
  const start = Math.max(0, Math.floor(scrollTop / row) - 4)
  const end = Math.min(count, Math.ceil((scrollTop + height) / row) + 4)
  return { start, end }
}

function scrollForRow(
  index: number,
  scrollTop: number,
  height: number,
  row: number
) {
  const top = index * row
  if (top < scrollTop) {
    return top
  }
  if (top + row > scrollTop + height) {
    return top + row - height
  }
  return scrollTop
}

const row = 32
const height = 288

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Item</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Search 10,000 items…" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show items">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <div>
          <ui-combobox-list></ui-combobox-list>
        </div>
      </ui-combobox-content>
    </ui-combobox>
  `
  const combobox = root.querySelector("ui-combobox") as HTMLElement & {
    items: typeof manyItems
  }
  const scroller = root.querySelector<HTMLElement>("ui-combobox-content > div")!
  const list = root.querySelector<HTMLElement>("ui-combobox-list")!

  let matches = manyItems
  const filter = (text: string) => {
    const needle = text.trim().toLowerCase()
    matches = needle
      ? manyItems.filter((item) => item.label.toLowerCase().includes(needle))
      : manyItems
  }

  const rendered = new Map<string, HTMLElement>()
  const render = () => {
    list.style.height = `${matches.length * row}px`
    const { start, end } = visibleRows(
      scroller.scrollTop,
      height,
      matches.length,
      row
    )
    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-combobox-item value="${item.value}" label="${item.label}" index="${index}" style="top: ${index * row}px; height: ${row}px">${item.label}</ui-combobox-item>`
      )
      rendered.set(value, list.lastElementChild as HTMLElement)
    }
  }
  render()
  combobox.items = manyItems
  scroller.addEventListener("scroll", render)
  combobox.addEventListener("querychange", (event) => {
    const { value, reason } = (
      event as CustomEvent<{ value: string; reason: string }>
    ).detail
    filter(reason === "input-change" ? value : "")
    render()
  })
  combobox.addEventListener("highlight", (event) => {
    const { index } = (
      event as CustomEvent<{ value: string | null; index: number }>
    ).detail
    if (index < 0) {
      return
    }
    scroller.scrollTop = scrollForRow(
      index,
      scroller.scrollTop,
      scroller.clientHeight,
      row
    )
    render()
  })
}

export { mount }
```

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

## 受控
选择、文字和浮层各有独立的值：

| 值      | 变更通知      | 含义                                        |
| ------- | ------------- | ------------------------------------------- |
| `value` | `valuechange` | 一个值或 `null`；使用 `multiple` 时是数组。 |
| `query` | `querychange` | 输入框的文字。                              |
| `open`  | `openchange`  | 浮层是否打开。                              |

读取或写入元素的 property，并监听这些事件。在变更事件上调用 `preventDefault()` 可以拒绝它。选择一个项会把它的标签写进输入框，被取消的选择保留当前值。未选择就关闭会恢复选中值的标签，除非允许自定义值。[状态与事件](/docs/web-components/state-and-events)介绍了绑定模式。

输入法正在组字时，比如日语转换或死键的重音，列表保持当前的过滤，且 `querychange` 的 `detail.composing: true`。等它变为 `false` 后再搜索服务器。

焦点离开输入框会以原因 `focus-out` 关闭浮层，即使焦点是代码移动的，比如一个获取焦点的通知。要让浮层保持打开，在那个 `openchange` 上调用 `preventDefault()`。

```ts title="controlled.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"
import { log } from "./log"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="value">Choose Japan</button>
        <button type="button" data-action="open">Open</button>
      </div>
      <ui-combobox default-value="fr" debug>
        <div data-slot="stack">
          <ui-combobox-label>Country</ui-combobox-label>
          <div data-slot="row">
            <ui-combobox-input>
              <input placeholder="Search countries…" />
            </ui-combobox-input>
            <ui-combobox-trigger>
              <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
            </ui-combobox-trigger>
          </div>
        </div>
        <ui-combobox-content hidden>
          <ui-combobox-empty>No countries found.</ui-combobox-empty>
          <ui-combobox-list>
            ${countries
              .map(
                (country) => `
                  <ui-combobox-item value="${country.value}" label="${country.label}">
                    ${country.label}
                    <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                  </ui-combobox-item>
                `
              )
              .join("")}
          </ui-combobox-list>
        </ui-combobox-content>
      </ui-combobox>
    </div>
  `
  const combobox = root.querySelector("ui-combobox")!
  combobox.itemToLabel = (value) => countryLabel(value as string)
  combobox.addEventListener("valuechange", (event) =>
    log(root, `value: ${event.detail.value} (${event.detail.reason})`)
  )
  combobox.addEventListener("querychange", (event) =>
    log(root, `query: “${event.detail.value}” (${event.detail.reason})`)
  )
  combobox.addEventListener("openchange", (event) =>
    log(root, `open: ${event.detail.value} (${event.detail.reason})`)
  )
  root
    .querySelector("[data-action=value]")!
    .addEventListener("click", () => (combobox.value = "jp"))
  root
    .querySelector("[data-action=open]")!
    .addEventListener("click", () => (combobox.open = true))
}

export { mount }
```

输入、选择，或使用按钮。控制台会记录每次值、查询和打开状态变更及其原因。

## 控制器
用元素的 `api` property。它可以读取或设置值和查询，打开或关闭列表，并聚焦输入框。列表关闭时 `open()` 兑现，带上原因和来源，包括 `unmount`；传入中止信号以便在取消时关闭它。[控制器](/docs/web-components/controllers)介绍了生命周期和设置。

```ts title="controller.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"
import { log } from "./log"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="open">Open and Wait</button>
        <button type="button" data-action="search">Search “sw”</button>
        <button type="button" data-action="germany">Choose Germany</button>
        <button type="button" data-action="clear">Clear</button>
      </div>
      <ui-combobox>
        <div data-slot="stack">
          <ui-combobox-label>Country</ui-combobox-label>
          <div data-slot="row">
            <ui-combobox-input>
              <input placeholder="Search countries…" />
            </ui-combobox-input>
            <ui-combobox-trigger>
              <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
            </ui-combobox-trigger>
          </div>
        </div>
        <ui-combobox-content hidden>
          <ui-combobox-empty>No countries found.</ui-combobox-empty>
          <ui-combobox-list>
            ${countries
              .map(
                (item) => `
                  <ui-combobox-item value="${item.value}" label="${item.label}">
                    ${item.label}
                    <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                  </ui-combobox-item>
                `
              )
              .join("")}
          </ui-combobox-list>
        </ui-combobox-content>
      </ui-combobox>
    </div>
  `
  const combobox = root.querySelector("ui-combobox")!
  combobox.itemToLabel = (value) => countryLabel(value as string)
  const country = combobox.api
  const actions: Record<string, () => void> = {
    open: async () => {
      const { reason } = await country.open()
      log(root, `Closed by ${reason}, with ${country.getValue() ?? "nothing"}`)
    },
    search: () => {
      country.focus()
      country.setQuery("sw")
      country.open()
    },
    germany: () => country.setValue("de"),
    clear: () => country.clear(),
  }
  for (const button of root.querySelectorAll<HTMLElement>("[data-action]")) {
    button.addEventListener("click", () => actions[button.dataset.action!]())
  }
}

export { mount }
```

用按钮从外部驱动 Combobox。Open and Wait 会记录列表如何关闭以及选中了什么。

## 定位
`side` 和 `align` 把浮层放在输入框或标签片周围。`anchor` 可以使用另一个元素，`ui-combobox-arrow` 会跟随碰撞处理之后选定的方向。[浮层](https://ui-sdk.cn/docs/web-components/popups#place-the-content)介绍了偏移和可用空间。

默认情况下页面保持可用。`modal="pointer"` 让外部按压只关闭列表；`modal` 还会锁定滚动，并让页面其余部分不可交互（inert）。浮层使用顶层并在原地渲染；当它的 DOM 属于别处时，比如影子根（shadow root），使用 `container`。

```ts title="positioning.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/combobox"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

const sides = [
  { value: "top", label: "Top" },
  { value: "right", label: "Right" },
  { value: "bottom", label: "Bottom" },
  { value: "left", label: "Left" },
]
const aligns = [
  { value: "start", label: "Start" },
  { value: "center", label: "Center" },
  { value: "end", label: "End" },
]

const select = (
  name: string,
  label: string,
  options: { value: string; label: string }[],
  value: string
) => `
  <ui-select data-control="${name}" default-value="${value}">
    <ui-select-label>${label}</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>
      ${options
        .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>
`

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        ${select("side", "Side", sides, "bottom")}
        ${select("align", "Align", aligns, "start")}
        <label data-slot="label">
          <ui-checkbox>
            <ui-checkbox-indicator>
              ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
            </ui-checkbox-indicator>
          </ui-checkbox>
          Anchor to the box
        </label>
      </div>
      <div id="combobox-positioning-box" data-slot="card">
        <ui-combobox>
          <ui-combobox-input>
            <input aria-label="Framework" placeholder="Framework" />
          </ui-combobox-input>
          <ui-combobox-content hidden side="bottom" align="start" side-offset="10" align-offset="0" collision-padding="16">
            <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
            <ui-combobox-list>
              ${frameworks
                .map(
                  (framework) => `
                    <ui-combobox-item value="${framework.value}" label="${framework.label}">
                      ${framework.label}
                      <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                    </ui-combobox-item>
                  `
                )
                .join("")}
            </ui-combobox-list>
          </ui-combobox-content>
        </ui-combobox>
      </div>
    </div>
  `
  const content = root.querySelector("ui-combobox-content")!
  for (const control of root.querySelectorAll("ui-select")) {
    control.addEventListener("valuechange", (event) => {
      if (event.detail.value) {
        content.setAttribute(
          control.dataset.control!,
          String(event.detail.value)
        )
      }
    })
  }
  root
    .querySelector("ui-checkbox")!
    .addEventListener("checkedchange", (event) => {
      if (event.detail.value === true) {
        content.setAttribute("anchor", "#combobox-positioning-box")
      } else {
        content.removeAttribute("anchor")
      }
    })
}

export { mount }
```

选择一个方向和一种对齐，然后打开列表。勾选 Anchor to the Box，让它以盒子而不是输入框为锚点。

## 动画
内容打开期间带有 `data-starting-style`，关闭期间带有 `data-ending-style`。从这些状态做过渡，浮层会保持挂载直到退场结束。`openchangecomplete` 事件在打开或关闭结束后触发，项指示器上的 `keep-mounted` 会让它留在页面里，用于选择动画。

```css
[data-slot="combobox-content"] {
  transition:
    opacity 0.15s,
    translate 0.2s cubic-bezier(0.22, 1, 0.36, 1);

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
    translate: 0 -6px;
  }
}
```

```ts title="animation.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"
import { log } from "./log"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Framework</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Select a framework" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show frameworks">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks
            .map(
              (framework) => `
                <ui-combobox-item value="${framework.value}" label="${framework.label}">
                  ${framework.label}
                  <ui-combobox-item-indicator keep-mounted>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
  root
    .querySelector("ui-combobox")!
    .addEventListener("openchangecomplete", (event) =>
      log(root, event.detail.value ? "Finished opening" : "Finished closing")
    )
}

export { mount }
```

打开并关闭列表。控制台会记录每个动画结束的时间。

## 呈现方式
用 `presentation="sheet"` 使用底部面板（sheet），或用 `"auto"` 在每次打开列表时，于小屏触摸设备上选择底部面板。输入框会移进面板的头部；仍然只有一个输入框和一个查询。

触摸打开时键盘不会弹出。轻点头部的输入框会弹出键盘并展开面板；关闭键盘会保留查询。选择一个项会关闭面板，除非设置了 `multiple`。向下轻扫会以原因 `swipe` 关闭它。

把选项放在 `ui-combobox-list` 里，让头部留在列表框之外。给面板内容一个高度，用 `data-presentation` 为它设样式，把 `translate` 留给面板行为。`--sheet-backdrop` 控制背景。除非把 `modal` 设为 false，否则面板是模态的；鼠标和键盘打开时，输入框移动时保持焦点。

```ts title="presentation.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, createElement } from "lucide"

const frameworks = [
  { value: "next", label: "Next.js" },
  { value: "sveltekit", label: "SvelteKit" },
  { value: "nuxt", label: "Nuxt" },
  { value: "remix", label: "Remix" },
  { value: "astro", label: "Astro" },
  { value: "solidstart", label: "SolidStart" },
  { value: "qwik", label: "Qwik City" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox presentation="sheet">
      <div data-slot="stack">
        <ui-combobox-label>Framework</ui-combobox-label>
        <div data-slot="row">
          <ui-combobox-input>
            <input placeholder="Select a framework" />
          </ui-combobox-input>
          <ui-combobox-trigger>
            <button aria-label="Show frameworks">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No frameworks found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks
            .map(
              (framework) => `
                <ui-combobox-item value="${framework.value}" label="${framework.label}">
                  ${framework.label}
                  <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
}

export { mount }
```

打开字段查看底部面板。在触摸设备上，轻点头部的搜索字段调出键盘，或向下轻扫关闭它。

## 表单
Combobox 以 `name` 提交选中的值，而不是查询文字。多个值作为独立的条目提交。`required` 阻止空提交，重置会恢复默认选择及其标签，`form` 让它加入页面别处的表单。

自定义元素在它的定义加载后加入表单。[表单](/docs/web-components/forms)介绍了共用的集成方式。

放在 [`ui-field`](/docs/web-components/components/field) 里时，字段为输入框提供无障碍名称、描述和错误。提交必填字段却没有选择时，会设置 `aria-invalid` 和 `data-invalid`。

```ts title="form.ts"
import "@ui-sdk/web/combobox"
import "@ui-sdk/web/field"
import { Check, ChevronDown, createElement, X } from "lucide"
import { log } from "./log"

const countries = [
  { value: "ar", label: "Argentina" },
  { value: "au", label: "Australia" },
  { value: "at", label: "Austria" },
  { value: "be", label: "Belgium" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "cl", label: "Chile" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "jp", label: "Japan" },
  { value: "nl", label: "Netherlands" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

const countryLabel = (value: string) =>
  countries.find((country) => country.value === value)?.label ?? value

const interests = ["Design", "Engineering", "Marketing", "Research", "Sales"]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field name="country">
        <ui-field-label>Country</ui-field-label>
        <ui-combobox required>
          <div data-slot="row">
            <ui-combobox-input>
              <input placeholder="Search countries…" />
            </ui-combobox-input>
            <ui-combobox-trigger>
              <button aria-label="Show countries">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
            </ui-combobox-trigger>
          </div>
          <ui-combobox-content hidden>
            <ui-combobox-empty>No countries found.</ui-combobox-empty>
            <ui-combobox-list>
              ${countries
                .map(
                  (country) => `
                    <ui-combobox-item value="${country.value}" label="${country.label}">
                      ${country.label}
                      <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                    </ui-combobox-item>
                  `
                )
                .join("")}
            </ui-combobox-list>
          </ui-combobox-content>
        </ui-combobox>
        <ui-field-description>Where we ship your order.</ui-field-description>
        <div>
          <ui-field-error match="valueMissing">Choose a country.</ui-field-error>
        </div>
      </ui-field>
      <ui-field name="interests">
        <ui-field-label>Interests</ui-field-label>
        <ui-combobox multiple default-value="Design">
          <ui-combobox-chips>
            <ui-combobox-input>
              <input placeholder="Add interests…" />
            </ui-combobox-input>
          </ui-combobox-chips>
          <ui-combobox-content hidden>
            <ui-combobox-list>
              ${interests
                .map(
                  (interest) => `
                    <ui-combobox-item value="${interest}">
                      ${interest}
                      <ui-combobox-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-combobox-item-indicator>
                    </ui-combobox-item>
                  `
                )
                .join("")}
            </ui-combobox-list>
          </ui-combobox-content>
          <template>
            <ui-combobox-chip>
              <ui-combobox-chip-remove>
                <button type="button">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button>
              </ui-combobox-chip-remove>
            </ui-combobox-chip>
          </template>
        </ui-combobox>
      </ui-field>
      <div data-slot="row">
        <button type="submit">Submit</button>
        <button type="reset">Reset</button>
      </div>
    </form>
  `
  root.querySelector("ui-combobox")!.itemToLabel = (value) =>
    countryLabel(value as string)
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const entries = [...new FormData(form)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(root, `Submitted ${entries.join("&")}`)
  })
}

export { mount }
```

不选国家直接提交，查看行内错误。选择一个并提交；控制台会记录值，Reset 会恢复默认值。

## 自定义渲染
元素没有 render 函数。在它们周围和内部放你自己的标记，用它们的属性设样式，并观察这些属性来改变里面的内容：这里的触发器按钮在 `data-open` 变化时切换箭头，每个项根据 `data-selected` 和 `data-highlighted` 显示对勾或 Enter。每个元素的状态列在[下面](https://ui-sdk.cn/docs/web-components/components/combobox#state)。

```ts title="custom-rendering.ts"
import "@ui-sdk/web/combobox"
import { Check, ChevronDown, ChevronUp, createElement, Search } from "lucide"

const users = [
  { id: 1, name: "Hollis Grant", username: "hollis", role: "Owner" },
  { id: 2, name: "Inès Moreau", username: "ines", role: "Admin" },
  { id: 3, name: "Kofi Mensah", username: "kofi", role: "Member" },
  { id: 4, name: "Wren Takahashi", username: "wren", role: "Member" },
  { id: 5, name: "Tomasz Wójcik", username: "tomasz", role: "Guest" },
]

const chevron = (open: boolean) =>
  createElement(open ? ChevronUp : ChevronDown, { "aria-hidden": "true" })
    .outerHTML

const mark = (item: Element) =>
  item.hasAttribute("data-selected")
    ? createElement(Check, { "aria-hidden": "true" }).outerHTML
    : item.hasAttribute("data-highlighted")
      ? `<kbd data-slot="kbd">Enter</kbd>`
      : ""

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-combobox>
      <div data-slot="stack">
        <ui-combobox-label>Assignee</ui-combobox-label>
        <div data-slot="row">
          <div data-slot="row">
            ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
            <ui-combobox-input>
              <input placeholder="Search people…" />
            </ui-combobox-input>
          </div>
          <ui-combobox-trigger>
            <button aria-label="Show people">${chevron(false)}</button>
          </ui-combobox-trigger>
        </div>
      </div>
      <ui-combobox-content hidden>
        <ui-combobox-empty>No one by that name.</ui-combobox-empty>
        <ui-combobox-list>
          ${users
            .map(
              (user) => `
                <ui-combobox-item value="${user.username}" label="${user.name}" keywords="${user.username}">
                  <span data-slot="badge">${user.name.slice(0, 1)}</span>
                  <span data-slot="stack">
                    ${user.name}
                    <span data-slot="hint">@${user.username}</span>
                  </span>
                </ui-combobox-item>
              `
            )
            .join("")}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `
  const update = (el: Element) => {
    if (el.localName === "button") {
      el.innerHTML = chevron(el.hasAttribute("data-open"))
    }
    if (el.localName !== "ui-combobox-item") {
      return
    }
    el.querySelector(":scope > svg, :scope > kbd")?.remove()
    el.insertAdjacentHTML("beforeend", mark(el))
  }
  const observer = new MutationObserver((records) =>
    records.forEach((record) => update(record.target as Element))
  )
  observer.observe(root.querySelector("ui-combobox-trigger")!, {
    subtree: true,
    attributeFilter: ["data-open"],
  })
  observer.observe(root.querySelector("ui-combobox-list")!, {
    subtree: true,
    attributeFilter: ["data-selected", "data-highlighted"],
  })
}

export { mount }
```

打开列表并在其中移动。打开时箭头会翻转，高亮的人显示 Enter，选中的人显示对勾。

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

用 `data-highlighted` 表示当前活动的选项，用 `data-selected` 表示已选中的值。因为键盘高亮移动时焦点通常不离开输入框，用内容的 `data-modality="keyboard"` 来为它设样式。真实的焦点可能为触摸屏阅读器移进列表，或移进底部面板。

`--anchor-width` 跟随输入框或标签片。`--available-height` 不会继承：嵌套的滚动容器需要它时，把它复制到内容上的自定义属性，比如 `--list-height: var(--available-height)`，然后在滚动容器上使用那个属性。

### `<ui-combobox-content>`
- `--anchor-width`: Width of the anchor, usually the trigger. Use it to match widths.
- `--anchor-height`: Height of the anchor.
- `--available-width`: Space beside the popup, up to the viewport edge. Not inherited either.
- `--available-height`: Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like `[--list-height:var(--available-height)]`, and reads `max-h-(--list-height)`. The first popup registers both names for the whole page with `CSS.registerProperty`, so they don't inherit anywhere. A page that needs them to inherit calls it first, with `inherits: true`. An `@property` rule can't, since a registration in script wins.
- `--transform-origin`: The point on the anchor the popup opens from. Use it to scale from the right place.
- `--arrow-offset`: Where the anchor's center falls along the popup's edge, kept `arrowPadding` from the corners. Position a ::before arrow with it.
- `--drawer-progress`: While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
- `--drawer-dim`: While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
- `--drawer-expand`: While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
- `--drawer-stack`: While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
- `--sheet-backdrop`: Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

### `<ui-combobox-viewport>`
- `--keyboard-inset`: While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: While it presents as a sheet: the width of the part of the page you can see.
- `--visual-viewport-height`: While it presents as a sheet: the height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: While it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

## 数据属性
### `<ui-combobox-label>`
`[data-slot="combobox-label"]`

- `data-disabled`: Present when the combobox is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the combobox is read-only.
- `data-required`: Present when the combobox is required.

### `<ui-combobox-input>`
`[data-slot="combobox-input"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-open`: Present while the list is open.
- `data-disabled`: Present when the combobox is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the combobox is read-only.
- `data-required`: Present when the combobox is required.

### `<ui-combobox-trigger>`
`[data-slot="combobox-trigger"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-open`: Present while the list is open.
- `data-disabled`: Present when the combobox is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the combobox is read-only.
- `data-required`: Present when the combobox is required.

### `<ui-combobox-clear>`
`[data-slot="combobox-clear"]`

- `data-disabled`: Present when the combobox is disabled or read-only.

### `<ui-combobox-chips>`
`[data-slot="combobox-chips"]`

- `data-disabled`: Present when the combobox is disabled, by its own prop, a field or a `<fieldset>`.
- `data-readonly`: Present when the combobox is read-only.
- `data-required`: Present when the combobox is required.

### `<ui-combobox-content>`
`[data-slot="combobox-content"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-presentation` (`popover`, `sheet`): How the list presents this time it's open.
- `data-open`: Present while the list is open.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while the list animates out. Style the state you animate to.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the list ended up, after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How the list lines up with the input.
- `data-modality` (`keyboard`, `pointer`): Whether the keyboard or a pointer moves the highlight. Style a focus ring for the keyboard only.
- `data-has-icons`: Present while any item inside holds an icon part, so items without one can line up.

### `<ui-combobox-item>`
`[data-slot="combobox-item"]`

- `data-selected`: Present on selected items, and on the check inside them.
- `data-disabled`: Present when the item can't be chosen, or `maxSelected` is reached.
- `data-highlighted`: Present on the highlighted item. Focus stays in the input.
- `data-has-icon`: Present on an item while it holds an icon part.

### `<ui-combobox-item-text>`
`[data-slot="combobox-item-text"]`

- `data-matched`: Present on an item's text while the input's text matched part of it, which is marked.

### `<ui-combobox-item-indicator>`
`[data-slot="combobox-item-indicator"]`

- `data-selected`: Present on selected items, and on the check inside them.

### `<ui-combobox-empty>`
`[data-slot="combobox-empty"]`

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

### `<ui-combobox-status>`
`[data-slot="combobox-status"]`

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

### `<ui-combobox-arrow>`
`[data-slot="combobox-arrow"]`

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-open`: Present while the list is open.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the list ended up, after flipping away from edges.
- `data-align` (`start`, `center`, `end`): How the list lines up with the input.
- `data-arrow-clamped`: Present on the arrow when it stops short of the middle of the input, held back by `arrowPadding`.

### `<ui-combobox-item-icon>`
`[data-slot="combobox-item-icon"]`

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

### `<ui-combobox-chip>`
`[data-slot="combobox-chip"]`

- `data-value` (`a`): The chip's value, as the string it submits as.
- `data-disabled`: Present when the combobox is disabled or read-only, so the chip can't be removed.

### `<ui-combobox-chip-remove>`
`[data-slot="combobox-chip-remove"]`

- `data-disabled`: Present when the combobox is disabled or read-only.

### `<ui-combobox-select-all>`
`[data-slot="combobox-select-all"]`

- `data-disabled`: Present when nothing the select-all option covers can be chosen, or choosing them all would pass `maxSelected`.
- `data-unchecked`: Present on a select-all option while none of its items is selected.
- `data-highlighted`: Present on the highlighted item. Focus stays in the input.

### `<ui-combobox-create>`
`[data-slot="combobox-create"]`

- `data-highlighted`: Present while the create option is highlighted.
- `data-pending`: Present while the Promise `onCreate` returned is running.

## API 参考
属性使用 kebab 形式，比如 `default-value`、`max-selected` 和 `auto-highlight`：`"false"` 是 false，数字就是数字。`filter` 接受 `contains`、`startsWith` 或 `false`。`items`、一个 `filter` 函数、`itemToValue`、`itemToLabel` 和 `isItemEqualToValue` 是 property。`container` 和 `anchor` 接受 CSS 选择器。回调是 DOM 事件。

### Combobox
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `query?` (`string`): The input's text, which filters the list. Pass it to control it. Choosing an item sets it to the item's label, or empties it with `multiple`.
- `defaultQuery?` (`string`): The input's text at first, when uncontrolled. Defaults to the selected item's label.
- `querychange event`: Runs when the input's text wants to change: typing, choosing an item, or closing with text that wasn't chosen. While an input method composes, `details.composing` is `true`; search once it's `false`.
- `open?` (`boolean`): Whether the list is open. Pass it to control it.
- `defaultOpen?` (`boolean`): Whether the list starts open, when uncontrolled.
- `openchange event`: Runs when the list wants to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `openchangecomplete event`: Runs once the list has finished opening or closing, after any animation.
- `maxSelected?` (`number`): With `multiple`, how many items can be selected. Once reached, the other items are disabled.
- `items?` (`ListData<T>`): The items as data. Renders the list for you, and filters it without rendering every item.
- `emptyItems?` (`ListData<T>`): Items shown instead of `items` while the input is empty, like recent choices or suggestions. Groups work, like `{ type: "group", label: "Recent", items }`. Needs `items`.
- `filter?` (`ListFilter<T>`): How typing narrows the list: `"contains"`, `"startsWith"`, a function of the item and the text, whose numeric result also sorts data items, or `false` to keep every item, for results a server already filtered.
- `itemToValue?` (`((value: T) => string)`): The string an item's value submits as and is identified by, for object values. Strings pass through, and objects use their `value` or `id`.
- `itemToLabel?` (`((value: T) => string)`): The text a value shows, for values whose item isn't rendered, like async results.
- `isItemEqualToValue?` (`((itemValue: T, value: T) => boolean)`): Whether an item's value is the selected value, for object values that aren't the same object.
- `autoHighlight?` (`"always" | "selected" | boolean`): Whether the first matching item is highlighted while typing, so Enter chooses it. `"always"` also highlights the selected item, or the first, when the list opens, so arrows move from there. `"selected"` highlights only the selected item when the list opens, and nothing when none is.
- `keepQuery?` (`boolean`): With `multiple`, whether the input keeps its text after an item is chosen.
- `pendingAnnouncement?` (`string`): What screen readers hear once the Create part's `create` 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.
- `allowCustomValue?` (`boolean`): Whether text that matches no item becomes the value, when Enter is pressed with nothing highlighted, or, without `multiple`, when the list closes. The value is the text itself.
- `status?` (`AsyncOptionsStatus`): Whether results are loading or failed, for the status and empty parts. Sets `aria-busy` on the list while loading.
- `highlight event`: Runs when the highlight moves, with the item's index among the visible items, so a virtualized list can scroll to it.
- `loadmore event`: Runs when the highlight or scrolling reaches the last item, so the next page can load, like `createAsyncOptions`'s `loadMore`. Not again for the same items, unless the last load failed.
- `announcement?` (`((change: ListAnnouncement) => string | null | undefined)`): What screen readers hear after typing pauses, when no `ComboboxStatus` is rendered, and when a chip is removed. Return null for nothing.
- `loop?` (`boolean`): Whether arrow keys wrap from the last item to the first.
- `modal?` (`"pointer" | boolean`): `false`: the page stays usable while the list is open. `"pointer"`: an outside press only closes the list. `true`: also locks scroll and makes the rest of the page inert.
- `presentation?` (`PresentationSetting<"popover">`): How the list presents. `"sheet"` slides it up from the bottom of the screen with the input in its header, where it can be swiped away, and `"auto"` does that on small touch screens. A tap that opens a sheet leaves the keyboard closed until the input in the header is tapped. Decided each time it opens; the server renders `"popover"` for `"auto"`.
- `disabled?` (`boolean`): Disables the combobox like a native input: it can't be focused or changed, and the value isn't submitted.
- `readOnly?` (`boolean`): Keeps the combobox focusable and its value submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission until a value is selected, with the browser's own message.
- `name?` (`string`): The name the value submits under. Without one, the combobox submits nothing.
- `form?` (`string`): The id of a form to belong to, when the combobox isn't inside that form.
- `controller?` (`object`): Opens, closes, reads and sets the combobox from anywhere. Create one with `createComboboxController()`.
- `dismissible?` (`boolean`): Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass `false` while it holds unsaved work, and ask in `dismissattempt`.
- `dismissattempt event`: Runs when `dismissible` refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.
- `multiple?` (`boolean`): Whether several items can be selected. The value is then a list, the list stays open as items toggle, and the input empties after each choice. Whether several items can be selected.
- `value?` (`T | T[] | null`): The selected value. Pass it to control the combobox. `null` selects nothing. The selected values. Pass it to control the combobox. The selected value, or values with `multiple`. Pass it to control the combobox.
- `defaultValue?` (`T | T[] | null`): The value selected at first, when uncontrolled. A form reset returns to it. The values selected at first, when uncontrolled. A form reset returns to them. The value or values selected at first, when uncontrolled. A form reset returns to it.
- `valuechange event`: Runs when a user, a form reset or a controller wants to change the value. `details.reason` says why, and `details.cancel()` stops it.

`announcement` 接收 `{ type: "results", count, query, loading }` 或 `{ type: "removed", label }`，返回要播报的词，静默时返回 `null`。默认文案是英文："3 results"、"No results"、"Loading" 或 "France removed"。

### ComboboxLabel
输入框可见的标签。`<ui-combobox-label>` 为输入框提供名称。

### ComboboxInput
过滤列表并显示所选标签的文本字段。`<ui-combobox-input>` 包装一个原生 `input`。

### ComboboxTrigger
打开和关闭列表。`<ui-combobox-trigger>` 包装一个原生 `button`，当输入框在它旁边时留在 Tab 顺序之外。

### ComboboxClear
- `keepMounted?` (`boolean`): Whether the clear button stays in the page while there's nothing to clear.

### ComboboxChips
容纳多选时的标签片和输入框。`<ui-combobox-chips>` 为每个值渲染一个标签片。

### ComboboxValue
没有 `ui-combobox-value` 元素：`<ui-combobox-chips>` 渲染标签片，`value` property 和 `valuechange` 事件给你所选内容，用来做摘要。

### ComboboxChip
- `value` (`T`): The selected value this chip shows.

### ComboboxChipRemove
移除它所在标签片的值。`<ui-combobox-chip-remove>` 包装一个原生 `button`。接受与 `ComboboxChip` 相同的 props。

### ComboboxChipsOverflow
为它周围的标签片开启折叠，并显示隐藏了多少个。`<ui-combobox-chips-overflow>` 持有计数。

### ComboboxValueIcon
在输入框旁显示选中项的图标。它不接受自己的 props，也不接受 children。

### ComboboxContent
- `side?` (`Side`): Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the input the list opens on.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How the list lines up with the input along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the input and the list, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the input, in pixels.
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels.
- `arrowPadding?` (`number`): Space to keep between the arrow and the popup's corners, in pixels.
- `anchor?` (`string | Anchor | null`): Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `keepMounted?` (`boolean`): Whether the list stays in the page, hidden, while closed.

### ComboboxArrow
从浮层指向它的锚点，跟随碰撞处理之后选定的方向。`<ui-combobox-arrow>` 定位在内容的边缘上。

### ComboboxStatus
播报加载中、错误和结果数量。`<ui-combobox-status>` 有 status 角色。

### ComboboxEmpty
在没有选项匹配时显示。`<ui-combobox-empty>` 在有匹配时保持隐藏。

### ComboboxList
容纳选项。`<ui-combobox-list>` 有 listbox 角色。

### ComboboxSelectAll
切换它所在分组内或分组外所有匹配且启用的选项。`<ui-combobox-select-all>` 有 option 角色。

### ComboboxGroup
把一个分组下的选项归到一起。`<ui-combobox-group>` 有 group 角色。

### ComboboxGroupLabel
为它的分组命名。`<ui-combobox-group-label>` 为分组提供名称。

### ComboboxItem
- `label?` (`string`): The text the input shows once chosen, and filtering matches, when the content isn't plain text. Not the accessible name: use `aria-label` for that.
- `keywords?` (`string[]`): More words filtering matches.
- `disabled?` (`boolean`): Keeps the item from being chosen. The keyboard and the pointer skip it. Sets `data-disabled` and `aria-disabled`.
- `index?` (`number`): The item's position among all visible items, for virtualized lists that render only some. Sets `aria-posinset` and `aria-setsize`.
- `value` (`T`): What the value becomes when the item is chosen. A string, or any value with `itemToValue`.

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

### ComboboxItemText
显示它所在项的名称，并在 `<mark>` 中标记匹配查询的部分。`<ui-combobox-item-text>` 只容纳文本。

### ComboboxItemIndicator
- `keepMounted?` (`boolean`): Whether the indicator stays in the page while its item isn't selected.

### ComboboxSeparator
分隔选项或分组。`<ui-combobox-separator>` 有 separator 角色。

### ComboboxCreate
- `create event`: Runs with the input's text when the create option is chosen. It doesn't change the value by itself. Return a Promise to mark the option pending until it settles; the list closes (or the input empties, with `multiple`) once it resolves.
- `minLength?` (`number`): How many characters the text needs before the option shows.

### 以数据形式提供的选项
`items` 中的每一项。分组是 `{ type: "group", label, items }`，分隔符是 `{ type: "separator" }`。

- `value` (`T`): Identifies the item, and is what choosing it reports. A string, or any value with `itemToValue`.
- `label` (`string`): The text shown and matched by typeahead and filtering. A select's trigger shows it once chosen.
- `keywords?` (`string[]`): More words filtering matches, like `["team"]` for a plan called Pro.
- `disabled?` (`boolean`): Keeps the item from being chosen. The keyboard skips it, like in a native select.

整个数组是一个 `ListData`，当值是对象时是 `ListData<Item>`。

### 异步选项
[异步选项](/docs/web-components/utilities/async-options)介绍加载、分页和重试。

### 状态
同样的状态会以数据属性的形式显示在每个元素上。

`ComboboxInput`：

- `open` (`boolean`): Whether the list is open.
- `disabled` (`boolean`): Whether the combobox is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the combobox keeps its value but refuses changes, from its `readOnly` option.
- `required` (`boolean`): Whether a value must be selected before the form submits, from its `required` option.

`ComboboxTrigger`：

- `open` (`boolean`): Whether the list is open.
- `disabled` (`boolean`): Whether the combobox is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the combobox keeps its value but refuses changes, from its `readOnly` option.
- `required` (`boolean`): Whether a value must be selected before the form submits, from its `required` option.

`ComboboxContent` 和 `ComboboxList`：

- `open` (`boolean`): Whether the list is open. False while it animates out.
- `presentation` (`"popover" | "sheet"`): How it presents this time it's open.
- `multiple` (`boolean | undefined`): Whether several items can be selected.
- `status` (`AsyncOptionsStatus`): Whether results are loading or failed.
- `items` (`ListData<unknown>`): The visible items, for rendering a virtualized list yourself.

`ComboboxItem`：

- `highlighted` (`boolean`): Whether the item is highlighted, by the keyboard or the pointer.
- `selected` (`boolean`): Whether its value is in the combobox's value, compared with `isItemEqualToValue` when you pass one.
- `disabled` (`boolean`): Whether the item can't be chosen, by itself or because `maxSelected` is reached.
- `maxReached` (`boolean`): Whether `maxSelected` is reached and the item isn't selected, which is why it's disabled.

`ComboboxItemIndicator`：

- `selected` (`boolean`): Whether its item is selected. While false, the indicator isn't shown unless `keepMounted` is set.

`ComboboxItemIcon`：

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

`ComboboxCreate`：

- `query` (`string`): The text the option would create.
- `highlighted` (`boolean`): Whether the option is highlighted.
- `pending` (`boolean`): Whether `onCreate`'s Promise is running.
- `error` (`unknown`): Why the last `onCreate` failed, until the next try.

`ComboboxEmpty`：

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

`ComboboxStatus`：

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

`ComboboxValue`：

- `value` (`unknown`): The selected value: one, `null`, or a list with `multiple`.
- `labels` (`string[]`): Each selected item's label, in the order they were selected.
- `label` (`string`): The labels joined with commas, or with `maxLabels`, as a list in the page's language, like "France, Chile and 2 more". An empty string for none.

`ComboboxChip`：

- `value` (`unknown`): The selected value the chip stands for, from its `value` prop.
- `label` (`string`): The text for the value: from `itemToLabel`, its item's label, or the value itself.
- `disabled` (`boolean`): Whether the combobox is disabled or read-only, so the chip can't be removed.

`ComboboxClear` 和 `ComboboxChipRemove`：

- `disabled` (`boolean`): Whether the combobox is disabled or read-only.

`ComboboxArrow`：

- `open` (`boolean`): Whether the list is open.

`ComboboxItemText`：

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

`ComboboxSelectAll`：

- `checked` (`boolean`): Whether every item it covers is selected.
- `indeterminate` (`boolean`): Whether some of its items are selected, but not all.
- `highlighted` (`boolean`): Whether it's highlighted, by the keyboard or the pointer.
- `disabled` (`boolean`): Whether it can't be used: nothing it covers can be chosen, or choosing them all would pass `maxSelected`.

`ComboboxChipsOverflow`：

- `count` (`number`): How many chips don't fit and are hidden.
- `labels` (`string[]`): The labels of the hidden chips.

### 原因
`event.detail.reason` 说明值为什么变化：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `remove-press` (`MouseEvent | KeyboardEvent`): A chip's remove part was pressed, or Backspace or Delete removed a chip or a span.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

文字为什么变化：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `reset` (`none`): A form reset.
- `imperative` (`none`): A controller or `api` call.
- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

以及列表为什么打开或关闭：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `imperative` (`none`): A controller or `api` call.
- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

当 `dismissible` 为 false 时，`dismissattempt` 报告这些被拒绝的关闭：

- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `outside-press` (`MouseEvent`): A press outside the layer.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.

### 控制器
元素的 `api` property 有同样的方法。

每个写入方法都接受一个可选的 `{ reason, event }`，变更事件会带上它。

- `isOpen()` (`() => boolean`): Whether the list is open.
- `setOpen(open, options?)` (`(open: boolean, options?: ComboboxChangeOptions<ComboboxOpenChangeReason> | undefined) => boolean`): Opens or closes the list. Returns false when the change was canceled or it was already open or closed.
- `open(options?)` (`(options?: (ComboboxChangeOptions<ComboboxOpenChangeReason> & { signal?: AbortSignal | undefined; }) | undefined) => Promise<...>`): Opens the list, and resolves once it closes, with why and how. Resolves exactly once and never rejects: on the next close from any source, when `signal` aborts, or with reason `"unmount"` when the combobox leaves the page.
- `close(options?)` (`(options?: ComboboxChangeOptions<ComboboxOpenChangeReason> | undefined) => boolean`): Closes the list. Returns false when the close was canceled or it was already closed.
- `toggle(options?)` (`(options?: ComboboxChangeOptions<ComboboxOpenChangeReason> | undefined) => boolean`): Opens the list when it's closed, and closes it when it's open. Returns false when the change was canceled.
- `getValue()` (`() => ComboboxValue<T, Multiple>`): The selected value.
- `setValue(value, options?)` (`(value: ComboboxValue<T, Multiple>, options?: ComboboxChangeOptions<ComboboxValueChangeReason> | undefined) => boolean`): Selects a value, as a user would. A disabled or read-only combobox ignores it. Returns false when the change was canceled or nothing changed.
- `clear(options?)` (`(options?: ComboboxChangeOptions<ComboboxValueChangeReason> | undefined) => boolean`): Selects nothing and empties the input. Returns false when the change was canceled or nothing changed.
- `getQuery()` (`() => string`): The input's text.
- `setQuery(query, options?)` (`(query: string, options?: ComboboxChangeOptions<ComboboxQueryChangeReason> | undefined) => boolean`): Changes the input's text, which filters the list. Returns false when the change was canceled or nothing changed.
- `getHighlighted()` (`() => T | null`): The value of the highlighted item, or null when none is.
- `highlight(value)` (`(value: T | null) => boolean`): Highlights the item with this value in the open list, scrolled into view, or none with null. Returns false when the list is closed, or no enabled item has the value.
- `focus()` (`() => void`): Moves focus to the input.

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

| 成员                      | 所属          | 说明                                                             |
| ------------------------- | ------------- | ---------------------------------------------------------------- |
| `value` property          | `ui-combobox` | 选中的值。设置它会像控制器那样选中                               |
| `query` property          | `ui-combobox` | 输入框的文字                                                     |
| `open` property、属性     | `ui-combobox` | 列表是否打开。该属性设置它一开始是否打开                         |
| `api` property            | `ui-combobox` | [控制器](https://ui-sdk.cn/docs/web-components/components/combobox#controller-1)                                          |
| `valuechange` 事件        | `ui-combobox` | `detail: { value, reason, event, source }`                       |
| `querychange` 事件        | `ui-combobox` | `detail: { value: query, reason, event, source, composing }`     |
| `openchange` 事件         | `ui-combobox` | `detail: { value: open, reason, event, source }`                 |
| `openchangecomplete` 事件 | `ui-combobox` | `detail: { value: open }`，在动画之后                            |
| `highlight` 事件          | `ui-combobox` | `detail: { value, index, event }`                                |
| `loadmore` 事件           | `ui-combobox` | 到达最后一个项时                                                 |
| `create` 事件             | `ui-combobox` | `detail: { value: query, waitUntil(promise) }`，来自 create 部件 |
| `dismissattempt` 事件     | `ui-combobox` | `detail: { reason, event }`，当一次关闭被拒绝时                  |

## 无障碍
组合框遵循[带列表自动完成的 WAI-ARIA 组合框模式](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/)。焦点通常留在输入框里，由 `aria-activedescendant` 标识高亮的选项。触摸屏阅读器使用的触发器可以把真实焦点移进列表，底部面板也有自己的[焦点行为](https://ui-sdk.cn/docs/web-components/components/combobox#presentation)。下面每一行都是一个自动化测试。

### 键盘
| 按键                  | 作用                                                        |
| --------------------- | ----------------------------------------------------------- |
| Typing                | 过滤选项并打开列表                                          |
| ArrowDown, ArrowUp    | 打开列表，然后移动高亮。除非 `loop="false"`，到任一端会绕回 |
| Enter                 | 选择高亮的选项                                              |
| Escape                | 关闭列表，然后恢复选中项的标签文字                          |
| Backspace             | 在带标签片的空输入框里，移除最后一个标签片                  |
| ArrowLeft, ArrowRight | 在标签片之间移动，在从右到左的文本中方向相反                |

### 经过测试的行为
**Input**

- Is a combobox named by its label, with list autocomplete.
- Typing opens the list with the items that match.
- Text an input method is composing filters once it's committed.
- Matching ignores case and accents.
- ArrowDown opens the list.
- Choosing with the keyboard leaves the caret after the text.
- Points to the list it controls while open.

**Highlight**

- Arrow keys move the highlight while focus stays in the input.
- Arrow keys skip disabled items.
- Moving over a disabled item leaves the highlight where it was.
- The highlighted option has the id aria-activedescendant names.

**AutoHighlight**

- The first match is highlighted from the first keystroke, so Enter chooses it.
- A disabled match is passed over.

**Choosing**

- Enter chooses the highlighted item, puts its label in the input and closes.
- Clicking an item chooses it and keeps focus in the input.
- A disabled item can't be chosen.
- After choosing, opening again shows every item with the chosen one selected.
- A canceled choice closes the list and keeps the value's label in the input.
- Text that matches nothing shows the empty message.

**Closing**

- Escape closes the list and keeps focus in the input.
- Escape after deleting the text brings back the value and its label.
- Leaving after deleting the text keeps the value empty.
- Clicking outside closes the list.
- Tab closes the list and moves on.

**Trigger and clear**

- The trigger button opens and closes the list.
- Clear empties the input and the value.

**Default value**

- Shows its label in the input.
- Typing inside the label keeps the caret where it is.

**Multiple**

- Choosing adds a chip and empties the input.
- A canceled choice adds no chip and keeps the text.
- Backspace in an empty input removes the last chip.
- A chip's remove button removes its value.

**Groups**

- Items sit in groups named by their labels, and empty groups hide while filtering.

**Forms**

- The form submits the value under the combobox's name.
- Several values submit under one name.
- A required combobox blocks submission until a value is chosen.
- A disabled combobox can't be focused.
- A disabled fieldset disables the combobox and leaves it out of the form.

**Async**

- Results load for the text, with the list kept while loading.
- The chosen item's label survives results that don't include it.

Runs in React、Vue 和 web components.

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

**Virtualized**

- Renders only the rows in view, each with its place in the whole list.
- Arrow keys reach items that weren't rendered, and the active descendant follows.
- Filtering covers every item, rendered or not.

Runs in React.

还测试了：

**Enhancements**

- The list is named by the combobox's label.
- A click on the label focuses the input and leaves the list closed.
- Filtering matches an item's keywords as well as its label.
- A create option offers the text, and hides when an item's label matches it exactly.
- Enter on the create option calls onCreate with the text.
- A create option is pending while onCreate's Promise runs.
- With multiple, the list stays open after choosing.
- MaxSelected disables the other items once reached.
- Arrow keys move between chips, and Backspace on one removes it.
- The chips are a toolbar named by the combobox's label.
- Web chips follow a label that changes after they rendered. Web components only.
- Enter on the trigger opens the list as the keyboard did.
- ArrowDown on the trigger opens the list at its first item.
- The content says whether the keyboard or a pointer is in use, while focus stays in the input.
- A form reset returns the combobox to its default value and label.
- Arrow keys keep the highlighted item in view when the … scrolls.

Runs in React、Vue 和 web components.

人们自行重建的行，这里和 Select 里都有：

**Items shown while nothing is typed**

- A combobox shows its recent items, as a group, until the user types.
- An autocomplete shows recent searches while the field is empty.

**Select all**

- Selects every item that can be chosen, then clears them, and says which with aria-checked.
- Is mixed while some are selected.
- Covers only the items the text matches.
- Is reached with the arrow keys and chosen with Enter.
- In a group, it covers that group.
- A select's works the same, with real focus.

**Chips that collapse**

- Chips past the line hide, and a count says how many.
- Removing chips brings the hidden ones back, and the count goes.
- A value text lists two labels and counts the rest, in the page's language. React 和 Vue only.
- A select's value lists two labels and counts the rest.
- A web select value takes getMoreLabel as a property. Web components only.

**Loading more**

- Reaching the last item with the keyboard loads the next page.
- Scrolling to the end loads the next page, with a status while it does.
- The last page loads no more.

**Rows**

- A recent item is chosen like any other.
- Typing on a select never lands on it.

Runs in React、Vue 和 web components.

匹配高亮，这里以及 Autocomplete 和 Command 里都有：

**Combobox**

- Marks the part of each label the text matched.
- Marks keep the label's own case and accents while matching without them.
- An item matched by a keyword has nothing to mark.
- Marks go away when the text is cleared, and the label reads whole.

**Autocomplete**

- Marks the part of each suggestion the text matched.

**Command**

- Marks each letter a fuzzy match found, joining neighbours.
- Marks a whole match at a word start.

**Highlighting**

- The chosen label in the input shows every item unmarked.

Runs in React、Vue 和 web components.

触摸屏阅读器和播报：

**A screen reader's tap moves real focus into the list**

- Autocomplete: tapping the trigger focuses the first suggestion, and Escape returns.
- Searchable select: tapping the trigger focuses the selected item, not the search field.

**Combobox**

- Tapping the trigger focuses the selected item, with no aria-activedescendant.
- Arrow keys move real focus, and choosing returns focus to the input.
- Escape closes the list and focus returns to the input.

**Announcements**

- How many items match is announced once typing pauses.
- Autocomplete and searchable select announce counts too.
- Removing a chip announces which.

**Touch screen readers and announcements**

- A tap on the input is for typing: focus stays there.
- A status part says it instead, so nothing is announced twice.

Runs in React、Vue 和 web components.

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

- Announcements while filtering and choosing with a keyboard.

Runs in React、Vue 和 web components.
