# Resizable

用指针和键盘调整、收起并保存面板布局。

用一组可调整大小的面板，让人们拖动它们之间的句柄或使用键盘，调整布局中各窗格的大小，比如编辑器旁边的文件列表。

```ts title="basic.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="35" min-size="20">
        <h3>Files</h3>
        <ul>
          <li>page.tsx</li>
          <li>layout.tsx</li>
          <li>globals.css</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
      <ui-resizable-panel default-size="65" min-size="40">
        <ui-resizable orientation="vertical">
          <ui-resizable-panel default-size="60" min-size="30">
            <h3>page.tsx</h3>
            <span data-slot="hint">Saved just now</span>
          </ui-resizable-panel>
          <ui-resizable-handle aria-label="Resize editor"></ui-resizable-handle>
          <ui-resizable-panel default-size="40" min-size="30">
            <h3>Terminal</h3>
            <span data-slot="hint">Ready on port 3000</span>
          </ui-resizable-panel>
        </ui-resizable>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

拖动 Files 旁边的句柄，再拖动 page.tsx 和 Terminal 之间的那个。

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

导入组件会定义它的元素。在服务器上，导入不会做任何事。

```ts
import "@ui-sdk/web/resizable"
```

## 组合
用下面的组合构建一个 `ui-resizable`：

```text
ui-resizable
├── ui-resizable-panel
├── ui-resizable-handle
└── ui-resizable-panel
```

在你想调整大小的面板之间放一个句柄，并用 `aria-label` 给它命名，比如“Resize files”。这一组会把面板排成一行，所以要给它一个尺寸，每个面板的大小是各面板共享空间的百分比。一组面板可以放在一个面板里面，比如终端上方的编辑器。

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

```html
<script type="module">
  import "@ui-sdk/web/resizable"
</script>

<ui-resizable>
  <ui-resizable-panel default-size="30">Files</ui-resizable-panel>
  <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
  <ui-resizable-panel>Editor</ui-resizable-panel>
</ui-resizable>
```

没有 `default-size` 的面板占剩下的空间，这里是 70%。

## 自己构建
`@ui-sdk/web/resizable` 自带现成的 `ui-resizable` 元素。如果你想用自己的元素名构建一个，可以从 `@ui-sdk/core` 里的 `resizable` 原语（primitive）开始：

```ts title="split-view-elements.ts"
import { resizable } from "@ui-sdk/core/resizable"
import { createParts } from "@ui-sdk/web"

createParts(resizable, {
  root: { tag: "split-view", display: "block" },
  panel: { tag: "split-view-pane", display: "block" },
  handle: { tag: "split-view-divider", display: "block" },
})
```

```html
<split-view>
  <split-view-pane default-size="30">Files</split-view-pane>
  <split-view-divider aria-label="Resize files"></split-view-divider>
  <split-view-pane>Editor</split-view-pane>
</split-view>
```

每个元素都保留其现成对应元素的行为、状态和数据属性：根元素负责排列面板，每个窗格把大小写入 `--resizable-panel-size`，分隔元素是可聚焦的 `separator`。更多内容见[渲染原语](/docs/web-components/rendering)和[自定义部件](/docs/web-components/custom-parts)。

## 垂直
设置 `orientation="vertical"` 把面板堆叠起来，并给这一组一个高度。ArrowUp 和 ArrowDown 移动句柄。每个部件都会得到带有这一组方向的 `data-orientation`，所以垂直组的句柄是 `[data-slot="resizable-handle"][data-orientation="vertical"]`。

```ts title="vertical.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable orientation="vertical">
      <ui-resizable-panel default-size="45" min-size="25">
        <h3>Inbox</h3>
        <span data-slot="hint">3 unread messages</span>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize inbox"></ui-resizable-handle>
      <ui-resizable-panel default-size="55" min-size="25">
        <h3>Quarterly report</h3>
        <span data-slot="hint">From Hollis Grant</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

拖动 Inbox 和 Quarterly report 之间的句柄，或者聚焦它并使用 ArrowUp 和 ArrowDown。

## 句柄
把任何内容放进句柄，比如一个表明它可以拖动的握柄。句柄本身可以保持成一条细线：即使不加任何样式，它的命中区域也至少有 10 像素宽，以它为中心，触摸时为 24 像素。

```ts title="handle.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="35" min-size="20">
        <h3>Channels</h3>
        <ul>
          <li>general</li>
          <li>design</li>
          <li>releases</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize channels"><div></div></ui-resizable-handle>
      <ui-resizable-panel default-size="65" min-size="20">
        <h3>general</h3>
        <span data-slot="hint">Kofi Mensah: The release notes are ready.</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

抓住 Channels 旁边的握柄，或者聚焦句柄并使用方向键。

## 可收起
`collapsible` 让面板越过它的 `min-size` 一直收起到 `collapsed-size`（默认 0）：可以拖过中点到达它的收起尺寸，也可以在它的句柄上按 Enter 或双击，或者通过控制器。往回拖过同一个位置会以最小尺寸打开它，按 Enter 则恢复它原来的尺寸。收起的面板会得到 `data-collapsed`，尺寸为 0 时，它的内容会离开 Tab 顺序和无障碍树。

```ts title="collapsible.ts"
import "@ui-sdk/web/resizable"
import { createElement, Folder, Search, Settings } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="30" min-size="25" collapsible collapsed-size="48px">
        <ul>
          <li data-slot="row">
            ${createElement(Folder, { "aria-hidden": "true" }).outerHTML}
            <span>Files</span>
          </li>
          <li data-slot="row">
            ${createElement(Search, { "aria-hidden": "true" }).outerHTML}
            <span>Search</span>
          </li>
          <li data-slot="row">
            ${createElement(Settings, { "aria-hidden": "true" }).outerHTML}
            <span>Settings</span>
          </li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize sidebar"><div></div></ui-resizable-handle>
      <ui-resizable-panel min-size="40">
        <h3>README.md</h3>
        <span data-slot="hint">Edited by Inès Moreau</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

把侧边栏拖到关闭，只留下它的图标；或者聚焦它的句柄并按 Enter 收起或恢复它。

## 像素尺寸
尺寸是作为数字的百分比，或者带 `%`、`px` 或 `rem` 的字符串。这一组调整大小时，像素和 rem 的限制仍然成立，所以 `min-size="160px"` 的导航永远不会变得更窄，由它引起的变更会报告 `resize` 原因。

```ts title="sizes.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="200px" min-size="160px" max-size="320px">
        <h3>Docs</h3>
        <ul>
          <li>Getting Started</li>
          <li>Components</li>
          <li>Guides</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize navigation"><div></div></ui-resizable-handle>
      <ui-resizable-panel min-size="30">
        <h3>Getting Started</h3>
        <span data-slot="hint">Install the packages</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

调整 Docs 的大小。无论这一组有多宽，它的宽度都保持在 160 到 320 像素之间。

## 默认布局
`default-layout` 按顺序一次设置每个面板的大小，比如 `"25,35,40"`。否则，没有 `default-size` 的面板会平均分配剩下的空间。

```ts title="default-layout.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable default-layout="25,35,40">
      <ui-resizable-panel min-size="15">
        <h3>Mail</h3>
        <ul>
          <li>Inbox</li>
          <li>Drafts</li>
          <li>Sent</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize folders"></ui-resizable-handle>
      <ui-resizable-panel min-size="15">
        <h3>Inbox</h3>
        <ul>
          <li>Hollis Grant</li>
          <li>Inès Moreau</li>
          <li>Kofi Mensah</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize inbox"></ui-resizable-handle>
      <ui-resizable-panel min-size="15">
        <h3>Quarterly report</h3>
        <span data-slot="hint">From Hollis Grant</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

三个邮件面板的起始大小是 25%、35% 和 40%。调整其中任意一个。

## 受控
设置元素的 `layout` property，并监听 `layoutchange` 获取原因。布局是按顺序排列的每个面板一个百分比，加起来是 100。每次变更都带有[原因](https://ui-sdk.cn/docs/web-components/components/resizable#reasons)，比如 `drag`、`step-key` 或 `collapse`，而 `event.preventDefault()` 会保留当前的布局。设置 `layout` 会调整面板大小，但不触发 `layoutchange`，所以一个把它设回去的监听器不会听到自己的写入。是 [`api`](https://ui-sdk.cn/docs/web-components/components/resizable#controller) 触发它，并带有 `imperative` 原因。

```ts title="controlled.ts"
import "@ui-sdk/web/resizable"
import { log } from "./log"

const format = (layout: number[]) => layout.map(Math.round).join(" / ")

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-layout="50,50">Split Evenly</button>
        <button type="button" data-layout="30,70">Reset</button>
      </div>
      <ui-resizable default-layout="30,70">
        <ui-resizable-panel min-size="20">
          <h3>Files</h3>
          <ul>
            <li>page.tsx</li>
            <li>layout.tsx</li>
            <li>globals.css</li>
          </ul>
        </ui-resizable-panel>
        <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
        <ui-resizable-panel min-size="20">
          <h3>page.tsx</h3>
          <span data-slot="hint">Saved just now</span>
        </ui-resizable-panel>
      </ui-resizable>
    </div>
  `
  const group = root.querySelector("ui-resizable")!
  let layout = [30, 70]
  group.addEventListener("layoutchange", (event) => {
    const { value, reason } = event.detail
    if (format(value) !== format(layout)) {
      log(root, `${format(value)} (${reason})`)
    }
    layout = value
  })
  root
    .querySelectorAll<HTMLButtonElement>("[data-layout]")
    .forEach((button) => {
      button.addEventListener(
        "click",
        () => (group.layout = button.dataset.layout!.split(",").map(Number))
      )
    })
}

export { mount }
```

调整 Files 的大小，记录布局和它的原因。Split Evenly 和 Reset 会从外部设置布局。

## 完成后保存
`layoutchange` 在拖动的每一帧触发。`layoutcommit` 只触发一次，在改变布局的交互结束时：指针抬起、按键松开，或者面板收起。在那里保存。拖动期间按 Escape 会把面板放回开始的位置，不会提交任何内容。

```ts title="complete.ts"
import "@ui-sdk/web/resizable"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="40" min-size="20">
        <h3>Files</h3>
        <ul>
          <li>page.tsx</li>
          <li>layout.tsx</li>
          <li>globals.css</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
      <ui-resizable-panel min-size="20">
        <h3>page.tsx</h3>
        <span data-slot="hint">Saved just now</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
  root
    .querySelector("ui-resizable")!
    .addEventListener("layoutcommit", (event) => {
      log(
        root,
        `Saved ${event.detail.value.map(Math.round).join(" / ")} (${event.detail.reason})`
      )
    })
}

export { mount }
```

拖动句柄并松开，或者按一次方向键。松手时，控制台会记录一次布局。

## 持久化
`auto-save-id` 在交互完成时把布局保存到 `localStorage`，并在这一组于浏览器中挂载时恢复它。服务端标记从默认尺寸开始。每一组面板都保留自己的布局，所以一个时有时无的面板也能取回它的大小。给面板一个 `id`，这样即使页面别处发生变化，保存的布局也能保留下来。

这和 [Preferences](/docs/web-components/components/preferences) 是同一个思路，后者在多次访问之间保存一项选择，比如主题。Resizable 则在它的 `auto-save-id` 下保存整个布局。

```ts title="persistence.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable auto-save-id="docs-persistence">
      <ui-resizable-panel id="docs-sidebar" default-size="30" min-size="20">
        <h3>Outline</h3>
        <ul>
          <li>Introduction</li>
          <li>Installation</li>
          <li>Usage</li>
        </ul>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize outline"><div></div></ui-resizable-handle>
      <ui-resizable-panel id="docs-content" min-size="30">
        <h3>Introduction</h3>
        <span data-slot="hint">Last edited by Wren Takahashi</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

调整 Outline 的大小，然后重新加载这个页面，恢复它保存的宽度。

## 存储
`storage` property 接受任何带有 `getItem` 和 `setItem` 的对象，比如 `sessionStorage` 或 cookie。那是浏览器的存储形状，而不是 Preferences 接受的[存储](https://ui-sdk.cn/docs/web-components/components/preferences#save-the-value)辅助函数，比如 `createLocalStorage`；那些辅助函数各自只保存一个值。像选择偏好那样，在[记住选择](https://ui-sdk.cn/docs/core/behaviors/preferences#remember-the-choice)里决定用 local storage、session storage 还是 cookie。

这个示例把布局保存在 `sessionStorage` 里，作用于这个标签页的会话。它在把这一组放进页面之前就设置 `storage`，所以这一组挂载时会从它恢复：

```ts title="storage.ts"
import "@ui-sdk/web/resizable"
import type { ResizableStorage } from "@ui-sdk/web"

const session: ResizableStorage = {
  getItem: (key) => sessionStorage.getItem(key),
  setItem: (key, value) => sessionStorage.setItem(key, value),
}

function mount(root: HTMLElement) {
  const group = document.createElement("ui-resizable")
  group.storage = session
  group.setAttribute("auto-save-id", "docs-storage")
  group.innerHTML = `
    <ui-resizable-panel id="session-chats" default-size="35" min-size="20">
      <h3>Messages</h3>
      <ul>
        <li>Inès Moreau</li>
        <li>Kofi Mensah</li>
        <li>Wren Takahashi</li>
      </ul>
    </ui-resizable-panel>
    <ui-resizable-handle aria-label="Resize messages"></ui-resizable-handle>
    <ui-resizable-panel id="session-thread" min-size="20">
      <h3>Inès Moreau</h3>
      <span data-slot="hint">Can we move the review to Friday?</span>
    </ui-resizable-panel>
  `
  root.replaceChildren(group)
}

export { mount }
```

调整 Messages 的大小，然后重新加载。宽度在这个标签页里会回来，但在新标签页里不会。

服务器无法读取 `localStorage`，所以它会渲染每个面板的 `default-size`，保存的布局在元素挂载后才到达。要在首次绘制时就渲染保存的布局，就把它放进 cookie，并把各面板的大小写入各自的 `default-size`。这里你的服务器从请求的 `Cookie` 头读取它们。它导入 `resizableStorageKey`（它给 cookie 命名）：

```ts title="server.ts"
import { resizableStorageKey } from "@ui-sdk/core/resizable"

function editor(cookie: string | null) {
  const value = cookie?.match(
    new RegExp(`(?:^|; )${resizableStorageKey("editor")}=([^;]*)`)
  )?.[1]
  const saved = value ? JSON.parse(decodeURIComponent(value)) : {}
  const [sidebar = 25, main = 75] = saved["sidebar,main"] ?? []
  return `<ui-resizable auto-save-id="editor">
  <ui-resizable-panel id="sidebar" default-size="${sidebar}"></ui-resizable-panel>
  <ui-resizable-handle aria-label="Resize sidebar"></ui-resizable-handle>
  <ui-resizable-panel id="main" default-size="${main}"></ui-resizable-panel>
</ui-resizable>`
}
```

```ts title="page.ts"
import "@ui-sdk/web/resizable"
import type { ResizableStorage } from "@ui-sdk/web"

const cookieStorage: ResizableStorage = {
  getItem: (key) => {
    const value = document.cookie.match(
      new RegExp(`(?:^|; )${key}=([^;]*)`)
    )?.[1]
    return value === undefined ? null : decodeURIComponent(value)
  },
  setItem: (key, value) => {
    document.cookie = `${key}=${encodeURIComponent(value)}; path=/; max-age=31536000`
  },
}

document.querySelector("ui-resizable")!.storage = cookieStorage
```

## 控制器
元素的 `api` 可以在任何地方按 id 或索引收起、展开和调整面板大小，并用 `getLayout()` 读取布局。它做出的变更会报告 `imperative` 原因。

```ts title="controller.ts"
import "@ui-sdk/web/resizable"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="collapse">Collapse</button>
        <button type="button" data-action="expand">Expand</button>
        <button type="button" data-action="resize">240px</button>
        <button type="button" data-action="read">Read</button>
      </div>
      <ui-resizable>
        <ui-resizable-panel id="controller-sidebar" default-size="30" min-size="20" collapsible>
          <h3>Files</h3>
          <ul>
            <li>page.tsx</li>
            <li>layout.tsx</li>
            <li>globals.css</li>
          </ul>
        </ui-resizable-panel>
        <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
        <ui-resizable-panel min-size="30">
          <h3>page.tsx</h3>
          <span data-slot="hint">Saved just now</span>
        </ui-resizable-panel>
      </ui-resizable>
    </div>
  `
  const editor = root.querySelector("ui-resizable")!.api
  const actions: Record<string, () => void> = {
    collapse: () => editor.collapse("controller-sidebar"),
    expand: () => editor.expand("controller-sidebar"),
    resize: () => editor.resize("controller-sidebar", "240px"),
    read: () =>
      log(
        root,
        `Layout ${editor.getLayout().map(Math.round).join(" / ")}${editor.isCollapsed("controller-sidebar") ? ", collapsed" : ""}`
      ),
  }
  root
    .querySelectorAll<HTMLButtonElement>("[data-action]")
    .forEach((button) => {
      button.addEventListener("click", () => actions[button.dataset.action!]())
    })
}

export { mount }
```

用 Collapse、Expand 和 240px 从这一组之外移动 Files，用 Read 记录它的大小。

## 步长
`step` 设置方向键移动句柄的距离，默认 1%；`large-step` 设置 Shift 加方向键移动的距离，默认 10%。

```ts title="keyboard.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable step="5" large-step="25">
      <ui-resizable-panel default-size="50" min-size="20">
        <h3>Original</h3>
        <span data-slot="hint">v1.2.0</span>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize original"></ui-resizable-handle>
      <ui-resizable-panel default-size="50" min-size="20">
        <h3>Changes</h3>
        <span data-slot="hint">v1.3.0</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
}

export { mount }
```

聚焦 Original 和 Changes 之间的句柄。方向键移动 5%，Shift 加方向键移动 25%，Home 和 End 则会移到它能到的最远处。

## 禁用
在句柄上设置 `disabled` 会把它固定在原处。设置在组上会固定每个句柄。禁用的句柄会离开 Tab 顺序，它们旁边的面板保持原有大小。用禁用的 `<fieldset>` 包住这一组，也会固定每个句柄。

```ts title="disabled.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/resizable"
import { Check, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <ui-checkbox>
            <ui-checkbox-indicator>
              ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
            </ui-checkbox-indicator>
          </ui-checkbox>
          Lock layout
        </label>
      </div>
      <ui-resizable>
        <ui-resizable-panel min-size="15">
          <h3>Pinned</h3>
          <span data-slot="hint">2 notes</span>
        </ui-resizable-panel>
        <ui-resizable-handle disabled aria-label="Resize pinned"></ui-resizable-handle>
        <ui-resizable-panel min-size="15">
          <h3>Inbox</h3>
          <span data-slot="hint">3 unread</span>
        </ui-resizable-panel>
        <ui-resizable-handle aria-label="Resize inbox"></ui-resizable-handle>
        <ui-resizable-panel min-size="15">
          <h3>Message</h3>
          <span data-slot="hint">From Kofi Mensah</span>
        </ui-resizable-panel>
      </ui-resizable>
    </div>
  `
  const group = root.querySelector("ui-resizable")!
  root
    .querySelector("ui-checkbox")!
    .addEventListener("checkedchange", (event) => {
      group.toggleAttribute("disabled", event.detail.value === true)
    })
}

export { mount }
```

Pinned 之后的句柄保持固定。拖动 Inbox 之后的那个，然后勾选 Lock layout 把它也固定住。

## 自定义渲染
元素没有渲染函数。像这个示例一样，用数据属性为每个部件设置样式，比如面板的 `data-collapsed` 或句柄的 `data-dragging`，并从 `--resizable-panel-size` 或 `layoutchange` 读取尺寸。部件绑定哪些元素，见[部件与组合](/docs/web-components/parts-and-composition)。

```ts title="render.ts"
import "@ui-sdk/web/resizable"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-resizable>
      <ui-resizable-panel default-size="35" min-size="20" collapsible>
        <h3>Files</h3>
        <span data-slot="hint">35%</span>
      </ui-resizable-panel>
      <ui-resizable-handle aria-label="Resize files"></ui-resizable-handle>
      <ui-resizable-panel min-size="30">
        <h3>Editor</h3>
        <span data-slot="hint">65%</span>
      </ui-resizable-panel>
    </ui-resizable>
  `
  const [files, editor] = root.querySelectorAll("[data-slot=hint]")
  root
    .querySelector("ui-resizable")!
    .addEventListener("layoutchange", (event) => {
      const [filesSize, editorSize] = event.detail.value
      files.textContent =
        filesSize === 0 ? "Collapsed" : `${Math.round(filesSize)}%`
      editor.textContent = `${Math.round(editorSize)}%`
    })
}

export { mount }
```

调整 Files 的大小，看两个面板报告各自的尺寸；或者收起它，看到 Collapsed。

原语会把拖动中的尺寸直接写入面板样式。`layoutchange` 监听器也会在拖动的每一帧运行。

## 样式
除了所需的布局，部件没有样式：这一组是 flex 行或列，面板以 flex basis 取得自己的大小，句柄不收缩，并采用 `touch-action: none`。给这一组一个尺寸，给句柄宽度或高度以及背景，并用 `data-hovering`、`data-dragging` 和 `:focus-visible` 设置样式。句柄被悬停或拖动时，它的光标会显示在整个页面上，并在到达限制时指向它唯一能走的方向。

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

### `<ui-resizable-panel>`
- `--resizable-panel-size`: The panel's share of the group, as a percentage. Written on every frame of a drag, without a render.

## 数据属性
### `<ui-resizable>`
`[data-slot="resizable"]`

- `data-orientation` (`horizontal`, `vertical`): The group's direction, on every part. A handle's own `aria-orientation` is the other one, since it runs across the group.
- `data-disabled`: Present when the group, or this handle, is disabled.
- `data-dragging`: Present while a handle of the group is being dragged.

### `<ui-resizable-panel>`
`[data-slot="resizable-panel"]`

- `data-orientation` (`horizontal`, `vertical`): The group's direction, on every part. A handle's own `aria-orientation` is the other one, since it runs across the group.
- `data-collapsed`: Present while a collapsible panel is collapsed.

### `<ui-resizable-handle>`
`[data-slot="resizable-handle"]`

- `data-orientation` (`horizontal`, `vertical`): The group's direction, on every part. A handle's own `aria-orientation` is the other one, since it runs across the group.
- `data-disabled`: Present when the group, or this handle, is disabled.
- `data-dragging`: Present while this handle is being dragged.
- `data-hovering`: Present while the pointer is over the handle or within its hit area, which reaches past the handle itself.

## API 参考
属性是 kebab 写法的 attribute，比如 `default-size` 和 `auto-save-id`。布局写成 `"30,70"`。`storage` 和 `controller` 是 property。回调是 DOM 事件。

### Resizable
- `layout?` (`number[]`): Each panel's size in percent, in panel order, like `[25, 75]`. Pass it to control the group.
- `defaultLayout?` (`number[]`): The layout at first, when uncontrolled. Panels' own `defaultSize` is what a server renders, so prefer that with server rendering.
- `layoutchange event`: Runs while the layout changes: on every frame of a drag and every key. `details.cancel()` keeps the layout.
- `layoutcommit event`: Runs once an interaction that changed the layout ends: the pointer lifts, the key comes up, or a panel collapses. For saving.
- `orientation?` (`"horizontal" | "vertical"`): The direction panels are laid out in. Horizontal panels sit side by side, vertical ones stack.
- `disabled?` (`boolean`): Stops every handle: no drags, no keys, and handles leave the tab order.
- `step?` (`number`): How far an arrow key moves a handle, in percent.
- `largeStep?` (`number`): How far Shift with an arrow key moves a handle, in percent.
- `autoSaveId?` (`string`): Saves the layout when an interaction completes and restores it on the next visit, under this key. Give panels an `id` so it survives changes elsewhere on the page.
- `storage?` (`ResizableStorage`): Where `autoSaveId` saves: anything with `getItem` and `setItem`, like a cookie store a server can read.
- `controller?` (`object`): Resizes the group from anywhere. Create one with `createResizableController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### ResizablePanel
- `id?` (`string`): Identifies the panel for the controller, `aria-controls` and saved layouts. It's the element's id. Generated when left out.
- `defaultSize?` (`ResizableSize`): Where the panel starts, in percent or with a unit, like `30` or `"240px"`. Without one, panels share what's left evenly. A server renders this size.
- `minSize?` (`ResizableSize`): The smallest the panel gets while open.
- `maxSize?` (`ResizableSize`): The largest the panel gets.
- `collapsible?` (`boolean`): Lets the panel collapse below its minimum to `collapsedSize`: by dragging past half the way there, with Enter or a double-click on its handle, or through the controller.
- `collapsedSize?` (`ResizableSize`): The size a collapsible panel collapses to. At 0, its content leaves the tab order and the accessibility tree.

### ResizableHandle
- `disabled?` (`boolean`): Stops this handle: no drags and no keys, and it leaves the tab order.

### 状态
同样的状态会作为数据属性显示在每个元素上。

- `orientation` (`"horizontal" | "vertical"`): The direction panels are laid out in.
- `disabled` (`boolean`): Whether the group is disabled.
- `dragging` (`boolean`): Whether a handle is being dragged.
- `layout` (`number[]`): Each panel's size in percent. Reading it renders on every frame of a drag.

面板：

- `orientation` (`"horizontal" | "vertical"`): The direction panels are laid out in.
- `size` (`number`): The panel's size in percent. Reading it renders on every frame of a drag.
- `collapsed` (`boolean`): Whether the panel is down at its `collapsedSize`, below its minimum.
- `collapsible` (`boolean`): Whether the panel can collapse.

句柄：

- `orientation` (`"horizontal" | "vertical"`): The direction panels are laid out in. The separator itself runs across it.
- `disabled` (`boolean`): Whether the handle can't move.
- `dragging` (`boolean`): Whether the handle is being dragged.
- `hovering` (`boolean`): Whether the pointer is over the handle or within its hit area.

### 原因
`event.detail.reason` 说明布局为什么改变。

- `drag` (`PointerEvent`): A slider thumb or a resize handle was dragged, or an item was dragged to a new place in a list.
- `step-key` (`KeyboardEvent`): Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
- `collapse` (`MouseEvent | KeyboardEvent`): Enter or a double-click on a resize handle collapsed the panel beside it, or restored it.
- `resize` (`none`): The group changed size, so panels with sizes in pixels moved to stay within their bounds.
- `imperative` (`none`): A controller or `api` call.

### 控制器
元素的 `api` property 有同样的方法。`layout` property 读取和设置布局。

写方法接受可选的 `{ reason, event }`，像拖动一样触发变更事件，并在没有任何改变或变更被取消时返回 `false`。

- `getLayout()` (`() => number[]`): Each panel's size in percent, in order.
- `setLayout(layout, options?)` (`(layout: number[], options?: ResizableChangeOptions | undefined) => boolean`): Sets every panel's size at once, in percent. It's fitted to the panels' bounds and adds up to 100. Returns whether anything changed.
- `collapse(panel, options?)` (`(panel: string | number, options?: ResizableChangeOptions | undefined) => boolean`): Collapses a collapsible panel, by its id or its index. Returns whether it collapsed.
- `expand(panel, options?)` (`(panel: string | number, options?: ResizableChangeOptions | undefined) => boolean`): Expands a collapsed panel to the size it had before it collapsed, or its minimum. Returns whether it expanded.
- `resize(panel, size, options?)` (`(panel: string | number, size: ResizableSize, options?: ResizableChangeOptions | undefined) => boolean`): Resizes one panel, by its id or its index, like `resize("sidebar", "240px")`. Its neighbours give or take the difference.
- `isCollapsed(panel)` (`(panel: string | number) => boolean`): Whether a panel is collapsed.

### 事件
事件在各自的元素上触发，不会冒泡，布局在 `event.detail.value` 里，`reason`、`event` 和 `source` 在它旁边。对 `layoutchange` 调用 `preventDefault()` 会取消这次变更。

| 成员                         | 所属           | 说明                                                   |
| ---------------------------- | -------------- | ------------------------------------------------------ |
| `layout` property, attribute | `ui-resizable` | 布局。attribute 以文本形式设置它，比如 `"30,70"`       |
| `api` property               | `ui-resizable` | [控制器](https://ui-sdk.cn/docs/web-components/components/resizable#controller)                                  |
| `layoutchange` 事件          | `ui-resizable` | `detail: { value, reason, event, source }`，每次变更时 |
| `layoutcommit` 事件          | `ui-resizable` | `detail: { value, reason, event, source }`，结束时一次 |

## 无障碍
句柄遵循 [WAI-ARIA 窗口分隔条模式](https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/)。每个句柄都是一个可聚焦的 `separator`，它的 `aria-valuenow` 是它前面那个面板的大小，`aria-valuemin` 和 `aria-valuemax` 是各面板允许的范围，`aria-controls` 指向那个面板，`aria-orientation` 则横跨这一组的排列方向。用 `aria-label` 给每个句柄命名。

### 键盘
聚焦一个句柄，沿这一组的轴线按方向键，让它移动 `step`；按住 Shift 则移动 `large-step`。Home 和 End 会把它移到各面板允许的最远处，Enter 收起或恢复它旁边的可收起面板。到达最小值的面板会把剩余的移动量传给下一个面板。禁用的句柄会离开 Tab 顺序。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Keyboard**

- Starts at each panel's default size, and panels without one share the rest.
- ArrowRight grows the panel before the handle by one step, and ArrowLeft shrinks it.
- Shift with an arrow key moves by the large step.
- Arrows across the group's axis do nothing.
- ArrowDown and ArrowUp move a vertical group's handle.
- Home collapses a collapsible panel, and End grows it to its maximum.
- Home stops at the minimum of a panel that can't collapse.
- Enter collapses the panel before the handle, and restores its size.
- Enter collapses the panel after the handle when only that one can collapse.
- One step past a collapsible panel's minimum collapses it.
- A panel at its minimum passes the rest on to the next one.
- End stops where the panels' bounds meet.
- Keys pressed without waiting all land.
- Keys complete the change once they come up.
- Step and large step set how far keys move.
- A canceled change keeps the layout.
- A controlled group follows its layout.
- A controlled group that ignores a change completes nothing. React 和 Vue only.
- A disabled handle stops a move from the next one, so the panels past it keep their sizes.
- DefaultLayout sets where the panels start.
- A disabled group's handles leave the tab order and ignore drags.

**Pointer**

- Dragging a handle moves it with the pointer.
- A drag reports its moves with the drag reason and completes once.
- Dragging past a disabled handle moves nothing beyond it.
- Dragging a vertical group's handle moves it up and down.
- Dragging past half a collapsible panel's minimum collapses it, and back opens it.
- A drag stops at the panels' bounds.
- Escape during a drag puts the panels back where they started.
- A double-click on a handle collapses its panel, and another restores it.
- A press just beside the thin handle drags it.
- A press farther from the handle doesn't drag.
- Where two handles meet, one drag moves both.
- A drag shows the axis cursor over the whole page until it ends.

**Controller**

- Collapses and expands a panel, with the imperative reason.
- Resizes a panel to a size in pixels.

**Container**

- A panel with a minimum in pixels keeps it as the group shrinks.
- Panels keep their share as the group grows.

**Pages around a group**

- A layer above a handle keeps its presses.
- A press beside a handle doesn't click what's under it.
- Only the main button drags.
- An iframe under the pointer doesn't stop a drag.
- At a limit, the cursor points the only way a handle can go.
- A saved layout is there on the first paint.

**Touch**

- A touch drag that starts beside the handle, in its touch hit area, resizes without scrolling.

Runs in React、Vue 和 web components.
