# Combobox

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

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

```vue title="demo.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Framework</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Select a framework" />
        <ComboboxTrigger aria-label="Show frameworks">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="framework in frameworks"
          :key="framework.value"
          :value="framework.value"
          :label="framework.label"
        >
          {{ framework.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

```text
Combobox
├── ComboboxLabel
├── ComboboxInput
└── ComboboxContent
    └── ComboboxList
        ├── ComboboxItem
        └── ComboboxItem
```

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

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

```vue
<script setup lang="ts">
import {
  Combobox,
  ComboboxContent,
  ComboboxInput,
  ComboboxItem,
  ComboboxLabel,
  ComboboxList,
} from "@ui-sdk/vue/combobox"
</script>

<template>
  <Combobox>
    <ComboboxLabel>Fruit</ComboboxLabel>
    <ComboboxInput placeholder="Search fruits…" />
    <ComboboxContent>
      <ComboboxList>
        <ComboboxItem value="apple">Apple</ComboboxItem>
        <ComboboxItem value="banana">Banana</ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

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

```ts title="country-picker.ts"
import { combobox } from "@ui-sdk/core/combobox"
import { createParts } from "@ui-sdk/vue/primitive"

const {
  Root: CountryPicker,
  Label: CountryLabel,
  Input: CountryInput,
  Content: CountryPopup,
  List: CountryList,
  Item: CountryOption,
  Empty: CountryEmpty,
} = createParts(combobox, {
  label: "label",
  input: "input",
  content: "div",
  list: "div",
  item: "div",
  empty: "div",
})

export {
  CountryEmpty,
  CountryInput,
  CountryLabel,
  CountryList,
  CountryOption,
  CountryPicker,
  CountryPopup,
}
```

```vue
<template>
  <CountryPicker>
    <CountryLabel>Country</CountryLabel>
    <CountryInput />
    <CountryPopup>
      <CountryEmpty>No countries found.</CountryEmpty>
      <CountryList>
        <CountryOption value="fr" label="France">France</CountryOption>
        <CountryOption value="jp" label="Japan">Japan</CountryOption>
      </CountryList>
    </CountryPopup>
  </CountryPicker>
</template>
```

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

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

```vue title="disabled.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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 = ["disabled", "readOnly", "item"] as const
</script>

<template>
  <div data-slot="stack">
    <Combobox
      v-for="variant in variants"
      :key="variant"
      :default-value="variant === 'item' ? null : 'fr'"
      :item-to-label="countryLabel"
      :disabled="variant === 'disabled'"
      :read-only="variant === 'readOnly'"
    >
      <div data-slot="stack">
        <ComboboxLabel>
          {{
            variant === "disabled"
              ? "Billing country"
              : variant === "readOnly"
                ? "Shipping from"
                : "Shipping to"
          }}
        </ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Search countries…" />
          <ComboboxTrigger aria-label="Show countries">
            <ChevronDownIcon aria-hidden="true" />
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxEmpty>No countries found.</ComboboxEmpty>
        <ComboboxList>
          <ComboboxItem
            v-for="country in countries"
            :key="country.value"
            :value="country.value"
            :label="country.label"
            :disabled="country.value === 'dk'"
          >
            {{ country.label }}
            <ComboboxItemIndicator>
              <CheckIcon aria-hidden="true" />
            </ComboboxItemIndicator>
          </ComboboxItem>
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  </div>
</template>
```

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

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

```vue title="clear.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxClear,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"
import { useLog } 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

const log = useLog()
const value = ref<string | null>("sveltekit")
</script>

<template>
  <Combobox
    v-model:value="value"
    :item-to-label="frameworkLabel"
    @value-change="
      (next: string | null, details: { reason: string }) =>
        log(`${next ? frameworkLabel(next) : 'Cleared'} (${details.reason})`)
    "
  >
    <div data-slot="stack">
      <ComboboxLabel>Framework</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Select a framework" />
        <ComboboxClear aria-label="Clear framework">
          <XIcon aria-hidden="true" />
        </ComboboxClear>
        <ComboboxTrigger aria-label="Show frameworks">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="framework in frameworks"
          :key="framework.value"
          :value="framework.value"
          :label="framework.label"
        >
          {{ framework.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="auto-highlight.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox auto-highlight>
    <div data-slot="stack">
      <ComboboxLabel>Country</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Type “sw” and press Enter" />
        <ComboboxTrigger aria-label="Show countries">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No countries found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="country in countries"
          :key="country.value"
          :value="country.value"
          :label="country.label"
        >
          {{ country.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

## 高亮匹配项
`ComboboxItemText` 会标记匹配的文字。匹配使用当前 locale 忽略大小写和变音符号，而标签保留原来的拼写。如果你想自己渲染标记，它的状态也会暴露 `segments`。

```vue title="highlight.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxItemText,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Country</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search countries…" />
        <ComboboxTrigger aria-label="Show countries">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No countries found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="country in countries"
          :key="country.value"
          :value="country.value"
          :label="country.label"
          :keywords="country.keywords"
        >
          <ComboboxItemText>
            <template #render="{ props, state }">
              <span v-bind="props">
                <template
                  v-for="(segment, index) in state.segments"
                  :key="index"
                >
                  <mark v-if="segment.match">{{ segment.text }}</mark>
                  <template v-else>{{ segment.text }}</template>
                </template>
              </span>
            </template>
          </ComboboxItemText>
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

```vue title="filter.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/vue/select"
import { ref } from "vue"

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 filters = {
  contains: "contains",
  startsWith: "startsWith",
  fuzzy,
} as const
const modes = [
  { value: "contains", label: "Contains" },
  { value: "startsWith", label: "Starts with" },
  { value: "fuzzy", label: "Fuzzy" },
]
type Mode = keyof typeof filters

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

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <Select
        :items="modes"
        :value="mode"
        @value-change="(next) => next && (mode = next as Mode)"
      >
        <SelectLabel>Filter</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in modes"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>
    <Combobox :filter="filters[mode]">
      <div data-slot="stack">
        <ComboboxLabel>Country</ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Try “an”, “swd” or “deutschland”" />
          <ComboboxTrigger aria-label="Show countries">
            <ChevronDownIcon aria-hidden="true" />
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxEmpty>No countries found.</ComboboxEmpty>
        <ComboboxList>
          <ComboboxItem
            v-for="country in countries"
            :key="country.value"
            :value="country.value"
            :label="country.label"
            :keywords="country.keywords"
          >
            {{ country.label }}
            <ComboboxItemIndicator>
              <CheckIcon aria-hidden="true" />
            </ComboboxItemIndicator>
          </ComboboxItem>
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  </div>
</template>
```

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

## 分组
用 `ComboboxGroup` 和 `ComboboxGroupLabel` 给分组命名。随着分组里的项消失，过滤会隐藏空分组和分隔线。

```vue title="groups.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxGroup,
  ComboboxGroupLabel,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxSeparator,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Timezone</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search cities…" />
        <ComboboxTrigger aria-label="Show timezones">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No cities found.</ComboboxEmpty>
      <ComboboxList>
        <template v-for="(group, index) in timezones" :key="group.label">
          <ComboboxSeparator v-if="index > 0" />
          <ComboboxGroup>
            <ComboboxGroupLabel>
              {{ group.label }}
            </ComboboxGroupLabel>
            <ComboboxItem
              v-for="item in group.items"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
              {{ item.label }}
              <ComboboxItemIndicator>
                <CheckIcon aria-hidden="true" />
              </ComboboxItemIndicator>
            </ComboboxItem>
          </ComboboxGroup>
        </template>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

```vue title="icons.vue"
<script setup lang="ts">
import {
  ArrowRightIcon,
  CheckIcon,
  ChevronDownIcon,
  CircleIcon,
  CircleCheckIcon,
  CircleXIcon,
} from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIcon,
  ComboboxItemIndicator,
  ComboboxItemText,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
  ComboboxValueIcon,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"

const field = ref<HTMLDivElement | null>(null)
</script>

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Status</ComboboxLabel>
      <div ref="field" data-slot="row">
        <ComboboxValueIcon />
        <ComboboxInput placeholder="Select a status" />
        <ComboboxTrigger aria-label="Show statuses">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent :anchor="field">
      <ComboboxEmpty>No statuses found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem value="backlog" label="Backlog">
          <ComboboxItemIcon>
            <CircleIcon />
          </ComboboxItemIcon>
          <ComboboxItemText />
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
        <ComboboxItem value="in-progress" label="In progress">
          <ComboboxItemIcon mirror>
            <ArrowRightIcon />
          </ComboboxItemIcon>
          <ComboboxItemText />
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
        <ComboboxItem value="done" label="Done">
          <ComboboxItemIcon>
            <CircleCheckIcon />
          </ComboboxItemIcon>
          <ComboboxItemText />
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
        <ComboboxItem value="canceled" label="Canceled">
          <ComboboxItemIcon>
            <CircleXIcon />
          </ComboboxItemIcon>
          <ComboboxItemText />
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="custom-items.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Owner</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search people…" />
        <ComboboxTrigger aria-label="Show people">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No people found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="user in users"
          :key="user.id"
          :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>
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue
<script setup lang="ts">
const fruits = [
  { value: "apple", label: "Apple" },
  { value: "cherry", label: "Cherry", keywords: ["red"] },
  {
    type: "group",
    label: "Citrus",
    items: [{ value: "lemon", label: "Lemon" }],
  },
]
</script>

<template>
  <Combobox :items="fruits">
    <ComboboxInput aria-label="Fruit" />
  </Combobox>
</template>
```

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

## 最近使用的项
查询为空时，`empty-items` 提供建议。把它和 `items` 搭配，覆盖完整的可搜索集合。从 `state.items` 渲染列表，让它跟随当前的集合。

```vue title="recent.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxGroup,
  ComboboxGroupLabel,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxItemText,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import type { ListAnnouncement } from "@ui-sdk/core/combobox"

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

const announcement = (change: ListAnnouncement) =>
  change.type === "results" ? `${change.count} countries match` : null
</script>

<template>
  <Combobox
    :items="countries"
    :empty-items="recentCountries"
    :announcement="announcement"
  >
    <div data-slot="stack">
      <ComboboxLabel>Country</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search countries…" />
        <ComboboxTrigger aria-label="Show countries">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No countries found.</ComboboxEmpty>
      <ComboboxList v-slot="{ state }">
        <template
          v-for="entry in state.items as (
            (typeof countries)[number] | (typeof recentCountries)[number]
          )[]"
          :key="'items' in entry ? entry.label : entry.value"
        >
          <ComboboxGroup v-if="'items' in entry">
            <ComboboxGroupLabel>{{ entry.label }}</ComboboxGroupLabel>
            <ComboboxItem
              v-for="country in entry.items"
              :key="country.value"
              :value="country.value"
              :label="country.label"
            >
              <ComboboxItemText />
              <ComboboxItemIndicator>
                <CheckIcon aria-hidden="true" />
              </ComboboxItemIndicator>
            </ComboboxItem>
          </ComboboxGroup>
          <ComboboxItem v-else :value="entry.value" :label="entry.label">
            <ComboboxItemText />
            <ComboboxItemIndicator>
              <CheckIcon aria-hidden="true" />
            </ComboboxItemIndicator>
          </ComboboxItem>
        </template>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

## 对象值
用 `item-to-value` 提供对象的字符串标识和表单值，用 `item-to-label` 提供显示的文字，当两个不同的对象可能代表同一个选项时用 `is-item-equal-to-value`。

```vue
<Combobox
  name="reviewer"
  :item-to-value="(person) => String(person.id)"
  :item-to-label="(person) => person.name"
  :is-item-equal-to-value="(person, value) => person.id === value.id"
/>
```

## 多选
加上 `multiple` 让值变成数组。选择选项会切换它，保持列表打开并清空查询。把 `ComboboxValue` 和输入框放进 `ComboboxChips`，然后把手里的每个值渲染成一个标签片，带一个移除按钮。

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

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

```vue title="multiple.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"

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
</script>

<template>
  <Combobox
    multiple
    :default-value="['next', 'astro']"
    :item-to-label="frameworkLabel"
  >
    <div data-slot="stack">
      <ComboboxLabel>Frameworks</ComboboxLabel>
      <div data-slot="row">
        <ComboboxChips>
          <ComboboxValue v-slot="{ state }">
            <ComboboxChip
              v-for="(value, index) in state.value as string[]"
              :key="value"
              :value="value"
            >
              {{ state.labels[index] }}
              <ComboboxChipRemove :aria-label="`Remove ${state.labels[index]}`">
                <XIcon aria-hidden="true" />
              </ComboboxChipRemove>
            </ComboboxChip>
          </ComboboxValue>
          <ComboboxInput placeholder="Add a framework…" />
        </ComboboxChips>
        <ComboboxTrigger aria-label="Show frameworks">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="framework in frameworks"
          :key="framework.value"
          :value="framework.value"
          :label="framework.label"
        >
          {{ framework.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="select-all.vue"
<script setup lang="ts">
import { CheckIcon, MinusIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxGroup,
  ComboboxGroupLabel,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxSelectAll,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox multiple :default-value="['Europe/Paris']">
    <div data-slot="stack">
      <ComboboxLabel>Timezones</ComboboxLabel>
      <ComboboxChips>
        <ComboboxValue v-slot="{ state }">
          <ComboboxChip
            v-for="(value, index) in state.value as string[]"
            :key="value"
            :value="value"
          >
            {{ state.labels[index] }}
            <ComboboxChipRemove :aria-label="`Remove ${state.labels[index]}`">
              <XIcon aria-hidden="true" />
            </ComboboxChipRemove>
          </ComboboxChip>
        </ComboboxValue>
        <ComboboxInput placeholder="Add timezones…" />
      </ComboboxChips>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No timezones found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxSelectAll>
          <span>
            <CheckIcon aria-hidden="true" />
            <MinusIcon aria-hidden="true" />
          </span>
          Select all
        </ComboboxSelectAll>
        <ComboboxGroup v-for="group in timezones" :key="group.label">
          <ComboboxGroupLabel>
            {{ group.label }}
          </ComboboxGroupLabel>
          <ComboboxSelectAll v-slot="{ state }">
            {{
              state.checked
                ? `Clear ${group.label}`
                : `Select all in ${group.label}`
            }}
          </ComboboxSelectAll>
          <ComboboxItem
            v-for="zone in group.items"
            :key="zone.value"
            :value="zone.value"
            :label="zone.label"
          >
            <span>
              <ComboboxItemIndicator>
                <CheckIcon aria-hidden="true" />
              </ComboboxItemIndicator>
            </span>
            {{ zone.label }}
          </ComboboxItem>
        </ComboboxGroup>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

## 会折叠的标签片
加上 `ComboboxChipsOverflow`，让标签片保持在一行。它会测量哪些标签片放得下，隐藏其余的，并暴露它们的数量和标签。另外，`ComboboxValue` 可以用 `max` 显示所选内容的简短文字摘要。

```vue title="chips-overflow.vue"
<script setup lang="ts">
import { CheckIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxChipsOverflow,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"

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
</script>

<template>
  <Combobox
    multiple
    :default-value="['fr', 'jp', 'se', 'de', 'ch']"
    :item-to-label="countryLabel"
  >
    <div data-slot="stack">
      <ComboboxLabel>Countries</ComboboxLabel>
      <ComboboxChips>
        <ComboboxValue v-slot="{ state }">
          <ComboboxChip
            v-for="(value, index) in state.value as string[]"
            :key="value"
            :value="value"
          >
            {{ state.labels[index] }}
            <ComboboxChipRemove :aria-label="`Remove ${state.labels[index]}`">
              <XIcon aria-hidden="true" />
            </ComboboxChipRemove>
          </ComboboxChip>
        </ComboboxValue>
        <ComboboxChipsOverflow>
          <template #render="{ props, state }">
            <span
              v-bind="props"
              :title="state.labels.join(', ')"
              data-slot="hint"
            >
              +{{ state.count }}
            </span>
          </template>
        </ComboboxChipsOverflow>
        <ComboboxInput placeholder="Add…" />
      </ComboboxChips>
      <p data-slot="hint">
        <ComboboxValue
          :max-labels="2"
          :get-more-label="(count: number) => `${count} more`"
        />
      </p>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No countries found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="country in countries"
          :key="country.value"
          :value="country.value"
          :label="country.label"
        >
          {{ country.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="max-selected.vue"
<script setup lang="ts">
import { CheckIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxContent,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"

const labels = [
  "Bug",
  "Feature",
  "Documentation",
  "Design",
  "Performance",
  "Security",
  "Testing",
]
</script>

<template>
  <Combobox multiple :max-selected="3" :default-value="['Bug', 'Design']">
    <div data-slot="stack">
      <ComboboxLabel>Labels (up to 3)</ComboboxLabel>
      <ComboboxChips>
        <ComboboxValue v-slot="{ value }">
          <ComboboxChip
            v-for="label in value as string[]"
            :key="label"
            :value="label"
          >
            {{ label }}
            <ComboboxChipRemove :aria-label="`Remove ${label}`">
              <XIcon aria-hidden="true" />
            </ComboboxChipRemove>
          </ComboboxChip>
        </ComboboxValue>
        <ComboboxInput placeholder="Add labels…" />
      </ComboboxChips>
    </div>
    <ComboboxContent>
      <ComboboxList>
        <ComboboxItem
          v-for="label in labels"
          v-slot="{ state }"
          :key="label"
          :value="label"
        >
          {{ label }}
          <span v-if="state.maxReached" data-slot="hint">Limit reached</span>
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

## 新建选项
当没有标签精确匹配查询，且查询满足 `min-length` 时，`ComboboxCreate` 会提供这个查询作为选项。用 `on-create` 保存它；异步操作返回一个 promise。创建本身不会改变选择：保存之后再把新项加进来并选中它。

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

```vue title="create.vue"
<script setup lang="ts">
import { CheckIcon, LoaderCircleIcon, PlusIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxContent,
  ComboboxCreate,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"

const initialLabels = [
  "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 labels = ref(initialLabels)
const value = ref<string[]>(["Bug"])

async function create(query: string) {
  await saveLabel(query)
  labels.value = [...labels.value, query]
  value.value = [...value.value, query]
}
</script>

<template>
  <Combobox v-model:value="value" multiple>
    <div data-slot="stack">
      <ComboboxLabel>Labels</ComboboxLabel>
      <ComboboxChips>
        <ComboboxValue v-slot="{ value: selected }">
          <ComboboxChip
            v-for="label in selected as string[]"
            :key="label"
            :value="label"
          >
            {{ label }}
            <ComboboxChipRemove :aria-label="`Remove ${label}`">
              <XIcon aria-hidden="true" />
            </ComboboxChipRemove>
          </ComboboxChip>
        </ComboboxValue>
        <ComboboxInput placeholder="Add or create a label…" />
      </ComboboxChips>
    </div>
    <ComboboxContent>
      <ComboboxList>
        <ComboboxItem v-for="label in labels" :key="label" :value="label">
          {{ label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
        <ComboboxCreate v-slot="{ state }" :min-length="2" :on-create="create">
          <template v-if="state.pending">
            <LoaderCircleIcon aria-hidden="true" data-slot="spinner" />
            Creating “{{ state.query }}”…
          </template>
          <template v-else>
            <PlusIcon aria-hidden="true" />
            <span data-slot="stack">
              Create “{{ state.query }}”
              <span v-if="state.error" data-slot="hint">{{
                (state.error as Error).message
              }}</span>
            </span>
          </template>
        </ComboboxCreate>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="custom-value.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"
import { useLog } from "./log"

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

const log = useLog()
const value = ref<string | null>(null)
</script>

<template>
  <Combobox
    v-model:value="value"
    allow-custom-value
    @value-change="
      (next: string | null, details: { reason: string }) =>
        log(`${next ? `“${next}”` : 'No title'} (${details.reason})`)
    "
  >
    <div data-slot="stack">
      <ComboboxLabel>Job title</ComboboxLabel>
      <ComboboxInput placeholder="Type any title…" />
    </div>
    <ComboboxContent>
      <ComboboxEmpty v-slot="{ state }">
        <template v-if="state.empty"
          >Press Enter to use “{{ state.query }}”.</template
        >
      </ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem v-for="title in titles" :key="title" :value="title">
          {{ title }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="popup.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon, SearchIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxList,
  ComboboxTrigger,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"
import { computed, ref, type ComponentPublicInstance } from "vue"

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 trigger = ref<ComponentPublicInstance | null>(null)
const button = computed(
  () => (trigger.value?.$el ?? null) as HTMLButtonElement | null
)
const query = ref("")
</script>

<template>
  <Combobox
    v-model:query="query"
    default-value="jp"
    :item-to-label="countryLabel"
    @open-change="(open: boolean) => open && (query = '')"
    @open-change-complete="(open: boolean) => !open && button?.focus()"
  >
    <ComboboxTrigger ref="trigger" aria-label="Country">
      <span>
        <ComboboxValue v-slot="{ state }">{{
          state.label || "Select a country"
        }}</ComboboxValue>
      </span>
      <ChevronDownIcon aria-hidden="true" />
    </ComboboxTrigger>
    <ComboboxContent :anchor="button">
      <div data-slot="row">
        <SearchIcon aria-hidden="true" />
        <ComboboxInput
          autofocus
          aria-label="Search countries"
          placeholder="Search…"
        />
      </div>
      <ComboboxEmpty>No countries found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="country in countries"
          :key="country.value"
          :value="country.value"
          :label="country.label"
        >
          {{ country.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

```vue title="async.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { useAsyncOptions } from "@ui-sdk/vue/async-options"

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

const { state: movies, setQuery } = useAsyncOptions(searchMovies, {
  debounce: 300,
  query: "the",
  immediate: true,
})
</script>

<template>
  <Combobox
    :items="movies.items"
    default-query="the"
    :filter="false"
    :status="movies.status"
    @query-change="(query: string) => setQuery(query)"
  >
    <div data-slot="stack">
      <ComboboxLabel>Movie</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search movies…" />
        <ComboboxTrigger aria-label="Show movies">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxStatus v-slot="{ state }">
        {{
          state.status === "error"
            ? "Couldn't load movies."
            : state.loading
              ? "Searching…"
              : `${state.count} ${state.count === 1 ? "movie" : "movies"}`
        }}
      </ComboboxStatus>
      <ComboboxEmpty v-slot="{ state }">
        <template v-if="state.empty && !state.loading"
          >No movies match “{{ state.query }}”.</template
        >
      </ComboboxEmpty>
      <ComboboxList v-slot="{ state }">
        <ComboboxItem
          v-for="item in state.items as {
            value: string
            label: string
            disabled?: boolean
          }[]"
          :key="item.value"
          :value="item.value"
          :label="item.label"
          :disabled="item.disabled"
        >
          {{ item.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

```vue title="infinite.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { useAsyncOptions } from "@ui-sdk/vue/async-options"

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

const {
  state: movies,
  setQuery,
  loadMore,
} = useAsyncOptions(searchMoviePages, { immediate: true })
</script>

<template>
  <Combobox
    :items="movies.items"
    :filter="false"
    :status="movies.status"
    @query-change="(query: string) => setQuery(query)"
    @load-more="loadMore"
  >
    <div data-slot="stack">
      <ComboboxLabel>Movie</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search movies…" />
        <ComboboxTrigger aria-label="Show movies">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty v-slot="{ state }">
        <template v-if="state.empty && !state.loading"
          >No movies found.</template
        >
      </ComboboxEmpty>
      <ComboboxList v-slot="{ state }">
        <ComboboxItem
          v-for="item in state.items as {
            value: string
            label: string
            disabled?: boolean
          }[]"
          :key="item.value"
          :value="item.value"
          :label="item.label"
          :disabled="item.disabled"
        >
          {{ item.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
      <ComboboxStatus v-slot="{ state }">
        {{
          state.loading
            ? "Loading more…"
            : movies.hasMore
              ? `${state.count} loaded`
              : `All ${state.count}`
        }}
      </ComboboxStatus>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

```vue title="virtualized.vue"
<script setup lang="ts">
import { ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"

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

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

function onHighlight(_value: unknown, { index }: { index: number }) {
  const el = scroller.value
  if (el && index >= 0) {
    el.scrollTop = scrollForRow(index, el.scrollTop, el.clientHeight, row)
  }
}

function visible(items: { value: string; label: string }[]) {
  const { start, end } = visibleRows(scrollTop.value, height, items.length, row)
  return items
    .slice(start, end)
    .map((item, offset) => ({ item, index: start + offset }))
}
</script>

<template>
  <Combobox :items="manyItems" @highlight="onHighlight">
    <div data-slot="stack">
      <ComboboxLabel>Item</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search 10,000 items…" />
        <ComboboxTrigger aria-label="Show items">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No items found.</ComboboxEmpty>
      <div
        ref="scroller"
        @scroll="scrollTop = ($event.currentTarget as HTMLDivElement).scrollTop"
      >
        <ComboboxList v-slot="{ state }">
          <div :style="{ height: `${state.items.length * row}px` }">
            <ComboboxItem
              v-for="{ item, index } in visible(
                state.items as { value: string; label: string }[]
              )"
              :key="item.value"
              :value="item.value"
              :label="item.label"
              :index="index"
              :style="{ top: `${index * row}px`, height: `${row}px` }"
            >
              {{ item.label }}
            </ComboboxItem>
          </div>
        </ComboboxList>
      </div>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

只控制你需要的值；Vue 也支持 `v-model:value`、`v-model:query` 和 `v-model:open`。变更事件会带上原因和 `details.cancel()`，用来拒绝这次请求。选择一个项会把它的标签写进输入框，被取消的选择保留当前值。未选择就关闭会恢复选中值的标签，除非允许自定义值。[状态与事件](/docs/vue/state-and-events)介绍了绑定模式。

输入法正在组字时，比如日语转换或死键的重音，列表保持当前的过滤，且 `@query-change` 会收到 `details.composing: true`。等它变为 `false` 后再搜索服务器；异步选项会自己等待这一点。

焦点离开输入框会以原因 `focus-out` 关闭浮层，即使焦点是代码移动的，比如一个获取焦点的通知。要让浮层保持打开，在 `@open-change` 里取消这次关闭。

```vue title="controlled.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { ref } from "vue"
import { useLog } 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 value = ref<string | null>("fr")
const query = ref("France")
const open = ref(false)
const log = useLog()
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="value = 'jp'">Choose Japan</button>
      <button type="button" @click="open = true">Open</button>
    </div>
    <Combobox
      v-model:value="value"
      v-model:query="query"
      v-model:open="open"
      :item-to-label="countryLabel"
      debug
      @value-change="
        (next: unknown, details: { reason: string }) =>
          log(`value: ${next} (${details.reason})`)
      "
      @query-change="
        (next: string, details: { reason: string }) =>
          log(`query: “${next}” (${details.reason})`)
      "
      @open-change="
        (next: boolean, details: { reason: string }) =>
          log(`open: ${next} (${details.reason})`)
      "
    >
      <div data-slot="stack">
        <ComboboxLabel>Country</ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Search countries…" />
          <ComboboxTrigger aria-label="Show countries">
            <ChevronDownIcon />
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxEmpty>No countries found.</ComboboxEmpty>
        <ComboboxList>
          <ComboboxItem
            v-for="country in countries"
            :key="country.value"
            :value="country.value"
            :label="country.label"
          >
            {{ country.label }}
            <ComboboxItemIndicator>
              <CheckIcon />
            </ComboboxItemIndicator>
          </ComboboxItem>
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  </div>
</template>
```

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

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

```vue title="controller.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
  createComboboxController,
} from "@ui-sdk/vue/combobox"
import { useLog } 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 country = createComboboxController<string>()
const log = useLog()

async function openAndWait() {
  const { reason } = await country.open()
  log(`Closed by ${reason}, with ${country.getValue() ?? "nothing"}`)
}

function search() {
  country.focus()
  country.setQuery("sw")
  country.open()
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="openAndWait">Open and Wait</button>
      <button type="button" @click="search">Search “sw”</button>
      <button type="button" @click="country.setValue('de')">
        Choose Germany
      </button>
      <button type="button" @click="country.clear()">Clear</button>
    </div>
    <Combobox :controller="country" :item-to-label="countryLabel">
      <div data-slot="stack">
        <ComboboxLabel>Country</ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Search countries…" />
          <ComboboxTrigger aria-label="Show countries">
            <ChevronDownIcon />
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxEmpty>No countries found.</ComboboxEmpty>
        <ComboboxList>
          <ComboboxItem
            v-for="item in countries"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
            {{ item.label }}
            <ComboboxItemIndicator>
              <CheckIcon />
            </ComboboxItemIndicator>
          </ComboboxItem>
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  </div>
</template>
```

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

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

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

```vue title="positioning.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxList,
} from "@ui-sdk/vue/combobox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/vue/select"
import { ref } from "vue"

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" },
]
type Side = "top" | "right" | "bottom" | "left"
type Align = "start" | "center" | "end"

const side = ref<Side>("bottom")
const align = ref<Align>("start")
const box = ref<HTMLDivElement | null>(null)
const anchored = ref(false)
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <Select
        :items="sides"
        :value="side"
        @value-change="(next) => next && (side = next as Side)"
      >
        <SelectLabel>Side</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in sides"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
      <Select
        :items="aligns"
        :value="align"
        @value-change="(next) => next && (align = next as Align)"
      >
        <SelectLabel>Align</SelectLabel>
        <SelectTrigger>
          <SelectValue />
          <ChevronDownIcon />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="option in aligns"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
            <SelectItemIndicator>
              <CheckIcon />
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
      <label data-slot="label">
        <Checkbox
          :checked="anchored"
          @checked-change="(next) => (anchored = next === true)"
        >
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        Anchor to the box
      </label>
    </div>
    <div ref="box" data-slot="card">
      <Combobox>
        <ComboboxInput aria-label="Framework" placeholder="Framework" />
        <ComboboxContent
          :side="side"
          :align="align"
          :side-offset="10"
          :align-offset="0"
          :collision-padding="16"
          :anchor="anchored ? box : null"
        >
          <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
          <ComboboxList>
            <ComboboxItem
              v-for="framework in frameworks"
              :key="framework.value"
              :value="framework.value"
              :label="framework.label"
            >
              {{ framework.label }}
              <ComboboxItemIndicator>
                <CheckIcon />
              </ComboboxItemIndicator>
            </ComboboxItem>
          </ComboboxList>
        </ComboboxContent>
      </Combobox>
    </div>
  </div>
</template>
```

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

## 动画
内容打开期间带有 `data-starting-style`，关闭期间带有 `data-ending-style`。从这些状态做过渡，浮层会保持挂载直到退场结束。`@open-change-complete` 在打开或关闭结束后运行，项指示器上的 `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;
  }
}
```

```vue title="animation.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"
import { useLog } 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 log = useLog()
</script>

<template>
  <Combobox
    @open-change-complete="
      (open: boolean) => log(open ? 'Finished opening' : 'Finished closing')
    "
  >
    <div data-slot="stack">
      <ComboboxLabel>Framework</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Select a framework" />
        <ComboboxTrigger aria-label="Show frameworks">
          <ChevronDownIcon />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="framework in frameworks"
          :key="framework.value"
          :value="framework.value"
          :label="framework.label"
        >
          {{ framework.label }}
          <ComboboxItemIndicator keep-mounted>
            <CheckIcon />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

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

```vue title="presentation.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox presentation="sheet">
    <div data-slot="stack">
      <ComboboxLabel>Framework</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Select a framework" />
        <ComboboxTrigger aria-label="Show frameworks">
          <ChevronDownIcon aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="framework in frameworks"
          :key="framework.value"
          :value="framework.value"
          :label="framework.label"
        >
          {{ framework.label }}
          <ComboboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

服务器 HTML 包含用于选择的隐藏输入框，所以它们的值可以在水合之前提交。[表单](/docs/vue/forms)介绍了共用的集成方式。

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

```vue title="form.vue"
<script setup lang="ts">
import { CheckIcon, ChevronDownIcon, XIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxChip,
  ComboboxChipRemove,
  ComboboxChips,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxList,
  ComboboxTrigger,
  ComboboxValue,
} from "@ui-sdk/vue/combobox"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/vue/field"
import { useLog } 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"]

const log = useLog()

function submit(event: Event) {
  const entries = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(`Submitted ${entries.join("&")}`)
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="submit">
    <Field name="country">
      <FieldLabel>Country</FieldLabel>
      <Combobox required :item-to-label="countryLabel">
        <div data-slot="row">
          <ComboboxInput placeholder="Search countries…" />
          <ComboboxTrigger aria-label="Show countries">
            <ChevronDownIcon aria-hidden="true" />
          </ComboboxTrigger>
        </div>
        <ComboboxContent>
          <ComboboxEmpty>No countries found.</ComboboxEmpty>
          <ComboboxList>
            <ComboboxItem
              v-for="country in countries"
              :key="country.value"
              :value="country.value"
              :label="country.label"
            >
              {{ country.label }}
              <ComboboxItemIndicator>
                <CheckIcon aria-hidden="true" />
              </ComboboxItemIndicator>
            </ComboboxItem>
          </ComboboxList>
        </ComboboxContent>
      </Combobox>
      <FieldDescription>Where we ship your order.</FieldDescription>
      <div>
        <FieldError match="valueMissing">Choose a country.</FieldError>
      </div>
    </Field>
    <Field name="interests">
      <FieldLabel>Interests</FieldLabel>
      <Combobox multiple :default-value="['Design']">
        <ComboboxChips>
          <ComboboxValue v-slot="{ value }">
            <ComboboxChip
              v-for="interest in value as string[]"
              :key="interest"
              :value="interest"
            >
              {{ interest }}
              <ComboboxChipRemove :aria-label="`Remove ${interest}`">
                <XIcon aria-hidden="true" />
              </ComboboxChipRemove>
            </ComboboxChip>
          </ComboboxValue>
          <ComboboxInput placeholder="Add interests…" />
        </ComboboxChips>
        <ComboboxContent>
          <ComboboxList>
            <ComboboxItem
              v-for="interest in interests"
              :key="interest"
              :value="interest"
            >
              {{ interest }}
              <ComboboxItemIndicator>
                <CheckIcon aria-hidden="true" />
              </ComboboxItemIndicator>
            </ComboboxItem>
          </ComboboxList>
        </ComboboxContent>
      </Combobox>
    </Field>
    <div data-slot="row">
      <button type="submit">Submit</button>
      <button type="reset">Reset</button>
    </div>
  </form>
</template>
```

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

## 自定义渲染
每个部件都接受一个 `render` 槽位，它接收要绑定的 props 和部件的状态，默认槽位也会收到状态。每个部件的状态列在[下面](https://ui-sdk.cn/docs/vue/components/combobox#state)。

```vue title="custom-rendering.vue"
<script setup lang="ts">
import {
  CheckIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  SearchIcon,
} from "@lucide/vue"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxLabel,
  ComboboxList,
  ComboboxTrigger,
} from "@ui-sdk/vue/combobox"

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

<template>
  <Combobox>
    <div data-slot="stack">
      <ComboboxLabel>Assignee</ComboboxLabel>
      <div data-slot="row">
        <ComboboxInput placeholder="Search people…">
          <template #render="{ props }">
            <div data-slot="row">
              <SearchIcon aria-hidden="true" />
              <input v-bind="props" />
            </div>
          </template>
        </ComboboxInput>
        <ComboboxTrigger v-slot="{ state }" aria-label="Show people">
          <ChevronUpIcon v-if="state.open" aria-hidden="true" />
          <ChevronDownIcon v-else aria-hidden="true" />
        </ComboboxTrigger>
      </div>
    </div>
    <ComboboxContent>
      <ComboboxEmpty>No one by that name.</ComboboxEmpty>
      <ComboboxList>
        <ComboboxItem
          v-for="user in users"
          :key="user.id"
          v-slot="{ state }"
          :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>
          <CheckIcon v-if="state.selected" aria-hidden="true" />
          <kbd v-else-if="state.highlighted" data-slot="kbd">Enter</kbd>
        </ComboboxItem>
      </ComboboxList>
    </ComboboxContent>
  </Combobox>
</template>
```

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

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

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

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

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

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

## 数据属性
### ComboboxLabel
`[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.

### ComboboxInput
`[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.

### ComboboxTrigger
`[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.

### ComboboxClear
`[data-slot="combobox-clear"]`

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

### ComboboxChips
`[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.

### ComboboxContent
`[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.

### ComboboxItem
`[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.

### ComboboxItemText
`[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.

### ComboboxItemIndicator
`[data-slot="combobox-item-indicator"]`

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

### ComboboxEmpty
`[data-slot="combobox-empty"]`

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

### ComboboxStatus
`[data-slot="combobox-status"]`

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

### ComboboxArrow
`[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`.

### ComboboxItemIcon
`[data-slot="combobox-item-icon"]`

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

### ComboboxChip
`[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.

### ComboboxChipRemove
`[data-slot="combobox-chip-remove"]`

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

### ComboboxSelectAll
`[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.

### ComboboxCreate
`[data-slot="combobox-create"]`

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

## API 参考
属性和下面相同，回调是事件。

### 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.
- `@query-change` (`((query: string, details: TextChangeDetails<ComboboxQueryChangeReason>) => void)`): 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.
- `@open-change` (`((open: boolean, details: ChangeDetails<ComboboxOpenChangeReason>) => void)`): Runs when the list wants to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `@open-change-complete` (`((open: boolean) => void)`): 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` (`((value: T | null, details: ListHighlightDetails) => void)`): Runs when the highlight moves, with the item's index among the visible items, so a virtualized list can scroll to it.
- `@load-more` (`(() => void)`): 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 `@dismiss-attempt`.
- `@dismiss-attempt` (`function`): 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.
- `@value-change` (`union`): 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
输入框可见的标签。渲染一个 `label`。

### ComboboxInput
过滤列表并显示所选标签的文本字段。渲染一个 `input`。

### ComboboxTrigger
打开和关闭列表。渲染一个 `button`，当输入框在它旁边时留在 Tab 顺序之外。

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

### ComboboxChips
容纳多选时的标签片和输入框。渲染一个 `div`。

### ComboboxValue
- `maxLabels?` (`number`): With `multiple`, how many labels the `label` in its state shows before the rest are counted, as in "France, Chile and 2 more", joined the way the page's language joins lists, or in English with the default `getMoreLabel`.
- `getMoreLabel?` (`((count: number) => string)`): The words for the labels past `maxLabels`.

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

### ComboboxChipRemove
移除它所在标签片的值。渲染一个 `button`。接受与 `ComboboxChip` 相同的 props。

### ComboboxChipsOverflow
为它周围的标签片开启折叠，并显示隐藏了多少个。渲染一个 `span`。

### 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
从浮层指向它的锚点，跟随碰撞处理之后选定的方向。渲染一个 `div`。

### ComboboxStatus
播报加载中、错误和结果数量。渲染一个带 status 角色的 `div`。

### ComboboxEmpty
在没有选项匹配时显示。渲染一个 `div`。

### ComboboxList
容纳选项。渲染一个带 listbox 角色的 `div`。

### ComboboxSelectAll
切换它所在分组内或分组外所有匹配且启用的选项。渲染一个带 option 角色的 `div`。

### ComboboxGroup
把一个分组下的选项归到一起。渲染一个带 group 角色的 `div`。

### ComboboxGroupLabel
为它的分组命名。渲染一个 `div`。

### 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
显示它所在项的名称，并标记匹配查询的部分。渲染一个 `span`。

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

### ComboboxSeparator
分隔选项或分组。渲染一个带 separator 角色的 `div`。

### ComboboxCreate
- `@create` (`((query: string) => unknown)`): 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.

### 异步选项
[异步选项](/docs/vue/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.

### 原因
`details.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 时，`@dismiss-attempt` 报告这些被拒绝的关闭：

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

### 控制器
用 `createComboboxController<Value, Multiple>()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受一个可选的 `{ 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.

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

| 绑定                    | 所属             | 收到                                                                     |
| ----------------------- | ---------------- | ------------------------------------------------------------------------ |
| `v-model:value`         | `Combobox`       | 选中的值                                                                 |
| `v-model:query`         | `Combobox`       | 输入框的文字                                                             |
| `v-model:open`          | `Combobox`       | 列表是否打开                                                             |
| `@value-change`         | `Combobox`       | `(value, details)`：新值，以及[原因](https://ui-sdk.cn/docs/vue/components/combobox#reasons)                           |
| `@query-change`         | `Combobox`       | `(query, details)`：新文字、[原因](https://ui-sdk.cn/docs/vue/components/combobox#reasons)，以及它是否仍在 `composing` |
| `@open-change`          | `Combobox`       | `(open, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/vue/components/combobox#reasons)                          |
| `@open-change-complete` | `Combobox`       | `(open)`，在动画之后                                                     |
| `@highlight`            | `Combobox`       | `(value, { index, event })`：高亮的项和它所在的行                        |
| `@load-more`            | `Combobox`       | 到达最后一个项时                                                         |
| `@dismiss-attempt`      | `Combobox`       | `({ reason, event })`，当一次关闭被拒绝时                                |
| `:on-create`            | `ComboboxCreate` | `(query)`：文字。返回一个 Promise 把它标记为待处理                       |

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