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

用 Collapsible 显示和隐藏一个内容面板。要处理一组面板时,用 Accordion。

import "@ui-sdk/web/collapsible"
import { ChevronDown, createElement } from "lucide"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-collapsible data-variant="card">
      <ui-collapsible-trigger>
        <button type="button" aria-expanded="false">
          <span data-slot="stack">
            <span>Order #4189</span>
            <span data-slot="hint">3 items, $84.00</span>
          </span>
          ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
        </button>
      </ui-collapsible-trigger>
      <ui-collapsible-panel hidden>
        ${items
          .map(
            (item) => `
              <div data-slot="row">
                <span>${item.name}</span>
                <span>${item.price}</span>
              </div>`
          )
          .join("")}
      </ui-collapsible-panel>
    </ui-collapsible>
  `
}

export { mount }
按 Order #4189,或者聚焦它后按 Enter 或 Space,显示这些条目。

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件来注册它的元素。这个导入在服务器上是安全的。

import "@ui-sdk/web/collapsible"

组合

用下面的组合来构建 ui-collapsible:

ui-collapsible
├── ui-collapsible-trigger
│   └── button
└── ui-collapsible-panel

触发器包住你自己的原生 button,根部件和面板是块级元素。在它们周围放其他内容,比如一个标题,或一段始终显示的摘要。

用法

导入各个部件并把它们组合起来:

<script type="module">
  import "@ui-sdk/web/collapsible"
</script>

<ui-collapsible>
  <ui-collapsible-trigger
    ><button>Order details</button></ui-collapsible-trigger
  >
  <ui-collapsible-panel hidden>2 × Linen shirt</ui-collapsible-panel>
</ui-collapsible>

自己构建

@ui-sdk/web/collapsible 自带现成的 ui-collapsible 元素。如果你想用自己的元素名构建一个,可以从 @ui-sdk/core 里的 collapsible 原语(primitive)开始:

spoiler-elements.ts
import { collapsible } from "@ui-sdk/core/collapsible"
import { createParts, wrappedButton } from "@ui-sdk/web"

createParts(collapsible, {
  root: "spoiler-box",
  trigger: {
    tag: "spoiler-toggle",
    target: wrappedButton,
    display: "contents",
  },
  panel: "spoiler-content",
})
<spoiler-box>
  <spoiler-toggle><button>Show the ending</button></spoiler-toggle>
  <spoiler-content hidden>The butler did it.</spoiler-content>
</spoiler-box>

每个元素都保留其现成对应元素的行为、状态和数据属性。更多内容见渲染原语和自定义部件。

禁用

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

<ui-collapsible disabled>
  <ui-collapsible-trigger><button>Gift options</button></ui-collapsible-trigger>
  <ui-collapsible-panel hidden
    >Add a gift message and wrapping.</ui-collapsible-panel
  >
</ui-collapsible>

保持挂载

收起的面板带着 hidden 留在页面里,所以 Tab 会跳过它们的内容,输入框里写的内容也会保留。在面板上设置 keep-mounted,让它在收起期间保持绑定,这样触发器的 aria-controls 仍然指向它。

import "@ui-sdk/web/collapsible"
import "@ui-sdk/web/field"
import "@ui-sdk/web/textarea"
import { ChevronDown, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-collapsible data-variant="card">
      <ui-collapsible-trigger>
        <button type="button" aria-expanded="false">
          <span data-slot="stack">
            <span>Add a delivery note</span>
            <span data-slot="hint">Optional, for the courier</span>
          </span>
          ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
        </button>
      </ui-collapsible-trigger>
      <ui-collapsible-panel keep-mounted hidden>
        <ui-field>
          <ui-field-label>Delivery note</ui-field-label>
          <ui-textarea>
            <textarea placeholder="Leave it with the front desk…"></textarea>
          </ui-textarea>
        </ui-field>
      </ui-collapsible-panel>
    </ui-collapsible>
  `
}

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

在页面中查找

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

在收起的面板上一并写上 hidden="until-found",让它在元素升级之前就能被找到。

import "@ui-sdk/web/collapsible"
import { ChevronDown, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-collapsible data-variant="card">
      <ui-collapsible-trigger>
        <button type="button" aria-expanded="false">
          <span data-slot="stack">
            <span>Ingredients</span>
            <span data-slot="hint">Morning buns, makes 12</span>
          </span>
          ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
        </button>
      </ui-collapsible-trigger>
      <ui-collapsible-panel hidden-until-found hidden="until-found">
        <p>Flour, butter, brown sugar, eggs, a pinch of cardamom and sea salt.</p>
      </ui-collapsible-panel>
    </ui-collapsible>
  `
}

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

受控

读取或设置元素的 open property。设置它会直接提交变更,不触发 openchange,就像原生输入框的 value。监听 openchange 来跟随人们做的变更,在它里面调用 event.preventDefault() 可以取消变更。

页面其他位置要放一个按钮时,调用元素的 api.toggle()、api.open() 或 api.close()。它的 api property 就是控制器。

控制台
import "@ui-sdk/web/collapsible"
import { ChevronDown, createElement } from "lucide"
import { log } from "./log"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Toggle</button>
      </div>
      <ui-collapsible data-variant="card">
        <ui-collapsible-trigger>
          <button type="button" aria-expanded="false">
            <span data-slot="stack">
              <span>Recovery codes</span>
              <span data-slot="hint">Each code signs you in once</span>
            </span>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-collapsible-trigger>
        <ui-collapsible-panel hidden>
          <div data-slot="stack">
            <ul>${recoveryCodes.map((code) => `<li>${code}</li>`).join("")}</ul>
            <button type="button">Done</button>
          </div>
        </ui-collapsible-panel>
      </ui-collapsible>
    </div>
  `
  const collapsible = root.querySelector("ui-collapsible")!
  root
    .querySelector("[data-slot=controls] button")!
    .addEventListener("click", () => collapsible.api.toggle())
  root
    .querySelector("ui-collapsible-panel button")!
    .addEventListener("click", () => collapsible.api.close())
  collapsible.addEventListener("openchange", (event) => {
    const { value, reason } = event.detail
    log(root, `${value ? "Opened" : "Closed"} (${reason})`)
  })
}

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

动画

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

[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;
  }
}

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

控制台
import "@ui-sdk/web/collapsible"
import { ChevronDown, createElement } from "lucide"
import { log } 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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-collapsible data-variant="card">
      <ui-collapsible-trigger>
        <button type="button" aria-expanded="false">
          <span data-slot="stack">
            <span>Release notes</span>
            <span data-slot="hint">Version 2.4, released October 28</span>
          </span>
          ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
        </button>
      </ui-collapsible-trigger>
      <ui-collapsible-panel hidden>
        <ul>
          ${notes.map((note) => `<li>${note}</li>`).join("")}
        </ul>
      </ui-collapsible-panel>
    </ui-collapsible>
  `
  root
    .querySelector("ui-collapsible")!
    .addEventListener("openchangecomplete", (event) => {
      log(root, event.detail.value ? "Finished opening" : "Finished closing")
    })
}

export { mount }
打开再收起 Release notes。每次动画结束时,控制台都会记录。

自定义渲染

触发器包住你自己的 button,把它放进标题里即可。在面板上设置 as-child,把它绑定到你自己的元素,这里是一个有序列表。元素没有渲染函数,所以摘要跟随根部件的 data-open。见部件与组合。

import "@ui-sdk/web/collapsible"
import { ChevronDown, createElement } from "lucide"

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 mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-collapsible data-variant="card">
      <h3>
        <ui-collapsible-trigger>
          <button type="button" aria-expanded="false">
            <span data-slot="stack">
              <span>Track parcel</span>
              <span data-slot="hint" data-show="open">3 updates</span>
              <span data-slot="hint" data-show="closed">Arrives Thursday</span>
            </span>
            ${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-collapsible-trigger>
      </h3>
      <ui-collapsible-panel as-child>
        <ol hidden>
          ${updates
            .map(
              (update) => `
                <li data-slot="row">
                  <span>${update.label}</span>
                  <span>${update.time}</span>
                </li>`
            )
            .join("")}
        </ol>
      </ui-collapsible-panel>
    </ui-collapsible>
  `
}

export { mount }
按 Track parcel,打开有序列表。摘要会从 Arrives Thursday 变成 3 updates。

样式

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

每个部件都有一个 data-slot,比如 collapsible-panel,它的状态属性列在数据属性下。

<ui-collapsible-panel>

变量内容
--collapsible-panel-heightThe panel's content height in pixels while it animates, auto once open and 0px while closed.
--collapsible-panel-widthThe panel's content width, the same way. For panels that open sideways.

数据属性

<ui-collapsible>

[data-slot="collapsible"]

属性含义
data-openPresent while the panel is open.
data-closedPresent while the panel is closed, including while it animates out.
data-disabledPresent when the collapsible can't open or close.

<ui-collapsible-trigger>

[data-slot="collapsible-trigger"]

属性含义
data-openPresent while the panel is open.
data-closedPresent while the panel is closed, including while it animates out.
data-disabledPresent when the collapsible can't open or close.

<ui-collapsible-panel>

[data-slot="collapsible-panel"]

属性含义
data-openPresent while the panel is open.
data-closedPresent while the panel is closed, including while it animates out.
data-disabledPresent when the collapsible can't open or close.
data-starting-stylePresent for the panel's first frame. Style the state you animate from.
data-ending-stylePresent while the panel animates closed. Style the state you animate to.

API 参考

Props 在 HTML 里写成 kebab 形式的属性,比如 default-open、keep-mounted 和 hidden-until-found:"false" 表示 false。回调是 DOM 事件。元素没有 controller 属性:它们的 api property 就是控制器。

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.
openchange event
Runs when the panel wants to open or close. details.reason says why, and details.cancel() stops it.
openchangecomplete event
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

触发器没有自己的选项。<ui-collapsible-trigger> 包住一个原生 button。

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.

状态

同样的状态会以数据属性的形式显示在每个元素上。

openboolean
Whether the panel is open.
disabledboolean
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.

原因

event.detail.reason 说明面板为什么打开或收起。

trigger-pressMouseEvent | 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-pageEvent
The browser's find in page matched hidden content.
imperativenone
A controller or api call.

控制器

元素的 api property 带有相同的方法。open property 读取并设置面板是否展开。

每个写入方法都接受可选的 { 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.

事件

事件在各自的元素上触发,不冒泡;新状态在 event.detail.value 里,reason 和 event 就在旁边。在 openchange 上调用 preventDefault() 会取消变更。

成员所属元素说明
open property, attributeui-collapsible面板是否展开。属性设置它一开始的状态,并且是实时的
api propertyui-collapsible控制器
openchange eventui-collapsibledetail: { value: open, reason, event, source }
openchangecomplete eventui-collapsibledetail: { value: open },在面板动画之后

无障碍

Collapsible 遵循 WAI-ARIA 披露模式。触发器用 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.

运行于 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.

运行于 React、Vue 和 web components。

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

  • Announcements while using the collapsible with a keyboard.

运行于 React、Vue 和 web components。