# Accordion
Stacked sections that open and close under their headings.
Source page: https://dinachi.dev/docs/components/accordion

## Installation
```bash
npx @dinachi/cli@latest add accordion
```
Adds to your project:
- `components/ui/accordion/accordion.tsx`
- `components/ui/accordion/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `lucide-react` ^0.552.0

## Usage
```tsx
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@/components/ui/accordion"

export function Faq() {
  return (
    <Accordion aria-label="FAQ" defaultValue={["returns"]}>
      <AccordionItem value="returns">
        <AccordionHeader>
          <AccordionTrigger>Returns</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>Send it back within 30 days for a full refund.</AccordionPanel>
      </AccordionItem>
      <AccordionItem value="shipping">
        <AccordionHeader>
          <AccordionTrigger>Shipping</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>Orders leave the warehouse within two working days.</AccordionPanel>
      </AccordionItem>
    </Accordion>
  )
}
```

## Anatomy
```tsx
<Accordion>
  <AccordionItem>
    <AccordionHeader>
      <AccordionTrigger />
    </AccordionHeader>
    <AccordionPanel />
  </AccordionItem>
</Accordion>
```
- `Accordion`: Holds which items are open.
- `AccordionItem`: One section; its own disclosure to agents.
- `AccordionHeader`: The heading that wraps the trigger.
- `AccordionTrigger`: Toggles its item; built-in chevron turns when open.
- `AccordionPanel`: The content, animated by height.

## Examples

### Default
One item open at a time.
```tsx
import { Accordion, AccordionItem, AccordionHeader, AccordionTrigger, AccordionPanel } from '@/components/ui/accordion';

export function Example() {
  return (
    <Accordion defaultValue={["item-1"]} className="w-full">
      <AccordionItem value="item-1">
        <AccordionHeader>
          <AccordionTrigger>Is it accessible?</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Yes. It adheres to the WAI-ARIA design pattern.
        </AccordionPanel>
      </AccordionItem>
      <AccordionItem value="item-2">
        <AccordionHeader>
          <AccordionTrigger>Is it styled?</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Yes. It comes with default styles.
        </AccordionPanel>
      </AccordionItem>
    </Accordion>
  );
}
```

### Multiple
Several items open at once.
```tsx
import { Accordion, AccordionItem, AccordionHeader, AccordionTrigger, AccordionPanel } from '@/components/ui/accordion';

export function Example() {
  return (
    <Accordion multiple className="w-full">
      <AccordionItem value="item-1">
        <AccordionHeader>
          <AccordionTrigger>Getting Started</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Start by installing the required dependencies.
        </AccordionPanel>
      </AccordionItem>
      <AccordionItem value="item-2">
        <AccordionHeader>
          <AccordionTrigger>Configuration</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Configure your project with the following steps.
        </AccordionPanel>
      </AccordionItem>
    </Accordion>
  );
}
```

### Controlled
The open items held in React state.
```tsx
import * as React from 'react';
import { Accordion, AccordionItem, AccordionHeader, AccordionTrigger, AccordionPanel } from '@/components/ui/accordion';

export function Example() {
  const [value, setValue] = React.useState(["features"]);

  return (
    <div className="w-full space-y-4">
      <div className="rounded-lg border border-dashed border-border p-3 text-sm text-muted-foreground">
        Controlled value: {value.length > 0 ? value.join(", ") : "none"}
      </div>

      <Accordion
        value={value}
        onValueChange={(nextValue) => setValue(nextValue as string[])}
      >
        <AccordionItem value="features">
          <AccordionHeader>
            <AccordionTrigger>Features</AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            Our component library includes over 20 production-ready components with full TypeScript support.
          </AccordionPanel>
        </AccordionItem>
        <AccordionItem value="pricing">
          <AccordionHeader>
            <AccordionTrigger>Pricing</AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            DinachiUI is completely free and open source. Use it in your personal and commercial projects.
          </AccordionPanel>
        </AccordionItem>
        <AccordionItem value="support">
          <AccordionHeader>
            <AccordionTrigger>Support</AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            Get support through our GitHub issues, Discord community, or comprehensive documentation.
          </AccordionPanel>
        </AccordionItem>
      </Accordion>
    </div>
  );
}
```

### Disabled item
One item locked while the rest stay interactive.
```tsx
import { Accordion, AccordionItem, AccordionHeader, AccordionTrigger, AccordionPanel } from '@/components/ui/accordion';

export function Example() {
  return (
    <Accordion defaultValue={["available"]} className="w-full">
      <AccordionItem value="available">
        <AccordionHeader>
          <AccordionTrigger>Available Section</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          This item is interactive and behaves like a standard accordion section.
        </AccordionPanel>
      </AccordionItem>
      <AccordionItem value="disabled" disabled>
        <AccordionHeader>
          <AccordionTrigger>Disabled Section</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Disabled accordion items keep their structure but ignore pointer and keyboard interaction.
        </AccordionPanel>
      </AccordionItem>
      <AccordionItem value="notes">
        <AccordionHeader>
          <AccordionTrigger>Notes</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          Use item-level disabled when only one section should be locked while the rest remain interactive.
        </AccordionPanel>
      </AccordionItem>
    </Accordion>
  );
}
```

### Keep mounted
A closed panel keeps its field state, and the item reports each change.
```tsx
import * as React from 'react';
import { Accordion, AccordionItem, AccordionHeader, AccordionTrigger, AccordionPanel } from '@/components/ui/accordion';

export function Example() {
  const [draft, setDraft] = React.useState("Draft notes stay mounted between toggles.");
  const [events, setEvents] = React.useState<Array<{ id: number; message: string }>>([]);

  return (
    <div className="w-full space-y-4">
      <Accordion className="w-full">
        <AccordionItem
          value="draft"
          onOpenChange={(open) => {
            setEvents((current) => [
              {
                id: Date.now() + current.length,
                message: `${open ? "Opened" : "Closed"} draft section`,
              },
              ...current,
            ].slice(0, 3));
          }}
        >
          <AccordionHeader>
            <AccordionTrigger>Persistent Draft</AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel keepMounted>
            <div className="space-y-3">
              <p className="text-muted-foreground">
                This panel uses keepMounted, so field state is preserved after collapse.
              </p>
              <textarea
                value={draft}
                onChange={(event) => setDraft(event.target.value)}
                className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              />
            </div>
          </AccordionPanel>
        </AccordionItem>

        <AccordionItem value="search">
          <AccordionHeader>
            <AccordionTrigger>Find-in-Page Friendly Content</AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel hiddenUntilFound>
            Content inside this panel can be revealed by the browser's built-in find-in-page when hiddenUntilFound is enabled.
          </AccordionPanel>
        </AccordionItem>
      </Accordion>

      <div className="rounded-lg border border-dashed border-border p-3 text-sm text-muted-foreground">
        <p className="font-medium text-foreground">Recent item events</p>
        <ul className="mt-2 space-y-1">
          {events.length > 0 ? (
            events.map((event) => <li key={event.id}>{event.message}</li>)
          ) : (
            <li>Open or close the draft section to see item-level events.</li>
          )}
        </ul>
      </div>
    </div>
  );
}
```

## Notes

### Values are arrays
`value` and `defaultValue` are always arrays, even when `multiple` is false. When controlled, give each item a `value`.

### Horizontal layouts
The bundled styles are vertical. A horizontal accordion needs its own styling.

## API reference
Props marked **agent** change what an agent reads or may do.

### Accordion
Holds which items are open.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `any[]` | - | Controlled open items. Always an array, even when only one can be open. |
| `defaultValue` | `any[]` | `[]` | Starting open items when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `multiple` **agent** | `boolean` | `false` | Lets several items stay open. Otherwise opening one closes the rest. |
| `disabled` **agent** | `boolean` | `false` | Blocks every item, for people and agents. |
| `keepMounted` | `boolean` | `false` | Keeps closed panels in the DOM. Also settable per panel. |
| `hiddenUntilFound` | `boolean` | `false` | Lets find-in-page reveal text in a closed panel. Overrides `keepMounted`. |
| `aria-label` **agent** | `string` | - | Names the accordion. Its items report it to the agent as `in`. |

### AccordionItem
One section; its own disclosure to agents.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `any` | `useId()` | Identifies the item in the root's value. Generated when omitted. |
| `disabled` **agent** | `boolean` | `false` | Locks this item only. Refused for agents. |
| `onOpenChange` | `(open, details) => void` | - | Runs when this item opens or closes. |

### AccordionHeader
The heading that wraps the trigger.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | `<h3>` | Swap the heading level, for example `<h2 />`. |

### AccordionTrigger
Toggles its item; built-in chevron turns when open.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | The heading text. Also the name the agent reads. |

### AccordionPanel
The content, animated by height.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keepMounted` | `boolean` | `false` | Keeps this panel in the DOM while closed, so uncontrolled fields keep their state. |
| `hiddenUntilFound` | `boolean` | `false` | Lets find-in-page reveal this panel while closed. |
| `children` **agent** | `ReactNode` | - | The panel text. The agent reads it as the item's value while open. |

## Agent
Inside an `AgentProvider`, Accordion appears in `agent.snapshot()` as `disclosure`.
Reads:
- `label`: The item's trigger text.
- `open`: Whether the item is open.
- `value`: The panel's text while open. Nothing while closed.
- `in`: The Accordion's aria-label, when it has one.
- `disabled`: True when the item or the whole accordion is disabled.
Actions:
- `open()`: Opens the item while closed. In a single accordion it closes the open one.
- `close()`: Closes the item while open. Other open items stay open.
Each item is listed on its own. An agent's change runs through the root's `onValueChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` keeps the item as it was and the agent is told the app refused. A disabled item or a disabled accordion refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Is it styled?", action: "open" }],
})
```

## Accessibility
- Each trigger is a button with aria-expanded, and aria-controls on its panel while open.
- Each panel is a region labelled by its trigger.
- Disabled items keep their place but cannot be opened.
- `AccordionHeader` renders an h3. Pass `render` to match the page's heading level.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens or closes the focused item |
| `Tab` | Moves to the next trigger or focusable content |

## Source
`components/ui/accordion/accordion.tsx`
```tsx
import * as React from "react";
import { Accordion as BaseAccordion } from "@base-ui/react/accordion";
import { cn } from "@/lib/utils";
import { ChevronDown } from "lucide-react";
import { changeAsAgent, useAgentControl, useAgentState, useHasAgent, useMergedRef } from "@/components/ui/agent";

type Details = BaseAccordion.Root.ChangeEventDetails;

interface AccordionAgent {
  value: unknown[];
  multiple: boolean;
  change: (next: unknown[], details: Details) => void;
}

const AccordionAgentContext = React.createContext<AccordionAgent | null>(null);
type Ref<T> = React.MutableRefObject<T | null>;
const AccordionPartsContext = React.createContext<{ trigger: Ref<HTMLButtonElement>; panel: Ref<HTMLDivElement> } | null>(null);

/**
 * Base UI's root, holding its own value so an agent can open and close items the way a
 * parent would. Controlled use is unchanged, and `onValueChange` sees the agent's changes
 * first and can cancel them.
 */
const Accordion = React.forwardRef<
  React.ComponentRef<typeof BaseAccordion.Root>,
  React.ComponentProps<typeof BaseAccordion.Root>
>(({ className, value: valueProp, defaultValue, onValueChange, ...props }, ref) => {
  const [value, change] = useAgentState<unknown[], Details>(valueProp, defaultValue ?? [], onValueChange);
  const agent = { value, multiple: Boolean(props.multiple), change };
  return (
    <AccordionAgentContext.Provider value={useHasAgent() ? agent : null}>
      <BaseAccordion.Root data-slot="accordion" ref={ref} data-agent-in={props["aria-label"]} className={cn(className)} {...props} value={value} onValueChange={change} />
    </AccordionAgentContext.Provider>
  );
});
Accordion.displayName = "Accordion";

/** Each item is its own disclosure to the agent, standing at its trigger. Open, it reads as its panel's text. */
const AccordionItem = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseAccordion.Item>
>(({ className, value: valueProp, ...props }, ref) => {
  const fallback = React.useId();
  const value = valueProp ?? fallback;
  const root = React.useContext(AccordionAgentContext);
  const trigger = React.useRef<HTMLButtonElement | null>(null);
  const panel = React.useRef<HTMLDivElement | null>(null);
  const [parts] = React.useState(() => ({ trigger, panel }));

  useAgentControl(() => {
    if (!root) return null;
    const open = root.value.includes(value);
    const next = open
      ? root.value.filter((v) => v !== value)
      : root.multiple
        ? [...root.value, value]
        : [value];
    return {
      kind: "disclosure",
      element: trigger.current,
      open,
      value: open ? panel.current?.textContent?.replace(/\s+/g, " ").trim() || undefined : undefined,
      actions: { [open ? "close" : "open"]: () => changeAsAgent(root.change, next) },
    };
  });

  return (
    <AccordionPartsContext.Provider value={root ? parts : null}>
      <BaseAccordion.Item
        data-slot="accordion-item"
        ref={ref}
        className={cn("border-b", className)}
        value={value}
        {...props}
      />
    </AccordionPartsContext.Provider>
  );
});
AccordionItem.displayName = "AccordionItem";

const AccordionHeader = React.forwardRef<
  HTMLHeadingElement,
  React.ComponentProps<typeof BaseAccordion.Header>
>(({ className, ...props }, ref) => (
  <BaseAccordion.Header 
    data-slot="accordion-header"
    ref={ref}
    className={cn("flex", className)} 
    {...props} 
  />
));
AccordionHeader.displayName = "AccordionHeader";

const AccordionTrigger = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof BaseAccordion.Trigger> & {
    children?: React.ReactNode;
  }
>(({ className, children, ...props }, ref) => (
  <BaseAccordion.Trigger
    data-slot="accordion-trigger"
    ref={useMergedRef(ref, React.useContext(AccordionPartsContext)?.trigger)}
    className={cn(
      "flex flex-1 items-center justify-between py-4 font-medium transition-colors hover:underline",
      "[&[data-panel-open]>svg]:rotate-180",
      "disabled:pointer-events-none disabled:opacity-50",
      className
    )}
    {...props}
  >
    {children}
    <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))] motion-reduce:transition-none" />
  </BaseAccordion.Trigger>
));
AccordionTrigger.displayName = "AccordionTrigger";

const AccordionPanel = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseAccordion.Panel>
>(({ className, children, ...props }, ref) => (
  <BaseAccordion.Panel
    data-slot="accordion-panel"
    ref={useMergedRef(ref, React.useContext(AccordionPartsContext)?.panel)}
    className={cn(
      "overflow-hidden text-sm h-[var(--accordion-panel-height)]",
      "transition-[height] duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      "data-[starting-style]:h-0 data-[ending-style]:h-0",
      "motion-reduce:transition-none",
      className
    )}
    {...props}
  >
    <div className="pb-4 pt-0">{children}</div>
  </BaseAccordion.Panel>
));
AccordionPanel.displayName = "AccordionPanel";

export { 
  Accordion, 
  AccordionItem, 
  AccordionHeader,
  AccordionTrigger, 
  AccordionPanel 
};
```
