# Accordion

Built on `<details>` and `<summary>`. Without value 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 Suspense-friendly panels.

For one disclosure on its own, use [Collapsible](collapsible.md): the same `<details>` base without the wrapper, with its own `open` / `openChangeAction`. An `Accordion.Item` outside any Root still works as a JS-free disclosure, but it has no library mode.

## Anatomy

```tsx
import { Accordion } from "@funstack/ui/accordion";

<Accordion.Root>                     {/* div: state, keyboard navigation */}
  <Accordion.Item value="shipping">  {/* details */}
    <Accordion.Trigger>              {/* summary: must be the Item's first child */}
      <h3>Shipping</h3>
    </Accordion.Trigger>
    <Accordion.Panel>                {/* div: the content */}
      We ship worldwide.
    </Accordion.Panel>
  </Accordion.Item>
</Accordion.Root>
```

There is no Header part: the only valid place for a heading is inside the `<summary>`, so put it in the Trigger. If you use `render`, the Item must still render a `<details>` and the Trigger a `<summary>` (development warning otherwise).

```tsx title="AccordionFaq.tsx"
// No "use client": this file is a Server Component. The Accordion has no value props, so it runs
// in JS-free mode: the browser owns <details open>, `exclusive` becomes the native `name` group,
// and opening an item works before hydration (and with JavaScript off).
import { Accordion } from "@funstack/ui/accordion";

const faq = [
  {
    id: "what",
    question: "What is FUNSTACK UI?",
    answer:
      "A headless React component library built for Async React: transitions by default, action props, Suspense-native content.",
  },
  {
    id: "js",
    question: "Does this accordion need JavaScript?",
    answer:
      "No. It renders <details> and <summary>. Try your browser's find-in-page for the word zeppelin: the browser opens the matching item by itself.",
  },
  {
    id: "zeppelin",
    question: "Is anything hidden in here?",
    answer: "Only a zeppelin, to show that closed items stay searchable.",
  },
];

export function AccordionFaq() {
  return (
    <Accordion.Root exclusive className="demo-accordion">
      {faq.map((item, index) => (
        <Accordion.Item
          key={item.id}
          value={item.id}
          defaultOpen={index === 0}
          className="demo-accordion-item"
        >
          <Accordion.Trigger className="demo-accordion-trigger">
            <h4>{item.question}</h4>
          </Accordion.Trigger>
          <Accordion.Panel className="demo-accordion-panel">
            <p>{item.answer}</p>
          </Accordion.Panel>
        </Accordion.Item>
      ))}
    </Accordion.Root>
  );
}
```

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

.demo-accordion-item + .demo-accordion-item {
  border-top: 1px solid var(--color-border);
}

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

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

.demo-accordion-trigger h4 {
  flex: 1;
  margin: 0;
  font-size: 1rem;
}

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

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

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

/* Chevron. While an item is pending, the optimistic attribute alone decides, so closing an open
   item flips the chevron at once instead of waiting for :open to go. */
.demo-accordion-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-accordion-item:open > .demo-accordion-trigger:not([data-pending])::before,
.demo-accordion-trigger[data-open]::before {
  rotate: 45deg;
}

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

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

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

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

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

## How it works

### Two modes

| | JS-free mode | Library mode |
| - | - | - |
| Selected when | Root has none of `value`, `defaultValue`, `valueChangeAction` | Root has any of them |
| Open state owner | the browser | React (committed state) |
| Initial open | `Item defaultOpen` | `Root defaultValue` / `value` |
| `exclusive` | native `<details name>` group | the library keeps at most one value |
| `data-open`, `data-pending` | not emitted; style with `:open` | emitted (optimistic) |
| Works before hydration | yes, fully | yes; reconciled on mount |
| `transition` (Item, Panel) | no effect (development warning) | animates the commit that ends an action |
| `state.open` | `false` (React holds no value) | optimistic (Panel: committed) |

See [Browser-owned state](../concepts/browser-owned-state.md) for the reasoning. Switching modes after mount is not supported.

## Props

### `Accordion.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `exclusive` | `boolean` | `false` | At most one item open. Also decides the value type: `V \| null` when exclusive, `V[]` otherwise. Fixed at mount: a later change is ignored (development warning). |
| `value` | `readonly V[] \| V \| null (exclusive)` | – | Controlled open items. undefined means uncontrolled; \[] or null means none open. Selects library mode. `V` is the item value type: a declared union you pass is kept, a literal is `string` ([Typed values](../concepts/action-props.md#typed-values)). |
| `defaultValue` | `readonly V[] \| V \| null (exclusive)` | – | Initial open items in uncontrolled library mode. Selects library mode. |
| `valueChangeAction` | `ChangeAction<V[] \| V \| null, AccordionValueChangeDetails<V>>` | – | Called with the next open items on every change, inside the Root's transition. Sync, async or a Server Function. `details`: `reason` (a `ChangeReason`; Accordion dispatches `"activate"` or `"platform"`), `added` (the items the change opened) and `removed` (the items it closed), the diff every set-valued component reports, in document order. With `exclusive`, opening B while A is open is `added: ["b"]`, `removed: ["a"]`. In multiple mode the array lists items in document order. Selects library mode. |
| `disabled` | `boolean` | `false` | Disables every item: Triggers get aria-disabled="true" and never toggle. A click on a disabled control runs no `onClick`, a `render` element's included ([unavailable parts](../concepts/render.md#unavailable)). |
| `loop` | `boolean` | `true` | ArrowDown on the last Trigger moves to the first and ArrowUp on the first to the last. With false the arrows stop at the ends. |
| `experimental_interpolateSize` | `boolean` | `false` | Sets `interpolate-size: allow-keywords` on the root so `::details-content` can transition `height` to `auto`. Chromium only today; merged under your `style`. |
| `className` | `string \| ((state: AccordionRootState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: AccordionRootState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: AccordionRootState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: AccordionRootState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `AccordionRootState` is `{ value, pending, disabled }`; `value` is the optimistic open items in document order, always an array (one entry at most with `exclusive`), and `[]` in JS-free mode.
- **Owned**: `onKeyDown`, `data-pending`, `data-disabled`.

### `Accordion.Item`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required in both modes. Identifies the item in the Root's value. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `defaultOpen` | `boolean` | `false` | JS-free mode only: renders the initial open attribute. Ignored in library mode (development warning). |
| `disabled` | `boolean` | `false` | The Trigger gets aria-disabled 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)). |
| `transition` | `ViewTransitionClass` | – | Library mode only. The class of the `<ViewTransition>` around the `<details>`. A string animates this item'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)); the other items are not named and cross-fade with the page. To make them slide, give every Item the map `{ "fsui-accordion-open": "auto", "fsui-accordion-close": "auto", default: "none" }` and keep the string on the Panel ([recipe](../concepts/transitions.md#siblings)). A controlled `value` you change in your own transition needs a map keyed on `fsui-accordion-open` / `-close` plus `addTransitionType`. A type map is React's: it names every Item 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: AccordionItemState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: AccordionItemState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: AccordionItemState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: AccordionItemState) => ReactNode)` | – | Replace the default \<details> (element form) or take over rendering (function form). |

- **State**: `AccordionItemState` is `{ value, 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.

### `Accordion.Trigger`

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

- **State**: `AccordionTriggerState` is the Item's state.
- **Owned**: `aria-disabled`, `data-open`, `data-pending`, `data-disabled`, and `onClick` in library mode (and on disabled items).

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

### `Accordion.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 item'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 control inside the Panel and another item's change start none. 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: AccordionPanelState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: AccordionPanelState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: AccordionPanelState) => ReactNode)` | – | Always mounted. The function form receives committed open: use it to mount content lazily. |
| `render` | `ReactElement \| ((props, state: AccordionPanelState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

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

Panels have no `keepMounted`: closed content is always in the DOM, which keeps it searchable. A popup open inside a panel that closes (a Popover, Menu, Combobox, Dialog) leaves the screen with it, still open and with no `onOpenChange`, and is shown again without moving focus when the panel opens (a modal Dialog takes focus); one open on mount inside a closed panel is shown when the panel opens. A popup in JS-free mode inside it is closed with it.

## Data attributes

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

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

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

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

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| Enter / Space | Trigger | Toggles the Item (native). |
| Tab / Shift+Tab | anywhere | Every Trigger is a Tab stop. |
| ArrowDown / ArrowUp | Trigger | Next / previous Trigger in the same Root, disabled ones included; wraps if `loop`. |
| Home / End | Trigger | First / last Trigger, disabled or not. |
| Any of these with Alt, Ctrl or Meta, or already default-prevented | Trigger | Not handled: the key is the browser's (Ctrl+Home scrolls the page). |

- The summary's disclosure role and expanded state are native. 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.
- Disabled Triggers stay focusable and the arrow keys reach them, so they are announced as unavailable. Focus never moves on open or close.

## Transition types

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

Library mode: `fsui-accordion`, plus `fsui-accordion-open` when the change opened an item (`details.added` is non-empty) and `fsui-accordion-close` when it closed one (`details.removed` is non-empty); an exclusive switch carries both. 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 Item and Trigger show the optimistic open state (`data-open`) and `data-pending` while their open state is changing; the Root carries `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. JS-free mode has no optimistic or pending state.

### Walkthrough (library mode)

```tsx title="AccordionThreads.tsx"
"use client";
import { use, useState } from "react";
import { Accordion } from "@funstack/ui/accordion";
import { sleep } from "./fake-api.js";

const cache = new Map<string, Promise<string[]>>();
function loadReplies(thread: string): Promise<string[]> {
  let promise = cache.get(thread);
  if (promise === undefined) {
    promise = sleep(1200).then(() => [`First reply to ${thread}`, `Second reply to ${thread}`]);
    cache.set(thread, promise);
  }
  return promise;
}

function Replies({ thread }: { thread: string }) {
  const replies = use(loadReplies(thread));
  return (
    <ul>
      {replies.map((reply) => (
        <li key={reply}>{reply}</li>
      ))}
    </ul>
  );
}

const threads = ["Release planning", "Bug triage", "Design review"];

// Library mode (controlled, exclusive). The Panel's function child mounts <Replies> only once
// the item is open in committed state. Replies suspend for 1.2 s; because opening is a
// transition, the item stays closed with a spinner on its trigger until the data is ready, then
// opens with its content. No Suspense fallback is ever shown.
export function AccordionThreads() {
  const [open, setOpen] = useState<string | null>(null);
  return (
    <>
      <Accordion.Root
        exclusive
        className="demo-accordion"
        value={open}
        valueChangeAction={(next) => {
          setOpen(next); // sync prefix: a Transition update
        }}
      >
        {threads.map((thread) => (
          <Accordion.Item key={thread} value={thread} className="demo-accordion-item">
            <Accordion.Trigger className="demo-accordion-trigger">
              {({ pending }) => (
                <>
                  <h4>{thread}</h4>
                  {pending && <span className="demo-spinner" aria-hidden />}
                </>
              )}
            </Accordion.Trigger>
            <Accordion.Panel className="demo-accordion-panel">
              {({ open }) => open && <Replies thread={thread} />}
            </Accordion.Panel>
          </Accordion.Item>
        ))}
      </Accordion.Root>
      <output className="demo-readout">
        value: <code>{JSON.stringify(open)}</code>
      </output>
    </>
  );
}
```

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

1. Click a Trigger: the click is intercepted, the chevron flips (`data-open`), the item and Trigger get `data-pending`, and `valueChangeAction(next, { reason: "activate", added: [item], removed: [] })` runs.
2. The commit renders the Panel's function child with `open: true`; the replies suspend, so React holds the commit. The `<details>` stays closed.
3. The data arrives: the item opens with its content in one commit, and `data-pending` goes.
4. If the action rejects, `data-open` reverts, the item never opens, and the error goes to the nearest Error Boundary.

> **Find-in-page in library mode**
>
> The browser opens a closed item when find-in-page or a text fragment matches its content. The Accordion dispatches that as `reason: "platform"` with the `toggle` event. If a controlled parent does not adopt the change, the item is closed again when the action settles. Disabled items are re-closed without dispatching. A reveal while the item's 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. If that content suspends, the item stays closed with the Trigger pending until the content is ready, then opens. Trigger content must not suspend.

## Browser-owned state

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

JS-free mode: the browser owns every `<details open>`, and `exclusive` is the native `name` group; style with `:open` and animate with `::details-content`. Library mode: open state is library-owned, but the browser can still open a closed item (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, the `exclusive` group (`<details name>`), find-in-page, CSS animation. Hydration only adds arrow-key navigation and `disabled`. Library mode: the native toggle; items opened before hydration are reconciled on mount with one `valueChangeAction` call (`reason: "platform"`).

## Recipes

### Persist open sections with a Server Function

```tsx
// Server Component
<Accordion.Root defaultValue={user.openSections} valueChangeAction={saveOpenSections}>
  ...
</Accordion.Root>
```

### Animate item boxes with ViewTransition

```tsx
<Accordion.Root exclusive defaultValue={null} valueChangeAction={save}>
  <Accordion.Item value="a" transition="grow">...</Accordion.Item>
</Accordion.Root>
```

Use either the `transition` prop or a `::details-content` CSS transition for a given change, not both. The string animates the item that opened or closed only: the items below it are not named and cross-fade to their new place with the page.

### Slide the other items with the change

To make the items below travel, name every Item with a map that uses `"auto"` (the browser's move and resize) and keep the string on the Panel, which animates the changed item's content alone:

```tsx
const move = { "fsui-accordion-open": "auto", "fsui-accordion-close": "auto", default: "none" };

<Accordion.Item value="a" transition={move}>
  <Accordion.Trigger>Shipping</Accordion.Trigger>
  <Accordion.Panel transition="fade">...</Accordion.Panel>
</Accordion.Item>
```

A map with a class of your own that has motion makes every Item play it, changed or not, so keep maps to `"auto"` here. Every named Item takes no clicks while the view transition runs ([Input during a view transition](../concepts/transitions.md#input)).
