<!-- ui-sdk Core docs, as one file. Pages: /docs/core. -->

# 简介

给智能体提供行为，用来构建无样式、无障碍的组件，键盘、焦点和屏幕阅读器支持都已内置。

本节讲如何用 `@ui-sdk/core` 构建你自己的组件。

- 要在项目里配置 ui-sdk，请看开始使用。
- 要浏览组件库，请看[组件](/docs/components)。

## 它是什么
`@ui-sdk/core` 是一个 TypeScript 的 UI 行为库，也就是构成组件库的那些层。它为键盘导航、焦点、选择、浮层、拖放，以及这些交互所需的 ARIA 属性提供构建块。

你把这些片段组合起来，构建自己的组件。

## 让我给你演示一下
这是一个图标选择器。`@ui-sdk/react` 里没有这个组件。一个智能体把 `@ui-sdk/core` 里的行为组合起来，构建了这个组件。

你期待的功能它都有：一个在按钮旁打开的浮层、用方向键在图标之间导航、按匹配度排序的模糊搜索，以及屏幕阅读器播报。

点击 Pick an Icon 打开选择器，然后点击一个图标或输入内容来搜索。最匹配的项会高亮，按 Enter 即可选中。按向下键进入结果，用方向键移动。

这个图标选择器由 `@ui-sdk/core` 的五个片段组成，它们一起提供这套行为：

- **一个浮层。** [`createPopup`](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own) 配合 popover 预设，在按钮旁打开选择器，把焦点移到搜索框，并在按 Escape 或点击外部时关闭。选中图标后浮层关闭，焦点回到按钮。
- **一个 Tab 停靠点。** [`createRovingFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus) 让 Tab 只进入网格一次。方向键在图标之间移动，再按 Tab 就离开。你无需逐个按 Tab 经过每个按钮。
- **跟随布局的方向键。** [`spatialMove`](https://ui-sdk.cn/docs/core/behaviors/focus#spatial-focus) 在你按下的方向上选择最近的图标。小屏幕上网格列数更少时，向下键仍然向下。
- **搜索结果。** [`fuzzyScore`](https://ui-sdk.cn/docs/core/text#rank-what-someone-searches-for) 按你输入的内容给每个图标的名称和关键词排序。“idea”能找到灯泡，“launch”能找到火箭。
- **播报。** [`announce`](https://ui-sdk.cn/docs/core/platform#announcements) 告诉屏幕阅读器有多少个图标与你输入的内容匹配。

选择器补上了它们之间的连接，比如按下向下键时把焦点从搜索框移进网格。

## 它如何组合起来
选择器保存状态，比如是否打开、搜索词和当前聚焦的图标。它有部件，比如打开它的按钮、搜索框、网格和每个图标。**原语（primitive）** 把这份状态、这些部件和它们的行为放进同一个定义里。

原语只需写一次。各框架的适配器在 React、Vue、Svelte、Solid 和 Web Components 里渲染它的部件。行为留在 `@ui-sdk/core`，每个适配器把它接到你的框架上。

部件不带样式。它们暴露属性和 CSS 变量供你设置样式，你可以按自己的方式设置。

## 为什么要有它
组件库覆盖了常见的模式，比如菜单、对话框和标签页。你的产品可能需要看板、可以拖动浏览的时间线，或者为某个任务专门做的选择器。

界面本身你能做，但交互要花功夫。条目消失时，焦点得有地方可去。拖拽需要键盘替代方式。关闭浮层需要把你送回原来的位置。

智能体生成界面时也面临同样的问题。`@ui-sdk/core` 给你和你的智能体提供经过测试的行为作为基础，让每个新组件都能复用这些成果。

片段怎么组合，组件叫什么名字、有哪些角色和说明，仍由你决定。`@ui-sdk/core` 里的[测试工具包](/docs/core/testing)帮你检查结果，包括键盘行为、ARIA 关系和服务端渲染出的属性。

## 构建你的第一个组件
从[构建一个组件](/docs/core/build-a-component)开始。你会做一个只有一份状态和一个按钮的开关，在你的框架里渲染它，再加上样式。

之后，Core 指南会把每一步展开：[定义原语](/docs/core/kernel/define-a-primitive)、[渲染原语](/docs/core/kernel/render-a-primitive)和[为组件设置样式](/docs/core/kernel/style-a-component)。[组合行为](/docs/core/compose-behaviors)用一个星级评分把几个行为串起来，[处理变更](/docs/core/kernel/handle-changes)让应用控制状态并对状态变化做出响应。

接下来：

- [行为](/docs/core/behaviors)帮你找到正在构建的东西所需的片段。
- [参考](/docs/core/reference)在你需要细节时列出函数和类型。


# 构建组件

做一个开关按钮，然后在你的框架里渲染同一个原语。

让我们从一个开关按钮开始。按压 **Mute** 开启它，再按压一次关闭。

点击 Mute，或聚焦它后按 Enter 或 Space。每按一次，它的按压状态都会变化。

我们会定义它的行为，把它连接到你的框架，再加上样式。

## 安装
先安装 `@ui-sdk/core`。

```
npm add @ui-sdk/core
```

## 定义原语
**原语（primitive）** 描述一个组件的行为：它的状态、改变状态的函数，以及使用它的部件。它本身不渲染任何东西。

我们的原语就是静音按钮的。它有一项状态 `muted`，静音开启时为 `true`，还有一个部件。

```ts title="lib/mute-button.ts"
import { definePrimitive } from "@ui-sdk/core"

const muteButton = definePrimitive({
  name: "mute-button",
  state: () => ({ muted: false }),
  api: (context) => ({
    toggle: () => context.store.set({ muted: !context.store.get().muted }),
  }),
  slots: (slot) => ({
    root: slot({
      attrs: (state) => ({
        type: "button",
        "aria-pressed": String(state.muted),
      }),
      press: ({ api }) => api.toggle(),
    }),
  }),
})

export { muteButton }
```

- `state` 把 `muted` 初始化为 `false`。
- `api` 定义了 `toggle`，它在 `true` 和 `false` 之间切换 `muted`。
- `slots` 描述组件的部件。我们唯一的**槽位** 是 `root`，渲染时它会变成那个按钮。
- `attrs` 把状态变成 HTML 属性。`muted` 为 `true` 时，根部件会得到 `aria-pressed="true"`。
- 根部件被激活时，`press` 调用 `toggle`。

行为就这些。[定义原语](/docs/core/kernel/define-a-primitive) 会逐个详细讲解每个字段。现在把它放到页面上。

## 渲染它
**适配器** 把原语连接到你的框架。在页面顶部选择你的框架，然后安装对应的包。

**React**

```bash
npm add @ui-sdk/react
```

**Vue**

```bash
npm add @ui-sdk/vue
```

**Svelte**

```bash
npm add @ui-sdk/svelte
```

**Solid**

```bash
npm add @ui-sdk/solid
```

**Web Components**

```bash
npm add @ui-sdk/web
```

首先，用 `muteButton` 原语创建组件。

**React**

```ts title="components/ui/mute-button.tsx"
"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { muteButton } from "@/lib/mute-button"

const { Root: MuteButton } = createParts(muteButton, { root: "button" })

export { MuteButton }
```

`{ root: "button" }` 表示 `MuteButton` 的根部件渲染一个 `<button>`。然后在任何要用它的地方导入它：

```tsx title="pages/index.tsx"
import { MuteButton } from "@/components/ui/mute-button"

function Example() {
  return <MuteButton>Mute</MuteButton>
}
```

**Vue**

```ts title="components/ui/mute-button.ts"
import { createParts } from "@ui-sdk/vue/primitive"
import { muteButton } from "@/lib/mute-button"

const { Root: MuteButton } = createParts(muteButton, { root: "button" })

export { MuteButton }
```

`{ root: "button" }` 表示 `MuteButton` 的根部件渲染一个 `<button>`。然后在任何要用它的地方导入它：

```vue title="pages/index.vue"
<script setup lang="ts">
import { MuteButton } from "@/components/ui/mute-button"
</script>

<template>
  <MuteButton>Mute</MuteButton>
</template>
```

**Svelte**

```ts title="components/ui/mute-button.ts"
import { createParts } from "@ui-sdk/svelte/primitive"
import { muteButton } from "@/lib/mute-button"

const { Root: MuteButton } = createParts(muteButton, { root: "button" })

export { MuteButton }
```

`{ root: "button" }` 表示 `MuteButton` 的根部件渲染一个 `<button>`。然后在任何要用它的地方导入它：

```svelte title="pages/index.svelte"
<script lang="ts">
  import { MuteButton } from "@/components/ui/mute-button"
</script>

<MuteButton>Mute</MuteButton>
```

**Solid**

```ts title="components/ui/mute-button.ts"
import { createParts } from "@ui-sdk/solid/primitive"
import { muteButton } from "@/lib/mute-button"

const { Root: MuteButton } = createParts(muteButton, { root: "button" })

export { MuteButton }
```

`{ root: "button" }` 表示 `MuteButton` 的根部件渲染一个 `<button>`。然后在任何要用它的地方导入它：

```tsx title="pages/index.tsx"
import { MuteButton } from "@/components/ui/mute-button"

function Example() {
  return <MuteButton>Mute</MuteButton>
}

export { Example }
```

**Web Components**

在 Web Components 上，注册一个自定义元素：

```ts title="components/ui/mute-button.ts"
import { createParts, wrappedButton } from "@ui-sdk/web"
import { muteButton } from "@/lib/mute-button"

createParts(muteButton, {
  root: { tag: "mute-button", target: wrappedButton },
})
```

这会为根部件注册一个 `<mute-button>` 元素，`wrappedButton` 把根部件的行为和属性放到它内部的 `<button>` 上。在应用的浏览器入口文件里导入 `@/components/ui/mute-button`，然后在你的 HTML 里使用它：

```html title="pages/index.html"
<mute-button>
  <button>Mute</button>
</mute-button>
```

因为我们用的是原生 `<button>`，点击、Enter 和 Space 都会到达原语的 `press` 处理函数。屏幕阅读器从 `aria-pressed` 读取它的按压状态。

行为留在 `mute-button.ts` 里。更换框架只会改变渲染它的方式，行为保持不变。[渲染原语](/docs/core/kernel/render-a-primitive) 介绍选项、内容中的状态和服务端渲染。

## 为组件设置样式
部件渲染出来没有样式。下面是这个按钮的完整外观，包含悬停、焦点和按压状态：

```css
[data-slot="mute-button"] {
  border: 1px solid #e5e5e5;
  border-radius: 0.5rem;
  background: white;
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;

  &:hover {
    background: #f5f5f5;
  }

  &:focus-visible {
    outline: 2px solid #a3a3a3;
    outline-offset: 2px;
  }

  &[aria-pressed="true"] {
    background: #171717;
    color: white;
  }
}
```

按压时的外观来自 `aria-pressed`。`muted` 为 `true` 时，根部件会渲染 `aria-pressed="true"`，这来自你定义原语时写的 `attrs`。在 CSS 标签页里，`&[aria-pressed="true"]` 规则会选中它。在 Tailwind 标签页里，`aria-pressed:` 类做同样的事。

`data-slot` 标识部件，而这些属性在每个框架里都一样，所以这段 CSS 对五个版本都有效。[为组件设置样式](/docs/core/kernel/style-a-component) 介绍更多状态属性、CSS 变量和来来去去的部件。

## 下一步
你已经定义了一个原语、渲染了它并设置了样式。Core 指南会把每一步讲得更深：

- [定义原语](/docs/core/kernel/define-a-primitive): 为原语设置选项，把状态暴露给它的部件，并处理元素。
- [渲染原语](/docs/core/kernel/render-a-primitive): 把原语的槽位变成你所用框架里的部件，传入选项并读取状态。
- [为组件设置样式](/docs/core/kernel/style-a-component): 依据每个部件的 data-slot 和状态所设的属性，用 CSS 或 Tailwind 设置样式。
- [组合行为](/docs/core/compose-behaviors): 用共享状态和键盘导航构建一个星级评分。
- [处理变更](/docs/core/kernel/handle-changes): 上报变更，让应用接受或取消它们，并选择状态更新如何到达页面。

或者从现成的东西开始：

- [组件](/docs/components): 在你的框架里使用 Select、Dialog 和 Tabs 这类现成组件。
- [所有行为](/docs/core/behaviors): 焦点、选择、浮层，以及组成组件的其他片段。


# 定义原语

为原语设置选项，把状态暴露给它的部件，并处理元素。

`definePrimitive` 把一个组件的选项、状态、方法和部件整合到一起。用它提供的槽位来暴露属性和状态、处理事件，以及操作已经挂载的元素。

在 [构建一个组件](/docs/core/build-a-component) 里，你定义了一个静音按钮。本页用一个复制按钮，逐个讲解定义里的每个字段。每个演示的代码标签页里都有完整示例。

下面是本页要构建的复制按钮，写成一份定义。下面的每一节都会更详细地讲解它的一个字段。

```ts title="copy-button.ts"
import { definePrimitive } from "@ui-sdk/core"

type CopyButtonOptions = { text?: string; onCopy?: (text: string) => void }

const copyButton = definePrimitive({
  name: "copy-button",
  options: { text: "string", onCopy: "callback" },
  state: (options: CopyButtonOptions) => ({ copied: false }),
  api: (context) => ({
    async copy() {
      const { text = "", onCopy } = context.options()
      await navigator.clipboard.writeText(text)
      context.store.set({ copied: true })
      onCopy?.(text)
    },
  }),
  slots: (slot) => ({
    root: slot<{}, { copied: boolean }>({
      state: (state) => ({ copied: state.copied }),
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.copy(),
    }),
  }),
})

export { copyButton }
```

## 选项
让我们给复制按钮加上要复制的文本。用一个类型描述选项，在 `options` 里列出每个选项的种类，并用这个类型标注 `state` 的参数：

```ts
type CopyButtonOptions = { text?: string; onCopy?: (text: string) => void }
```

```ts
options: { text: "string", onCopy: "callback" },
state: (options: CopyButtonOptions) => ({ copied: false }),
```

`state` 的参数用这个类型标注后，`api` 里的 `context.options()` 也就有了类型，所以类型只需要写一次。种类告诉适配器如何处理每个值。比如，Web Components 会从属性读取 `text`，并把 `onCopy` 变成一个事件。TypeScript 会检查每个选项都有种类。如果你的原语（primitive）没有选项，就不写 `options`。

用 `context.options()` 读取当前值。这里，`copy` 在按钮被按压时读取文本：

```ts
api: (context) => {
  return {
    async copy() {
      const { text = "", onCopy } = context.options()
      await navigator.clipboard.writeText(text)
      context.store.set({ copied: true })
      onCopy?.(text)
    },
  }
},
```

`api` 对每个实例只运行一次，所以在方法内部读取选项可以避免拿着旧值不放。

### 选项变化时
如果某个变化需要额外处理，就用 `context.onOptions`。对复制按钮来说，新的文本应该清掉之前的“Copied”状态。在 `api` 里、返回它的方法之前加上这段：

```ts
let text = context.options().text

context.onOptions((options) => {
  if (options.text === text) return
  text = options.text
  context.store.set({ copied: false })
})
```

如果想改为让一个受控值保持同步，就用 `sync`，[处理变更](https://ui-sdk.cn/docs/core/kernel/handle-changes#control-the-state) 里有示例。

### 选项种类
同样的种类也适用于槽位的 `props` schema，它让每个部件拥有自己的值，比如 [组合行为](https://ui-sdk.cn/docs/core/compose-behaviors#add-a-star) 里星星的 `value`。

| 种类                                | 用途                                                                   |
| ----------------------------------- | ---------------------------------------------------------------------- |
| `"string"`, `"number"`, `"boolean"` | 可以从属性读取的值。                                                   |
| `"list"`                            | 一个字符串或一个字符串列表。属性里用逗号分隔各值。                     |
| `"value"`                           | 其他值，比如对象、元素或函数。在 Web Components 上作为 property 设置。 |
| `"callback"`                        | 报告某事的回调。Vue 把它当作 emit；Web Components 触发事件。           |
| `"action"`                          | 返回值有意义的函数，比如 Promise。Vue 把它保留为函数 prop。            |
| `"id"`                              | 省略时由适配器生成的字符串。                                           |
| `"key"`                             | 列表项的值，类型不限。部件以它为键，里面的部件能看到这个键。           |

对于嵌套在另一个部件里的部件，`{ kind: "string", from: "item" }` 在省略时从外层的 `item` 继承同一个 prop。要继承不同的 prop，就用 `from: "group.id"`；如果部件只有放在父级里才有意义，再加上 `required: true`，这样在别处使用就会抛错。内置种类都不合适时，可以用函数 `(attribute) => value` 解析 Web Component 的属性。

## 部件展示什么
只做样式的话，属性就够了。如果想让组件的内容也能读取状态，就在它的槽位里加上 `state`：

```ts
root: slot<{}, { copied: boolean }>({
  state: (state) => ({ copied: state.copied }),
  attrs: () => ({ type: "button" }),
  press: ({ api }) => api.copy(),
}),
```

第一个类型参数描述部件的 props；第二个描述它的 `state` 返回什么。在 React 里，复制按钮的子内容现在可以读取 `copied`：

```tsx
<CopyButton text="npm add @ui-sdk/core">
  {({ copied }) => (copied ? "Copied" : "Copy")}
</CopyButton>
```

试试看。这个版本还会在短暂超时后重置。

按压 Copy。命令复制期间按钮显示 Copied，复制完成后回到 Copy。

## 来来去去的部件
如果部件只在某些状态下出现，就用 `present`。这个面板在 `open` 为 `true` 时保持呈现：

```ts
panel: slot({
  present: (state) => state.open,
  attrs: (_state, part) => ({ id: `${part.id}-panel` }),
}),
```

触发器用 `aria-controls` 指向面板：

```ts
trigger: slot({
  attrs: (state, part) => ({
    type: "button",
    "aria-expanded": String(state.open),
    "aria-controls": `${part.id}-panel`,
  }),
  press: ({ api }) => api.toggle(),
}),
```

`part.id` 是实例的唯一 id。两个部件都用它来构成同一个面板 id。如果 id 里包含某个项的值，就用 `@ui-sdk/core` 的 `idPart(value)` 转义空格和百分号。

作者在部件元素上写的 id，会胜过槽位生成的那个 id，每个框架和 Web Components 都是如此。在它之后渲染的部件，从首次渲染起就指向作者的 id，在服务器上也是如此；元素绑定后，所有部件都会这样：`aria-controls`、`aria-labelledby`、`aria-describedby`、`aria-activedescendant`、`for` 以及其他指向所生成 id 的引用都会指向它。所以从 `part.id` 构建引用，核心会让它们保持正确。

一直在的部件就不用写 `present`。框架适配器会移除不存在的部件；Web Components 会保留标记，并随着呈现状态的变化绑定或解绑它的行为。

## 事件
按钮激活用 `press`。其他 DOM 事件用 `on`。下面是一个按 Escape 就清空的搜索框：

```ts
input: slot({
  attrs: (state) => ({ type: "search", value: state.query }),
  on: {
    input: (event, { api }) => api.search((event.target as HTMLInputElement).value),
    keydown: (event, { api }) => {
      if (event.key !== "Escape") return
      event.preventDefault()
      api.search("")
    },
  },
}),
```

每个处理函数都会收到事件和部件的上下文：`el`、`id`、`key`、`props`、`store` 和 `api`。组件使用者传入的处理函数会先运行。它可以调用 `event.preventDefault()` 跳过原语的处理函数。

## 角色、焦点和按键
在每个部件的槽位上声明角色，不要写在 `attrs` 里。角色由核心写入；如果角色要获取焦点、被激活或随按键移动，槽位就必须说明怎么做。下面是一个选项：

```ts
item: slot({
  role: "option",
  focus: "roving",
  press: ({ api, key }) => api.choose(key),
  attrs: (state, part) => ({
    "aria-selected": String(state.value === part.key),
  }),
}),
```

漏掉一个，TypeScript 会点出来：没有 `focus` 的选项会报 “Property 'focus' is missing”。角色决定哪些字段是必需的：

- **`focus`** 用于要获取焦点的角色，比如 `option`、`tab` 或 `menuitem`：`"roving"`、`"tab-stop"`、`"active-descendant"` 或 `"native"`。开发构建会检查绑定的元素能否以这种方式获取焦点，比如渲染成 `<div>` 的 `"native"` 部件。
- **`press`** 用于会被激活的角色，比如 `button`、`option` 或 `tab`。
- **`keys`** 用于其模式随按键移动的角色，比如 `listbox`、`menu` 或 `slider`：它的 `on.keydown` 处理的按键，或者当这些按键取决于状态时，用状态函数返回它们。

```ts
list: slot({
  role: "listbox",
  keys: (state) => [...(state.orientation === "horizontal" ? ["ArrowLeft", "ArrowRight"] : ["ArrowUp", "ArrowDown"]), "Home", "End", "typeahead"],
  on: { keydown: (event, { api }) => api.navigate(event) },
}),
```

列出了按键，却没有处理它们的 `on.keydown`，在任何槽位上都编译不过。如果另一个元素满足了某个需要，就用 `{ none: "why" }` 说明是哪一个，比如 `keys: { none: "The combobox's input handles them." }`。随状态变化的角色是一个函数，它可能选到的每个角色都放在 `roles` 里：

```ts
root: slot({
  role: (state) => (state.decorative ? "none" : "separator"),
  roles: ["none", "separator"],
}),
```

角色也决定部件的 ARIA。它的 `attrs` 要返回该角色离不开的状态，比如复选框的 `aria-checked` 或选项的 `aria-selected`，而且不能返回角色不接受的属性：组上的 `aria-orientation` 会报 “aria-orientation isn't allowed on a group”。

```ts
box: slot({
  role: "checkbox",
  focus: "native",
  press: ({ api }) => api.toggle(),
  attrs: (state) => ({ "aria-checked": String(state.checked) }),
}),
```

由 `live` 保持最新的状态，在 `attrs` 里是 `undefined`，所以 `attrs` 仍然要写出它。类型看不到的东西，开发构建会发出警告，比如展开写法的槽位或 JavaScript；没有值却渲染的必需状态也会警告。在测试设置里设置 `globalThis.__UI_SDK_STRICT__ = true`，就能让每个警告都变成错误。

## 操作元素
需要元素才能做的工作就用 `bind`，比如测量元素或挂上观察器。它在部件绑定后于浏览器里运行。返回一个清理函数：

```ts
root: slot({
  attrs: () => ({ rows: "1" }),
  bind: (el) => {
    const fit = () => {
      el.style.height = "auto"
      el.style.height = `${el.scrollHeight}px`
    }
    fit()
    el.addEventListener("input", fit)
    return () => el.removeEventListener("input", fit)
  },
}),
```

这个 textarea 会在每次输入后测量内容并调整高度。

让 `attrs` 和槽位的 `state` 保持纯净：它们也会在服务器上运行。从状态和部件的 props 读取；DOM 操作放在 `bind` 里。槽位的 `state` 每次调用都可以返回新的对象和数组，因为部件会按值比较它们；但其他值，比如 `Date` 或 `Map`，在变化之前应保持同一个对象。

`bind` 还会把部件作为第二个参数传进来。它的 `props` 会保持最新，`part.store.subscribe` 可以让你跟踪状态变化。如果某项工作必须在元素留在页面期间一直保持活动，即使部件没有呈现，比如隐藏的自定义元素，就用 `connect`。

### 清理实例
所有部件共享的工作放在 `api` 里。用 `context.onDestroy` 在实例销毁时清理它。比如，复制按钮会清掉它的重置定时器：

```ts
let timer: ReturnType<typeof setTimeout> | undefined

context.onDestroy(() => clearTimeout(timer))
```

另外，在启动下一个定时器之前，也要清掉上一个。

## 在 API 中读取部件
有时方法需要找到某个部件。`elements(context, slot)` 会按页面顺序返回已绑定的部件，以及它们的元素、键和 props：

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

api: (context) => ({
  next() {
    const fields = elements<{ value: string }>(context, "field")
    const empty = fields.find((field) => (field.el as HTMLInputElement).value === "")
    empty?.el.focus()
  },
}),
```

试着留空一个字段。按钮会按当前的页面顺序找到它，所以不需要单独维护一份索引。

要拿单个部件，用 `context.element(slot, key)`。要读取它最新的 props，用 `context.props(slot, key)`，命名方式相同：`context.props<{ title: string }>("window", key)`。这个 `key` 是部件的 `id` prop，或者它的 `value`，就像 [组合行为](https://ui-sdk.cn/docs/core/compose-behaviors#add-a-star) 里的星星那样。

## Agent 能做什么
`agent` 键告诉 [Agent 桥接层](https://ui-sdk.cn/docs/agents/connect-an-agent/reference#custom-primitives) 一个 Agent 可以调用哪些 api 方法，以及组件的一些信息，比如它的值是否必须是某个项：

```ts
agent: { actions: ["setValue", "clear"], closed: true },
```

把它放在 `api` 后面，这样它的 `items` 函数就能读到 api 的类型。没有它的话，桥接层会挑选名字听起来像变更的方法，比如 `setValue` 或 `toggle`。[Agent 键](/docs/agents/connect-an-agent/your-components) 展示了一个 Agent 可以使用的评分，以及这个键的每个部分。

## 命名
原语的 `name` 会作为每个部件 `data-slot` 的前缀，比如标签页的 `list` 槽位得到 `tabs-list`。`root` 槽位只拿到名字本身，所以 `name: "copy-button"` 会让它的根变成 `data-slot="copy-button"`。

警告和 devtools 也使用这个名字。如果希望它们显示别的名字，就设置 `label`；它不会改变 `data-slot`。

对于状态属性，`openAttrs(open)` 返回 `data-open` 或 `data-closed`。`checkedAttrs(checked)` 返回 `data-checked`、`data-unchecked` 或 `data-indeterminate`。两者都是 `@ui-sdk/core` 里的辅助函数。

## API 参考
### definePrimitive
- `name` (`string`): Prefixes `data-slot`, and names the component in warnings and the devtools. Kebab case. Example: [Naming](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#naming).
- `state` (`(options: Options) => State`): The starting state, from the first options. Read `default<Key>` here. Example: [Define a Primitive](https://ui-sdk.cn/docs/core/build-a-component#define-a-primitive).
- `live?` (`(keyof State)[]`): State keys that change often and never affect rendering, like a highlighted item. Example: [Live State](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state).
- `asleep?` (`((options: object) => boolean)`): Whether an instance with these options starts asleep: its parts render and run `asleep`, while its api and each part's `bind` wait for the first event a part handles or the first read of `instance.api`, or of `api` in a slot's render. Like a closed tooltip, which costs little until its trigger is hovered or focused.
- `sync?` (`(options: Options) => Partial<State>`): Maps controlled options onto state. Runs whenever options change. Example: [State a User Controls](https://ui-sdk.cn/docs/core/kernel/handle-changes#state-a-user-controls).
- `controlled?` (`(keyof State)[]`): State keys a user can control with `<key>`, `default<Key>` and `on<Key>Change`. Development builds warn when one starts with both `<key>` and `default<Key>`, or was controlled and becomes undefined. Defaults to whichever of `open`, `value` and `checked` the state has. Example: [State a User Controls](https://ui-sdk.cn/docs/core/kernel/handle-changes#state-a-user-controls).
- `commits?` (`(keyof State)[]`): State keys an interaction changes in steps and then commits, through `createCommit`, like a slider's `value` while it's dragged. `observe` reports each of them once per commit rather than per step. Example: [Commits](https://ui-sdk.cn/docs/core/kernel/handle-changes#commits).
- `api` (`(context: PrimitiveContext) => Api`): Runs once per instance and returns its api, which slots, adapters and a controller call. Example: [Define a Primitive](https://ui-sdk.cn/docs/core/build-a-component#define-a-primitive).
- `slots` (`(slot: SlotFactory) => Record<string, SlotDefinition>`): The parts, built with `slot`. `slot<Props, State>({ ... })` types a slot's props and the state its render functions get. Example: [Define a Primitive](https://ui-sdk.cn/docs/core/build-a-component#define-a-primitive).
- `label?` (`string`): What warnings, `debug` and the devtools call it, when that isn't `name`, which prefixes `data-slot`. Like a checkbox group's parts in `checkbox`. Example: [Naming](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#naming).
- `agent?` (`object: actions, closed, items, reveals, shown, secret`): What `@ui-sdk/core/agent` offers an agent. Without it, the agent takes the api's methods that change something by their names, like `setValue`. Example: [What Agents Can Do](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#what-agents-can-do).
- `options?` (`PropSchema<Options>`): Each option, with its kind, for renderers to read. A primitive without options leaves it out. Example: [Options](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#options).

### 槽位
- `present?` (`((state: State, context: { id: string; key: string; props: Props; api: Api; }) => boolean)`): Whether the slot's element should exist. Adapters that cannot unmount markup, like custom elements, bind and unbind on it. Defaults to always. Keyed parts, like one panel among many, decide from their own props. May read live state: adapters check presence on every change. Example: [Parts That Come and Go](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#parts-that-come-and-go).
- `attrs?` (`((state: State, context: { id: string; key: string; props: Props; api: Api; }) => Attrs)`): Pure. Runs on the server and on every render. Never reads live state. Example: [Define a Primitive](https://ui-sdk.cn/docs/core/build-a-component#define-a-primitive).
- `state?` (`((state: State, context: { id: string; key: string; props: Props; api: Api; }) => Public)`): What `render` functions and state-based class names see, like { highlighted, disabled }. May read live state: adapters only re-render a part for live changes when its render function actually read them. Example: [What a Part Shows](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#what-a-part-shows).
- `live?` (`Live<State, Api, Props>`): Attributes written straight to the element on every change, built by `live()`. Example: [Live State](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state).
- `direct?` (`{ names: readonly string[]; attach: (part: Part, el: HTMLElement) => () => void; }`): Attributes of `attrs` core keeps current on a framework's element, built by `direct()`. Example: [Live State](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state).
- `selects?` (`Selects<State, Api, Props>`): Narrows which changes reach the slot's parts, built by `selects()`. Example: [Live State](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state).
- `press?` (`(context: { el, id, key, props, store, api }, event?: Event) => void`): Activation: a click, which keys and screen readers send too. `{ none: "why" }` for a role that activates when another handler does it, like the author's own click. Example: [Define a Primitive](https://ui-sdk.cn/docs/core/build-a-component#define-a-primitive).
- `on?` (`Partial<Record<keyof HTMLElementEventMap, (event: Event, context: { el, id, key, props, store, api }) => void>>`): DOM events. Adapters attach these so user handlers run first and can call preventDefault() to skip them. Example: [Events](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#events).
- `bind?` (`((el: HTMLElement, part: Part<State, Api, Props>) => (() => void) | void)`): Client only, web only. Focus, positioning, observers. Gets the part, whose `props` are its newest render's. Return a cleanup. Follow state with `part.store.subscribe`, or write attributes that change often with `direct`. Example: [Working with the Element](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#working-with-the-element).
- `asleep?` (`((el: HTMLElement, part: Part<State, Api, Props>) => (() => void) | void)`): Client only, web only. Like `bind`, but runs at once while the instance is asleep, for what a part can't wait for, like naming its trigger. Its `part.api` is undefined until the instance wakes.
- `connect?` (`((el: HTMLElement) => () => void)`): Client only. Runs while the element is in the page, present or not, for adapters that keep parts that aren't present, like custom elements. A popup's content registers here, so shortcuts inside a closed one don't run. Example: [Working with the Element](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#working-with-the-element).
- `props?` (`PropSchema<Props>`): Each prop the slot's parts take, with its kind, like `{ value: "string" }`. Example: [Add a Star](https://ui-sdk.cn/docs/core/compose-behaviors#add-a-star).

### 角色
- `role?` (`Role | ((state, context) => Role | undefined)`): The part's WAI-ARIA role, which core writes. A role that takes focus, activates or moves with keys makes the slot say how, with `focus`, `press` and `keys`. A function picks the role from state, with every role it can pick in `roles`. Never put `role` in `attrs`. Example: [Roles, Focus and Keys](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#roles-focus-and-keys).
- `roles?` (`array`): Every role a `role` function can pick. Development builds check what each one needs. Example: [Roles, Focus and Keys](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#roles-focus-and-keys).
- `focus?` (`Unneeded | ((state: State, context: { id: string; key: string; props: Props; api: Api; }) => Focus | Unneeded) | Focus`): How the part gets focus, for a role that takes it, like an option or a tab. `{ none: "why" }` when another element takes it instead. Example: [Roles, Focus and Keys](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#roles-focus-and-keys).
- `keys?` (`HandledKey[] | ((state) => HandledKey[]) | { none: string }`): The keys the part's `on.keydown` handles, for a role whose pattern moves with keys, or a function of state when they depend on it, like the arrows of an orientation. `{ none: "why" }` when another element handles them, like a combobox's input for its listbox. Example: [Roles, Focus and Keys](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#roles-focus-and-keys).

## 下一步
复制按钮需要的东西都齐了。接下来，[渲染原语](/docs/core/kernel/render-a-primitive) 会把它放到你所用框架的页面上。


# 渲染原语

把原语的槽位变成你所用框架里的部件，传入选项并读取状态。

[定义原语](/docs/core/kernel/define-a-primitive) 已经给复制按钮准备好了选项、状态和槽位。现在把它放到页面上。在页面顶部选择你的框架，下面的代码会随之切换。

## 安装适配器
**适配器** 把原语（primitive）连接到你所用的框架。安装对应你框架的那个：

**React**

```bash
npm add @ui-sdk/react
```

**Vue**

```bash
npm add @ui-sdk/vue
```

**Svelte**

```bash
npm add @ui-sdk/svelte
```

**Solid**

```bash
npm add @ui-sdk/solid
```

**Web Components**

```bash
npm add @ui-sdk/web
```

## 创建部件
`createParts` 会把每个槽位变成一个**部件**。把原语和每个部件要渲染的元素传给它：

**React**

```ts title="copy-button-parts.ts"
"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { copyButton } from "./copy-button"

const { Root: CopyButton } = createParts(copyButton, { root: "button" })

export { CopyButton }
```

**Vue**

```ts title="copy-button-parts.ts"
import { createParts } from "@ui-sdk/vue/primitive"
import { copyButton } from "./copy-button"

const { Root: CopyButton } = createParts(copyButton, { root: "button" })

export { CopyButton }
```

**Svelte**

```ts title="copy-button-parts.ts"
import { createParts } from "@ui-sdk/svelte/primitive"
import { copyButton } from "./copy-button"

const { Root: CopyButton } = createParts(copyButton, { root: "button" })

export { CopyButton }
```

**Solid**

```ts title="copy-button-parts.ts"
import { createParts } from "@ui-sdk/solid/primitive"
import { copyButton } from "./copy-button"

const { Root: CopyButton } = createParts(copyButton, { root: "button" })

export { CopyButton }
```

**Web Components**

```ts title="copy-button-parts.ts"
import { createParts, wrappedButton } from "@ui-sdk/web"
import { copyButton } from "./copy-button"

createParts(copyButton, {
  root: { tag: "copy-button", target: wrappedButton },
})
```

`createParts` 会为你映射的每个槽位注册一个自定义元素。`wrappedButton` 把根部件的行为和属性放到元素内部的原生按钮上。在应用的浏览器入口文件里导入这个文件。

`Root` 创建原语的实例，并把它共享给里面的部件。你映射的其他每个槽位都会变成一个按 Pascal 命名的部件，所以 `star` 槽位会变成 `Star`。

## 传入选项
原语的选项会成为部件的属性（props），与元素自身的属性并列：

**React**

```tsx
<CopyButton text="npm add @ui-sdk/core" onCopy={(text) => console.log(text)}>
  Copy
</CopyButton>
```

**Vue**

```vue
<CopyButton
  text="npm add @ui-sdk/core"
  @copy="(text) => console.log(text)"
>Copy</CopyButton>
```

回调选项会变成一个事件，所以 `onCopy` 就是 `@copy`。

**Svelte**

```svelte
<CopyButton text="npm add @ui-sdk/core" onCopy={(text) => console.log(text)}
  >Copy</CopyButton
>
```

**Solid**

```tsx
<CopyButton text="npm add @ui-sdk/core" onCopy={(text) => console.log(text)}>
  Copy
</CopyButton>
```

**Web Components**

```html
<copy-button text="npm add @ui-sdk/core">
  <button>Copy</button>
</copy-button>
```

`"string"` 选项会从它的属性读取值，回调选项则以事件的形式在元素上触发。

## 读取状态
根槽位的 `state` 会返回 `copied`，所以按钮的内容可以跟着它走：

**React**

```tsx
<CopyButton text="npm add @ui-sdk/core">
  {({ copied }) => (copied ? "Copied" : "Copy")}
</CopyButton>
```

**Vue**

```vue
<CopyButton v-slot="{ state }" text="npm add @ui-sdk/core">
  {{ state.copied ? "Copied" : "Copy" }}
</CopyButton>
```

**Svelte**

```svelte
<CopyButton text="npm add @ui-sdk/core">
  {#snippet children(state)}{state.copied ? "Copied" : "Copy"}{/snippet}
</CopyButton>
```

**Solid**

```tsx
<CopyButton text="npm add @ui-sdk/core">
  {(state) => (state.copied ? "Copied" : "Copy")}
</CopyButton>
```

**Web Components**

在 Web Components 上，内容是你自己的 HTML。通过部件设置的属性来展示状态，[为组件设置样式](/docs/core/kernel/style-a-component) 里有说明。

## 自己编写部件
当每个槽位都映射到一个元素时，`createParts` 就够了。如果某个部件需要自己的逻辑，比如根据数据渲染列表，就自己写一个，并把它连接到同一个原语。[自定义部件](/docs/custom-parts) 介绍了在你的框架里怎么做。

## 在服务器上渲染
部件会把属性渲染进服务器返回的 HTML，所以页面在你的框架水合之前就能显示正确的状态。在 Web Components 上，你发送标记，元素会在模块加载后接上自己的行为。[服务端渲染](/docs/server-rendering) 介绍了你的框架需要怎么配置。

## 下一步
按钮能用了，但还没有样式。接下来，[为组件设置样式](/docs/core/kernel/style-a-component) 会利用它渲染出的属性来添加样式。


# 为组件设置样式

设置每个部件的样式：依据它的 data-slot 和状态所设的属性，用 CSS 或 Tailwind。

[渲染原语](/docs/core/kernel/render-a-primitive) 把复制按钮放到了页面上。部件渲染出来没有样式，所以让我们给它加一些。本页的所有内容在每个框架里用法都一样。

## 找到部件
每个部件都有一个 `data-slot` 属性：先是原语（primitive）的 `name`，然后是槽位的名字，比如 `tabs-list`。根部件只拿到名字本身，所以复制按钮的根是 `copy-button`：

```css
[data-slot="copy-button"] {
  border-radius: 0.5rem;
  padding: 0.25rem 0.75rem;
}
```

用 `data-slot`，不要用生成的 id，因为生成的 id 可能会变。

## 为它的状态设置样式
想给哪个状态设置样式，就给部件加一个对应的属性。这里，根部件的 `attrs` 会在文本已复制时加上 `data-copied`：

```ts
root: slot<{}, { copied: boolean }>({
  state: (state) => ({ copied: state.copied }),
  attrs: (state) => ({ type: "button", "data-copied": state.copied ? "" : undefined }),
  press: ({ api }) => api.copy(),
}),
```

空字符串会加上该属性，`undefined` 则不加。现在你的 CSS 可以跟着它走：

```css
[data-slot="copy-button"][data-copied] {
  background: #171717;
  color: white;
}
```

用 Tailwind 时，把这个属性当作变体：

**React**

```tsx
<CopyButton className="data-copied:bg-neutral-900 data-copied:text-white">
  Copy
</CopyButton>
```

**Vue**

```vue
<CopyButton
  class="data-copied:bg-neutral-900 data-copied:text-white"
>Copy</CopyButton>
```

**Svelte**

```svelte
<CopyButton class="data-copied:bg-neutral-900 data-copied:text-white"
  >Copy</CopyButton
>
```

**Solid**

```tsx
<CopyButton class="data-copied:bg-neutral-900 data-copied:text-white">
  Copy
</CopyButton>
```

**Web Components**

```html
<copy-button text="npm add @ui-sdk/core">
  <button class="data-copied:bg-neutral-900 data-copied:text-white">
    Copy
  </button>
</copy-button>
```

ARIA 属性也可以当作样式钩子，比如 [构建一个组件](https://ui-sdk.cn/docs/core/build-a-component#style-the-component) 里静音按钮的 `aria-pressed`。对于打开和选中状态，`openAttrs` 和 `checkedAttrs` 返回常见的属性名，[命名](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#naming) 里有说明。

## 把值作为 CSS 变量传入
如果要传的是值而不是开、关状态，比如百分比，就设置一个 CSS 变量。`@ui-sdk/core` 的 `css` 会把声明变成 `style` 属性，并跳过值为 `undefined` 的声明：

```ts
indicator: slot({
  attrs: (state) => ({ style: css({ "--volume": `${state.value}%` }) }),
}),
```

```css
[data-slot="volume-indicator"] {
  width: var(--volume);
}
```

样式也会写进服务器返回的 HTML，所以指示器在页面水合之前就有宽度了。

## 来来去去的部件
带 `present` 的部件，一旦状态把它隐藏，就会立刻离开页面。想让部件进出时有动画，就用 [过渡与手势](https://ui-sdk.cn/docs/core/behaviors/motion#entering-and-leaving) 里的辅助函数，让它在过渡结束前保持呈现。它们会在第一帧加上 `data-starting-style`，并在部件离开期间加上 `data-ending-style`：

```css
[data-slot="disclosure-panel"] {
  transition: opacity 0.15s;

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
  }
}
```

## 在你的框架里
[样式与动画](/docs/styling-and-animation) 介绍了在你的框架里怎么处理类名、CSS Modules，以及 ui-sdk 添加的那一层薄薄的级联层。

## 下一步
你已经定义、渲染并为一个自带行为的原语设置了样式。接下来，[组合行为](/docs/core/compose-behaviors) 会用多个行为构建一个星级评分，只有一个 Tab 停靠点，并支持方向键。


# 组合行为

用共享状态和键盘导航构建一个星级评分。

到目前为止，每个原语都只有自己的一个行为。现在让我们组合 `@ui-sdk/core` 里的行为，构建一个五星评分：`createChange` 上报每一次新的评分，`createRovingFocus` 管理整个组的 Tab 停靠点和方向键。我们会一次加一个。

## 从共享状态开始
评分的 `value` 是一个数字：`0` 表示还没有评分。`defaultValue` 设置起始评分。

创建 `rating.ts`。目前，它有一个容纳星星的根部件，和一个选择值的 `rate` 函数：

```ts title="rating.ts"
import { createChange, definePrimitive, type ChangeDetails } from "@ui-sdk/core"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)

    return {
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
  }),
})

export { rating, type RatingOptions }
```

- `createChange(context)` 返回 `change`。`rate` 用新的值和原因调用它。它会先调用 `onValueChange`，然后更新 `value`，除非回调取消，或者由应用控制。
- `controlled` 和 `sync` 让父级拥有 `value`。`sync` 会把新的 `value` 选项复制进状态。

[处理变更](/docs/core/kernel/handle-changes) 深入介绍变更模式。

在添加星星之前，我们先试试改变值。这些按钮会调用 `rate(3)` 和 `rate(0)`：

按压 Set to 3，再按压 Reset 回到 0。

## 添加一颗星
添加一个 `star` 部件。按压它会把评分设为那颗星的值。

在 `slots` 里、`root` 旁边加上 `star`：

```ts
star: slot<{ value: string }>({
  props: { value: "string" },
  attrs: (state, part) => ({
    type: "button",
    role: "radio",
    "aria-checked": String(Number(part.key) === state.value),
    "data-filled": Number(part.key) <= state.value ? "" : undefined,
  }),
  press: ({ api, key }, event) => api.rate(Number(key), event),
}),
```

- `props` 给每颗星一个 `value`，比如 `"3"`。它会成为这颗星的键。我们用 `Number(key)` 把它作为数字传给 `rate`。[选项种类](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#option-kinds) 列出了属性（prop）可以取的种类。
- `aria-checked` 标记被选中的星。根部件和星星组成一个单选组：从多个选项里选一个。
- `data-filled` 标记直到选中项为止的每一颗星，所以选三颗时，前三颗星会填满。

按压这颗星。评分变成 1，这颗星会填满。

## 把五颗星放进组里
现在用同一个部件渲染五颗星。它们共享一个评分，每颗星有自己的值和无障碍名称。

**React**

```tsx
"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { rating } from "./rating"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  return (
    <Rating aria-label="Rating">
      {Array.from({ length: 5 }, (_, index) => (
        <RatingStar
          key={index}
          value={String(index + 1)}
          aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
        >
          ★
        </RatingStar>
      ))}
    </Rating>
  )
}

export { Example }
```

**Vue**

```vue
<script setup lang="ts">
import { createParts } from "@ui-sdk/vue/primitive"
import { rating } from "./rating"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})
</script>

<template>
  <Rating aria-label="Rating">
    <RatingStar
      v-for="star in 5"
      :key="star"
      :value="String(star)"
      :aria-label="`${star} ${star === 1 ? 'star' : 'stars'}`"
    >
      ★
    </RatingStar>
  </Rating>
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import { createParts } from "@ui-sdk/svelte/primitive"
  import { rating } from "./rating"

  const { Root: Rating, Star: RatingStar } = createParts(rating, {
    root: "div",
    star: "button",
  })
</script>

<Rating aria-label="Rating">
  {#each Array.from({ length: 5 }, (_, index) => index + 1) as star (star)}
    <RatingStar
      value={String(star)}
      aria-label={`${star} ${star === 1 ? "star" : "stars"}`}
    >
      ★
    </RatingStar>
  {/each}
</Rating>
```

**Solid**

```tsx
import { createParts } from "@ui-sdk/solid/primitive"
import { rating } from "./rating"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  return (
    <Rating aria-label="Rating">
      {Array.from({ length: 5 }, (_, index) => (
        <RatingStar
          value={String(index + 1)}
          aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
        >
          ★
        </RatingStar>
      ))}
    </Rating>
  )
}

export { Example }
```

**Web Components**

在应用的浏览器入口文件里注册这些部件：

```ts
import { createParts, wrappedButton } from "@ui-sdk/web"
import { rating } from "./rating"

createParts(rating, {
  root: "my-rating",
  star: { tag: "my-rating-star", target: wrappedButton },
})
```

然后把星星加到你的 HTML 里。每颗星的行为会连接到它内部的原生按钮：

```html
<my-rating aria-label="Rating">
  <my-rating-star value="1"
    ><button aria-label="1 star">★</button></my-rating-star
  >
  <my-rating-star value="2"
    ><button aria-label="2 stars">★</button></my-rating-star
  >
  <my-rating-star value="3"
    ><button aria-label="3 stars">★</button></my-rating-star
  >
  <my-rating-star value="4"
    ><button aria-label="4 stars">★</button></my-rating-star
  >
  <my-rating-star value="5"
    ><button aria-label="5 stars">★</button></my-rating-star
  >
</my-rating>
```

用 `data-filled` 给星星上色，就像 [为组件设置样式](https://ui-sdk.cn/docs/core/kernel/style-a-component#style-its-state) 用 `data-copied` 给复制按钮设置样式那样：

```css
[data-slot="rating"] {
  display: flex;
  gap: 0.25rem;
}

[data-slot="rating-star"][data-filled],
[data-slot="rating-star"]:hover {
  color: #b45309;
}
```

悬停可以预览评分，然后点击选定它。试试 Tab：每颗星仍然有自己的 Tab 停靠点。

## 让组只有一个 Tab 停靠点
让 Tab 只进入这个组一次，落在选中的星上。如果没有选中项，就落在第一颗星上。

`@ui-sdk/core` 的 `createRovingFocus` 负责这件事。把它加到导入里，然后在状态里加上 `focused`：

```ts
state: (options: RatingOptions) => ({
  value: options.value ?? options.defaultValue ?? 0,
  focused: null as string | null,
}),
```

`value` 是评分。`focused` 是拥有 Tab 停靠点的那颗星的键。

更新 `api`，让它创建这个行为，并和 `rate` 一起返回：

```ts {3-9,12}
api: (context) => {
  const change = createChange(context)
  const roving = createRovingFocus(context, {
    slot: "star",
    key: "focused",
    remember: false,
    preferred: (star) => Number(star.key) === context.store.get().value,
    claims: (state, star) => (state.value ? Number(star.key) === state.value : star.key === "1"),
  })

  return {
    roving,
    rate: (value: number, event?: Event) => change("value", value, { reason: "item-press", event }),
  }
},
```

- `slot` 指定要跟踪的部件；`key` 指定要更新的状态字段。
- `preferred` 选择被选中的那颗星。`remember: false` 让焦点回来时回到这个选择。
- `claims` 在元素挂载之前就决定 Tab 停靠点，在服务器上也是如此。它选中被选中的星；没有选择时选第一颗。

现在把星星槽位连接到这个行为。在 `attrs` 里加上 `tabindex`，并在 `press` 旁边加上 `bind`：

```ts {7,11}
star: slot<{ value: string }>({
  props: { value: "string" },
  attrs: (state, part) => ({
    type: "button",
    role: "radio",
    "aria-checked": String(Number(part.key) === state.value),
    tabindex: part.api.roving.tabIndex(state, part),
    "data-filled": Number(part.key) <= state.value ? "" : undefined,
  }),
  press: ({ api, key }, event) => api.rate(Number(key), event),
  bind: (el, part) => part.api.roving.bind(el, part),
}),
```

`bind` 注册每个按钮，并在它卸载时清理。`tabIndex` 给一颗星 `0`，其余的 `-1`。

选择一颗星。Tab 离开这个组；Shift+Tab 回到你的选择。

## 用方向键移动
`createRovingFocus` 处理方向键、Home 和 End，以及从右到左（RTL）的布局。默认情况下它使用 Up 和 Down，像垂直列表一样。

对这个评分来说，我们需要全部四个方向键，而且最后一颗星应该绕回第一颗。在 `createRovingFocus` 的选项里加上 `orientation` 和 `loop`：

```ts
orientation: () => "both",
loop: () => true,
```

Down 和 Right 移到下一颗星，Up 和 Left 移到上一颗。在从右到左的布局里，Left 和 Right 互换。Home 和 End 跳到第一颗和最后一颗星。

行为负责移动焦点；评分决定选中什么。在 `api` 返回的对象里、`rate` 旁边加上 `keydown`：

```ts
keydown(event: KeyboardEvent, el: HTMLElement) {
  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), { reason: "list-navigation", event })
  }
},
```

点击和方向键都会经过 `createChange`。`onValueChange` 回调会收到新的值和原因：`item-press` 或 `list-navigation`。

最后，连接星星的按键事件。在它的 `press` 和 `bind` 字段旁边加上 `on`：

```ts
on: {
  keydown: (event, { el, api }) => {
    if (el) {
      api.keydown(event, el)
    }
  },
},
```

用方向键改变评分。Home 和 End 跳到第一颗和最后一颗星。

## 检查行为
我们可以直接测试这个共享原语。下面是一个很小的 Vitest 测试，它选择三颗星并检查值：

```ts
// rating.test.ts
import { expect, test } from "vitest"
import { rating } from "./rating"

test("choosing a star changes the rating", () => {
  const instance = rating({ id: "rating" })
  instance.api.rate(3)
  expect(instance.get().value).toBe(3)
})
```

要检查焦点和键盘操作，就渲染组件，并运行 `@ui-sdk/core/testing` 的 `checkPattern(root, "radio-group")`。[测试](/docs/core/testing) 展示了怎么做。

## 完整原语
下面是我们添加的所有内容，放在一个文件里：

**显示 rating.ts**

```ts
// rating.ts
import {
  createChange,
  createRovingFocus,
  definePrimitive,
  type ChangeDetails,
} from "@ui-sdk/core"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
    focused: null as string | null,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus(context, {
      slot: "star",
      key: "focused",
      remember: false,
      preferred: (star) => Number(star.key) === context.store.get().value,
      claims: (state, star) =>
        state.value ? Number(star.key) === state.value : star.key === "1",
      orientation: () => "both",
      loop: () => true,
    })

    return {
      roving,
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
      keydown(event: KeyboardEvent, el: HTMLElement) {
        const moved = roving.keydown(event, el)
        if (moved) {
          change("value", Number(moved.key), {
            reason: "list-navigation",
            event,
          })
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
    star: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(Number(part.key) === state.value),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-filled": Number(part.key) <= state.value ? "" : undefined,
      }),
      press: ({ api, key }, event) => api.rate(Number(key), event),
      on: {
        keydown: (event, { el, api }) => {
          if (el) {
            api.keydown(event, el)
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

export { rating, type RatingOptions }
```

## 继续构建
接下来，[处理变更](/docs/core/kernel/handle-changes) 会进一步讲解这个评分用到的变更模式：回调、受控状态、提交和撤销。

- [自定义行为](/docs/core/customize-a-behavior) 给这个评分添加按键，并修改它的规则。
- [焦点与按键](/docs/core/behaviors/focus) 介绍网格，以及在组里移动的其他方式。
- [测试](/docs/core/testing) 检查组件的键盘行为和无障碍。


# 处理变更

上报变更，让应用接受或取消变更，并选择状态更新如何到达页面。

[组合行为](/docs/core/compose-behaviors) 用 `createChange` 上报每一次新的评分。这一页更进一步：接受或取消变更的回调、由父组件控制的状态、提交、频繁更新和撤销。这些辅助函数从 `@ui-sdk/core` 导出。

## 控制状态
来自[构建组件](/docs/core/build-a-component)的静音按钮管理自己的状态。让我们从父组件控制它，并用这个状态改变它的图标和标签。

我们将使用 `createChange`。用高亮标出的改动更新 `lib/mute-button.ts`：

```ts title="lib/mute-button.ts" {1,5-19,22-23}
import { createChange, definePrimitive } from "@ui-sdk/core"

const muteButton = definePrimitive({
  name: "mute-button",
  options: { muted: "boolean", onMutedChange: "callback" },
  controlled: ["muted"],
  state: (options: {
    muted?: boolean
    onMutedChange?: (muted: boolean) => void
  }) => ({
    muted: options.muted ?? false,
  }),
  sync: (options) =>
    options.muted === undefined ? {} : { muted: options.muted },
  api: (context) => {
    const change = createChange(context)

    return {
      toggle: (event?: Event) => {
        change("muted", !context.store.get().muted, { reason: "press", event })
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }, event) => api.toggle(event),
    }),
  }),
})

export { muteButton }
```

- `options` 添加值和回调。`controlled` 把 `muted` 标记为可受控的状态值。
- `state` 设置初始值。当新的 `muted` 值传入时，`sync` 让它保持最新。
- `createChange` 用下一个值调用 `onMutedChange`，并等待它通过 `muted` 返回。如果你省略 `muted`，它会更新按钮自己的状态。

现在标签描述的是下一个动作，所以这个版本不需要 `aria-pressed`。

### 连接状态
现在把 `muted` 用于按钮、它的图标和标签：

**React**

```tsx title="pages/index.tsx"
"use client"

import * as React from "react"
import { Volume2Icon, VolumeXIcon } from "lucide-react"
import { MuteButton } from "@/components/ui/mute-button"

function Example() {
  const [muted, setMuted] = React.useState(false)

  return (
    <MuteButton muted={muted} onMutedChange={setMuted}>
      {muted ? (
        <VolumeXIcon aria-hidden="true" />
      ) : (
        <Volume2Icon aria-hidden="true" />
      )}
      {muted ? "Unmute" : "Mute"}
    </MuteButton>
  )
}

export { Example }
```

**Vue**

```vue title="pages/index.vue"
<script setup lang="ts">
import { ref } from "vue"
import { MuteButton } from "@/components/ui/mute-button"

const muted = ref(false)
</script>

<template>
  <MuteButton v-model:muted="muted">
    <svg
      aria-hidden="true"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
    >
      <path d="m11 5-6 4H2v6h3l6 4z" />
      <path
        :d="
          muted ? 'm16 9 6 6m0-6-6 6' : 'M16 9a5 5 0 0 1 0 6m3-9a9 9 0 0 1 0 12'
        "
      />
    </svg>
    {{ muted ? "Unmute" : "Mute" }}
  </MuteButton>
</template>
```

`v-model:muted` 传递值并监听更新。

**Svelte**

```svelte title="pages/index.svelte"
<script lang="ts">
  import { MuteButton } from "@/components/ui/mute-button"

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

<MuteButton bind:muted>
  <svg
    aria-hidden="true"
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
  >
    <path d="m11 5-6 4H2v6h3l6 4z" />
    <path
      d={muted ? "m16 9 6 6m0-6-6 6" : "M16 9a5 5 0 0 1 0 6m3-9a9 9 0 0 1 0 12"}
    />
  </svg>
  {muted ? "Unmute" : "Mute"}
</MuteButton>
```

`bind:muted` 让按钮和父组件的状态保持同步。

**Solid**

```tsx title="pages/index.tsx"
import { createSignal } from "solid-js"
import { MuteButton } from "@/components/ui/mute-button"

function Example() {
  const [muted, setMuted] = createSignal(false)

  return (
    <MuteButton muted={muted()} onMutedChange={setMuted}>
      <svg
        aria-hidden="true"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <path d="m11 5-6 4H2v6h3l6 4z" />
        <path
          d={
            muted()
              ? "m16 9 6 6m0-6-6 6"
              : "M16 9a5 5 0 0 1 0 6m3-9a9 9 0 0 1 0 12"
          }
        />
      </svg>
      {muted() ? "Unmute" : "Mute"}
    </MuteButton>
  )
}

export { Example }
```

**Web Components**

通过 `muted` 属性传入初始值：

```html title="pages/index.html"
<mute-button muted="false">
  <button>
    <svg
      aria-hidden="true"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
    >
      <path d="m11 5-6 4H2v6h3l6 4z" />
      <path data-volume d="M16 9a5 5 0 0 1 0 6m3-9a9 9 0 0 1 0 12" />
    </svg>
    <span data-label>Mute</span>
  </button>
</mute-button>
```

然后，在按钮的标记出现在页面上之后，从浏览器入口监听 `mutedchange`：

```ts title="main.ts"
import "@/components/ui/mute-button"

let muted = false
const button = document.querySelector("mute-button")
const icon = button?.querySelector("[data-volume]")
const label = button?.querySelector("[data-label]")

if (button && icon && label) {
  button.addEventListener("mutedchange", (event) => {
    muted = (event as CustomEvent<{ value: boolean }>).detail.value
    button.setAttribute("muted", String(muted))
    icon.setAttribute(
      "d",
      muted ? "m16 9 6 6m0-6-6 6" : "M16 9a5 5 0 0 1 0 6m3-9a9 9 0 0 1 0 12"
    )
    label.textContent = muted ? "Unmute" : "Mute"
  })
}
```

适配器把 `muted="false"` 读取为布尔值 `false`。每个事件会一起更新值、图标和标签。

点按可在 Mute 和 Unmute 之间切换。父组件控制值、图标和标签。

按压 **Mute** 会更新父组件里的 `muted`。按钮收到新值，图标和标签也随之更新。

## 变更
这个按钮需要按压两次才能确认。第一次让它进入待命状态；如果你没有再次按压，计时器会解除待命。

在 `api` 中创建一次 `change`，然后在交互发生时从方法里调用它：

```ts
api: (context) => {
  const change = createChange(context)
  return {
    arm: (event?: Event) => change("armed", true, { reason: "press", event }),
  }
},
```

调用 `arm` 会请求 `armed: true`。它先调用 `onArmedChange`，然后如果回调允许且应用没有控制 `armed`，就写入该值。

返回值告诉你请求是否被接受。如果值已经相同或回调取消了它，返回值就是 `false`。对于受控状态，`true` 表示请求已被接受；应用仍然需要把值传回来。

对于不需要回调的内部记录，比如持有 Tab 停靠点的条目，请使用 `context.store.set`：

```ts
context.store.set({ pending: true })
```

## 变更上报什么
试一次点按、一次键盘按压和超时。回调能区分它们。打开 **Lock** 来拒绝变更。

回调会收到请求的值和一个 `details` 对象。例如，应用可以拒绝让按钮进入待命状态：

```ts
onArmedChange: (armed, details) => {
  if (armed && locked) {
    details.cancel()
  }
},
```

- `reason` 说明发生了什么，比如 `"press"` 或 `"timeout"`。
- `event` 是它背后的 DOM 事件，如果有的话。
- `source` 说明它是怎么发生的：`"mouse"`、`"touch"`、`"pen"`、`"keyboard"`、`"virtual"`、`"programmatic"` 或 `"agent"`。
- `cancel()` 拒绝请求；`canceled` 记录这个决定。

虚拟点按背后没有指针或键盘按压，可能来自辅助技术。通过 `@ui-sdk/core/agent` 发起的 Agent 调用会报告 `"agent"`。可以把来源用于分析和焦点选择之类的事情，而不要用它改变哪些动作可用。

调用 `details.cancel()` 来拒绝非受控变更。只调用 `event.preventDefault()` 不会取消它。对于受控状态，应用通过传入新值或保留旧值来决定。

## 原因
原因描述的是交互本身，而不只是说明有东西变了。在这里，应用允许 Close 按钮生效，但可以拒绝 Escape。

声明回调可以接收的原因：

```ts
type NoticeOptions = {
  onOpenChange?: (
    open: boolean,
    details: ChangeDetails<"close-press" | "escape-key">
  ) => void
}
```

如果有合适的内置原因，就使用共享原因。`ReasonVocabulary` 列出了它们，检查 `details.reason` 会收窄 `details.event`：例如 `"escape-key"` 会给你一个 `KeyboardEvent`。当事件与它的原因不匹配时，开发构建还会发出警告。

自定义原因也可以。词汇表之外的原因，比如 `"validation"`，其事件类型是 `Event`。

`isDismissal` 把 Escape、外部按压和滑动等原因归为一组。当同一条规则适用于多种关闭方式时，就用它：

```ts
onOpenChange: (open, details) => {
  if (!open && isDismissal(details.reason) && hasUnsavedChanges) {
    details.cancel()
  }
},
```

## 用户控制的状态
下面的复选框和面板的触发器共享一个由应用持有的值。

[控制状态](https://ui-sdk.cn/docs/core/kernel/handle-changes#control-the-state) 展示了如何连接值、回调和 `sync`。当你让它可复用时，有几个细节很重要：

- 创建状态时读取 `defaultOpen`。之后更改该选项不会重置面板。
- 从 `sync` 只返回受控值。`{}` 不会改动状态；`{ open: undefined }` 会覆盖它。
- 在实例的整个生命周期内，每个键要么受控，要么非受控。开发构建会对切换状态或同时传入 `open` 和 `defaultOpen` 发出警告。
- 这些检查默认覆盖 `open`、`value` 和 `checked`。使用 `controlled: ["expanded"]` 为另一个键启用它们。

## 不是状态的事件
有时回调请求的是一个动作，比如删除文件。没有名为 `delete` 的状态键需要更新。

使用 `dispatch` 调用一个选项，并传入与变更收到的相同的详情：

```ts
remove(file: string, event?: Event) {
  const canceled = dispatch(context, "onDelete", file, { reason: "delete-press", event })
  if (canceled) {
    return
  }
  context.store.set({ files: context.store.get().files.filter((name) => name !== file) })
},
```

当回调取消了动作时，`dispatch` 返回 `true`。在这个例子里，应用用它来保护 readme。

## 提交
拖动音量滑块。拖动过程中值一直在变，但 **Saved** 会在你松开时变化。每次方向键步进都会立即保存。

用 `createChange` 处理持续变化的值，用 `createCommit` 处理交互结束。两者都在 `api` 内创建：

```ts
const change = createChange(context)
const commit = createCommit(context)
```

拖动过程中，上报每个值：

```ts
change("value", value, { reason: "track-press", event })
```

松开时，上报最终值：

```ts
commit("value", context.store.get().value, { reason: "track-press", event })
```

在选项 schema 中声明 `onValueCommit`，并用 `CommitDetails` 标注它的类型。在原语（primitive）定义中添加 `commits: ["value"]`，这样 `observe` 会为每次交互上报一次提交的变更。提交会上报值；它不写入值，也不能被取消。

示例用 `css` 定位滑块手柄，它把声明转成 `style` 属性，并跳过 `undefined` 值：

```ts
style: css({ left: `${state.value}%` }),
```

## 实时状态
把指针悬停在座位上，然后选择一个。悬停变化频繁；选中的座位是另一个值。

在原语的 `live` 字段中列出频繁更新的键：

```ts
live: ["hovered"],
```

然后使用槽位的 `live` 字段，把属性直接写到它的元素上：

```ts
live: live((state, part) => ({
  "data-hovered": state.hovered === part.key ? "" : undefined,
})),
```

这样会更新悬停属性，而不会重新渲染座位。显式读取实时键的渲染函数仍然会订阅它，所以标签可以显示当前悬停的座位。

`selects` 回答的是另一个问题：哪些部件需要知道状态变化？对于选中的座位，每个部件只把值跟自己的键比较：

```ts
selects: selects({ selected: ({ key }) => [key] }),
```

当选择移动时，旧座位和新座位会收到通知。数组值按成员匹配；普通对象按条目匹配。只有列表中的键会以这些方式读取。像把评分之前的每颗星都填满这样的范围比较，需要更新的不止旧值和新值。

## 保持属性最新
在这个过滤器里输入会更新每个条目的 `hidden` 属性，而不会重新渲染这些条目。

当属性本来就应该放在 `attrs` 里时，使用 `direct`：

```ts
item: slot<{ value: string }>({
  props: { value: "string" },
  direct: direct(["hidden"]),
  attrs: (state, part) => ({
    hidden: part.key.toLowerCase().includes(state.query.toLowerCase()) ? undefined : "",
  }),
}),
```

把 `hidden` 留在 `attrs` 里，也会让它出现在服务端渲染的 HTML 中。对于由实时状态驱动的属性用 `live`，对于要让 `attrs` 中选定的属性在两次渲染之间保持最新，用 `direct`。

## 控制器
控制器让组件外部的代码可以调用它的 API。这些按钮通过一个句柄启动和停止倒计时。

给句柄提供它应该暴露的方法：

```ts
function createCountdownController() {
  return createController<{
    start: (seconds: number) => void
    stop: () => void
    left: () => number
  }>()
}
```

原语接收一个 `controller` 选项，其 schema 类型为 `"value"`，句柄会驱动它的 `api` 返回的内容：

```ts
return {
  start,
  stop,
  left: () => context.store.get().left,
}
```

创建一次句柄，并把它传给组件的 `controller` 选项。`controller.start(30)` 会转发给所附加实例的 `start` 方法。在组件附加它之前，方法什么都不做并返回 `undefined`。实例销毁时，句柄会分离。

这些方法自己选择变更原因。例如，倒计时的 `start` 方法会调用 `change("left", seconds, { reason: "imperative" })`；每次计时器滴答使用 `"timeout"`。

## 撤销
涂几个像素，然后撤销和重做。按钮和键盘快捷键共享同一个撤销栈。

`createUndoStack` 存储任意值的快照。在每次编辑后记录结果：

```ts
const stack = createUndoStack(pixels)
stack.record(nextPixels)

const previous = stack.undo()
if (previous !== undefined) {
  show(previous)
}
```

`undo()` 和 `redo()` 返回要显示的值，如果没有可走的步骤则返回 `undefined`。它们不会自己更新组件的状态。`canUndo()` 和 `canRedo()` 告诉你什么时候该禁用按钮。撤销之后记录新的编辑会替换重做分支。

对于键盘快捷键，`matchesShortcut(event, "mod+z")` 在 Apple 平台上识别 Command，在其他平台上识别 Control。重做使用 `"mod+shift+z"`。

要记录页面上每一次变更（包括 Agent 的变更）并在它们之间回退，请参阅[历史与撤销](/docs/agents/connect-an-agent/history-and-undo)。

### 针对输入的撤销
当一连串编辑只占一个撤销步骤时，输入通常感觉更顺手。试着输入、暂停，再继续输入。**Fix** 会把每一步里的“teh”替换掉；**Clear** 会从头开始。

```ts
const stack = createUndoStack("", { limit: 10, groupDelay: 800 })

stack.record(text, { group: "typing" })
stack.seal()
stack.map((text) => text.replaceAll("teh", "the"))
stack.reset("")
```

同一 `group` 中的编辑会合并成一个步骤，前提是间隔低于 `groupDelay`。当这一连串编辑应该结束时，比如光标移动时，调用 `seal()`。`limit` 限制撤销步骤数，`map` 重写每个快照，`reset` 从新值重新开始这个栈。

## 人们是如何操作的
按 Tab 聚焦到保存按钮，然后试着点按它。提示会跟随焦点到达的方式。

`sourceOf(event)` 识别鼠标、触摸、笔、键盘、虚拟或程序化事件。没有事件时，`sourceOf()` 报告最后一次键盘或指针输入。`isFocusFromKeyboard()` 检查焦点是否刚刚从键盘到达：

```ts
save: slot({
  press: ({ api }, event) => api.save(sourceOf(event)),
  on: { focus: (_event, { store }) => store.set({ hint: isFocusFromKeyboard() }) },
}),
```

`createChange` 在原语创建时就开始跟踪输入，因此它的第一次变更就能识别背后的输入。

## 来自别处的变更
图片加载或计时器不需要指针或按键事件。像 `"image-load"` 和 `"timeout"` 这样的共享原因已经解析为程序化来源。要提供自己的来源解析器，把它作为第二个参数传入：

```ts
const change = createChange(context, () => "programmatic")
```

受控拖拽还有一个时序问题：它的草稿可能需要保持可见，直到应用返回已提交的值。`settleDraft(store, value, before, clear)` 处理这个交接。把 getter 作为 `value` 传入，把提交之前的值作为 `before` 传入，再传入一个清理函数，用来检查它仍在清理同一个草稿。[拖放](/docs/core/behaviors/drag-and-drop) 在重排序示例中展示了它。

## API 参考
### 变更上报什么
- `reason` (`string`): Why it changed, like `"escape-key"`. Example: [What a Change Reports](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports).
- `event?` (`Event`): The DOM event behind it, typed by `reason`. Undefined for controllers and cascades. Example: [What a Change Reports](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports).
- `source` (`ChangeSource`): How the user caused it: `"mouse"`, `"touch"`, `"pen"`, `"keyboard"`, `"virtual"` (a click with no pointer or key behind it, which may be assistive technology), `"agent"` (an AI agent's call through `@ui-sdk/core/agent`) or `"programmatic"`. For analytics and focus choices, never for behavior. Example: [What a Change Reports](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports).
- `cancel` (`() => void`): Stops the change. A controlled component ignores it, since the next value comes from you. Example: [What a Change Reports](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports).
- `canceled` (`boolean`): Whether `cancel()` was called. Example: [What a Change Reports](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports).

### 提交上报什么
- `reason` (`string`): What changed the value, like `"drag"` or `"step-key"`. Example: [Commits](https://ui-sdk.cn/docs/core/kernel/handle-changes#commits).
- `event?` (`Event`): The DOM event that ended the interaction, or the one behind the last change when the end was another kind, like a blur after a wheel. Undefined for controllers. Example: [Commits](https://ui-sdk.cn/docs/core/kernel/handle-changes#commits).
- `source` (`ChangeSource`): How the user caused it, like `"mouse"` or `"keyboard"`. Example: [Commits](https://ui-sdk.cn/docs/core/kernel/handle-changes#commits).

### 撤销
- `limit?` (`number`): How many entries are kept. Example: [Undo for Typing](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo-for-typing).
- `groupDelay?` (`number`): Milliseconds of pause after which typing starts a new entry. Example: [Undo for Typing](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo-for-typing).

- `record` (`(state: unknown, { group, time }?: { group?: string; time?: number; }) => void`): Records the state after an edit. Edits of the same `group`, like "insert" or "delete", join the last entry while they come within `groupDelay` of each other. Without a group, the edit is its own entry. Example: [Undo](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo).
- `seal` (`() => void`): Ends the open group, so the next edit starts an entry, like after a caret jump. Example: [Undo for Typing](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo-for-typing).
- `undo` (`() => unknown`): Steps back, and returns the state to show, or `undefined` at the first entry. Example: [Undo](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo).
- `redo` (`() => unknown`): Steps forward again, and returns the state to show, or `undefined` at the last entry. Example: [Undo](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo).
- `canUndo` (`() => boolean`): Whether there's an entry to step back to. Example: [Undo](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo).
- `canRedo` (`() => boolean`): Whether there's an entry to step forward to. Example: [Undo](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo).
- `map` (`(update: (state: unknown) => unknown) => void`): Rewrites every entry, like a token's status changing everywhere without an entry of its own. Example: [Undo for Typing](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo-for-typing).
- `reset` (`(state: unknown) => void`): Starts over from `state`, like after a controlled value from outside. Example: [Undo for Typing](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo-for-typing).

## 下一步
接下来，[自定义行为](/docs/core/customize-a-behavior) 会修改你导入的行为的按键和规则。这是 Core 指南的最后一篇。[参考](/docs/core/reference) 按职责列出每个导出，[行为](/docs/core/behaviors) 则包含用于焦点、选择、浮层等功能的构建块。


# 自定义行为

修改一条规则、添加或移除按键、拒绝一次变更，并在现有行为之上构建自己的行为。

[组合行为](/docs/core/compose-behaviors) 用 `createChange` 和 `createRovingFocus` 构建了一个评分组件。每个行为都有自己的规则：游走焦点（roving focus）决定哪些按键移动焦点、每个按键把焦点移到哪里，以及 Tab 落在哪颗星上。当你的组件需要不同的东西时，保留这个行为，并在下面这些位置之一修改它：

| 你想做的事               | 去哪里                                         |
| ------------------------ | ---------------------------------------------- |
| 修改它的某条规则         | [一个选项](https://ui-sdk.cn/docs/core/customize-a-behavior#change-a-rule)                     |
| 添加一个按键，或去掉一个 | [你的 `api`，围绕这次调用](https://ui-sdk.cn/docs/core/customize-a-behavior#add-a-key)         |
| 选择它运行之后发生什么   | [调用的返回值](https://ui-sdk.cn/docs/core/customize-a-behavior#choose-what-a-move-does)       |
| 在其他组件里复用你的版本 | [包住行为的函数](https://ui-sdk.cn/docs/core/customize-a-behavior#extend-a-behavior)           |
| 修改游走焦点之外的行为   | [同样的位置，按行为分](https://ui-sdk.cn/docs/core/customize-a-behavior#other-behaviors)       |
| 从外部阻止一次变更       | [变更回调](https://ui-sdk.cn/docs/core/customize-a-behavior#refuse-a-change)                   |
| 从组件外部接管一个按键   | [你自己的事件处理函数](https://ui-sdk.cn/docs/core/customize-a-behavior#handle-an-event-first) |

我们会继续处理[那个评分组件](https://ui-sdk.cn/docs/core/compose-behaviors#complete-primitive)。每一步会改动 `rating.ts` 或渲染它的代码中的几行。

## 修改一条规则
行为遵循的每条规则都是一个选项。这个评分组件之所以会从最后一颗星绕回第一颗，是因为它传入了 `loop`。要在任一端停下，就在 `createRovingFocus` 中修改那个选项：

```ts
loop: () => false,
```

大多数选项是函数，所以规则可以依赖状态，也可以依赖组件自己的选项。行为每次需要答案时，它们都会运行。

任何行为都从这里入手：它的选项和指南列在一起，[所有行为](/docs/core/behaviors) 链接到每一个。对于游走焦点，[焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus) 介绍了 `orientation`、`loop`、`disabled`、`focusable`、`preferred` 和 `remember`。

有一个选项走得更远。`move` 会替换所有内置按键，适合内置按键描述不了的布局，比如[数字键盘](https://ui-sdk.cn/docs/core/behaviors/focus#any-layout)。要添加一个按键并保留其余的，就包住这次调用。

## 添加一个按键
游走焦点本身不监听按键。星星的 `keydown` 处理函数调用 `api.keydown`，而后者调用 `roving.keydown`。这次调用由你掌控，所以你可以在行为看到按键之前先处理它。

我们来让数字键跳到某颗星。更新 `api` 返回对象中的 `keydown`：

```ts {2-14}
keydown(event: KeyboardEvent, el: HTMLElement) {
  const modified = event.ctrlKey || event.metaKey || event.altKey
  const star = modified
    ? undefined
    : roving.items().find((item) => item.key === event.key)
  if (star) {
    event.preventDefault()
    roving.focus(star.key)
    change("value", Number(star.key), {
      reason: "list-navigation",
      event,
    })
    return
  }

  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), {
      reason: "list-navigation",
      event,
    })
  }
},
```

- `roving.items()` 返回可以获得焦点的星星。每颗星的键就是它的值，所以按 4 会找到第四颗星。
- `roving.focus(key)` 把焦点移到那颗星。Tab 停靠点会跟随新的评分，和之前一样。
- 其他每个按键仍然会到达 `roving.keydown`，所以方向键、Home 和 End 照常工作。

聚焦一颗星，然后按 4。方向键、Home 和 End 仍然有效。

## 去掉一个按键
要去掉一个按键，就在调用之前返回。把这段加到 `keydown` 顶部，Home 和 End 就不再改变评分：

```ts
if (event.key === "Home" || event.key === "End") {
  return
}
```

行为永远看不到这个按键，所以浏览器会照常处理它。

## 选择一次移动做什么
`roving.keydown` 移动焦点，并告诉你焦点去了哪里。它返回 `key`（移到的条目）、`from`（离开的条目）和 `shift`（是否按住 Shift）。对于不属于它的按键，它返回 `undefined`。

一次移动意味着什么，由组件决定。评分组件会选中焦点落在的那颗星：

```ts
const moved = roving.keydown(event, el)
if (moved) {
  change("value", Number(moved.key), { reason: "list-navigation", event })
}
```

一排按钮可以忽略结果，于是焦点移动，其他什么都不变。文件列表用 `shift` 扩展选择，[范围与全选](https://ui-sdk.cn/docs/core/behaviors/selection#ranges-and-select-all) 展示了这一点。

## 扩展一个行为
数字键现在位于评分组件内部。要在其他组件中使用它们，把它们移进一个函数，这个函数包住行为，并返回行为，用你的 `keydown` 代替原来的版本：

```ts title="number-keys.ts"
import {
  createRovingFocus,
  type PrimitiveContext,
  type RovingFocusOptions,
} from "@ui-sdk/core"

function createNumberKeys<State extends object>(
  context: PrimitiveContext<any, State, any>,
  options: RovingFocusOptions<State>
) {
  const roving = createRovingFocus(context, options)

  return {
    ...roving,
    keydown(event: KeyboardEvent, el: HTMLElement) {
      const modified = event.ctrlKey || event.metaKey || event.altKey
      const items = roving.items()
      const from = items.find((item) => item.el === el)
      const to = modified
        ? undefined
        : items.find((item) => item.key === event.key)
      if (from && to) {
        event.preventDefault()
        roving.focus(to.key)
        return { key: to.key, from: from.key, shift: event.shiftKey }
      }

      return roving.keydown(event, el)
    },
  }
}

export { createNumberKeys }
```

- 它接收与 `createRovingFocus` 相同的 `context` 和选项，所以每个组件仍然传入自己的规则。
- `...roving` 保留 `bind`、`tabIndex`、`items` 以及其余内容。
- 它的 `keydown` 返回与原来相同的结果，所以组件会把数字键当作任何其他移动一样处理。

在 `rating.ts` 中，用 `createNumberKeys` 代替 `createRovingFocus`，选项保持不变。`keydown` 回到它在组合行为里的样子：

```ts
keydown(event: KeyboardEvent, el: HTMLElement) {
  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), { reason: "list-navigation", event })
  }
},
```

任何以数字为键的分组现在都可以使用它。一排分页按钮传入自己的槽位和 `orientation`，就一并获得了数字键。

你的 `keydown` 会在组件调用它的地方运行。你可以用同样的方式替换 `focus` 或 `tabIndex`。在内部，行为继续使用自己的方法：当焦点落在某个条目上时，它调用原来的 `remember`。要改变它自身的行为，请使用它的选项。

## 其他行为
其他行为也在同样的位置修改。它们的规则也是选项。游走焦点从 `keydown` 返回每次移动，而改变值的行为则通过 `set` 把要写入的值交给你。

选择通过 `set` 写入每个新值，所以限制也放在那里。这个选择最多允许三种配料：

```ts
const selection = createSelection(context, {
  key: "value",
  set: (value, details) => value.length <= 3 && change("value", value, details),
  order: () => roving.items().map((item) => item.key),
  multiple: () => true,
})
```

`set` 返回这个值是否被接受。返回 `false` 会让选择保持原样。

下面是你最常使用的行为中该看的位置。每个名字都链接到它的指南：

| 行为                                                                     | 你可以修改的规则                                       | 它交给你什么                                           |
| ------------------------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------ |
| [`createRovingFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus)                    | `orientation`、`loop`、`disabled`、`focusable`、`move` | 每次移动，从 `keydown` 返回                            |
| [`createGridFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#grids)                             | `disabled`、`pageSize`                                 | 每次移动，在 `onMove` 中                               |
| [`createSelection`](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-items)               | `multiple`、`selectable`                               | 每次选择，在 `set` 中                                  |
| [`createListbox`](https://ui-sdk.cn/docs/core/behaviors/lists#options-you-search)                  | `filter`、`loop`                                       | 每次高亮，在 `onHighlight` 中                          |
| [`createReorder`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#reordering)                  | `orientation`、`group`、`disabled`                     | 每个顺序，在 `set` 中；每次播报，在 `message` 中       |
| [`createTransfer`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#moving-between-lists)       | `accepts`、`order`、`disabled`                         | 每次列表间移动，在 `set` 中；每次播报，在 `message` 中 |
| [`createMove`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#moving-in-two-dimensions) | `bounds`、`step`、`disabled`                           | 每个位置，在 `set` 中；每次播报，在 `message` 中       |
| [`createResize`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#resizing-boxes)         | `min`、`max`、`aspect`、`bounds`                       | 每个尺寸，在 `set` 中；每次播报，在 `message` 中       |
| [`createPopup`](https://ui-sdk.cn/docs/core/behaviors/popups#pick-its-behavior)                    | 一个预设，以及 `role`                                  | 每次打开和关闭，在 `onOpenChange` 中                   |

`message` 可以改写其中一条播报，而保留其他播报，因为每个默认值都导出了：`reorderMessage`、`transferMessage`、`moveMessage` 和 `resizeMessage`。[会读出什么](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#whats-read-out) 展示了一个例子。

## 拒绝一次变更
接下来两步不需要改动 `rating.ts`。它们是给渲染评分组件的人用的。

评分组件做出的每次变更都会经过 `change`，它在写入值之前调用 `onValueChange`。回调可以拒绝。这里有一个评价表单，在保存期间保持值不变：

**React**

```tsx
<Rating
  aria-label="Rating"
  onValueChange={(value, details) => {
    if (saving) {
      details.cancel()
    }
  }}
>
  {children}
</Rating>
```

**Vue**

```vue
<Rating
  aria-label="Rating"
  @value-change="(value, details) => saving && details.cancel()"
>
  <slot />
</Rating>
```

**Svelte**

```svelte
<Rating
  aria-label="Rating"
  onValueChange={(value, details) => {
    if (saving) {
      details.cancel()
    }
  }}
>
  {@render children()}
</Rating>
```

**Solid**

```tsx
<Rating
  aria-label="Rating"
  onValueChange={(value, details) => {
    if (saving()) {
      details.cancel()
    }
  }}
>
  {props.children}
</Rating>
```

**Web Components**

```ts
const rating = document.querySelector<HTMLElement>("my-rating")!

rating.addEventListener("valuechange", (event) => {
  if (saving) {
    event.preventDefault()
  }
})
```

它会同样拒绝按压、方向键和数字键，因为它们都通过 `change` 请求。要只拒绝其中一部分，检查 `details.reason`：评分组件会报告 `item-press` 和 `list-navigation`。[变更上报什么](https://ui-sdk.cn/docs/core/kernel/handle-changes#what-a-change-reports) 列出了回调能收到的所有内容。

变更被拒绝时，焦点仍然跟随按键移动。只有值保持不变。

`cancel()` 拒绝评分组件本会自己写入的变更。如果你传入 `value`，就由你决定：保留旧值，评分组件就停在原处。

## 先处理事件
你传给部件的事件处理函数会在部件自己的处理函数之前运行。调用 `event.preventDefault()`，部件就会跳过它对该事件的处理。

假设评分组件位于一个表格行里，Up 和 Down 在行之间移动。拿走这两个按键，把其他按键留给评分组件：

**React**

```tsx
<RatingStar
  value="3"
  onKeyDown={(event) => {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault()
      moveRow(event.key)
    }
  }}
/>
```

**Vue**

```vue
<script setup lang="ts">
function onKeydown(event: KeyboardEvent) {
  if (event.key === "ArrowUp" || event.key === "ArrowDown") {
    event.preventDefault()
    moveRow(event.key)
  }
}
</script>

<template>
  <RatingStar value="3" @keydown="onKeydown" />
</template>
```

**Svelte**

```svelte
<RatingStar
  value="3"
  onkeydown={(event) => {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault()
      moveRow(event.key)
    }
  }}
/>
```

**Solid**

```tsx
<RatingStar
  value="3"
  onKeyDown={(event) => {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault()
      moveRow(event.key)
    }
  }}
/>
```

**Web Components**

```ts
const rating = document.querySelector<HTMLElement>("my-rating")!

rating.addEventListener(
  "keydown",
  (event) => {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault()
      moveRow(event.key)
    }
  },
  { capture: true }
)
```

在捕获阶段监听，监听评分组件或它周围的任何元素。星星自己的监听器在它的按钮上，所以稍后加到那个按钮上的普通监听器会在它之后运行。

Left、Right、Home、End 和数字键仍然属于评分组件。`preventDefault()` 也会阻止浏览器对该按键的默认行为，比如滚动页面。

两者在现成组件上的工作方式相同，因为它们由同样的部件构建。[Tabs](/docs/components/tabs) 接收带 `details.cancel()` 的 `onValueChange`，其列表上的按键处理函数会在方向键生效之前运行。使用 Web Components 时，在那里也要在捕获阶段监听。

## 替换一个行为
行为之间互不了解。评分组件的 `createChange` 和 `createRovingFocus` 只在你的 `api` 中相遇。所以当组件需要自己的焦点规则时，你可以自己写这一块，保留其余部分：变更、回调和受控状态都保持原样。

## 继续构建
- [焦点与按键](/docs/core/behaviors/focus) 包含所有游走焦点选项，每个都有演示。
- [处理变更](/docs/core/kernel/handle-changes) 深入介绍回调、原因和受控状态。
- [测试](/docs/core/testing) 检查修改之后的键盘操作是否仍符合该模式。


# 参考

找到构建组件所需的片段。

在这里找到 Core 中管理状态、添加交互和处理浏览器的辅助函数。每节都有一个小示例，并链接到相关指南。

ui-sdk 还没到 1.0，这些内容在不同版本之间仍可能变化。标为实验性的最有可能变化。

## 状态与部件
`definePrimitive` 把组件的状态、方法和部件放在一起。在它的 `api` 里，用 `createChange` 上报变更：

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

const change = createChange(context)

return {
  mute: () => change("muted", true, { reason: "press" }),
}
```

调用 `mute` 会通过 `onMutedChange` 上报新值。同一个辅助函数同时处理受控和非受控状态，[受控的静音按钮](https://ui-sdk.cn/docs/core/kernel/handle-changes#control-the-state)展示了这一点。

- [定义原语](/docs/core/kernel/define-a-primitive)涵盖选项、槽位、事件和清理。
- [处理变更](/docs/core/kernel/handle-changes)涵盖回调、受控状态和撤销。

## 添加交互
假设你在做一排按钮。`createRovingFocus` 让这一排只有一个 Tab 停靠点，并用左右方向键在按钮之间移动。在原语（primitive）的 `api` 里：

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

const roving = createRovingFocus(context, {
  slot: "item",
  key: "focused",
  orientation: () => "horizontal",
  loop: () => true,
})
```

这决定了焦点如何移动。[焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus)演示如何把它接到按钮上。[组合行为](/docs/core/compose-behaviors)用它来构建星级评分。

其他交互从这里开始：

| 我想……                             | 指南                                              |
| ---------------------------------- | ------------------------------------------------- |
| 选择一个或多个条目                 | [选择](/docs/core/behaviors/selection)                     |
| 重新排序条目，或在列表之间移动条目 | [拖放](/docs/core/behaviors/drag-and-drop)                 |
| 移动、调整大小或滑动元素           | [拖动与调整大小](/docs/core/behaviors/direct-manipulation) |
| 渲染长列表，或就地编辑条目         | [列表](/docs/core/behaviors/lists)                         |
| 导航并展开嵌套条目                 | [树](/docs/core/behaviors/trees)                           |
| 为布局变化添加动画                 | [过渡与手势](/docs/core/behaviors/motion)                  |
| 定位并关闭浮层                     | [浮层与图层](/docs/core/behaviors/popups)                  |
| 在画布上平移、缩放或连接条目       | [画布](/docs/core/behaviors/canvas)                        |
| 处理日历日期                       | [日期](/docs/core/date)                                    |

## 单独使用辅助函数
有些辅助函数不需要原语也能工作。例如，复制成功后，你可以向屏幕阅读器播报：

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

announce("Copied")
```

[平台](/docs/core/platform)涵盖播报、页面方向和键盘快捷键。[文本](/docs/core/text)涵盖搜索、匹配和语言。

要检查你构建的东西，[测试](/docs/core/testing)演示如何测试状态、键盘行为和无障碍。


# 文本

查找条目、为搜索结果排序、高亮匹配项、找回之前的消息，并按正确的语言格式化文本。

用 `createTypeahead` 在用户输入时查找条目，用 `fuzzyScore` 为搜索结果排序，用 `matchRanges` 或 `matchSegments` 高亮匹配项，用 `createInputHistory` 配合方向键找回之前的消息。

`pageLocale` 和 `userLocale` 读取页面或用户的语言，用于匹配和格式化。

## 通过输入查找条目
从几个标签开始。`createTypeahead()` 记住你输入的按键，并返回匹配条目的索引：

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

const fruits = ["Apple", "Pear", "Plum"]
const typeahead = createTypeahead()

typeahead("p", fruits, 0) // 1 (Pear).
typeahead("l", fruits, 1) // 2 (Plum).
```

第三个参数是当前索引。按“p”会在 Apple 之后开始查找；紧接着按“l”会把查询继续为“pl”。没有匹配的查找返回 `-1`。

在下面试试。反复输入“p”在匹配的水果之间循环，或快速输入“pl”找到 Plum。

在 keydown 处理函数中，用 `isTypeaheadKey(event)`（来自 `@ui-sdk/core`）检查某个键是否会输入字符。它把方向键和 Ctrl+C 这类快捷键排除在查找之外。[焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#typeahead)展示如何把结果接到游走焦点（roving focus）上。

## 条目叫什么
条目的标签可能带有快捷键提示。`labelOf(el)` 读取名称，并跳过标记为 `aria-hidden` 的文本：

```html
<button id="copy-command">Copy <kbd aria-hidden="true">⌘C</kbd></button>
```

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

const button = document.getElementById("copy-command")!
labelOf(button) // "Copy".
```

调用键入查找（typeahead）时使用这些标签。如果条目没有可见文本，`labelOf` 会改用它的 `aria-label`。带有 `aria-label="Delete"` 的图标按钮可以通过输入“d”找到。

试试用“c”找 Copy 或 Cut，用“d”找 Delete：

## 带空格的名称
默认情况下，彼此相隔 500 毫秒内输入的按键组成一次查询。如果用户需要更多时间，可以传入更长的超时：

```ts
const typeahead = createTypeahead(1500)
```

查询进行中时，空格会继续它，所以“new y”能找到 New York。`typeahead.active()` 告诉你是否有查询正在进行。用它决定空格应该继续查找还是激活当前条目。

`typeahead.reset()` 立即清除查询。例如，在组件处理 Escape 时调用它：

```ts
if (event.key === "Escape") {
  typeahead.reset()
}
```

在下面试试“new y”。Enter 选中城市；没有进行中的查找时，空格也会选中它。Escape 清除查找，勾选框会给你更多按键间隔时间。

## 给搜索内容排序
搜索框经常需要筛选并排序整个列表。`fuzzyScore(text, query)` 返回 `0` 到 `1` 的分数。保留大于零的结果，再把最匹配的排在前面：

```ts
import { fuzzyScore } from "@ui-sdk/core/text-match"

const commands = ["Open settings", "Settings", "Git push"]
const query = "set"

const ranked = commands
  .map((command) => ({ command, score: fuzzyScore(command, query) }))
  .filter(({ score }) => score > 0)
  .sort((a, b) => b.score - a.score)

ranked.map(({ command }) => command) // ["Settings", "Open settings"].
```

完全匹配得分最高，其次是标签开头的匹配。字母也可以按顺序匹配，所以“gp”能找到“Git push”。空查询会给每个条目 `1` 分。

在下面试试“gp”、“set”或“resu”：

匹配遵循用户的语言。当该语言认为大小写和重音等价时，它们会被忽略，所以输入“resume”也能找到“Résumé”。

## 高亮匹配项
有结果之后，显示匹配的是哪一部分。`matchRanges` 找出范围；`matchSegments` 把原文拆成可以渲染的片段：

```ts
import { matchRanges, matchSegments } from "@ui-sdk/core/text-match"

const ranges = matchRanges("Settings", "set", "startsWith")
// [{ start: 0, end: 3 }].

matchSegments("Settings", ranges)
// [{ text: "Set", match: true }, { text: "tings", match: false }].
```

把每个匹配片段渲染在 `<mark>` 元素里。原文保持不变，包括大小写和重音。

选择搜索使用的匹配模式：

| 模式           | 高亮的内容                                                             |
| -------------- | ---------------------------------------------------------------------- |
| `"contains"`   | 查询第一次出现的位置。                                                 |
| `"startsWith"` | 标签开头的查询，忽略前导空白。                                         |
| `"fuzzy"`      | 查询整体出现时的整个查询，优先从单词开头开始；否则按顺序匹配它的字母。 |

没有匹配会得到空的范围数组。导出的类型是 `MatchRange`，带有 `start` 和 `end`（与 `slice` 接收的一样），以及 `MatchSegment`，带有 `text` 和 `match`。

在下面切换模式看看区别：

## 页面语言
为读者格式化内容时，使用页面的语言。`pageLocale()` 读取文档的 `lang`，浏览器偏好的语言作为回退：

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

const price = new Intl.NumberFormat(pageLocale(), {
  style: "currency",
  currency: "EUR",
})

price.format(12.5)
```

对于带有自己的 `lang` 的区域，把该区域中的元素传给 `pageLocale(el)`。它会读取最近的 `lang` 属性。在原语（primitive）内部，`bind` 是读取它的好地方，因为此时元素已在页面中。

`userLocale()` 直接读取浏览器偏好的语言。搜索辅助函数在比较用户输入的内容时使用这个语言。如果没有可用的 locale，辅助函数返回 `undefined`，`Intl` 则使用其运行时的默认值。

在下面选择一种语言，看看价格和排序的变化。在瑞典语中，Å 和 Ö 排在 Z 之后。

同一个 locale 也适用于 `Intl.DateTimeFormat`、`Intl.ListFormat` 和 `Intl.Collator`。[日期](/docs/core/date)涵盖日历日期。

## 来自其他地方的标签
服务器或旧系统可能给你 `en_US`，而 `Intl` 期望 `en-US`。`toLocale` 会规范化这些标签：

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

toLocale("en_US") // "en-US".
toLocale("de_DE.UTF-8") // "de-DE".
toLocale("??") // undefined.
```

无效的标签会返回 `undefined`，所以你可以把结果传给 `Intl`，让它使用默认 locale。

在下面试试几个标签：

## 正确处理输入法编辑器
中文、日文、韩文、越南文等许多语言都通过输入法编辑器（IME）输入。它分步骤把按键变成文字：用日文输入“nihon”会显示 にほん，然后按 Space 提供 日本，按 Enter 确认。在此之前，文本仍在组合中，对每次按键都做出反应的输入框会作用在片段上。

### 在用户输入时搜索
组合的每一步都会触发 `input` 事件，所以对每次事件都搜索会在词还没完成时先搜 にh 和 にほn。跳过 `isComposing(event)` 标记的事件，等输入法提交后再搜索，也就是在 `compositionend` 时：

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

field.addEventListener("input", (event) => {
  if (!isComposing(event)) search(field.value)
})
field.addEventListener("compositionend", () => search(field.value))
```

Chrome 和 Firefox 在最后一个 `input` 事件之后结束组合，所以 `compositionend` 才会带来已提交的文本。在 Android 上，Gboard 也会组合英文单词，所以那里的结果一次变化一个单词。

用日文或中文输入法输入：搜索会等你确认文本。关闭等待，看看组合每一步都搜索的效果。

### 用 Enter 发送
Enter 经常用来确认输入法的候选，所以在 Enter 时发送的输入框会发送只写了一半的文本。处理按键前先检查 `isComposing(event)`：

```ts
textarea.addEventListener("keydown", (event) => {
  if (event.key !== "Enter" || event.shiftKey || isComposing(event)) return
  event.preventDefault()
  send()
})
```

`isComposing` 也接受 React 的事件，所以同样的几行可以放进 `onChange` 和 `onKeyDown`。它读取事件的 `isComposing`，并把键码 229 也算作组合中，因为 macOS 上的 Safari 会在最后一次 Enter 到达前结束组合，并报告它不在组合中。不需要保存状态：每个事件自己说明输入法是否还在处理它。Core 自带的组件已经处理了这两种情况。

## 找回之前的消息
用 `createInputHistory` 逐步找回用户之前发送的内容，就像终端或聊天框那样。ArrowUp 找回上一条，ArrowDown 找回下一条，越过最新一条再按 ArrowDown 会找回用户正在输入的内容。

在 `api` 中用三个函数创建它：一个返回较早的条目，最旧的排在最前，另外两个读写输入框的值：

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

const history = createInputHistory({
  entries: () => options().history,
  read: () => store.get().value,
  write: (value) => store.set({ value }),
})
```

然后把它接到输入框的按键上。`keydown` 在找回条目时返回 `true`，所以你自己的按键，比如 Enter 发送，要放在它后面：

```ts
root: slot({
  on: {
    keydown: (event, { api }) => {
      if (api.history.keydown(event)) return
      if (event.key === "Enter" && !event.shiftKey && !isComposing(event)) {
        event.preventDefault()
        api.send()
      }
    },
  },
}),
```

按 ArrowUp 找回较早的消息，按 ArrowDown 回到你正在输入的内容。用 Enter 发送一条消息，它就是 ArrowUp 找回的第一条。

在 textarea 中，方向键会先在各行之间移动。只有当光标在 ArrowUp 的第一行，或 ArrowDown 的最后一行时，才会找回条目，长消息换行后的行也算在内。光标会移到找回条目的末尾。

在你浏览其他条目时，对找回条目的修改会保留。当 `entries` 变化时，比如发送之后，它会从最新一条重新开始。调用 `history.reset()` 可以自己做到这一点。

由你的消息生成的对象条目，比如 `messages.map((m) => ({ id: m.id, text: m.text }))`，每次都是新的。传入 `getEntryKey`，比如 `(entry) => entry.id`，条目就会改为按键匹配：列表重新生成时，或你浏览期间有新消息到达时，找回的那一条会保持位置。

按住修饰键时、输入法组合中时、textarea 中选中文本时，以及在只读输入框上，它不会碰方向键。当输入框的 `aria-expanded` 为 `"true"`，或输入框带有 `data-open`（Trigger Menu 会把它设在 textarea 上）时，它也会把方向键留给浮层，比如建议菜单。在 input 上，它适用于 `text`、`search`、`url` 和 `tel` 类型，所以数字输入框保留自己的步进。

### 报告为变更
当组件用 `createChange` 报告值变更时，通过它写入，原因用 `"history-key"`。这样 `onValueChange` 会收到每个找回的条目，并且可以取消它。被取消的变更保持原来的值，并把按键留给浏览器：

```ts
write: (value, event) =>
  change("value", value, { reason: "history-key", event }),
```

### 不是文本的值
条目可以是任何值，比如由文本和 token 组成的列表。对于不是 input 或 textarea 的编辑器，还要传入 `atEdge(direction, event)`：返回 `true` 的条件是光标在 `"up"` 的第一行，或在 `"down"` 的最后一行。

## API 参考
| 用途                                                      | 辅助函数                                                                |
| --------------------------------------------------------- | ----------------------------------------------------------------------- |
| [在用户输入时查找条目](https://ui-sdk.cn/docs/core/text#find-an-item-by-typing)           | `createTypeahead`、`isTypeaheadKey`；查找带有 `active()` 和 `reset()`。 |
| [读取条目的标签](https://ui-sdk.cn/docs/core/text#what-an-item-is-called)                 | `labelOf`                                                               |
| [给搜索结果排序](https://ui-sdk.cn/docs/core/text#rank-what-someone-searches-for)         | `fuzzyScore`                                                            |
| [高亮匹配项](https://ui-sdk.cn/docs/core/text#highlight-what-matched)                     | `matchRanges`、`matchSegments`、`MatchRange`、`MatchSegment`            |
| [选择语言](https://ui-sdk.cn/docs/core/text#the-pages-language)                           | `pageLocale`、`userLocale`、[`toLocale`](https://ui-sdk.cn/docs/core/text#tags-from-elsewhere)          |
| [处理输入法编辑器](https://ui-sdk.cn/docs/core/text#properly-handle-input-method-editors) | `isComposing`                                                           |
| [找回之前的消息](https://ui-sdk.cn/docs/core/text#bring-back-earlier-messages)            | `createInputHistory`；历史记录带有 `keydown()` 和 `reset()`。           |

排序和高亮辅助函数来自 `@ui-sdk/core/text-match`。其他辅助函数来自 `@ui-sdk/core`。


# 数字

步进、缩放、格式化和读取用户语言中的数字，并用一套键盘映射处理数字控件。

`@ui-sdk/core/number` 提供步进与边界、缩放、格式化、解析，以及数字控件共享的键盘映射。

这些辅助函数是不依赖 DOM 的普通函数。Slider、Number Input、Progress 和 Meter 使用同一套辅助函数，所以你自己写的控件也能像它们一样步进、格式化和读取数字。

## 边界与步进
### 按步进吸附
`scrubTo` 把值放到边界内的步进网格上，`stepValue` 从它出发移动若干步。两者都会舍去浮点噪声，所以 `0.1 + 0.2` 步会落在 `0.3`：

```ts
import { clamp, roundTo, scrubTo, stepValue } from "@ui-sdk/core/number"

const range = { min: 0, max: 10, step: 0.25 }

scrubTo(3.3, range).value // 3.25
stepValue(3.3, 1, range) // 3.5, off the grid moves onto it first
stepValue(9.9, 1, range) // 10
clamp(14, 0, 10) // 10
roundTo(0.1 + 0.2, 2) // 0.3
```

`min` 有限时，网格从它开始，和原生 range input 一样，所以 `{ min: 1, max: 10, step: 2 }` 会经过 1、3、5、7 和 9。`maxOnGrid` 返回那个最大值，`decimalsOf` 计算一个数字的小数位数。给范围设置 `snap` 点后，`scrubTo` 也会落在这些点上，[拖动](https://ui-sdk.cn/docs/core/number#snap-while-scrubbing)一节展示了这一点。步进为 0 时没有网格，所以值会原样留在边界内。

### 循环
`wrap` 让值保持在循环中，用于色相、角度、钟面和绕圈旋转的轮播：

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

wrap(370, 0, 360) // 10
wrap(-15, 0, 360) // 345
wrap(slide + 1, 0, slides.length) // the next slide, back to the first after the last
```

## 按键
### 一套键盘映射
`stepFromKey` 把按键读成一次移动，正如 APG 的 slider 和 spinbutton 模式所述：Up 和 Right 向上步进，Down 和 Left 向下步进，Shift 采用大步，Alt 采用小步，Page Up 和 Page Down 采用大步，Home 和 End 跳到边界。`stepBy` 应用这次移动：

```ts
import { stepBy, stepFromKey } from "@ui-sdk/core/number"

const range = { min: 0, max: 20, step: 0.5, largeStep: 5, smallStep: 0.1 }

function onKeyDown(event: KeyboardEvent) {
  const move = stepFromKey(event, { arrows: "vertical" })
  if (!move) return
  event.preventDefault()
  value = stepBy(value, move, range)
}
```

聚焦数量，按方向键，配合 Shift 或 Alt 得到更大和更小的步进，然后试试 Home 和 End。输入一个重量并按 Enter：它会吸附到步进上。

在水平控件上，从右到左（RTL）会翻转 Left 和 Right，通过 `{ dir: "rtl" }` 设置；垂直控件保持它们不变。`{ arrows: "vertical" }` 把 Left 和 Right 留给文本光标，就像数字输入框那样。没有 `largeStep` 时，大步是十步；没有 `smallStep` 时，小步是一步。输入法组合期间，比如用日文输入法输入全角数字，`stepFromKey` 返回 null，这样用于选择候选的箭头不会同时步进。

一次移动是 `{ direction, size }` 或 `{ bound }`，所以控件可以按自己的方式处理边界，比如滑块手柄停在相邻位置。

## 位置与刻度
### 从值到位置
`fractionOf` 给出值在边界之间的位置，从 0 到 1，`valueAt` 给出某个位置上的值。两者一起可以放置滑块手柄、填充进度条，并把一次按压变成值：

```ts
import { fractionOf, scrubTo, valueAt } from "@ui-sdk/core/number"

fractionOf(30, { min: 0, max: 120 }) // 0.25
const pressed = valueAt((event.clientX - box.left) / box.width, range)
scrubTo(pressed, range).value
```

超出边界的值会停在某一端，相同的边界会得到 0。

### 对数与自定义刻度
在对数刻度上，每十倍取相同的距离，正如频率、音量和缩放控件需要的那样。传入 `"log"`，并带有正的 `min`，或传入一对 `to` 和 `from`，把值映射到均匀空间再映射回来：

```ts
fractionOf(200, { min: 20, max: 20000 }, "log") // 0.33: 20 to 200 is a third of the way
valueAt(0.5, { min: 20, max: 20000 }, "log") // 632, halfway by ratio

const area = { to: Math.sqrt, from: (position: number) => position * position }
fractionOf(25, { min: 0, max: 100 }, area) // 0.5: a size that feels even by area, like a brush
```

拖动滑块，把指针从 1° 转到 180°，然后在 Linear 和 Log 之间切换。在对数刻度上，小角度占据滑块的大部分：45° 位于 73% 处，而半程只转到 13°。

要让带刻度的控件均匀步进，就步进它的位置，再读回值，比如 `valueAt(stepBy(fraction, move, { min: 0, max: 1, step: 0.01 }), range, "log")`。

## 拖动
### 拖动时吸附
给范围设置 `snap` 点和 `threshold`，当拖动到离点不超过阈值的距离时，就会落在点上，比如时间线的章节或编辑器的关键帧。`scrubTo` 读取指针或滑块，`stepBy` 为按键采用相同的点：一步会停在向前遇到的第一个点，而离开当前所在的点时不受限制：

```ts
import { scrubTo, stepBy, stepFromKey } from "@ui-sdk/core/number"

const range = {
  min: 0,
  max: 60,
  step: 0.1,
  snap: { points: [0, 9.5, 24, 38.5, 52], threshold: 1.5 },
}

scrubTo(23, range) // { value: 24, point: 24 }
scrubTo(23, range, { snap: false }) // { value: 23, point: undefined }

function onKeyDown(event: KeyboardEvent) {
  const move = stepFromKey(event)
  if (!move) return
  event.preventDefault()
  time = stepBy(time, move, range, { snap: !event.metaKey })
}
```

`{ snap: false }` 会忽略这些点，比如按住 Cmd 或输入数字时，但仍然落在步进网格上。滑块的 `input` 事件不会说明按下了哪些键，所以要从它的指针事件中读取：

```tsx
<input
  type="range"
  onPointerDown={(event) => (free = event.metaKey)}
  onPointerMove={(event) => (free = event.metaKey)}
  onChange={(event) =>
    setTime(scrubTo(Number(event.target.value), range, { snap: !free }).value)
  }
/>
```

拖动滑块：播放头在进入 1.5 秒范围内时吸附到每个区段，方向键也会停在每个区段。按住 Command 或 Ctrl 可以自由拖动和步进。

`point` 表示值被拉向哪个吸附点，所以释放时可以提交 `point ?? value`。使用 `{ ease: true }` 时，靠近点的值会向它移动，而不是跳过去：在阈值处完全不动，越接近越快，最后落在点上。拖动时显示 `value`，结束时落在 `point`：

```ts
scrubTo(23.25, range, { ease: true }) // { value: 23.625, point: 24 }
scrubTo(22.5, range, { ease: true }) // { value: 22.5, point: 24 }, at the threshold
```

传入一条关于接近程度的曲线，从阈值处的 0 到点上的 1，比如 `{ ease: (t) => t * t }`，用来改变拉力累积的方式。[超过阈值后折叠](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#collapse-past-a-threshold)让侧边栏缓动到折叠状态。

把 Up 和 Down 留给页面的控件，比如轨道列表中的时间线，会把 `{ arrows: "horizontal" }` 传给 `stepFromKey`。

## 格式化
### 任意语言的数字
`formatNumber` 通过 `Intl.NumberFormat` 按 locale 显示值：货币、百分比、单位和紧凑计数，使用该 locale 自己的数字和分隔符。传入一个函数可以自定义文本。null 和非有限值显示为空文本：

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

formatNumber(1234.5, "de-DE", { style: "currency", currency: "EUR" }) // "1.234,50 €"
formatNumber(1234.5, "ja-JP", { style: "currency", currency: "JPY" }) // "￥1,235"
formatNumber(1234.5, "zh-CN", { style: "currency", currency: "CNY" }) // "¥1,234.50"
formatNumber(0.256, "en-US", { style: "percent", maximumFractionDigits: 1 }) // "25.6%"
formatNumber(1234567, "en-US", { notation: "compact" }) // "1.2M"
formatNumber(3, "en-US", (value) => `${value} of 5 stars`) // "3 of 5 stars"
```

把同样的文本用于控件的 `aria-valuetext`，让屏幕阅读器读出显示的内容。`numberFormatter` 返回 `Intl.NumberFormat` 本身，按 locale 和选项各构建一次。

### 范围与部件
`formatNumberRange` 只写一次两端共有的内容，`formatNumberToParts` 返回每个数字组和符号，以便分别设置样式，或像里程表那样滚动数字：

```ts
import { formatNumberRange, formatNumberToParts } from "@ui-sdk/core/number"

formatNumberRange(5, 10, "en-US", { style: "currency", currency: "USD" }) // "$5.00 – $10.00"
formatNumberToParts(1234.5, "en-US", { style: "currency", currency: "USD" })
// [{ type: "currency", value: "$" }, { type: "integer", value: "1" }, { type: "group", value: "," }, …]
```

选择一个 locale 和一种样式。大数字由它的各部件构成，小数和货币部分变暗，范围则共享两端共有的内容。

## 输入数字
### 读取用户输入的内容
`parseNumber` 读取按某个 locale 格式输入的数字：它的数字、分组和小数分隔符、负号，以及货币、百分比和单位文本。不是数字的文本会返回 null，百分比格式会除以 100。`isPartialNumber` 说明文本是否仍可能变成一个数字，所以输入框可以对单独的 `"-"` 保持等待，而不是拒绝它：

```ts
import { isPartialNumber, parseNumber } from "@ui-sdk/core/number"

parseNumber("1.234,5", "de-DE") // 1234.5
parseNumber("٣٫٥", "ar-EG") // 3.5
parseNumber("50 %", "fr-FR", { style: "percent" }) // 0.5
parseNumber("-", "de-DE") // null
isPartialNumber("-", "de-DE") // true
```

按该 locale 的写法输入一个金额，或切换 locale。还在输入中的数字会等待；无法变成数字的文本会被标记。

## API 参考
这些函数都来自 `@ui-sdk/core/number`。

| 你想做什么                 | 使用                                                                                                      |
| -------------------------- | --------------------------------------------------------------------------------------------------------- |
| 让值在边界内落在步进网格上 | [`scrubTo`, `stepValue`, `clamp`, `roundTo`, `decimalsOf`, `maxOnGrid`](https://ui-sdk.cn/docs/core/number#snap-to-a-step)                  |
| 让值保持在循环中           | [`wrap`](https://ui-sdk.cn/docs/core/number#loops)                                                                                          |
| 把按键变成步进             | [`stepFromKey`, `stepBy`](https://ui-sdk.cn/docs/core/number#one-keyboard-map)                                                              |
| 在值与位置之间映射         | [`fractionOf`, `valueAt`](https://ui-sdk.cn/docs/core/number#value-to-position)                                                             |
| 让拖动吸附到点             | [`scrubTo`, `stepBy`](https://ui-sdk.cn/docs/core/number#snap-while-scrubbing)                                                              |
| 按用户的语言显示数字       | [`formatNumber`, `formatNumberRange`, `formatNumberToParts`, `numberFormatter`](https://ui-sdk.cn/docs/core/number#numbers-in-any-language) |
| 读取输入的数字             | [`parseNumber`, `isPartialNumber`](https://ui-sdk.cn/docs/core/number#read-what-people-type)                                                |


# 日期

处理日历日期、构建月份网格，并按用户的语言读取和格式化日期。

`@ui-sdk/core/date` 提供日期运算、月份网格、本地化标签，以及供日历和日期输入框使用的解析。

这些辅助函数处理 `"2026-10-16"` 这样的日期字符串，无需 DOM 即可运行。Calendar 和 Date Picker 使用相同的辅助函数。

## 字符串形式的日期
### 真实日期
用 `isoDate` 构建日期，用 `dateParts` 读取它的字段。月份从 1 到 12。日期不存在时，两个函数都返回 `undefined`：

```ts
import { dateParts, isISODate, isoDate } from "@ui-sdk/core/date"

isoDate(2026, 10, 16) // "2026-10-16"
isoDate(2026, 2, 30) // undefined
dateParts("2026-10-16") // { year: 2026, month: 10, day: 16 }
isISODate("2026-02-30") // false
```

把 2 月 30 日改成 2 月 28 日，得到有效日期。在下面选择另一个日期，读取它的年、月、日，或按压 Today。

这些字符串使用 `YYYY-MM-DD`，与 `<input type="date">` 的格式相同。有效日期按日期顺序排序，所以 `start < end` 这样的比较可以直接使用。

要引入已有的值，使用 `toISODate`。它接受 ISO 字符串、`Date`，或带有 `year`、`month` 和 `day` 的对象，包括 `Temporal.PlainDate`：

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

toISODate({ year: 2026, month: 10, day: 16 }) // "2026-10-16"
toISODate(new Date()) // Today's date in the runtime's local time zone.
```

`Date` 表示一个时刻，所以这个转换使用它的本地年、月、日。得到的字符串不带时区。

## 运算
### 整日
对于三晚的住宿，在入住日期上加三天：

```ts
import { addDays, daysBetween } from "@ui-sdk/core/date"

addDays("2026-12-24", 3) // "2026-12-27"
daysBetween("2026-12-24", "2026-12-27") // 3
```

负数向后移动。运算按整日进行，所以跨过夏令时变化不会多一天或少一天。

用 `clampDate` 把日期保持在预订季节内。`weekday` 对周日返回 0，对周六返回 6：

```ts
import { clampDate, weekday } from "@ui-sdk/core/date"

clampDate("2026-10-20", "2026-11-01", "2027-01-31") // "2026-11-01"
weekday("2026-12-24") // 4: Thursday.
```

更改入住日期或住宿晚数。试试把入住日期设在 11 月 1 日之前，看它移进预订季节。

### 周与月
按月移动时，尽可能保留日。1 月 31 日会变成 2 月 28 日，因为 2 月没有 31 日：

```ts
import { addMonths, addYears } from "@ui-sdk/core/date"

addMonths("2026-01-31", 1) // "2026-02-28"
addYears("2028-02-29", 1) // "2029-02-28"
```

需要边界时，使用 `startOfWeek` 和 `endOfWeek`，或 `startOfMonth` 和 `endOfMonth`。按周的辅助函数接收一周的第一天，周日为 0：

```ts
import {
  daysInMonth,
  endOfMonth,
  isSameMonth,
  startOfWeek,
} from "@ui-sdk/core/date"

startOfWeek("2026-10-16", 1) // "2026-10-12": Monday.
endOfMonth("2026-02-10") // "2026-02-28"
daysInMonth(2028, 2) // 29
isSameMonth("2026-09-28", "2026-10-04") // false
```

在 1 月 31 日按压 + Month，然后更改一周从哪一天开始。Reset 并加两年，在闰年试试同样的移动。

## 月份网格
### 可供选择的月份
`monthGrid` 返回由七个 ISO 日期组成的行。相邻月份的日期会填补边缘。用 `weekStartsOn` 选择一周的第一天：

```ts
import { firstDayOfWeek, monthGrid } from "@ui-sdk/core/date"

const weeks = monthGrid("2026-10-01", {
  weekStartsOn: firstDayOfWeek("de-DE"),
})
// The first week runs from "2026-09-28" to "2026-10-04".
```

每周渲染一行，每个日期渲染一个按钮。这个示例加入了[游走焦点（roving focus）](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus)，把每个日期当作键。它自定义的 `move` 在水平方向键时加一天，垂直方向键时加七天。当焦点到达另一个月份时，示例会渲染那个月份。

用 Tab 进入月份，用方向键按天和周移动。移出月份可以翻页，或更改 locale 看看不同的每周第一天。

### 贴合月份的周
网格默认有六周，这样相邻的日历高度一致。传入 `fixedWeeks: false` 只返回该月需要的周：

```ts
monthGrid("2026-02-01").length // 6
monthGrid("2026-02-01", { fixedWeeks: false }).length // 4
```

取消勾选 Six weeks each。在每周从周日开始时，2026 年 2 月、3 月和 8 月分别需要四行、五行和六行。

## 名称与标签
### 任意语言的名称
传入 locale，为阅读者格式化日期。不传时，这些函数使用运行时的 locale：

```ts
import { formatDate, formatDateRange } from "@ui-sdk/core/date"

formatDate("2026-10-16", "de-DE") // "Freitag, 16. Oktober 2026"
formatDate("2026-10-16", "en-US", { month: "long", year: "numeric" }) // "October 2026"
formatDateRange("2026-10-16", "2026-10-20", "en-US") // "Oct 16 – 20, 2026"
```

`formatDate` 接受 `Intl.DateTimeFormat` 选项。它的默认值包括星期、日、月和年，这为日期按钮提供了有用的无障碍标签。

日历的标题需要单独获取月份和星期名称。保持星期名称与网格相同的顺序：

```ts
import { firstDayOfWeek, monthNames, weekdayNames } from "@ui-sdk/core/date"

const firstDay = firstDayOfWeek("de-DE") // 1: Monday.
const weekdays = weekdayNames("de-DE", "short", firstDay)
const months = monthNames("de-DE")
```

你可以用 [`pageLocale`](https://ui-sdk.cn/docs/core/text#the-pages-language) 获取页面的 locale。`firstDayOfWeek` 也遵循显式的一周偏好，比如 `"en-US-u-fw-mon"` 表示周一。

更改 locale，比较日期标签、范围、星期顺序和月份名称。选择 Persian，看看相同公历日期上的本地化标签。

需要分别设置样式的标签时，`formatDateToParts` 返回每个格式化片段及其类型：

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

const parts = formatDateToParts("2026-10-16", "en-US", {
  month: "long",
  day: "numeric",
})
// [{ type: "month", value: "October" }, { type: "literal", value: " " }, { type: "day", value: "16" }]
```

这些辅助函数使用 `Intl` 并复用它提供的格式化器。它们让月份和日期标签与公历网格保持一致。使用不同月份体系的 locale，比如 Persian，仍使用公历标签；共享这些月份的日历，比如泰国佛历，可以保留自己的年份。`dateFormatter(locale, options)` 在需要直接使用时暴露缓存的格式化器。

### 今天
`todayDate()` 返回代码运行处的今天日期。当日期属于特定地点时，传入时区：

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

todayDate()
todayDate("Asia/Tokyo")
```

把每个城市的今天日期与 Here（浏览器的本地日期）比较。临近午夜时，不同城市可能显示不同的日期。

服务端渲染（SSR）时，在服务器和客户端传入相同的时区，或等到组件挂载后再标记今天。

## 输入日期
### 读取用户输入的内容
`parseDate` 读取 locale 的日期顺序，返回 ISO 日期。输入不完整或无效时返回 `undefined`：

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

parseDate("10/16/2026", "en-US") // "2026-10-16"
parseDate("16.10.2026", "de-DE") // "2026-10-16"
parseDate("16 oct 2026", "fr") // "2026-10-16"
parseDate("Feb 30", "en-US") // undefined
```

点、斜杠和空格都可以作分隔符。解析器还接受 ISO 日期、月份名称、locale 数字，以及不带分隔符的数字，比如德语中的 `"16102026"`。

年份缺失时，解析器使用参考日期的年份。参考日期默认是当前年份。如果结果需要保持可预测，传入 `referenceDate`：

```ts
parseDate("October 16", "en-US", { referenceDate: "2026-01-01" }) // "2026-10-16"
parseDate("16.10.70", "de-DE", { referenceDate: "2026-01-01" }) // "1970-10-16"
parseDate("16.10.70", "de-DE", { referenceDate: "2060-01-01" }) // "2070-10-16"
```

两位年份落在 100 年的窗口内，窗口到参考年份之后 20 年为止。

输入一个日期，然后更改 locale 试试另一种顺序。在德语中输入 16.10.70，并把参考年份从 2026 改成 2060，看看使用哪个世纪。

用 `datePattern` 生成输入框的占位符和显示顺序的提示：

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

const pattern = datePattern("de-DE")
pattern.fields // ["day", "month", "year"]
pattern.placeholder // "TT.MM.JJJJ"
pattern.separator // "."
// pattern.example is December 31 in the current year, written in this locale.
```

## API 参考
这些函数都来自 `@ui-sdk/core/date`。

| 你想做什么                   | 使用                                                                                                                                       |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| 校验或转换日期               | [`isoDate`, `isISODate`, `dateParts`, `toISODate`](https://ui-sdk.cn/docs/core/date#real-dates)                                                                            |
| 移动日期或计算住宿时长       | [`addDays`, `daysBetween`, `weekday`, `clampDate`](https://ui-sdk.cn/docs/core/date#whole-days)                                                                            |
| 在月份之间移动或找出月份边界 | [`addMonths`, `addYears`, `startOfWeek`, `endOfWeek`, `startOfMonth`, `endOfMonth`, `daysInMonth`, `isSameMonth`](https://ui-sdk.cn/docs/core/date#weeks-and-months)       |
| 为日历构建行                 | [`monthGrid`](https://ui-sdk.cn/docs/core/date#month-grids)                                                                                                                |
| 为日期和日历标题添加标签     | [`formatDate`, `formatDateRange`, `formatDateToParts`, `monthNames`, `weekdayNames`, `firstDayOfWeek`, `dateFormatter`](https://ui-sdk.cn/docs/core/date#names-and-labels) |
| 在时区中查找今天             | [`todayDate`](https://ui-sdk.cn/docs/core/date#today)                                                                                                                      |
| 读取输入的日期或显示其格式   | [`parseDate`, `datePattern`](https://ui-sdk.cn/docs/core/date#typing-a-date)                                                                                               |


# 颜色

读取、转换并写出 CSS 颜色，把颜色适配到屏幕能显示的范围，并检查它们之间的对比度。

`@ui-sdk/core/color` 读取 CSS 颜色，在色彩空间之间转换，再把它们写回 CSS，把颜色适配到屏幕的色域，并比较两种颜色。

这些辅助函数是操作普通数据的普通函数，不依赖 DOM 就能运行。你自己的颜色输入框、色板列表或主题编辑器，可以用它们读写颜色。

## 颜色即数据
### 读取 CSS 颜色
`parseColor` 把任意 CSS 颜色读成它所在的色彩空间、三个通道和一个 alpha 值。对不是颜色的文本，它返回 null：

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

parseColor("#ff0000") // { space: "srgb", coords: [1, 0, 0], alpha: 1 }
parseColor("oklch(0.7 0.15 250 / 50%)") // { space: "oklch", coords: [0.7, 0.15, 250], alpha: 0.5 }
parseColor("rebeccapurple") // { space: "srgb", coords: [0.4, 0.2, 0.6], alpha: 1 }
parseColor("not a color") // null
```

它能读取十六进制、命名颜色、`transparent`、`rgb()`、`hsl()`、`hwb()`、`lab()`、`lch()`、`oklab()`、`oklch()`，以及 `srgb`、`srgb-linear`、`display-p3` 和 `xyz` 空间中的 `color()`，也支持 `rgba(255, 0, 0, 0.5)` 这样的旧逗号语法。颜色会保留它书写时所在的色彩空间，各通道使用 CSS 给它们的范围：sRGB 和 Display P3 是 0 到 1，HSL 的饱和度这类百分比是 0 到 100，色相则用角度。CSS 会限制超出范围的值，比如 `rgb(300 0 0)`，这里也同样处理。

### 缺失的通道
写成 `none` 的通道就是缺失的，读出来是 null。灰色没有色相，所以把它转换到带色相的色彩空间时，色相也会保持缺失：

```ts
import { convertColor, parseColor } from "@ui-sdk/core/color"

parseColor("oklch(0.7 0.1 none)")!.coords // [0.7, 0.1, null]
convertColor(parseColor("white")!, "oklch").coords // [1, 0, null]
```

颜色转换时，缺失的通道按 0 计算。当有人把滑块拖到灰色再拖回来时，你要自己记住上一个色相，这样它不会跳到红色。

## 转换
### 空间之间
`convertColor` 返回同一种颜色在另一个色彩空间中的表示：

```ts
import { convertColor, parseColor } from "@ui-sdk/core/color"

const red = parseColor("red")!

convertColor(red, "hsl").coords // [0, 100, 50]
convertColor(red, "oklch").coords // [0.628, 0.258, 29.234], rounded
convertColor(red, "srgb") === red // true, it's already sRGB
```

这些空间都是 CSS 的：`"srgb"`、`"srgb-linear"`、`"display-p3"`、`"hsl"`、`"hwb"`、`"lab"`、`"lch"`、`"oklab"`、`"oklch"`、`"xyz-d65"` 和 `"xyz-d50"`，外加 `"hsv"`，大多数取色器都在这个空间里画它们的方形色板。OKLCH 的明度、色度和色相的变化方式与人感知到的一致，所以按明度步进时色相保持不变，明度相同的两种颜色看起来也一样亮。

## 写出 CSS
### 格式
`formatColor` 把颜色写成 CSS，用它自己的色彩空间，或者用你传入的格式：

```ts
import { formatColor, parseColor } from "@ui-sdk/core/color"

const red = parseColor("red")!

formatColor(red) // "rgb(255 0 0)"
formatColor(red, "hex") // "#ff0000"
formatColor(red, "oklch") // "oklch(0.628 0.2577 29.23)"
formatColor(red, "display-p3") // "color(display-p3 0.9175 0.2003 0.1386)"
formatColor(red, "oklch", { precision: 3 }) // "oklch(0.63 0.26 29)"
```

`"srgb"` 写成 `rgb()`，没有自己函数的色彩空间写成 `color()`。小于 1 的 alpha 写在斜杠后面，或者在十六进制里写进第四个字节。HSV 没有 CSS 语法，所以 HSV 颜色写成 `hsl()`。

`precision` 设置每个通道的有效数字，默认是 5，按各通道的范围来算：`rgb()` 得到两位小数，OKLCH 的明度得到四位。十六进制、`rgb()`、`hsl()` 和 `hwb()` 只能容纳 sRGB 颜色，所以更广的颜色会被裁剪以适应范围。先用 [`toGamut`](https://ui-sdk.cn/docs/core/color#fit-a-screen) 映射一下，可以让结果更接近原色。

输入任意 CSS 颜色，比如 #7654cd 或 lab(60 40 -60)，每种格式都会更新。下面一行说明哪些屏幕能显示它。试试 oklch(0.7 0.35 150)，让它超出 P3 的范围。

## 色域
### 适配屏幕
色域是屏幕能显示的颜色范围。每块屏幕都能显示 sRGB，大多数手机和笔记本能显示更广的 P3。`isInGamut` 表示颜色是否在范围内，`toGamut` 在颜色自己的色彩空间里返回范围内最接近的颜色：

```ts
import { formatColor, isInGamut, parseColor, toGamut } from "@ui-sdk/core/color"

const green = parseColor("oklch(0.7 0.25 150)")!

isInGamut(green) // false
isInGamut(green, "p3") // true
formatColor(toGamut(green)) // "oklch(0.7091 0.2103 147.07)"
formatColor(toGamut(green), "hex") // "#00c248"
toGamut(green, "p3") === green // true, it already fits
```

`toGamut` 的映射方式与 CSS Color 4 及浏览器一致：它在 OKLCH 中降低色度，保持明度和色相，直到裁剪剩下的部分也看不出差别。这样鲜艳的绿色仍然是绿色，而逐个通道裁剪可能会让它的色相偏移。

## 混合
### 混合两种颜色
`mixColor` 按 CSS `color-mix()` 的方式混合两种颜色。传入你想要第二种颜色的比例，从 0 到 1：

```ts
import { formatColor, mixColor, parseColor } from "@ui-sdk/core/color"

const blue = parseColor("#2563eb")!
const yellow = parseColor("#facc15")!

formatColor(mixColor(blue, yellow), "hex") // "#90a3ad", halfway in Oklab
formatColor(mixColor(blue, yellow, 0.25, { space: "srgb" })) // "rgb(90.25 125.25 181.5)"
```

颜色默认在 Oklab 中混合，两种颜色之间的过渡看起来均匀。设置 `space` 可以换到其他色彩空间混合，结果也在那个空间里。半透明颜色按各自的 alpha 混合，和 `color-mix()` 一样，所以透明颜色不会让另一种颜色变暗。

选两种颜色，看看它们之间怎样一步步过渡。选 sRGB，中间会变暗；选 OKLCH，中间保持鲜艳，会经过绿色。

### 色相
在带色相的色彩空间里，比如 OKLCH 或 HSL，色相沿色轮走较短的一边。把 `hue` 设为 `"longer"`、`"increasing"` 或 `"decreasing"`，可以换一个方向：

```ts
const red = parseColor("oklch(0.63 0.26 29)")!
const violet = parseColor("oklch(0.55 0.25 300)")!

mixColor(red, violet, 0.5, { space: "oklch" }).coords[2] // 344.5, through pink
mixColor(red, violet, 0.5, { space: "oklch", hue: "longer" }).coords[2] // 164.5, through green
```

## 比较
### 对比度
`contrastRatio` 给出两种颜色之间的 WCAG 2 对比度，范围是 1 到 21。文字与背景的对比度需要达到 4.5，大号文字需要 3：

```ts
import { contrastRatio, parseColor } from "@ui-sdk/core/color"

contrastRatio(parseColor("#767676")!, parseColor("white")!) // 4.54
```

顺序无关紧要，alpha 也不计入，所以先把半透明颜色叠到它的背景上再算。

选一种文字颜色和一个背景。比值会说明文字是否达到 WCAG 对普通文字的 4.5 或对大号文字的 3。把灰色调暗，直到所有文字都能通过。

### 距离
`colorDistance` 用两种颜色在 Oklab 中的距离，衡量它们看起来相差多少。大约 0.02 是大多数人能察觉到的最小差别：

```ts
import { colorDistance, parseColor } from "@ui-sdk/core/color"

colorDistance(parseColor("red")!, parseColor("#fe0000")!) // 0.002, too small to see
```

用它判断一个色块是否已经是某种颜色，或者在调色板里找到最接近的颜色。


# 图片

裁出图片中的一块区域，保存为新文件，可旋转、翻转、缩放或裁成圆形。

`@ui-sdk/core/image` 从图片中裁出一块区域，并把它作为新的图片文件返回。在用户选好裁剪范围后使用它，比如从照片里裁出头像，然后提交或上传它返回的文件。

## 裁剪图片
`cropImage` 接收一张图片、要保留的区域，以及写出文件的选项。区域使用图片自身的像素，与图片在页面上显示的尺寸无关：

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

const file = await cropImage(photo, { x: 120, y: 40, width: 600, height: 600 })

file.name // "photo.png", from the photo's name
file.type // "image/png"
```

图片可以是来自 `<input type="file">` 的文件、一个 URL、一个 `<img>`、一个 `<canvas>` 或一个 `ImageBitmap`。来自其他源的 URL 需要 CORS，否则浏览器不会让页面读取它的像素。Promise 会兑现为 `File`，所以 `FormData` 和 `fetch` 可以直接接收它。

## 旋转与翻转
设置 `rotation` 让图片每次顺时针旋转四分之一圈，设置 `flipX` 或 `flipY` 可镜像翻转。区域的 `x` 和 `y` 从图片旋转、翻转后显示的左上角算起：

```ts
const file = await cropImage(photo, {
  x: 0,
  y: 0,
  width: 300,
  height: 400,
  rotation: 90,
  flipX: true,
})
```

所以一张宽 400、高 300 的照片旋转 90 度后宽 300、高 400，上面的区域能保留整张图片。

旋转或翻转图片，然后按压 Crop。旋转后图片左上角的正方形会变成一个 96 像素的文件。勾选 Circle 可以得到圆角。

## 文件
| 选项      | 设置的内容                                                    |
| --------- | ------------------------------------------------------------- |
| `type`    | 默认 `"image/png"`，也可以是 `"image/jpeg"` 或 `"image/webp"` |
| `quality` | 0 到 1，用于 JPEG 和 WebP                                     |
| `width`   | 像素宽度。不传时，按区域比例跟随 `height`，否则使用区域的宽度 |
| `height`  | 像素高度。不传时，按区域比例跟随 `width`，否则使用区域的高度  |
| `shape`   | `"circle"` 保留区域内的椭圆，并让四角透明                     |
| `name`    | 文件名，用来代替由源文件名加新扩展名得到的名称                |

只传 `width` 可缩放裁剪结果，比如从一张大得多的照片得到 256 像素的头像：

```ts
const avatar = await cropImage(photo, crop, {
  type: "image/webp",
  quality: 0.9,
  width: 256,
  shape: "circle",
})
```

浏览器无法写出你要求的类型时，会改为写 PNG，文件的 `type` 和名称会说明它实际写了哪种。JPEG 没有透明度，所以在那里圆形裁剪的四角会变黑。圆形裁剪请用 PNG 或 WebP。


# 存储

保留一个值到下次访问，跟踪变化，并在服务器上读取 cookie。

用存储辅助函数保存一个值，稍后再读回来。它们支持 localStorage、sessionStorage 和 cookie，还能让你监听变化。

对于用户偏好，比如主题或侧边栏状态，把一个存储传给 [`createPreference`](https://ui-sdk.cn/docs/core/behaviors/preferences#remember-the-choice)。

## 选择存储
按值的保留时长和服务器是否需要读取它来选择：

| 存储                   | 保留时长                     | 共享对象           | 服务器可读取 |
| ---------------------- | ---------------------------- | ------------------ | ------------ |
| `createLocalStorage`   | 直到被移除                   | 站点上的其他标签页 | 否           |
| `createSessionStorage` | 标签页打开期间               | 当前标签页         | 否           |
| `createCookieStorage`  | 一年，或 `maxAge` 指定的秒数 | 请求和其他标签页   | 是           |

想留到下次访问的笔记可以用 localStorage。临时的草稿可以用 sessionStorage。会影响服务端渲染内容的偏好可以用 cookie。

## 保存一个值
这些辅助函数按名称存储字符串，这个名称会成为 localStorage 或 sessionStorage 的键，或者 cookie 的名字：

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

const note = createLocalStorage("note")

note.set("Buy milk")
note.get()
note.remove()
note.get()
```

第一次 `get()` 返回 `"Buy milk"`。调用 `remove()` 之后，它返回 `null`。

输入一条笔记并重新加载页面。切换存储类型，或者打开另一个标签页，看看哪些值会保留下来。

## 存储不可用时
浏览器可能禁止存储，或者存储空间会用完。如果读取失败，`get()` 返回 `null`。对 localStorage 和 sessionStorage 来说，写入成功时 `set` 和 `remove` 返回 `true`，失败时返回 `false`。

用 `available()` 做初始检查。之后的写入仍可能失败，所以也要检查它的返回值：

```ts
if (!note.available()) {
  console.log("Saving is unavailable here.")
}

if (!note.set("Buy milk")) {
  console.log("The note wasn't saved.")
}
```

存储已满时，你仍然可以读取或移除已有的值。

对 cookie 来说，`true` 表示没有报告错误，并不能确认 cookie 已经保存或移除。

在服务器上，localStorage 和 sessionStorage 不可用。要在那里读取保存的值，[请使用 cookie](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server)。

## 跟踪变化
先用 `get` 读取初始值，再订阅变化。`subscribe` 不会用初始值调用你的监听器：

```ts
function logNote(value: string | null) {
  console.log(value ?? "")
}

logNote(note.get())
const stop = note.subscribe(logNote)
```

通过种类和 ID 相同的存储写入时，页面上的监听器会收到通知，包括通过 `note` 本身的写入。localStorage 还会跟踪其他标签页的变化。在支持 `cookieStore` 的浏览器里，cookie 也会跟踪其他标签页。

不再需要订阅时调用返回的函数，比如组件卸载时：

```ts
stop()
```

## 在服务器上读取 cookie
在服务端渲染期间，传入请求的 `Cookie` 头来读取保存的值：

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

function readDensity(request: Request) {
  const density = createCookieStorage("density", {
    cookie: request.headers.get("cookie"),
  })

  return density.get()
}
```

像上面那样在请求处理函数里创建存储，让每个访客的 cookie 保持独立。在浏览器里，它读取 `document.cookie`。

在服务器上，提供 `Cookie` 头时 `available()` 返回 `true`，但 `set` 和 `remove` 返回 `false`。这个辅助函数读取请求的 cookie，不设置响应头。它的 `readsOnServer` 标记让 `createPreference` 这类辅助函数能在初始状态里使用保存的值。

默认情况下，cookie 保留一年，使用路径 `/` 和 `SameSite=Lax`，在 HTTPS 页面上使用 `Secure`。你可以用 `maxAge`、`path`、`domain`、`sameSite` 和 `secure` 修改这些设置。

## 在水合前显示值
服务器无法读取 localStorage 或 sessionStorage。对于依赖保存值的样式，`script` 会生成一段 JavaScript，在水合之前把值放到 `data-*` 属性上：

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

const densityStorage = createLocalStorage("density")
const script = densityStorage.script({
  attribute: "data-density",
  values: ["comfortable", "compact"],
})
```

渲染元素时带上它的默认属性，比如 `data-density="comfortable"`。紧跟在这个元素之后，把 `script` 渲染成内联 JavaScript。它会在页面加载时读取保存的值，并更新前一个元素的属性。

只有列在 `values` 里的值才会被写入。保存的值缺失或无效时，属性保持服务器渲染的样子。属性名必须以 `data-` 开头。

脚本只更新属性。组件挂载时读取存储，并订阅变化，让它的状态保持最新。当你[在自己的框架里渲染这段脚本](https://ui-sdk.cn/docs/server-rendering#render-the-storage-script-yourself)时，要考虑到属性会在水合之前发生变化。

种类和 ID 相同的脚本共享一次初始读取。cookie 存储的 `script` 返回 `undefined`，因为服务器自己就能渲染 cookie 的值。

对于用户偏好，[用 `Preferences` 应用它们](https://ui-sdk.cn/docs/core/behaviors/preferences#apply-preferences)，这样只需渲染一段脚本，就能让它们的属性保持最新。

## API 参考
- `id` (`string`): The ID the value is kept under: the localStorage or sessionStorage key, or the cookie's name. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `kind` (`Kind`): Where the value is kept: `"local"`, `"session"` or `"cookie"`. Example: [Choose a Storage](https://ui-sdk.cn/docs/core/storage#choose-a-storage).
- `readsOnServer` (`boolean`): Whether the server reads the value too, so it renders right from the first render. True for cookies. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `script` (`(options: StorageScriptOptions) => string`): The inline script a component renders right after its root, which puts the saved value on the root before hydration, so CSS shows it on the first paint. Undefined for a cookie, since the server renders its value. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).
- `available` (`() => boolean`): Whether storage appears available. A later write can still fail. On the server, a cookie with a request header is available for reading only. Example: [When Storage Is Unavailable](https://ui-sdk.cn/docs/core/storage#when-storage-is-unavailable).
- `get` (`() => string | null`): The value kept under the ID, or null when nothing is, or the storage is unavailable. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `set` (`(value: string) => boolean`): Saves a value under the ID. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was saved. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `remove` (`() => boolean`): Removes the value. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was removed. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `subscribe` (`(listener: (value: string | null) => void) => () => void`): Hears the value change, through another storage with the same ID on the page or in another tab. Returns the function that stops it. Example: [Follow Changes](https://ui-sdk.cn/docs/core/storage#follow-changes).

- `cookie?` (`string | null`): The request's `Cookie` header, so the server reads the same value the browser will. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `maxAge?` (`number`): How long the cookie lasts, in seconds. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `path?` (`string`): The paths that send the cookie. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `domain?` (`string`): The domain that sends the cookie. Defaults to the page's host. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `sameSite?` (`"lax" | "none" | "strict"`): Whether other sites' requests send the cookie. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `secure?` (`boolean`): Whether only HTTPS requests send the cookie. Defaults to true on HTTPS pages. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).

- `attribute` (``data-${string}``): The attribute that shows the value, which has to start with `data-`, like `"data-color-scheme"`. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).
- `values` (`readonly string[]`): The values it may show. Anything else saved under the ID leaves the root as the server rendered it. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).


# 平台

播报变更，跟踪页面的方向，并按用户的平台调整键盘快捷键。

用 `announce` 向屏幕阅读器发送消息，用 `isRTL` 读取文字方向，用快捷键辅助函数按用户的平台匹配和标注键盘快捷键。

这些辅助函数可以从 `@ui-sdk/core` 引入。你既可以在原语（primitive）里使用它们，也可以单独使用。

## 播报
假设你做了一个复制按钮。复制成功后，用 `announce` 让屏幕阅读器知道：

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

async function copyText(text: string) {
  await navigator.clipboard.writeText(text)
  announce("Copied")
}
```

`announce` 写入一个共享的实时区域（live region）。默认情况下，它会让屏幕阅读器等到停顿之后再朗读消息。可以用屏幕阅读器试一试：

对于原本不会被播报的结果，这很有用，比如列表完成排序或者文件复制完成。在动作成功之后调用它，放在事件处理函数或 `bind` 里。`attrs` 和 `state` 里不要有副作用。

## 紧急播报
需要立即引起注意的内容，用 `priority: "assertive"`：

```ts
announce("Enter an email address", { priority: "assertive" })
```

这会要求屏幕阅读器打断当前消息。少用为妙，大多数更新都可以等。

有些屏幕阅读器要求实时区域在文字变化之前就已存在。如果组件出现后很快就会播报，就在它的根槽位的 `bind` 里准备好这些区域：

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

root: slot({
  bind: (el) => prepareAnnouncements(el.ownerDocument),
}),
```

`announce` 默认使用当前文档。对于 frame 里的元素，也要传入它的文档：`announce("Copied", { doc: el.ownerDocument })`。

## 方向
在从左到右的分页器里，按右方向键是前进。在从右到左的分页器里，按左方向键是前进。用 `isRTL` 读取元素计算后的方向：

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

function isForwardKey(event: KeyboardEvent, el: HTMLElement) {
  const forward = isRTL(el) ? "ArrowLeft" : "ArrowRight"
  return event.key === forward
}
```

在按键处理函数里调用它，这样它会跟随页面方向的变化。聚焦下面的分页器，试试方向键，然后打开 **Right to left**：

[游走焦点（roving focus）](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus) 已经为 Left 和 Right 处理了这一点。要处理语言而不是方向，见[页面语言](https://ui-sdk.cn/docs/core/text#the-pages-language)。要跟随人们选择的或浏览器偏好的浅色或深色配色，见[偏好设置](/docs/core/behaviors/preferences)。

## 快捷键
在 Apple 平台上用 `mod` 表示 Command，在其他平台上表示 Control。在 `keydown` 处理函数里，先匹配快捷键，再调用你的动作：

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

if (matchesShortcut(event, "mod+b")) {
  event.preventDefault()
  toggleBold()
}
```

这里的 `toggleBold` 是你自己的函数。`matchesShortcut` 只检查按键；由处理函数阻止浏览器的默认动作，并运行你的动作。

同一个快捷键字符串既能给出可见的标签，也能给出 `aria-keyshortcuts` 的值：

```ts
import { ariaKeyshortcuts, formatShortcut } from "@ui-sdk/core"

formatShortcut("mod+b") // Displays “⌘B” on Apple platforms, “Ctrl+B” elsewhere.
ariaKeyshortcuts("mod+b") // "Meta+B" or "Control+B".
```

这些标签取决于用户的平台。在原语里，把它们放在 `bind` 里设置，这样服务器和客户端的首次渲染就能保持一致：

```ts
keys: slot({
  bind: (el) => {
    el.textContent = formatShortcut("mod+b")
  },
}),
```

在笔记里输入时试试这个快捷键：

`formatShortcut` 用两个不可见字符包裹标签，让它在从右到左的页面上也保持从左到右的顺序。测试时，从 `@ui-sdk/core/testing` 引入 `setPlatform`，调用 `setPlatform("apple")` 或 `setPlatform("other")`。

## 图层与定位
要构建浮层？[放置浮层](https://ui-sdk.cn/docs/core/behaviors/popups#placing-a-popup)介绍了 `position`。[自己的图层](https://ui-sdk.cn/docs/core/behaviors/popups#layers-of-your-own)讲的是 `bindLayer`、顶层，以及让元素在模态之上仍然可用。

## API 参考
| 辅助函数                           | 用途                                   |
| ---------------------------------- | -------------------------------------- |
| `announce(text, options?)`         | 播报结果，可选用 `priority` 和 `doc`。 |
| `prepareAnnouncements(doc)`        | 在第一次播报之前创建实时区域。         |
| `isRTL(el)`                        | 读取元素的文字方向。                   |
| `matchesShortcut(event, shortcut)` | 检查按键是否匹配某个快捷键。           |
| `formatShortcut(shortcut)`         | 用平台的符号或名称显示快捷键。         |
| `ariaKeyshortcuts(shortcut)`       | 生成 `aria-keyshortcuts` 的值。        |


# 移动端

围绕屏幕键盘和手机的安全区域布局，并区分手指和鼠标。

在手机上，页面要为一个人们看不全的屏幕做布局：屏幕键盘盖住底部，iOS 会平移页面让输入框保持可见，刘海或主屏幕指示条占据边缘。`bindViewport` 会测量所有这些，`bindAvoidKeyboard` 让一条栏保持在键盘上方。`createPointerKind` 判断人们用的是手指还是鼠标。

这些辅助函数可以从 `@ui-sdk/core` 引入。你既可以在原语（primitive）里使用它们，也可以单独使用。

## 视口
### 跟随视口
`bindViewport` 在某个元素上跟踪视口，通常是在根元素上，并报告每次变化：

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

const stop = bindViewport(document.documentElement, {
  onChange: (viewport) =>
    console.log(viewport.keyboard, viewport.safeArea.bottom),
})
```

`onChange` 在开始时运行一次，之后每当有变化时再运行。`viewport.keyboard` 是输入框获得焦点时键盘的高度，`width`、`height`、`offsetTop` 和 `offsetLeft` 描述页面上可见的那部分，也就是视觉视口。调用清理函数即可停止。

键盘按屏幕上的实际占用测量，对照输入框获得焦点之前页面还有多少可见空间。无论是 iOS 放大到输入框，还是浏览器为键盘缩小整个页面，这个测量都成立，而单靠页面本身是判断不出来的。`viewport.keyboardInset` 表示键盘盖住了页面底部的多少，用来摆放东西：iOS 平移页面时会小一些，浏览器改为调整页面大小时则是 0。

在手机上打开这个页面并轻点输入框：控制台会记录键盘的高度，以及 iOS 把页面平移了多远。双指缩放，看看比例的变化。

在 CSS 里，元素会得到这些变量，键盘打开期间还会得到 `data-keyboard`：

| 变量                       | 内容                                       |
| -------------------------- | ------------------------------------------ |
| `--keyboard-inset`         | 键盘盖住页面底部的多少，即 `keyboardInset` |
| `--visual-viewport-width`  | 页面上可见部分的宽度                       |
| `--visual-viewport-height` | 它的高度，键盘打开时会缩小                 |
| `--visual-viewport-top`    | 页面向下平移了多远，比如为了显示输入框     |

当输入框的文字小于 16 像素时，iOS 会在它获得焦点时放大。给输入框至少 `font-size: 16px`，页面就能保持原来的尺寸。

### 安全区域
`viewport.safeArea` 保存刘海、圆角或主屏幕指示条周围的内边距，是供脚本使用的数字。在 CSS 里，直接使用 `env(safe-area-inset-bottom)`。除非页面用 `viewport-fit=cover` 绘制到它们下面，否则两者都是 0：

```html
<meta
  name="viewport"
  content="width=device-width, initial-scale=1, viewport-fit=cover"
/>
```

键盘会盖住主屏幕指示条，但键盘打开时 iOS 仍会报告它的内边距。这时可以去掉底部内边距：

```css
.composer {
  padding-bottom: env(safe-area-inset-bottom);
}
.composer[data-keyboard] {
  padding-bottom: 0;
}
```

## 屏幕键盘
### 让栏保持在键盘上方
输入框获得焦点时，浏览器只把这个输入框滚动到键盘上方的可见区域，别的都不动。笔记下方的状态胶囊、输入框旁边的按钮，或者固定在屏幕底部的工具栏，都会留在键盘盖住的位置。`bindAvoidKeyboard` 把这样的元素抬高，抬高的距离等于键盘盖住它的部分：

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

const stop = bindAvoidKeyboard(pill)
```

键盘打开时，固定在底部的栏会上移到刚好在键盘上方。位置更高的元素只移动键盘与它重叠的那部分，位于屏幕下方的元素则原地不动。如果浏览器为键盘缩小页面，比如 Android 使用 `interactive-widget=resizes-content`，就没有东西被盖住，也没有东西移动。

在手机上打开这个页面并轻点列表：浏览器会保持你正在输入的文字可见，它下面的胶囊会升到键盘上方，而不是藏在键盘后面。键盘打开时滚动页面，它会一直保持在键盘上方，直到它所在的卡片完全滚开。

元素的底边会贴着键盘，所以如果要在两者之间留出空间，就给一个带底部内边距的外层容器绑定，示例就是这么做的。元素上的 `translate` 归这个辅助函数所有，清理时会把你自己原来的值放回去。键盘打开期间，它会得到 `data-keyboard`，可以用来去掉安全区域内边距或加上阴影。滚动时它每帧移动一次；不要给 `translate` 加过渡，否则它会拖在后面。抬升不会改变布局，所以如果栏后面的内容需要保持可见，用 `bindViewport` 提供的 `var(--keyboard-inset)` 给它留出空间。

## 合适的键盘
手机根据输入框选择键盘：`inputmode` 选择按键，比如验证码用数字键盘，`enterkeyhint` 选择回车键，比如“next”或“send”，iOS 26 会把它们画成图标。“焦点与按键”里的 [`inputHints`](https://ui-sdk.cn/docs/core/behaviors/focus#input-hints) 会为一类输入框填入这些设置，还有自动填充和纠错。

## 触摸与鼠标
### 指针种类
`createPointerKind` 根据 `pointer` 和 `hover` 媒体特性，报告主指针是手指还是鼠标、能否悬停，另外还有针对所有已接入指针的 `anyPointer` 和 `anyHover`，比如平板上的触控板。像读取偏好一样读取它，在每个框架里用 `usePreference`：

**React**

```tsx
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/react/preferences"

const pointerKind = createPointerKind()

const { hover } = usePreference(pointerKind)
// "hover" with a mouse, "none" on a phone, "unknown" on the server
```

**Vue**

```ts
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/vue/preferences"

const pointerKind = createPointerKind()

const pointer = usePreference(pointerKind)
// pointer.value.hover: "hover" with a mouse, "none" on a phone, "unknown" on the server
```

**Svelte**

```ts
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/svelte/preferences"

const pointerKind = createPointerKind()

const pointer = usePreference(pointerKind)
// pointer.current.hover: "hover" with a mouse, "none" on a phone, "unknown" on the server
```

**Solid**

```tsx
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/solid/preferences"

const pointerKind = createPointerKind()

const pointer = usePreference(pointerKind)
// pointer().hover: "hover" with a mouse, "none" on a phone, "unknown" on the server
```

**Web Components**

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

const pointerKind = createPointerKind()

const { hover } = pointerKind.get()
// "hover" with a mouse, "none" on a phone, "unknown" on the server
```

它用于行为和内容，比如在无法悬停的地方改为轻点打开。样式直接使用媒体查询，`@media (hover: hover)` 或 Tailwind 的 `pointer-coarse:`，它们从首次绘制起就是正确的。

使用鼠标时，详情在悬停时打开。在手机上，轻点打开，按钮上也会写明这一点。

### 在服务器上渲染
服务器无法知道设备是什么，所以在服务端渲染和浏览器首次渲染（水合时对照的就是它）中，每个字段都是 `"unknown"`。水合刚结束时，状态会跟上，依赖它的内容随之变化，比如上面的按钮会多出“(tap for details)”。用媒体查询写的样式不用等：它们从首次绘制起就是正确的。

要从一开始就渲染正确的内容，就为每个请求创建指针种类，并给 `initial` 一个猜测值。Chromium 浏览器会发送 `Sec-CH-UA-Mobile` 头，`pointerKindOf` 能把它转成猜测值：

```ts
import { createPointerKind, pointerKindOf } from "@ui-sdk/core"

// On the server, for each request.
const initial = pointerKindOf(request.headers.get("Sec-CH-UA-Mobile"))

// On the server and in the browser, from the same `initial`.
const pointerKind = createPointerKind({ initial })
```

把 `initial` 和页面的其他数据一起发给浏览器，让它的首次渲染与服务器一致，水合才能对上。[为每个请求创建一个](https://ui-sdk.cn/docs/server-rendering#read-a-cookie-on-the-server)，不要放在模块里，这样访客之间不会共享猜测值。

Safari 和 Firefox 不发送这个头，所以 `pointerKindOf` 在那里什么也不返回，字段会一直是 `"unknown"`，直到水合。会变化的内容在 `"unknown"` 时要读起来通顺，比如示例里朴素的“Shipping”。如果有缓存保存页面，发送 `Vary: Sec-CH-UA-Mobile`，让手机和电脑各自拿到对应的副本。

## API 参考
| 辅助函数                         | 用途                                             |
| -------------------------------- | ------------------------------------------------ |
| `bindViewport(el, { onChange })` | 在 CSS 和脚本中跟踪键盘、视觉视口和安全区域。    |
| `bindAvoidKeyboard(el)`          | 让元素保持在屏幕键盘上方。                       |
| `createPointerKind({ initial })` | 区分手指和鼠标，并判断能否悬停。                 |
| `pointerKindOf(header)`          | 在服务器上根据 `Sec-CH-UA-Mobile` 猜测指针类型。 |


# 所有行为

了解焦点、选择、浮层，以及构成组件的其他片段。

按主题浏览这些辅助函数。每个名称都链接到对应的指南和示例。

除非标明了其他入口，否则从 `@ui-sdk/core` 导入辅助函数。

## 焦点与按键
| 辅助函数                                                             | 作用                                                |
| -------------------------------------------------------------------- | --------------------------------------------------- |
| [`createRovingFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus)                          | 让一组部件只有一个 Tab 停靠点，并用方向键移动焦点。 |
| [`createGridFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#grids)                                   | 按行和列移动焦点，包括尚未渲染的单元格。            |
| [`byCell`](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop-in-a-grid)                           | 只更新焦点离开的单元格和落到的单元格。              |
| [`spatialMove`](https://ui-sdk.cn/docs/core/behaviors/focus#spatial-focus)                               | 根据条目在屏幕上的位置选择下一个条目。              |
| [`nearestInDirection`](https://ui-sdk.cn/docs/core/behaviors/focus#choose-a-target-without-moving-focus) | 在某个方向上找到最近的条目，但不移动焦点。          |
| [`createTypeahead`](https://ui-sdk.cn/docs/core/behaviors/focus#typeahead)                               | 在有人输入名称时找到对应条目。                      |
| [`createFocusRecovery`](https://ui-sdk.cn/docs/core/behaviors/focus#focus-recovery)                      | 聚焦的条目被移除时恢复焦点。                        |
| [`keepFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#focus-that-follows-a-move)                     | 在移动元素的变更过程中保持焦点。                    |
| [`inputHints`](https://ui-sdk.cn/docs/core/behaviors/focus#input-hints)                                  | 为某类字段选择屏幕键盘和自动填充。                  |

## 文本
| 辅助函数                                                      | 作用                                                 |
| ------------------------------------------------------------- | ---------------------------------------------------- |
| [`createInputHistory`](https://ui-sdk.cn/docs/core/text#bring-back-earlier-messages)   | 像终端一样，用 ArrowUp 和 ArrowDown 调出更早的条目。 |
| [`isTypeaheadKey`](https://ui-sdk.cn/docs/core/text#find-an-item-by-typing)            | 检查某个按键能否用于键入查找（typeahead）。          |
| [`labelOf`](https://ui-sdk.cn/docs/core/text#what-an-item-is-called)                   | 读取元素的标签，用来匹配输入的文字。                 |
| [`isComposing`](https://ui-sdk.cn/docs/core/text#properly-handle-input-method-editors) | 检查某个输入事件是否属于仍在组合中的文字。           |
| [`pageLocale`](https://ui-sdk.cn/docs/core/text#the-pages-language)                    | 读取页面的语言，或页面中某一节的语言。               |
| [`userLocale`](https://ui-sdk.cn/docs/core/text#the-pages-language)                    | 读取浏览器偏好的语言。                               |
| [`toLocale`](https://ui-sdk.cn/docs/core/text#tags-from-elsewhere)                     | 把 `en_US` 这样的标签转换成 `Intl` 接受的形式。      |

### 搜索匹配
从 `@ui-sdk/core/text-match` 导入这些辅助函数。

| 辅助函数                                               | 作用                                     |
| ------------------------------------------------------ | ---------------------------------------- |
| [`fuzzyScore`](https://ui-sdk.cn/docs/core/text#rank-what-someone-searches-for) | 给一段文字与输入内容的匹配程度打分。     |
| [`matchRanges`](https://ui-sdk.cn/docs/core/text#highlight-what-matched)        | 找出输入的文字在一段文字中出现的位置。   |
| [`matchSegments`](https://ui-sdk.cn/docs/core/text#highlight-what-matched)      | 把文字拆成匹配和未匹配的片段，供你渲染。 |

## 选择
| 辅助函数                                              | 作用                                 |
| ----------------------------------------------------- | ------------------------------------ |
| [`createSelection`](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-items)      | 跟踪选中的条目，包括多选和范围选择。 |
| [`createLasso`](https://ui-sdk.cn/docs/core/behaviors/selection#rectangle-selection)      | 选中被指针画出的矩形碰到的条目。     |
| [`createCellRange`](https://ui-sdk.cn/docs/core/behaviors/selection#ranges-of-cells)      | 选中网格中一个矩形范围的单元格。     |
| [`byCellRange`](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block)           | 只更新加入或离开范围的单元格。       |
| [`cellRangeMessage`](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-from-code) | 为一组单元格提供默认的播报。         |
| [`cellsToText`](https://ui-sdk.cn/docs/core/behaviors/selection#copy-and-paste)           | 把单元格的值转换成文本，用于复制。   |
| [`textToCells`](https://ui-sdk.cn/docs/core/behaviors/selection#copy-and-paste)           | 把粘贴的文本解析成一行行的单元格值。 |

## 拖放
| 辅助函数                                                            | 作用                                 |
| ------------------------------------------------------------------- | ------------------------------------ |
| [`bindDrag`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#pointer-drags)                         | 用捕获、阈值和取消来跟踪指针拖拽。   |
| [`dragThreshold`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#follow-a-pointer)                 | 把标准拖拽阈值设为 3 像素。          |
| [`createReorder`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#reordering)                       | 用指针或键盘重新排序列表或网格。     |
| [`createTreeReorder`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#reordering-a-tree)            | 重排树条目，并连同其子孙一起嵌套。   |
| [`createTransfer`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#moving-between-lists)            | 在列表内或列表之间移动条目。         |
| [`bindDragPreview`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#dragging-a-copy)                | 在页面之上显示被拖拽元素的副本。     |
| [`createAutoScroll`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging)      | 拖拽接近容器边缘时滚动容器。         |
| [`settleDraft`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#keeping-focus-and-the-draft)        | 在受控值跟上之前保持草稿可见。       |
| [`reorderMessage`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#whats-read-out)                  | 为列表重排提供默认的播报。           |
| [`subtreeEnd`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code)         | 找出子树之后的第一个行索引。         |
| [`treeReorderMessage`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code) | 为树的重排提供默认的播报。           |
| [`transferMessage`](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules)             | 为在列表之间移动条目提供默认的播报。 |

## 拖动与调整大小
| 辅助函数                                                             | 作用                                           |
| -------------------------------------------------------------------- | ---------------------------------------------- |
| [`createMove`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#moving-in-two-dimensions)       | 用指针或键盘移动自由定位的对象。               |
| [`createResize`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#resizing-boxes)               | 从边缘和角调整盒子的大小。                     |
| [`createSwipeActions`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#swiping-rows-aside)     | 显示行背后的动作，并支持滑动到底触发的动作。   |
| [`bindHold`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#pressing-and-holding)             | 按住时执行动作，并可在按住期间重复执行。       |
| [`bindRepeat`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held)              | 按下按钮时步进一次，按住期间持续步进。         |
| [`createArea`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#two-dimensional-values)         | 沿两个轴选取一个值，比如面板上的一个点。       |
| [`createSpans`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#ranges-on-tracks)              | 在轨道上绘制、移动和调整范围。                 |
| [`stackSpans`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down)             | 把重叠的范围放进不同的泳道。                   |
| [`createPreview`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#previews)                    | 跟踪一个在选定之前正在试用的值。               |
| [`moveMessage`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once)               | 为位置变更提供默认的播报。                     |
| [`resizeMessage`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-boxes-and-from-code) | 为调整盒子大小提供默认的播报。                 |
| [`isSpanFree`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#changing-ranges-from-code)      | 检查提议的范围是否与同一轨道上的其他范围重叠。 |
| [`spansMessage`](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#changing-ranges-from-code)    | 为范围的变更提供默认的播报。                   |

## 列表
| 辅助函数                                                     | 作用                                                 |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| [`createListbox`](https://ui-sdk.cn/docs/core/behaviors/lists#options-you-search)                | 用方向键高亮选项，并在有人输入时过滤它们。           |
| [`createVirtualizer`](https://ui-sdk.cn/docs/core/behaviors/lists#long-lists)                    | 计算要渲染哪些行，以及把它们放在哪里。               |
| [`createStickToBottom`](https://ui-sdk.cn/docs/core/behaviors/lists#logs-that-follow-their-end)  | 跟随新内容，同时在读者向上滚动时保留他们所在的位置。 |
| [`bindScrollPicker`](https://ui-sdk.cn/docs/core/behaviors/lists#wheels-you-scroll-to-pick-from) | 像滚轮一样，选中滚动列表中央的选项。                 |
| [`createInlineEdit`](https://ui-sdk.cn/docs/core/behaviors/lists#editing-in-place)               | 就地管理值的编辑、提交和取消。                       |

## 树
| 辅助函数                                            | 作用                                             |
| --------------------------------------------------- | ------------------------------------------------ |
| [`createTreeCollection`](https://ui-sdk.cn/docs/core/behaviors/trees#a-trees-shape)     | 查找父节点、子节点、层级和可见节点。             |
| [`treeDataNodes`](https://ui-sdk.cn/docs/core/behaviors/trees#tree-data-and-file-paths) | 把嵌套条目转换成树集合所需的节点。               |
| [`treeFromPaths`](https://ui-sdk.cn/docs/core/behaviors/trees#tree-data-and-file-paths) | 从文件路径构建嵌套的树数据。                     |
| [`visibleTreeRows`](https://ui-sdk.cn/docs/core/behaviors/trees#flat-rows)              | 把展开的分支展平成行，附带父级、层级和索引数据。 |
| [`treeCheckedStates`](https://ui-sdk.cn/docs/core/behaviors/trees#check-a-branch)       | 计算整棵树中选中、未选中和混合的状态。           |
| [`toggleTreeChecked`](https://ui-sdk.cn/docs/core/behaviors/trees#check-a-branch)       | 切换节点时返回下一个选中值。                     |

## 过渡与手势
| 辅助函数                                                       | 作用                                           |
| -------------------------------------------------------------- | ---------------------------------------------- |
| [`bindPanel`](https://ui-sdk.cn/docs/core/behaviors/motion#panels-and-presence)                    | 打开或关闭时协调面板高度、过渡和焦点。         |
| [`hiddenAttrs`](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-and-opening-at-once)     | 为隐藏内容或可搜索内容设置可见性属性。         |
| [`bindFindable`](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-on-its-own)             | 浏览器找到匹配时显示隐藏内容。                 |
| [`supportsHiddenUntilFound`](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-on-its-own) | 检查浏览器能否搜索隐藏内容。                   |
| [`animateIn`](https://ui-sdk.cn/docs/core/behaviors/motion#entering-and-leaving)                   | 应用 CSS 入场动画的起始状态。                  |
| [`animateOut`](https://ui-sdk.cn/docs/core/behaviors/motion#entering-and-leaving)                  | 应用退出状态，并在动画结束后调用你的完成回调。 |

### 手势计算
从 `@ui-sdk/core/gesture` 导入这些辅助函数。

| 辅助函数                                               | 作用                                         |
| ------------------------------------------------------ | -------------------------------------------- |
| [`createVelocityTracker`](https://ui-sdk.cn/docs/core/behaviors/motion#throws-and-springs) | 根据最近的指针位置测量速度。                 |
| [`projectDistance`](https://ui-sdk.cn/docs/core/behaviors/motion#throws-and-springs)       | 估算一个运动中的值减速后还会走多远。         |
| [`solveSpring`](https://ui-sdk.cn/docs/core/behaviors/motion#throws-and-springs)           | 计算弹簧的位置和速度随时间的变化。           |
| [`rubberBand`](https://ui-sdk.cn/docs/core/behaviors/motion#past-an-edge)                  | 值越过边缘时增加阻力。                       |
| [`sectorOf`](https://ui-sdk.cn/docs/core/behaviors/motion#which-way-a-stroke-points)       | 把笔画的方向转换成扇区，比如径向菜单的一项。 |

## 浮层与图层
| 辅助函数                                                             | 作用                                               |
| -------------------------------------------------------------------- | -------------------------------------------------- |
| [`createPopup`](https://ui-sdk.cn/docs/core/behaviors/popups#make-your-own)                              | 使用浮层预设管理打开、关闭、定位和焦点。           |
| [`popupState`](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own)                         | 创建初始的打开、挂载和payload状态。                |
| [`popupTrigger`](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own)                       | 构建一个打开和关闭浮层的触发槽位。                 |
| [`popupContent`](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own)                       | 构建一个带有呈现、放置和焦点处理的内容槽位。       |
| [`popupClose`](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own)                         | 构建一个关闭浮层的槽位。                           |
| [`popupTitle`](https://ui-sdk.cn/docs/core/behaviors/popups#one-popup-many-triggers)                     | 把可见标题连接到浮层的无障碍名称。                 |
| [`popupDescription`](https://ui-sdk.cn/docs/core/behaviors/popups#one-popup-many-triggers)               | 把描述性文字连接到浮层。                           |
| [`popupArrow`](https://ui-sdk.cn/docs/core/behaviors/popups#one-popup-many-triggers)                     | 构建一个跟随浮层放置位置的箭头槽位。               |
| [`popupBackdrop`](https://ui-sdk.cn/docs/core/behaviors/popups#every-part-and-parts-of-your-own)         | 构建模态浮层后面的背景槽位。                       |
| [`popupViewport`](https://ui-sdk.cn/docs/core/behaviors/popups#every-part-and-parts-of-your-own)         | 为浮层底部面板（sheet）构建全屏容器槽位。          |
| [`popupSlots`](https://ui-sdk.cn/docs/core/behaviors/popups#every-part-and-parts-of-your-own)            | 一起构建标准的浮层部件。                           |
| [`position`](https://ui-sdk.cn/docs/core/behaviors/popups#placing-a-popup)                               | 把元素放在锚点（anchor）旁边，并更新它的放置位置。 |
| [`bindLayer`](https://ui-sdk.cn/docs/core/behaviors/popups#layers-of-your-own)                           | 为 Escape 和外部按压关闭注册一个浮动元素。         |
| [`bindPersistentLayer`](https://ui-sdk.cn/docs/core/behaviors/popups#modal-layers-and-what-stays-usable) | 让元素在各个图层之间保持可用，包括模态浮层。       |
| [`isDismissal`](https://ui-sdk.cn/docs/core/behaviors/popups#modal-layers-and-what-stays-usable)         | 识别关闭原因，比如 Escape 或外部按压。             |
| [`supportsTopLayer`](https://ui-sdk.cn/docs/core/behaviors/popups#types-and-the-top-layer)               | 检查浏览器是否支持浮层所用的顶层。                 |

[浮层预设](https://ui-sdk.cn/docs/core/behaviors/popups#pick-its-behavior)为 popover、dialog、tooltip 或 hover card 选择交互方式。[浮层控制器](https://ui-sdk.cn/docs/core/behaviors/popups#open-from-code)从代码打开现有的浮层组件，并等待结果。各自从对应的组件入口导入，比如 `@ui-sdk/core/popover`。

## 偏好设置
| 辅助函数                                                           | 作用                                                       |
| ------------------------------------------------------------------ | ---------------------------------------------------------- |
| [`createPreference`](https://ui-sdk.cn/docs/core/behaviors/preferences#create-a-preference)            | 保存列表中的一个选择，通知订阅者，并可在多次访问之间保存。 |
| [`createColorScheme`](https://ui-sdk.cn/docs/core/behaviors/preferences#choose-a-color-scheme)         | 基于偏好设置选择浅色、深色或浏览器的配色方案。             |
| [`colorSchemeOf`](https://ui-sdk.cn/docs/core/behaviors/preferences#browser-preferences-on-the-server) | 读取浏览器随请求发送的配色方案。                           |
| [`preferencesScript`](https://ui-sdk.cn/docs/core/behaviors/preferences#server-rendering)              | 在首次绘制之前把已保存的偏好写入对应的属性。               |
| [`createPointerKind`](https://ui-sdk.cn/docs/core/mobile#pointer-kind)                      | 报告主指针是手指还是鼠标，以及它能否悬停。                 |
| [`pointerKindOf`](https://ui-sdk.cn/docs/core/mobile#render-on-the-server)                  | 根据请求头推测指针类型。                                   |

### 存储
| 辅助函数                                                        | 作用                                                           |
| --------------------------------------------------------------- | -------------------------------------------------------------- |
| [`createLocalStorage`](https://ui-sdk.cn/docs/core/storage#keep-a-value)                 | 把值保存在 localStorage 中，对所有标签页有效，直到被移除。     |
| [`createSessionStorage`](https://ui-sdk.cn/docs/core/storage#keep-a-value)               | 把值保存在 sessionStorage 中，仅对当前标签页有效，直到它关闭。 |
| [`createCookieStorage`](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server) | 把值保存在 cookie 中，服务器也能读取。                         |

## 画布
| 辅助函数                                             | 作用                                             |
| ---------------------------------------------------- | ------------------------------------------------ |
| [`createViewport`](https://ui-sdk.cn/docs/core/behaviors/canvas#panning-and-zooming)     | 平移和缩放画布，并在屏幕坐标与画布坐标之间转换。 |
| [`createConnect`](https://ui-sdk.cn/docs/core/behaviors/canvas#connections)              | 用指针或键盘跟踪端口之间的连接。                 |
| [`connectMessage`](https://ui-sdk.cn/docs/core/behaviors/canvas#snapping-words-and-code) | 为连接步骤提供默认的播报。                       |

## 平台
| 辅助函数                                                   | 作用                                       |
| ---------------------------------------------------------- | ------------------------------------------ |
| [`announce`](https://ui-sdk.cn/docs/core/platform#announcements)                    | 向屏幕阅读器读出消息。                     |
| [`prepareAnnouncements`](https://ui-sdk.cn/docs/core/platform#urgent-announcements) | 在第一条消息之前添加屏幕阅读器监听的区域。 |
| [`isRTL`](https://ui-sdk.cn/docs/core/platform#direction)                           | 检查元素的文字是否从右到左排列。           |
| [`matchesShortcut`](https://ui-sdk.cn/docs/core/platform#shortcuts)                 | 检查按键是否匹配某个快捷键，比如 `mod+b`。 |
| [`formatShortcut`](https://ui-sdk.cn/docs/core/platform#shortcuts)                  | 按用户所在平台的显示方式写出快捷键。       |
| [`ariaKeyshortcuts`](https://ui-sdk.cn/docs/core/platform#shortcuts)                | 把快捷键写成 `aria-keyshortcuts` 的值。    |

### 移动端
| 辅助函数                                                       | 作用                           |
| -------------------------------------------------------------- | ------------------------------ |
| [`bindViewport`](https://ui-sdk.cn/docs/core/mobile#follow-the-viewport)                | 跟随可见视口，并报告每次变化。 |
| [`bindAvoidKeyboard`](https://ui-sdk.cn/docs/core/mobile#keep-a-bar-above-the-keyboard) | 把元素抬到屏幕键盘之上。       |

## 变更与历史
| 辅助函数                                                                 | 作用                                                    |
| ------------------------------------------------------------------------ | ------------------------------------------------------- |
| [`createChange`](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)                       | 请求变更状态值，先调用它的回调。                        |
| [`createCommit`](https://ui-sdk.cn/docs/core/kernel/handle-changes#commits)                       | 交互结束时上报最终值。                                  |
| [`dispatch`](https://ui-sdk.cn/docs/core/kernel/handle-changes#events-that-arent-state)           | 调用动作的回调，比如 `onDelete`，并告诉你它是否被取消。 |
| [`createUndoStack`](https://ui-sdk.cn/docs/core/kernel/handle-changes#undo)                       | 保存你记录的值快照，以便撤销和重做。                    |
| [`createController`](https://ui-sdk.cn/docs/core/kernel/handle-changes#controllers)               | 让组件外部的代码调用它的方法。                          |
| [`sourceOf`](https://ui-sdk.cn/docs/core/kernel/handle-changes#how-people-are-working)            | 判断事件来自鼠标、触摸、笔、键盘还是代码。              |
| [`isFocusFromKeyboard`](https://ui-sdk.cn/docs/core/kernel/handle-changes#how-people-are-working) | 检查焦点是否刚刚由键盘带来。                            |

### 观察变更
从 `@ui-sdk/core/observe` 导入这些辅助函数。

| 辅助函数                                                  | 作用                                |
| --------------------------------------------------------- | ----------------------------------- |
| [`observe`](https://ui-sdk.cn/docs/core/observe#listen-for-changes)                | 页面上组件每次变更时都会调用你。    |
| [`elementOf`](https://ui-sdk.cn/docs/core/observe#find-the-element)                | 找到发出变更的组件的元素。          |
| [`withSource`](https://ui-sdk.cn/docs/core/observe#keep-the-source-after-an-await) | 让变更的来源跨过 `await` 保留下来。 |

## 构建块
| 辅助函数                                                            | 作用                                           |
| ------------------------------------------------------------------- | ---------------------------------------------- |
| [`definePrimitive`](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#defineprimitive)   | 为所有框架统一定义一个组件的选项、状态和部件。 |
| [`idPart`](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#parts-that-come-and-go)     | 转义条目值，让它能成为 id 的一部分。           |
| [`elements`](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#reading-parts-in-the-api) | 按页面顺序返回组件已绑定的部件。               |
| [`openAttrs`](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#naming)                  | 返回打开或关闭部件常用的属性。                 |
| [`checkedAttrs`](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#naming)               | 返回选中、未选中或混合状态部件常用的属性。     |
| [`css`](https://ui-sdk.cn/docs/core/kernel/style-a-component#pass-values-as-css-variables)   | 把样式声明转换成 `style` 属性，并跳过空值。    |
| [`live`](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state)                       | 为频繁变化的状态写入属性，无需再次渲染。       |
| [`selects`](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state)                    | 告诉每个部件它需要关注哪些状态变更。           |
| [`direct`](https://ui-sdk.cn/docs/core/kernel/handle-changes#attributes-kept-current)        | 在两次渲染之间保持所选属性最新。               |

## Agent
从 `@ui-sdk/core/agent` 导入这些辅助函数。

| 辅助函数                                                                    | 作用                                                   |
| --------------------------------------------------------------------------- | ------------------------------------------------------ |
| [`createAgent`](https://ui-sdk.cn/docs/agents/connect-an-agent/reference#createagentoptions) | 让智能体读取页面上的组件并使用它们。                   |
| [`agentTools`](https://ui-sdk.cn/docs/agents/connect-an-agent/reference#agenttools)          | 为你的模型描述 `snapshot`、`act` 和 `query` 三个工具。 |
| [`registerTools`](https://ui-sdk.cn/docs/agents/connect-an-agent/webmcp#register-the-tools)  | 把这些工具提供给浏览器内置的智能体。                   |

### 历史
从 `@ui-sdk/core/history` 导入这些辅助函数。

| 辅助函数                                                                           | 作用                                                                       |
| ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [`createHistory`](https://ui-sdk.cn/docs/agents/connect-an-agent/history-and-undo#start-recording)  | 记录页面上组件的每一次变更以及是谁做的，让你可以回退或撤销某个来源的变更。 |
| [`describeEntry`](https://ui-sdk.cn/docs/agents/connect-an-agent/history-and-undo#read-the-history) | 为一条历史记录写一句简短的说明。                                           |
| [`stageChanges`](https://ui-sdk.cn/docs/agents/connect-an-agent/history-and-undo#try-a-suggestion)  | 在真实控件上试用一组值，并让你把旧值放回去。                               |

## 值与测试
[数字](/docs/core/number)、[日期](/docs/core/date)、[颜色](/docs/core/color)和[图片](/docs/core/image)涵盖每种值的格式化、解析和运算。它们各有自己的入口，比如 `@ui-sdk/core/number`。[测试](/docs/core/testing)涵盖对你自己的组件的检查。


# 焦点与按键

穿行于列表和网格之间，通过输入查找条目，在页面变化时保持焦点，并给字段配上合适的键盘。

一组部件只有一个 Tab 停靠点、需要用方向键导航时，用 `createRovingFocus`；按行和列移动时，用 `createGridFocus`。其他辅助函数通过输入查找条目、选择附近的目标、在条目移动或消失时恢复焦点，并通过 `inputHints` 给字段配上合适的键盘。

从 `@ui-sdk/core` 导入它们。[组合行为](https://ui-sdk.cn/docs/core/compose-behaviors#give-the-group-one-tab-stop)演示如何把游走焦点（roving focus）接到部件上。聚焦的条目做什么由你的组件决定；[选择](/docs/core/behaviors/selection)涵盖选中条目和范围。

## 游走焦点
### 一个 Tab 停靠点
星级评分用的是 `orientation: () => "both"`，四个方向键都启用。一排按钮只需要 Left 和 Right：

```ts
const roving = createRovingFocus(context, {
  slot: "item",
  key: "focused",
  orientation: () => "horizontal",
})
```

这会处理 Left、Right、Home 和 End。竖向列表用 Up 和 Down，省略 `orientation` 即可。Left 和 Right 遵循页面的文字方向。

按 Tab 进入工具栏。用 Left、Right、Home 或 End 在按钮之间移动；按 Tab 离开这一组。

默认情况下，最后聚焦的条目保留 Tab 停靠点。如果想改为回到选中的条目，就用 `remember: false`、`preferred` 和 `claims`，就像我们在[评分指南](https://ui-sdk.cn/docs/core/compose-behaviors#give-the-group-one-tab-stop)里做的那样。

### 禁用条目与循环
不可用的动作有时仍然值得找到。传入 `disabled`，选择 Tab 停靠点时优先选启用的条目，同时让方向键仍能到达每一个动作：

```ts
const roving = createRovingFocus(context, {
  slot: "item",
  key: "focused",
  disabled: (item) => !!item.props.disabled,
  loop: () => true,
})
```

`loop` 让焦点从最后一个条目绕回第一个，也能再绕回来。

按 Tab 到 Cut，然后按 Up 到达已禁用的 Redo 动作。继续按 Up 或 Down 可以循环绕回。

条目仍需要 `aria-disabled` 和一个忽略它的按压处理函数。原生 `disabled` 按钮无法获得焦点。如果所有条目都已禁用，这一组仍然可以把 Tab 停靠点给其中一个。

### 无法获得焦点的条目
如果某个条目应该被完全跳过，就用 `focusable`。这些嵌套文件夹在所在分支关闭时仍保持渲染：

```ts
focusable: (item) => !item.props.nested || context.store.get().open,
```

用方向键到达 Labels。按 Enter 打开它，然后按 Down 到达 Work。

状态变化时，这一组会重新检查 `focusable`。如果它依赖状态之外的东西，就在那个东西变化后调用 `roving.check()`。

### 来来去去的条目
`roving.focus(key)` 把焦点移到一个条目上。你也可以在条目渲染之前就调用它：

```ts
function add(tag: string) {
  context.options().onAdd?.(tag)
  roving.focus(tag)
}
```

输入一个标签并按 Enter。新标签会获得焦点，控制台会记录数量。

`roving.items()` 按文档顺序返回可获得焦点的条目，每项带有 `key`、`props` 和 `el`。这个演示用 `onItemsChange` 在条目加入或离开后更新计数。

当新条目作为本次更新的一部分渲染时，这样可行。对于之后才加载的数据，等条目就绪后再调用 `focus(key)`。如果用户在此期间把焦点移到了别处，焦点就留在那里。

### 只移动 Tab 停靠点，不移动焦点
快捷键可以在焦点留在编辑器里时使用工具栏动作。在这个快捷键的处理函数里调用 `remember`，下次进入工具栏时就会落在那个动作上：

```ts
api.roving.remember("Underline")
```

在 Notes 里，按 Control 或 Command 加 U，再按 Shift+Tab。焦点回到 Underline。

`remember(key)` 改变 Tab 停靠点，但不移动焦点。设置了 `remember: false` 的组会忽略它。

### 任意布局
`move` 决定每个按键去往哪里。小键盘可以用它让 Up 和 Down 一次移动三个条目：

```ts
move: (event, { from, items, rtl }) => {
  if (event.ctrlKey || event.metaKey) {
    return
  }

  const index = items.findIndex((item) => item.key === from.key)
  const by = {
    ArrowDown: 3,
    ArrowUp: -3,
    ArrowRight: rtl ? -1 : 1,
    ArrowLeft: rtl ? 1 : -1,
  }[event.key]

  return by === undefined ? undefined : items[index + by]?.key
},
```

聚焦一个数字。用 Up 和 Down 移动一行，用 Left 和 Right 移动一项。

`move` 接收聚焦的条目、按文档顺序排列的可获得焦点的条目，以及文字方向。返回一个键就移动到那里，返回 `undefined` 则不干预这次按键。它会替换内置的方向键、Home、End 和循环规则，所以你的组件需要哪些规则就自己包含哪些。

和 `focus(key)` 一样，它可以返回一个即将渲染的条目的键。日历可以用它从一个月的最后一天移到下个月。

### 沿环排列
动作沿圆圈排列时，Left 和 Right 可以按它们在环上的顺序移动。使用内置的横向按键并加上循环：

```ts
const roving = createRovingFocus(context, {
  slot: "action",
  key: "focused",
  orientation: () => "horizontal",
  loop: () => true,
})
```

按动作在圆圈上的顺序渲染它们。它们的位置不会改变下一个动作是谁。

聚焦一个动作，然后不断按 Left 或 Right 在环上循环。Home 和 End 跳到第一个和最后一个动作。

## 空间焦点
### 跟随布局
在看板上，文档里的下一个条目未必是右边的那一个。用 `spatialMove()` 按方向键的方向选择附近的条目：

```ts
const roving = createRovingFocus(context, {
  slot: "note",
  key: "focused",
  move: spatialMove(),
})
```

聚焦一张便签，然后用方向键移动到该方向上附近的便签。

`spatialMove` 测量元素的位置，并偏向正前方的条目。即使在从右到左的文字里，Left 也始终表示屏幕上的左边。Home 和 End 按文档顺序移动。Alt、Control 和 Command 组合留给其他快捷键。

### 提供你自己的位置
如果你的应用已经知道各个条目的位置，就传入一个 `rect` 函数。这对缩放过的画布，或按角度计算出来的布局很有用：

```ts
move: spatialMove({
  rect: (el, key) => {
    const { x, y } = place(key)
    return { left: x, right: x, top: y, bottom: y }
  },
}),
```

每个条目使用相同的单位，`y` 值越大越靠下。

### 选择目标而不移动焦点
`nearestInDirection` 在普通的矩形盒子上做同样的基于位置的搜索。它返回一个键，结果怎么用由你决定：

```ts
const next = nearestInDirection(
  { left: 0, right: 10, top: 0, bottom: 10 },
  [{ key: "next", rect: { left: 20, right: 30, top: 0, bottom: 10 } }],
  [1, 0]
)
// next is "next".
```

方向是 `[x, y]`：`[1, 0]` 表示右，`[0, -1]` 表示上。如果那个方向什么都没有，结果就是 `undefined`。

聚焦地图，用方向键选择城市。焦点仍留在地图上。

## 键入查找
[文本](https://ui-sdk.cn/docs/core/text#find-an-item-by-typing)涵盖根据输入的字符查找条目。要把焦点移到匹配项上，把它与 `roving.items()` 和 `roving.focus()` 结合使用：

```ts
const typeahead = createTypeahead()

function keydown(event: KeyboardEvent, el: HTMLElement) {
  if (
    event.defaultPrevented ||
    roving.keydown(event, el) ||
    !isTypeaheadKey(event)
  ) {
    return
  }
  if (event.key === " " && typeahead.active()) {
    event.preventDefault()
  }

  const items = roving.items()
  const index = typeahead(
    event.key,
    items.map((item) => labelOf(item.el)),
    items.findIndex((item) => item.el === el)
  )
  if (index !== -1) {
    roving.focus(items[index].key)
  }
}
```

在 `api` 里创建一次 `typeahead`，然后把这个处理函数接到条目的 `keydown` 上。

聚焦 Apple，反复按 P 在匹配项之间循环。停顿一下，然后快速输入 PL 到达 Plum。

## 焦点恢复
聚焦的行被移除时，浏览器可能把焦点留在页面上。`createFocusRecovery` 让你选择焦点该去哪里：

```ts
const recovery = createFocusRecovery<{ value: string; index: number }>({
  fallback: (lost) => {
    const items = roving.items()
    return (items[lost.props.index] ?? items.at(-1))?.el
  },
})
```

这会选中取代旧行位置的那一行；如果移除的是末尾，就选最后一行。从 `api` 返回 `recovery`，然后把它和游走焦点一起绑定：

```ts
bind: (el, part) => {
  const unbindFocus = part.api.roving.bind(el, part)
  const unbindRecovery = part.api.recovery.bind(el, part)
  return () => {
    unbindFocus()
    unbindRecovery()
  }
},
```

聚焦一个任务并按 Delete，或点击 Done。焦点会移到一个仍然存在的任务上。

`fallback` 接收被移除部件的键、最后的 props 和元素。什么都不返回时，焦点留在原处。恢复会在部件解绑时运行，并等待渲染完成；它不会把焦点从别处（比如对话框）抢回来。

## 跟随移动的焦点
有时条目会移到另一个列表，并渲染成新的元素。在改变状态之后调用 `keepFocus`，传入一个能找到新元素的函数：

```ts
move(task: string) {
  const { done } = context.store.get()
  context.store.set({ done: [...done, task] })
  keepFocus(() => context.element("task", task))
},
```

聚焦一个任务并按 Enter。焦点会在列表之间跟着它走。关掉任务上的 Keep focus 来对比。

`keepFocus` 会在更新后重试，让新元素有时间渲染。如果用户在此期间把焦点移到了别处，它不会打扰那个焦点。

## 网格
### 网格中的一个 Tab 停靠点
对于按行和列定位的单元格，用 `createGridFocus`。从 `@ui-sdk/core` 导入 `GridCell` 类型，把活动单元格初始化为 `null`，然后在 `api` 里创建这个行为：

```ts
state: () => ({ active: null as GridCell | null }),
api: (context) => ({
  grid: createGridFocus(context, {
    key: "active",
    rows: () => 3,
    cols: () => 6,
  }),
}),
```

每个单元格都有从零开始的 `row` 和 `col`。把它的 Tab 停靠点、按键和元素接到这个行为上：

```ts
seat: slot<{ id: string; row: number; col: number }>({
  props: { id: "string", row: "number", col: "number" },
  selects: selects({ active: byCell }),
  attrs: (state, { props, api }) => ({
    role: "gridcell",
    tabindex: api.grid.tabIndex(state, props),
  }),
  on: {
    keydown: (event, { api }) => api.grid.keydown(event),
    pointerdown: (event, { api, props }) => api.grid.focus(props, { reason: "item-press", event }),
  },
  bind: (el, { api, props }) => api.grid.bind(el, props),
}),
```

把单元格渲染在带 `role="row"` 的行里，再放进带 `role="grid"` 的根元素里。给每个单元格一个稳定的 `id`，比如 `"1:2"`，好让原语（primitive）区分它们。

`selects({ active: byCell })` 让一次移动只触达焦点离开的单元格和落到的单元格，所以有几千个单元格的网格依然很快。

聚焦一个座位，用方向键移动。Home 和 End 到达本行的两端；按住 Control 或在 Mac 上按 Command，可到达网格的四角。

Left 和 Right 遵循文字方向。要从别的交互（比如点击）移动到某个单元格，调用 `grid.focus({ row, col })`。

### 无法获得焦点的单元格
传入 `disabled` 跳过不可用的单元格：

```ts
disabled: (cell) => context.options().taken.includes(`${cell.row}:${cell.col}`),
```

和游走焦点的 `disabled` 选项不同，这里会在导航时跳过该单元格。进入网格之前，Tab 会逐行落在第一个未禁用的单元格上。

用方向键越过已被占用的座位。按 Tab 离开网格；当前座位仍保持标记。

用 `grid.isActive(state, cell)` 在焦点离开时让活动单元格保持标记：

```ts
"data-active": api.grid.isActive(state, props) ? "" : undefined,
```

### 选择范围
`onMove` 会告诉你焦点移到了哪里、从哪里来，以及是否按住了 Shift。用它来记住选择的起点：

```ts
onMove: (cell, { from, shift }) => {
  const anchor = context.store.get().anchor ?? from
  context.store.set({ anchor: shift && anchor ? anchor : cell })
},
```

点击一个单元格，然后按住 Shift 用方向键或点击另一个单元格来扩展范围。不按 Shift 移动即可重新开始。

要支持 Shift 点击，把 `shift: event.shiftKey` 传给 `grid.focus`。回调还会收到 `event` 和一个 `reason`：按键对应 `"list-navigation"`，按压对应 `"item-press"`，命令式调用对应 `"imperative"`，这些名字与 listbox 上报的一致。[选择](https://ui-sdk.cn/docs/core/behaviors/selection#ranges-of-cells)涵盖如何把锚点（anchor）和活动单元格变成范围。

### 未渲染的行
大型网格可能只渲染可见的行。加上 `reveal`，在焦点移到目标行之前先把它带入视野：

```ts
reveal: ({ row }) => {
  const { first } = context.store.get()
  if (row < first) {
    context.store.set({ first: row })
  } else if (row >= first + 6) {
    context.store.set({ first: row - 5 })
  }
},
pageSize: () => 6,
```

这个时刻表一次显示六行。

聚焦一个单元格，按 Down 越过最后一行可见的行，或按 Page Down，把接下来的行带入视野。

`pageSize` 设置 Page Up 和 Page Down 移动多远。配合[虚拟列表](https://ui-sdk.cn/docs/core/behaviors/lists#long-lists)时，`reveal` 可以改为调用 `virtualizer.scrollToIndex(row)`。单元格绑定时焦点落下。

## 输入提示
有几个属性会告诉浏览器字段里装的是什么：`inputmode` 选择手机的按键，比如邮箱地址用带 `@` 的键盘，验证码用数字键盘；`enterkeyhint` 选择 Return 键。`autocomplete` 说明要自动填充什么，`autocapitalize`、`autocorrect` 和 `spellcheck` 说明是否要改动人们输入的内容。`inputHints` 会为一类字段填好这些属性：

```tsx
import { inputHints } from "@ui-sdk/core"

const hints = inputHints("email", { enter: "next" })
// { inputMode: "email", enterKeyHint: "next", autoComplete: "email", autoCapitalize: "none", autoCorrect: "off", spellCheck: "false" }
```

把它们展开到 `<input>` 或 `<textarea>` 上。它们按 React 的拼写方式书写，而 HTML 读取属性名时不区分大小写，所以同一个对象在 Vue、Svelte、Solid 和 `setAttribute` 里都能用。`enter` 设置 Return 键，比如后面还有字段时用 `"next"`，最后一个字段用 `"done"`。iPhone 的数字键盘（用于 `"tel"`、`"numeric"`、`"decimal"` 和 `"one-time-code"`）没有 Return 键，所以在这些键盘上，`enter` 只会在其他手机上显示。

| 类型                                    | 按键与 Return 键           | 自动填充与更正                         |
| --------------------------------------- | -------------------------- | -------------------------------------- |
| `"email"`、`"url"`                      | 地址键盘                   | 自动填充地址，不大写、不更正           |
| `"tel"`、`"one-time-code"`              | 数字键盘                   | 自动填充号码，或来自短信的验证码       |
| `"numeric"`、`"decimal"`                | 数字，`"decimal"` 带小数点 | 不自动填充                             |
| `"search"`                              | 搜索用 Return 键           | 不自动填充，也不大写或标记拼写         |
| `"name"`、`"username"`、`"postal-code"` | 常用键盘                   | 自动填充，并让姓名和邮政编码首字母大写 |
| `"current-password"`、`"new-password"`  | 常用键盘                   | 提供已保存的密码，或建议一个新密码     |
| `"message"`                             | 发送用 Return 键           | 开启大写、更正和拼写标记               |

在手机上点按每个字段：按键会变，Return 键也会变；iOS 26 把它画成符号，比如 next 显示为 ›，search 显示为 →。

它们只是提示：字段保留自己的 `type` 和校验，所以 `type="email"` 的字段仍会检查地址。展开之后写的属性会替换这些提示。

## API 参考
### 游走焦点选项
- `slot` (`string`): The slot whose parts are the group's items. Each joins in the slot's `bind` with `roving.bind(el, part)`. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `key` (`keyof State & string`): The state key that holds the key of the item with the tab stop. Start it at `null`, and set it back to `null` to forget the item focused last. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `orientation?` (`(() => RovingOrientation | "both")`): Which arrows move focus when there's no `move`: Up and Down, Left and Right, or `"both"` for all four, like a rating. Defaults to `"vertical"`. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `loop?` (`(() => boolean)`): Whether moving past either end wraps around. Defaults to `false`. Example: [Disabled Items and Wrapping](https://ui-sdk.cn/docs/core/behaviors/focus#disabled-items-and-wrapping).
- `remember?` (`boolean`): Whether the item focused last keeps the stop, like a toolbar, rather than the preferred one, like tabs. Defaults to `true`. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `disabled?` (`((item: RovingFocusItem<Props>) => boolean)`): Whether an item can't be activated. Enabled items take the stop first; disabled ones can still take focus. Example: [Disabled Items and Wrapping](https://ui-sdk.cn/docs/core/behaviors/focus#disabled-items-and-wrapping).
- `focusable?` (`((item: RovingFocusItem<Props>) => boolean)`): Whether an item can take focus now. An item that can't stays in the group and is skipped, like a tree item under a collapsed branch. Defaults to every item. Example: [Items That Can't Take Focus](https://ui-sdk.cn/docs/core/behaviors/focus#items-that-cant-take-focus).
- `preferred?` (`((item: RovingFocusItem<Props>) => boolean)`): Whether an item takes the stop before focus has been in the group: the selected tab, the checked radio. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `claims?` (`((state: State, item: RovingFocusItem<Props>) => boolean)`): Whether an item rendering before any item binds, like on the server, may hold the stop. The first such item does, so server markup has exactly one stop. Defaults to enabled and focusable items. Pass it when the stop should start on a selected item, like `(state, item) => state.value === null || item.key === state.value`. Example: [One Tab Stop](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop).
- `move?` (`((event: KeyboardEvent, context: RovingFocusMoveContext<Props>) => string | undefined)`): The key focus moves to for a key press, or `undefined` to leave the press alone. Replaces the default, which moves along `orientation` with the arrows, Home and End. Use it for any other shape: a tree's visible order, or a grid's rows. Shift is never swallowed, so a list can extend a range. The key may be one that isn't rendered or focusable yet, like the first day of next month in a calendar: the stop moves to it at once, and focus follows when its item can take it, as long as focus is still where the press left it. Example: [Any Layout](https://ui-sdk.cn/docs/core/behaviors/focus#any-layout).
- `onItemsChange?` (`(() => void)`): Runs once after items join or leave, however many did, once the stop has moved to where the rules put it. Example: [Items That Come and Go](https://ui-sdk.cn/docs/core/behaviors/focus#items-that-come-and-go).

### 网格焦点选项
- `key` (`keyof State & string`): The state key that holds the active `GridCell`, or `null` before the grid is entered. Example: [One Tab Stop in a Grid](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop-in-a-grid).
- `rows` (`() => number`): How many rows the grid has, header rows included when they hold cells. Example: [One Tab Stop in a Grid](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop-in-a-grid).
- `cols` (`() => number`): How many columns. Example: [One Tab Stop in a Grid](https://ui-sdk.cn/docs/core/behaviors/focus#one-tab-stop-in-a-grid).
- `pageSize?` (`(() => number)`): How many rows Page Up and Page Down move, usually how many show. Example: [Rows That Aren't Rendered](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered).
- `disabled?` (`((cell: GridCell) => boolean)`): Cells that can't take focus, skipped by the arrows and by the tab stop before the grid is entered. Example: [Cells That Can't Take Focus](https://ui-sdk.cn/docs/core/behaviors/focus#cells-that-cant-take-focus).
- `reveal?` (`((cell: GridCell) => void)`): Shows a cell that may not be rendered, like `virtualizer.scrollToIndex(cell.row)`, before focus moves to it. Example: [Rows That Aren't Rendered](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered).
- `onMove?` (`((cell: GridCell, details: { from: GridCell | null; reason: GridFocusReason; event?: Event; shift: boolean; }) => void)`): Runs after the active cell moves, with the cell it left. Example: [Selecting a Range](https://ui-sdk.cn/docs/core/behaviors/focus#selecting-a-range).


# 选择

选择条目、扩展选择，或框选一片形状或单元格。

`createSelection` 选择条目的键并扩展范围，`createLasso` 用画出的矩形选择条目，`createCellRange` 选择一块网格单元格。

从 `@ui-sdk/core` 导入它们。把它们与 [焦点与按键](/docs/core/behaviors/focus) 搭配使用，在条目之间移动并选择它们。

## 选择条目
### 选择一个
把选中的键保存在 `string[]` 里，即使只能选择一个条目。在 `api` 中，把 `createSelection` 加到已有的游走焦点（roving focus）行为旁边：

```ts
const change = createChange(context)
const selection = createSelection(context, {
  key: "value",
  set: (value, details) => change("value", value, details),
  order: () => roving.items().map((item) => item.key),
})
```

让 `value` 从 `[]` 开始，并从 `api` 返回 `selection`。`set` 回调使用与指南相同的 [变更模式](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)。

这个行为提供了一些方法，供你从事件处理函数中调用。例如，一次指针按压可以选择一个条目：

```ts
pointerdown: (event, { api, key }) => api.selection.choose(key, { reason: "item-press", event }),
```

`choose` 选中那个条目。`toggle` 还允许用户清除选择。把这一分支加到已有的 Space 按键处理函数里：

```ts
if (event.key === " ") {
  event.preventDefault()
  selection.toggle(key, { reason: "item-press", event })
}
```

这个方案选择器两者都用。`selection.isSelected(key)` 让它的 Enter 处理函数在继续之前检查是否已选中某个方案。

点击一个方案，或用方向键和 Space 选择一个。在已选中的方案上按 Space 会清除选择；按 Enter 带着它继续，控制台会记录每一步。

对于列表框（listbox），给根元素 `role="listbox"`，给每个条目 `role="option"`，并用 `state.value.includes(key)` 设置它的 `aria-selected`。保留 [焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus) 里的焦点连接。

### 选择多个
把 `multiple` 加到选择选项里：

```ts
multiple: () => true,
```

现在 `toggle` 在保留其他条目的同时添加或移除一个条目。指针按压和 Space 都用它，就像这个配料选择器。允许多选的列表框还需要在根元素上设置 `aria-multiselectable="true"`。

点击配料来添加或移除。使用键盘时，用 Left 和 Right，然后按 Space。

### 范围与全选
`extend` 从锚点选择到另一个条目。锚点是在不按 Shift 的情况下最近选择或切换的条目。下面三次调用给文件列表提供它惯常的指针交互：

```ts
press(event: PointerEvent, key: string) {
  const details = { reason: "item-press" as const, event }
  if (event.shiftKey) {
    selection.extend(key, { ...details, from: context.store.get().focused })
  } else if (event.metaKey || event.ctrlKey) {
    selection.toggle(key, details)
  } else {
    selection.choose(key, details)
  }
},
```

对于配合方向键的 Shift，使用已有焦点处理函数的返回值：

```ts
const moved = roving.keydown(event, el)
if (moved?.shift) {
  selection.extend(moved.key, {
    from: moved.from,
    reason: "list-navigation",
    event,
  })
}
```

还没有锚点时，`from` 提供起点。`selection.anchor()` 返回当前锚点的键。

当方向键只移动焦点而不选择时，比如在带复选框列的表格里，让锚点跟着焦点移动，这样下一次 Shift 范围就从那里开始。`setAnchor` 保持选择不变，`null` 清除锚点：

```ts
const moved = roving.keydown(event, el)
if (moved && !moved.shift) {
  selection.setAnchor(moved.key)
}
```

范围会保留设置锚点时已选中的内容，然后加入锚点与目标之间的条目。传入 `additive: false` 可以只选择该范围。从外部提供一个不同的选择会让下一次范围从头开始。

点击一个文件，然后按住 Shift 点击另一个来选择一个范围。按住 Control 或 Command 点击可以切换一个文件。勾选 Ranges replace the selection 进行比较。

在多选模式下，`toggleAll` 选择 `order` 里所有可用的键，如果它们已经全部选中则清除。在阻止浏览器默认动作之后，从你的 Control 或 Command+A 处理函数中调用它：

```ts
selection.toggleAll({ reason: "list-navigation", event })
```

`order` 决定范围和全选能到达哪些条目。对于虚拟化列表，传入完整的键列表，包括尚未渲染的条目。

### 无法选择的条目
用 `selectable` 跳过那些不应被选择、切换或加入范围的键：

```ts
selectable: (key) => !context.options().owners.includes(key),
```

在这个成员列表里，所有者一开始就是选中的。演示使用 `toggle` 和 `toggleAll`，它们不会动这些所有者。

聚焦一个成员，按两次 Control 或 Command+A。Hollis Grant 保持选中，而其他成员先被选中，然后被清除。

这并不会把条目固定在选择里：`choose` 和带 `additive: false` 的范围可以替换整个值。如果某些键必须始终保持选中，请在你的 `set` 回调里强制这一点。

## 矩形选择
### 画一个矩形
`createLasso` 选择被矩形触碰到的条目。在状态里先放 `selected: string[]` 和 `lasso: LassoDraft | null`，把 `lasso` 设为 `null`。把 `lasso` 加到原语的 `live` 字段里，[实时状态](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state) 有相关说明。

在 `api` 里创建这个行为，并把它作为 `lasso` 返回：

```ts
const lasso = createLasso(context, {
  slot: "shape",
  draft: "lasso",
  selected: () => context.store.get().selected,
  set: (keys, details) => change("selected", keys, details),
})
```

给绘制表面设置 `position: relative`、`touch-action: none` 和 `user-select: none`，这样绘制时不会滚动页面或选中文本。在指针落到它的空白处时开始：

```ts
pointerdown: (event, { el, api }) => {
  if (el && event.target === el) {
    api.lasso.pointerdown(event, el)
  }
},
```

让矩形部件保持渲染。没有拖动时，它的 `style` 会把它隐藏：

```ts
lasso: slot({
  attrs: () => ({ "aria-hidden": "true" }),
  live: live((state, { api }) => ({ style: api.lasso.style(state) })),
}),
```

从空白处拖动来选择形状；控制台会记录选择。按住 Shift 可以加入选择；在释放之前按 Escape 会取消矩形。

`lasso.touches(state, key)` 告诉你哪些条目属于预览选择。按住 Shift 时，这包括拖动之前已经选中的条目。用它来提供 `data-lassoed` 高亮。

选择只改变一次，在指针释放时，原因为 `"lasso"`。Escape 取消拖动并保留之前的选择。

### 它跳过的条目
加上 `selectable`，把某些条目排除在矩形的命中范围之外；再加上 `message`，自定义屏幕阅读器的播报：

```ts
selectable: (key) => !context.options().locked.includes(key),
message: (count) => `${count} ${count === 1 ? "photo" : "photos"} selected`,
```

播报在选择请求被接受之后运行。

从空白处拖过照片。City 和 Lake 保持未选中；释放时屏幕阅读器会播报选中的数量。

## 单元格范围
### 选择一块
[焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#grids) 展示了如何导航网格。当你还需要在单元格之间拖动、选择整行或整列，或复制一块内容时，加上 `createCellRange`。

在状态里保留 `range: CellRange | null` 字段，初始值为 `null`。传入已有的网格行为及其行数和列数：

```ts
const range = createCellRange(context, {
  key: "range",
  grid,
  rows: () => 4,
  cols: () => 5,
})
```

从 `api` 返回 `range`，然后更新已有的单元格槽位：

```ts
selects: selects({ active: byCell, range: byCellRange }),
attrs: (state, { props, api }) => ({
  role: "gridcell",
  tabindex: api.grid.tabIndex(state, props),
  ...api.range.cellAttrs(state, props),
}),
on: {
  keydown: (event, { api }) => api.range.keydown(event),
  pointerdown: (event, { api, props }) => api.range.pointerdown(event, props),
},
bind: (el, { api, props }) => api.range.bind(el, props),
```

`range.bind` 还会绑定网格焦点，`range.keydown` 把普通的导航转发给网格。同一个事件不需要同时调用两个行为。`byCellRange` 让范围变更只到达加入或离开范围的单元格，以及沿移动边界的单元格。

在单元格之间拖动，或点击一个单元格并按住 Shift 配合方向键。总计会跟随选中的范围。

范围扩大时，焦点停留在活动单元格上。不带 Shift 的移动会清除范围。这个行为还处理这些快捷键：

| 按键          | 动作               |
| ------------- | ------------------ |
| Shift+Space   | 选择范围所在的行。 |
| Control+Space | 选择范围所在的列。 |
| Control+A     | 选择每个单元格。   |
| Escape        | 清除范围。         |

`cellAttrs` 用 `aria-selected`、`data-selected` 和 `data-range-edge` 标记显式范围。最后一项列出单元格位于范围的哪些边上，比如 `"top left"`，所以你可以用 `[data-range-edge~="top"]` 画出轮廓。

### 从代码中选择
同一个范围可以从按钮或其他控件改变。行和列的索引从零开始：

```ts
range.selectColumns(1)
range.selectRows(0, 1)
range.select({ anchor: { row: 1, col: 1 }, end: { row: 2, col: 2 } })
range.selectAll()
range.select(null)
```

这些调用改变范围而不移动焦点。`select(null)` 清除范围。

用按钮选择一列、几行、一块或整个网格。摘要会说明范围并统计大于 10 的值。

`range.bounds(state)` 给出包含端点的 `top`、`left`、`bottom` 和 `right` 索引。没有显式范围时，它回退到活动单元格；如果没有活动单元格，则返回 `null`。当你需要汇总或统计单元格时，`range.contains(state, cell)` 使用同样的规则。

默认情况下，范围变更直接写入状态。要通过 `createChange` 上报它们，加上 `set`。你还可以自定义键盘选择之后屏幕阅读器听到的内容：

```ts
set: (value, details) => change("range", value, details),
message: ({ top, left, bottom, right }) =>
  `Rows ${top + 1} to ${bottom + 1}, columns ${left + 1} to ${right + 1} selected`,
```

对于尚未渲染的行，`reveal` 的作用和在 [网格焦点](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered) 里一样。

### 复制与粘贴
`range.text(state, read)` 把选中的单元格读成以制表符分隔的文本。从网格的 `copy` 处理函数中调用它：

```ts
copy(event: ClipboardEvent) {
  const state = context.store.get()
  const text = range.text(state, ({ row, col }) => state.cells[row][col])
  event.preventDefault()
  event.clipboardData?.setData("text/plain", text)
},
```

在 `paste` 处理函数里，`textToCells` 把剪贴板文本转换成行：

```ts
const rows = textToCells(event.clipboardData?.getData("text/plain") ?? "")
```

你的处理函数阻止默认粘贴，并从选择范围的左上角单元格开始，把这些值写进状态。到网格边缘就停止。演示的 Code 标签页显示了完整的处理函数。

选择单元格，用 Control 或 Command+C 复制。点击目标单元格，用 Control 或 Command+V 粘贴。

`cellsToText(rows)` 反方向工作。用它复制整张表，即使只选中了其中一部分。

## API 参考
### 条目选择选项
- `key` (`Key`): The state key that holds the selected keys, a `string[]`. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `set` (`(value: string[], details: Why<Reason>) => boolean`): Asks for a new selection and returns whether it went through. Pass the primitive's change, so `on<Key>Change`, `cancel()` and controlled values work: `set: (value, details) => change("value", value, details)`. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `order` (`() => readonly string[]`): Every key in list order, for ranges and select all, like the visible items' keys. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `multiple?` (`(() => boolean)`): Whether more than one item can be selected. Defaults to `false`. Example: [Choose Many](https://ui-sdk.cn/docs/core/behaviors/selection#choose-many).
- `selectable?` (`((key: string) => boolean)`): Whether a key can be chosen, toggled, or added to a range. Replacing the selection can still remove it. Defaults to every item. Example: [Items That Can't Be Selected](https://ui-sdk.cn/docs/core/behaviors/selection#items-that-cant-be-selected).

### 矩形选择选项
- `slot` (`string`): The slot whose parts the rectangle selects. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `draft` (`keyof State & string`): The state key that holds the `LassoDraft` while one is drawn. Start it at `null`, and list it in `live`. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `selected` (`() => string[]`): The selection now, which Shift adds to. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `set` (`(keys: string[], details: { reason: "lasso"; event?: Event; }) => boolean`): Asks for a new selection. Pass the primitive's change. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `selectable?` (`((key: string) => boolean)`): Whether an item can be selected. Defaults to every item. Example: [Items It Skips](https://ui-sdk.cn/docs/core/behaviors/selection#items-it-skips).
- `message?` (`((count: number) => string)`): What screen readers hear when the rectangle lifts. Defaults to English. Example: [Items It Skips](https://ui-sdk.cn/docs/core/behaviors/selection#items-it-skips).

### 单元格范围选项
- `key` (`keyof State & string`): The state key that holds the `CellRange`, or `null` when only the active cell is selected. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `grid` (`object`): The grid's focus, which keeps the active cell. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `rows` (`() => number`): How many rows the range can reach. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `cols` (`() => number`): How many columns. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `reveal?` (`((cell: GridCell) => void)`): Shows a cell the range grows to that may not be rendered, like `createGridFocus`'s `reveal`. Example: [Rows That Aren't Rendered](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered).
- `set?` (`((range: CellRange | null, details: { reason: CellRangeReason; event?: Event; }) => boolean)`): Asks for a new range and returns whether it went through. Defaults to writing the state; pass the primitive's change to report it. Example: [Selecting from Code](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-from-code).
- `message?` (`((bounds: CellBounds) => string)`): What screen readers hear after the range changes from the keyboard. Defaults to English. Example: [Selecting from Code](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-from-code).


# 拖放

排序列表、嵌套树，或用指针或键盘在列表之间移动条目。

`createReorder` 排序列表和网格，`createTreeReorder` 移动行和子树，`createTransfer` 在列表之间移动条目。它们在移动过程中保留一份草稿，并在放下时通过你的[变更](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)提交它。用 `bindDrag` 为自定义拖动跟踪指针。

从 `@ui-sdk/core` 导入这些辅助函数。[组合行为](/docs/core/compose-behaviors)演示如何把行为接到原语（primitive）上。对于自由定位的条目，见[拖动与调整大小](/docs/core/behaviors/direct-manipulation)。

## 指针拖动
### 跟随指针
`bindDrag` 跟随按压某个元素的指针。在指针处理函数里调用它，并保留它的清理函数，这样销毁原语时也会停止拖动：

```ts
let stop: (() => void) | undefined
context.onDestroy(() => stop?.())

return {
  pointerdown(event: PointerEvent, el: HTMLElement) {
    if (event.button !== 0) {
      return
    }
    stop?.()
    stop = bindDrag(el, event, {
      threshold: dragThreshold,
      cancelOnEscape: true,
      onMove: ({ x }) => resizeTo(x),
      onEnd: (_event, canceled) => (canceled ? restore() : commit()),
    })
  },
}
```

这里 `resizeTo`、`restore` 和 `commit` 是你自己的分隔条方法。`bindDrag` 只跟踪指针；每个位置意味着什么由你决定，键盘控制也由你添加。

拖动分隔条，或者聚焦它并使用 Left 和 Right。拖动过程中按 Escape 可以恢复宽度。

`onMove` 每帧最多运行一次。如果浏览器接管了指针，或者 Escape 取消了拖动，`onEnd` 会收到一个取消标志。返回的清理函数会停止跟踪，但不调用 `onEnd`。

`dragThreshold` 会等待移动几个像素后才开始 `onMove`。一次按压仍可能在低于该阈值时就结束，所以不要假设每个 `onEnd` 前面都有一次移动。当拖动应当优先于滚动时，给可拖动的表面设置 `touch-action: none`。

### 越过阈值收起
侧边栏会在最小宽度和最大宽度之间调整大小，也可以收起，但绝不会停在两者之间。当指针低于最小值时，让 `scrubTo` 来决定：给它两个吸附点，收起和最小值，各自覆盖一半的范围，并朝它们缓动：

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

const collapse = { min: 0, max: minWidth, step: 1, snap: { points: [0, minWidth], threshold: minWidth / 2 } }

const widthAt = (pointer: number) =>
  pointer >= minWidth ? { value: Math.min(maxWidth, pointer), point: undefined } : scrubTo(pointer, collapse, { ease: true })

onMove: ({ x }) => {
  const { value, point } = widthAt(x - root.getBoundingClientRect().left)
  store.set({ draft: value, landing: point ?? null })
},
onEnd: () => commit(store.get().landing ?? store.get().draft),
```

当指针移到最小值以下时，侧边栏会跟随它，并朝更近的那个点加速，于是逐渐接近收起，而不会突然跳变。`point` 表示它最终会落到哪里，所以演示可以在松开之前就说明；朝另一个方向拖动时，它也会以同样的方式展开。

把分隔条拖到侧边栏最小值以下：它会朝收起或回到最小值的方向缓动，并说明松手后会发生哪一种。聚焦分隔条后可以使用 Left、Right 和 Enter。

### 不受限制地拖动
对于拖动调节器（scrubber），指针锁定让用户能一直拖动，越过屏幕边缘。读取移动的距离，而不是指针的位置：

```ts
bindDrag(el, event, {
  threshold: dragThreshold,
  lock: true,
  onStart: () => !context.options().locked,
  onMove: ({ movementX, event }) => {
    change("value", context.store.get().value + movementX / 2, {
      reason: "drag",
      event,
    })
  },
  onEnd: () => {},
})
```

当移动达到阈值时，`onStart` 会运行。返回 `false` 会停止跟踪，但不调用 `onEnd`。如果浏览器无法锁定指针，跟踪会继续使用指针捕获。

把 Opacity 标签向左或向右拖动。指针锁定可用时，光标会隐藏，这样你可以一直拖。勾选 Locked 可以阻止拖动。

传给 `onMove` 的采样对象会被复用。在回调期间读取 `x`、`y`、`movementX`、`movementY`、`locked` 和 `event`，不要把这个对象留到以后再用。

## 重新排序
### 排序列表
把已提交的顺序保存在一个 `string[]` 里，并另起一个 `ReorderDraft | null` 字段，初始值为 `null`。在 `api` 里把它们接到 `createReorder`：

```ts
const change = createChange(context)
const reorder = createReorder(context, {
  slot: "item",
  key: "value",
  draft: "moving",
  set: (value, details) => change("value", value, details),
})
```

从 `api` 返回 `reorder`。用 `reorder.order(state)` 渲染条目，它在移动过程中读取草稿，其他时候读取已提交的值。顺序变化时，保持每个条目的键稳定。

条目的槽位会先运行重排处理函数，再运行已有的游走焦点处理函数。这样，在有人拿起条目之前，方向键仍然可以移动焦点：

```ts
on: {
  keydown: (event, { el, api, key }) =>
    api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
  pointerdown: (event, { api, key }) => api.reorder.pointerdown(event, key),
},
bind: (el, part) => {
  const cleanups = [part.api.roving.bind(el, part), part.api.reorder.bind(el, part)]
  return () => cleanups.forEach((cleanup) => cleanup())
},
```

拖动一个季节来给它排名。使用键盘时，聚焦其中一个，按 Space 或 Enter，用方向键移动，再按 Space 或 Enter 放下。Escape 取消。

Home 和 End 把拿起的条目移到任意一端。Tab 取消移动，并继续在页面中移动焦点。变更会报告 `drag` 或 `move-key`，屏幕阅读器会听到拿起、移动和放下。

这个演示使用由 `option` 组成的 `listbox`，为可排序列表和条目设置 `aria-roledescription`，并为拿起的条目设置 `aria-selected`。给每个条目一个 `aria-describedby`，指向键盘操作说明。对于带嵌套控件的条目，使用列表并单独提供一个拖动手柄按钮，把处理函数放在那个手柄上。

拖动过程中，core 会把 `--drag-x` 和 `--drag-y` 写到绑定的条目上。用它们让条目保持在指针下方，并用 `state.moving?.key === key` 派生出 `data-grabbed` 属性：

```css
[data-slot="sortable-list-item"] {
  touch-action: none;
  user-select: none;
}
[data-slot="sortable-list-item"][data-grabbed] {
  transform: translate(var(--drag-x, 0), var(--drag-y, 0));
  position: relative;
  z-index: 1;
}
```

### 网格
默认方向是纵向。对于会换行成多行的条目，加上 `orientation: () => "grid"`：

```ts
orientation: () => "grid",
```

把照片拖到新位置，或者按 Space 拿起它。Left 和 Right 移动一个位置；Up 和 Down 在行之间移动。Space 放下它。

对于单行横向排列，使用 `"horizontal"`，给它的游走焦点设置相同的方向，并在列表框上设置 `aria-orientation="horizontal"`。

### 一次移动多个
`group` 回调让选中的一组条目一起移动。把它加到重排选项里：

```ts
group: (key) => {
  const { selected } = context.store.get()
  return selected.includes(key) ? selected : [key]
},
```

分组在拖动开始时确定，保持列表的顺序，并把已禁用的条目留在原处。`reorder.moving(state, key)` 标识分组里的每个条目；`reorder.dragging(state, key)` 还要求这是一次指针拖动。

勾选几个任务，然后拖动其中一个已勾选的任务。你也可以聚焦一个已勾选的任务，用 Space 和方向键移动整个分组。

已经用 `preventDefault()` 处理过的指针事件不会启动重排。这样，复选框可以处理自己的按压，而不会同时拿起条目。

### 拖动时显示副本
对于可滚动的列表，被平移的条目可能会被裁剪。加上 `preview: true`，在页面之上拖动一份副本：

```ts
preview: true,
createAutoScroll: { edge: 40, speed: 12 },
```

拖动一首曲目，并把它停在播放列表的顶部或底部边缘附近来滚动。它的占位符会显示它将落到哪里。

原条目会留在拟定的顺序里。使用分组时，副本还会获得 `data-drag-count` 和 `--drag-count`，用于显示数量徽标。自动滚动会随预览一起启用；用 `createAutoScroll: false` 关掉它。

### 用代码移动
对于立即发生的变更，比如菜单的 Move to Top 操作，使用 `move`：

```ts
reorder.move("Serve", 0)
```

对于一次只走一步的控件，使用 `grab(key)`、`moveTo(index)` 和 `drop()` 或 `cancel()`。`moveTo` 在移除正在移动的分组后剩下的条目之间计算位置。

使用 Top 立即移动一个食谱步骤。工具栏会拿起聚焦的步骤，移动它，然后放下或取消。

立即移动会报告 `imperative`；拿起和放下控件遵循与键盘相同的草稿。

### 播报什么
当条目的可见文本包含的内容多于它的名称时，使用 `label`。自定义 `message` 可以只替换一条播报，其余仍用默认值：

```ts
disabled: (item) => item.key === context.options().pinned,
label: (key) => titles[key],
message: (message) =>
  message.type === "move" ? `${message.label}, track ${message.position}.` : reorderMessage(message),
```

用 Space 拿起未固定的曲目，并用方向键移动它。屏幕阅读器会播报曲目编号。已固定的曲目不能被拿起，但其他曲目可以越过它移动。

`disabled` 阻止拿起；但它不会保留条目的位置。播报是即时（assertive）的，一轮中的多个变更可能作为最新消息一起播报。

## 重新排序树
### 排序与嵌套
树使用一个扁平的 `{ key, depth }` 行数组，按阅读顺序排列。移动父级会移动它的整个子树。把 `moving` 的初始值设为 `null`，类型为 `TreeReorderDraft | null`：

```ts
const tree = createTreeReorder(context, {
  key: "rows",
  draft: "moving",
  set: (value, details) => change("rows", value, details),
  indent: () => 20,
  preview: true,
})
```

渲染 `tree.rows(state)`，按 `depth` 缩进，并用 `tree.bind(el, key)` 绑定每个渲染出的行。也要保留游走焦点的绑定。和可排序列表一样，在焦点处理函数之前调用 `tree.keydown(event, key)`，在按压时调用 `tree.pointerdown(event, key)`。

把大纲行向上或向下拖动，横向拖动可以改变它的深度。使用键盘时，按 Space 拿起它，用 Up 和 Down 放置，用 Left 和 Right 改变它的层级。

`indent` 是一级的水平距离，默认 24 像素。关闭的子树可以留在数据里，而它们的行不挂载；指针命中会跳过这些隐藏的行。

一次移动不会改变相邻行的父级。深度受插入点周围行的限制。`set` 的详情包括 `key`、`parent`（根节点处为 `null`），以及在该父级子节点中从 0 开始的 `index`；当你的应用存储的是嵌套树时，这很有用。

### 限制与用代码移动
加上最大深度和拿起规则：

```ts
maxDepth: () => 1,
disabled: (key) => key === "Inbox",
```

深度从 0 开始，所以这里允许两层。限制包括正在移动的行及其后代。

使用文件夹的箭头按钮，把它连同内容一起缩进或取消缩进。树允许两层，Inbox 不能被拿起。

`tree.move(key, before, depth)` 把子树移到另一行之前；当 `before` 为 `null` 时，移到末尾。它会使用最接近且合适的深度。`subtreeEnd(rows, index)` 返回子树之后的第一个索引，有助于计算插入位置。

对于分步移动，使用 `grab`、`place`，然后 `drop` 或 `cancel`。`moving(state, key)` 包括后代；`dragging` 还会检查移动是否来自指针。像列表那样自定义 `label` 和 `message`，默认文案由 `treeReorderMessage` 提供。

## 在列表之间移动
### 两个列表
把各个列表一起存成一个 `Record<string, string[]>`，并让条目键在所有列表之间唯一。为移动添加一个 `TransferDraft | null` 字段：

```ts
const transfer = createTransfer(context, {
  key: "lists",
  draft: "moving",
  set: (value, details) => change("lists", value, details),
})
```

从 `transfer.lists(state)` 渲染。用 `bindList(el, key)` 绑定列表元素，用 `bindItem(el, key)` 绑定条目元素，并从槽位返回它们的清理函数。保留已有的焦点绑定，并在它的按键处理函数之前运行 `transfer.keydown(event, key)`。按压时调用 `transfer.pointerdown(event, key)`。

在打包清单之间拖动条目。使用键盘时，按 Space 拿起它，用 Left 和 Right 切换列表，用 Up 和 Down 放置，然后按 Space 放下。

移动使用一份被拖动的副本，并在靠近边缘时自动滚动。`moving(state, key)` 标识拿起的条目，而 `dragging(state, key)` 标识一次指针拖动。`set` 的详情包括条目的 `key`、它的 `from` 和 `to` 列表，以及它的新 `index`。

### 带规则的看板
用 `accepts` 拒绝某个目标，用 `order` 选择键盘在列表之间的行进顺序：

```ts
order: () => ["todo", "doing", "done"],
accepts: (key, list) =>
  list !== "doing" || context.store.get().lists.doing.filter((card) => card !== key).length < 2,
disabled: (key) => key === "Billing",
listLabel: (list) => columns[list],
```

在列之间移动卡片。Doing 最多容纳两张卡片，Billing 不能被拿起，卡片上的勾选会把它直接移到 Done。

`transfer.move("Search", "done", 0)` 会立即移动。对于分步移动，使用 `grab`、`moveTo(list, index)`，然后 `drop` 或 `cancel`。

`label` 为条目命名，`listLabel` 为目标命名，`message` 自定义播报，默认由 `transferMessage` 提供。对于不需要边缘滚动的看板，设置 `createAutoScroll: false`。

## 拖动副本
对于你自己的拖动，`bindDragPreview` 会创建一个跟随指针的元素副本。原元素留在原处：

```ts
const preview = bindDragPreview(el, { x: event.clientX, y: event.clientY })
```

在拖动的 `onMove` 里调用 `preview.move(x, y)`。在 `onEnd` 和任何提前清理中调用 `preview.remove()`。你可以通过 `preview.el` 给副本设置样式，例如在有效目标上方切换 `data-over` 属性。

把标签拖到便签上，当副本高亮时松开。你也可以聚焦一个标签并按 Enter 添加它。

副本在创建时保留元素的外观；它不会渲染之后框架的更新。它带有 `data-drag-preview`，移除了 ID，并且对辅助技术和指针命中隐藏。它在可用时使用顶层，否则回退到固定定位。

## 拖动时滚动
自定义拖动可以用 `createAutoScroll` 在指针附近滚动。为这次拖动创建它，每次移动时调用 `update(x, y)`，并在每次退出时调用 `stop()`：

```ts
const scroll = createAutoScroll({
  edge: 48,
  speed: 16,
  ignore: () => preview.el,
  onScroll: findChapter,
})
```

把书签拖到章节列表的顶部或底部边缘附近。保持在那里继续按住即可滚动，然后在某一章上松开。

`edge` 是开始滚动的距离，单位为像素；`speed` 是每帧的最大像素数。辅助函数会找到指针下方最近的滚动容器，并以页面的纵向滚动作为回退。`ignore` 会跳过某个元素，比如被拖动的副本。`onScroll` 让你在内容从静止的指针下方移过后重新找到目标。

## 保持焦点与草稿
排序行为已经会保留焦点，并在受控值赶上之前保持已提交的草稿可见。如果你要构建自己的拖动，在移动已聚焦的元素之后使用 [`keepFocus`](https://ui-sdk.cn/docs/core/behaviors/focus#focus-that-follows-a-move)，在把草稿交给它的所有者时使用 [`settleDraft`](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes-from-elsewhere)。

## API 参考
选项表格会链接回介绍它们的示例。

- `onMove` (`(sample: PointerSample) => void`): At most once per frame, with the latest position and the movement since the last call. Example: [Follow a Pointer](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#follow-a-pointer).
- `onEnd` (`(event: PointerEvent, canceled: boolean) => void`): The pointer lifted, or the browser took it over, like for a scroll. A move still pending runs first, so the last position is never lost. Example: [Follow a Pointer](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#follow-a-pointer).
- `threshold?` (`number`): How far, in CSS pixels, the pointer moves along either axis before moves are reported, so a press that barely moves stays a click. Defaults to 0. Example: [Follow a Pointer](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#follow-a-pointer).
- `onStart?` (`((event: PointerEvent) => boolean | void)`): Runs once, on the first move past `threshold`, before its `onMove`. Return `false` to stop following the pointer, like when a drag can't start. Example: [Dragging Without Limits](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#dragging-without-limits).
- `lock?` (`boolean`): Locks the pointer once it has moved past `dragThreshold`, so it can travel without limit, like a scrub, while a plain click never hides the cursor. Falls back to capture where the browser refuses, as Safari does. Example: [Dragging Without Limits](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#dragging-without-limits).
- `cancelOnEscape?` (`boolean`): Ends the gesture as canceled when Escape is pressed once it has started, and keeps that press from reaching anything else, like a popup around it. `onEnd` gets the last pointer event. Defaults to `false`. Example: [Follow a Pointer](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#follow-a-pointer).

- `slot` (`string`): The slot whose parts are the items. Each joins in the slot's `bind` with `reorder.bind(el, part)`. Example: [Sort a List](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-a-list).
- `key` (`keyof State & string`): The state key that holds the order, a `string[]` of item keys. Example: [Sort a List](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-a-list).
- `draft` (`keyof State & string`): The state key that holds the `ReorderDraft` while an item moves. Start it at `null`. Example: [Sort a List](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-a-list).
- `set` (`(value: string[], details: { reason: ReorderReason; event?: Event; }) => boolean`): Asks for a new order and returns whether it went through. Pass the primitive's change, so `on<Key>Change`, `cancel()` and controlled values work: `set: (value, details) => change("value", value, details)`. Example: [Sort a List](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-a-list).
- `orientation?` (`(() => ReorderOrientation)`): Whether the items run top to bottom, along a line, or wrap in rows like a grid of photos, which picks the arrows and how a drag finds its place. Defaults to `"vertical"`. Example: [Grids](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#grids).
- `group?` (`((key: string) => string[])`): The keys that move with the one picked up, like the selection when it holds it. Defaults to that one key. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#several-at-once).
- `preview?` (`boolean`): Drags a copy of the item above the page while the item itself shows where it would drop, so a list that scrolls neither clips it nor grows under it. A drag near a scroller's edge scrolls it. Defaults to `false`. Example: [A Copy While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-copy-while-dragging).
- `createAutoScroll?` (`false | Omit<AutoScrollOptions, "ignore" | "onScroll">`): How a drag with `preview` near a scroller's edge scrolls it, or `false` not to. Example: [A Copy While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-copy-while-dragging).
- `disabled?` (`((item: { key: string; props: Props; }) => boolean)`): Whether an item can't be picked up. It still moves aside for others. Example: [What's Read Out](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#whats-read-out).
- `label?` (`((key: string) => string | undefined)`): The name screen readers hear for an item. Return `undefined` for the default, its text. Example: [What's Read Out](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#whats-read-out).
- `message?` (`((message: ReorderMessage) => string)`): The text screen readers hear for each step. Defaults to English. Example: [What's Read Out](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#whats-read-out).

- `key` (`keyof State & string`): The state key that holds the rows, a `TreeReorderRow[]` in reading order. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).
- `draft` (`keyof State & string`): The state key that holds the `TreeReorderDraft` while an item moves. Start it at `null`. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).
- `set` (`(value: TreeReorderRow[], details: { reason: TreeReorderReason; event?: Event; key: string; } & TreePlace) => boolean`): Asks for the new rows and returns whether they went through. Pass the primitive's change: `set: (value, details) => change("rows", value, details)`. `details` says which item moved and where to. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).
- `indent?` (`(() => number)`): How far a drag goes sideways for each level, in CSS pixels. Defaults to 24. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).
- `maxDepth?` (`(() => number)`): The deepest an item and the rows under it can go, from 0. Defaults to no limit. Example: [Limits and Moving from Code](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code).
- `disabled?` (`((key: string) => boolean)`): Whether an item can't be picked up. It still moves aside for others. Example: [Limits and Moving from Code](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code).
- `label?` (`((key: string) => string | undefined)`): The name screen readers hear for an item. Defaults to its text. Example: [Limits and Moving from Code](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code).
- `message?` (`((message: TreeReorderMessage) => string)`): The text screen readers hear for each step. Defaults to English. Example: [Limits and Moving from Code](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#limits-and-moving-from-code).
- `preview?` (`boolean`): Drags a copy of the row above the page while the rows show where it would drop. Defaults to `false`. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).
- `createAutoScroll?` (`false | Omit<AutoScrollOptions, "ignore" | "onScroll">`): How a drag with `preview` near a scroller's edge scrolls it, or `false` not to. Example: [Sort and Nest](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#sort-and-nest).

- `key` (`keyof State & string`): The state key that holds every list, a `TransferLists`. Example: [Two Lists](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#two-lists).
- `draft` (`keyof State & string`): The state key that holds the `TransferDraft` while an item moves. Start it at `null`. Example: [Two Lists](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#two-lists).
- `set` (`(value: TransferLists, details: { reason: TransferReason; event?: Event; key: string; from: string; to: string; index: number; }) => boolean`): Asks for the new lists and returns whether they went through. Pass the primitive's change: `set: (value, details) => change("lists", value, details)`. `details` says what moved, from where to where. Example: [Two Lists](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#two-lists).
- `order?` (`(() => string[])`): The lists in the order Left and Right go through them. Defaults to the order of the value's keys. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `accepts?` (`((key: string, list: string) => boolean)`): Whether a list takes an item, like a column at its limit. Lists that don't are skipped. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `disabled?` (`((key: string) => boolean)`): Whether an item can't be picked up. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `label?` (`((key: string) => string | undefined)`): The name screen readers hear for an item. Defaults to its text. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `listLabel?` (`((list: string) => string | undefined)`): The name screen readers hear for a list. Defaults to its key. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `message?` (`((message: TransferMessage) => string)`): The text screen readers hear for each step. Defaults to English. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).
- `createAutoScroll?` (`false | Omit<AutoScrollOptions, "ignore" | "onScroll">`): How a drag near a scroller's edge scrolls it, or `false` not to. Example: [A Board with Rules](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#a-board-with-rules).

- `edge?` (`number`): How far in from an edge scrolling starts, in pixels. Example: [Scrolling While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging).
- `speed?` (`number`): The fastest it scrolls, in pixels per frame, with the pointer at the edge. Example: [Scrolling While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging).
- `onScroll?` (`(() => void)`): Runs after each frame that scrolled, so a drag can find its target again under a pointer that didn't move. Example: [Scrolling While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging).
- `ignore?` (`(() => Element | null | undefined)`): The element being dragged, which sits under the pointer, so the scrollers under it are found instead of its own. Example: [Scrolling While Dragging](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging).


# 拖动与调整大小

移动和调整对象的大小，显示滑动操作，按压并按住，选取点，绘制范围，并预览选项。

`createMove` 移动对象，`createResize` 改变它们的边界，`createSwipeActions` 露出行背后的操作，`bindHold` 响应持续按住的按压，`bindRepeat` 在按钮被按住期间持续步进。`createArea` 选取二维值，`createSpans` 编辑轨道上的范围，`createPreview` 让人在选定之前试用一个值。

从 `@ui-sdk/core` 导入这些辅助函数。当辅助函数需要 `set` 回调时，把它接到你的[变更](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)上。要把条目排序，见[拖放](/docs/core/behaviors/drag-and-drop)。

## 在二维中移动
### 放置任意对象
把位置保存在 `Record<string, MovePoint>` 里，并另起一个 `MoveDraft | null` 字段，初始值为 `null`。在 `api` 里把它们接到 `createMove`：

```ts
const change = createChange(context)
const move = createMove(context, {
  key: "positions",
  draft: "moving",
  set: (value, details) => change("positions", value, details),
  step: () => 4,
  bounds: () => ({ minX: 0, minY: 0, maxX: 264, maxY: 144 }),
})
```

从 `api` 返回 `move`。定位槽位使用已提交的坐标作为基础位置。把 `moving` 加到原语的 `live` 字段里，并让实时槽位绑定写入拖动偏移：

```ts
attrs: (state, { key }) => ({
  style: css({
    position: "absolute",
    left: `${state.positions[key].x}px`,
    top: `${state.positions[key].y}px`,
    "touch-action": "none",
  }),
}),
live: live((state, { api, key }) => ({
  "data-dragging": api.move.dragging(state, key) ? "" : undefined,
  style: api.move.style(state, key),
})),
on: {
  keydown: (event, { api, key }) => api.move.keydown(event, key),
  pointerdown: (event, { el, api, key }) => api.move.pointerdown(event, key, el!),
},
```

在一个已定位的容器里，把这个槽位渲染成可获得焦点、带有无障碍名称的元素。实时绑定会更新 `translate`、`--move-x` 和 `--move-y`，而不必为每次指针移动触发框架渲染。

拖动一张贴纸，或者聚焦它并按 Alt 加方向键移动 4 像素。加上 Shift 会移动十倍的距离。拖动过程中按 Escape 会把它放回原处。

`step` 是放下的位置所落到的网格，也是 Alt 加方向键移动的距离；Shift 会按 `largeStep` 移动，默认是十步。`bounds` 限制已提交的坐标；拖动预览在松开之前可以超出这些坐标。放下会报告 `drag`，键盘微移会报告 `move-key`，屏幕阅读器会听到新的位置。

### 一次移动多个
加上 `group`，让选中的一组一起移动：

```ts
group: (key) => {
  const { selected } = context.store.get()
  return selected.includes(key) ? selected : [key]
},
step: () => 20,
disabled: (key) => key === "ship",
label: (key) => titles[key],
```

`step` 设置网格以及 Alt 加方向键的距离，默认为 1。`disabled` 阻止指针和键盘移动，并把该条目从正在移动的分组中移除。

点击便签将其选中，或按住 Shift 点击以加入一个。拖动已选中的便签来移动整个分组。Alt 加方向键会把它微移 20 像素；固定的便签留在原处。

在 pointerdown 时先选择，再调用 `move.pointerdown`。当按压的便签已经在选择中时，保持选择不变。演示把它和[空间焦点](https://ui-sdk.cn/docs/core/behaviors/focus#spatial-focus)结合起来，所以普通方向键可以在便签之间移动。

`label` 提供播报用的名称。`message` 可以用移动的 `keys`、第一个条目的 `label` 以及它新的 `at` 点来自定义句子。`moveMessage` 提供默认文案。

### 缩放与用代码移动
在缩放过的画布上，告诉行为多少个屏幕像素代表一个单位：

```ts
scale: () => context.store.get().zoom,
```

指针距离会除以这个缩放比例。用代码发起的移动仍然使用画布自己的单位：

```ts
move.moveTo("circle", { x: 100, y: 60 })
move.moveBy(["circle"], 10, 0)
```

改变缩放，然后拖动形状。用按钮在不拖动的情况下移动圆形。

两个方法都会报告 `imperative` 并应用 `bounds`。它们不会应用拖动的网格，也不会过滤已禁用的键，所以如有需要，在调用它们之前先检查这些应用规则。

## 调整盒子大小
### 盒子上的手柄
一个盒子有 `{ x, y, width, height }`。把盒子保存在状态里，另起一个 `ResizeDraft | null` 字段并初始化为 `null`，然后在 `api` 里添加 `createResize`：

```ts
const resize = createResize(context, {
  boxes: (state) => state.boxes,
  draft: "draft",
  set: (value, details) => change("boxes", value, details),
  min: () => ({ width: 60, height: 40 }),
  bounds: () => ({ left: 0, top: 0, right: 320, bottom: 200 }),
  step: () => 4,
})
```

盒子槽位用 `boxStyle` 读取已提交的尺寸。把 `draft` 列进原语的 `live` 字段，然后通过实时绑定应用 `resize.style`：

```ts
box: slot({
  attrs: (state, { api }) => ({ style: api.resize.boxStyle(state, "frame") }),
  live: live((state, { api }) => ({ style: api.resize.style(state, "frame") })),
  on: {
    pointerdown: (event, { el, api }) => api.resize.pointerdown(event, "frame", "move", el!),
  },
}),
```

把盒子绝对定位，并给每个手柄自己的 ID。手柄使用罗盘方向名：`n`、`e`、`s`、`w`、`ne`、`nw`、`se` 和 `sw`。盒子本身使用 `move`。

把手柄渲染成按钮，名称例如 “Resize bottom right”。它们的槽位调用 `resize.handleAttrs(handle)` 来处理光标和触摸行为，调用 `resize.pointerdown(event, key, handle, el)` 来处理拖动，调用 `resize.keydown(event, key, handle)` 来处理方向键。

拖动手柄调整框架大小，或拖动框架移动它。聚焦一个手柄并使用方向键；加上 Shift 可以走更大的步长。Escape 取消拖动。

`handleAttrs` 不提供标签，也不让元素可获得焦点。按钮负责这些。方向键按 `step` 移动一条边，也就是放下的盒子所落到的网格，或者加上 Shift 时按 `largeStep` 移动，默认十步；边上的手柄沿自己的轴响应。变更会报告 `drag` 或 `resize-key`。

### 保持形状
在调整大小的选项里设置宽高比和尺寸限制：

```ts
aspect: () => (context.store.get().locked ? 16 / 9 : undefined),
min: () => ({ width: 96, height: 54 }),
max: () => ({ width: 256, height: 144 }),
largeStep: () => 16,
```

在勾选 16:9 时调整视频框架的大小。取消勾选即可自由调整，或在拖动角时按住 Shift，以保持框架起始时的比例。

`aspect` 是宽度除以高度。角会跟随移动得更远的那条边；边上的手柄围绕中心调整另一个维度。`min` 和 `max` 限制尺寸，而 `bounds` 描述周围的区域。这里 `largeStep` 让 Shift 加方向键移动 16 像素，而普通方向键仍然移动 1。

### 多个盒子，以及用代码操作
同一个行为可以管理多个盒子。为缩放过的桌面加上 `scale`，为用户不应移动或调整大小的盒子加上 `disabled`：

```ts
scale: () => 0.75,
disabled: (key) => key === "notes",
label: (key) => titles[key],
```

在缩放过的桌面上移动或调整 Mail 的大小。Notes 已锁定。Maximize 会设置 Mail 的盒子，Grow 会从右下角把它放大。

有两种用代码更改盒子的方式：

```ts
resize.resizeTo("mail", { x: 0, y: 0, width: 400, height: 240 })
resize.resizeBy("mail", "se", 40, 40)
```

`resizeBy` 会应用手柄的尺寸限制和禁用规则。`resizeTo` 直接写入提供的盒子，所以尺寸和权限由你自己校验。两者都会报告 `imperative`。

要渲染实时尺寸标签，就把草稿排除在 `live` 之外，并读取 `resize.box(state, key)`。它在拖动过程中返回草稿盒子，其他时候返回已提交的盒子。`dragging(state, key)` 返回活动的手柄。`label` 和 `message` 自定义播报，默认由 `resizeMessage` 提供。

## 把行滑到一旁
### 行背后的操作
`createSwipeActions` 一次只保持一行打开。把 `open` 初始化为 `SwipeOpen | null`，把 `swiping` 初始化为 `SwipeDraft | null`，两者都是 `null`：

```ts
const swipe = createSwipeActions(context, {
  key: "open",
  draft: "swiping",
})
```

每一行都有会移动的内容，覆盖在 `start` 或 `end` 一侧的操作之上。用 `bindRow(el, key)` 绑定行，用 `bindActions(el, rowKey, side)` 绑定每个操作组。从槽位返回这些清理函数。

把 `swiping` 放进 `live`。内容槽位把 transform 和实时属性结合起来：

```ts
attrs: () => ({ style: css({ transform: "translateX(var(--swipe-x, 0px))" }) }),
live: live((state, { api, key }) => api.swipe.contentAttrs(state, key)),
```

在行上调用 `swipe.pointerdown(event, key, el)` 和 `swipe.keydown(event, key)`。给它 `position: relative`、`overflow: hidden` 和 `touch-action: pan-y`。操作槽位用 `swipe.actionsAttrs(state, rowKey, side)` 让隐藏的操作变为不可交互（inert）。

向左滑动一条消息，露出 Delete。使用键盘时，聚焦一行并按 Left 到达它的操作，然后按 Escape 关闭。

滑动会等待横向移动，这样纵向滚动仍然可用。超过操作宽度的一半再松开，就会保持打开；快速轻扫可以更早地打开或关闭。操作的宽度来自你的布局。

`start` 操作会在朝行的末端滑动时出现，在英文中是从左到右。在从右到左的布局中方向相反。`contentAttrs` 提供 `--swipe-x`、`data-swipe` 和 `data-swiping`，因此你可以在指针移动时禁用过渡。

### 完整滑动
加上 `onFullSwipe`，在用户滑动得足够远时执行操作。回调会完成实际工作；辅助函数不会替你点击操作按钮：

```ts
onFullSwipe: (key, side) => {
  context.options().onAction?.(key, side)
  return true
},
fullSwipe: () => 0.5,
disabled: (key) => key === context.options().pinned,
```

返回操作是否被接受。`fullSwipe` 是行宽的一个比例，默认 0.6。当松开就会触发操作时，内容会获得 `data-full`。

向右滑动把消息标为已读，向左滑动将其归档。超过行宽的一半后，松开即可执行操作。固定的消息保持关闭；Peek 和 Close 用代码控制操作。

`swipe.show(key, "end", { focus: true })` 打开一行并聚焦它的第一个操作。`swipe.close({ focus: true })` 关闭它并把焦点送回行。省略 `focus` 就让焦点留在原处。`swipe.open()` 读取打开的行。

### 拖动关闭
一条 toast 或卡片被拖动得足够远时，会在松开时关闭。给 `scrubTo` 一个位于 0 的吸附点：在阈值之内，它的结果带有那个 `point`，所以 toast 会弹回；超过阈值后，就没有可返回的点。每次移动都询问一次，这样 toast 才能显示松开后会发生什么：

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

const keeps = { min: -width, max: width, step: 1, snap: { points: [0], threshold: width * 0.3 } }

onMove: ({ x }) => {
  moved = x - startX
  setOffset(moved)
  setDismissing(scrubTo(moved, keeps).point === undefined)
},
onEnd: () => (scrubTo(moved, keeps).point === undefined ? dismiss(Math.sign(moved)) : setOffset(0)),
```

给 `data-dismissing` 设置样式，让变更在松开之前就清楚可见，像 iOS 那样：这里 toast 背后的层会变红，并显示 “Release to dismiss”。拖回阈值以内就会恢复。为键盘在每条 toast 里保留一个 Dismiss 按钮。

把 toast 向侧面拖动：超过它宽度的三分之一后，背后的层会变红，松开就会关闭它。拖回来，或按 Escape，可以保留它。

## 按压并按住
### 按住确认
当一次按压持续超过 `delay`（默认 500 毫秒）时，`bindHold` 会运行 `onHold`。给它一个按钮，并保留它的清理函数：

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

const unbind = bindHold(button, {
  delay: 1500,
  onHold: () => deleteProject(),
})
```

它适用于鼠标、手指、触控笔，以及按钮获得焦点时的 Space 或 Enter。按压期间，按钮带有 `data-holding`；按住之后，再带有 `data-held`。`--hold-delay` 保存这个延迟，所以 CSS 可以在完全相同的时间内填充按钮：

```css
[data-holding] .fill {
  transform: scaleX(1);
  transition: transform var(--hold-delay) linear;
}
```

按住 Delete Project，直到它填满。过早松开则不会删除任何内容。使用键盘时，聚焦它并按住 Space。

按压结束后，`onEnd` 会带着 `held` 和 `canceled` 运行。在按住之前指针移动超过 `tolerance` 像素（默认 10）、手指开始滚动、按下 Escape，或焦点离开按钮或窗口时，按压会被取消。被取消的按压不会点击，Escape 也不会到达按钮周围的对话框或浮层。在按钮的标签或描述里说明它需要按住，就像这里的提示那样。

### 按住时重复
`bindRepeat` 在按钮被按下时步进一次，然后在按住期间持续步进，像步进器的按钮、滚动箭头或遥控器的音量键那样。告诉它一步要做什么：

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

const unbind = bindRepeat(button, {
  repeat: 80,
  onStep: () => zoomBy(5),
})
```

在 `delay` 之后（默认 400 毫秒），`onStep` 每隔 `repeat` 毫秒再次运行（默认 60），直到按压结束。从 `onStep` 返回 `false` 可以停止重复，比如到达边界时。`count` 表示这是本次按压的第几步，从 1 开始；按压结束后，`onEnd` 会收到总数。

你不需要点击处理函数。鼠标或按键在按下时就步进，随后的点击不会再次步进。手指或触控笔在抬起时步进，或者在按住之后步进，所以在按钮上开始的滚动永远不会步进。没有按压支撑的点击，比如屏幕阅读器发出的点击，会步进一次。

按一次 Zoom In 增加 5%。按住它，缩放会持续上升，直到你松开或达到 400%。按住时滑出按钮，它会等到你回来。

按住期间，只要指针离开按钮，重复就会等待，指针回来时再继续，就像滚动条的箭头那样。短按 Space 或 Enter 会步进一次；按住时，它们会以和指针相同的节奏重复，无论键盘重复按键有多快。传入 `keys: []` 把按键交给浏览器，它发送的每次点击都会步进一次。松开、浏览器取消、Escape，或焦点离开按钮或窗口，都会结束这次按压。

`bindRepeat` 构建在 `bindHold` 之上，所以按钮在按压期间带有 `data-holding`，开始重复后带有 `data-held`。`bindHold` 也接受 `repeat`，用于那种要等到按压被按住之后才第一次运行的操作。

按压开始时，`onPress` 会运行，`input` 会被设为 `mouse`、`touch`、`pen` 或 `keyboard`。返回 `false` 可以忽略它，比如一个只在触摸时长按打开的上下文菜单区域，因为鼠标有右键。传入 `disabled` 可以拒绝按压，并阻止按住重复。当手指或触控笔按压时，浏览器自带的长按菜单和 iOS 的 callout 会保持关闭。清理函数会停止正在进行的按压，但不调用 `onEnd`。

## 二维值
### 面板上的一个点
`createArea` 把一个表面映射为两个值。从状态里读取这个点，并把每次变更写回去：

```ts
const area = createArea(context, {
  value: (state) => ({ x: state.mix.warmth, y: state.mix.energy }),
  set: (value, details) =>
    change("mix", { warmth: value.x, energy: value.y }, details),
  x: () => ({ min: 0, max: 100, step: 1, label: "Warmth" }),
  y: () => ({ min: 0, max: 100, step: 1, label: "Energy" }),
})
```

表面负责开始指针跟踪；滑块手柄提供键盘控制和滑块属性：

```ts
pad: slot({
  on: { pointerdown: (event, { el, api }) => api.area.pointerdown(event, el!) },
}),
thumb: slot({
  attrs: (state, { api }) => ({ ...api.area.thumbAttrs(state), style: api.area.thumbStyle(state) }),
  on: { keydown: (event, { api }) => api.area.keydown(event) },
}),
```

让表面定位，并设置 `touch-action: none`。滑块手柄的位置相对于它。和移动草稿不同，这个选择器在整个手势期间都会调用 `set`，使用滑块报告的原因：按压时是 `track-press`，移动时是 `drag`，按键时是 `step-key`。

在面板上点击或拖动来改变 warmth 和 energy。聚焦滑块手柄并使用方向键，加 Shift 可以走更大的步长。

每个轴默认是 0–1，步长为 0.01。y 轴从下到上，x 跟随文字方向。方向键移动一步，Shift 移动十步，Page Up 和 Page Down 把 y 移动其范围的十分之一，Home 和 End 则到达 x 的两端。

`thumbAttrs` 暴露一个滑块，其值文本描述两个轴。`thumbStyle` 设置它的百分比位置以及 `--area-x` 和 `--area-y` 的比例。

### 播报什么，以及何时落定
用 `valueText` 提供可读的描述，用 `onCommit` 做应当等到手势结束才执行的工作：

```ts
valueText: ({ x, y }) => `${x}% saturation, ${y}% brightness`,
onCommit: (value) => context.options().onColorCommit?.(value),
disabled: () => context.store.get().locked,
```

拖动来调整饱和度和亮度。色块会立即跟随；保存的值会在松开后或键盘变更后记录到控制台。Lock 会禁用选择器，Reset 用代码设置它的值。

`onCommit` 在指针跟踪结束时或键盘变更成功后运行。`disabled` 阻止用户输入，并把滑块手柄从 Tab 顺序中移除。

`area.set({ x: 60, y: 80 })` 会以 `imperative` 原因吸附并钳制一个程序化值。它在禁用时仍然有效，也不会调用 `onCommit`。`area.fractions(state)` 给出每个值在其轴内的位置，对渐变或色块很有用。

## 轨道上的范围
### 时间轴上的预订
一个 `Span` 有 `id`、`track`，以及以你的单位表示的 `start` 和 `end` 值。对于会议室预订，这些单位可以是从午夜起算的分钟数。把预订保存在数组里，并另起一个 `SpansDraft<Booking> | null` 字段，初始值为 `null`：

```ts
type Booking = Span & { title: string }
type RoomsState = { bookings: Booking[]; draft: SpansDraft<Booking> | null }

let booked = 0
const spans = createSpans<RoomsState, Booking>(context, {
  key: "bookings",
  draft: "draft",
  set: (value, details) => change("bookings", value, details),
  axis: "x",
  min: () => 9 * 60,
  max: () => 17 * 60,
  step: () => 30,
  overlap: false,
  create: (span) => ({ ...span, id: `booking-${++booked}`, title: "New" }),
})
```

渲染 `spans.spans(state)`，这样拖动期间会显示草稿。放下时会把数组提交一次，详情里带有受影响的 `id` 和 `action`。

用 `bindTrack(el, key)` 绑定轨道，用 `bindSpan(el, id)` 绑定预订。轨道上的按压调用 `trackPointerdown(event, key)`；预订上的按压调用 `spanPointerdown(event, id)`。给预订内部的调整大小手柄加上 `data-span-edge="start"` 或 `"end"`。

在空白处拖动来预订房间。拖动预订可以移动它，拖动它的末端可以调整大小。值会吸附到半小时，预订之间不能重叠。

用 `spanStyle(booking)` 定位预订，用 `spanAttrs(state, id)` 获取 `data-span-id` 以及绘制、拖动或调整大小的状态。能否获得焦点以及无障碍名称由你自己提供；`label(booking)` 提供播报中使用的名称。给轨道和可拖动的范围设置 `touch-action: none`。

在预订上调用 `keydown(event, id)`。沿轨道的方向键移动它；配合 Shift 时移动它的末端。跨轨道的方向键更换房间，Delete 或 Backspace 删除它。每次按键都会立即提交。

`create` 提供新预订的 ID 和数据。没有它时，空轨道不会创建预订。`overlap: false` 会拒绝与同一轨道上另一个范围重叠的提议范围。

### 向下排列的日期
轨道默认纵向排列。为日历加上持续时间限制、点击持续时间和显式的轨道顺序：

```ts
minSize: () => 60,
maxSize: () => 180,
size: () => 60,
tracks: () => ["Mon", "Tue", "Wed"],
createAutoScroll: { edge: 32 },
```

在一天里向下拖动来绘制事件，或点击创建一小时的事件。在一到三小时之间移动或调整事件大小。拖动时把指针保持在顶部或底部附近即可滚动。

`minSize` 和 `maxSize` 限制持续时间；`size` 决定点击创建什么。`tracks` 控制键盘跨日期行进的顺序。自动滚动接受[与其他拖动相同的选项](https://ui-sdk.cn/docs/core/behaviors/drag-and-drop#scrolling-while-dragging)。

允许重叠时，给每个事件一条泳道，让它们共享一天的宽度：

```ts
const lanes = stackSpans(plans.filter((other) => other.track === plan.track))
const style = spans.spanStyle(plan, lanes.get(plan.id))
```

`spansOn(state, track)` 读取一条轨道上的范围。`valueAt(track, x, y)` 把指针位置转换成该轨道范围内的值，并吸附到 `step`。`action(state, id)` 报告当前活动的指针动作。

### 用代码更改范围
对于表单字段或操作按钮，使用 `update` 和 `remove`：

```ts
spans.update("standup", { start: booking.start + 30, end: booking.end + 30 })
spans.update("standup", { end: booking.end + 30 })
spans.remove("standup")
```

`update` 会应用范围和重叠规则。这些方法会报告 `imperative`；它们不检查 `disabled`，后者只适用于指针和键盘输入。`isSpanFree(bookings, proposed)` 检查提议的预订是否与它所在轨道上的另一个预订重叠。

用按钮移动、延长或删除 Standup。Book noon 会检查房间是否空闲。board meeting 已锁定，拖动期间离开窗口会取消拖动。

`spans.cancel()` 结束拖动但不提交。如果你在窗口失去焦点时取消，就在原语销毁时移除那个监听器：

```ts
window.addEventListener("blur", spans.cancel)
context.onDestroy(() => window.removeEventListener("blur", spans.cancel))
```

`message` 自定义播报，默认由 `spansMessage` 提供。当你的轨道不需要边缘滚动时，设置 `createAutoScroll: false`。

## 预览
### 按压并滑动
预览让人在选定之前先试用一个值。把一个 `string | null` 的预览放在已选值旁边，并渲染 `preview ?? value`：

```ts
const preview = createPreview(context, {
  key: "preview",
  slot: "font",
  value: () => context.store.get().value,
  choose: (key, details) => change("value", key, details),
})
```

预览直接写入它的状态字段。如果它还需要经过变更回调，就加上 `set`。

保留字体槽位已有的游走焦点绑定，并加上这些处理函数：

```ts
on: {
  pointerdown: (event, { el, api, key }) => api.preview.pointerdown(event, key, el!.parentElement!),
  keydown: (event, { el, api, key }) => {
    if (api.preview.keydown(event, key)) {
      return
    }
    const moved = api.roving.keydown(event, el!)
    if (moved) {
      api.preview.show(moved.key, { reason: "list-navigation", event })
    }
  },
},
```

按下一个字体，然后滑过其他字体来预览它们。在其中一个上松开即可选定，在外面松开则取消。使用键盘时，方向键预览，Enter 或 Space 选定。

把共同的父级表面传给 `pointerdown`，以便跨选项跟踪手势。`show(key)` 预览一个，`choose(key)` 提交它，`clear()` 回到已选的值。Enter 和 Space 选定；Escape 清除。

当焦点离开这一组时清除预览，除非指针仍在滑动：

```ts
focusout: (event, { el, api }) => {
  if (api.preview.dragging() || el?.contains(event.relatedTarget as Node)) {
    return
  }
  api.preview.clear({ reason: "focus-out", event })
},
```

按压并滑动也可以试用一种顺序。在按压开始时测量每个标签页，并把被拖动标签页可能占据的每个槽位的左边缘设为一个吸附点。`scrubTo` 会在标签页靠近时把它拉进槽位，最近的槽位显示它将形成的顺序，松开就保留它：

```ts
const slots = lefts([...others, key], widths)

onMove: ({ x, event }) => {
  const { value: left } = scrubTo(start + x, { min: 0, max: slots.at(-1), step: 1, snap: { points: slots, threshold: 12 } }, {
    snap: !event.metaKey,
  })
  preview(insert(others, key, nearest(slots, left)), left)
},
```

对于键盘，`stepFromKey` 和 `stepBy` 把聚焦的标签页移动一个位置，或用 Home 和 End 移到任意一端，方式和滑块步进一样。

沿标签栏拖动一个标签页：它靠近每个位置时会吸附进去，其他标签页会让出空间。按住 Command 或 Ctrl 可以自由放置，或按 Escape 取消。使用键盘时，Option 或 Alt 加方向键移动聚焦的标签页。

### 悬停，以及播报什么
对于悬停预览，在进入和离开时使用 `show` 和 `clear`，然后在点击时使用 `choose`：

```ts
pointerenter: (event, { api, key }) => api.preview.show(key, { reason: "item-hover", event }),
pointerleave: (event, { api }) => api.preview.clear({ reason: "item-hover", event }),
click: (event, { api, key }) => api.preview.choose(key, { event }),
```

悬停在一个主题上试用它，点击即可保留。方向键也可以预览；Enter 选定，Escape 清除。Contrast 已禁用。

`disabled(key)` 阻止预览或选定选项。`label(key)` 和 `message(label)` 为原因为 `list-navigation` 的预览自定义播报；指针预览不会在每次经过选项时都播报。

## API 参考
选项表格会链接回介绍它们的示例。

- `key` (`keyof State & string`): The state key that holds every item's position, a `Record<string, MovePoint>`. Example: [Place Anything](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#place-anything).
- `draft` (`keyof State & string`): The state key that holds the `MoveDraft` while a pointer drags. Start it at `null`, and list it in `live`. Example: [Place Anything](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#place-anything).
- `set` (`(value: Record<string, MovePoint>, details: { reason: MoveReason; event?: Event; }) => boolean`): Asks for new positions and returns whether they went through. Pass the primitive's change: `set: (value, details) => change("positions", value, details)`. Example: [Place Anything](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#place-anything).
- `group?` (`((key: string) => string[])`): The keys that move together with the one pressed, like the selection when it holds it. Defaults to that one key. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once).
- `step?` (`(() => number)`): The grid a dropped position lands on, and how far Alt with an arrow nudges. Defaults to 1. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once).
- `largeStep?` (`(() => number)`): How far Alt with Shift and an arrow nudges. Defaults to ten steps. Example: [Place Anything](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#place-anything).
- `scale?` (`(() => number)`): How many screen pixels one unit of position takes, like a canvas's zoom, so a drag follows the pointer when the items are scaled. Defaults to 1. Example: [Zoom and Moving from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#zoom-and-moving-from-code).
- `bounds?` (`((key: string) => { minX: number; minY: number; maxX: number; maxY: number; } | undefined)`): Keeps positions inside a box, like the board's size minus a card's. Example: [Place Anything](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#place-anything).
- `disabled?` (`((key: string) => boolean)`): Whether an item can't be moved. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once).
- `label?` (`((key: string) => string | undefined)`): The name screen readers hear for an item. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once).
- `message?` (`((message: MoveMessage) => string)`): The text screen readers hear after a move. Defaults to English. Example: [Several at Once](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-at-once).

- `boxes` (`(state: State) => Record<string, ResizeBox>`): Every box in state, by key, like `(state) => state.boxes` or `(state) => ({ crop: state.crop })`. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `draft` (`keyof State & string`): The state key that holds the `ResizeDraft` while a pointer drags. Start it at `null`, and list it in `live`. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `set` (`(value: Record<string, ResizeBox>, details: { reason: ResizeReason; event?: Event; }) => boolean`): Asks for new boxes and returns whether they went through. Pass the primitive's change: `set: (value, details) => change("boxes", value, details)`, or `change("crop", value.crop, details)` for a primitive with one box. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `min?` (`((key: string) => { width: number; height: number; })`): The smallest a box gets. Defaults to 1 by 1. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `max?` (`((key: string) => { width: number; height: number; } | undefined)`): The largest a box gets. Example: [Keeping a Shape](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#keeping-a-shape).
- `bounds?` (`((key: string) => { left: number; top: number; right: number; bottom: number; } | undefined)`): Keeps a box inside an area, like the image a crop sits on. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `aspect?` (`((key: string) => number | undefined)`): Keeps width over height at this ratio, like `16 / 9`. Without one, Shift on a corner keeps the ratio the box had when the drag started. Example: [Keeping a Shape](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#keeping-a-shape).
- `step?` (`(() => number)`): The grid a dropped box lands on, and how far an arrow moves an edge. Defaults to 1. Example: [Handles on a Box](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#handles-on-a-box).
- `largeStep?` (`(() => number)`): How far Shift with an arrow moves an edge. Defaults to ten steps. Example: [Keeping a Shape](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#keeping-a-shape).
- `scale?` (`(() => number)`): How many screen pixels one unit takes, like a canvas's zoom. Defaults to 1. Example: [Several Boxes, and from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-boxes-and-from-code).
- `disabled?` (`((key: string) => boolean)`): Whether a box can't be changed. Example: [Several Boxes, and from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-boxes-and-from-code).
- `label?` (`((key: string) => string | undefined)`): The name screen readers hear for a box. Example: [Several Boxes, and from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-boxes-and-from-code).
- `message?` (`((message: ResizeMessage) => string)`): The text screen readers hear after a change. Defaults to English. Example: [Several Boxes, and from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#several-boxes-and-from-code).

- `key` (`keyof State & string`): The state key that holds the `SwipeOpen` row, or `null`. Example: [Actions Behind a Row](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#actions-behind-a-row).
- `draft` (`keyof State & string`): The state key that holds the `SwipeDraft` while a pointer swipes. Start it at `null`, and list it in `live`. Example: [Actions Behind a Row](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#actions-behind-a-row).
- `onFullSwipe?` (`((key: string, side: SwipeSide, details: { event: Event; }) => boolean)`): Runs a side's first action when a swipe goes past `fullSwipe` of the row's width, and returns whether it did. Without it, a long swipe only opens the row. Example: [Full Swipes](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#full-swipes).
- `fullSwipe?` (`(() => number)`): How far across the row a swipe runs the first action, as a fraction of its width. Example: [Full Swipes](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#full-swipes).
- `disabled?` (`((key: string) => boolean)`): Whether a row can't be swiped. Example: [Full Swipes](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#full-swipes).

- `delay?` (`number`): How long a press lasts before it's held, in milliseconds. Example: [Hold to Confirm](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hold-to-confirm).
- `repeat?` (`number`): Runs `onHold` again this often while held, in milliseconds, like a stepper's button. Without it, `onHold` runs once. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `tolerance?` (`number`): How far a pointer can move before it's held, in pixels, before the press is canceled, like when a finger starts to scroll. Example: [Hold to Confirm](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hold-to-confirm).
- `keys?` (`string[]`): The keys that press it while it has focus. A short press clicks it, as a pointer's does. An empty list leaves keys alone. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `disabled?` (`(() => boolean)`): Whether a press can't start, and a held one stops repeating. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onPress?` (`((details: HoldDetails) => boolean | void)`): Runs as a press starts. Return `false` to ignore it, like a mouse press where only touch holds. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onHold?` (`((details: HoldDetails & { count: number; }) => boolean | void)`): Runs once the press is held, then every `repeat` milliseconds. Return `false` to stop repeating, like at a bound; the press goes on until it ends. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onEnd?` (`((details: HoldEndDetails) => void)`): Runs once when the press ends, released or canceled. Example: [Hold to Confirm](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hold-to-confirm).

- `delay?` (`number`): How long a press lasts before it starts repeating, in milliseconds. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `repeat?` (`number`): How often it steps again while held, in milliseconds. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `keys?` (`string[]`): The keys that press it while it has focus. An empty list leaves keys to the browser, which clicks a button once per key press. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `disabled?` (`(() => boolean)`): Whether a press can't start, and a held one stops repeating. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onPress?` (`((details: HoldDetails) => boolean | void)`): Runs as a press starts. Return `false` to ignore it. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onStep?` (`((details: RepeatDetails) => boolean | void)`): Runs once for each press, then every `repeat` milliseconds while it's held. Return `false` to stop repeating, like at a bound. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).
- `onEnd?` (`((details: RepeatEndDetails) => void)`): Runs once when a press ends, released or canceled, and after a click's step. Example: [Repeat While Held](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#repeat-while-held).

- `value` (`(state: State) => AreaValue`): Reads the point from state, like `(state) => state.value`, or one made from other state, like a color's saturation and brightness. Example: [A Point on a Pad](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#a-point-on-a-pad).
- `set` (`(value: AreaValue, details: { reason: AreaReason; event?: Event; }) => boolean`): Asks for a new value and returns whether it went through. Pass the primitive's change: `set: (value, details) => change("value", value, details)`. Example: [A Point on a Pad](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#a-point-on-a-pad).
- `x?` (`(() => AreaAxis)`): The x axis, left to right. Example: [A Point on a Pad](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#a-point-on-a-pad).
- `y?` (`(() => AreaAxis)`): The y axis, bottom to top, like a chart: a higher value sits higher. Example: [A Point on a Pad](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#a-point-on-a-pad).
- `valueText?` (`((value: AreaValue) => string)`): The text screen readers hear for the value. Defaults to each axis's label and percentage. Example: [What's Read Out, and When It Settles](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#whats-read-out-and-when-it-settles).
- `onCommit?` (`((value: AreaValue, details: { reason: AreaReason; event?: Event; }) => void)`): Runs when a press or a drag ends, or a key changed the value, with the value it ended on, like Slider's `onValueCommit`. Example: [What's Read Out, and When It Settles](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#whats-read-out-and-when-it-settles).
- `disabled?` (`(() => boolean)`): Whether it can't change. Example: [What's Read Out, and When It Settles](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#whats-read-out-and-when-it-settles).

- `key` (`keyof State & string`): The state key that holds the spans, an array of `Span`. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `draft` (`keyof State & string`): The state key that holds the `SpansDraft` while a pointer drags. Start it at `null`. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `set` (`(value: S[], details: { reason: SpansReason; event?: Event; id: string; action: SpanAction; }) => boolean`): Asks for the new spans and returns whether they went through. Pass the primitive's change: `set: (value, details) => change("spans", value, details)`. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `min?` (`(() => number)`): Where tracks start, in their units. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `max?` (`(() => number)`): Where tracks end. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `step?` (`(() => number)`): What every start and end snaps to, and what arrows move by. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `minSize?` (`(() => number)`): The shortest a span can be. Example: [Days That Run Down](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down).
- `maxSize?` (`(() => number)`): The longest a span can be. Example: [Days That Run Down](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down).
- `axis?` (`"x" | "y"`): The direction tracks run: `y` down, like a calendar's days, or `x` across, like a Gantt chart's rows. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `tracks?` (`(() => string[])`): The tracks in the order the arrows across them go through. Defaults to the bound tracks in document order. Example: [Days That Run Down](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down).
- `overlap?` (`boolean`): Whether spans on one track can overlap. When they can't, a drag stops where it would. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `create?` (`((span: Span) => S | null)`): Makes the span a press on a track starts to draw, with a new `id` and anything else it needs, like a title, or returns `null` to not draw. Runs on every press on an empty stretch of track. Without it, nothing is drawn. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `size?` (`(() => number | undefined)`): How long a span a click on an empty track makes. Without it, a click makes none. Example: [Days That Run Down](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down).
- `disabled?` (`((span: S) => boolean)`): Whether a span can't change. Example: [Changing Ranges from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#changing-ranges-from-code).
- `label?` (`((span: S) => string)`): What screen readers call a span, like `"Standup, Tuesday 9:00 to 9:30"`. Defaults to its track and range. Example: [Bookings on a Timeline](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#bookings-on-a-timeline).
- `message?` (`((message: SpansMessage<S>) => string)`): The text screen readers hear for each change. Defaults to English. Example: [Changing Ranges from Code](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#changing-ranges-from-code).
- `createAutoScroll?` (`false | Omit<AutoScrollOptions, "ignore" | "onScroll">`): How a drag near a scroller's edge scrolls it, or `false` not to. Example: [Days That Run Down](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#days-that-run-down).

- `key` (`keyof State & string`): The state key that holds the previewed option's key, or `null`. Example: [Press and Slide](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#press-and-slide).
- `slot` (`string`): The slot whose parts are the options. Example: [Press and Slide](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#press-and-slide).
- `set?` (`((value: string | null, details: { reason: PreviewReason; event?: Event; }) => boolean)`): Asks for a new preview. Defaults to setting the state key; pass the primitive's change to fire `onPreviewChange`. Example: [Press and Slide](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#press-and-slide).
- `choose` (`(key: string, details: { reason: "item-press"; event?: Event; }) => boolean`): Chooses an option. Pass the primitive's change for its value. Example: [Press and Slide](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#press-and-slide).
- `value?` (`(() => string | null)`): The chosen option now, which previews as nothing. Example: [Press and Slide](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#press-and-slide).
- `disabled?` (`((key: string) => boolean)`): Whether an option can't be previewed or chosen. Example: [Hovering, and What's Read Out](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hovering-and-whats-read-out).
- `label?` (`((key: string) => string)`): An option's name for screen readers. Defaults to its key. Example: [Hovering, and What's Read Out](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hovering-and-whats-read-out).
- `message?` (`((label: string) => string)`): What screen readers hear when the keyboard previews one. Defaults to English. Example: [Hovering, and What's Read Out](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#hovering-and-whats-read-out).


# 列表

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

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


# 树

处理嵌套数据，显示展开的分支，并计算勾选状态。

用这些辅助函数查找父节点和子节点、找出可见的行，并计算整棵树上的勾选状态。

它们处理的是普通数据，所以可以用在组件里、服务器上，或者测试中。

## 树的形状
### 层级与位置
给 `createTreeCollection` 一个节点列表，父节点排在子节点之前，同级节点按显示顺序排列：

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

const outline = createTreeCollection([
  { key: "basics", parent: null },
  { key: "setup", parent: "basics" },
  { key: "hello", parent: "basics" },
  { key: "extras", parent: null, branch: true },
])

outline.parent("hello") // "basics".
outline.level("hello") // 2.
outline.position("hello") // { index: 2, size: 2 }.
```

`level` 和 `position` 从 1 开始计数，与 `aria-level`、`aria-posinset` 和 `aria-setsize` 一致。有子节点的节点是分支。空文件夹，或者稍后才加载子节点的文件夹，用 `branch: true`。

读一读每一节旁边的层级和位置。Setup 和 Hello 是 Basics 下的同级节点；Extras 是还没有加载子节点的分支。

`outline.size` 统计节点数量，`has(key)` 检查某个节点是否存在，`isBranch(key)` 判断是否为分支。父节点不在集合里的节点会被当作顶层节点。

### 展开与收起的分支
把展开的分支键保存在你自己的状态里。`visible` 返回祖先都展开的那些键：

```ts
outline.visible([]) // ["basics", "extras"].
outline.visible(["basics"]) // ["basics", "setup", "hello", "extras"].
```

对于同一个展开数组，它会复用结果。展开的分支变化时，替换这个数组。

展开 lib，然后选择 date.ts；控制台会记录它的路径。收起 src 可以隐藏它的后代，或者用 Expand All 显示所有文件夹。

用 `children(key)` 获取直接子节点，用 `children(null)` 获取顶层节点。`descendants(key)` 包含一个节点下面的所有内容；`ancestors(key)` 返回从最外层父节点向内到它的路径。`keys()` 按树的顺序列出整个集合。

### 树数据与文件路径
如果你的数据已经是嵌套的，`treeDataNodes` 会把它转换成集合节点：

```ts
import { createTreeCollection, treeDataNodes } from "@ui-sdk/core"

const items = [
  {
    value: "src",
    label: "src",
    children: [{ value: "index", label: "index.ts" }],
  },
]
const tree = createTreeCollection(treeDataNodes(items))
```

每个节点保留原始的 `item`。带 `children` 的条目是分支，即使是空数组也一样。叶子节点则省略 `children`。

对于文件路径，`treeFromPaths` 会替你构建嵌套数据：

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

const items = treeFromPaths([
  "src/index.ts",
  "src/lib/util.ts",
  "README.md",
  "assets/",
])
```

编辑路径，每行一个。文件夹显示在文件之前；加上末尾的斜杠可以创建一个空文件夹。

### 扁平行
你可以把嵌套数据渲染成扁平列表。`visibleTreeRows` 返回每个可见条目及其父节点、层级和行索引：

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

const rows = visibleTreeRows(items, ["src"])
```

`level` 从 1 开始；`index` 从 0 开始。用它们来缩进行，或者接入[虚拟化列表](https://ui-sdk.cn/docs/core/behaviors/lists#long-lists)。

展开 Guides 显示它的行。标签显示每一行的索引和父节点；Old setup 仍然不可用。

辅助函数提供数据。怎么处理数据由你的渲染器决定：这个演示把带 `href` 的条目渲染成链接，把不可用的条目渲染成不可交互的行。在树组件里，禁用的条目仍然可以获得焦点，但选择和激活会被阻止。

### 数据字段
- `value` (`string`): Identifies the item. Unique in the tree. Example: [Tree Data and File Paths](https://ui-sdk.cn/docs/core/behaviors/trees#tree-data-and-file-paths).
- `label` (`string`): What it shows, and what typeahead matches. Example: [Tree Data and File Paths](https://ui-sdk.cn/docs/core/behaviors/trees#tree-data-and-file-paths).
- `children?` (`TreeItemData[]`): Its children. Leave it out for a leaf. An empty array is a branch with no children, or one whose children load when it opens. Example: [Tree Data and File Paths](https://ui-sdk.cn/docs/core/behaviors/trees#tree-data-and-file-paths).
- `disabled?` (`boolean`): Whether it can't be selected, checked or activated. It can still take focus. Example: [Flat Rows](https://ui-sdk.cn/docs/core/behaviors/trees#flat-rows).
- `href?` (`string`): Makes the item a link to this address. Example: [Flat Rows](https://ui-sdk.cn/docs/core/behaviors/trees#flat-rows).

## 复选框
### 勾选分支
`treeCheckedStates` 计算每个节点是已勾选、未勾选还是混合状态。`toggleTreeChecked` 返回下一个勾选值：

```ts
import {
  createTreeCollection,
  toggleTreeChecked,
  treeCheckedStates,
} from "@ui-sdk/core"

const tree = createTreeCollection([
  { key: "fruit", parent: null },
  { key: "apple", parent: "fruit" },
  { key: "pear", parent: "fruit" },
])

const checked = treeCheckedStates(tree, ["apple"])
checked("fruit") // "indeterminate".
toggleTreeChecked(tree, ["apple"], "fruit") // ["apple", "pear"].
```

针对一个勾选值计算一次状态，然后用 `checked(key)` 读取每个节点。把 `"indeterminate"` 渲染为 `aria-checked="mixed"`。

勾选一个文件夹来勾选它的内容。取消勾选一个文件，让它的文件夹变成混合状态，然后切换策略，在控制台里比较这些值。

### 策略与锁定条目
策略决定勾选值如何表示：

| 策略            | 值                                                         |
| --------------- | ---------------------------------------------------------- |
| `"leaf"`        | 已勾选的叶子节点。这是默认值。                             |
| `"trunk"`       | 最外层完全勾选的节点，这样已勾选的文件夹可以代表它的内容。 |
| `"branch"`      | 每个完全勾选的节点，包括分支和叶子。                       |
| `"independent"` | 每个节点各自独立勾选，没有级联，也没有混合状态。           |

计算状态和切换节点时传入同一个策略：

```ts
const checked = treeCheckedStates(tree, value, "trunk")
const next = toggleTreeChecked(tree, value, "fruit", { strategy: "trunk" })
```

对于级联策略，值里的一个分支代表它的叶子节点。这样在改变策略或加载子节点之后，值仍然有意义。

勾选 Photos 选中它可编辑的文件，再按一次取消。逐个试试各种策略；锁定的文件始终保持未勾选。

要锁定节点，传入 `checkable`。被拒绝的节点保持原状态，被拒绝的分支会保护它的后代：

```ts
toggleTreeChecked(tree, value, key, {
  strategy,
  checkable: (node) => !locked.includes(node),
})
```

文件夹可能因为一个锁定的文件而保持混合状态。再次按压它时，如果可编辑的文件已经勾选，就取消勾选这些文件。

## 嵌套部件
嵌套条目的事件会冒泡经过它的父节点。父节点处理事件之前，先检查最近的树条目是不是它自己的元素：

```ts
const own = (el: HTMLElement | undefined, event?: Event) =>
  !el ||
  !(event?.target instanceof Element) ||
  event.target.closest('[role="treeitem"]') === el
```

在条目的处理函数里使用这个检查。例如：

```ts
press: ({ api, key, el }, event) => own(el, event) && api.press(key, event),
```

对于虚拟化的树，参见[未渲染的行](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered)，在条目出现时把焦点移过去。


# 过渡与手势

运行你的 CSS 过渡，在面板进出时让它们保持呈现直到结束，并把指针移动变成手势。

这里的过渡跟随状态。状态变化时，你的 CSS 过渡会运行，元素会留在页面里直到动画结束。偏好减少动态效果的人会直接看到终点。`bindPanel` 管理面板过渡，`animateIn` 和 `animateOut` 为 CSS 的进入和退出动画应用状态。

从 `@ui-sdk/core` 导入这些辅助函数。`@ui-sdk/core/gesture` 里的函数计算速度、弹簧运动、阻力和方向。这些计算如何用在输入处理函数和动画循环里，由你决定。

要把条目滑到新位置，请用 CSS、View Transitions 或动画库。

## 面板与呈现
### 打开与关闭
`bindPanel` 协调面板的高度、打开和关闭样式以及焦点。你的状态告诉它面板是打开的还是仍在退出：

```ts
present: (state, { key }) => state.expanded.includes(key) || state.exiting.includes(key),
```

让正在关闭的面板保持呈现，直到它的过渡结束。在它的 `bind` 里，把这些值连接到 `bindPanel`，并返回清理函数：

```ts
bind: (el, { api, key, store }) =>
  bindPanel(el, {
    size: (el, height) => el.style.setProperty("--panel-height", height),
    isOpen: () => store.get().expanded.includes(key),
    isExiting: () => store.get().exiting.includes(key),
    isFindable: () => false,
    opening: () => "animate",
    reveal: () => api.toggle(key),
    trigger: () => el.previousElementSibling as HTMLElement | undefined,
    subscribe: store.subscribe,
    settled: () => {},
    exited: () => store.set({ exiting: store.get().exiting.filter((item) => item !== key) }),
  }),
```

从 `@ui-sdk/core` 导入 `bindPanel`。这个例子里的触发器紧挨在面板前面。`exited` 从 `exiting` 中移除这个键，允许面板卸载。

打开一个问题，然后关闭它。答案保持挂载，同时它的高度过渡到零。

用它设置的属性来写过渡：

```css
[data-slot="faq-panel"] {
  height: var(--panel-height);
  overflow: hidden;
  transition: height 200ms ease-out;
}
[data-slot="faq-panel"][data-starting-style],
[data-slot="faq-panel"][data-ending-style] {
  height: 0;
}
@media (prefers-reduced-motion: reduce) {
  [data-slot="faq-panel"] {
    transition: none;
  }
}
```

过渡期间，`size` 收到测量出的高度，打开后收到 `auto`。如果焦点在正在关闭的面板里，`trigger()` 提供应当改为聚焦的元素。

### 在页面中查找与立即打开
关闭的面板可以用 `hidden="until-found"` 保持可搜索。让它保持挂载，并用 `hiddenAttrs` 控制它的可见性：

```ts
attrs: (state, { key }) => hiddenAttrs(state.expanded.includes(key), true),
```

从 `@ui-sdk/core` 导入 `hiddenAttrs`。在面板绑定里启用页面查找，并在 `reveal` 中打开匹配的小节：

```ts
isFindable: () => true,
reveal: () => api.show([key]),
opening: () => store.get().opening,
```

用浏览器的查找命令搜索 offline。在支持该功能的浏览器里，它收起的小节会打开。Open All 会立即显示其余小节。

`opening()` 对初始就打开的面板返回 `"mount"`；返回 `"instant"` 会跳过打开动画；也可以返回 `"animate"`。`settled(open)` 报告已完成的打开和关闭，包括即时变化，但初始的 `"mount"` 不会触发它。

### 单独使用页面查找
对于没有过渡的隐藏内容，把 `bindFindable` 与 `hiddenAttrs` 一起使用。它会在需要时恢复 `hidden="until-found"`，并在匹配时调用你的 `reveal` 回调：

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

const findable = bindFindable(el, {
  shown: () => store.get().shown,
  findable: () => true,
  reveal: () => api.show(),
})
const unsubscribe = store.subscribe(findable.check)
```

在槽位的 `bind` 里，返回一个同时调用 `unsubscribe()` 和 `findable()` 的清理函数。

在页面里搜索 simmer，在支持该功能的浏览器里显示隐藏的方法。Show Method 和 Hide Method 不依赖浏览器查找也能用。

`supportsHiddenUntilFound()` 告诉你浏览器是否支持这个功能。无论支持与否，都要提供一个可见的控件来显示内容。

### 进入与离开
对于只是出现和消失的元素，用 `animateIn` 和 `animateOut`：

```ts
import { animateIn, animateOut } from "@ui-sdk/core"

const stopEntering = animateIn(el)
```

当它该离开时，停止尚未完成的进入，开始退出。在完成回调里移除元素：

```ts
stopEntering()
const stopExiting = animateOut(el, () => removeToast(key))
```

按 Save 添加一条消息。按它的 Dismiss 按钮；淡出之后它会离开页面。

用 CSS 给 `data-starting-style` 和 `data-ending-style` 设置样式。退出会等待正在运行的动画，并带有超时，卡住的动画无法让元素永远挂载。两个辅助函数都返回清理函数；元素卸载时调用当前的清理函数。像面板示例那样，在 CSS 里加上减少动态效果的规则。

### 选项
- `size` (`(el: HTMLElement, height: string, width: string) => void`): Writes the panel's size variables, like `--accordion-panel-height`: the measured size while animating, `auto` once open and `0px` while closed. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).
- `isOpen` (`() => boolean`): Whether the panel is open now. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).
- `isExiting` (`() => boolean`): Whether a closed panel is still shown while it animates out. Keep the panel `present` while it is. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).
- `isFindable` (`() => boolean`): Whether a closed panel stays in the page, findable with `hidden="until-found"`. Example: [Find in Page, and Opening at Once](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-and-opening-at-once).
- `opening` (`() => "mount" | "instant" | "animate"`): How the panel opens: as it mounts with the page, at once, or animated. Example: [Find in Page, and Opening at Once](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-and-opening-at-once).
- `reveal` (`(event: Event) => void`): Find in page matched text in the closed panel. Open it here. Example: [Find in Page, and Opening at Once](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-and-opening-at-once).
- `trigger` (`() => HTMLElement`): Where focus goes when the panel closes with focus inside it, like its trigger. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).
- `subscribe` (`(listener: () => void) => () => void`): Runs `listener` when the panel's state may have changed, like `store.subscribe`. Returns the unsubscribe. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).
- `settled` (`(open: boolean) => void`): The open or close animation finished, or there was none. Never on mount. Example: [Find in Page, and Opening at Once](https://ui-sdk.cn/docs/core/behaviors/motion#find-in-page-and-opening-at-once).
- `exited` (`() => void`): The exit animation finished, so the panel can leave the page: stop counting it as exiting here. Example: [Open and Close](https://ui-sdk.cn/docs/core/behaviors/motion#open-and-close).

## 手势
`@ui-sdk/core/gesture` 里的函数帮助解读指针移动。输入、状态和动画帧仍由你的组件处理。

### 甩动与弹簧
指针移动时记录位置，然后在释放时读取速度：

```ts
import { createVelocityTracker, projectDistance } from "@ui-sdk/core/gesture"

const tracker = createVelocityTracker()
tracker.add(event.timeStamp, x)
```

`velocity(time)` 返回每毫秒的像素数。`projectDistance` 估算这个速度在物体减速的过程中能把它带多远：

```ts
const speed = tracker.velocity(release.timeStamp)
const target = x + projectDistance(speed, 0.994)
```

慢慢拖动风扇控件，然后快速甩一下。释放得越快，走得越远。Left 和 Right 也能改变速度。

要稳定到一个目标上，创建一个弹簧，并在每一帧读取它的位置：

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

const spring = solveSpring(0.4, 0.8, x - target, speed)
const position = target + spring.position(elapsedMilliseconds)
```

第一个参数是以秒为单位的响应时间。第二个是阻尼比：`1` 会平稳停下而不振荡；更低的值允许回弹。剩下的参数是初始位移和速度。`position(t)` 和 `velocity(t)` 接受经过的毫秒数。在动画循环里，判断弹簧是否已稳定之前，要同时检查位置和速度。

### 越过边缘
`rubberBand` 让拉动在越过边缘越远时阻力越大：

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

const offset = rubberBand(distancePastEdge, list.clientHeight)
```

把收件箱往下拉得足够远来刷新，然后释放。试试短距离拉动后停住再释放；它会回位而不刷新。按按钮也能刷新。

拉动越远，结果越接近传入的尺寸。每次手势开始时调用 `tracker.reset()`。`staleAfter` 让过旧的采样读作零，这样释放前停住不动就不会被当成一次新的甩动。

### 一笔指向哪个方向
`sectorOf` 把拖动方向变成一个带编号的扇区。分成四个扇区时，0 是上，然后是右、下、左：

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

const index = sectorOf(dx, dy, 4) // -1 near the center
```

从中心朝某个反应拖动并释放来选择它。短距离划动不会选中任何东西。也可以直接点击一个反应。

在 `deadZone` 内，`sectorOf` 返回 `-1`；默认是 18 像素。使用索引之前先检查这一点。传入以圈为单位的 `start` 偏移，可以旋转扇区。

### 选项
- `horizon?` (`number`): How far back samples count, in ms before the newest. Defaults to 70. Example: [Past an Edge](https://ui-sdk.cn/docs/core/behaviors/motion#past-an-edge).
- `staleAfter?` (`number`): How old the newest sample can be, in ms, before the pointer counts as stopped and reads 0. Defaults to 40. Example: [Past an Edge](https://ui-sdk.cn/docs/core/behaviors/motion#past-an-edge).
- `maxSpeed?` (`number`): The fastest the tracker reads, in px/ms either way. Defaults to 8. Example: [Past an Edge](https://ui-sdk.cn/docs/core/behaviors/motion#past-an-edge).
- `capacity?` (`number`): How many samples it keeps. Defaults to 20, enough for the horizon at 240 Hz. Example: [Past an Edge](https://ui-sdk.cn/docs/core/behaviors/motion#past-an-edge).


# 浮层与图层

构建浮层，组合现有的浮层，或者单独使用定位和关闭。

用 `createPopup` 管理你自己浮层的打开、关闭、定位和焦点。

你也可以把现有的 Popover、Dialog 或 Menu [组合](https://ui-sdk.cn/docs/core/behaviors/popups#compose-ours)进你的组件，或者单独使用[定位](https://ui-sdk.cn/docs/core/behaviors/popups#placing-a-popup)和[图层](https://ui-sdk.cn/docs/core/behaviors/popups#layers-of-your-own)。

## 自己构建
### 你自己的浮层
从一个邀请用的 popover 开始。`popupState` 提供它的状态，`createPopup` 提供它的行为，槽位构建器把它的部件连接起来：

```ts
import {
  createPopup,
  definePrimitive,
  popupClose,
  popupContent,
  popupState,
  popupTrigger,
} from "@ui-sdk/core"
import { popoverPreset } from "@ui-sdk/core/popover"

const invite = definePrimitive({
  name: "invite",
  options: { defaultOpen: "boolean" },
  state: (options: { defaultOpen?: boolean }) => popupState(options),
  api: (context) => createPopup(context, { preset: popoverPreset }),
  slots: (slot) => ({
    trigger: popupTrigger(slot),
    content: popupContent(slot),
    close: popupClose(slot),
  }),
})
```

用你所用框架的适配器渲染这些部件，就像[构建组件](/docs/core/build-a-component)那样。popover 预设提供触发器旁的放置、关闭和焦点处理：

按 Invite，然后用 Escape、外部按压或 Done 关闭它。Escape 和 Done 会把焦点还给 Invite。

`state.open` 告诉你浮层是否打开。`state.mounted` 在退出动画期间保持为 true。渲染你的浮层时，用内容构建器保留这个呈现行为。

默认槽位名是 `content` 和 `trigger`。如果你的名字不同，把 `slot` 和 `trigger` 传给 `createPopup`。

### 选择它的行为
换一个预设就换一种交互。例如，下面这个把浮层变成模态对话框：

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

api: (context) => createPopup(context, { preset: dialogPreset }),
```

打开 Filters，再打开 Rename，比较 Tab 的行为。悬停或聚焦 Help 打开 tooltip。

预设决定内容的 role、如何打开和关闭、是否定位在触发器旁边，以及是否为模态。我们的组件使用同样的预设，所以 `dialogPreset` 的行为和 [Dialog](/docs/components/dialog) 一样：没有标题的对话框会取触发器的名字，因为模态对话框会让页面不可交互（inert），触发器也不例外。

| 预设              | 导入来源                  | 用于                       |
| ----------------- | ------------------------- | -------------------------- |
| `popoverPreset`   | `@ui-sdk/core/popover`    | 触发器旁的交互内容         |
| `dialogPreset`    | `@ui-sdk/core/dialog`     | 保持焦点的模态任务         |
| `tooltipPreset`   | `@ui-sdk/core/tooltip`    | 悬停或聚焦时显示的简短标签 |
| `hoverCardPreset` | `@ui-sdk/core/hover-card` | 悬停或聚焦时显示的预览     |

`role` 选项可以覆盖预设的内容角色。单靠 role 并不会带来某个模式的行为；例如，确认框必须遵循 Alert Dialog 模式时，就用 [Alert Dialog](/docs/components/alert-dialog)。

### 它读取的选项
你的原语（primitive）可以在自己的选项之外暴露浮层选项。把需要的字段加到它的选项类型和 schema 里；`createPopup` 会替你读取它们。

例如，`dismissible: false` 让 Escape 和外部按压无法关闭有未保存内容的浮层。`onDismissAttempt` 告诉你别人为什么试图关闭它：

```tsx
<Cart
  dismissible={false}
  onDismissAttempt={(details) => setStatus(`Kept open: ${details.reason}`)}
>
  {children}
</Cart>
```

打开 Cart，关闭时留意原因。试试 Modal、Open on hover，以及取消勾选 Dismissible。Check Out 仍然会关闭购物车。

| 选项                                  | 它改变了什么                                                               |
| ------------------------------------- | -------------------------------------------------------------------------- |
| `open`, `defaultOpen`, `onOpenChange` | 控制打开状态或观察变化，原因如 `trigger-press` 和 `escape-key`。           |
| `modal`                               | 覆盖预设的模态设置。为 `true` 时，浮层打开期间外部页面不可交互。           |
| `openOnHover`, `delay`, `closeDelay`  | 给按压打开的浮层加上悬停打开，并以毫秒为单位设置打开和关闭的延迟。         |
| `dismissible`, `onDismissAttempt`     | 拒绝关闭，并得知尝试关闭的原因。触发器、Close 部件和控制器仍然可以关闭它。 |
| `disabled`                            | 阻止打开。                                                                 |

受控的 `open` 和其他状态使用同样的[变更与同步模式](https://ui-sdk.cn/docs/core/kernel/handle-changes#state-a-user-controls)。购物车的源码把这些字段放在一起展示。

### 一个浮层，多个触发器
多个触发器可以共享一个浮层。给每个触发器一个 `payload` 属性（props），比如它的卡片应当显示的那个人：

```tsx
<TeamCardTrigger payload={person}>{person.initials}</TeamCardTrigger>
```

内容以 `state.payload` 收到这个值。打开另一个触发器会更新payload，并把浮层移到它那里。`onPayloadChange` 报告这次变化。

打开一个人的卡片，然后按另一个头像。同一个浮层移到新的触发器，并显示那个人的详情。

加上 `popupTitle(slot)` 和 `popupDescription(slot)`，把可见的标题和描述连接到内容。`popupArrow(slot)` 添加一个箭头，它的 `data-side` 跟随放置位置。

### 所有部件，以及你自己的部件
`popupSlots(slot)` 一起给你标准部件：`trigger`、`content`、`title`、`description`、`close`、`arrow`、`backdrop` 和 `viewport`。

你可以在它们旁边再加一个槽位。这个链接预览添加了一张图片，只有在 payload 带有图片时才渲染：

```ts
slots: (slot) => ({
  ...popupSlots(slot),
  image: slot({
    present: (state) => !!(state.payload as LinkPreviewPage | undefined)?.image,
    attrs: (state) => ({
      src: (state.payload as LinkPreviewPage | undefined)?.image,
      alt: "",
    }),
  }),
}),
```

像之前一样，用同一套 `popupState` 和 `createPopup` 设置搭配 `hoverCardPreset`。在这个例子里，`LinkPreviewPage` 描述 payload 的标题、描述和可选图片：

悬停或聚焦 popup layer、focus 和 motion。预览跟随每个链接；motion 没有图片，所以它的图片部件不会渲染。

`backdrop` 部件位于模态浮层后面；按压它算作外部按压。`viewport` 为底部面板（sheet）提供全屏容器。只需要几个部件时用各自的构建器，需要整套时用 `popupSlots`。

### 创建选项
- `preset` (`PopupPreset`): The behavior, like `popoverPreset` or `hoverCardPreset`. Example: [A Popup of Your Own](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own).
- `slot?` (`string`): The slot that is the popup. Example: [A Popup of Your Own](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own).
- `trigger?` (`string`): The slot that opens it. Example: [A Popup of Your Own](https://ui-sdk.cn/docs/core/behaviors/popups#a-popup-of-your-own).
- `role?` (`"alertdialog" | "dialog" | "menu" | "tooltip"`): The content's role, like `"alertdialog"`. Example: [Pick Its Behavior](https://ui-sdk.cn/docs/core/behaviors/popups#pick-its-behavior).

## 组合现有的浮层
选择器可以自己持有选择，而由现有的 Popover 处理打开、放置和关闭。按你要显示的内容选择合适的组件：

| 你需要                   | 渲染                                                                             |
| ------------------------ | -------------------------------------------------------------------------------- |
| 触发器旁的交互内容       | [Popover](/docs/components/popover)                                              |
| 一组动作                 | [Menu](/docs/components/menu)                                                    |
| 模态任务或确认           | [Dialog](/docs/components/dialog)、[Alert Dialog](/docs/components/alert-dialog) |
| 从屏幕边缘出现的底部面板 | [Drawer](/docs/components/drawer)                                                |
| 悬停标签或预览           | [Tooltip](/docs/components/tooltip)、[Hover Card](/docs/components/hover-card)   |
| 从列表中选择             | [Select](/docs/components/select)、[Combobox](/docs/components/combobox)         |

### Popover 里的选择器
这个 emoji 选择器已经自己持有 `open`。它的 React 渲染器把这个状态传给 Popover，并把 Popover 的变更详情转发给选择器的 `setOpen` 方法：

```tsx
<Popover
  open={state.open}
  onOpenChange={(open, details) =>
    handle.api.setOpen(open, {
      reason: details.reason,
      event: details.event,
      source: details.source,
    })
  }
>
  {children}
</Popover>
```

转发 reason、event 和 source，能让这次变更对选择器的调用方仍然有意义。选一个 emoji 会用它自己的 `item-press` 原因关闭同一个状态。

打开 React，选择一个 emoji。选择器记录下这个反应，并关闭它的 Popover。

演示的代码标签页包含 React 渲染器。[自定义部件](/docs/react/custom-parts)涵盖渲染辅助函数，[Web Components 指南](https://ui-sdk.cn/docs/web-components/custom-parts#compose-a-popup)展示自定义元素里的连接方式。浮层的内容属性（props），比如 `initialFocus`，仍然照常工作。

## 从代码打开
浮层控制器让你可以在事件处理函数里打开浮层并等待结果。每个浮层都从它的 core 入口和框架适配器导出一个工厂函数，比如 `createPopoverController`。

### 打开、等待与关闭
创建一个控制器并传给浮层。这里的 payload 是一个点：

```tsx
import {
  createPopoverController,
  Popover,
  PopoverContent,
} from "@ui-sdk/react/popover"

const note = createPopoverController<{ x: number; y: number }>()

function Note() {
  return (
    <Popover controller={note}>
      <PopoverContent>Leave a note at this point.</PopoverContent>
    </Popover>
  )
}
```

在点击处理函数里，给 `open` 一个锚点（anchor）和 payload。锚点使用视口坐标；payload 可以是内容需要的任何数据：

```ts
const result = await note.open({
  anchor: { x: event.clientX, y: event.clientY },
  payload: { x: event.clientX, y: event.clientY },
})
```

内容从它的渲染状态里读取 payload。`open` 在浮层关闭时兑现，带着 `reason`、`source` 和可选的 `returnValue`。要从浮层里的按钮返回一个值：

```ts
note.close({ returnValue: "kept" })
```

点击卡片，在那个点打开一条便签。按 Keep 或 Escape，并读取结果。单独选择 Close，会在两秒后关闭。

给 `open` 传入 `signal: AbortSignal.timeout(2000)` 来实现定时关闭。中止会以 `imperative` 原因关闭；移除浮层的组件则会以 `unmount` 兑现。promise 只兑现一次，不会拒绝。

想用这种方式暴露你自己组件的 API，参见[控制器](https://ui-sdk.cn/docs/core/kernel/handle-changes#controllers)。

## 放置浮层
`position(anchor, element, options)` 把元素放在锚点旁边，监听移动，并在没有空间时翻转位置。它不会打开或关闭元素。

### 放在锚点旁边
锚点可以是一个元素、一个像 `{ x, y }` 这样的点，或者一个带 `getBoundingClientRect` 的对象，比如文本选区的 range。

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

const stop = position(anchor, popup, {
  side: "bottom",
  align: "start",
  sideOffset: 4,
})
```

元素消失时调用 `stop()`。在原语里，从槽位的 `bind` 返回清理函数：

```ts
card: slot({
  present: (state) => state.open,
  bind: (el, { store }) => position(() => store.get().anchor, el),
}),
```

getter 让锚点可以在元素保持挂载时变化。虚拟锚点的矩形每一帧都会检查，所以工具栏可以跟随变化的文本选区。

点击地图放一个图钉，然后用 Escape 或 Done 关闭它。聚焦地图并按 Enter，用键盘打开卡片。

这个演示把 `position` 和[图层](https://ui-sdk.cn/docs/core/behaviors/popups#layers-of-your-own)结合来处理关闭，并在打开和关闭时处理焦点。

### 方向、间距与箭头
直接传入放置选项，或者在它们可能于打开期间变化时从 getter 返回。箭头也可以是 getter，这样它可以在内容之后挂载：

```ts
bubble: slot({
  bind: (el, { api }) =>
    position(api.target, el, () => ({
      side: "top",
      align: "center",
      sideOffset: 8,
      arrow: () => api.arrow(),
      arrowPadding: 8,
    })),
}),
```

改变 Side、Align 和偏移量。当提示位于按钮上方时，向上滚动让按钮靠近窗口顶部，看提示翻到下方。

`data-side` 和 `data-align` 在浮层和箭头上报告最终的放置位置。用 `--available-width` 和 `--available-height` 约束内容，用 `--transform-origin` 作为它的动画原点。返回的清理函数还有一个 `place()` 方法，可以立即重新计算。

### 定位选项
- `side?` (`Side`): Which side of the anchor it opens on. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `align?` (`Align`): How it lines up with the anchor along that side. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `sideOffset?` (`number`): Gap between the anchor and the element, in pixels. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `arrow?` (`HTMLElement | (() => HTMLElement | null | undefined) | null`): An element inside that points at the anchor, like an arrow, placed along the edge facing it. A function is read on every check, so an arrow that mounts later is still found. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).
- `arrowPadding?` (`number`): Space to keep between the arrow and the corners, in pixels. Example: [Sides, Gaps and an Arrow](https://ui-sdk.cn/docs/core/behaviors/popups#sides-gaps-and-an-arrow).

## 你自己的图层
`bindLayer` 把元素注册到和 SDK 浮层相同的关闭栈里。当你构建的浮动界面有自己的形状和行为时用它，比如一圈动作按钮，或者选区上方的工具栏。

### 栈中的一个图层
在部件呈现时绑定图层，并返回清理函数。`contains` 让你把另一个元素（比如它的触发器）算作在图层内部：

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

panel: slot({
  present: (state) => state.open,
  bind: (el, { api }) =>
    bindLayer(el, {
      topLayer: true,
      contains: (target) => !!api.trigger()?.contains(target),
      onDismiss: () => api.close(),
    }),
}),
```

Escape 交给最上面的图层。嵌套的浮层算作在父级内部，所以在面板里的菜单上操作时，面板会保持打开：

打开 Share，再打开它的访问菜单。按一次 Escape 关闭菜单，再按一次关闭 Share。选择访问级别会让 Share 保持打开。

`onDismiss(reason, event)` 请求你的代码关闭图层。状态、role、焦点行为和放置位置仍然由你负责。`topLayer: true` 在浏览器支持时使用顶层（top layer），元素因此可以显示在会裁剪它的祖先之上。

### 模态图层，以及什么仍然可用
对 `bindLayer` 来说，`modal: true` 阻止外部按压到达下面的页面。`closeOnBlur` 要求它在窗口失去焦点时关闭：

```ts
bindLayer(el, {
  topLayer: true,
  modal: true,
  closeOnBlur: true,
  onDismiss: (reason) => api.close(reason),
})
```

这个图层选项处理外部按压。当你还需要模态焦点处理，并让页面其余部分不可交互时，就用 dialog 预设。

打开计时器，在 Modal 打开时按 Count，然后关掉 Modal。面板打开时试试 Pause：播放器仍然可用。切换窗口也会关闭面板。

`bindPersistentLayer` 让元素在多个图层之间保持可用，包括模态浮层。它很适合 toast 区域或播放器；在它内部按压不会关闭其他图层：

```ts
player: slot({ bind: (el) => bindPersistentLayer(el) }),
```

用 `isDismissal(reason)` 区分关闭操作（比如 Escape 或外部按压）和在你的界面里做出的选择：

```ts
onClose: (reason) => {
  setStatus(isDismissal(reason) ? "Dismissed" : "Closed")
},
```

### 图层选项
- `onDismiss` (`(reason: LayerDismissReason, event: Event) => void`): Runs when Escape, a press outside or the window losing focus asks the layer to close. Example: [A Layer in the Stack](https://ui-sdk.cn/docs/core/behaviors/popups#a-layer-in-the-stack).
- `contains?` (`((target: Node) => boolean)`): Other elements that count as inside, like the trigger that opened it. Example: [A Layer in the Stack](https://ui-sdk.cn/docs/core/behaviors/popups#a-layer-in-the-stack).
- `modal?` (`boolean`): Whether a press outside only closes the layer, without reaching the page beneath. Defaults to `false`. Example: [Modal Layers, and What Stays Usable](https://ui-sdk.cn/docs/core/behaviors/popups#modal-layers-and-what-stays-usable).
- `topLayer?` (`boolean`): Whether the element joins the browser's top layer. Defaults to `false`. Example: [A Layer in the Stack](https://ui-sdk.cn/docs/core/behaviors/popups#a-layer-in-the-stack).
- `closeOnBlur?` (`boolean`): Whether the window losing focus closes it, like a click into an iframe. Defaults to `false`. Example: [Modal Layers, and What Stays Usable](https://ui-sdk.cn/docs/core/behaviors/popups#modal-layers-and-what-stays-usable).

## 类型与顶层
SDK 浮层就地渲染，使用浏览器的顶层。浏览器不支持时，适配器改用传送到 body 的传送门（portal）。`container` 属性（props）让你显式选择容器。`supportsTopLayer()` 检查是否支持。

传给 `bindLayer` 的原始元素需要自己的放置位置和样式。在应用你的设计之前，重置浏览器默认的 popover `inset`、`margin`、`padding`、`border` 和 `background`。

### 浮层类型
把转发给浮层的放置属性（props）用 `PositionProps` 标注，元素或虚拟锚点用 `Anchor`。`Side` 和 `Align` 标注单个放置值；`PopupController` 描述浮层控制器工厂返回的方法。


# 偏好设置

定义肤色或密度等选择，保存它们，并让组件保持同步。

用 `createPreference` 在你的应用里共享一项用户偏好。偏好变化时，它让各组件保持同步，还能在多次访问之间保存这项偏好。

你可以用它处理主题，比如浅色或深色模式（见 [`createColorScheme`](https://ui-sdk.cn/docs/core/behaviors/preferences#choose-a-color-scheme)），也可以处理其他用户偏好，比如偏好的包管理器，或者侧边栏是否展开。

## 创建偏好
为偏好指定允许的取值、一个默认值和一个 `data-*` 属性。下面是一个肤色偏好：

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

const skinTone = createPreference({
  values: ["default", "light", "medium-light", "medium", "medium-dark", "dark"],
  defaultValue: "default",
  attribute: "data-skin-tone",
})

export { skinTone }
```

这个属性让 CSS 有办法使用所选的值。[应用偏好](https://ui-sdk.cn/docs/core/behaviors/preferences#apply-preferences) 介绍如何把它放到页面上。每个取值长什么样，由你决定。

### 读取和改变值
调用 `set` 改变选择，调用 `get` 读取它的状态：

```ts
skinTone.set("medium")
skinTone.get().value
```

设置 `"medium"` 之后，`get().value` 返回 `"medium"`。`set` 只接受允许列表里的值。值发生变化时它返回 `true`；值保持不变或变更被取消时返回 `false`。

### 响应变更
在偏好的选项里加上 `onValueChange`，就能收到提议的变更：

```ts
onValueChange: (value, details) => {
  console.log(value, details.reason)
},
```

它在值改变之前运行。详情里包含原因、事件和来源。如果你的应用需要保留当前值，就调用 `details.cancel()`。[处理变更](/docs/core/kernel/handle-changes) 介绍了这些详情。

### 跟随变更
值变化时，用 `subscribe` 更新框架组件之外的东西：

```ts
const stop = skinTone.subscribe(({ value }) => {
  console.log(value)
})
```

初始化时用 `get()` 读取当前状态。不再需要订阅时调用 `stop()`。在框架组件里，使用下面的[读取偏好](https://ui-sdk.cn/docs/core/behaviors/preferences#read-a-preference)。

## 记住选择
加上[存储](/docs/core/storage)，保存每次选择，并在下次访问时恢复它：

```ts
import { createLocalStorage, createPreference } from "@ui-sdk/core"

const skinTone = createPreference({
  values: ["default", "light", "medium-light", "medium", "medium-dark", "dark"],
  defaultValue: "default",
  attribute: "data-skin-tone",
  storage: createLocalStorage("skin-tone"),
})

export { skinTone }
```

这个演示使用 localStorage：

选择一种肤色，然后刷新页面。你的选择会被保存。

| 存储                   | 用途                                           |
| ---------------------- | ---------------------------------------------- |
| `createLocalStorage`   | 在多次访问之间保留、并在标签页之间共享的选择。 |
| `createSessionStorage` | 在标签页打开期间保留的选择。                   |
| `createCookieStorage`  | 服务器渲染内容时需要读取的选择。               |

订阅恢复出不同的已保存值时，`onValueChange` 会收到原因 `"restore"`。来自另一个存储实例或标签页的变更会报告 `"storage-sync"`。哪些标签页能共享同一个值，取决于所用的存储。

如果在服务器上渲染，就[在页面绘制之前应用已保存的偏好](https://ui-sdk.cn/docs/core/behaviors/preferences#show-a-preference-before-hydration)，让样式从一开始就使用保存的选择。

### 没有保存值时
如果没有已保存的值，偏好从 `defaultValue` 开始。保存的值不在允许的 `values` 里时，也会使用这个默认值。对肤色示例来说，就是 `"default"`。

### 无法保存时
浏览器可能阻止存储，或者存储空间耗尽。偏好仍会改变并更新它的订阅者，但新的选择可能在重新加载后丢失。

`skinTone.set(...)` 返回偏好是否发生了变化。如果你的界面需要告诉用户当前能否保存，就[检查存储](https://ui-sdk.cn/docs/core/storage#when-storage-is-unavailable)。

### 记住侧边栏的状态
再看一个例子。用 `createPreference` 记住侧边栏是展开还是收起。把 `sidebarPreference` 定义在单独的文件里：

```ts title="sidebar-preference.ts"
import { createLocalStorage, createPreference } from "@ui-sdk/core"

const sidebarPreference = createPreference({
  values: ["open", "closed"],
  defaultValue: "open",
  attribute: "data-sidebar",
  storage: createLocalStorage("sidebar-state"),
})

export { sidebarPreference }
```

然后在你的侧边栏组件里读取它：

**React**

```tsx title="sidebar.tsx"
import { usePreference } from "@ui-sdk/react/preferences"
import { sidebarPreference } from "./sidebar-preference"

function Sidebar() {
  const { value } = usePreference(sidebarPreference)

  return <aside hidden={value === "closed"}>Sidebar content</aside>
}

export { Sidebar }
```

**Vue**

```vue title="sidebar.vue"
<script setup lang="ts">
import { usePreference } from "@ui-sdk/vue/preferences"
import { sidebarPreference } from "./sidebar-preference"

const sidebar = usePreference(sidebarPreference)
</script>

<template>
  <aside :hidden="sidebar.value === 'closed'">Sidebar content</aside>
</template>
```

**Svelte**

```svelte title="sidebar.svelte"
<script lang="ts">
  import { usePreference } from "@ui-sdk/svelte/preferences"
  import { sidebarPreference } from "./sidebar-preference"

  const sidebar = usePreference(sidebarPreference)
</script>

<aside hidden={sidebar.current.value === "closed"}>Sidebar content</aside>
```

**Solid**

```tsx title="sidebar.tsx"
import { usePreference } from "@ui-sdk/solid/preferences"
import { sidebarPreference } from "./sidebar-preference"

function Sidebar() {
  const sidebar = usePreference(sidebarPreference)

  return <aside hidden={sidebar().value === "closed"}>Sidebar content</aside>
}

export { Sidebar }
```

**Web Components**

```ts title="sidebar.ts"
import { sidebarPreference } from "./sidebar-preference"

class AppSidebar extends HTMLElement {
  #stop?: () => void

  connectedCallback() {
    const update = () => {
      this.hidden = sidebarPreference.get().value === "closed"
    }

    this.#stop = sidebarPreference.subscribe(update)
    update()
  }

  disconnectedCallback() {
    this.#stop?.()
  }
}

customElements.define("app-sidebar", AppSidebar)
```

```html
<app-sidebar>
  <aside>Sidebar content</aside>
</app-sidebar>
```

在开关里调用 `sidebarPreference.set("closed")` 收起侧边栏，或调用 `sidebarPreference.set("open")` 展开它。偏好变化时组件会更新，选择也会保存下来供下次访问使用。

## 应用偏好
把偏好传给框架的 [`Preferences` 组件](/docs/components/preferences)，以应用它们的属性并让属性保持最新：

**React**

```tsx
import type * as React from "react"
import { Preferences } from "@ui-sdk/react/preferences"
import { skinTone } from "./preferences"

function App({ children }: { children: React.ReactNode }) {
  return <Preferences preferences={[skinTone]}>{children}</Preferences>
}

export { App }
```

**Vue**

```vue
<script setup lang="ts">
import { Preferences } from "@ui-sdk/vue/preferences"
import { skinTone } from "./preferences"
</script>

<template>
  <Preferences :preferences="[skinTone]">
    <RouterView />
  </Preferences>
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import { Preferences } from "@ui-sdk/svelte/preferences"
  import { skinTone } from "$lib/preferences"

  let { children } = $props()
</script>

<Preferences preferences={[skinTone]}>
  {@render children()}
</Preferences>
```

**Solid**

```tsx
import { Preferences } from "@ui-sdk/solid/preferences"
import type { JSX } from "@solidjs/web"
import { skinTone } from "./preferences"

function App(props: { children: JSX.Element }) {
  return <Preferences preferences={[skinTone]}>{props.children}</Preferences>
}
```

**Web Components**

```html
<ui-preferences>
  <main>…</main>
</ui-preferences>

<script type="module">
  import "@ui-sdk/web/preferences"
  import { skinTone } from "./preferences.js"

  document.querySelector("ui-preferences").preferences = [skinTone]
</script>
```

参见[服务端渲染](https://ui-sdk.cn/docs/core/behaviors/preferences#server-rendering)，在页面水合之前应用已保存的值。

### 作用于整个页面
在偏好上设置 `global: true`，再把它传给 `Preferences`。它的属性会加到 `<html>` 上，而不是包裹元素上。例如，密度设置可以作用于整个页面：

```ts
const density = createPreference({
  values: ["comfortable", "compact"],
  defaultValue: "comfortable",
  attribute: "data-density",
  global: true,
})
```

不加 `global` 时，属性留在它自己的 `Preferences` 元素上。页面不同部分需要各自的选择时，就使用单独的偏好实例。

### 读取偏好
在组件里读取偏好的当前状态：

**React**

```tsx
import { usePreference } from "@ui-sdk/react/preferences"
import { skinTone } from "./preferences"

function CurrentTone() {
  const { value } = usePreference(skinTone)
  return <span>Selected tone: {value}</span>
}
```

**Vue**

```vue
<script setup lang="ts">
import { usePreference } from "@ui-sdk/vue/preferences"
import { skinTone } from "./preferences"

const tone = usePreference(skinTone)
</script>

<template>
  <span>Selected tone: {{ tone.value }}</span>
</template>
```

它返回计算 ref，所以模板通过 `tone.value` 读取状态里的 `value`。

**Svelte**

```svelte
<script lang="ts">
  import { usePreference } from "@ui-sdk/svelte/preferences"
  import { skinTone } from "$lib/preferences"

  const tone = usePreference(skinTone)
</script>

<span>Selected tone: {tone.current.value}</span>
```

**Solid**

```tsx
import { usePreference } from "@ui-sdk/solid/preferences"
import { skinTone } from "./preferences"

function CurrentTone() {
  const tone = usePreference(skinTone)
  return <span>Selected tone: {tone().value}</span>
}
```

**Web Components**

用 `get()` 和 `subscribe()` 读取值并让你的元素保持最新，如[跟随变更](https://ui-sdk.cn/docs/core/behaviors/preferences#follow-changes)所示。

## 在原语中使用
原语需要在自身状态里使用偏好时，就用 `initialState` 和 `follow`。从 `initialState` 开始，让服务端渲染和水合保持一致：

```ts
state: () => ({ tone: skinTone.initialState }),
```

然后从 `root` 的 `bind` 里调用 `follow`，让那份状态保持最新。返回它的清理函数：

```ts
root: slot({
  attrs: (state) => ({ "data-skin-tone": state.tone.value }),
  bind: (_el, part) => skinTone.follow(part.store, "tone"),
}),
```

从原语的 API 里调用 `skinTone.set(...)` 改变选择。

## 选择配色方案
`createColorScheme` 内部使用 `createPreference`。它的选择从这些选项开始：

```ts
const choice = createPreference({
  values: ["system", "light", "dark"],
  defaultValue: "system",
  attribute: "data-color-scheme",
})
```

这保存的是选择。`createColorScheme` 还会读取浏览器的首选取色方案，并算出该用哪个方案。在你的应用里，用这个辅助函数：

```ts
import { createColorScheme, createLocalStorage } from "@ui-sdk/core"

const colorScheme = createColorScheme({
  storage: createLocalStorage("color-scheme"),
})

export { colorScheme }
```

它支持同样的 `set`、`subscribe`、`follow` 和可取消的 `onValueChange` 回调。把它和其他偏好一起传给 `Preferences`，以应用它的 `data-color-scheme` 属性。

调用 `colorScheme.set("dark")` 选择 Dark。调用 `colorScheme.set("system")` 重新跟随浏览器。默认值是 `"system"`；显式选择 Light 或 Dark 后，浏览器偏好变化时选择保持不变。

选择 Light 或 Dark。选择 Default (System)，然后改变系统的配色方案，看它如何跟随。

### 读取配色方案
`get()` 返回三个字段：

| 字段       | 说明                                                          |
| ---------- | ------------------------------------------------------------- |
| `value`    | 应用的选择：`"system"`、`"light"` 或 `"dark"`。               |
| `system`   | 浏览器的偏好：`"light"`、`"dark"`，尚不清楚时为 `"unknown"`。 |
| `resolved` | 要使用的方案：`value`；选择为 `"system"` 时则是 `system`。    |

例如，浏览器偏好 Dark 时选择 Light，会得到 `{ value: "light", system: "dark", resolved: "light" }`。

把 `value` 用于你的 CSS 属性，这样在 JavaScript 运行之前，CSS 就能处理 `"system"`。[按偏好设置样式](https://ui-sdk.cn/docs/core/behaviors/preferences#style-by-preferences)展示了做法。

### 跟随浏览器的方案
在有人订阅或跟随时，`onSystemValueChange` 报告浏览器的变化：

```ts
const colorScheme = createColorScheme({
  onSystemValueChange: (value) => console.log(value),
})
```

应用的选择用 `onValueChange`，浏览器的偏好用 `onSystemValueChange`。浏览器的变化无法取消。

### 在 iframe 内
传入 `view`，读取 iframe 的浏览器偏好：

```ts
const colorScheme = createColorScheme({ view: frame.contentWindow! })
```

## 按偏好设置样式
把偏好传给 `Preferences` 时，它会加上你用 `attribute` 指定的数据属性。设置 `global: true` 时，属性加到 `<html>` 上；否则加到 `Preferences` 元素上。

上面的密度偏好使用 `attribute: "data-density"` 和 `global: true`。调用 `density.set("compact")` 时，`Preferences` 会更新这个属性：

```html
<html data-density="compact">
  …
</html>
```

你可以在 CSS 或 Tailwind 里使用这个属性，改变页面的外观。

### CSS
在选择器里匹配属性的值。例如，在紧凑模式下减小行与行之间的间距：

```css
.row {
  padding-block: 0.5rem;
}

[data-density="compact"] .row {
  padding-block: 0.25rem;
}
```

### Tailwind CSS
定义一个匹配该属性的变体：

```css
@custom-variant compact (&:where([data-density="compact"], [data-density="compact"] *));
```

然后把它和其他工具类一起使用：

```html
<li class="py-2 compact:py-1">…</li>
```

### 配色方案
把 `data-color-scheme` 映射到 CSS 的 `color-scheme` 属性。用 `light-dark()` 选择每种颜色：

```css
:root,
[data-color-scheme="system"] {
  color-scheme: light dark;
}

[data-color-scheme="light"] {
  color-scheme: light;
}

[data-color-scheme="dark"] {
  color-scheme: dark;
}

:root,
[data-color-scheme] {
  --background: light-dark(oklch(1 0 0), oklch(0.145 0 0));
  --foreground: light-dark(oklch(0.145 0 0), oklch(0.985 0 0));
}
```

值为 `"system"` 时，由浏览器选择方案。表单控件和滚动条也会跟随它。在每个元素上按它自己的方案声明颜色变量，这样深色侧边栏可以使用与页面不同的颜色。

对于只有一套全局方案的页面，Tailwind 的 `dark:` 变体可以同时处理 Dark 和 System：

```css
@custom-variant dark {
  &:where([data-color-scheme="dark"], [data-color-scheme="dark"] *) {
    @slot;
  }
  @media (prefers-color-scheme: dark) {
    &:where([data-color-scheme="system"], [data-color-scheme="system"] *) {
      @slot;
    }
  }
}
```

### 显示匹配的内容
同一内容有几种版本时，把每种都渲染出来，让 CSS 显示匹配的值。肤色演示用它来处理问候语：

```tsx
import { skinTone } from "./preferences"

const waves = {
  default: "👋",
  light: "👋🏻",
  "medium-light": "👋🏼",
  medium: "👋🏽",
  "medium-dark": "👋🏾",
  dark: "👋🏿",
}

function Wave() {
  return (
    <span className="wave" role="img" aria-label="Waving hand">
      {skinTone.values.map((tone) => (
        <span key={tone} data-tone={tone} aria-hidden="true">
          {waves[tone]}
        </span>
      ))}
    </span>
  )
}

export { Wave }
```

```css
.wave [data-tone] {
  display: none;
}

[data-skin-tone="default"] .wave [data-tone="default"],
[data-skin-tone="light"] .wave [data-tone="light"],
[data-skin-tone="medium-light"] .wave [data-tone="medium-light"],
[data-skin-tone="medium"] .wave [data-tone="medium"],
[data-skin-tone="medium-dark"] .wave [data-tone="medium-dark"],
[data-skin-tone="dark"] .wave [data-tone="dark"] {
  display: inline;
}
```

容器提供无障碍名称。CSS 显示一只手，隐藏其余的手。

## 服务端渲染
服务器可以读取 cookie，但 localStorage 和 sessionStorage 只在浏览器里可用。根据偏好所影响的内容选择渲染方式：

| 依赖偏好的内容         | 渲染方式                            |
| ---------------------- | ----------------------------------- |
| 颜色、间距或字体       | 在 CSS 里为属性设置样式。           |
| 同一内容的几种版本     | 渲染每个版本，用 CSS 显示其中一个。 |
| 整页的格式化文本或内容 | 在服务器上读取 cookie。             |
| 水合后可以更新的内容   | 用 `usePreference` 读取状态。       |

### 在页面水合前显示偏好
对于保存在 localStorage 或 sessionStorage 里的偏好，把它传给 `Preferences`。它会渲染一段内联脚本，在页面绘制之前应用保存的选择：

1. 服务器使用 `defaultValue` 渲染。
2. 脚本读取保存的选择，并设置偏好的数据属性。CSS 可以立即使用它。
3. 水合之后，`usePreference` 和 `follow` 取得保存的值。

例如，如果有人保存了 `"medium"`，CSS 在首次绘制时会看到 `data-skin-tone="medium"`。由 `usePreference` 渲染的标签仍从 `"default"` 开始，并在水合后更新。

如果你的框架在水合期间检查这些属性，要[考虑到脚本带来的变化](https://ui-sdk.cn/docs/server-rendering#saved-preferences-and-storage)。如果你的内容安全策略要求内联脚本带 nonce，就把 `nonce` 传给 `Preferences`。

对于你自己渲染的 HTML，`preferencesScript([skinTone])` 会生成这段脚本。把它放在持有偏好的元素内部。如果只有一个存储值，可以改为[渲染存储的脚本](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration)。

### 在服务器上读取 cookie
服务器需要已保存的选择来渲染内容时，就用 cookie，比如按用户偏好的包管理器给出安装命令。在请求处理函数里，把 `Cookie` 请求头传给存储：

```ts
import { createCookieStorage, createPreference } from "@ui-sdk/core"

const packageManager = createPreference({
  values: ["npm", "pnpm", "yarn", "bun"],
  defaultValue: "npm",
  attribute: "data-package-manager",
  storage: createCookieStorage("package-manager", {
    cookie: request.headers.get("cookie"),
  }),
})
```

如果 cookie 里是 `"pnpm"`，`packageManager.initialState.value` 和 `packageManager.get().value` 都从 `"pnpm"` 开始。cookie 缺失或无效时使用 `"npm"`。

在浏览器里，存储读取 `document.cookie`。[为每个请求创建并共享偏好](https://ui-sdk.cn/docs/server-rendering#read-a-cookie-on-the-server)，让访客之间不共享状态。这样组件从第一次渲染起就能使用保存的选择。

### 服务器上的浏览器偏好
内容依赖系统的配色方案时，支持该特性的浏览器可以在 `Sec-CH-Prefers-Color-Scheme` 请求头里发送它。用这些响应头请求它：

```http
Accept-CH: Sec-CH-Prefers-Color-Scheme
Critical-CH: Sec-CH-Prefers-Color-Scheme
Vary: Sec-CH-Prefers-Color-Scheme
```

`Critical-CH` 会让支持的浏览器重试缺少该提示的请求。`Vary` 告诉缓存该响应依赖它。浏览器支持情况见 [color-scheme client hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-CH-Prefers-Color-Scheme)。

用 `colorSchemeOf` 读取请求头，并把它作为 `initial` 传入：

```ts
import { colorSchemeOf, createColorScheme } from "@ui-sdk/core"

const colorScheme = createColorScheme({
  initial: colorSchemeOf(request.headers.get("Sec-CH-Prefers-Color-Scheme")),
})
```

请求头缺失时，`colorSchemeOf` 返回 `"unknown"`。保留针对 `"system"` 的 CSS 处理，让样式仍然跟随浏览器。水合时，把相同的 `initial` 值共享给浏览器。

按请求从该请求的 cookie 或提示里创建偏好。这样不同访客的选择彼此独立。

## API 参考
### 偏好选项
- `values` (`readonly Value[]`): Every value people can choose. A saved value that isn't one of them is ignored. Example: [Create a Preference](https://ui-sdk.cn/docs/core/behaviors/preferences#create-a-preference).
- `defaultValue` (`NoInfer<Value>`): The value before anything is saved, and after a saved value is removed. Example: [Create a Preference](https://ui-sdk.cn/docs/core/behaviors/preferences#create-a-preference).
- `attribute` (``data-${string}``): The attribute that shows the value, which has to start with `data-`, like `"data-skin-tone"`. Example: [Create a Preference](https://ui-sdk.cn/docs/core/behaviors/preferences#create-a-preference).
- `global?` (`boolean`): Whether the attribute goes on `<html>`, for a preference the whole page styles by. Otherwise it goes on the `Preferences` element, for the part of the page inside it. Example: [On the Whole Page](https://ui-sdk.cn/docs/core/behaviors/preferences#on-the-whole-page).
- `storage?` (`object`): Where the value is kept between visits, from `createLocalStorage`, `createSessionStorage` or `createCookieStorage`. Example: [Remember the Choice](https://ui-sdk.cn/docs/core/behaviors/preferences#remember-the-choice).
- `onValueChange?` (`((value: Value, details: ChangeDetails<ChangeReason>) => void)`): Called before the value changes, with its reason. `details.cancel()` keeps the current one. Example: [Respond to Changes](https://ui-sdk.cn/docs/core/behaviors/preferences#respond-to-changes).

### 偏好状态与方法
`createPreference` 和 `createColorScheme` 都返回这些字段。配色方案的状态还包含[浏览器的方案和解析后的值](https://ui-sdk.cn/docs/core/behaviors/preferences#read-the-color-scheme)。

- `initialState` (`{ value: string; }`): What the server and the first client render show: `defaultValue`, or the value a cookie keeps. Example: [Use in a Primitive](https://ui-sdk.cn/docs/core/behaviors/preferences#use-in-a-primitive).
- `get` (`() => { value: string; }`): The current state, the same object until the value changes. In the browser it's the saved value even before anything subscribes, for a render in the browser only. Hydrate from `initialState`. Example: [Read and Change the Value](https://ui-sdk.cn/docs/core/behaviors/preferences#read-and-change-the-value).
- `set` (`(next: string, change?: { reason?: ChangeReason; event?: Event; }) => boolean`): Changes the value, through `onValueChange`, which can cancel it, and saves it. The reason defaults to `"imperative"`. Returns whether it changed. Example: [Read and Change the Value](https://ui-sdk.cn/docs/core/behaviors/preferences#read-and-change-the-value).
- `subscribe` (`(listener: (state: { value: string; }) => void) => () => void`): Hears every change. The first subscriber reads back the saved value. Returns the function that stops it. Example: [Follow Changes](https://ui-sdk.cn/docs/core/behaviors/preferences#follow-changes).
- `follow` (`<Key extends string>(store: PreferenceStore<Key, { value: string; }>, key: Key) => () => void`): Keeps `key` in a store set to the preference's state. Call it from a part's `bind`: the state starts at `initialState`, catches up a microtask later, once hydration is done, and follows every change after that. Returns the cleanup for `bind`. Example: [Use in a Primitive](https://ui-sdk.cn/docs/core/behaviors/preferences#use-in-a-primitive).

### Preferences 组件
- `nonce?` (`string`): The nonce your Content Security Policy gives inline scripts. Example: [Server Rendering](https://ui-sdk.cn/docs/core/behaviors/preferences#server-rendering).
- `preferences` (`readonly PreferenceLike[]`): The preferences to show, from `createPreference` or `createColorScheme`. Example: [Apply Preferences](https://ui-sdk.cn/docs/core/behaviors/preferences#apply-preferences).

### 配色方案选项
`storage`、`global` 和 `onValueChange` 的用法与 [`createPreference`](https://ui-sdk.cn/docs/core/behaviors/preferences#preference-options) 中相同。这些选项控制配色方案：

- `defaultValue?` (`ColorSchemeValue`): The scheme the app starts with, like a choice saved in a cookie that the server read. Example: [Choose a Color Scheme](https://ui-sdk.cn/docs/core/behaviors/preferences#choose-a-color-scheme).
- `initial?` (`SystemColorScheme`): The browser's preference the server and the first client render assume, so hydration matches. Read the request's `Sec-CH-Prefers-Color-Scheme` hint with `colorSchemeOf`. Example: [Browser Preferences on the Server](https://ui-sdk.cn/docs/core/behaviors/preferences#browser-preferences-on-the-server).
- `onSystemValueChange?` (`((value: "light" | "dark") => void)`): Called when the browser's preference changes, while something subscribes or follows. Example: [Follow the Browser's Scheme](https://ui-sdk.cn/docs/core/behaviors/preferences#follow-the-browsers-scheme).
- `view?` (`Window`): The window to read, like an iframe's. Defaults to the page's window. Example: [Inside a Frame](https://ui-sdk.cn/docs/core/behaviors/preferences#inside-a-frame).


# 画布

平移和缩放画布，并连接它的节点。

`createViewport` 平移和缩放画布，`createConnect` 连接画布上的端口。

从 `@ui-sdk/core` 导入它们。移动节点、选择节点、用键盘导航和查找节点，分别使用[拖动与调整大小](/docs/core/behaviors/direct-manipulation)、[选择](/docs/core/behaviors/selection)、[焦点与按键](/docs/core/behaviors/focus)和[在页面中查找](https://ui-sdk.cn/docs/core/behaviors/canvas#find-in-page)。

## 平移和缩放
视口是 `{ x, y, zoom }`。`x` 和 `y` 以屏幕像素为单位，把画布原点放在外框内。`zoom: 1` 表示它的正常大小。

### 平移与缩放
先在状态里放一个视口，并把它标记为[实时](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state)：

```ts
state: () => ({ viewport: { x: 0, y: 0, zoom: 1 } }),
live: ["viewport"],
```

在 `api` 里创建这个行为，并把它和 API 的其余部分一起返回：

```ts
const viewport = createViewport(context, {
  key: "viewport",
  surface: () => context.element("root"),
})
```

`root` 是外框，`world` 装下它内部的一切。连接外框的事件和 `world` 的实时样式：

```ts
root: slot({
  attrs: () => ({
    tabindex: "0",
    style: css({ position: "relative", overflow: "clip", "touch-action": "none" }),
  }),
  on: {
    wheel: (event, { api }) => api.viewport.wheel(event),
    pointerdown: (event, { el, api }) => {
      if (event.target === el) api.viewport.pointerdown(event)
    },
    keydown: (event, { api }) => api.viewport.keydown(event),
  },
}),
world: slot({
  attrs: () => ({ style: css({ position: "absolute", left: "0", top: "0" }) }),
  live: live((state, { api }) => ({ style: api.viewport.style(state) })),
}),
```

在你的组件里给外框一个可见的尺寸和无障碍名称。一次变换移动整个 world；实时样式让平移不会重新渲染每个节点。

拖动空白画板或滚动来平移。双指捏合，或按住 Control 或 Command 滚动来缩放。聚焦画板后试试 +、− 和 0；Reset View 会恢复起始位置。

`0` 把缩放重置为 100%。要连同位置一起重置，就调用 `viewport.setViewport({ x: 0, y: 0, zoom: 1 })`。

### 从代码中适应、显示和缩放
用 `fit` 完整显示一个矩形。它的坐标以画布为单位：

```ts
viewport.fit(
  { left: 0, top: 0, right: 800, bottom: 600 },
  { padding: 16, maxZoom: 1 }
)
viewport.zoomBy(1.25)
viewport.panBy(80, 0)
```

不传点时，`zoomBy` 和 `zoomTo` 使用外框的中心。`panBy` 接收屏幕像素。在行为的选项里设置 `minZoom` 和 `maxZoom` 来限制缩放；默认值分别是 0.1 和 4。

节点获得焦点时，`reveal` 会把它带入视野。`rectOf` 以画布为单位读取元素的矩形：

```ts
sight: slot({
  on: {
    focus: (_event, { el, api }) => {
      if (el) api.viewport.reveal(api.viewport.rectOf(el), { padding: 16 })
    },
  },
}),
```

在外框上使用 `overflow: clip`，让原生焦点滚动不与视口冲突；或者用 [`bindFindable`](https://ui-sdk.cn/docs/core/behaviors/canvas#find-in-page) 让视口接管这些滚动。`message` 选项自定义缩放按键播报的内容：

```ts
message: (zoom) => `Map at ${Math.round(zoom * 100)} percent`,
```

按 Fit 查看每个景点。试试缩放和平移按钮，然后用 Tab 在景点之间移动：地图会把每个获得焦点的景点带入视野。

### 在页面中查找
在页面中查找（⌘F 或 Ctrl+F）能找到画布上任意位置的文本，但它通过滚动来显示匹配项，而视口用的是平移。把 world 放进一个填满外框的面板，并用 `bindFindable` 绑定这个面板：

```ts
pane: slot({
  attrs: () => ({
    style: css({
      position: "absolute",
      inset: "0",
      overflow: "scroll",
      "scrollbar-width": "none",
      "touch-action": "none",
      "pointer-events": "none",
    }),
  }),
  bind: (el, { api }) => api.viewport.bindFindable(el),
}),
world: slot({
  attrs: () => ({ style: css({ position: "absolute", left: "0", top: "0", "pointer-events": "auto" }) }),
  live: live((state, { api }) => ({ style: api.viewport.style(state) })),
}),
```

面板必须是用户能滚动的元素，使用 `overflow: scroll`，因为在页面中查找不会滚动 `overflow: hidden` 的元素；`scrollbar-width: none` 会隐藏它的滚动条。保留外框的 `overflow: clip`，并把重置按钮之类的控件留在外框里、面板之外。面板会把空白处的按压和转轮事件传给外框，所以外框的处理函数照常工作。

浏览器在面板里的每次滚动都会变成原因为 `find-in-page` 的平移，于是匹配项会按浏览器自己的显示方式进入视野，带着它自己的高亮和计数。其他会滚动到元素的行为也一样，比如 `scrollIntoView` 或指向元素 id 的链接；用 Tab 移到视野外的节点时，会以 `focus-in` 为原因平移。

面板静止时，滚动位置停在远离原点的地方，并用一个空元素留出空间，这样无论节点在视野的哪一侧，浏览器都能朝它滚动。绑定时，world 的 `style` 会跟着移动；面板里的其他东西会滚走，所以面板只装 world。平滑的 `scrollIntoView` 只按第一步平移；要给平移加动画，就调用 `reveal`。

按 ⌘F 或 Ctrl+F，搜索 lighthouse。每个灯塔都在地图外不同的方向；按 Enter 从一个跳到下一个，地图会平移到每一个。

### 屏幕坐标与画布坐标
指针事件给出屏幕坐标。在往画布上放置东西之前，先把它们转换过来：

```ts
const point = viewport.toCanvas(event.clientX, event.clientY)
```

`toScreen(point)` 转换回客户端坐标，适合缩放后的 world 外部的标签。`visible()` 给出当前视野内的矩形，`get()` 返回视口。

默认情况下，行为直接写入它的状态键。要让组件控制视口，就配合 `set` 使用[变更模式](https://ui-sdk.cn/docs/core/kernel/handle-changes#state-a-user-controls)：

```ts
set: (value, details) => change("viewport", value, details),
```

变更会报告原因：`wheel`、`drag`、`pinch`、`zoom-key`、`focus-in`、`find-in-page` 或 `imperative`。

双击添加一个圆点。平移或缩放后再添加一个：它会落在你点击的位置。画布缩放时，最新圆点的标签保持原来的大小。

## 连接
`createConnect` 跟踪从一个端口到另一个端口的一条线。哪些端口对可以连接、连接后保存什么，由你决定。

### 绘制连接
在状态里加一个 `connecting` 字段，初始值为 `null as ConnectDraft | null`，并把它列进 `live`。然后在 `api` 里创建这个行为：

```ts
const connect = createConnect(context, {
  slot: "port",
  draft: "connecting",
  canConnect: (from, to) => from.endsWith(":out") && to.endsWith(":in"),
  point: (x, y) => viewport.toCanvas(x, y),
  connect: (from, to, details) =>
    change("edges", [...context.store.get().edges, { from, to }], details),
})
```

这里，端口键以 `:out` 或 `:in` 结尾。`canConnect` 只接受输出到输入的端口对。你可以在那里加上自己的检查，比如拒绝同一节点上的两个端口。`point` 把线的自由端放进画布坐标。

给每个端口一个 `value`，比如 `"prompt:out"` 或 `"answer:in"`，并接上它的指针处理函数。`role` 会给出 `source`、`target` 或 `candidate`，用于设置样式：

```ts
port: slot<{ value: string }>({
  props: { value: "string" },
  live: live((state, { api, key }) => ({ "data-connect": api.connect.role(state, key) })),
  on: {
    pointerdown: (event, { el, api, key }) => {
      if (el) api.connect.pointerdown(event, key, el)
    },
  },
}),
```

绘制过程中，`connecting` 保存 `{ from, to, x, y, keyboard }`。把这个草稿和已保存的边一起渲染，`to` 为 `null` 时用 `x` 和 `y` 作为它的自由端。

为了键盘操作，在节点的动作里调用 `connect.start(portKey)`，再把它的按键事件传给 `connect.keydown(event)`。方向键选择该方向上的有效端口；Enter 或 Space 连接；Escape 或 Tab 取消。

从 Prompt 的输出拖到一个输入，落在 Answer 或 Summary 上。或者聚焦 Prompt，按 C，用方向键选一个输入，再按 Enter。Escape 取消。

这个行为会播报每一步。给它一个 `label` 函数，提供易读的端口名称。如果端口对辅助技术隐藏，要保留节点键盘动作的可访问性，并用文字描述它的连接，比如 `aria-description="Connected to Answer."`。

### 吸附、文字和代码
`radius` 控制指针要离多近，端口才会成为目标。它以屏幕像素为单位，所以在不同缩放级别下保持一致。默认值是 28。

默认播报不合适时，覆盖 `message`。`connectMessage` 为其他步骤提供默认播报：

```ts
radius: () => 48,
message: (message, label) =>
  message.type === "connect"
    ? `${label(message.from)} into ${label(message.to)}.`
    : connectMessage(message, label),
```

你也可以从代码里连接：

```ts
if (connect.start("synth")) {
  connect.target("ch3")
  connect.commit({ reason: "connect-key" })
}
```

`active()` 告诉你是否有连接正在进行；`cancel()` 清除它的草稿。`connect` 回调决定保存什么。在这个接线板里，再次连接已有的端口对会移除它的线缆。

把源插孔拖向一个通道，再连接同一对端口即可拔掉。试试把 Synth 连到 3，或者聚焦一个源并按 Enter 开始；用方向键选择，Enter 连接，Escape 取消。

## 可访问性
给每个指针动作一条键盘路径，并在画布旁说明它。把获得焦点的节点带入视野，并用文字和线条一起描述连接。

要做一个完整的编辑器，把这些辅助函数与[在二维中移动](https://ui-sdk.cn/docs/core/behaviors/direct-manipulation#moving-in-two-dimensions)、[选择](/docs/core/behaviors/selection)和[空间焦点](https://ui-sdk.cn/docs/core/behaviors/focus#spatial-focus)组合起来。[测试](/docs/core/testing)涵盖对结果的键盘和可访问性检查。

## API 参考
- `key` (`keyof State & string`): The state key that holds the `Viewport`. List it in `live`, so panning renders nothing. Example: [Pan and Zoom](https://ui-sdk.cn/docs/core/behaviors/canvas#pan-and-zoom).
- `surface` (`() => HTMLElement | null`): The element that clips the canvas and takes the gestures. Example: [Pan and Zoom](https://ui-sdk.cn/docs/core/behaviors/canvas#pan-and-zoom).
- `set?` (`((value: Viewport, details: { reason: ViewportReason; event?: Event; }) => boolean)`): Asks for a new viewport. Defaults to setting the state key; pass the primitive's change to make it controllable. Example: [Screen and Canvas Points](https://ui-sdk.cn/docs/core/behaviors/canvas#screen-and-canvas-points).
- `minZoom?` (`(() => number)`) Example: [Fit, Reveal and Zoom from Code](https://ui-sdk.cn/docs/core/behaviors/canvas#fit-reveal-and-zoom-from-code).
- `maxZoom?` (`(() => number)`) Example: [Fit, Reveal and Zoom from Code](https://ui-sdk.cn/docs/core/behaviors/canvas#fit-reveal-and-zoom-from-code).
- `message?` (`((zoom: number) => string)`): What screen readers hear after a zoom key. Defaults to English, like "Zoom 150%". Example: [Fit, Reveal and Zoom from Code](https://ui-sdk.cn/docs/core/behaviors/canvas#fit-reveal-and-zoom-from-code).

- `slot` (`string`): The slot whose parts are ports. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `draft` (`keyof State & string`): The state key that holds the `ConnectDraft` while one is drawn. Start it at `null`, and list it in `live`. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `connect` (`(from: string, to: string, details: { reason: ConnectReason; event?: Event; }) => boolean`): Makes the connection and returns whether it went through. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `canConnect?` (`((from: string, to: string) => boolean)`): Whether `from` can connect to `to`. Defaults to any other port. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `point?` (`((clientX: number, clientY: number) => { x: number; y: number; })`): Turns a point on screen into your units, like a canvas viewport's `toCanvas`. Defaults to client pixels. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `radius?` (`(() => number)`): How near, in screen pixels, a pointer must come to a port to snap to it. Example: [Snapping, Words and Code](https://ui-sdk.cn/docs/core/behaviors/canvas#snapping-words-and-code).
- `label?` (`((key: string) => string)`): A port's name for screen readers. Defaults to its key. Example: [Draw a Connection](https://ui-sdk.cn/docs/core/behaviors/canvas#draw-a-connection).
- `message?` (`((message: ConnectMessage, label: (key: string) => string) => string)`): What screen readers hear. Defaults to English. Example: [Snapping, Words and Code](https://ui-sdk.cn/docs/core/behaviors/canvas#snapping-words-and-code).


# 观察

订阅整个页面或其中某个部件内的组件变更。

`observe` 用一条流上报来自 ui-sdk 组件的变更。用它维护活动日志、更新预览，或看清哪些动作来自人、哪些来自 Agent。

它适用于所有框架。从 `@ui-sdk/core/observe` 导入；各框架包也会重新导出它。

## 监听变更
在浏览器入口、渲染应用之前开始观察。这样观察器就能在组件创建时注册每个组件：

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

const stop = observe((change) => {
  console.log(change.label, change.key, change.previous, change.value)
})
```

例如，选择另一个可见性设置时，可能上报 `Visibility`、`value`、`private` 和 `internal`。

不再需要订阅时，调用返回的函数：

```ts
stop()
```

要在组件的渲染函数之外注册。effect 可能在子组件已经创建之后才运行，所以需要观察整个页面时，请使用应用的浏览器端初始化代码。

## 读取变更
每条通知都是一个 `ObservedChange`：

| 字段                | 它告诉你什么                                                                |
| ------------------- | --------------------------------------------------------------------------- |
| `component`, `id`   | 组件的种类和实例 ID。                                                       |
| `label`, `row`      | 它的无障碍名称和附近的行文本（如果有）。                                    |
| `key`               | 发生变更的状态键，例如 `value` 或 `checked`。                               |
| `value`, `previous` | 新值和变更前的值。                                                          |
| `reason`            | 变更的原因，例如 `item-press` 或 `drag`。                                   |
| `source`            | `keyboard`、`mouse`、`touch`、`pen`、`virtual`、`programmatic` 或 `agent`。 |
| `ref`               | 一个引用，可以传给 `elementOf`，或与 Agent 桥接层一起使用。                 |

用 `details.cancel()` 取消的变更不会上报。受控组件会在所有者把值传回之前，先上报请求的变更；这条通知不代表所有者已经接受了它。

密码、银行卡和一次性验证码字段的 `value` 和 `previous` 都会上报 `"[redacted]"`。

## 观察页面的一部分
用 `within` 把流限制在一个面板或其他元素内：

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

const stop = observe((change) => console.log(change), {
  within: () => document.querySelector("#settings"),
})
```

这个函数可以返回一个稍后才挂载的元素。你也可以直接传入元素。只要组件的任意一个部件位于其中，这个组件就会被包含进来，所以浮层可以通过它的触发器归属于该面板。

## 等待一次交互结束
有些组件会先反复改变值，再提交。默认情况下，一次滑块拖动只在结束时产生一条通知，`previous` 取自拖动之前的值。

改用 `live: true` 来获取每一次中间变更：

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

const stop = observe((change) => console.log(change.value), { live: true })
```

实时流不包含提交通知。不提交的状态，例如文本字段的输入，在两种模式下都会逐次上报变更。由代码或 Agent 发起的变更会立即上报。

## 在 await 之后保留来源
Agent 的按压会上报 `"agent"`，按压运行期间它引起的变更也是如此。稍后才完成的工作，比如等待请求的保存操作，会在按压结束之后运行，所以它的变更上报 `"programmatic"`。

每个可能返回 Promise 的动作，比如 Button 的点击处理函数、Close 部件的 `action` 或 toast 的按钮，都会在事件之后收到本次按压的 `source`。对 `await` 之后做出的变更，把它传给 `withSource`：

```ts
import type { ButtonActionDetails } from "@ui-sdk/core/button"
import { withSource } from "@ui-sdk/core/observe"

async function onSave(event: MouseEvent, { source }: ButtonActionDetails) {
  await save()
  withSource(source, () => status.setValue("Saved"))
}
```

这里的 `status` 是一个 Input 的控制器。Agent 按下 Save 时，新的状态上报 `"agent"`，就像按压期间一样。保存在运行期间别人做出的变更会保留各自的来源，因为只有传给 `withSource` 的函数才会采用这次按压的来源。各框架的 Button 页面都展示了这个处理函数的实际写法。

## 找到元素
`elementOf` 根据组件的 ref 找到根元素，或第一个可用的部件。例如，把 Agent 改动的控件滚动到可见区域：

```ts
import { elementOf, observe } from "@ui-sdk/core/observe"

const stop = observe((change) => {
  if (change.source === "agent") {
    elementOf(change.ref)?.scrollIntoView({ block: "nearest" })
  }
})
```

要在两轮之间让 Agent 了解情况，请参阅[观察变更](/docs/agents/connect-an-agent/observe-changes)。要记录可以撤销的变更，请参阅[历史与撤销](/docs/agents/connect-an-agent/history-and-undo)。


# 测试

测试原语的交互、无障碍属性、服务端输出和阅读方向。

`@ui-sdk/core/testing` 提供辅助函数，用来模拟输入、检查焦点和无障碍属性，并查看原语的状态和服务端输出。

你可以用它们直接测试原语，或检查渲染后的组件。交互测试需要一个 DOM，比如 jsdom 或浏览器。服务端输出和部件读取不需要 DOM。

## 检查模式
如果你渲染的控件遵循常见的无障碍模式，`checkPattern` 会检查它的角色、名称、状态、部件之间的引用和键盘交互：

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

await checkPattern(root, "tabs")
```

`root` 是控件的元素，或包围它的元素。检查会抛出包含所有问题的单个错误。在这里，移除选项卡列表的名称就能让它有东西可报告：

按 Check the Tabs Pattern。然后选中 Leave the tab list unnamed，再次运行检查，查看缺少名称的错误。

支持的模式有 `listbox`、`menu`、`menubar`、`tabs`、`radio-group`、`toolbar`、`tree`、`dialog`、`alertdialog`、`disclosure`、`accordion`、`combobox`、`slider`、`switch` 和 `checkbox`。

检查会使用控件自己的按键，并在可能时恢复焦点和状态。检查菜单或对话框之前，先把它打开。菜单检查会激活一个选项，所以要用可以安全执行的测试动作。

它要求列表框、选项卡和工具栏支持 Home 和 End，要求每个选项卡列表都有名称，并要求模态对话框带有 `aria-modal="true"`。这些要求故意比 WAI-ARIA Authoring Practices 中部分可选行为更严格。

## 挂载原语
想测试原语本身时，使用 `mount`。传入它的定义、选项和一小段标记。与槽位匹配的标签会成为部件；它们的属性提供部件的 props。

这个测试使用[确认按钮](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)。第一次按压让它进入待命状态。再按一次则确认并解除待命：

```ts
import { expect, test } from "vitest"
import { mount } from "@ui-sdk/core/testing"
import { confirmButton } from "./confirm-button"

test("confirm with a click and Enter", async () => {
  const button = mount(confirmButton, {}, `<root>Delete</root>`)
  try {
    await button.click(button.root)
    expect(button.state.armed).toBe(true)
    expect(button.changes.at(-1)).toMatchObject({
      key: "armed",
      reason: "press",
      source: "mouse",
    })

    await button.keys("Enter")
    expect(button.state.armed).toBe(false)
  } finally {
    button.unmount()
  }
})
```

按 Run the Test 点击确认按钮、按 Enter，并查看结果状态、变更原因和输入来源。

`root` 是标记中的第一个元素。用 `part(slot, key)` 找到另一个部件，例如 `view.part("item", "pear")`。`state` 读取当前状态，`api` 暴露原语的方法，`changes` 记录每一次被接受的变更。

完成后一定要调用 `unmount`。它会移除标记、解绑部件并销毁实例。

## 输入、悬停与播报
调用 `type` 之前先聚焦输入框。特殊按键和组合键用 `keys`，包括 `Tab`、`Shift+Tab` 和 `Space`：

```ts
const search = mount(
  searchField,
  {},
  `<root><input aria-label="Search"></input></root>`
)
try {
  search.part("input")!.focus()
  await search.type("pear")
  expect(search.state.query).toBe("pear")

  await search.keys("Escape")
  expect(search.state.query).toBe("")
} finally {
  search.unmount()
}
```

对于指针交互，`hover(element)` 把指针移到部件上。`drag(element, { to: target })` 拖到另一个元素；`drag(element, { by: { x, y } })` 按距离移动。

按 Run the Tests 输入并清空搜索、悬停一个座位，并检查空白注册表单产生的播报。

`announced` 捕获原语发送给屏幕阅读器播报器的文本。检查延迟播报之前，先用 `settle` 等待已排期的工作：

```ts
await form.click(form.root.querySelector("button")!)
await form.settle()
expect(form.announced).toContain("Enter an email address")
```

`settle` 会等待微任务、一轮定时器和两帧动画。如果你需要 devtools 上报的分组变更，请读取 `settled`；`changes` 保留每一次中间变更。

## 服务器返回的 HTML
`checkServer` 在没有 DOM 的情况下渲染传入的部件并返回 HTML。它会检查创建原语时没有读取浏览器全局对象、时钟或随机数，也会检查部件的属性、公开状态和存在性没有读取这些内容或选项：

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

const html = checkServer(
  readMore,
  {},
  `<root><trigger>Read more</trigger><panel>More</panel></root>`
)
```

这里使用 [read-more 原语](https://ui-sdk.cn/docs/core/kernel/define-a-primitive#parts-that-come-and-go)。如果检查发现某个依赖可能导致部件在服务端和客户端渲染结果不同，它就会抛出错误：

按 Check the Server HTML 读取渲染后的部件。然后选中 Read the clock in attrs，再次运行，查看被上报的依赖。

标记遵循与 `mount` 相同的规则。普通 HTML 标签保持原样。例如，当某个槽位需要渲染特定标签时，使用 `as="form"`。

## 两个方向
对于使用水平方向键导航的控件，`checkDirection` 会比较从左到右和从右到左的行为。每次检查都会挂载一个新实例，按 Tab 进入其中，然后比较按下方向键之后的焦点和状态：

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

await checkDirection(pager, {}, `<root>Page</root>`)
```

从右到左文本中的 Left 应与从左到右文本中的 Right 一致，反之亦然。当从左到右文本中的 Right 不起作用时，检查也会失败，因为没有可比较的移动。

按 Check Both Directions。然后选中 Ignore the direction，试试水平方向键从不交换的分页器。

[分页器示例](https://ui-sdk.cn/docs/core/platform#direction)展示了它如何从页面上读取方向。

## 读取部件
如果只想做针对性的渲染断言，可以创建实例并直接查看某个部件。这些辅助函数不需要 DOM：

```ts
import { partAttrs, partPresent, partState } from "@ui-sdk/core/testing"

const instance = readMore({ id: "more" })
try {
  instance.api.toggle()
  const trigger = instance.part("trigger", {})
  expect(partAttrs(trigger)).toMatchObject({ "aria-expanded": "true" })
  expect(partState(trigger)).toEqual({ open: true })
  expect(partPresent(instance.part("panel", {}))).toBe(true)
} finally {
  instance.destroy()
}
```

`partAttrs` 读取 HTML 属性，`partState` 读取传给渲染函数的公开状态，`partPresent` 告诉你该部件是否应该渲染。

选中 Open it，对比触发器的属性和公开状态与面板的存在性。

## 选择平台
快捷键标签在 Apple 平台上使用 Command，在其他平台上使用 Control。测试它们时显式设置平台，这样运行测试的机器就不会改变结果：

```ts
import { formatShortcut } from "@ui-sdk/core"
import { setPlatform } from "@ui-sdk/core/testing"

setPlatform("apple")
expect(formatShortcut("mod+b")).toContain("⌘B")

setPlatform("other")
expect(formatShortcut("mod+b")).toContain("Ctrl+B")
```

这个覆盖设置对后续测试持续生效。在测试设置中设置它，让每个测试都得到它期望的平台。

## 在框架中测试
需要检查组件的标记、props 或它与周围 UI 的集成时，请通过框架的测试工具来渲染。方法相同：先交互，再读取结果。你也可以把渲染出的元素传给 `checkPattern`。

与 `mount` 不同，框架渲染器不会填补 DOM 测试环境中的缺失功能。对于只需要浮层能渲染的测试，jsdom 环境可以提供这几个小桩：

```ts
HTMLElement.prototype.showPopover ??= function () {}
HTMLElement.prototype.hidePopover ??= function () {}
Element.prototype.getAnimations ??= () => []
document.head.append(
  Object.assign(document.createElement("style"), {
    textContent: "[popover] { display: block !important }",
  })
)
```

这些桩不会真正执行原生浮层或动画行为。这类检查请用浏览器，用键盘和屏幕阅读器检查完成后的组件时也是如此。

有些东西会在渲染或事件之后稍晚一点才到位。只有图标的按钮会在渲染后过一拍才从它的 tooltip 得到名称，按压打开的菜单会在下一帧把焦点移入其中。用 `settle` 等待它们，在 React 中放在 `act` 里，或者用 `findByRole` 查询：

```ts
import { checkPattern, settle } from "@ui-sdk/core/testing"

await user.click(screen.getByRole("button", { name: "Options" }))
await act(settle)
await checkPattern(screen.getByRole("menu"), "menu")
```


# 开始使用

粘贴一段提示词到智能体里即可完成配置，然后选择下一步。

UI SDK 是一个行为库，提供浮层、列表和键入查找（typeahead）等行为，由你的智能体把它们组合成组件。它可以和 React、Vue、Svelte、Solid 和 Web Components 一起使用。

第一次来？[简介](/docs/core)说明了这一切是如何运作的。

## 快速开始
选择你的框架，然后把这段提示词复制到你的智能体里。

**React**

```text prompt
Set up ui-sdk in this React project. It needs React 19 or newer.

1. Install @ui-sdk/react and @ui-sdk/core with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Add a note to AGENTS.md, creating it if needed: before using ui-sdk, follow the ui-sdk skill if it's installed, and read node_modules/@ui-sdk/react/docs/llms.txt. To build a new component, also search node_modules/@ui-sdk/react/docs/core.md by heading, and read rendering.md next to it.
3. If you support skills, run: npx skills@latest add vercel-labs/ui --skill ui-sdk
```

**Vue**

```text prompt
Set up ui-sdk in this Vue project. It needs Vue 3.5 or newer.

1. Install @ui-sdk/vue and @ui-sdk/core with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. If it's a Nuxt 4 or newer app, add "@ui-sdk/vue" to modules in nuxt.config.ts.
3. Add a note to AGENTS.md, creating it if needed: before using ui-sdk, follow the ui-sdk skill if it's installed, and read node_modules/@ui-sdk/vue/docs/llms.txt. To build a new component, also search node_modules/@ui-sdk/vue/docs/core.md by heading, and read rendering.md next to it.
4. If you support skills, run: npx skills@latest add vercel-labs/ui --skill ui-sdk
```

**Svelte**

```text prompt
Set up ui-sdk in this Svelte project. It needs Svelte 5.33 or newer.

1. Install @ui-sdk/svelte and @ui-sdk/core with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Add a note to AGENTS.md, creating it if needed: before using ui-sdk, follow the ui-sdk skill if it's installed, and read node_modules/@ui-sdk/svelte/docs/llms.txt. To build a new component, also search node_modules/@ui-sdk/svelte/docs/core.md by heading, and read rendering.md next to it.
3. If you support skills, run: npx skills@latest add vercel-labs/ui --skill ui-sdk
```

**Solid**

```text prompt
Set up ui-sdk in this Solid project. It needs Solid 2: solid-js and @solidjs/web 2.0.0 or newer.

1. Install @ui-sdk/solid and @ui-sdk/core with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Add a note to AGENTS.md, creating it if needed: before using ui-sdk, follow the ui-sdk skill if it's installed, and read node_modules/@ui-sdk/solid/docs/llms.txt. To build a new component, also search node_modules/@ui-sdk/solid/docs/core.md by heading, and read rendering.md next to it.
3. If you support skills, run: npx skills@latest add vercel-labs/ui --skill ui-sdk
```

**Web Components**

```text prompt
Set up ui-sdk in this Web Components project. Each component registers its tags when you import its entry, like @ui-sdk/web/dialog.

1. Install @ui-sdk/web and @ui-sdk/core with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Add a note to AGENTS.md, creating it if needed: before using ui-sdk, follow the ui-sdk skill if it's installed, and read node_modules/@ui-sdk/web/docs/llms.txt. To build a new component, also search node_modules/@ui-sdk/web/docs/core.md by heading, and read rendering.md next to it.
3. If you support skills, run: npx skills@latest add vercel-labs/ui --skill ui-sdk
```

然后让你的智能体构建一个组件：

```text prompt
Build a search field with ui-sdk: a text input and a Clear button that only shows when there's text. Clear empties the input and puts focus back in it. Use our existing styles.
```

## 找到组件
- [Select](/docs/components/select): 选择浮层列表中的一个或多个值。
- [Field](/docs/components/field): 把表单控件连接到它的标签、描述和校验错误。
- [Tabs](/docs/components/tabs): 切换多个相关面板，同一时间只选中一个选项卡。
- [Combobox](/docs/components/combobox): 搜索选项列表，选择一个或多个值。
- [Date Picker](/docs/components/date-picker): 输入日期，或从日历中选择，支持范围和表单。
- [Menu](/docs/components/menu): 选择按钮或上下文菜单中的操作和设置。

或者[查看所有组件](/docs/components)。

## 自己构建
- [Core](/docs/core): 各种行为，以及它们如何组合在一起。
- [构建一个组件](/docs/core/build-a-component): 做一个开关按钮，然后在你的框架里渲染它。
- [行为](/docs/core/behaviors): 焦点、选择、浮层，以及组成组件的其他片段。
- [组合行为](/docs/core/compose-behaviors): 用共享状态和键盘导航构建一个星级评分。

## 与智能体协作
- [用智能体构建](/docs/agents/build-with-an-agent): 给智能体合适的上下文，构建一个小版本，再检查它的行为。
- [Skills](/docs/agents/skills): 帮助你的智能体用 @ui-sdk/core 构建自定义组件。
- [连接智能体](/docs/agents/connect-an-agent): 让智能体读取你的组件并调用它们的动作。
- [WebMCP](/docs/agents/connect-an-agent/webmcp): 让浏览器内置的智能体读取并使用你的组件。

看看[更新日志](/docs/core/changelog)里有哪些新内容。
