# 过渡与手势

运行你的 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).
