# Select

选择浮层列表中的一个或多个值。

当人们需要从一组选项中做选择时，就使用 Select。它负责打开列表、键盘导航、选择，以及随表单提交的值。你负责提供部件和样式。

<ComponentExample
  name="select/demo"
  inspect
  caption="打开 Role 并选择 Editor。列表关闭，触发器显示你的选择。"
/>

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

导入 Select 会在浏览器中注册它的自定义元素（custom elements）。这个导入在服务端是安全的。

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

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

```text
ui-select
├── ui-select-label
├── ui-select-trigger
│   └── button
│       └── ui-select-value
└── ui-select-content
    ├── ui-select-item
    └── ui-select-item
```

从标签、触发器和选项列表开始。`ui-select-value` 在触发器里显示选中选项的标签。`ui-select-label` 为触发器命名；在 [Field](/docs/web-components/components/field) 里，改用它的 `ui-field-label`，示例就是这样做的。

## 用法
导入元素并把它们组合起来：

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

<ui-select placeholder="Select a role">
  <ui-select-label>Role</ui-select-label>
  <ui-select-trigger>
    <button>
      <ui-select-value></ui-select-value>
    </button>
  </ui-select-trigger>
  <ui-select-content>
    <ui-select-item value="viewer">Viewer</ui-select-item>
    <ui-select-item value="editor">Editor</ui-select-item>
  </ui-select-content>
</ui-select>
```

## 以数据形式提供的选项
当选项来自数据时，把数组传给 `items`。字符串既是值也是标签。两者不同时，使用对象：

```ts
const select = document.querySelector("ui-select")!

select.items = ["Free", "Pro"]
select.items = [{ value: "pro", label: "Pro plan" }]
```

这些是选项示例；补上前面展示的标签和触发器。`items` 还可以包含分组和分隔符，用 `ListData` 检查：

```ts
import type { ListData } from "@ui-sdk/web/select"

const plans: ListData = [
  { value: "free", label: "Free" },
  { type: "separator" },
  { type: "group", label: "Contact sales", items: ["Enterprise"] },
]
```

Select 可以直接渲染这份数据中的选项本身。要为它们设置样式，就在 `ui-select` 上设置 `items`，并在 `ui-select-content` 里写 `ui-select-item` 元素，示例就是这样做的。像 `items` 这样的 property 要从 JavaScript 设置；属性只能保存文本。把数据放在根元素上，还能让标签在列表打开之前就可用，写出来的选项也会在服务端渲染。

```ts title="data.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/select"
import type { ListData } from "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"

const plans = [
  { value: "free", label: "Free" },
  { value: "pro", label: "Pro" },
  { value: "team", label: "Team" },
]

const sales = [
  { value: "enterprise", label: "Enterprise" },
  { value: "education", label: "Education", disabled: true },
]

const items: ListData = [
  ...plans,
  { type: "separator" },
  { type: "group", label: "Contact sales", items: sales },
]

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Plan</ui-field-label>
      <ui-select default-value="pro">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${plans.map(item).join("")}
          <ui-select-separator></ui-select-separator>
          <ui-select-group>
            <ui-select-group-label>Contact sales</ui-select-group-label>
            ${sales.map(item).join("")}
          </ui-select-group>
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  root.querySelector("ui-select")!.items = items
}

export { mount }
```

打开 Plan 查看选项、分隔符和 Contact sales 分组。Education 已禁用；选择 Enterprise 来更新值。

列表打开期间，选项可以变化。导航跟随新的顺序；对应的选项还在时，它的选中和高亮状态保持不变。移除高亮的选项会清除高亮。[列表与菜单](/docs/web-components/lists-and-menus)介绍了共享的数据结构。

## 分组
把相关的选项放进 `ui-select-group`，用 `ui-select-group-label` 为每个分组命名。`ui-select-separator` 添加一条视觉分隔，本身不会成为选项。

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

const fonts = [
  {
    label: "Sans serif",
    items: [
      { value: "inter", label: "Inter" },
      { value: "geist", label: "Geist" },
    ],
  },
  {
    label: "Serif",
    items: [
      { value: "source-serif", label: "Source Serif" },
      { value: "lora", label: "Lora" },
    ],
  },
  {
    label: "Monospace",
    items: [
      { value: "geist-mono", label: "Geist Mono" },
      { value: "jetbrains-mono", label: "JetBrains Mono" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Font</ui-field-label>
      <ui-select placeholder="Select a font">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${fonts
            .map(
              (group, index) => `
                ${index > 0 ? "<ui-select-separator></ui-select-separator>" : ""}
                <ui-select-group>
                  <ui-select-group-label>${group.label}</ui-select-group-label>
                  ${group.items
                    .map(
                      (item) => `
                        <ui-select-item value="${item.value}">
                          ${item.label}
                          <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                        </ui-select-item>
                      `
                    )
                    .join("")}
                </ui-select-group>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

打开 Font，从 Sans serif、Serif 或 Monospace 中选择。每个分组都有屏幕阅读器会播报的标签。

## 图标
`ui-select-item-icon` 让图标与选项的文本分开，因此不影响它的无障碍名称、键入查找（typeahead）或搜索。把 `ui-select-value-icon` 加到触发器上，选中选项的图标也会显示在那里。

```html
<ui-select-trigger>
  <button>
    <ui-select-value-icon></ui-select-value-icon>
    <ui-select-value></ui-select-value>
  </button>
</ui-select-trigger>
```

完整示例用 `mirror` 标记方向性图标，让它们在从右到左（RTL）的布局中翻转。只包含图标的选项仍然需要 `aria-label`。

```ts title="icons.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/select"
import {
  Check,
  ChevronDown,
  createElement,
  TextAlignCenter,
  TextAlignEnd,
  TextAlignStart,
} from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Text alignment</ui-field-label>
      <ui-select default-value="start">
        <ui-select-trigger>
          <button>
            <ui-select-value-icon></ui-select-value-icon>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          <ui-select-item value="start">
            <ui-select-item-icon mirror>${createElement(TextAlignStart, { "aria-hidden": "true" }).outerHTML}</ui-select-item-icon>
            Start
            <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
          </ui-select-item>
          <ui-select-item value="center">
            <ui-select-item-icon>${createElement(TextAlignCenter, { "aria-hidden": "true" }).outerHTML}</ui-select-item-icon>
            Center
            <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
          </ui-select-item>
          <ui-select-item value="end">
            <ui-select-item-icon mirror>${createElement(TextAlignEnd, { "aria-hidden": "true" }).outerHTML}</ui-select-item-icon>
            End
            <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
          </ui-select-item>
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

选择 Center 或 End。触发器里的标签和图标都会更新，与选中的选项一致。

## 键入查找
触发器获得焦点且列表关闭时，输入内容会选择下一个匹配的选项，而不打开列表。列表打开时，输入会移动高亮；Enter 选择高亮的选项。

当选项内容包含不应参与匹配的额外文本时，设置它的 `label`。这里国家名称参与键入匹配，电话区号不参与。

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

const countries = [
  { value: "ar", label: "Argentina", code: "+54" },
  { value: "au", label: "Australia", code: "+61" },
  { value: "at", label: "Austria", code: "+43" },
  { value: "be", label: "Belgium", code: "+32" },
  { value: "br", label: "Brazil", code: "+55" },
  { value: "ca", label: "Canada", code: "+1" },
  { value: "dk", label: "Denmark", code: "+45" },
  { value: "fr", label: "France", code: "+33" },
  { value: "de", label: "Germany", code: "+49" },
  { value: "gr", label: "Greece", code: "+30" },
  { value: "ie", label: "Ireland", code: "+353" },
  { value: "jp", label: "Japan", code: "+81" },
  { value: "es", label: "Spain", code: "+34" },
  { value: "se", label: "Sweden", code: "+46" },
  { value: "ch", label: "Switzerland", code: "+41" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Country</ui-field-label>
      <ui-select default-value="fr">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${countries
            .map(
              (country) => `
                <ui-select-item value="${country.value}" label="${country.label}">
                  ${country.label}
                  <span data-slot="hint">${country.code}</span>
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

聚焦 Country 并输入“sw”，在不打开列表的情况下选择 Sweden。打开列表并输入“g”高亮 Germany，然后按 Enter。

## 禁用
禁用的 Select 无法聚焦或更改，也不会提交值。只读的 Select 保持可聚焦并提交它的值，但无法更改。键盘导航会跳过禁用的选项，它们也无法被选中。

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

const countries = [
  { value: "ca", label: "Canada" },
  { value: "dk", label: "Denmark" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "jp", label: "Japan" },
  { value: "es", label: "Spain" },
]

const fields = [
  { label: "Billing country", disabled: true },
  { label: "Shipping from", readOnly: true },
  { label: "Shipping to" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${fields
        .map(
          (field) => `
            <ui-field>
              <ui-field-label>${field.label}</ui-field-label>
              <ui-select
                ${field.disabled || field.readOnly ? 'default-value="fr"' : ""}
                placeholder="Select a country"
                ${field.disabled ? "disabled" : ""}
                ${field.readOnly ? "read-only" : ""}
              >
                <ui-select-trigger>
                  <button>
                    <ui-select-value></ui-select-value>
                    ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
                  </button>
                </ui-select-trigger>
                <ui-select-content>
                  ${countries
                    .map(
                      (country) => `
                        <ui-select-item value="${country.value}"${country.value === "dk" ? " disabled" : ""}>
                          ${country.label}
                          <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                        </ui-select-item>
                      `
                    )
                    .join("")}
                </ui-select-content>
              </ui-select>
            </ui-field>
          `
        )
        .join("")}
    </div>
  `
}

export { mount }
```

Billing country 已禁用，Shipping from 是只读的。打开 Shipping to 并按方向键：高亮会跳过无法选择的 Denmark。

## 清除按钮
没有选中任何内容时，`placeholder` 会显示。添加 `ui-select-clear` 可以回到这个状态。清除会把单值设为 `null`，把多值设为空数组，并把焦点返回触发器。

把清除按钮放在触发器旁边：按钮不能包含另一个按钮。`keep-mounted` 让它在没有内容可清除时仍留在 DOM 中。

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

const people = [
  { value: "hollis", label: "Hollis Grant" },
  { value: "ines", label: "Inès Moreau" },
  { value: "kofi", label: "Kofi Mensah" },
  { value: "wren", label: "Wren Takahashi" },
  { value: "tomasz", label: "Tomasz Wójcik" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Assignee</ui-field-label>
      <ui-select default-value="ines" placeholder="Unassigned">
        <div data-slot="row">
          <ui-select-trigger>
            <button>
              <ui-select-value></ui-select-value>
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-select-trigger>
          <ui-select-clear>
            <button aria-label="Clear assignee">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button>
          </ui-select-clear>
        </div>
        <ui-select-content>
          ${people
            .map(
              (person) => `
                <ui-select-item value="${person.value}">
                  ${person.label}
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
    log(
      root,
      `value: ${JSON.stringify(event.detail.value)} (${event.detail.reason})`
    )
  })
}

export { mount }
```

按清除按钮。触发器显示 Unassigned，焦点回到它上面，控制台记录 null。选择一个成员，按钮就会回来。

## 多选
设置 `multiple` 可以选择多个值。值会变成数组，选择某个选项会切换它，同时保持列表打开。

```html
<ui-select multiple default-value="en, ja"></ui-select>
```

监听 `valuechange`，更新 `ui-select-value` 的一个子元素来概括一长串选择，示例就是这样做的。

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

const languages = [
  { value: "en", label: "English" },
  { value: "fr", label: "French" },
  { value: "de", label: "German" },
  { value: "ja", label: "Japanese" },
  { value: "pt", label: "Portuguese" },
  { value: "es", label: "Spanish" },
]

function summary(value: string[]) {
  const labels = value.map(
    (key) => languages.find((language) => language.value === key)?.label ?? key
  )
  return labels.length === 0
    ? "Select languages"
    : labels.length > 2
      ? `${labels[0]} and ${labels.length - 1} more`
      : labels.join(", ")
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Languages</ui-field-label>
      <ui-select multiple default-value="en, ja" placeholder="Select languages">
        <ui-select-trigger>
          <button>
            <ui-select-value>${summary(["en", "ja"])}</ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${languages
            .map(
              (language) => `
                <ui-select-item value="${language.value}">
                  ${language.label}
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  const text = root.querySelector("ui-select-value")!
  root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
    const value = event.detail.value as string[]
    text.textContent = summary(value)
    log(root, `value: ${JSON.stringify(value)}`)
  })
}

export { mount }
```

选择多种语言，然后再次选择一个来移除它。列表保持打开，控制台记录该数组。

## 全选
添加 `ui-select-select-all` 可以选择或清除每个已启用的选项。只有部分选中时，它显示混合状态。放在 `ui-select-group` 内部时，它只作用于那个分组。

`<ui-select-value max-labels="2">` 最多显示两个标签，并概括其余的值。`getMoreLabel` 让你自己写这段概括。

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

const regions = [
  { value: "us-east", label: "US East" },
  { value: "us-west", label: "US West" },
  { value: "europe", label: "Europe" },
  { value: "asia-pacific", label: "Asia Pacific" },
  { value: "south-america", label: "South America" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Regions</ui-field-label>
      <ui-select multiple default-value="us-east, europe, asia-pacific" placeholder="Select regions">
        <ui-select-trigger>
          <button>
            <ui-select-value max-labels="2"></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          <ui-select-select-all>
            Select all
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
            ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
          </ui-select-select-all>
          <ui-select-separator></ui-select-separator>
          ${regions
            .map(
              (region) => `
                <ui-select-item value="${region.value}">
                  ${region.label}
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  root.querySelector("ui-select-value")!.getMoreLabel = (count) =>
    `${count} more`
}

export { mount }
```

打开 Regions 并按 Select all。再按一次清除选择，然后选择一个地区，查看混合状态。

## 带分组的搜索
在 `ui-select-content` 里添加 `ui-select-input` 来过滤选项。把选项放进 `ui-select-list`，这样搜索字段就留在可滚动列表之外。没有匹配项时显示 `ui-select-empty`。

```html
<ui-select-content>
  <ui-select-input><input aria-label="Search countries" /></ui-select-input>
  <ui-select-empty>No countries found.</ui-select-empty>
  <ui-select-list><!-- Items go here. --></ui-select-list>
</ui-select-content>
```

没有匹配选项的分组会自动隐藏。`ui-select-item-text` 可以高亮匹配的文本；这个示例给它创建的 `<mark>` 元素设置样式，把匹配项加粗。关闭浮层会清除搜索。

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

const regions = [
  {
    label: "Americas",
    items: [
      { value: "br", label: "Brazil" },
      { value: "ca", label: "Canada" },
      { value: "mx", label: "Mexico" },
    ],
  },
  {
    label: "Europe",
    items: [
      { value: "fr", label: "France" },
      { value: "de", label: "Germany" },
      { value: "es", label: "Spain" },
    ],
  },
  {
    label: "Asia Pacific",
    items: [
      { value: "au", label: "Australia" },
      { value: "jp", label: "Japan" },
      { value: "sg", label: "Singapore" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Country</ui-field-label>
      <ui-select placeholder="Select a country">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          <ui-select-input>
            <input aria-label="Search countries" placeholder="Search countries…" />
          </ui-select-input>
          <ui-select-empty>No countries found.</ui-select-empty>
          <ui-select-list>
            ${regions
              .map(
                (group) => `
                  <ui-select-group>
                    <ui-select-group-label>${group.label}</ui-select-group-label>
                    ${group.items
                      .map(
                        (item) => `
                          <ui-select-item value="${item.value}" label="${item.label}">
                            <ui-select-item-text>${item.label}</ui-select-item-text>
                            <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                          </ui-select-item>
                        `
                      )
                      .join("")}
                  </ui-select-group>
                `
              )
              .join("")}
          </ui-select-list>
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

打开 Country 并输入“ja”。只剩 Asia Pacific 和 Japan。试试“zz”查看空状态消息，然后清除搜索以显示所有国家。

方向键移动高亮，焦点留在搜索字段里。在触摸屏的屏幕阅读器上，焦点会改为移入选项。要在搜索之前显示最近的选择，把 `emptyItems` 和 `items` 一起传入。[列表与菜单](https://ui-sdk.cn/docs/web-components/lists-and-menus#search-and-load-items)介绍了选项过滤。

## 异步搜索
服务器已经在过滤选项时，使用 `filter="false"`。监听 `querychange` 来更新你的加载函数，并设置 Select 的 `items` 和 `status` property。

这个示例用[异步选项](/docs/web-components/utilities/async-options)替换过期的请求，并通过 `loadmore` 加载下一页。`ui-select-status` 显示加载状态和结果数量。没有状态部件时，Select 通过页面的实时区域（live region）播报结果数量。

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

const countryList = [
  { 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: "cn", label: "China" },
  { value: "dk", label: "Denmark" },
  { value: "fi", label: "Finland" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "gr", label: "Greece" },
  { value: "in", label: "India" },
  { value: "ie", label: "Ireland" },
  { value: "it", label: "Italy" },
  { value: "jp", label: "Japan" },
  { value: "mx", label: "Mexico" },
  { value: "nl", label: "Netherlands" },
  { value: "no", label: "Norway" },
  { value: "pt", label: "Portugal" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
  { value: "ch", label: "Switzerland" },
]

function searchCountries(
  query: string,
  { signal, page }: { signal: AbortSignal; page: number }
) {
  return new Promise<{ items: typeof countryList; hasMore: boolean }>(
    (resolve, reject) => {
      const timer = setTimeout(() => {
        const needle = query.trim().toLowerCase()
        const found = countryList.filter((country) =>
          country.label.toLowerCase().includes(needle)
        )
        resolve({
          items: found.slice(page * 6, page * 6 + 6),
          hasMore: found.length > page * 6 + 6,
        })
      }, 400)
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        reject(signal.reason)
      })
    }
  )
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Country</ui-field-label>
      <ui-select filter="false" placeholder="Select a country">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          <ui-select-input>
            <input aria-label="Search countries" placeholder="Search countries…" />
          </ui-select-input>
          <ui-select-empty></ui-select-empty>
          <ui-select-list></ui-select-list>
          <ui-select-status></ui-select-status>
        </ui-select-content>
        <template>
          <ui-select-item>
            <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
          </ui-select-item>
        </template>
      </ui-select>
    </ui-field>
  `
  const select = root.querySelector("ui-select")!
  const empty = root.querySelector("ui-select-empty")!
  const status = root.querySelector("ui-select-status")!
  const results = createAsyncOptions(searchCountries, { immediate: true })
  let query = ""
  const update = () => {
    const { items, status: loading } = results.getState()
    select.items = items
    select.setAttribute("status", loading)
    empty.textContent =
      loading === "loading" ? "" : `No countries match “${query}”.`
    status.textContent =
      loading === "loading"
        ? "Loading…"
        : loading === "error"
          ? "Couldn't load countries."
          : `${items.length} shown`
  }
  results.subscribe(update)
  update()
  select.addEventListener("querychange", (event) => {
    query = event.detail.value
    results.setQuery(query)
    update()
  })
  select.addEventListener("loadmore", () => results.loadMore())
}

export { mount }
```

打开 Country 并输入“an”。结果会在短暂延迟后到达。清除搜索，移动或滚动到最后一个结果，加载下一页。

## 对象值
值可以是对象。把它设为 `ui-select-item` 的 `value` property，因为属性只能保存文本，然后告诉 Select 如何识别它、显示它，以及如何与另一份副本比较：

| property             | 作用                                                 |
| -------------------- | ---------------------------------------------------- |
| `itemToValue`        | 返回用于标识和提交该值的字符串。                     |
| `itemToLabel`        | 返回触发器中显示的文本。                             |
| `isItemEqualToValue` | 把选项与选中值匹配，即使后者可能是另一份不同的对象。 |

```ts title="object-values.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/select"
import { Check, ChevronDown, createElement } from "lucide"
import { log } from "./log"

type Member = { id: number; name: string; email: string }

const members: Member[] = [
  { id: 1, name: "Hollis Grant", email: "hollis@example.com" },
  { id: 2, name: "Inès Moreau", email: "ines@example.com" },
  { id: 3, name: "Kofi Mensah", email: "kofi@example.com" },
  { id: 4, name: "Wren Takahashi", email: "wren@example.com" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Assignee</ui-field-label>
      <ui-select name="assignee" placeholder="Unassigned">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${members
            .map(
              (member) => `
                <ui-select-item>
                  <span data-slot="stack">
                    ${member.name}
                    <span data-slot="hint">${member.email}</span>
                  </span>
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  const select = root.querySelector("ui-select")!
  select.itemToValue = (member) => String((member as Member).id)
  select.itemToLabel = (member) => (member as Member).name
  select.isItemEqualToValue = (item, value) =>
    (item as Member).id === (value as Member).id
  root
    .querySelectorAll("ui-select-item")
    .forEach((item, index) => (item.value = members[index]))
  select.value = { ...members[1] }
  select.addEventListener("valuechange", (event) => {
    const member = event.detail.value as Member | null
    log(root, `Submits assignee=${member ? member.id : ""}`)
  })
}

export { mount }
```

Inès 一开始就是选中状态，即使初始值是她那份选项的副本。选择另一个负责人；控制台记录表单提交的 ID。

## 虚拟化
对于长列表，通过 `items` 传入每个选项，只渲染可见的行。`highlight` 事件告诉虚拟化器把哪一行带入视图。给每个渲染的选项传入它在完整列表中的 `index`，无障碍属性才能正确描述它的位置。

这个示例自带几个小的行窗口辅助函数。你也可以把同样的 props 用在你选择的虚拟化器上。

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

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

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

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

const row = 32
const height = 288

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Item</ui-field-label>
      <ui-select placeholder="Select an item">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          <div style="height: ${height}px">
            <ui-select-list>
              <div style="height: ${manyItems.length * row}px"></div>
            </ui-select-list>
          </div>
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
  const select = root.querySelector("ui-select")!
  const scroller = root.querySelector<HTMLElement>("ui-select-content > div")!
  const rows = root.querySelector<HTMLElement>("ui-select-list > div")!

  const rendered = new Map<number, Element>()
  const render = () => {
    const { start, end } = visibleRows(
      scroller.scrollTop,
      height,
      manyItems.length,
      row
    )
    for (const [index, el] of rendered) {
      if (index >= start && index < end) {
        continue
      }
      el.remove()
      rendered.delete(index)
    }
    for (let index = start; index < end; index++) {
      if (rendered.has(index)) {
        continue
      }
      const item = manyItems[index]
      rows.insertAdjacentHTML(
        "beforeend",
        `<ui-select-item value="${item.value}" label="${item.label}" index="${index}" style="top: ${index * row}px; height: ${row}px">${item.label}</ui-select-item>`
      )
      rendered.set(index, rows.lastElementChild!)
    }
  }
  render()
  select.items = manyItems
  scroller.addEventListener("scroll", render)
  select.addEventListener("highlight", (event) => {
    const { index } = event.detail
    if (index < 0) {
      return
    }
    scroller.scrollTop = scrollForRow(
      index,
      scroller.scrollTop,
      scroller.clientHeight,
      row
    )
    render()
  })
}

export { mount }
```

打开 Item 并按 End 到达 Item 10000，然后按 Home 回到开头。滚动列表，只有附近的行会被渲染。

## 让选项与触发器对齐
在 `ui-select-content` 上设置 `align-item-with-trigger`，把选中的选项放在触发器上方。通过触摸打开或空间不足时，它会回退到普通的浮层放置方式。

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

const priorities = [
  { value: "urgent", label: "Urgent" },
  { value: "high", label: "High" },
  { value: "medium", label: "Medium" },
  { value: "low", label: "Low" },
  { value: "none", label: "No priority" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <ui-checkbox default-checked>
            <ui-checkbox-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-checkbox-indicator>
          </ui-checkbox>
          Align item with trigger
        </label>
      </div>
      <ui-field>
        <ui-field-label>Priority</ui-field-label>
        <ui-select default-value="medium">
          <ui-select-trigger>
            <button>
              <ui-select-value></ui-select-value>
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-select-trigger>
          <ui-select-content align-item-with-trigger>
            ${priorities
              .map(
                (priority) => `
                  <ui-select-item value="${priority.value}">
                    ${priority.label}
                    <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                  </ui-select-item>
                `
              )
              .join("")}
          </ui-select-content>
        </ui-select>
      </ui-field>
    </div>
  `
  const content = root.querySelector("ui-select-content")!
  root
    .querySelector("ui-checkbox")!
    .addEventListener("checkedchange", (event) => {
      content.toggleAttribute(
        "align-item-with-trigger",
        event.detail.value === true
      )
    })
}

export { mount }
```

打开 Priority：Medium 位于触发器上方。关闭它，取消勾选 Align item with trigger，再次打开以比较放置位置。

## 可滚动
限制内容的高度并允许纵向滚动。`--available-height` 告诉你浮层有多少空间；用键盘移动时，高亮的选项会滚动到视图中。

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

const timezones = [
  {
    label: "North America",
    items: [
      { value: "est", label: "Eastern Standard Time" },
      { value: "cst", label: "Central Standard Time" },
      { value: "mst", label: "Mountain Standard Time" },
      { value: "pst", label: "Pacific Standard Time" },
      { value: "akst", label: "Alaska Standard Time" },
      { value: "hst", label: "Hawaii Standard Time" },
    ],
  },
  {
    label: "Europe & Africa",
    items: [
      { value: "gmt", label: "Greenwich Mean Time" },
      { value: "cet", label: "Central European Time" },
      { value: "eet", label: "Eastern European Time" },
      { value: "west", label: "Western European Summer Time" },
      { value: "cat", label: "Central Africa Time" },
      { value: "eat", label: "East Africa Time" },
    ],
  },
  {
    label: "Asia",
    items: [
      { value: "msk", label: "Moscow Time" },
      { value: "ist", label: "India Standard Time" },
      { value: "cst-china", label: "China Standard Time" },
      { value: "jst", label: "Japan Standard Time" },
      { value: "kst", label: "Korea Standard Time" },
      { value: "ist-indonesia", label: "Indonesia Central Standard Time" },
    ],
  },
  {
    label: "Australia & Pacific",
    items: [
      { value: "awst", label: "Australian Western Standard Time" },
      { value: "acst", label: "Australian Central Standard Time" },
      { value: "aest", label: "Australian Eastern Standard Time" },
      { value: "nzst", label: "New Zealand Standard Time" },
      { value: "fjt", label: "Fiji Time" },
    ],
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Time zone</ui-field-label>
      <ui-select placeholder="Select a time zone">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${timezones
            .map(
              (group) => `
                <ui-select-group>
                  <ui-select-group-label>${group.label}</ui-select-group-label>
                  ${group.items
                    .map(
                      (item) => `
                        <ui-select-item value="${item.value}">
                          ${item.label}
                          <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                        </ui-select-item>
                      `
                    )
                    .join("")}
                </ui-select-group>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

打开 Time zone 并用方向键向下移动。列表会滚动，让高亮的选项保持可见。

## 无效
在 [Field](/docs/web-components/components/field) 内部，字段的标签为触发器命名，它的描述和错误信息描述触发器。提交时在 `ui-select` 自身上设置 `name`。无效提交之后，触发器会得到 `aria-invalid` 和 `data-invalid`。

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

const methods = [
  { value: "standard", label: "Standard" },
  { value: "express", label: "Express" },
  { value: "overnight", label: "Overnight" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field name="shipping">
        <ui-field-label>Shipping method</ui-field-label>
        <ui-select required placeholder="Select a shipping method">
          <ui-select-trigger>
            <button>
              <ui-select-value></ui-select-value>
              ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-select-trigger>
          <ui-select-content>
            ${methods
              .map(
                (method) => `
                  <ui-select-item value="${method.value}">
                    ${method.label}
                    <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                  </ui-select-item>
                `
              )
              .join("")}
          </ui-select-content>
        </ui-select>
        <ui-field-description>Express arrives in two business days.</ui-field-description>
        <ui-field-error match="valueMissing">Choose a shipping method.</ui-field-error>
      </ui-field>
      <button type="submit" data-variant="solid">Continue</button>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Submitted shipping=${new FormData(form).get("shipping")}`)
  })
}

export { mount }
```

不选择配送方式就按 Continue，显示错误。选择一个并继续；控制台记录提交的值。

## 表单
设置 `name` 让 Select 参与表单提交。`required` 在选中内容之前阻止提交；重置表单会恢复 `default-value`。多个值会以独立条目提交在同一个名称下。

这个示例还用 `auto-complete="country"` 实现自动填充，并用 `form="select-newsletter"` 把 Frequency 的 Select 关联到它外部的表单。

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

const countries = [
  { value: "au", label: "Australia" },
  { value: "br", label: "Brazil" },
  { value: "ca", label: "Canada" },
  { value: "fr", label: "France" },
  { value: "de", label: "Germany" },
  { value: "jp", label: "Japan" },
  { value: "es", label: "Spain" },
  { value: "se", label: "Sweden" },
]

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

const frequencies = ["Daily", "Weekly", "Monthly"]

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

const trigger = `
  <ui-select-trigger>
    <button>
      <ui-select-value></ui-select-value>
      ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
    </button>
  </ui-select-trigger>
`

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <form id="select-newsletter" data-slot="stack">
        <ui-field>
          <ui-field-label>Country</ui-field-label>
          <ui-select name="country" auto-complete="country" required placeholder="Select a country">
            ${trigger}
            <ui-select-content>
              ${countries.map((country) => item(country.value, country.label)).join("")}
            </ui-select-content>
          </ui-select>
        </ui-field>
        <ui-field>
          <ui-field-label>Topics</ui-field-label>
          <ui-select name="topics" multiple default-value="Design">
            ${trigger}
            <ui-select-content>
              ${topics.map((topic) => item(topic, topic)).join("")}
            </ui-select-content>
          </ui-select>
        </ui-field>
      </form>
      <ui-field>
        <ui-field-label>Frequency</ui-field-label>
        <ui-select name="frequency" form="select-newsletter" default-value="Weekly">
          ${trigger}
          <ui-select-content>
            ${frequencies.map((frequency) => item(frequency, frequency)).join("")}
          </ui-select-content>
        </ui-select>
      </ui-field>
      <div data-slot="row">
        <button type="submit" form="select-newsletter" data-variant="solid">Save</button>
        <button type="reset" form="select-newsletter">Reset</button>
      </div>
    </div>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const entries = [...new FormData(form)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(root, `Submitted ${entries.join("&")}`)
  })
}

export { mount }
```

选择一个国家并选几个主题，修改 Frequency，然后按 Save；控制台记录全部三个字段。Reset 恢复初始选择。

## 呈现方式
用 `presentation="sheet"` 在底部面板（sheet）中打开选项，或用 `"auto"` 在小尺寸触摸屏上使用底部面板。选择选项仍会选中它，并关闭单选列表。

内容会得到 `data-presentation`。用它给底部面板的选项更多空间。为底部面板保留 `translate` property，供它的拖动行为使用，并在底部加入安全区域的内边距。

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

const statuses = [
  { value: "backlog", label: "Backlog" },
  { value: "todo", label: "Todo" },
  { value: "in-progress", label: "In Progress" },
  { value: "in-review", label: "In Review" },
  { value: "done", label: "Done" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Status</ui-field-label>
      <ui-select default-value="todo" presentation="sheet">
        <ui-select-trigger>
          <button>
            <ui-select-value></ui-select-value>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-select-trigger>
        <ui-select-content>
          ${statuses
            .map(
              (status) => `
                <ui-select-item value="${status.value}">
                  ${status.label}
                  <ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
                </ui-select-item>
              `
            )
            .join("")}
        </ui-select-content>
      </ui-select>
    </ui-field>
  `
}

export { mount }
```

打开 Status 显示底部面板。选择一个选项关闭它，或向下拖动，在不改变值的情况下关闭。

除非 `modal="false"`，底部面板会让它后面的页面不可交互（inert），并锁定滚动。[浮层](https://ui-sdk.cn/docs/web-components/popups#modals-and-sheets)解释了共享的呈现方式选项。

## 受控
读取或设置元素的 `value` 和 `open` property。单值是 `T | null`；使用 `multiple` 时是 `T[]`。在 Select 自身上监听 `valuechange` 和 `openchange`。请求的值在 `event.detail.value` 里；调用 `event.preventDefault()` 拒绝这次变更。

[状态与事件](/docs/web-components/state-and-events)解释了这个模式。[原因表](https://ui-sdk.cn/docs/web-components/components/select#reasons)列出了 Select 的原因，包括 `item-press`、`list-navigation` 和 `clear-press`。

## 控制器
元素的 `api` property 可以打开、读取或更改 Select。它之外的触发器用 `for="select-id"` 连接。设置方法以及等待浮层关闭的写法见[控制器](/docs/web-components/controllers)，方法列表见 [Select 控制器参考](https://ui-sdk.cn/docs/web-components/components/select#controller-1)。

## 定位
用 `side`、`align` 和偏移量放置浮层。`ui-select-arrow` 跟随它最终落在的那一侧。[浮层](https://ui-sdk.cn/docs/web-components/popups#place-the-content)介绍了锚点和碰撞处理。

## 模态
默认情况下，外部按压会关闭列表，但不会激活它后面的元素。`modal="true"` 还会锁定滚动，并让页面不可交互（inert）。`modal="false"` 允许外部按压穿透。见[控制关闭](https://ui-sdk.cn/docs/web-components/popups#control-dismissal)。

## 容器
浮层使用顶层，不需要传送门（portal）。当它必须渲染到另一个 DOM 容器时，使用 `container`。[隐藏内容与容器](https://ui-sdk.cn/docs/web-components/popups#hidden-content-and-containers)介绍了共享的设置。

## 动画
Select 会让正在关闭的内容保持挂载，直到它的退场（outro）动画结束。之后运行 `openchangecomplete`。如果你的动画库需要已关闭的内容留在 DOM 中，使用 `keep-mounted`。[样式与动画](/docs/web-components/styling-and-animation)介绍了生命周期属性。

## 自定义渲染
触发器和清除部件包裹你自己的 `<button>`；输入部件包裹你自己的 `<input>`。其他部件可以用 `as-child` 绑定你的元素。[部件与组合](https://ui-sdk.cn/docs/web-components/parts-and-composition#choose-the-element)解释了标记写法。Select 各部件状态以属性形式显示在[数据属性](https://ui-sdk.cn/docs/web-components/components/select#data-attributes)下。

## 样式
用 `data-highlighted` 标记活动选项，用 `data-selected` 标记选中的选项，没有选中任何内容时在触发器和值上使用 `data-placeholder`。内容上的 `data-modality="keyboard"` 区分键盘高亮和指针高亮。

`--anchor-width` 与触发器宽度一致，`--available-height` 说明浮层有多少空间。用它们设置内容的尺寸。

每个部件都有一个 `data-slot`，比如 `select-trigger`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/select#data-attributes)下。

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

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

## 数据属性
`<ui-select-list>`、`<ui-select-input>`、`<ui-select-group>`、`<ui-select-group-label>`、`<ui-select-separator>` 和 `<ui-select-value-icon>` 没有状态属性。

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

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

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

- `data-closed`: Present while the list is closed, including while it animates out.
- `data-disabled`: Present when the select or the trigger is disabled.
- `data-open`: Present while the list is open.
- `data-placeholder`: Present while nothing is selected, so the placeholder shows.
- `data-readonly`: Present when the select is read-only.
- `data-required`: Present when the select is required.

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

- `data-placeholder`: Present while nothing is selected, so the placeholder shows.

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

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

### `<ui-select-content>`
`[data-slot="select-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 trigger.
- `data-modality` (`keyboard`, `pointer`): Whether the keyboard or a pointer is in use, for focus styles.
- `data-has-icons`: Present while any item inside holds an icon part, so items without one can line up.

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

- `data-selected`: Present on selected items, and on the check inside them.
- `data-disabled`: Present when the item can't be chosen.
- `data-highlighted`: Present on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field.
- `data-has-icon`: Present on an item while it holds an icon part.

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

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

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

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

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

- `data-disabled`: Present when nothing the select-all option covers can be chosen.
- `data-unchecked`: Present on a select-all option while none of its items is selected.
- `data-highlighted`: Present on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field.

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

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

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

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

### `<ui-select-arrow>`
`[data-slot="select-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 trigger.
- `data-arrow-clamped`: Present on the arrow when it stops short of the middle of the trigger, held back by `arrowPadding`.

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

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

## API 参考
props 是以 kebab 命名的属性，比如 `default-value` 和 `align-item-with-trigger`：`"false"` 是 false，数字是数字。`items`、`itemToValue`、`itemToLabel` 和 `isItemEqualToValue` 是 property。`container` 和 `anchor` 接受 CSS 选择器。回调是 DOM 事件。

### Select
- `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.
- `open?` (`boolean`): Whether the list is open. Pass it to control it.
- `defaultOpen?` (`boolean`): Whether the list starts open, when uncontrolled.
- `openchange event`: Runs when the list wants to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `openchangecomplete event`: Runs once the list has finished opening or closing, after any animation.
- `items?` (`ListData<T>`): The items as data. Renders the list for you, and lets the trigger show labels and find items by typing before the list has ever opened.
- `emptyItems?` (`ListData<T>`): Items shown instead of `items` while the search field is empty, like recent choices. Groups work, like `{ type: "group", label: "Recent", items }`. Needs `items` and a `SelectInput`.
- `query?` (`string`): The text in the search field, which filters the list. Pass it to control it. Closing the list empties it.
- `defaultQuery?` (`string`): The search field's text at first, when uncontrolled.
- `querychange event`: Runs when the search field's text wants to change: typing, or closing the list, which empties it.
- `filter?` (`ListFilter<T>`): How a `SelectInput` 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.
- `status?` (`AsyncOptionsStatus`): Whether results are loading or failed, for the status and empty parts. Sets `aria-busy` on the list while loading.
- `loadmore event`: Runs when the highlight or scrolling reaches the last item, so the next page can load, like `createAsyncOptions`'s `loadMore`. Not again for the same items, unless the last load failed.
- `announcement?` (`((change: ListAnnouncement) => string | null | undefined)`): What screen readers hear after typing pauses in the search field, when no `SelectStatus` is rendered. Return null for nothing.
- `placeholder?` (`string`): What the value shows while nothing is selected.
- `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 in the trigger, 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.
- `highlight event`: Runs when the highlight moves, with the item's index among the visible items, so a virtualized list can scroll to it.
- `loop?` (`boolean`): Whether arrow keys wrap from the last item to the first.
- `virtualFocus?` (`boolean`): Keeps focus on the trigger while the list is open, as on a native select: arrow keys, Home, End and typing move the highlight, and the trigger points at the highlighted item with `aria-activedescendant`. A search field in the list still takes focus.
- `modal?` (`"pointer" | boolean`): `"pointer"`: an outside press only closes the list. `true`: also locks scroll and makes the rest of the page inert. `false`: outside presses reach what they hit.
- `presentation?` (`PresentationSetting<"popover">`): How the list presents. `"sheet"` slides it up from the bottom of the screen, where it can be swiped away, and `"auto"` does that on small touch screens. Decided each time it opens; the server renders `"popover"` for `"auto"`.
- `disabled?` (`boolean`): Disables the select like a native one: it can't be focused or changed, and the value isn't submitted.
- `readOnly?` (`boolean`): Keeps the select 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 select submits nothing.
- `form?` (`string`): The id of a form to belong to, when the select isn't inside that form.
- `autoComplete?` (`string`): A hint for the browser's autofill, like `"country"`.
- `controller?` (`object`): Opens, closes, reads and sets the select from anywhere. Create one with `createSelectController()`.
- `dismissible?` (`boolean`): Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass `false` while it holds unsaved work, and ask in `dismissattempt`.
- `dismissattempt event`: Runs when `dismissible` refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.
- `multiple?` (`boolean`): Whether several items can be selected. The value is then a list, and the list stays open as items toggle. Whether several items can be selected.
- `value?` (`T | T[] | null`): The selected value. Pass it to control the select. `null` selects nothing. The selected values. Pass it to control the select. The selected value, or values with `multiple`. Pass it to control the select.
- `defaultValue?` (`T | T[] | null`): The value selected at first, when uncontrolled. A form reset returns to it. The values selected at first, when uncontrolled. A form reset returns to them. The value or values selected at first, when uncontrolled. A form reset returns to it.
- `valuechange event`: Runs when a user, a form reset or a controller wants to change the value. `details.reason` says why, and `details.cancel()` stops it.

### SelectTrigger
Select 之外的触发器用 `for="select-id"` 为它命名。

- `disabled?` (`boolean`): Stops the trigger from opening the list. A native button can't be focused or pressed.
- `controller?` (`object`): Connects a trigger outside the select to the select with this controller.

### SelectValue
- `placeholder?` (`string`): What shows while nothing is selected. Overrides the select's `placeholder`.
- `maxLabels?` (`number`): With `multiple`, how many labels show before the rest are counted, as in "Apple, Banana 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`.

### SelectContent
- `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 trigger 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 trigger along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the trigger and the list, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the trigger, 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.
- `alignItemWithTrigger?` (`boolean`): Whether the list overlaps the trigger so the selected item sits on it, like a native select on macOS. Falls back to opening below when there isn't room, and for touch.
- `keepMounted?` (`boolean`): Whether the list stays in the page, hidden, while closed. Its content keeps its state between opens.

### SelectItem
- `label?` (`string`): The text the trigger shows and typing finds, when the content isn't plain text. Not the accessible name: use `aria-label` for that.
- `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 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`.

### SelectItemIndicator
- `keepMounted?` (`boolean`): Whether the indicator stays in the page while its item isn't selected, so it can be styled or animated in both states.

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

`ui-select-value-icon` 没有自己的 props，也不接受 children。

### SelectClear
- `keepMounted?` (`boolean`): Whether the clear button stays in the page while nothing is selected.

### SelectInput、SelectEmpty、SelectStatus、SelectItemText 和 SelectSelectAll
它们都没有自己的 props。`ui-select-input` 开启搜索，`ui-select-item-text` 在选项文本中标记搜索匹配的内容，`ui-select-select-all` 作用于它所在分组的选项，不在分组里时作用于每个选项。没有 `ui-select-status` 时，输入暂停后，结果数量会通过页面共享的实时区域（live region）播报给屏幕阅读器。`announcement` 接收 `{ type: "results", count, query, loading }` 并返回播报的措辞，返回 `null` 则不播报。默认是英文：“3 results”、“No results”或“Loading”。

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

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

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

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

`ui-select-trigger`：

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

`ui-select-value`：

- `value` (`unknown`): The selected value: one, `null`, or a list with `multiple`.
- `label` (`string`): The selected item's label, the labels joined with commas for several, or with `maxLabels`, as a list in the page's language, like "Apple, Banana and 2 more". An empty string for none.
- `labels` (`string[]`): Each selected item's label, in the order they were selected.
- `placeholder` (`boolean`): Whether nothing is selected, so the placeholder shows.

`ui-select-content` 和 `ui-select-list`：

- `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.
- `items` (`ListData<unknown>`): The data items that match the search, for rendering a virtualized list yourself.
- `status` (`AsyncOptionsStatus`): Whether results are loading or failed.

`ui-select-item`：

- `highlighted` (`boolean`): Whether the item has keyboard focus or is under the pointer.
- `selected` (`boolean`): Whether its value is in the select's value, compared with `isItemEqualToValue` when you pass one.
- `disabled` (`boolean`): Whether the item's own `disabled` prop is set. It can't be highlighted or chosen.

`ui-select-item-indicator`：

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

`ui-select-item-icon`：

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

`ui-select-clear`：

- `disabled` (`boolean`): Whether the select is disabled or read-only, so there's nothing it can clear.

`ui-select-arrow`：

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

`ui-select-input`：

- `open` (`boolean`): Whether the list is open.
- `disabled` (`boolean`): Whether the select is disabled, by itself or by a `<fieldset>`. A read-only select's search field stays enabled.

`ui-select-item-text`：

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

`ui-select-select-all`：

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

`ui-select-empty`：

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

`ui-select-status`：

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

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

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `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.
- `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`.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`PointerEvent | TouchEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

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

- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `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.

以及搜索文本为什么变化：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `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`.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `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.
- `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.

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

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

- `isOpen()` (`() => boolean`): Whether the list is open.
- `setOpen(open, options?)` (`(open: boolean, options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean`): Opens or closes the list. Returns false when the change was canceled or it was already open or closed.
- `open(options?)` (`(options?: (SelectChangeOptions<SelectOpenChangeReason> & { 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 select leaves the page.
- `close(options?)` (`(options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean`): Closes the list. Returns false when the close was canceled or it was already closed.
- `toggle(options?)` (`(options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean`): Opens the list when it's closed, and closes it when it's open. Returns false when the change was canceled.
- `getValue()` (`() => SelectValue<T, Multiple>`): The selected value.
- `setValue(value, options?)` (`(value: SelectValue<T, Multiple>, options?: SelectChangeOptions<SelectValueChangeReason> | undefined) => boolean`): Selects a value, as a user would. A disabled or read-only select ignores it. Returns false when the change was canceled, ignored or the value was already selected.
- `clear(options?)` (`(options?: SelectChangeOptions<SelectValueChangeReason> | undefined) => boolean`): Selects nothing: `null`, or an empty list with `multiple`. Returns false when nothing changed.
- `getQuery()` (`() => string`): The text in the search field.
- `setQuery(query, options?)` (`(query: string, options?: SelectChangeOptions<SelectQueryChangeReason> | undefined) => boolean`): Changes the text in the search field, which filters the list. Returns false when nothing changed.
- `focus()` (`() => void`): Moves focus to the trigger.

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

| 成员                       | 所属                | 说明                                                         |
| -------------------------- | ------------------- | ------------------------------------------------------------ |
| `value` property           | `ui-select`         | 选中的值。设置它会像控制器一样选中                           |
| `open` property, attribute | `ui-select`         | 列表是否打开。属性设置它的初始状态                           |
| `api` property             | `ui-select`         | [控制器](https://ui-sdk.cn/docs/web-components/components/select#controller-1)                                      |
| `valuechange` event        | `ui-select`         | `detail: { value, reason, event, source }`                   |
| `openchange` event         | `ui-select`         | `detail: { value: open, reason, event, source }`             |
| `openchangecomplete` event | `ui-select`         | `detail: { value: open }`，在动画之后                        |
| `highlight` event          | `ui-select`         | `detail: { value, index, event }`                            |
| `query` property           | `ui-select`         | 搜索文本                                                     |
| `querychange` event        | `ui-select`         | `detail: { value: query, reason, event, source, composing }` |
| `loadmore` event           | `ui-select`         | 在到达最后一个选项时                                         |
| `dismissattempt` event     | `ui-select`         | `detail: { reason, event }`，在关闭被拒绝时                  |
| `for` attribute            | `ui-select-trigger` | 位于它之外的触发器所打开的 Select 的 `id`                    |

## 无障碍
Select 遵循 [WAI-ARIA 只选组合框模式](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/)。触发器带有 `combobox` 角色，浮层是一个 `listbox`。如果不需要可见的标签，改为给它的 button 一个 `aria-label`。

### 键盘
方向键在打开的列表中移动；Home 和 End 到达第一个和最后一个选项。设置 `loop="false"` 让方向键在两端停住。浮层跟随触发器继承的文本方向；在从右到左的布局中，用逻辑 CSS 属性设置间距。

设置 `virtual-focus`，让列表打开期间焦点留在触发器上，就像原生 select 那样：方向键、Home、End 和输入会移动高亮，触发器用 `aria-activedescendant` 指向它，Tab 关闭列表并继续前进。列表里的搜索字段仍然会获得焦点。

### 经过测试的行为
下面每一行都是一个自动化测试。

- With alignItemWithTrigger, the selected item sits over the trigger.
- A controller opens the list.

**Trigger**

- Is a combobox named by its label that shows the placeholder.
- Click opens the list.
- Enter opens the list and focuses the first item.
- Space opens the list and focuses the first item.
- ArrowDown opens the list and focuses the first item.
- Points to the list it controls while open.
- A click on the open trigger closes the list.
- A click on a trigger in a shadow root opens the list, and it stays open. Vue 和 web components only.

**Keyboard in the list**

- Arrow keys move focus through the items.
- Home and End move to the first and last items.
- Arrow keys skip disabled items.
- Typing focuses the next item that starts with the text.
- Enter chooses the focused item, closes and returns focus to the trigger.
- Space chooses the focused item.
- Escape closes without choosing and returns focus to the trigger.
- An ancestor hears Escape already handled.
- The chosen item is selected when the list opens again, and takes focus.

**Typing on the closed trigger**

- Selects the next item that starts with the text, like a native select.
- Skips disabled items.

**Pointer**

- Clicking an item chooses it and closes the list.
- Clicking a disabled item does nothing.
- Moving over a disabled item leaves the highlight where it was.
- Clicking outside closes without choosing.
- Pressing, dragging to an item and releasing chooses it.
- Enter opens the list after a drag chose an item.
- Enter opens the list after pressing the open trigger and releasing elsewhere.

**Value**

- A disabled value stays in the trigger, and the list opens on the first enabled item.
- A default value shows its label and is selected.
- Opening with a selected item focuses it.
- Canceling the change keeps the value.

**Multiple**

- The list allows several selections.
- Choosing toggles items and keeps the list open.

**Groups**

- Items sit in groups named by their labels.
- Arrow keys move across groups.

**Forms**

- The form submits the value under the select's name.
- Enter in the form's one text field submits it, with no submit button.
- A required select blocks submission until a value is chosen.
- A disabled select can't be opened.
- A read-only select doesn't change its value.
- A disabled fieldset disables the select and leaves it out of the form.

**Positioning**

- The list opens below the trigger, at least as wide.

Runs in React、Vue 和 web components.

其他行为：

**Enhancements**

- A data select whose content part is wrapped in a component renders one list.
- The list is named by the select's label.
- A clear button selects nothing and keeps focus on the select.
- Alt+ArrowUp chooses the focused item and closes, as the APG asks.
- The content says whether the keyboard or a pointer is in use, for styling the highlight.
- A form reset returns the select to its default value.
- Typing on the closed trigger selects items before the list has ever been in the page.

**Focus on the trigger**

- With virtualFocus, keys move the highlight while focus stays on the trigger, which points at it.
- With virtualFocus, Tab closes the list and moves on from the trigger.
- With virtualFocus, a click on an item chooses it and keeps focus on the trigger.

Runs in React、Vue 和 web components.

带列表内搜索字段的搜索：

**Searchable select**

- Opening focuses the search field and highlights the selected item.
- The search field is a combobox that controls the listbox in the list.
- Typing filters the list and highlights the first match.
- A field whose onChange renders the filtered list at once still highlights the first match. React only.
- Typing never jumps by first letter: the characters go into the field.
- Arrow keys move the highlight while focus stays in the field.
- Home and End are the field's, so the highlight stays.
- Enter chooses the highlighted item, closes, and focus returns to the trigger.
- A click on an item chooses it.
- Escape closes the list and focus returns to the trigger.
- The search empties once the list closes.
- An empty message shows when nothing matches.
- Matches ignore case and accents.
- Labels mark what the search matched.
- With multiple, choosing keeps the list open and focus in the field.
- Tab closes the list and moves on from the trigger.
- No axe violations while searching.
- Typing on the closed trigger still selects by first letter.

**Items shown while the search is empty**

- Recent items show until the user types, then the results.
- A recent item is chosen like any other, and its label shows in the trigger.

Runs in React、Vue 和 web components.

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

- Announcements while choosing with a keyboard.

Runs in React、Vue 和 web components.
