# Collapsible

One show/hide region: the Root _is_ the `<details>` and the Trigger its `<summary>`. Without open props its behaviour needs no JavaScript (the parts still ship as client modules; see [Server Components](../concepts/server-components.md)); with them it becomes a regular [state owner](../concepts/pending-and-optimistic.md#state-owner) with actions, optimistic `data-open` and lazily mounted content. For a set of disclosures with arrow-key navigation or one-open-at-a-time, use [Accordion](accordion.md).

## Anatomy

```tsx
import { Collapsible } from "@funstack/ui/collapsible";

<Collapsible.Root>          {/* details: state and the transition */}
  <Collapsible.Trigger>     {/* summary: must be the Root's first child */}
    Advanced options
  </Collapsible.Trigger>
  <Collapsible.Panel>       {/* div: the content */}
    ...
  </Collapsible.Panel>
</Collapsible.Root>
```

There is one Trigger and it must be the first child of the Root: that is where the platform puts a `<summary>`. A Trigger placed after the content or outside the Root is not possible; drive the Collapsible from elsewhere with controlled `open` instead ([recipe](#recipes)). A heading may go inside the Trigger. If you use `render`, the Root must still render a `<details>` and the Trigger a `<summary>` (development warning otherwise).

```tsx title="CollapsibleSpoiler.tsx"
// No "use client": this file is a Server Component. The Collapsible has none of `open`,
// `defaultOpen` and `openChangeAction`, so it runs in JS-free mode: the browser owns
// <details open>, and opening it works before hydration (and with JavaScript off).
import { Collapsible } from "@funstack/ui/collapsible";

export function CollapsibleSpoiler() {
  return (
    <Collapsible.Root className="demo-collapsible">
      <Collapsible.Trigger className="demo-collapsible-trigger">
        How does the story end?
      </Collapsible.Trigger>
      <Collapsible.Panel className="demo-collapsible-panel">
        <p>
          The zeppelin lands safely. Closed content stays in the page: search for the word zeppelin
          with your browser's find-in-page and it opens by itself.
        </p>
      </Collapsible.Panel>
    </Collapsible.Root>
  );
}
```

```css title="collapsible.css"
/* Collapsible: the Root is the <details>. `:open` is committed state (both modes);
   [data-open] is optimistic state (library mode only). */
.demo-collapsible {
  border: 1px solid var(--color-border);
  border-radius: 8px;
  overflow: hidden;
}

.demo-collapsible-trigger {
  display: flex;
  align-items: center;
  gap: 0.6em;
  padding: 0.6em 0.9em;
  cursor: pointer;
  font-weight: 600;
  list-style: none; /* hides the UA marker; the chevron below replaces it */
}

.demo-collapsible-trigger::-webkit-details-marker {
  display: none;
}

.demo-collapsible-trigger:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: -2px;
}

.demo-collapsible-trigger[data-pending] {
  cursor: progress;
}

.demo-collapsible-trigger[data-disabled] {
  color: GrayText;
  cursor: not-allowed;
}

/* Chevron. While pending, the optimistic attribute alone decides, so closing flips the chevron
   at once instead of waiting for :open to go. */
.demo-collapsible-trigger::before {
  content: "";
  inline-size: 0.5em;
  block-size: 0.5em;
  border-inline-end: 2px solid currentColor;
  border-block-end: 2px solid currentColor;
  rotate: -45deg;
  transition: rotate 150ms;
}

.demo-collapsible:open > .demo-collapsible-trigger:not([data-pending])::before,
.demo-collapsible-trigger[data-open]::before {
  rotate: 45deg;
}

/* Open/close animation on ::details-content (grid-rows form, every engine, both modes). */
.demo-collapsible::details-content {
  display: grid;
  grid-template-rows: 0fr;
  transition:
    grid-template-rows 200ms ease,
    content-visibility 200ms allow-discrete;
}

.demo-collapsible:open::details-content {
  grid-template-rows: 1fr;
}

.demo-collapsible-panel {
  min-height: 0; /* the grid item */
  overflow: hidden;
  padding: 0 0.9em;
}

.demo-collapsible-panel :is(p, ul) {
  margin: 0 0 0.8em;
}

@media (prefers-reduced-motion: reduce) {
  .demo-collapsible::details-content,
  .demo-collapsible-trigger::before {
    transition: none;
  }
}
```

## How it works

### Two modes

| | JS-free mode | Library mode |
| - | - | - |
| Selected when | Root has none of `open`, `defaultOpen`, `openChangeAction` | Root has any of them (`defaultOpen={false}` included) |
| Open state owner | the browser | React (committed state) |
| Initial open | closed | `defaultOpen` / `open` |
| `data-open`, `data-pending` | not emitted; style with `:open` | emitted (optimistic) |
| Works before hydration | yes, fully | yes; reconciled on mount |
| `transition` (Root, Panel) | no effect (development warning) | animates the commit that ends an action |
| `state.open` | `false` (React holds no value) | optimistic (Panel: committed) |

A Collapsible that starts open is in library mode: `defaultOpen` selects it. The HTML is the same `<details open>` and it toggles natively before hydration; after hydration the toggle runs through the Root's transition, which with no action commits at once. See [Browser-owned state](../concepts/browser-owned-state.md) for the reasoning. Switching modes after mount is not supported.

## Props

### `Collapsible.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `open` | `boolean` | – | Controlled open state. undefined means uncontrolled. Selects library mode. |
| `defaultOpen` | `boolean` | `none (JS-free mode)` | Initial open state, uncontrolled; read once. Its presence selects library mode, false included. Library mode without it (open or openChangeAction only) starts closed, as false. |
| `openChangeAction` | `ChangeAction<boolean, CollapsibleOpenChangeDetails>` | – | Called with the next open state on every change, inside the Root's transition. Sync, async or a Server Function. `details.reason` (a `ChangeReason`) is `"activate"` for the Trigger, or `"platform"` when the browser opened or closed the `<details>` itself. There is no `onOpenChange`: every change is a request. Selects library mode. |
| `disabled` | `boolean` | `false` | The Trigger gets aria-disabled="true" and never toggles. Enforced by a click handler, so in JS-free mode it does not hold before hydration. A click on a disabled control runs no `onClick`, a `render` element's included ([unavailable parts](../concepts/render.md#unavailable)). |
| `experimental_interpolateSize` | `boolean` | `false` | Sets `interpolate-size: allow-keywords` on the `<details>` so `::details-content` can transition `height` to `auto`. Chromium only today; merged under your `style`. Both modes. |
| `transition` | `ViewTransitionClass` | – | Library mode only. The class of the `<ViewTransition>` around the `<details>`. A string animates this Collapsible's own opens and closes (the commit that ends the action) and its own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)); another Collapsible, content that changes inside and an unrelated transition start none. A controlled `open` you change in your own transition needs a map keyed on `fsui-collapsible-open` / `-close` plus `addTransitionType`. A type map is React's: it names every Collapsible that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). |
| `className` | `string \| ((state: CollapsibleRootState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: CollapsibleRootState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: CollapsibleRootState) => ReactNode)` | – | Content, or a function of the Root's state. The Trigger must come first. |
| `render` | `ReactElement \| ((props, state: CollapsibleRootState) => ReactNode)` | – | Replace the default \<details> (element form) or take over rendering (function form). |

- **State**: `CollapsibleRootState` is `{ open, pending, disabled }`; `open` is optimistic, and `false` in JS-free mode (the browser owns it and React holds no value; style with `:open`).
- **Owned**: `open`, `name`, `suppressHydrationWarning`, `data-open`, `data-pending`, `data-disabled`, and `onToggle` in library mode.

### `Collapsible.Trigger`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: CollapsibleTriggerState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: CollapsibleTriggerState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: CollapsibleTriggerState) => ReactNode)` | – | Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: CollapsibleTriggerState) => ReactNode)` | – | Replace the default \<summary> (element form) or take over rendering (function form). |

- **State**: `CollapsibleTriggerState` is the Root's state.
- **Owned**: `aria-disabled`, `data-open`, `data-pending`, `data-disabled`, and `onClick` in library mode (and when disabled).

No `disabled` prop: the Root carries it, and `aria-disabled` is owned. No `transition` prop: everything the Trigger renders is optimistic, and the Root's boundary covers it; animate `data-open` with CSS. Links and form controls inside the summary keep their own behaviour and do not toggle.

### `Collapsible.Panel`

| Prop | Type | Default | Description |
| - | - | - | - |
| `transition` | `ViewTransitionClass` | – | Library mode only. The class of the `<ViewTransition>` around the panel's `div`. A string animates content that mounts or changes in this Collapsible's own opens and closes, and the Panel's own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)). A type map is React's: it names every Panel that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). |
| `className` | `string \| ((state: CollapsiblePanelState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: CollapsiblePanelState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: CollapsiblePanelState) => ReactNode)` | – | Always mounted. The function form receives committed open: use it to mount content lazily (library mode). |
| `render` | `ReactElement \| ((props, state: CollapsiblePanelState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `CollapsiblePanelState` is `{ open, disabled }`; `open` is committed (`false` in JS-free mode).
- **Owned**: `data-disabled`.

No `keepMounted`: closed content is always in the DOM, which keeps it searchable. No `data-open` either: select `details:open > .panel`. A popup open inside the Panel when it closes leaves the screen with it, still open and with no `onOpenChange`, and is shown again without moving focus when it opens (a modal Dialog takes focus); one open on mount inside a closed Panel is shown when it opens. A popup in JS-free mode inside it is closed with it.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `:open` | Root (`details`) | Committed open state, both modes. |
| `data-open` | Root, Trigger | Optimistic open state (library mode only). |
| `data-pending` | Root, Trigger | Library mode: an action is in flight. |
| `data-disabled` | Root, Trigger, Panel | The Root's `disabled` prop. |
| `aria-disabled` | Trigger | `"true"` when disabled. |
| `::details-content` | Root | The native content slot: animate it. |

```css
.c > summary { list-style: none; }                /* hide the UA marker */
.c > summary::-webkit-details-marker { display: none; }
.c > summary::before { content: "▸" / ""; }  /* empty alt text: not in the name */
.c:open > summary:not([data-pending])::before,
.c > summary[data-open]::before { content: "▾" / ""; }   /* flips at once in library mode */

/* Open/close animation, every engine, both modes */
.c::details-content {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 200ms ease, content-visibility 200ms allow-discrete;
}
.c:open::details-content { grid-template-rows: 1fr; }
.c > .panel { min-height: 0; overflow: hidden; }

@media (prefers-reduced-motion: reduce) {
  .c::details-content { transition: none; }
}
```

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| Enter / Space | Trigger | Toggles (native). |
| Tab / Shift+Tab | anywhere | The Trigger is a Tab stop; closed content is skipped. |

- The `<details>` is a group and the summary the engine's disclosure control, with its expanded state from `open`. No `aria-*` is added except `aria-disabled`.
- HTML forbids `aria-expanded` on a summary, so assistive technology hears the committed state; `data-open` is visual only. For an audible pending state, render an `aria-live` region from the Trigger's state.
- The accessible name is the Trigger's content; a label that changes ("Show replies" / "Hide replies") is announced through the name, on top of the expanded state.
- A disabled Trigger stays focusable. Focus never moves on open or close.

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

Library mode: `fsui-collapsible` plus `fsui-collapsible-open` or `fsui-collapsible-close`, the kinds of every open state in the library. JS-free mode starts no transitions. These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

Library mode: the Root and Trigger show the optimistic open state (`data-open`) and `data-pending` while an action is in flight. The `<details>` element (`:open`, and what assistive technology hears) and the Panel's function child follow the committed state. A second click while pending reverses the first; `data-pending` stays until both actions have settled. JS-free mode has no optimistic or pending state.

### Walkthrough (async action)

```tsx title="CollapsibleFilters.tsx"
"use client";
import { startTransition, useState } from "react";
import { Collapsible } from "@funstack/ui/collapsible";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

// Library mode with an async action: every toggle saves the preference first (0.8 s) and the
// panel opens or closes when the save resolves. Meanwhile the chevron already shows the
// optimistic state (`data-open`) and the trigger is `data-pending`. Tick "fail" to see a
// rejected save: `data-open` reverts and the error goes to the nearest Error Boundary.
export function CollapsibleFilters() {
  const [fail, setFail] = useState(false);
  const [saved, setSaved] = useState<boolean | null>(null);
  return (
    <>
      <DemoErrorBoundary>
        <Collapsible.Root
          className="demo-collapsible"
          openChangeAction={async (open) => {
            await fakeSave("the preference", { fail });
            startTransition(() => setSaved(open)); // after an await: re-wrap (React limitation)
          }}
        >
          <Collapsible.Trigger className="demo-collapsible-trigger">Filters</Collapsible.Trigger>
          <Collapsible.Panel className="demo-collapsible-panel">
            <p>Price, brand and rating filters would go here.</p>
          </Collapsible.Panel>
        </Collapsible.Root>
      </DemoErrorBoundary>
      <label className="demo-readout">
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> fail
        the next save
      </label>
      <output className="demo-readout">
        saved: <code>{saved === null ? "nothing yet" : saved ? "open" : "closed"}</code>
      </output>
    </>
  );
}
```

`collapsible.css`: the same file as above.

1. Click the Trigger: the click is intercepted, the chevron flips (`data-open`), the Root and Trigger get `data-pending`, and `openChangeAction(true, { reason: "activate" })` runs.
2. The save resolves: the `<details>` opens (committed state) and `data-pending` goes.
3. If the action rejects, `data-open` reverts, the content never opens, and the error goes to the nearest Error Boundary.

> **Find-in-page in library mode**
>
> The browser opens a closed Collapsible when find-in-page or a text fragment matches its content. That is dispatched as `reason: "platform"` with the `toggle` event; the content stays visible while the action runs. If a controlled parent does not adopt the change, it is closed again when the action settles; a rejection goes to the nearest Error Boundary. A disabled Collapsible is re-closed without dispatching. A reveal while a close is pending is dispatched too; a match in content that is still open while its close is pending changes nothing the browser reports, so the close commits and hides it.

## Suspense

Concept: [Suspense](../concepts/suspense.md)

The Panel is always mounted; its function child receives the committed `open`, which is how you mount content lazily (library mode: `defaultOpen={false}` is enough). If that content suspends, the `<details>` stays closed with the Trigger pending until the content is ready, then opens. Trigger content must not suspend.

```tsx title="CollapsibleReplies.tsx"
"use client";
import { use } from "react";
import { Collapsible } from "@funstack/ui/collapsible";
import { sleep } from "./fake-api.js";

let replies: Promise<string[]> | undefined;
function loadReplies(): Promise<string[]> {
  replies ??= sleep(1200).then(() => ["Looks good to me.", "Ship it!", "One nit, see inline."]);
  return replies;
}

function ReplyList() {
  return (
    <ul>
      {use(loadReplies()).map((reply) => (
        <li key={reply}>{reply}</li>
      ))}
    </ul>
  );
}

// Library mode without an action: `defaultOpen={false}` alone selects it. The Panel's function
// child mounts <ReplyList> only once the Collapsible is open in committed state. The replies
// suspend for 1.2 s; because opening is a transition, the <details> stays closed with a spinner
// on the trigger until the data is ready, then opens with its content. No Suspense fallback.
export function CollapsibleReplies() {
  return (
    <Collapsible.Root defaultOpen={false} className="demo-collapsible">
      <Collapsible.Trigger className="demo-collapsible-trigger">
        {({ open, pending }) => (
          <>
            {open ? "Hide replies" : "Show 3 replies"}
            {pending && <span className="demo-spinner" aria-hidden />}
          </>
        )}
      </Collapsible.Trigger>
      <Collapsible.Panel className="demo-collapsible-panel">
        {({ open }) => open && <ReplyList />}
      </Collapsible.Panel>
    </Collapsible.Root>
  );
}
```

`collapsible.css`: the same file as above.

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

JS-free mode: the browser owns `<details open>`; style with `:open` and animate with `::details-content`. Library mode: open state is library-owned, but the browser can still open or close the `<details>` (find-in-page, a text fragment, a click before hydration). That is dispatched with `reason: "platform"`, and the committed state is re-applied once the action settles.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

JS-free mode: everything: open and close, Enter and Space, find-in-page, CSS animation. Hydration only adds `disabled`. Library mode: the native toggle; a Collapsible toggled before hydration is reconciled on mount with one `openChangeAction` call (`reason: "platform"`, no event).

## Recipes

### Remember the open state with a Server Function

```tsx
// Server Component
import { rememberOpen } from "./actions"; // "use server"

<Collapsible.Root defaultOpen={prefs.filtersOpen} openChangeAction={rememberOpen.bind(null, "filters")}>
  <Collapsible.Trigger>Filters</Collapsible.Trigger>
  <Collapsible.Panel><Filters /></Collapsible.Panel>
</Collapsible.Root>
```

Every toggle waits for the round trip. For a toggle that should not wait, pass a client function that calls the Server Function without returning its promise.

### Open from a control elsewhere

```tsx
"use client";
const [open, setOpen] = useState(false);

<button type="button" onClick={() => setOpen(true)}>Show details</button>

<Collapsible.Root open={open} openChangeAction={setOpen}>
  <Collapsible.Trigger>Details</Collapsible.Trigger>
  <Collapsible.Panel>...</Collapsible.Panel>
</Collapsible.Root>
```

One setter serves both: the Trigger's click and a find-in-page reveal arrive through `openChangeAction`. The outside control is your own button; give it `aria-expanded` and `aria-controls` if it needs them.

Its `onClick` sets the state with an [urgent update](../concepts/action-props.md#urgent-update), so the panel opens while a save is pending elsewhere in the app. A `Button` with `action={() => setOpen(true)}` would set it in a transition, which waits for that save (1.4 s in a test with a 1.5 s save; the urgent click took under 20 ms). The Trigger's own toggle goes through `openChangeAction` and waits too, because the Root is controlled ([Pending actions hold other transitions](../concepts/action-props.md#pending-actions-hold-transitions)).

### Animate the box with ViewTransition

```tsx
<Collapsible.Root defaultOpen={false} transition="grow">...</Collapsible.Root>
```

Use either the `transition` prop or a `::details-content` CSS transition for a given change, not both. Content after the Collapsible jumps unless you give it a `<ViewTransition>` of its own.
