# Listbox

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

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

```svelte title="basic.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"

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

<Field>
  <FieldLabel>Email me about</FieldLabel>
  <Listbox multiple activation="automatic" defaultValue={["mentions"]}>
    {#each topics as topic (topic.value)}
      <ListboxItem value={topic.value}>
        {topic.label}
        <ListboxItemIndicator>
          <CheckIcon aria-hidden="true" />
        </ListboxItemIndicator>
      </ListboxItem>
    {/each}
  </Listbox>
  <FieldDescription
    >Hold Shift to select a range, or Ctrl or ⌘ to add one.</FieldDescription
  >
</Field>
```

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

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

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

```text
Listbox
├── ListboxItem
│   └── ListboxItemIndicator
└── ListboxItem
    └── ListboxItemIndicator
```

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

也可以用 [Field](/docs/svelte/components/field) 的标签或 `aria-labelledby` 为列表命名。按钮、搜索字段和空状态消息要留在列表之外：列表内容应该是选项、分组和分隔符。

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

```svelte
<script lang="ts">
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
</script>

<Listbox aria-label="Toppings" defaultValue="basil">
  <ListboxItem value="basil">
    Basil
    <ListboxItemIndicator>✓</ListboxItemIndicator>
  </ListboxItem>
  <ListboxItem value="olive">
    Olive
    <ListboxItemIndicator>✓</ListboxItemIndicator>
  </ListboxItem>
</Listbox>
```

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

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

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

```svelte title="multiple.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<Listbox
  multiple
  defaultValue={["cheese", "onion"]}
  onValueChange={(value, details) =>
    log(`${value.join(", ") || "Nothing"} (${details.reason})`)}
  aria-label="Toppings"
>
  {#each toppings as topping (topping.value)}
    <ListboxItem value={topping.value}>
      {topping.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

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

```svelte
<Listbox multiple activation="automatic" aria-label="Files" />
```

```svelte title="activation.svelte"
<script lang="ts">
  import { FileIcon } from "@lucide/svelte"
  import { Listbox, ListboxItem, ListboxItemIcon } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<Listbox
  multiple
  activation="automatic"
  defaultValue={["readme"]}
  onValueChange={(value, details) =>
    log(`${value.length} selected (${details.reason})`)}
  aria-label="Files"
>
  {#each files as file (file.value)}
    <ListboxItem value={file.value}>
      <ListboxItemIcon>
        <FileIcon aria-hidden="true" />
      </ListboxItemIcon>
      {file.label}
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

```svelte title="manual.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<Listbox
  activation="manual"
  onValueChange={(value, details) =>
    log(`${value ?? "Nothing"} (${details.reason})`)}
  aria-label="Framework"
>
  {#each frameworks as framework (framework.value)}
    <ListboxItem value={framework.value}>
      {framework.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

```svelte title="virtual-focus.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<Listbox
  activation="manual"
  virtualFocus
  onValueChange={(value, details) =>
    log(`${value ?? "Nothing"} (${details.reason})`)}
  aria-label="Framework"
>
  {#each frameworks as framework (framework.value)}
    <ListboxItem value={framework.value}>
      {framework.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

## 可取消选择
添加 `deselectable`，按压已选中的选项就能清除单选。不加时，选择保持不变。

```svelte title="deselectable.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<Listbox
  deselectable
  defaultValue="astro"
  onValueChange={(value, details) =>
    log(`${value ?? "Nothing"} (${details.reason})`)}
  aria-label="Framework"
>
  {#each frameworks as framework (framework.value)}
    <ListboxItem value={framework.value}>
      {framework.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

```svelte title="groups.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxGroup,
    ListboxGroupLabel,
    ListboxItem,
    ListboxItemIndicator,
    ListboxSeparator,
  } from "@ui-sdk/svelte/listbox"

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

<Listbox multiple defaultValue={["banana"]} aria-label="Produce">
  {#each produce as group, index (group.label)}
    {#if index > 0}
      <ListboxSeparator />
    {/if}
    <ListboxGroup>
      <ListboxGroupLabel>{group.label}</ListboxGroupLabel>
      {#each group.items as item (item.value)}
        <ListboxItem value={item.value}>
          {item.label}
          <ListboxItemIndicator>
            <CheckIcon aria-hidden="true" />
          </ListboxItemIndicator>
        </ListboxItem>
      {/each}
    </ListboxGroup>
  {/each}
</Listbox>
```

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

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

```svelte title="icons.svelte"
<script lang="ts">
  import {
    ArchiveIcon,
    ArrowRightIcon,
    MailIcon,
    PencilIcon,
    StarIcon,
  } from "@lucide/svelte"
  import { Listbox, ListboxItem, ListboxItemIcon } from "@ui-sdk/svelte/listbox"

  const views = [
    { value: "inbox", label: "Inbox", icon: MailIcon },
    { value: "starred", label: "Starred", icon: StarIcon },
    { value: "drafts", label: "Drafts", icon: PencilIcon },
    { value: "archive", label: "Archive", icon: ArchiveIcon },
    { value: "next", label: "Next page", icon: ArrowRightIcon },
  ]
</script>

<Listbox defaultValue="inbox" aria-label="Mailbox">
  {#each views as view (view.value)}
    <ListboxItem value={view.value}>
      <ListboxItemIcon mirror={view.icon === ArrowRightIcon}>
        <view.icon />
      </ListboxItemIcon>
      {view.label}
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

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

```svelte title="horizontal.svelte"
<script lang="ts">
  import { Listbox, ListboxItem } from "@ui-sdk/svelte/listbox"

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

<Listbox
  orientation="horizontal"
  loop={false}
  defaultValue="m"
  aria-label="Size"
>
  {#each sizes as size (size.value)}
    <ListboxItem value={size.value} disabled={size.disabled}>
      {size.label}
    </ListboxItem>
  {/each}
</Listbox>
```

聚焦 M，然后用 Left Arrow 和 Right Arrow 选择尺码。列表会在两端停住；XL 无法被选中。

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

```svelte title="disabled.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"

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

  let disabled = $state(false)
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => (disabled = !disabled)}>
      {disabled ? "Enable the List" : "Disable the List"}
    </button>
  </div>
  <Listbox multiple {disabled} defaultValue={["basil"]} aria-label="Toppings">
    {#each toppings as topping (topping.value)}
      <ListboxItem value={topping.value} disabled={topping.value === "olive"}>
        {topping.label}
        <ListboxItemIndicator>
          <CheckIcon aria-hidden="true" />
        </ListboxItemIndicator>
      </ListboxItem>
    {/each}
  </Listbox>
</div>
```

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

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

```svelte title="read-only.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"

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

<Listbox readOnly defaultValue="nuxt" aria-label="Framework">
  {#each frameworks as framework (framework.value)}
    <ListboxItem value={framework.value}>
      {framework.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

在框架之间移动焦点。因为列表是只读的，Nuxt 保持选中。

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

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

列表可以放在表单之外：像这个示例一样，把 `form` 设为表单的 ID。禁用的 fieldset 也会禁用列表。[表单](/docs/svelte/forms)介绍了共享的集成方式。

```svelte title="form.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
</script>

<div data-slot="stack">
  <Listbox
    multiple
    name="toppings"
    form="pizza-order"
    required
    defaultValue={["cheese"]}
    aria-label="Toppings"
  >
    {#each toppings as topping (topping.value)}
      <ListboxItem value={topping.value}>
        {topping.label}
        <ListboxItemIndicator>
          <CheckIcon aria-hidden="true" />
        </ListboxItemIndicator>
      </ListboxItem>
    {/each}
  </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>
```

选择 Basil 并按 Order：控制台会记录两种配料。重置会恢复 Extra cheese；清空每个选项后，必填的列表会阻止下单。

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

```svelte title="data.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
    type ListData,
  } from "@ui-sdk/svelte/listbox"
  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 }>

  const log = useLog()
</script>

<Listbox
  items={plans}
  defaultValue={plans[1].value}
  onValueChange={(plan: { id: string; price: number } | null) =>
    log(plan ? `${plan.id}, $${plan.price} a month` : "No plan")}
  itemToValue={(plan: { id: string }) => plan.id}
  isItemEqualToValue={(plan: { id: string }, selected: { id: string }) =>
    plan.id === selected.id}
  aria-label="Plan"
>
  {#each plans as plan (plan.value.id)}
    <ListboxItem value={plan.value} disabled={plan.disabled}>
      {plan.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

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

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

```svelte title="controller.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    createListboxController,
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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" },
  ]

  const log = useLog()
  const controller = createListboxController<string, true>()
</script>

<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}
    onValueChange={(value, details) =>
      log(`${value.length} selected (${details.reason})`)}
    aria-label="Toppings"
  >
    {#each toppings as topping (topping.value)}
      <ListboxItem value={topping.value}>
        {topping.label}
        <ListboxItemIndicator>
          <CheckIcon aria-hidden="true" />
        </ListboxItemIndicator>
      </ListboxItem>
    {/each}
  </Listbox>
</div>
```

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

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

```svelte title="scrollable.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Listbox,
    ListboxItem,
    ListboxItemIndicator,
  } from "@ui-sdk/svelte/listbox"
  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 }
  })

  const log = useLog()
</script>

<Listbox
  defaultValue="utc9"
  onHighlight={(value, details) => {
    if (value) {
      log(
        `Focused ${timezones[details.index].label} (${details.index + 1} of ${timezones.length})`
      )
    }
  }}
  aria-label="Time zone"
>
  {#each timezones as zone, index (zone.value)}
    <ListboxItem value={zone.value} {index}>
      {zone.label}
      <ListboxItemIndicator>
        <CheckIcon aria-hidden="true" />
      </ListboxItemIndicator>
    </ListboxItem>
  {/each}
</Listbox>
```

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

对于虚拟化列表，提供 `items`，让键入查找知道未挂载的选项。`onHighlight` 报告获得焦点的值和索引；每个渲染条目的 `index` 让屏幕阅读器知道它在完整集合中的位置。[Select 虚拟化示例](https://ui-sdk.cn/docs/svelte/components/select#virtualized)展示了同样的数据和滚动方式。

当别的东西负责滚动列表时，设置 `keepInView={false}`，比如用 [`bindScrollPicker`](https://ui-sdk.cn/docs/core/behaviors/lists#wheels-you-scroll-to-pick-from) 选取中心选项的转轮。这样按键移动焦点时，列表不会去动滚动位置。

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

```svelte
<ListboxItem value="remix">
  {#snippet render({ props })}
    <a {...props} href="#remix">Remix</a>
  {/snippet}
</ListboxItem>
```

```svelte title="render.svelte"
<script lang="ts">
  import { ExternalLinkIcon } from "@lucide/svelte"
  import { Listbox, ListboxItem } from "@ui-sdk/svelte/listbox"

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

<Listbox defaultValue="next" activation="manual" aria-label="Framework docs">
  {#each frameworks as framework (framework.value)}
    <ListboxItem value={framework.value} label={framework.label}>
      {#snippet render({ props, state })}
        <a {...props} href={`#${framework.value}`}>
          <span>{framework.label}</span>
          {#if state.selected}
            <ExternalLinkIcon aria-hidden="true" />
          {/if}
        </a>
      {/snippet}
    </ListboxItem>
  {/each}
</Listbox>
```

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

[部件与组合](/docs/svelte/parts-and-composition)介绍了共享的渲染 API。每个部件的状态列在[下面](https://ui-sdk.cn/docs/svelte/components/listbox#state)。

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

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

## 数据属性
`ListboxGroup`、`ListboxGroupLabel` 和 `ListboxSeparator` 没有状态属性。

### Listbox
`[data-slot="listbox"]`

- `data-orientation` (`vertical`, `horizontal`): Which arrow keys move between items.
- `data-disabled`: Present when the listbox is disabled, by its own prop, a Field or a `<fieldset>`.
- `data-readonly`: Present when the listbox is read-only.
- `data-required`: Present when the listbox is required.
- `data-has-icons`: Present while any item inside holds an icon part, so items without one can line up.

### ListboxItem
`[data-slot="listbox-item"]`

- `data-selected`: Present on selected items, and on the check inside them.
- `data-disabled`: Present when the item can't be chosen. It can still be focused.
- `data-highlighted`: Present on the item that has focus.
- `data-has-icon`: Present on an item while it holds an icon part.

### ListboxItemIndicator
`[data-slot="listbox-item-indicator"]`

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

### ListboxItemIcon
`[data-slot="listbox-item-icon"]`

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

## API 参考
属性和回调与下面相同，都作为 Svelte props。`value` 可以用 `bind:value` 绑定。

### 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
- `value` (`T`): 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`:

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

`ListboxItem`:

- `highlighted` (`boolean`): Whether the item has focus.
- `selected` (`boolean`): Whether its value is in the listbox's value, compared with `isItemEqualToValue` when you pass one.
- `disabled` (`boolean`): Whether the item can't be chosen, by itself or a disabled listbox.

`ListboxItemIndicator`:

- `selected` (`boolean`): 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-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `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.

### 事件
回调先收到新值，然后收到详情。绑定的 `value` 只在 `onValueChange` 未被取消时更新。

| 属性            | 所属      | 收到                                                 |
| --------------- | --------- | ---------------------------------------------------- |
| `bind:value`    | `Listbox` | 选中的值                                             |
| `onValueChange` | `Listbox` | `(value, details)`：新值，以及[原因](https://ui-sdk.cn/docs/svelte/components/listbox#reasons)       |
| `onHighlight`   | `Listbox` | `(value, details)`：获得焦点的选项的值，以及它的索引 |

## 无障碍
遵循 [WAI-ARIA 列表框模式](https://www.w3.org/WAI/ARIA/apg/patterns/listbox/)，多选时两种键盘模型都支持。选项会获得真实的焦点，整组只有一个游走的 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.

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

Runs in React、Vue 和 web components.

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

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

Runs in React、Vue 和 web components.
