# Collapsible

显示和隐藏一个面板，保留它的内容，并为它的高度添加动画。

用 Collapsible 显示和隐藏一个内容面板。要处理一组面板时，用 [Accordion](/docs/react/components/accordion)。

```tsx title="basic.tsx"
"use client"

import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"
import { ChevronDownIcon } from "lucide-react"

const items = [
  { name: "Linen shirt", price: "$48.00" },
  { name: "Canvas tote", price: "$18.00" },
  { name: "Wool socks", price: "$18.00" },
]

function Example() {
  return (
    <Collapsible data-variant="card">
      <CollapsibleTrigger>
        <span data-slot="stack">
          <span>Order #4189</span>
          <span data-slot="hint">3 items, $84.00</span>
        </span>
        <ChevronDownIcon />
      </CollapsibleTrigger>
      <CollapsiblePanel>
        {items.map((item) => (
          <div data-slot="row" key={item.name}>
            <span>{item.name}</span>
            <span>{item.price}</span>
          </div>
        ))}
      </CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

按 Order #4189，或者聚焦它后按 Enter 或 Space，显示这些条目。

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

## 组合
用下面的组合来构建 `Collapsible`：

```text
Collapsible
├── CollapsibleTrigger
└── CollapsiblePanel
```

根部件和面板渲染成 div，触发器渲染成原生 button。在它们周围放其他内容，比如一个标题，或一段始终显示的摘要。

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

```tsx
import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"

function Example() {
  return (
    <Collapsible>
      <CollapsibleTrigger>Order details</CollapsibleTrigger>
      <CollapsiblePanel>2 × Linen shirt</CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

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

```ts title="spoiler.ts"
"use client"

import { collapsible } from "@ui-sdk/core/collapsible"
import { createParts } from "@ui-sdk/react/primitive"

const {
  Root: Spoiler,
  Trigger: SpoilerToggle,
  Panel: SpoilerContent,
} = createParts(collapsible, {
  root: "div",
  trigger: "button",
  panel: "div",
})

export { Spoiler, SpoilerContent, SpoilerToggle }
```

```tsx
<Spoiler>
  <SpoilerToggle>Show the ending</SpoilerToggle>
  <SpoilerContent>The butler did it.</SpoilerContent>
</Spoiler>
```

每个部件都保留其现成对应部件的行为、状态和数据属性。更多内容见[渲染原语](/docs/react/rendering)和[自定义部件](/docs/react/custom-parts)。

## 禁用
在根部件上设置 `disabled`，阻止它的触发器打开或收起面板。触发器仍留在 Tab 顺序里，并报告 `aria-disabled="true"`。用禁用的 `<fieldset>` 包住 collapsible，也会把它禁用。

```tsx
<Collapsible disabled>
  <CollapsibleTrigger>Gift options</CollapsibleTrigger>
  <CollapsiblePanel>Add a gift message and wrapping.</CollapsiblePanel>
</Collapsible>
```

## 保持挂载
面板收起时会卸载，所以 Tab 会跳过它们的内容。在面板上设置 `keepMounted`，让它保持挂载并隐藏，这样输入框里写的内容会保留下来。

```tsx title="keep-mounted.tsx"
import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"
import { ChevronDownIcon } from "lucide-react"

function Example() {
  return (
    <Collapsible data-variant="card">
      <CollapsibleTrigger>
        <span data-slot="stack">
          <span>Add a delivery note</span>
          <span data-slot="hint">Optional, for the courier</span>
        </span>
        <ChevronDownIcon />
      </CollapsibleTrigger>
      <CollapsiblePanel keepMounted>
        <Field>
          <FieldLabel>Delivery note</FieldLabel>
          <Textarea placeholder="Leave it with the front desk…" />
        </Field>
      </CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

打开 Add a delivery note，输入一段备注，然后收起再展开面板。你的备注还在。

## 在页面中查找
在面板上设置 `hiddenUntilFound`，让它以 `hidden="until-found"` 留在 DOM 里。浏览器的查找命令，以及指向面板内内容的链接，都能把它露出来。面板打开时没有动画，所以匹配的内容会立即出现。

React 在服务器上把 `hidden` 序列化为布尔值。收起的面板在水合之后才能被找到。

```tsx title="find-in-page.tsx"
import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"
import { ChevronDownIcon } from "lucide-react"

function Example() {
  return (
    <Collapsible data-variant="card">
      <CollapsibleTrigger>
        <span data-slot="stack">
          <span>Ingredients</span>
          <span data-slot="hint">Morning buns, makes 12</span>
        </span>
        <ChevronDownIcon />
      </CollapsibleTrigger>
      <CollapsiblePanel hiddenUntilFound>
        <p>
          Flour, butter, brown sugar, eggs, a pinch of cardamom and sea salt.
        </p>
      </CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

让 Ingredients 保持收起。打开浏览器的查找命令，搜索 cardamom，就能露出这个面板。

## 受控
传入 `open`，并在 `onOpenChange` 里更新它。在回调里调用 `details.cancel()` 取消这次变更。

页面其他位置要放一个按钮时，用 `createCollapsibleController()` 创建一个[控制器](https://ui-sdk.cn/docs/react/components/collapsible#controller)，并作为 `controller` 传入。每个挂载的 collapsible 各创建一个控制器。

```tsx title="controlled.tsx"
"use client"

import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
  createCollapsibleController,
} from "@ui-sdk/react/collapsible"
import { ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"
import * as React from "react"

const recoveryCodes = ["7KQ2-M9XD", "P4TR-8HZC", "W3NB-6JUE", "C5YF-2LSA"]

function Example() {
  const log = useLog()
  const [collapsible] = React.useState(createCollapsibleController)
  const [open, setOpen] = React.useState(false)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => collapsible.toggle()}>
          Toggle
        </button>
      </div>
      <Collapsible
        data-variant="card"
        open={open}
        onOpenChange={(next, details) => {
          setOpen(next)
          log(`${next ? "Opened" : "Closed"} (${details.reason})`)
        }}
        controller={collapsible}
      >
        <CollapsibleTrigger>
          <span data-slot="stack">
            <span>Recovery codes</span>
            <span data-slot="hint">Each code signs you in once</span>
          </span>
          <ChevronDownIcon />
        </CollapsibleTrigger>
        <CollapsiblePanel>
          <div data-slot="stack">
            <ul>
              {recoveryCodes.map((code) => (
                <li key={code}>{code}</li>
              ))}
            </ul>
            <button type="button" onClick={() => collapsible.close()}>
              Done
            </button>
          </div>
        </CollapsiblePanel>
      </Collapsible>
    </div>
  )
}

export { Example }
```

用 Toggle 或它的触发器打开 Recovery codes，然后按 Done。控制台会记录每次变更及其原因，Done 会把焦点移回触发器。

## 动画
把测量出的 `--collapsible-panel-height` 在零和内容高度之间做动画。`data-starting-style` 标记打开的第一帧，`data-ending-style` 在收起期间一直保留。面板会保持挂载，直到退场动画结束；第一次绘制时就展开的面板没有动画。

```css
[data-slot="collapsible-panel"] {
  height: var(--collapsible-panel-height);
  overflow: hidden;
  transition: height 0.2s ease-out;

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

`onOpenChangeComplete` 在打开或收起结束时报告。

```tsx title="animation.tsx"
"use client"

import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"
import { ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"

const notes = [
  "Search now matches file contents, not only names.",
  "Shared links remember the folder they were opened from.",
  "Uploads resume after the connection drops.",
]

function Example() {
  const log = useLog()
  return (
    <Collapsible
      data-variant="card"
      onOpenChangeComplete={(open) =>
        log(open ? "Finished opening" : "Finished closing")
      }
    >
      <CollapsibleTrigger>
        <span data-slot="stack">
          <span>Release notes</span>
          <span data-slot="hint">Version 2.4, released October 28</span>
        </span>
        <ChevronDownIcon />
      </CollapsibleTrigger>
      <CollapsiblePanel>
        <ul>
          {notes.map((note) => (
            <li key={note}>{note}</li>
          ))}
        </ul>
      </CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

打开再收起 Release notes。每次动画结束时，控制台都会记录。

## 自定义渲染
用 `render` 为部件选择元素，或用渲染函数读取它的状态。下面的触发器渲染在标题里，面板渲染成有序列表。

```tsx title="render.tsx"
"use client"

import {
  Collapsible,
  CollapsiblePanel,
  CollapsibleTrigger,
} from "@ui-sdk/react/collapsible"
import { ChevronDownIcon } from "lucide-react"

const updates = [
  { label: "Out for delivery", time: "07:40" },
  { label: "Arrived at the local depot", time: "05:12" },
  { label: "Left the sorting center", time: "Wed 21:03" },
]

function Example() {
  return (
    <Collapsible data-variant="card">
      <CollapsibleTrigger
        render={(props) => (
          <h3>
            <button {...props} />
          </h3>
        )}
      >
        {(state) => (
          <>
            <span data-slot="stack">
              <span>Track parcel</span>
              <span data-slot="hint">
                {state.open ? "3 updates" : "Arrives Thursday"}
              </span>
            </span>
            <ChevronDownIcon />
          </>
        )}
      </CollapsibleTrigger>
      <CollapsiblePanel render={<ol />}>
        {updates.map((update) => (
          <li data-slot="row" key={update.label}>
            <span>{update.label}</span>
            <span>{update.time}</span>
          </li>
        ))}
      </CollapsiblePanel>
    </Collapsible>
  )
}

export { Example }
```

按 Track parcel，打开有序列表。摘要会从 Arrives Thursday 变成 3 updates。

## 样式
用 `data-open`、`data-closed` 和 `data-disabled` 为每个状态设置样式。示例根据触发器的 `data-open` 转动箭头。

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

### CollapsiblePanel
- `--collapsible-panel-height`: The panel's content height in pixels while it animates, auto once open and 0px while closed.
- `--collapsible-panel-width`: The panel's content width, the same way. For panels that open sideways.

## 数据属性
### Collapsible
`[data-slot="collapsible"]`

- `data-open`: Present while the panel is open.
- `data-closed`: Present while the panel is closed, including while it animates out.
- `data-disabled`: Present when the collapsible can't open or close.

### CollapsibleTrigger
`[data-slot="collapsible-trigger"]`

- `data-open`: Present while the panel is open.
- `data-closed`: Present while the panel is closed, including while it animates out.
- `data-disabled`: Present when the collapsible can't open or close.

### CollapsiblePanel
`[data-slot="collapsible-panel"]`

- `data-open`: Present while the panel is open.
- `data-closed`: Present while the panel is closed, including while it animates out.
- `data-disabled`: Present when the collapsible can't open or close.
- `data-starting-style`: Present for the panel's first frame. Style the state you animate from.
- `data-ending-style`: Present while the panel animates closed. Style the state you animate to.

## API 参考
属性和回调与下面相同，以 React props 的形式传入。

### Collapsible
- `open?` (`boolean`): Whether the panel is open. Pass it to control the collapsible.
- `defaultOpen?` (`boolean`): Whether the panel is open at first, when uncontrolled.
- `onOpenChange?` (`((open: boolean, details: ChangeDetails<CollapsibleOpenChangeReason>) => void)`): Runs when the panel wants to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `onOpenChangeComplete?` (`((open: boolean) => void)`): Runs once the panel has finished opening or closing, after any animation.
- `disabled?` (`boolean`): Stops the trigger from opening or closing the panel. The trigger stays focusable.
- `controller?` (`object`): Opens and closes the panel from anywhere. Create one with `createCollapsibleController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### CollapsibleTrigger
触发器没有自己的选项，只有它渲染出的元素的 props。

### CollapsiblePanel
- `keepMounted?` (`boolean`): Whether the panel stays in the page, hidden, while closed.
- `hiddenUntilFound?` (`boolean`): Keeps the closed panel in the page as `hidden="until-found"`, so the browser's find in page can match its text and open it.

### 状态
渲染函数、基于状态的类名和槽位按部件分别收到什么。触发器和面板收到与 collapsible 相同的
状态。

- `open` (`boolean`): Whether the panel is open.
- `disabled` (`boolean`): Whether the trigger ignores presses, by its own `disabled` or a disabled fieldset around it. The `open` option and the controller can still open and close it.

### 原因
`details.reason` 说明面板为什么打开或收起。

- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `find-in-page` (`Event`): The browser's find in page matched hidden content.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createCollapsibleController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，并在变更被取消或没有任何效果时返回 `false`。

- `isOpen()` (`() => boolean`): Whether the panel is open.
- `setOpen(open, options?)` (`(open: boolean, options?: CollapsibleChangeOptions | undefined) => boolean`): Opens or closes the panel. Returns false when the change was canceled or not possible.
- `open(options?)` (`(options?: CollapsibleChangeOptions | undefined) => boolean`): Opens the panel.
- `close(options?)` (`(options?: CollapsibleChangeOptions | undefined) => boolean`): Closes the panel.
- `toggle(options?)` (`(options?: CollapsibleChangeOptions | undefined) => boolean`): Opens the panel when it's closed, and closes it when it's open.
- `focus()` (`() => void`): Moves focus to the trigger.

### 事件
回调先收到新状态，再收到详情。

| Prop                   | 所属部件      | 收到                                            |
| ---------------------- | ------------- | ----------------------------------------------- |
| `onOpenChange`         | `Collapsible` | `(open, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/react/components/collapsible#reasons) |
| `onOpenChangeComplete` | `Collapsible` | `(open)`，在面板动画之后                        |

## 无障碍
Collapsible 遵循 [WAI-ARIA 披露模式](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/)。触发器用 `aria-expanded` 表示面板是否展开，并在面板挂载期间用 `aria-controls` 指向它。下面每一行都是一个自动化测试。

### 键盘
| 按键         | 作用                               |
| ------------ | ---------------------------------- |
| Enter, Space | 打开或收起面板。焦点留在触发器上。 |
| Tab          | 把焦点从触发器移进展开的面板       |

焦点在面板里时收起面板，焦点会移回触发器。

### 经过测试的行为
**Opening and closing**

- Starts closed, with the panel out of the page.
- Clicking the trigger opens the panel, and clicking again closes it.
- The trigger controls the panel.
- Generated ids start with ui-sdk-.
- It can start open.
- An opening can be canceled.
- A disabled collapsible doesn't open.
- A disabled trigger stays focusable and says it's disabled.
- A controller opens and closes it from anywhere.

**Keyboard**

- Enter toggles the panel and keeps focus on the trigger.
- Space toggles the panel and keeps focus on the trigger.
- Tab moves from the open trigger into the panel.
- Tab skips a closed panel.

**Mounting**

- With keepMounted, the closed panel stays in the page, hidden.
- With keepMounted, a class that sets display doesn't show the closed panel.
- With hiddenUntilFound, the closed panel stays findable.
- With hiddenUntilFound, a class that sets display keeps the closed panel findable.
- Finding text in the closed panel opens it.
- Following a link into the closed panel opens it.
- The browser's own find opens the closed panel.

Runs in React、Vue 和 web components.

在模式基线之外：

**Enhancements**

- Closing the panel while focus is inside it moves focus to the trigger.
- OnOpenChangeComplete runs once the animation has finished.
- An inert its owner writes during the exit stays once the exit ends.
- Find in page reports its own reason and opens without an animation.
- A canceled find in page keeps the panel hidden until found.
- An infinite exit animation still unmounts the panel.
- Parts report open and closed through data attributes.

Runs in React、Vue 和 web components.

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

- Announcements while using the collapsible with a keyboard.

Runs in React、Vue 和 web components.
