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

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

const roles = [
  { value: "viewer", label: "Viewer" },
  { value: "commenter", label: "Commenter" },
  { value: "editor", label: "Editor" },
  { value: "admin", label: "Admin" },
]

function Example() {
  return (
    <Field>
      <FieldLabel>Role</FieldLabel>
      <Select placeholder="Select a role">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={roles}>
            {(role) => (
              <SelectItem value={role.value}>
                {role.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

export { Example }
打开 Role 并选择 Editor。列表关闭,触发器显示你的选择。

安装

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

组合

用下面的组合构建 Select:

Select
├── SelectLabel
├── SelectTrigger
│   └── SelectValue
└── SelectContent
    ├── SelectItem
    └── SelectItem

从标签、触发器和选项列表开始。SelectValue 在触发器里显示选中选项的标签。SelectLabel 为触发器命名;在 Field 里,改用它的 FieldLabel,示例就是这样做的。

用法

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

import {
  Select,
  SelectContent,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"

function Example() {
  return (
    <Select placeholder="Select a role">
      <SelectLabel>Role</SelectLabel>
      <SelectTrigger>
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="viewer">Viewer</SelectItem>
        <SelectItem value="editor">Editor</SelectItem>
      </SelectContent>
    </Select>
  )
}

export { Example }

以数据形式提供的选项

当选项来自数据时,把数组传给 items。字符串既是值也是标签。两者不同时,使用对象:

<Select items={["Free", "Pro"]} />
<Select items={[{ value: "pro", label: "Pro plan" }]} />

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

import type { ListData } from "@ui-sdk/solid/select"

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

Select 可以直接渲染这份数据中的选项本身。要为它们设置样式,就把 items 留在 Select 上,并在 SelectContent 里渲染 SelectItem 部件,示例就是这样做的。把数据放在根部件上,还能让标签在列表打开之前就可用,包括服务端渲染期间。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectGroupLabel,
  SelectItem,
  SelectItemIndicator,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
  type ListData,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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

function Example() {
  return (
    <Field>
      <FieldLabel>Plan</FieldLabel>
      <Select items={items} defaultValue="pro">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={plans}>
            {(plan) => (
              <SelectItem value={plan.value}>
                {plan.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
          <SelectSeparator />
          <SelectGroup>
            <SelectGroupLabel>Contact sales</SelectGroupLabel>
            <For each={sales}>
              {(plan) => (
                <SelectItem value={plan.value} disabled={plan.disabled}>
                  {plan.label}
                  <SelectItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </SelectItemIndicator>
                </SelectItem>
              )}
            </For>
          </SelectGroup>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

列表打开期间,选项可以变化。导航跟随新的顺序;对应的选项还在时,它的选中和高亮状态保持不变。移除高亮的选项会清除高亮。列表与菜单介绍了共享的数据结构。

分组

把相关的选项放进 SelectGroup,用 SelectGroupLabel 为每个分组命名。SelectSeparator 添加一条视觉分隔,本身不会成为选项。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectGroupLabel,
  SelectItem,
  SelectItemIndicator,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For, Show } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Font</FieldLabel>
      <Select placeholder="Select a font">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={fonts}>
            {(group, index) => (
              <>
                <Show when={index() > 0}>
                  <SelectSeparator />
                </Show>
                <SelectGroup>
                  <SelectGroupLabel>{group.label}</SelectGroupLabel>
                  <For each={group.items}>
                    {(item) => (
                      <SelectItem value={item.value}>
                        {item.label}
                        <SelectItemIndicator>
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            aria-hidden="true"
                          >
                            <path d="M20 6 9 17l-5-5" />
                          </svg>
                        </SelectItemIndicator>
                      </SelectItem>
                    )}
                  </For>
                </SelectGroup>
              </>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

图标

SelectItemIcon 让图标与选项的文本分开,因此不影响它的无障碍名称、键入查找(typeahead)或搜索。把 SelectValueIcon 加到触发器上,选中选项的图标也会显示在那里。

<SelectTrigger>
  <SelectValueIcon />
  <SelectValue />
</SelectTrigger>

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIcon,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
  SelectValueIcon,
} from "@ui-sdk/solid/select"

function Example() {
  return (
    <Field>
      <FieldLabel>Text alignment</FieldLabel>
      <Select defaultValue="start">
        <SelectTrigger>
          <SelectValueIcon />
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="start">
            <SelectItemIcon mirror>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M21 5H3" />
                <path d="M15 12H3" />
                <path d="M17 19H3" />
              </svg>
            </SelectItemIcon>
            Start
            <SelectItemIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </SelectItemIndicator>
          </SelectItem>
          <SelectItem value="center">
            <SelectItemIcon>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M21 5H3" />
                <path d="M17 12H7" />
                <path d="M19 19H5" />
              </svg>
            </SelectItemIcon>
            Center
            <SelectItemIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </SelectItemIndicator>
          </SelectItem>
          <SelectItem value="end">
            <SelectItemIcon mirror>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M21 5H3" />
                <path d="M21 12H9" />
                <path d="M21 19H7" />
              </svg>
            </SelectItemIcon>
            End
            <SelectItemIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </SelectItemIndicator>
          </SelectItem>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

键入查找

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

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Country</FieldLabel>
      <Select defaultValue="fr">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={countries}>
            {(country) => (
              <SelectItem value={country.value} label={country.label}>
                {country.label}
                <span data-slot="hint">{country.code}</span>
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

禁用

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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 Example() {
  return (
    <div data-slot="stack">
      <For each={fields}>
        {(field) => (
          <Field>
            <FieldLabel>{field.label}</FieldLabel>
            <Select
              defaultValue={field.disabled || field.readOnly ? "fr" : null}
              placeholder="Select a country"
              disabled={field.disabled}
              readOnly={field.readOnly}
            >
              <SelectTrigger>
                <SelectValue />
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </SelectTrigger>
              <SelectContent>
                <For each={countries}>
                  {(country) => (
                    <SelectItem
                      value={country.value}
                      disabled={country.value === "dk"}
                    >
                      {country.label}
                      <SelectItemIndicator>
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          aria-hidden="true"
                        >
                          <path d="M20 6 9 17l-5-5" />
                        </svg>
                      </SelectItemIndicator>
                    </SelectItem>
                  )}
                </For>
              </SelectContent>
            </Select>
          </Field>
        )}
      </For>
    </div>
  )
}

export { Example }
Billing country 已禁用,Shipping from 是只读的。打开 Shipping to 并按方向键:高亮会跳过无法选择的 Denmark。

清除按钮

没有选中任何内容时,placeholder 会显示。添加 SelectClear 可以回到这个状态。清除会把单值设为 null,把多值设为空数组,并把焦点返回触发器。

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

控制台
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectClear,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"
import { useLog } 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 Example() {
  const log = useLog()

  return (
    <Field>
      <FieldLabel>Assignee</FieldLabel>
      <Select
        defaultValue="ines"
        placeholder="Unassigned"
        onValueChange={(value, details) =>
          log(`value: ${JSON.stringify(value)} (${details.reason})`)
        }
      >
        <div data-slot="row">
          <SelectTrigger>
            <SelectValue />
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </SelectTrigger>
          <SelectClear aria-label="Clear assignee">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M18 6 6 18" />
              <path d="m6 6 12 12" />
            </svg>
          </SelectClear>
        </div>
        <SelectContent>
          <For each={people}>
            {(person) => (
              <SelectItem value={person.value}>
                {person.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

多选

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

<Select multiple defaultValue={["en", "ja"]} />

SelectValue 把选中的 labels 暴露给它的 children 函数。用它们概括一长串选择,示例就是这样做的。

控制台
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"
import { useLog } 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 Example() {
  const log = useLog()

  return (
    <Field>
      <FieldLabel>Languages</FieldLabel>
      <Select
        multiple
        defaultValue={["en", "ja"]}
        placeholder="Select languages"
        onValueChange={(value) => log(`value: ${JSON.stringify(value)}`)}
      >
        <SelectTrigger>
          <SelectValue>
            {(state) =>
              state.placeholder
                ? "Select languages"
                : state.labels.length > 2
                  ? `${state.labels[0]} and ${state.labels.length - 1} more`
                  : state.label
            }
          </SelectValue>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={languages}>
            {(language) => (
              <SelectItem value={language.value}>
                {language.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

全选

添加 SelectSelectAll 可以选择或清除每个已启用的选项。只有部分选中时,它显示混合状态。放在 SelectGroup 内部时,它只作用于那个分组。

SelectValue maxLabels={2} 最多显示两个标签,并概括其余的值。getMoreLabel 让你自己写这段概括。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectSelectAll,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For, Show } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Regions</FieldLabel>
      <Select
        multiple
        defaultValue={["us-east", "europe", "asia-pacific"]}
        placeholder="Select regions"
      >
        <SelectTrigger>
          <SelectValue
            maxLabels={2}
            getMoreLabel={(count) => `${count} more`}
          />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <SelectSelectAll>
            {(state) => (
              <>
                Select all
                <Show when={state.checked}>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </Show>
                <Show when={state.indeterminate}>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M5 12h14" />
                  </svg>
                </Show>
              </>
            )}
          </SelectSelectAll>
          <SelectSeparator />
          <For each={regions}>
            {(region) => (
              <SelectItem value={region.value}>
                {region.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

带分组的搜索

在 SelectContent 里添加 SelectInput 来过滤选项。把选项放进 SelectList,这样搜索字段就留在可滚动列表之外。没有匹配项时显示 SelectEmpty。

<SelectContent>
  <SelectInput aria-label="Search countries" />
  <SelectEmpty>No countries found.</SelectEmpty>
  <SelectList>{/* Items go here. */}</SelectList>
</SelectContent>

没有匹配选项的分组会自动隐藏。SelectItemText 可以高亮匹配的文本;这个示例用它的 segments 把匹配项加粗。关闭浮层会清除搜索。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectEmpty,
  SelectGroup,
  SelectGroupLabel,
  SelectInput,
  SelectItem,
  SelectItemIndicator,
  SelectItemText,
  SelectList,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Country</FieldLabel>
      <Select placeholder="Select a country">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <SelectInput
            aria-label="Search countries"
            placeholder="Search countries…"
          />
          <SelectEmpty>No countries found.</SelectEmpty>
          <SelectList>
            <For each={regions}>
              {(group) => (
                <SelectGroup>
                  <SelectGroupLabel>{group.label}</SelectGroupLabel>
                  <For each={group.items}>
                    {(item) => (
                      <SelectItem value={item.value} label={item.label}>
                        <SelectItemText>
                          {(state) => (
                            <For each={state.segments}>
                              {(segment) =>
                                segment.match ? (
                                  <b>{segment.text}</b>
                                ) : (
                                  segment.text
                                )
                              }
                            </For>
                          )}
                        </SelectItemText>
                        <SelectItemIndicator>
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            aria-hidden="true"
                          >
                            <path d="M20 6 9 17l-5-5" />
                          </svg>
                        </SelectItemIndicator>
                      </SelectItem>
                    )}
                  </For>
                </SelectGroup>
              )}
            </For>
          </SelectList>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

方向键移动高亮,焦点留在搜索字段里。在触摸屏的屏幕阅读器上,焦点会改为移入选项。要在搜索之前显示最近的选择,把 emptyItems 和 items 一起传入。列表与菜单介绍了选项过滤。

服务器已经在过滤选项时,使用 filter={false}。把 query 和 onQueryChange 接到你的加载函数上,并把它的选项和状态传给 Select。

这个示例用异步选项替换过期的请求,并通过 onLoadMore 加载下一页。SelectStatus 显示加载状态和结果数量。没有状态部件时,Select 通过页面的实时区域(live region)播报结果数量。

import { useAsyncOptions } from "@ui-sdk/solid/async-options"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectEmpty,
  SelectInput,
  SelectItem,
  SelectItemIndicator,
  SelectList,
  SelectStatus,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"

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 Example() {
  const [query, setQuery] = createSignal("")
  const results = useAsyncOptions(searchCountries, { immediate: true })

  return (
    <Field>
      <FieldLabel>Country</FieldLabel>
      <Select
        items={results.items}
        filter={false}
        status={results.status}
        query={query()}
        onQueryChange={(next) => {
          setQuery(next)
          results.setQuery(next)
        }}
        onLoadMore={results.loadMore}
        placeholder="Select a country"
      >
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <SelectInput
            aria-label="Search countries"
            placeholder="Search countries…"
          />
          <SelectEmpty>
            {(state) =>
              state.empty && !state.loading
                ? `No countries match “${state.query}”.`
                : null
            }
          </SelectEmpty>
          <SelectList>
            {(state) => (
              <For
                each={
                  state.items as {
                    value: string
                    label: string
                    disabled?: boolean
                  }[]
                }
              >
                {(item) => (
                  <SelectItem
                    value={item.value}
                    label={item.label}
                    disabled={item.disabled}
                  >
                    {item.label}
                    <SelectItemIndicator>
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="M20 6 9 17l-5-5" />
                      </svg>
                    </SelectItemIndicator>
                  </SelectItem>
                )}
              </For>
            )}
          </SelectList>
          <SelectStatus>
            {(state) =>
              state.loading
                ? "Loading…"
                : state.status === "error"
                  ? "Couldn't load countries."
                  : `${state.count} shown`
            }
          </SelectStatus>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

对象值

值可以是对象。告诉 Select 如何识别它、显示它,以及如何与另一份副本比较:

属性作用
itemToValue返回用于标识和提交该值的字符串。
itemToLabel返回触发器中显示的文本。
isItemEqualToValue把选项与选中值匹配,即使后者可能是另一份不同的对象。
控制台
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"
import { useLog } 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 Example() {
  const log = useLog()

  return (
    <Field>
      <FieldLabel>Assignee</FieldLabel>
      <Select
        defaultValue={{ ...members[1] }}
        onValueChange={(member) =>
          log(`Submits assignee=${member ? member.id : ""}`)
        }
        name="assignee"
        itemToValue={(member) => String(member.id)}
        itemToLabel={(member) => member.name}
        isItemEqualToValue={(item, value) => item.id === value.id}
        placeholder="Unassigned"
      >
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={members}>
            {(member) => (
              <SelectItem value={member}>
                <span data-slot="stack">
                  {member.name}
                  <span data-slot="hint">{member.email}</span>
                </span>
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

虚拟化

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

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectList,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"

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 Example() {
  let scroller: HTMLDivElement | undefined
  const [scrollTop, setScrollTop] = createSignal(0)

  return (
    <Field>
      <FieldLabel>Item</FieldLabel>
      <Select
        items={manyItems}
        placeholder="Select an item"
        onHighlight={(value, { index }) => {
          const el = scroller
          if (el && index >= 0) {
            el.scrollTop = scrollForRow(
              index,
              el.scrollTop,
              el.clientHeight,
              row
            )
          }
        }}
      >
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <div
            ref={scroller}
            style={{ height: `${height}px` }}
            onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
          >
            <SelectList>
              {(state) => {
                const items = () =>
                  state.items as { value: string; label: string }[]
                const rows = () =>
                  visibleRows(scrollTop(), height, items().length, row)
                return (
                  <div style={{ height: `${items().length * row}px` }}>
                    <For each={items().slice(rows().start, rows().end)}>
                      {(item, offset) => (
                        <SelectItem
                          value={item.value}
                          label={item.label}
                          index={rows().start + offset()}
                          style={{
                            top: `${(rows().start + offset()) * row}px`,
                            height: `${row}px`,
                          }}
                        >
                          {item.label}
                        </SelectItem>
                      )}
                    </For>
                  </div>
                )
              }}
            </SelectList>
          </div>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

让选项与触发器对齐

在 SelectContent 上设置 alignItemWithTrigger,把选中的选项放在触发器上方。通过触摸打开或空间不足时,它会回退到普通的浮层放置方式。

import { Checkbox, CheckboxIndicator } from "@ui-sdk/solid/checkbox"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"

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

function Example() {
  const [aligned, setAligned] = createSignal(true)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <Checkbox
            checked={aligned()}
            onCheckedChange={(next) => setAligned(next === true)}
          >
            <CheckboxIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </CheckboxIndicator>
          </Checkbox>
          Align item with trigger
        </label>
      </div>
      <Field>
        <FieldLabel>Priority</FieldLabel>
        <Select defaultValue="medium">
          <SelectTrigger>
            <SelectValue />
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </SelectTrigger>
          <SelectContent alignItemWithTrigger={aligned()}>
            <For each={priorities}>
              {(priority) => (
                <SelectItem value={priority.value}>
                  {priority.label}
                  <SelectItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </SelectItemIndicator>
                </SelectItem>
              )}
            </For>
          </SelectContent>
        </Select>
      </Field>
    </div>
  )
}

export { Example }
打开 Priority:Medium 位于触发器上方。关闭它,取消勾选 Align item with trigger,再次打开以比较放置位置。

可滚动

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

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectGroupLabel,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Time zone</FieldLabel>
      <Select placeholder="Select a time zone">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={timezones}>
            {(group) => (
              <SelectGroup>
                <SelectGroupLabel>{group.label}</SelectGroupLabel>
                <For each={group.items}>
                  {(item) => (
                    <SelectItem value={item.value}>
                      {item.label}
                      <SelectItemIndicator>
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          aria-hidden="true"
                        >
                          <path d="M20 6 9 17l-5-5" />
                        </svg>
                      </SelectItemIndicator>
                    </SelectItem>
                  )}
                </For>
              </SelectGroup>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

无效

在 Field 内部,字段的标签为触发器命名,它的描述和错误信息描述触发器,提交时使用它的 name。无效提交之后,触发器会得到 aria-invalid 和 data-invalid。

控制台
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        log(
          `Submitted shipping=${new FormData(event.currentTarget).get("shipping")}`
        )
      }}
    >
      <Field name="shipping">
        <FieldLabel>Shipping method</FieldLabel>
        <Select required placeholder="Select a shipping method">
          <SelectTrigger>
            <SelectValue />
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </SelectTrigger>
          <SelectContent>
            <For each={methods}>
              {(method) => (
                <SelectItem value={method.value}>
                  {method.label}
                  <SelectItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </SelectItemIndicator>
                </SelectItem>
              )}
            </For>
          </SelectContent>
        </Select>
        <FieldDescription>
          Express arrives in two business days.
        </FieldDescription>
        <FieldError match="valueMissing">Choose a shipping method.</FieldError>
      </Field>
      <button type="submit" data-variant="solid">
        Continue
      </button>
    </form>
  )
}

export { Example }
不选择配送方式就按 Continue,显示错误。选择一个并继续;控制台记录提交的值。

表单

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

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

控制台
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"
import { useLog } 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"]

function Example() {
  const log = useLog()

  return (
    <div data-slot="stack">
      <form
        id="select-newsletter"
        data-slot="stack"
        onSubmit={(event) => {
          event.preventDefault()
          const entries = [...new FormData(event.currentTarget)].map(
            ([name, value]) => `${name}=${value}`
          )
          log(`Submitted ${entries.join("&")}`)
        }}
      >
        <Field>
          <FieldLabel>Country</FieldLabel>
          <Select
            name="country"
            autoComplete="country"
            required
            placeholder="Select a country"
          >
            <SelectTrigger>
              <SelectValue />
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
            </SelectTrigger>
            <SelectContent>
              <For each={countries}>
                {(country) => (
                  <SelectItem value={country.value}>
                    {country.label}
                    <SelectItemIndicator>
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="M20 6 9 17l-5-5" />
                      </svg>
                    </SelectItemIndicator>
                  </SelectItem>
                )}
              </For>
            </SelectContent>
          </Select>
        </Field>
        <Field>
          <FieldLabel>Topics</FieldLabel>
          <Select name="topics" multiple defaultValue={["Design"]}>
            <SelectTrigger>
              <SelectValue />
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
            </SelectTrigger>
            <SelectContent>
              <For each={topics}>
                {(topic) => (
                  <SelectItem value={topic}>
                    {topic}
                    <SelectItemIndicator>
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="M20 6 9 17l-5-5" />
                      </svg>
                    </SelectItemIndicator>
                  </SelectItem>
                )}
              </For>
            </SelectContent>
          </Select>
        </Field>
      </form>
      <Field>
        <FieldLabel>Frequency</FieldLabel>
        <Select name="frequency" form="select-newsletter" defaultValue="Weekly">
          <SelectTrigger>
            <SelectValue />
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </SelectTrigger>
          <SelectContent>
            <For each={frequencies}>
              {(frequency) => (
                <SelectItem value={frequency}>
                  {frequency}
                  <SelectItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </SelectItemIndicator>
                </SelectItem>
              )}
            </For>
          </SelectContent>
        </Select>
      </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>
  )
}

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

呈现方式

用 presentation="sheet" 在底部面板(sheet)中打开选项,或用 "auto" 在小尺寸触摸屏上使用底部面板。选择选项仍会选中它,并关闭单选列表。

内容会得到 data-presentation,它的渲染状态里也包含 presentation。用其中任意一个给底部面板的选项更多空间。为底部面板保留 translate property,供它的拖动行为使用,并在底部加入安全区域的内边距。

import { Field, FieldLabel } from "@ui-sdk/solid/field"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/solid/select"
import { For } from "solid-js"

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 Example() {
  return (
    <Field>
      <FieldLabel>Status</FieldLabel>
      <Select defaultValue="todo" presentation="sheet">
        <SelectTrigger>
          <SelectValue />
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </SelectTrigger>
        <SelectContent>
          <For each={statuses}>
            {(status) => (
              <SelectItem value={status.value}>
                {status.label}
                <SelectItemIndicator>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                </SelectItemIndicator>
              </SelectItem>
            )}
          </For>
        </SelectContent>
      </Select>
    </Field>
  )
}

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

除非 modal={false},底部面板会让它后面的页面不可交互(inert),并锁定滚动。浮层解释了共享的呈现方式选项。

受控

用 value 和 onValueChange 掌控选择,用 open 和 onOpenChange 掌控浮层状态。单值是 T | null;使用 multiple 时是 T[]。两个回调都先收到请求的值,再收到变更详情。调用 details.cancel() 拒绝一次变更。

状态与事件解释了这个模式。原因表列出了 Select 的原因,包括 item-press、list-navigation 和 clear-press。

控制器

createSelectController() 可以从组件外部打开、读取或更改 Select。它还能连接一个独立的触发器。设置方法以及等待浮层关闭的写法见控制器,方法列表见 Select 控制器参考。

定位

用 side、align 和偏移量放置浮层。SelectArrow 跟随它最终落在的那一侧。浮层介绍了锚点和碰撞处理。

默认情况下,外部按压会关闭列表,但不会激活它后面的元素。modal={true} 还会锁定滚动,并让页面不可交互(inert)。modal={false} 允许外部按压穿透。见控制关闭。

容器

浮层使用顶层,不需要传送门(portal)。当它必须渲染到另一个 DOM 容器时,使用 container。挂载与容器介绍了共享的设置。

动画

Select 会让正在关闭的内容保持挂载,直到它的退场(outro)动画结束。之后运行 onOpenChangeComplete。如果你的动画库需要已关闭的内容留在 DOM 中,使用 keepMounted。样式与动画介绍了生命周期属性。

自定义渲染

用 render 指定部件渲染的元素,或用状态函数自定义它的 children 或类名。部件与组合解释了 props 如何合并。Select 各部件收到的状态列在状态下。

样式

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

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

每个部件都有一个 data-slot,比如 select-trigger,它的状态属性列在数据属性下。

SelectContent

变量内容
--anchor-widthWidth of the anchor, usually the trigger. Use it to match widths.
--anchor-heightHeight of the anchor.
--available-widthSpace beside the popup, up to the viewport edge. Not inherited either.
--available-heightSpace 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-originThe point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWhere the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it.
--drawer-progressWhile 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-dimWhile it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expandWhile 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-stackWhile 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-backdropSet it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

Viewport

变量内容
--keyboard-insetWhile it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthWhile it presents as a sheet: the width of the part of the page you can see.
--visual-viewport-heightWhile it presents as a sheet: the height of the part of the page you can see, above the keyboard.
--visual-viewport-topWhile 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.

数据属性

SelectList、SelectInput、SelectGroup、SelectGroupLabel、SelectSeparator 和 SelectValueIcon 没有状态属性。

SelectLabel

[data-slot="select-label"]

属性含义
data-disabledPresent when the select is disabled, by its own prop, a field or a <fieldset>.
data-readonlyPresent when the select is read-only.
data-requiredPresent when the select is required.

SelectTrigger

[data-slot="select-trigger"]

属性含义
data-closedPresent while the list is closed, including while it animates out.
data-disabledPresent when the select or the trigger is disabled.
data-openPresent while the list is open.
data-placeholderPresent while nothing is selected, so the placeholder shows.
data-readonlyPresent when the select is read-only.
data-requiredPresent when the select is required.

SelectValue

[data-slot="select-value"]

属性含义
data-placeholderPresent while nothing is selected, so the placeholder shows.

SelectClear

[data-slot="select-clear"]

属性含义
data-disabledPresent when the select is disabled or read-only.

SelectContent

[data-slot="select-content"]

属性含义
data-closedPresent while the list is closed, including while it animates out.
data-presentationpopoversheetHow the list presents this time it's open.
data-openPresent while the list is open.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the list animates out. Style the state you animate to.
data-sidetoprightbottomleftWhere the list ended up, after flipping away from edges.
data-alignstartcenterendHow the list lines up with the trigger.
data-modalitykeyboardpointerWhether the keyboard or a pointer is in use, for focus styles.
data-has-iconsPresent while any item inside holds an icon part, so items without one can line up.

SelectItem

[data-slot="select-item"]

属性含义
data-selectedPresent on selected items, and on the check inside them.
data-disabledPresent when the item can't be chosen.
data-highlightedPresent on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field.
data-has-iconPresent on an item while it holds an icon part.

SelectItemText

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

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

SelectItemIndicator

[data-slot="select-item-indicator"]

属性含义
data-selectedPresent on selected items, and on the check inside them.

SelectSelectAll

[data-slot="select-select-all"]

属性含义
data-disabledPresent when nothing the select-all option covers can be chosen.
data-uncheckedPresent on a select-all option while none of its items is selected.
data-highlightedPresent on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field.

SelectEmpty

[data-slot="select-empty"]

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

SelectStatus

[data-slot="select-status"]

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

SelectArrow

[data-slot="select-arrow"]

属性含义
data-closedPresent while the list is closed, including while it animates out.
data-openPresent while the list is open.
data-sidetoprightbottomleftWhere the list ended up, after flipping away from edges.
data-alignstartcenterendHow the list lines up with the trigger.
data-arrow-clampedPresent on the arrow when it stops short of the middle of the trigger, held back by arrowPadding.

SelectItemIcon

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

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

API 参考

props 和回调与下面相同,都作为 Solid props。

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.
onOpenChange?((open: boolean, details: ChangeDetails<SelectOpenChangeReason>) => void)
Runs when the list wants to open or close. details.reason says why, and details.cancel() stops it.
onOpenChangeComplete?((open: boolean) => void)
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.
onQueryChange?((query: string, details: TextChangeDetails<SelectQueryChangeReason>) => void)
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.
onLoadMore?(() => 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 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.
onHighlight?((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.
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 onDismissAttempt.
onDismissAttempt?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, 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.
onValueChange?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.

SelectTrigger

Select 之外的触发器还接受 controller。

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

SelectValueIcon 没有自己的 props,也不接受 children。

SelectClear

keepMounted?boolean
Whether the clear button stays in the page while nothing is selected.

SelectInput、SelectEmpty、SelectStatus、SelectItemText 和 SelectSelectAll

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

以数据形式提供的选项

items 里的每一项。分组是 { type: "group", label, items },分隔符是 { type: "separator" }。

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

状态

每个部件的渲染函数、基于状态的类名和槽位会收到什么。

SelectTrigger:

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

SelectValue:

valueunknown
The selected value: one, null, or a list with multiple.
labelstring
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.
labelsstring[]
Each selected item's label, in the order they were selected.
placeholderboolean
Whether nothing is selected, so the placeholder shows.

SelectContent 和 SelectList:

openboolean
Whether the list is open. False while it animates out.
presentation"popover" | "sheet"
How it presents this time it's open.
multipleboolean | undefined
Whether several items can be selected.
itemsListData<unknown>
The data items that match the search, for rendering a virtualized list yourself.
statusAsyncOptionsStatus
Whether results are loading or failed.

SelectItem:

highlightedboolean
Whether the item has keyboard focus or is under the pointer.
selectedboolean
Whether its value is in the select's value, compared with isItemEqualToValue when you pass one.
disabledboolean
Whether the item's own disabled prop is set. It can't be highlighted or chosen.

SelectItemIndicator:

selectedboolean
Whether its item is selected. While false, the indicator isn't shown unless keepMounted is set.

SelectItemIcon:

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

SelectClear:

disabledboolean
Whether the select is disabled or read-only, so there's nothing it can clear.

SelectArrow:

openboolean
Whether the list is open.

SelectInput:

openboolean
Whether the list is open.
disabledboolean
Whether the select is disabled, by itself or by a <fieldset>. A read-only select's search field stays enabled.

SelectItemText:

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

SelectSelectAll:

checkedboolean
Whether every item it covers is selected.
indeterminateboolean
Whether some of its items are selected, but not all.
highlightedboolean
Whether it's highlighted, by the keyboard or the pointer.
disabledboolean
Whether it can't be used: nothing it covers can be chosen, or choosing them all would pass maxSelected.

SelectEmpty:

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

SelectStatus:

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

原因

details.reason 说明值为什么变化:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
clear-pressMouseEvent | KeyboardEvent
A Clear part was pressed, like on an input, a select or a combobox.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

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

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone
A controller or api call.
trigger-pressMouseEvent | 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-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
focus-outKeyboardEvent | FocusEvent
Focus left the layer, or Tab moved it out.
window-blurFocusEvent
The window lost focus.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
anchor-hiddennone
The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.

dismissible 为 false 时,onDismissAttempt 报告的、被拒绝的关闭:

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

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

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone
A controller or api call.
trigger-pressMouseEvent | 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-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
focus-outKeyboardEvent | FocusEvent
Focus left the layer, or Tab moved it out.
window-blurFocusEvent
The window lost focus.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
input-changeEvent
Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.

控制器

用 createSelectController<Value, Multiple>() 创建一个,并作为 controller 传给 Select 以及它之外的触发器。

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

事件

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

属性所属收到
onValueChangeSelect(value, details):新值,以及原因
onOpenChangeSelect(open, details):新状态,以及原因
onOpenChangeCompleteSelect(open),在动画之后
onHighlightSelect(value, { index, event }):高亮的选项及其行
onQueryChangeSelect(query, details):搜索文本、原因,以及是否仍在 composing
onLoadMoreSelect(),在到达最后一个选项时
onDismissAttemptSelect({ reason, event }),在关闭被拒绝时

无障碍

Select 遵循 WAI-ARIA 只选组合框模式。触发器带有 combobox 角色,浮层是一个 listbox。如果不需要可见的标签,改为给 SelectTrigger 一个 aria-label。

键盘

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

设置 virtualFocus,让列表打开期间焦点留在触发器上,就像原生 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 运行。
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.

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

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

运行于 React、Vue 和 web components。

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

  • Announcements while choosing with a keyboard.

运行于 React、Vue 和 web components。