# 列表

搜索选项列表、渲染长列表、跟随新消息、滚动选取，以及就地编辑值。

用 `createListbox` 处理可以移动和搜索的选项，用 `createVirtualizer` 处理长列表，用 `createStickToBottom` 处理聊天和日志，用 `bindScrollPicker` 处理滚动选取的转轮，用 `createInlineEdit` 处理可编辑的标签。

每个辅助函数都可以单独工作，也可以在组件里与 [焦点](https://ui-sdk.cn/docs/core/behaviors/focus#grids) 和 [选择](/docs/core/behaviors/selection) 配合使用。

## 可以搜索的选项
### 在选项之间移动
`createListbox` 保持一个选项高亮，并用方向键移动高亮，就像列表框或组合框那样。在状态里保留高亮选项的键，初始值为 `null`，并在 `api` 中创建这个行为：

```ts
import { createListbox } from "@ui-sdk/core"

const listbox = createListbox(context, {
  key: "highlighted",
  focus: "virtual",
})
```

使用 `focus: "virtual"` 时，焦点留在原处，比如在搜索框里，由输入框把 `aria-activedescendant` 指向高亮的选项。省略 `focus`，高亮则会改为把真实焦点从一个选项移到另一个选项。

每个选项在自己的槽位 `bind` 里接入，`attrs` 给它一个 `id`、`data-highlighted` 和 `aria-disabled`：

```ts
option: slot<{ value: string }>({
  role: "option",
  focus: "active-descendant",
  props: { value: "string" },
  selects: selects({ highlighted: ({ key }) => [key, null] }),
  attrs: (state, part) => ({
    ...part.api.listbox.attrs(state, part),
    "aria-selected": String(state.value === part.key),
  }),
  press: ({ key, api }, event) => api.choose(key, event),
  on: {
    pointerdown: (event) => event.preventDefault(),
    pointermove: (event, { key, api }) => api.listbox.highlight(key, { event }),
  },
  bind: (el, part) => part.api.listbox.bind(el, part),
}),
```

`selects` 让一次移动只到达它离开的选项和它落到的选项。在输入框上，把 `aria-activedescendant` 设为 `api.listbox.activeId(state)`，并把 `keydown` 传给 `api.listbox.keydown(event)`。方向键、PageUp 和 PageDown 移动高亮。使用真实焦点时，Home、End 和输入选项名称也会移动它。越过任一端时会绕回，除非 `loop` 返回 `false`。

选择一个选项由你决定。按 Enter 时，从状态里读取高亮的键，并用 [`createChange`](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes) 写入你的值；如果人们可以选择多个，则用 [`createSelection`](/docs/core/behaviors/selection)。

### 输入时过滤
把用于过滤的文本作为 `query` 传入。在上面这种组合列表里，选项只在匹配时才渲染，所以给选项槽位加上 `present`：

```ts
const listbox = createListbox(context, {
  key: "highlighted",
  focus: "virtual",
  query: () => context.store.get().query,
})
```

```ts
present: (_state, part) => part.api.listbox.shows(part),
```

选项按 `label` 属性匹配；没有 `label` 时按它们的文本匹配，忽略大小写和变音符号。查询变化时，调用 `listbox.move("first")` 高亮最匹配的选项，就像这个搜索：

输入内容来过滤水果。用 Up 和 Down 移动高亮，按 Enter 或点击来选择一个。

`filter` 决定什么算匹配：默认是 `"contains"`，也可以是 `"startsWith"`，或一个返回 `true`、`false` 或分数的函数。分数会给选项排名，最优在前，0 会隐藏某个选项。`listbox.count()` 说明有多少选项匹配，用于一个都没匹配时的提示。

### 以数据形式提供的选项
对于来自数据的选项，把它们作为 `items` 传入：字符串、带 `value` 和 `label` 的条目、分组和分隔符。`listbox.items()` 按顺序返回匹配查询的内容，所以渲染它而不是完整列表：

```ts
const listbox = createListbox(context, {
  key: "highlighted",
  items: () => context.options().items,
  query: () => context.store.get().query,
})
```

传入 `onHighlight` 来获知高亮移动到了哪里，并带上它的索引，供 [虚拟化器](https://ui-sdk.cn/docs/core/behaviors/lists#long-lists) 滚动到；传入 `onEnd`，在到达最后一个选项时加载下一页。

### 选项
- `key` (`keyof State & string`): The state key that holds the highlighted option's key. Start it at `null`. Example: [Move Through the Options](https://ui-sdk.cn/docs/core/behaviors/lists#move-through-the-options).
- `focus?` (`"real" | "virtual"`): `"real"` moves focus to the highlighted option. `"virtual"` keeps it where it is, like in an input that points `aria-activedescendant` at `activeId(state)`. Defaults to `"real"`. Example: [Move Through the Options](https://ui-sdk.cn/docs/core/behaviors/lists#move-through-the-options).
- `items?` (`(() => ListData<T>)`): The options as data: items, plain strings, groups and separators. Without it, the bound parts are the options, in document order. Example: [Options as Data](https://ui-sdk.cn/docs/core/behaviors/lists#options-as-data).
- `query?` (`(() => string)`): The text options are filtered by. Empty shows every option. Example: [Filter as You Type](https://ui-sdk.cn/docs/core/behaviors/lists#filter-as-you-type).
- `filter?` (`(() => ListFilter<T>)`): How `query` narrows the options. A function that returns a number ranks them too, best first. Defaults to `"contains"`. Example: [Filter as You Type](https://ui-sdk.cn/docs/core/behaviors/lists#filter-as-you-type).
- `loop?` (`(() => boolean)`): Whether moving past either end wraps around. Defaults to `true`. Example: [Move Through the Options](https://ui-sdk.cn/docs/core/behaviors/lists#move-through-the-options).
- `onHighlight?` (`((key: string | null, details: ListHighlightDetails) => void)`): Runs when the highlight moves, with the option's index among those that match, for a virtualizer to scroll to. Example: [Options as Data](https://ui-sdk.cn/docs/core/behaviors/lists#options-as-data).
- `onEnd?` (`(() => void)`): Runs when the highlight reaches the last option, so the next page can load. Example: [Options as Data](https://ui-sdk.cn/docs/core/behaviors/lists#options-as-data).

## 长列表
### 只渲染视图内的内容
`createVirtualizer` 告诉你要渲染哪些行，以及把它们放在哪里。先提供行数和以像素为单位的估算高度：

```ts
import { createVirtualizer } from "@ui-sdk/core"

const virtual = createVirtualizer({
  count: () => entries.length,
  estimate: () => 32,
})
```

滚动容器挂载后，连接它并订阅变更：

```ts
const disconnect = virtual.connect(scroller)
const unsubscribe = virtual.subscribe(render)
```

在一个相对定位、高度为 `virtual.size()` 像素的盒子里渲染 `virtual.items()`。每个条目给出它的 `index`、`key`、`start` 和 `size`。把它的元素绝对定位到 `start`，让占满高度的盒子提供滚动条。

滚动浏览账目。计数显示了它的 10,000 行中一次只渲染了多少行。

视图卸载时调用 `disconnect()` 和 `unsubscribe()`。在原语里，从滚动容器槽位的 `bind` 返回 `virtual.connect(el)`。行数或顺序变化后，调用 `virtual.refresh()`。

`items()` 在内容变化之前返回同一个数组，所以它能配合 React 的 `useSyncExternalStore` 这类订阅。给每一行设置 `aria-setsize` 和 `aria-posinset`，或者在网格里使用 `aria-rowcount` 和 `aria-rowindex`，让辅助技术知道它位于完整列表的哪里。

### 任意高度的行
对于会换行的行，先估算它们的高度，渲染之后再测量。给每一行一个稳定的数据键，这样排序时测量出的尺寸会跟着它走：

```ts
const virtual = createVirtualizer({
  count: () => notes.length,
  key: (index) => notes[index].id,
  estimate: () => 52,
  overscan: 2,
})
```

在行槽位里，返回测量的清理函数：

```ts
bind: (el, { api, props }) => api.virtual.measure(props.index, el),
```

`measure` 还会观察之后的尺寸变化。让每个测量绑定与它的索引保持关联；这个演示用索引给渲染的行设键，而虚拟化器按数据键跟踪尺寸。

滚动浏览笔记，然后试试 Newest First 和 Larger Text。行的位置会按测量出的高度调整。

在影响每一行的变更之后，比如更改文字大小，调用 `virtual.reset()` 丢弃缓存的测量值。`overscan` 会在每一端之外多保留几行；默认是四行。固定高度的行可以跳过测量。

### 跳转与加载更多
用 `scrollToIndex` 把某一行带入视图。索引从零开始：

```ts
virtual.scrollToIndex(49, { align: "center" })
virtual.scrollToIndex(79)
```

`align` 可以是 `"start"`、`"center"`、`"end"` 或 `"auto"`。默认值 `"auto"` 只滚动到刚好能显示该行。

试试 Center 50 和 Last。接近末尾时会加载更多联系人。点击一个联系人然后滚开；它聚焦的元素会保持渲染。

对于吸顶的表头，把 `scrollMargin` 设成它的高度。要加载更多，提供 `onEnd`，并可选地提供 `endThreshold`：

```ts
scrollMargin: 32,
onEnd: () => loadMore(),
endThreshold: 5,
keep: () => (focusedIndex === null ? [] : [focusedIndex]),
```

当可见范围接近末尾时，`onEnd` 在每个行数下运行一次。加载之后，更新行数并调用 `refresh()`。`keep()` 添加必须保持渲染的索引，比如持有焦点的那一行。

### 横向
对于横向列表，设置 `horizontal: true`：

```ts
const virtual = createVirtualizer({
  count: () => 365,
  estimate: () => 56,
  horizontal: true,
})
```

现在 `start` 和 `size` 描述横向位置。用一个宽度为 `virtual.size()` 像素的占位元素，并用 `translateX` 定位条目。

横向滚动浏览这些日期。只有可见的日期和附近的几个会被渲染。

### 在页面中查找
在页面中查找（⌘F 或 Ctrl+F）只能看到虚拟化器已渲染的行。用 `findable` 把每一行的文本交给它，并通过可查找层连接，这样它能找到每一行，列表也会滚动到匹配的那一行：

```ts
const virtual = createVirtualizer({
  count: () => invoices.length,
  estimate: () => 36,
  findable: (index) => [invoices[index].id, invoices[index].customer],
})

virtual.connect(scroller, { findable: true })
```

让 `findable` 保持为行所显示的文本，这样无论是否已渲染，行都能以同样的方式被找到。只传值得查找的文本，比如标题而不是时间戳。

然后通过 ref，用 `findableText` 渲染那段文本，每个片段用一个空元素：

**React**

```tsx
<span ref={(el) => virtual.findableText(item.index, el, 0)} />
<span ref={(el) => virtual.findableText(item.index, el, 1)} />
```

**Vue**

```vue
<span
  :ref="(el) => virtual.findableText(item.index, el as HTMLElement | null, 0)"
/>
<span
  :ref="(el) => virtual.findableText(item.index, el as HTMLElement | null, 1)"
/>
```

**Svelte**

```svelte
<span {@attach (el) => virtual.findableText(item.index, el, 0)}></span>
<span {@attach (el) => virtual.findableText(item.index, el, 1)}></span>
```

**Solid**

```tsx
<span ref={(el) => virtual.findableText(item.index, el, 0)} />
<span ref={(el) => virtual.findableText(item.index, el, 1)} />
```

**Web Components**

```ts
const [idText, customerText] = row.querySelectorAll("span")
const off = [
  virtual.findableText(index, idText, 0),
  virtual.findableText(index, customerText, 1),
]
```

离开 `items()` 的行会自己交还它的文本，因此那些不运行 ref 的返回值、而是用 `null` 调用 ref 的框架，行为也一样。

这个元素承载的正是在页面中查找所搜索的文本，所以浏览器会在行本身、用行自己的样式高亮匹配项，并且只计一次。最后一个参数 `part` 在 `findable` 返回多个片段时选择其中一个。

按 ⌘F 或 Ctrl+F，搜索 Acme。查找栏会计入每一张 Acme 发票，无论是否已渲染；按 Enter 逐个浏览，列表会滚动到每一个。

### 它找到的那一行
在页面中查找匹配到的行会在 `items()` 中标记为 `found`，直到下一个匹配、直到它滚出视图，或直到有人在列表里按压或输入。不用 `findableText` 渲染文本的行仍然会滚动到视图中，但浏览器的突出显示无法显示在它上面，所以你自己标记它：

```tsx
<div data-found={item.found ? "" : undefined} className="data-found:bg-neutral-100">
```

### 工作原理
可查找层是两个不占空间的元素，一个在滚动容器的开头，一个在末尾。它们为每一个未渲染的行保存一个替身：一个只包含该行文本的元素，`hidden="until-found"`，在页面中查找可以搜索它，而它不会被渲染出来。

1. **顺序：** 在页面中查找按页面顺序遍历匹配项，所以视图内行上方的那些行的替身放在第一层，其余放在最后一层。已渲染的行在页面中没有替身，所以它们的文本只在显示的位置被找到一次。
2. **匹配项** 会在浏览器滚动到它之前触发替身的 `beforematch`。列表先滚动到该行并渲染它，替身则平铺在该行上方，所以浏览器自己的滚动无事可做。
3. **在下一帧，** 匹配的文本会移入该行的 `findableText` 元素，于是浏览器的突出显示出现在那里，查找栏的 Enter 继续处理它之后的行。没有这些元素的行则改用那个透明的替身，查找栏会把它计两次，直到它滚出视图。
4. **替身分组** 同样带有 `hidden="until-found"`，所以浏览器会跳过它们全部的样式和布局，直到其中一个匹配。

每一行要花费一个替身，以及每个片段一个文本节点，片段之间还有一个空格：单个字符串是两个 DOM 节点，两个片段则是四个。它们几乎不产生布局开销，因为浏览器只布局这些分组。行发生变化后调用 `virtual.refresh()`：它只就地更新变化了的文本，并且只在数量变化时重建替身。

替身的代码在列表第一次带 `findable` 连接时加载，所以没有它的列表不会下载这段代码。

不支持 `hidden="until-found"` 的浏览器不会得到这些层，在页面中查找只能看到屏幕上的行，就像没有 `findable` 一样；`supportsHiddenUntilFound()` 会告诉你。关闭的标签页、手风琴、可折叠区域、树和导航菜单也用同样的方式变得可查找，通过它们的 `hiddenUntilFound` 选项或 [`findableText`](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-on-its-own)；关闭面板里的列表会先打开该面板。

### 选项
- `count` (`() => number`): How many rows the list has. Read on every update, so it can grow, like a list that loads more. Example: [Render What's in View](https://ui-sdk.cn/docs/core/behaviors/lists#render-whats-in-view).
- `estimate` (`(index: number) => number`): The size of a row before it's measured, in pixels. A close guess keeps the scrollbar steady. Example: [Render What's in View](https://ui-sdk.cn/docs/core/behaviors/lists#render-whats-in-view).
- `key?` (`((index: number) => string)`): A stable key for each row, so a measured size follows its row when the list sorts or filters. Defaults to the index. Example: [Rows of Any Height](https://ui-sdk.cn/docs/core/behaviors/lists#rows-of-any-height).
- `overscan?` (`number`): How many rows to render past each edge, so a fast scroll or Tab doesn't show a gap. Example: [Rows of Any Height](https://ui-sdk.cn/docs/core/behaviors/lists#rows-of-any-height).
- `horizontal?` (`boolean`): Whether the list scrolls sideways. Example: [Sideways](https://ui-sdk.cn/docs/core/behaviors/lists#sideways).
- `scrollMargin?` (`number`): Pixels in the scroller before the first row, like a sticky header. Example: [Jumping and Loading More](https://ui-sdk.cn/docs/core/behaviors/lists#jumping-and-loading-more).
- `keep?` (`(() => readonly number[])`): Rows rendered wherever the scroller is, like the one with focus, so scrolling it away doesn't drop focus to the page. Example: [Jumping and Loading More](https://ui-sdk.cn/docs/core/behaviors/lists#jumping-and-loading-more).
- `onEnd?` (`(() => void)`): Runs when the rendered rows come within `endThreshold` rows of the last, to load more. Runs once per `count`, so it doesn't ask again before the list grows. Example: [Jumping and Loading More](https://ui-sdk.cn/docs/core/behaviors/lists#jumping-and-loading-more).
- `endThreshold?` (`number`): How close to the end `onEnd` runs, in rows. Example: [Jumping and Loading More](https://ui-sdk.cn/docs/core/behaviors/lists#jumping-and-loading-more).
- `findable?` (`((index: number) => string | readonly string[])`): The text the browser's find in page should find in a row, like its title, so it finds rows that aren't rendered too. Keep it what the row shows. Return a list of pieces to give each its own `findableText`. Example: [Find in Page](https://ui-sdk.cn/docs/core/behaviors/lists#find-in-page).

## 跟随末尾的日志
### 跟随最新一行
`createStickToBottom` 在读者位于底部时跟随新内容。向上滚动可以让他们阅读而不被拉走：

```ts
import { createStickToBottom } from "@ui-sdk/core"

const stick = createStickToBottom()
const disconnect = stick.connect(scroller)
```

这个辅助函数观察内容尺寸的变化，包括一次只到达一个词的文本。卸载时调用 `disconnect()`，或者从槽位的 `bind` 返回 `stick.connect(el)`。

新行不断到达时，向上滚动可以暂停跟随。Jump to latest 会带你回到末尾。

用 `stick.get()` 读取日志是否正在 `following`、当前是否 `atBottom`，或者下方是否有 `unseen` 内容。`stick.subscribe(listener)` 上报变更并返回一个清理函数。这些值可以驱动一个跳转按钮：

```ts
stick.scrollToBottom({ behavior: "smooth" })
```

当新条目需要由屏幕阅读器播报时，给内容设置 `role="log"`。

### 较早的消息与放手
要让对话打开时停在当前位置而不是跳到末尾，使用 `initial: false`：

```ts
const stick = createStickToBottom({ initial: false, threshold: 48 })
```

`threshold` 是以像素为单位的距离，在这个范围内仍算位于底部。加在当前消息上方的较早消息会自行保持读者的位置，不需要调用任何东西。

滚动到末尾并点击 Send。Load Older 会在上方添加消息而不移动你的视图。Let Go 会停止跟随新消息。控制台会记录会话是否正在跟随。

`stick.release()` 从代码里停止跟随。滚回末尾或调用 `scrollToBottom()` 会恢复跟随。连接期间，这个辅助函数会管理滚动锚定，这样浏览器不会再做第二次调整。

### 选项
- `threshold?` (`number`): How close to the end, in pixels, still counts as at the bottom. Example: [Older Messages and Letting Go](https://ui-sdk.cn/docs/core/behaviors/lists#older-messages-and-letting-go).
- `initial?` (`boolean`): Whether it follows from the start. Example: [Older Messages and Letting Go](https://ui-sdk.cn/docs/core/behaviors/lists#older-messages-and-letting-go).
- `onChange?` (`((state: StickToBottomState) => void)`): Runs when `get()` changes. Example: [Follow the Newest Line](https://ui-sdk.cn/docs/core/behaviors/lists#follow-the-newest-line).

## 滚动选取的转轮
### 滚动选取
从 `@ui-sdk/core` 导入 `bindScrollPicker`。它把可滚动的列表框变成一个转轮，就像时间选择器的小时和分钟滚轮：位于中心的选项就是值。列表进入页面后，把它绑定到一个 [Listbox](/docs/components/listbox)，并选择它上报的选项。它返回一个清理函数，供列表离开时使用：

**React**

```tsx
const list = React.useRef<HTMLDivElement>(null)
const select = React.useEffectEvent((index: number) => setHour(hours[index]))

React.useLayoutEffect(
  () => bindScrollPicker(list.current!, { onSelect: (index) => select(index) }),
  []
)

<Listbox ref={list} keepInView={false} value={hour} onValueChange={setHour}>
```

**Vue**

```vue
<script setup lang="ts">
const holder = useTemplateRef<HTMLElement>("holder")
let unbind: (() => void) | undefined
onMounted(() => {
  const list = holder.value!.querySelector<HTMLElement>('[role="listbox"]')!
  unbind = bindScrollPicker(list, {
    onSelect: (index) => (hour.value = hours[index]),
  })
})
onBeforeUnmount(() => unbind?.())
</script>

<template>
  <div ref="holder">
    <Listbox v-model="hour" :keep-in-view="false">…</Listbox>
  </div>
</template>
```

**Svelte**

```svelte
<Listbox
  bind:value={hour}
  keepInView={false}
  {@attach (el) =>
    bindScrollPicker(el, { onSelect: (index) => (hour = hours[index]) })}
>
```

**Solid**

```tsx
let list: HTMLDivElement | undefined
onSettled(() =>
  bindScrollPicker(list!, { onSelect: (index) => setHour(hours[index]) })
)

<Listbox ref={list} keepInView={false} value={hour()} onValueChange={setHour}>
```

**Web Components**

```ts
const listbox = document.querySelector("ui-listbox")!
const unbind = bindScrollPicker(listbox, {
  onSelect: (index) => (listbox.value = hours[index]),
})
```

`index` 计入列表里的每个选项，包括禁用的选项，所以它与你的数组对应。选择器自己不选任何东西，所以 `onSelect` 才是只读表单或你自己的检查做决定的地方。

列表仍然是一个单选的列表框。滚动、触摸屏上的轻扫以及鼠标拖动，会在选项经过中心时选择它；列表停止后会停在最近的已启用选项上。当列表框自己选中一个选项时，比如通过点击、方向键、Home、End 或输入选项名称，选择器会平滑地滚动到那里，而不选择中间的选项。Page Up 和 Page Down 会移动一屏的选项。

把列表框的 `keepInView` 选项设为 `false`，这样它不会跳到一个转轮即将滑过去的选项。给列表一个高度、`scroll-snap-type`，并在两端留出空间，让第一个和最后一个选项也能到达中心；再给每个选项设置 `scroll-snap-align: center`：

```css
[role="listbox"] {
  height: 180px;
  padding-block: 72px;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
}

[role="option"] {
  height: 36px;
  scroll-snap-align: center;
}
```

吸附由浏览器自己完成，所以列表在你的 JavaScript 加载之前就会吸附。选项可以是任意尺寸：选择器会测量它们，并在它们或列表尺寸变化时重新测量。

### 用 CSS 绘制转轮
每个选项都会得到 `--picker-offset`，即它到中心的距离，以选项为单位：中心是 `0`，下一个选项是 `1`，往前两个是 `-2`。当列表在选项之间移动时，它是小数，并且每帧更新，所以 CSS 可以不用你自己的代码就画出转轮：

```css
[role="option"] {
  transform: rotateX(calc(var(--picker-offset, 0) * -24deg));
  opacity: calc(1 - abs(var(--picker-offset, 0)) * 0.25);
}
```

`0` 这个回退值覆盖选择器绑定之前的服务端 HTML。给列表设置 `perspective`，让旋转看起来是圆形的，并用 `mask-image` 让两端淡出：

滚动或拖动转轮，或在触摸屏上轻扫。点击一个小时，或聚焦一个转轮并使用 Up、Down、Home 和 End。控制台会记录时间。

在减少动态效果的情况下，转轮会直接跳到选项，而不是滑过去。

### 横向
对于横向的转轮，比如一条页码横带，把列表框的 `orientation` 设为 `"horizontal"`。选择器从 `aria-orientation` 读取它，所以会横向滚动和测量；在从右到左的文本中，这条横带从右侧开始：

滚动或拖动这条横带，或聚焦它并使用 Left 和 Right。中间的页码就是当前页，控制台会记录它。

### 选项
- `orientation?` (`"horizontal" | "vertical"`): Which way the list scrolls. A horizontal list runs from the right in right-to-left text. Example: [Sideways](https://ui-sdk.cn/docs/core/behaviors/lists#sideways).
- `onSelect?` (`((index: number, details: ScrollPickerSelectDetails) => void)`): Runs when someone's scroll, drag, or Page Up or Page Down brings another enabled option to the center, with its index among all the options. Select it here. Clicks and arrow keys select through the list itself. Example: [Pick by Scrolling](https://ui-sdk.cn/docs/core/behaviors/lists#pick-by-scrolling).

## 就地编辑
### 在显示的位置重命名
`createInlineEdit` 管理编辑会话。你的状态保存条目的 id，没有任何内容在编辑时为 `null`。你的 `commit` 回调保存新文本：

```ts
import { createInlineEdit } from "@ui-sdk/core"

const edit = createInlineEdit(context, {
  key: "editing",
  value: (id) => nameOf(id),
  commit: (id, text, details) => {
    if (!text.trim()) {
      return false
    }
    return rename(id, text, details)
  },
})
```

返回 `false` 会让编辑器保持打开。文本没有变化时，结束编辑而不调用 `commit`。

聚焦一个播放列表，按 Enter 或 F2，或双击它。Enter 保存名称；Escape 取消。输入一个字母会开始替换。

在条目上，把 `keydown` 传给 `edit.keydown(event, key)`，把 `dblclick` 传给 `edit.dblclick(event, key)`。为 `edit.editing(state)` 返回的 id 渲染一个输入框，然后连接它：

```ts
input: slot({
  on: {
    keydown: (event, { api }) => api.edit.inputKeydown(event),
    focusout: (event, { api }) => api.edit.end("focus-out", event),
  },
  bind: (el, { api }) => api.edit.bindInput(el as HTMLInputElement),
}),
```

`bindInput` 填充并聚焦输入框。Enter 保存；Escape 取消。焦点离开时，`focusout` 处理函数会保存。编辑结束后，如果移除输入框会让焦点丢失，这个辅助函数会恢复焦点。

### 继续前进与从代码开始
Tab 也会保存，但焦点下一步去哪里由你的组件决定。`inputKeydown` 成功处理按键时返回 `true`：

```ts
if (event.key === "Tab" && edit.inputKeydown(event)) {
  nextField.focus()
}
```

把校验放在 `commit` 里。对于不能编辑的值，使用 `disabled(id)`；用 `edit.start(id)` 从单独的按钮或菜单开始编辑。如果编辑结束时那个按钮或菜单已经不在了，焦点会改为转移到输入框周围最近的可聚焦元素，比如它所在的行。

编辑一个产品值，按 Tab 保存并继续。Price 要求数字，SKU 保持只读，Rename 开始编辑名称。

### 选项
- `key` (`keyof State & string`): The state key that holds the id being edited, or `null`. Example: [Rename Where It Shows](https://ui-sdk.cn/docs/core/behaviors/lists#rename-where-it-shows).
- `value` (`(id: string) => string`): The text an id shows now, put in the input when editing starts. Example: [Rename Where It Shows](https://ui-sdk.cn/docs/core/behaviors/lists#rename-where-it-shows).
- `commit` (`(id: string, text: string, details: { reason: InlineEditReason; event?: Event; }) => boolean`): Saves the text and returns whether it went through. Return `false` to keep editing, like when the text isn't valid. Example: [Rename Where It Shows](https://ui-sdk.cn/docs/core/behaviors/lists#rename-where-it-shows).
- `disabled?` (`((id: string) => boolean)`): Whether an id can't be edited. Example: [Moving on and Starting from Code](https://ui-sdk.cn/docs/core/behaviors/lists#moving-on-and-starting-from-code).
