选择始终可见的列表中的一个或多个选项。

当选项需要始终留在视野里时,使用 Listbox。它像一个有多行可见选项的原生 select,带有键盘导航、键入查找(typeahead)以及可选的范围选择。

import { Field, FieldDescription, FieldLabel } from "@ui-sdk/solid/field"
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"

const topics = [
  { value: "comments", label: "Comments" },
  { value: "mentions", label: "Mentions" },
  { value: "reactions", label: "Reactions" },
  { value: "sign-ins", label: "New sign-ins" },
  { value: "billing", label: "Billing" },
]

function Example() {
  return (
    <Field>
      <FieldLabel>Email me about</FieldLabel>
      <Listbox multiple activation="automatic" defaultValue={["mentions"]}>
        <For each={topics}>
          {(topic) => (
            <ListboxItem value={topic.value}>
              {topic.label}
              <ListboxItemIndicator>
                <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>
              </ListboxItemIndicator>
            </ListboxItem>
          )}
        </For>
      </Listbox>
      <FieldDescription>
        Hold Shift to select a range, or Ctrl or ⌘ to add one.
      </FieldDescription>
    </Field>
  )
}

export { Example }
选择 Comments,然后按住 Shift 并选择 New sign-ins 来选中这个范围。单击会替换选择;Ctrl 或 ⌘ 会添加一个选项。

安装

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

组合

用下面的组合构建 Listbox:

Listbox
├── ListboxItem
│   └── ListboxItemIndicator
└── ListboxItem
    └── ListboxItemIndicator

给列表一个无障碍名称,并给每个选项一个唯一的值。选中某个选项时,ListboxItemIndicator 会显示它的内容。

也可以用 Field 的标签或 aria-labelledby 为列表命名。按钮、搜索字段和空状态消息要留在列表之外:列表内容应该是选项、分组和分隔符。

用法

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

import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"

function Example() {
  return (
    <Listbox aria-label="Toppings" defaultValue="basil">
      <ListboxItem value="basil">
        Basil
        <ListboxItemIndicator>✓</ListboxItemIndicator>
      </ListboxItem>
      <ListboxItem value="olive">
        Olive
        <ListboxItemIndicator>✓</ListboxItemIndicator>
      </ListboxItem>
    </Listbox>
  )
}

export { Example }

多选

添加 multiple 可以选择多个选项。值会变成数组;单选列表使用一个值或 null。默认情况下,方向键只移动焦点,不改变多选的选择。

操作结果
按压一个选项或按 Space切换该选项。
Shift + 按压、方向键或 Space从最后选中的选项开始选择一个范围。
Ctrl/Cmd + Shift + Home 或 End把范围扩展到第一个或最后一个选项。
Ctrl/Cmd + A选中每个已启用的选项,然后再清除选择。

调整 Shift 范围时,范围开始之前选中的选项会保留。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const toppings = [
  { value: "basil", label: "Basil" },
  { value: "cheese", label: "Extra cheese" },
  { value: "mushroom", label: "Mushroom" },
  { value: "olive", label: "Olive" },
  { value: "onion", label: "Onion" },
  { value: "pepper", label: "Pepper" },
]

function Example() {
  const log = useLog()

  return (
    <Listbox
      multiple
      defaultValue={["cheese", "onion"]}
      onValueChange={(value, details) =>
        log(`${value.join(", ") || "Nothing"} (${details.reason})`)
      }
      aria-label="Toppings"
    >
      <For each={toppings}>
        {(topping) => (
          <ListboxItem value={topping.value}>
            {topping.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
选择 Basil,然后按住 Shift 并选择 Pepper 来选中一个范围。用 Ctrl+A 或 ⌘A 选中每个选项,再按一次清除。控制台会记录每次变更。

选择跟随焦点

单选列表会在方向键、Page Up 和 Page Down、Home、End 或输入移动焦点时选中。Page Up 和 Page Down 移动十个选项,并在两端停住。多选列表设置 activation="automatic" 后也能这样做,就像文件列表:按压或方向键会替换选择,Ctrl 或 Cmd 会添加选择,Ctrl 或 Cmd 加方向键只移动焦点而不选择。

轻点和屏幕阅读器的按压则会切换一个选项,因为它们没有修饰键。

<Listbox multiple activation="automatic" aria-label="Files" />
控制台
import { Listbox, ListboxItem, ListboxItemIcon } from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const files = [
  { value: "readme", label: "README.md" },
  { value: "package", label: "package.json" },
  { value: "tsconfig", label: "tsconfig.json" },
  { value: "index", label: "index.ts" },
  { value: "styles", label: "styles.css" },
  { value: "logo", label: "logo.svg" },
]

function Example() {
  const log = useLog()

  return (
    <Listbox
      multiple
      activation="automatic"
      defaultValue={["readme"]}
      onValueChange={(value, details) =>
        log(`${value.length} selected (${details.reason})`)
      }
      aria-label="Files"
    >
      <For each={files}>
        {(file) => (
          <ListboxItem value={file.value}>
            <ListboxItemIcon>
              <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 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
                <path d="M14 2v5a1 1 0 0 0 1 1h5" />
              </svg>
            </ListboxItemIcon>
            {file.label}
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
选择 index.ts 来替换选择。按住 Ctrl 或 Cmd 再选择另一个文件可以添加它;Shift 会选择范围。

手动激活

在单选列表上设置 activation="manual",可以只浏览而不选择。Space、Enter 或按压会选择获得焦点的选项。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()

  return (
    <Listbox
      activation="manual"
      onValueChange={(value, details) =>
        log(`${value ?? "Nothing"} (${details.reason})`)
      }
      aria-label="Framework"
    >
      <For each={frameworks}>
        {(framework) => (
          <ListboxItem value={framework.value}>
            {framework.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
用方向键在选项之间移动。在你按 Space 或 Enter 之前不会选中任何内容,控制台会记录你的选择。

焦点留在列表上

设置 virtualFocus,让焦点留在列表本身,由方向键、Home、End 和输入在选项之间移动高亮。列表用 aria-activedescendant 指向高亮的选项,所以屏幕阅读器仍会播报它。用 [data-highlighted] 设置高亮的样式,因为选项不会获得焦点。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()

  return (
    <Listbox
      activation="manual"
      virtualFocus
      onValueChange={(value, details) =>
        log(`${value ?? "Nothing"} (${details.reason})`)
      }
      aria-label="Framework"
    >
      <For each={frameworks}>
        {(framework) => (
          <ListboxItem value={framework.value}>
            {framework.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
按 Tab 进入列表,用方向键在其中移动。焦点留在列表上,Space 或 Enter 选择高亮的选项。

可取消选择

添加 deselectable,按压已选中的选项就能清除单选。不加时,选择保持不变。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()

  return (
    <Listbox
      deselectable
      defaultValue="astro"
      onValueChange={(value, details) =>
        log(`${value ?? "Nothing"} (${details.reason})`)
      }
      aria-label="Framework"
    >
      <For each={frameworks}>
        {(framework) => (
          <ListboxItem value={framework.value}>
            {framework.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
再次按压 Astro 清除选择,或选择另一个框架。控制台会记录每次变更。

分组

用 ListboxGroup 和 ListboxGroupLabel 为分组命名。方向键和范围会跨分组继续。分隔符不会进入无障碍树。

import {
  Listbox,
  ListboxGroup,
  ListboxGroupLabel,
  ListboxItem,
  ListboxItemIndicator,
  ListboxSeparator,
} from "@ui-sdk/solid/listbox"
import { For, Show } from "solid-js"

const produce = [
  {
    label: "Fruits",
    items: [
      { value: "apple", label: "Apple" },
      { value: "banana", label: "Banana" },
      { value: "orange", label: "Orange" },
    ],
  },
  {
    label: "Vegetables",
    items: [
      { value: "carrot", label: "Carrot" },
      { value: "broccoli", label: "Broccoli" },
      { value: "spinach", label: "Spinach" },
    ],
  },
]

function Example() {
  return (
    <Listbox multiple defaultValue={["banana"]} aria-label="Produce">
      <For each={produce}>
        {(group, index) => (
          <>
            <Show when={index() > 0}>
              <ListboxSeparator />
            </Show>
            <ListboxGroup>
              <ListboxGroupLabel>{group.label}</ListboxGroupLabel>
              <For each={group.items}>
                {(item) => (
                  <ListboxItem value={item.value}>
                    {item.label}
                    <ListboxItemIndicator>
                      <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>
                    </ListboxItemIndicator>
                  </ListboxItem>
                )}
              </For>
            </ListboxGroup>
          </>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
从 Apple 开始用 Down Arrow 在列表中移动。导航会继续进入 Vegetables 分组。

图标

把图标包进 ListboxItemIcon,屏幕阅读器和键入查找会跳过它。给方向性图标加上 mirror,它会在从右到左(RTL)的文本中翻转。

import { Listbox, ListboxItem, ListboxItemIcon } from "@ui-sdk/solid/listbox"
import { For } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const Mail = icon(
  '<path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7" /><rect x="2" y="4" width="20" height="16" rx="2" />'
)
const Star = icon(
  '<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />'
)
const Pencil = icon(
  '<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" /><path d="m15 5 4 4" />'
)
const Archive = icon(
  '<rect width="20" height="5" x="2" y="3" rx="1" /><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" /><path d="M10 12h4" />'
)
const ArrowRight = icon('<path d="M5 12h14" /><path d="m12 5 7 7-7 7" />')

const views = [
  { value: "inbox", label: "Inbox", icon: Mail },
  { value: "starred", label: "Starred", icon: Star },
  { value: "drafts", label: "Drafts", icon: Pencil },
  { value: "archive", label: "Archive", icon: Archive },
  { value: "next", label: "Next page", icon: ArrowRight },
]

function Example() {
  return (
    <Listbox defaultValue="inbox" aria-label="Mailbox">
      <For each={views}>
        {(view) => (
          <ListboxItem value={view.value}>
            <ListboxItemIcon mirror={view.icon === ArrowRight}>
              <view.icon />
            </ListboxItemIcon>
            {view.label}
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
选择 Drafts。图标不属于选项的无障碍名称,也不参与键入查找匹配的文字。

横向

设置 orientation="horizontal",用 Left Arrow 和 Right Arrow 移动。方向键通常会绕回;像这个示例一样设置 loop={false} 就会在两端停住。Shift 范围永远不会绕回。

列表从页面或祖先元素读取 dir="rtl",所以在从右到左的文本中,Left Arrow 会移动到下一个选项。

import { Listbox, ListboxItem } from "@ui-sdk/solid/listbox"
import { For } from "solid-js"

const sizes = [
  { value: "xs", label: "XS" },
  { value: "s", label: "S" },
  { value: "m", label: "M" },
  { value: "l", label: "L" },
  { value: "xl", label: "XL", disabled: true },
]

function Example() {
  return (
    <Listbox
      orientation="horizontal"
      loop={false}
      defaultValue="m"
      aria-label="Size"
    >
      <For each={sizes}>
        {(size) => (
          <ListboxItem value={size.value} disabled={size.disabled}>
            {size.label}
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
聚焦 M,然后用 Left Arrow 和 Right Arrow 选择尺码。列表会在两端停住;XL 无法被选中。

禁用

禁用的选项无法被选中。方向键、键入查找和范围都会跳过它。禁用整个列表会移除它的 Tab 停靠点,阻止变更,并让它的值不参与表单。

import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { createSignal, For } from "solid-js"

const toppings = [
  { value: "basil", label: "Basil" },
  { value: "cheese", label: "Extra cheese" },
  { value: "mushroom", label: "Mushroom" },
  { value: "olive", label: "Olive" },
  { value: "onion", label: "Onion" },
  { value: "pepper", label: "Pepper" },
]

function Example() {
  const [disabled, setDisabled] = createSignal(false)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => setDisabled(!disabled())}>
          {disabled() ? "Enable the List" : "Disable the List"}
        </button>
      </div>
      <Listbox
        multiple
        disabled={disabled()}
        defaultValue={["basil"]}
        aria-label="Toppings"
      >
        <For each={toppings}>
          {(topping) => (
            <ListboxItem
              value={topping.value}
              disabled={topping.value === "olive"}
            >
              {topping.label}
              <ListboxItemIndicator>
                <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>
              </ListboxItemIndicator>
            </ListboxItem>
          )}
        </For>
      </Listbox>
    </div>
  )
}

export { Example }
试着选择 Olive。然后按 Disable the List,让每个选项都不可用,直到你再次启用它。

只读

当人们应该能浏览列表但不能改变它的值时,使用 readOnly。列表仍然可以获得焦点,它的值仍会提交。

import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"

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

function Example() {
  return (
    <Listbox readOnly defaultValue="nuxt" aria-label="Framework">
      <For each={frameworks}>
        {(framework) => (
          <ListboxItem value={framework.value}>
            {framework.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
在框架之间移动焦点。因为列表是只读的,Nuxt 保持选中。

表单

添加 name 来提交选择。多选会为每个值提交一个条目。重置会恢复 defaultValue,required 在没有选中任何内容时阻止提交。

服务端 HTML 会包含当前选择的隐藏 input,所以这些值能在水合之前提交。

列表可以放在表单之外:像这个示例一样,把 form 设为表单的 ID。禁用的 fieldset 也会禁用列表。表单介绍了共享的集成方式。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const toppings = [
  { value: "basil", label: "Basil" },
  { value: "cheese", label: "Extra cheese" },
  { value: "mushroom", label: "Mushroom" },
  { value: "olive", label: "Olive" },
  { value: "onion", label: "Onion" },
  { value: "pepper", label: "Pepper" },
]

function Example() {
  const log = useLog()

  return (
    <div data-slot="stack">
      <Listbox
        multiple
        name="toppings"
        form="pizza-order"
        required
        defaultValue={["cheese"]}
        aria-label="Toppings"
      >
        <For each={toppings}>
          {(topping) => (
            <ListboxItem value={topping.value}>
              {topping.label}
              <ListboxItemIndicator>
                <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>
              </ListboxItemIndicator>
            </ListboxItem>
          )}
        </For>
      </Listbox>
      <form
        id="pizza-order"
        data-slot="row"
        onSubmit={(event) => {
          event.preventDefault()
          log(
            `Ordered ${new FormData(event.currentTarget).getAll("toppings").join(", ")}`
          )
        }}
      >
        <button type="reset">Reset</button>
        <button data-variant="solid">Order</button>
      </form>
    </div>
  )
}

export { Example }
选择 Basil 并按 Order:控制台会记录两种配料。重置会恢复 Extra cheese;清空每个选项后,必填的列表会阻止下单。

对象值

当选择需要携带 ID 之外的信息时,把对象作为选项的值传入。itemToValue 提供用于标识和表单提交的字符串;isItemEqualToValue 匹配表示同一个选项但实例不同的对象。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
  type ListData,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const plans = [
  { value: { id: "hobby", price: 0 }, label: "Hobby" },
  { value: { id: "pro", price: 20 }, label: "Pro" },
  { value: { id: "team", price: 50 }, label: "Team" },
  {
    value: { id: "enterprise", price: 200 },
    label: "Enterprise",
    disabled: true,
  },
] satisfies ListData<{ id: string; price: number }>

function Example() {
  const log = useLog()

  return (
    <Listbox
      items={plans}
      defaultValue={plans[1].value}
      onValueChange={(plan) =>
        log(plan ? `${plan.id}, $${plan.price} a month` : "No plan")
      }
      itemToValue={(plan) => plan.id}
      isItemEqualToValue={(plan, selected) => plan.id === selected.id}
      aria-label="Plan"
    >
      <For each={plans}>
        {(plan) => (
          <ListboxItem value={plan.value} disabled={plan.disabled}>
            {plan.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
选择 Team。控制台会记录选中对象里的价格,而不是它字符串 ID 里的价格。

items 以数据形式提供整个集合,也可以替你渲染选项。若要让标记和类名保持显式,就按示例那样把数据映射成部件。用 ListData<T> 为对象值的数据标注类型。列表与菜单介绍了共享的数据格式。

控制器

控制器可以选中所有选项、清除选择,或从另一个控件聚焦列表。用 createListboxController() 创建一个,并作为 controller 传入。控制器介绍了设置和生命周期。

控制台
import {
  createListboxController,
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const toppings = [
  { value: "basil", label: "Basil" },
  { value: "cheese", label: "Extra cheese" },
  { value: "mushroom", label: "Mushroom" },
  { value: "olive", label: "Olive" },
  { value: "onion", label: "Onion" },
  { value: "pepper", label: "Pepper" },
]

function Example() {
  const log = useLog()
  const controller = createListboxController<string, true>()

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => controller.selectAll()}>
          Select All
        </button>
        <button type="button" onClick={() => controller.clear()}>
          Clear
        </button>
        <button type="button" onClick={() => controller.focus()}>
          Focus
        </button>
      </div>
      <Listbox
        multiple
        controller={controller}
        onValueChange={(value, details) =>
          log(`${value.length} selected (${details.reason})`)
        }
        aria-label="Toppings"
      >
        <For each={toppings}>
          {(topping) => (
            <ListboxItem value={topping.value}>
              {topping.label}
              <ListboxItemIndicator>
                <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>
              </ListboxItemIndicator>
            </ListboxItem>
          )}
        </For>
      </Listbox>
    </div>
  )
}

export { Example }
按 Select All、Clear 和 Focus。每个按钮都通过控制器驱动同一个列表,控制台会记录变更。

可滚动

给长列表一个最大高度和 overflow-y: auto。它一开始会滚动到选中的选项,但不获取焦点。键盘导航会把获得焦点的选项带入视图,而不滚动页面。

控制台
import {
  Listbox,
  ListboxItem,
  ListboxItemIndicator,
} from "@ui-sdk/solid/listbox"
import { For } from "solid-js"
import { useLog } from "./log"

const timezones = Array.from({ length: 27 }, (_, index) => {
  const offset = index - 12
  const label = `UTC${offset < 0 ? "−" : "+"}${String(Math.abs(offset)).padStart(2, "0")}:00`
  return { value: `utc${offset}`, label }
})

function Example() {
  const log = useLog()

  return (
    <Listbox
      defaultValue="utc9"
      onHighlight={(value, details) =>
        value &&
        log(
          `Focused ${timezones[details.index].label} (${details.index + 1} of ${timezones.length})`
        )
      }
      aria-label="Time zone"
    >
      <For each={timezones}>
        {(zone, index) => (
          <ListboxItem value={zone.value} index={index()}>
            {zone.label}
            <ListboxItemIndicator>
              <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>
            </ListboxItemIndicator>
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
聚焦列表并使用方向键。选项会滚动到视图中,控制台会记录获得焦点的时区。

对于虚拟化列表,提供 items,让键入查找知道未挂载的选项。onHighlight 报告获得焦点的值和索引;每个渲染条目的 index 让屏幕阅读器知道它在完整集合中的位置。Select 虚拟化示例展示了同样的数据和滚动方式。

当别的东西负责滚动列表时,设置 keepInView={false},比如用 bindScrollPicker 选取中心选项的转轮。这样按键移动焦点时,列表不会去动滚动位置。

自定义渲染

当选择某个选项应该跳转时,把选项渲染成链接。按压或 Enter 会跟随链接并选中该选项。这个示例使用手动激活,所以方向键只能浏览。

<ListboxItem value="remix" render={(props) => <a {...props} href="#remix" />}>
  Remix
</ListboxItem>
import { Listbox, ListboxItem } from "@ui-sdk/solid/listbox"
import { For, Show } from "solid-js"

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

function Example() {
  return (
    <Listbox
      defaultValue="next"
      activation="manual"
      aria-label="Framework docs"
    >
      <For each={frameworks}>
        {(framework) => (
          <ListboxItem
            value={framework.value}
            label={framework.label}
            render={(props) => <a {...props} href={`#${framework.value}`} />}
          >
            {(state) => (
              <>
                <span>{framework.label}</span>
                <Show when={state.selected}>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M15 3h6v6" />
                    <path d="M10 14 21 3" />
                    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                  </svg>
                </Show>
              </>
            )}
          </ListboxItem>
        )}
      </For>
    </Listbox>
  )
}

export { Example }
聚焦 Remix 并按 Enter,或用指针选择它。选项会被选中,它的链接会更新 URL 的 hash。

部件与组合介绍了共享的渲染 API。每个部件的状态列在下面。

样式

用 data-selected 表示选中,用 data-highlighted 表示焦点。当选择不跟随焦点时,它们可能描述不同的选项。禁用和只读状态各有自己的属性。

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

数据属性

ListboxGroup、ListboxGroupLabel 和 ListboxSeparator 没有状态属性。

Listbox

[data-slot="listbox"]

属性含义
data-orientationverticalhorizontalWhich arrow keys move between items.
data-disabledPresent when the listbox is disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the listbox is read-only.
data-requiredPresent when the listbox is required.
data-has-iconsPresent while any item inside holds an icon part, so items without one can line up.

ListboxItem

[data-slot="listbox-item"]

属性含义
data-selectedPresent on selected items, and on the check inside them.
data-disabledPresent when the item can't be chosen. It can still be focused.
data-highlightedPresent on the item that has focus.
data-has-iconPresent on an item while it holds an icon part.

ListboxItemIndicator

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

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

ListboxItemIcon

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

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

API 参考

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

Listbox

activation?"automatic" | "manual"
Whether the selection follows focus. "automatic": arrow keys, Home, End and typing select the option they move to, and with multiple a press replaces the selection while Ctrl or ⌘ adds to it, like a native multiple select. "manual": keys only move focus, and Space, Enter or a press selects, or toggles with multiple.
deselectable?boolean
Whether pressing the selected item of a single listbox unselects it, so nothing is selected.
orientation?"horizontal" | "vertical"
Which arrow keys move between items. Horizontal lists use Left and Right, swapped in right-to-left text.
loop?boolean
Whether arrow keys wrap from the last item to the first. Shift with an arrow never wraps.
virtualFocus?boolean
Keeps focus on the list itself, which points at the highlighted option with aria-activedescendant, instead of moving focus onto the options.
keepInView?boolean
Whether the list scrolls the option keys move to into view, and the selected option when it first shows. Turn it off when something else scrolls the list, like bindScrollPicker.
items?ListData<T>
The items as data. Renders them for you, and lets typing find items a virtualized list hasn't rendered.
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.
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 focus moves to another item, with its index among the items, so a virtualized list can scroll to it.
disabled?boolean
Disables the listbox like a native control: its items can't be focused or chosen, and the value isn't submitted.
readOnly?boolean
Keeps the listbox 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 listbox submits nothing.
form?string
The id of a form to belong to, when the listbox isn't inside that form.
controller?object
Reads and sets the listbox from anywhere. Create one with createListboxController().
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, Shift selects ranges, and Ctrl or ⌘ with A selects every item. Whether several items can be selected.
value?T | T[] | null
The selected value. Pass it to control the listbox. null selects nothing. The selected values. Pass it to control the listbox. The selected value, or values with multiple. Pass it to control the listbox.
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.

ListboxItem

valueT
What the value becomes when the item is chosen. A string, or any value with itemToValue.
label?string
The text 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. Arrow keys, typing and ranges 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.

ListboxItemIndicator

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.

ListboxItemIcon

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.

ListboxGroup、ListboxGroupLabel 和 ListboxSeparator 没有自己的 props。

状态

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

Listbox:

multipleboolean | undefined
Whether several items can be selected.
orientation"horizontal" | "vertical"
Which arrow keys move between items.
disabledboolean
Whether the listbox is disabled, by itself, a Field or a <fieldset>.
readOnlyboolean
Whether the listbox keeps its value but refuses changes, from its readOnly option. A form reset still restores it.
requiredboolean
Whether a value is required.
itemsListData<unknown>
The data items, for rendering a virtualized list yourself. Empty without items.

ListboxItem:

highlightedboolean
Whether the item has focus.
selectedboolean
Whether its value is in the listbox's value, compared with isItemEqualToValue when you pass one.
disabledboolean
Whether the item can't be chosen, by itself or a disabled listbox.

ListboxItemIndicator:

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

原因

details.reason 说明值为什么变化:按压、Space 或 Enter 是 item-press;移动时顺带选择的按键、带方向键的 Shift 范围以及 Ctrl 或 ⌘ 加 A 是 list-navigation;来自表单的是 reset 和 restore;来自控制器的是 imperative。

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

控制器

用 createListboxController() 创建一个,并作为 controller 传入。

每个写入方法都接受一个可选的 { reason, event },传给 onValueChange。

getValue()() => ListboxValue<T, Multiple>
The selected value.
setValue(value, options?)(value: ListboxValue<T, Multiple>, options?: ListboxChangeOptions | undefined) => boolean
Selects a value, as a user would. A disabled or read-only listbox ignores it. Returns false when the change was canceled or nothing changed.
clear(options?)(options?: ListboxChangeOptions | undefined) => boolean
Selects nothing: null, or an empty list with multiple. Returns false when the change was canceled or nothing changed.
selectAll(options?)(options?: ListboxChangeOptions | undefined) => boolean
Selects every enabled item, with multiple. Returns false when the change was canceled or nothing changed.
getHighlighted()() => T | null
The value of the highlighted option, or null when none is, like while focus is outside the list.
highlight(value)(value: T | null) => boolean
Highlights the option with this value, scrolled into view, or none with null. While focus is outside the list, the option takes the tab stop instead, so focus lands on it next. Returns false when no enabled option has the value.
focus()() => void
Moves focus into the list, onto the option that holds its tab stop.

事件

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

属性所属收到
onValueChangeListbox(value, details):新值,以及原因
onHighlightListbox(value, details):获得焦点的选项的值,以及它的索引

无障碍

遵循 WAI-ARIA 列表框模式,多选时两种键盘模型都支持。选项会获得真实的焦点,整组只有一个游走的 Tab 停靠点。每个选项都会说明自己是否被选中。

焦点

整个列表是一个 Tab 停靠点。Tab 会回到最后聚焦的选项,若没有则回退到第一个选中或已启用的选项。选项获得真实的 DOM 焦点,所以 focus-visible 直接可用。使用 virtualFocus 时,列表本身是 Tab 停靠点并保持焦点。

根部件会把焦点转进选项,包括在按 Field 的标签或列表的内边距时。Escape 仍留给外层对话框使用。

经过测试的行为

下面每一行都是一个自动化测试。

Focus
  • Tab lands on the first option when nothing is selected.
  • Tab lands on the selected option.
  • Tab lands on the first selected option with multiple.
  • The list is one tab stop: Tab leaves it from any option.
  • Shift+Tab back into the list returns to the option focused last.
  • A press focuses the option.
  • Arrow keys skip disabled options.
  • A disabled option can't be chosen.
  • Arrow keys from a pressed disabled option move to the enabled ones around it.
  • Tab lands on the first enabled option when the selected one is disabled.
Single selection
  • Arrow keys move focus and the selection follows.
  • Home and End move to the first and last option.
  • Arrow keys wrap from the last option to the first.
  • With loop off, arrow keys stop at the ends.
  • A press selects the option.
  • Pressing the selected option keeps it selected.
  • With deselectable, pressing the selected option unselects it.
  • With manual activation, arrows only move focus and Space selects.
  • Typing moves focus to the next option that starts with it, and selects it.
  • Typing several letters finds the option that starts with them.
  • Escape leaves the selection alone.
Multiple selection
  • Presses and Space toggle options.
  • Arrow keys move focus without changing the selection.
  • Shift with a press selects the range from the last option chosen.
  • Shift with an arrow passes over a disabled option.
  • A range skips disabled options.
  • A second Shift press changes the range, keeping what was selected before it.
  • Shift with an arrow key moves focus and extends the selection.
  • Shift with Space selects from the last option chosen to the focused one.
  • Ctrl+Shift+End selects from the focused option to the last.
  • Ctrl+Shift+Home selects from the focused option to the first.
  • Ctrl+A selects every enabled option, and again unselects them.
  • Ctrl+A does nothing in a single listbox.
  • Typing moves focus without selecting.
Multiple selection with automatic activation
  • A press replaces the selection.
  • Ctrl or Cmd with a press adds an option, and removes it again.
  • Shift with a press replaces the selection with a range.
  • Arrow keys select the option they move to.
  • Ctrl or Cmd with an arrow moves focus only, and with Space toggles.
  • Shift with an arrow key extends the selection.
Horizontal
  • Left and Right move between options, and Up and Down don't.
Groups
  • Arrow keys move across groups, skipping their labels.
  • A range crosses groups.
Form
  • Submits the selected value under its name.
  • Submits each value with multiple.
  • A reset returns to the default value.
  • Required blocks submission until a value is selected.
  • A disabled listbox can't be focused or changed, and submits nothing.
  • A disabled fieldset disables the listbox.
  • A read-only listbox can be browsed but not changed, and submits.
Changes
  • A canceled change keeps the selection.
  • A controlled listbox shows the value it's given.
  • The controller clears and selects everything.

运行于 React、Vue 和 web components。

模式之外:

  • Keys pressed with no waits between them all land.
  • Escape leaves the selection alone and reaches a dialog around the list.
  • A Shift press after the selection was cleared starts a new range there.
  • Shift with an arrow never wraps past the end.
  • A Shift press doesn't select the page's text.
  • The selected option scrolls into view without taking focus.
  • Arrow keys keep the focused option clear of the list's scroll padding at both ends.
  • The selected option scrolls into view clear of the list's scroll padding.
  • A focused option that leaves the list hands focus back to it, so keys keep working.
  • Options that all leave take the tab stop with them, and options that come back hold it again.
  • Options the app reorders keep their place in the keys.
  • A press on the list's padding gives focus to the option that holds the tab stop.
Touch
  • Taps toggle where clicks replace, since touch has no modifier keys.
Focus on the list
  • With virtualFocus, keys move the highlight while focus stays on the list, which points at it.
  • With virtualFocus, a press chooses an option and keeps focus on the list.

运行于 React、Vue 和 web components。

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

  • Announcements while choosing one option with a keyboard.
  • Announcements while choosing several options with a keyboard.

运行于 React、Vue 和 web components。