# Accordion

A set of panels, each under a heading with a button that shows and hides it.

- Page: https://www.effectcn.com/components/accordion
- Kind: Headless component with parts
- File: `src/ui/accordion.ts`
- Built on: `Accordion` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/accordion.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/accordion.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { Accordion, AccordionItem } from "@effect/ui-kit"
import { cn } from "#lib/cn"

type AccordionParts = Component.Headless.Parts<typeof Accordion>
type AccordionItemParts = Component.Headless.Parts<typeof AccordionItem>

const variants = {
  default: "",
  card: "overflow-hidden rounded-lg border bg-card shadow-sm",
  separated: "grid gap-2"
} as const

export type AccordionVariant = keyof typeof variants

interface ClassOption {
  readonly class?: string | undefined
}

/** The `<div>` around the items. `variant` also restyles the items, triggers and content inside it. */
export const AccordionRoot = <Msg>(
  h: Html.H<Msg>,
  accordion: AccordionParts,
  options: ClassOption & { readonly variant?: AccordionVariant | undefined } = {}
) =>
  accordion.root(
    h.div
      .class(cn("group/accordion w-full", variants[options.variant ?? "default"], options.class))
      .attr("data-variant", options.variant ?? "default")
  )

/** The `<div>` around one item's header and panel. */
export const AccordionItemRoot = <Msg>(h: Html.H<Msg>, item: AccordionItemParts, options: ClassOption = {}) =>
  item.root(
    h.div.class(cn(
      "border-b group-data-[variant=card]/accordion:last:border-b-0 " +
        "group-data-[variant=separated]/accordion:rounded-md group-data-[variant=separated]/accordion:border " +
        "group-data-[variant=separated]/accordion:bg-card group-data-[variant=separated]/accordion:transition-colors " +
        "group-data-[variant=separated]/accordion:duration-150 " +
        "group-data-[variant=separated]/accordion:data-[open]:border-brand " +
        "group-data-[variant=separated]/accordion:data-[open]:bg-brand-wash",
      options.class
    ))
  )

/** The heading around the trigger. An `<h3>`: pass the trigger as its child. */
export const AccordionHeader = <Msg>(h: Html.H<Msg>, item: AccordionItemParts, options: ClassOption = {}) =>
  item.header(h.h3.class(cn("m-0 flex", options.class)))

/** The button that opens and closes the item, with a chevron drawn by `::after`. */
export const AccordionTrigger = <Msg>(h: Html.H<Msg>, item: AccordionItemParts, options: ClassOption = {}) =>
  item.trigger(
    h.button.class(cn(
      "flex w-full flex-1 items-center gap-2.5 rounded-xs py-3.5 text-left text-sm font-medium text-foreground " +
        "underline-offset-4 hover:underline data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 " +
        "data-[disabled]:no-underline [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground " +
        "after:mr-1 after:mb-1 after:ml-auto after:size-[7px] after:shrink-0 after:rotate-45 after:border-r-[1.5px] " +
        "after:border-b-[1.5px] after:border-muted-foreground after:transition-transform after:duration-200 " +
        "data-[panel-open]:after:mb-0 data-[panel-open]:after:mt-1 data-[panel-open]:after:rotate-[225deg] " +
        "group-data-[variant=card]/accordion:rounded-none group-data-[variant=card]/accordion:px-4 " +
        "group-data-[variant=card]/accordion:-outline-offset-2 group-data-[variant=card]/accordion:hover:bg-muted " +
        "group-data-[variant=card]/accordion:hover:no-underline " +
        "group-data-[variant=separated]/accordion:rounded-md group-data-[variant=separated]/accordion:px-3.5 " +
        "group-data-[variant=separated]/accordion:py-3 group-data-[variant=separated]/accordion:hover:no-underline",
      options.class
    ))
  )

/**
 * The panel, whose height animates from the kit's `--accordion-panel-height`.
 * `undefined` once it has closed, so chain with `?.children(...)`.
 */
export const AccordionPanel = <Msg>(h: Html.H<Msg>, item: AccordionItemParts, options: ClassOption = {}) =>
  item.panel(
    h.div.class(cn(
      "h-[var(--accordion-panel-height)] overflow-hidden text-[13px] leading-relaxed text-muted-foreground " +
        "transition-[height] duration-200 ease-out data-[starting-style]:h-0 data-[ending-style]:h-0",
      options.class
    ))
  )

/** The padding inside a panel. The panel itself has none, so it can shrink to nothing. */
export const AccordionContent = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn(
    "pr-6 pb-3.5 [&_p]:m-0 [&_p+p]:mt-2 group-data-[variant=card]/accordion:px-4 " +
      "group-data-[variant=card]/accordion:pb-4 group-data-[variant=separated]/accordion:px-3.5",
    options.class
  ))
```

```ts
import { AccordionRoot, AccordionItemRoot, AccordionHeader, AccordionTrigger, AccordionPanel, AccordionContent } from "#ui/accordion"
```

## Usage

Opening a question closes the others. The panel's height animates from the kit's CSS variable.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"

const AccordionFaqMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) }
})

const questions = [
  {
    id: "accessible",
    question: "Is it accessible?",
    answer: "Yes. Each trigger is a native button inside a heading, and the open panel is a region named by it."
  },
  {
    id: "styled",
    question: "Is it styled?",
    answer: "The kit is headless: it sets the ARIA and data attributes, and the helpers in ui/accordion.ts add the classes."
  },
  {
    id: "animated",
    question: "Is it animated?",
    answer: "Yes. The panel gets its content's height as a CSS variable, so a plain transition on height opens and closes it."
  }
]

export const AccordionFaq = Html.component({
  name: "AccordionFaq",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionFaqMessage
}).make({
  init: () => ({ open: ["accessible"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value })
  },
  view: (h, model) =>
    Accordion(h, {
      props: { value: model.open },
      onEmit: { Toggled: ({ value }) => AccordionFaqMessage.ToggledAccordion({ value }) },
      view: (accordion) =>
        AccordionRoot(h, accordion, { class: "max-w-md" }).children(
          questions.map((entry) =>
            AccordionItem(h, {
              key: entry.id,
              props: { value: entry.id },
              view: (item) =>
                AccordionItemRoot(h, item).children(
                  AccordionHeader(h, item).children(AccordionTrigger(h, item).children(entry.question)),
                  AccordionPanel(h, item)?.children(AccordionContent(h).children(entry.answer))
                )
            })
          )
        )
    })
})
```

## Examples

### Multiple

With multiple, each item opens and closes on its own.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"

const AccordionMultipleMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) }
})

const sections = [
  { id: "shipping", title: "Shipping", body: "Orders leave the warehouse within one working day and arrive in 3 to 5." },
  { id: "returns", title: "Returns", body: "Send anything back within 30 days. The label is in the box." },
  { id: "warranty", title: "Warranty", body: "Two years on parts and labour, from the day of delivery." }
]

export const AccordionMultiple = Html.component({
  name: "AccordionMultiple",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionMultipleMessage
}).make({
  init: () => ({ open: ["shipping", "returns"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-md flex-col gap-4").children(
      Accordion(h, {
        props: { value: model.open, multiple: true },
        onEmit: { Toggled: ({ value }) => AccordionMultipleMessage.ToggledAccordion({ value }) },
        view: (accordion) =>
          AccordionRoot(h, accordion, { class: "max-w-md" }).children(
            sections.map((section) =>
              AccordionItem(h, {
                key: section.id,
                props: { value: section.id },
                view: (item) =>
                  AccordionItemRoot(h, item).children(
                    AccordionHeader(h, item).children(
                      AccordionTrigger(h, item).children(section.title)
                    ),
                    AccordionPanel(h, item)?.children(
                      AccordionContent(h).children(section.body)
                    )
                  )
              })
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground").children(
        model.open.length === 0 ? "Nothing open" : `Open: ${model.open.join(", ")}`
      )
    )
})
```

### Disabled item

A disabled item's trigger is a disabled button and emits nothing.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"

const AccordionDisabledMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) }
})

const plans = [
  { id: "free", title: "Free", body: "One project, community support and 1 GB of storage.", disabled: false },
  { id: "team", title: "Team", body: "Unlimited projects, roles and 100 GB of storage.", disabled: false },
  { id: "enterprise", title: "Enterprise (coming soon)", body: "Single sign-on and audit logs.", disabled: true }
]

export const AccordionDisabled = Html.component({
  name: "AccordionDisabled",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionDisabledMessage
}).make({
  init: () => ({ open: ["free"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value })
  },
  view: (h, model) =>
    Accordion(h, {
      props: { value: model.open },
      onEmit: { Toggled: ({ value }) => AccordionDisabledMessage.ToggledAccordion({ value }) },
      view: (accordion) =>
        AccordionRoot(h, accordion, { class: "max-w-md" }).children(
          plans.map((plan) =>
            AccordionItem(h, {
              key: plan.id,
              props: { value: plan.id, disabled: plan.disabled },
              view: (item) =>
                AccordionItemRoot(h, item).children(
                  AccordionHeader(h, item).children(
                    AccordionTrigger(h, item).children(plan.title)
                  ),
                  AccordionPanel(h, item)?.children(
                    AccordionContent(h).children(plan.body)
                  )
                )
            })
          )
        )
    })
})
```

### Card

The same parts inside a bordered card, from the root's variant option.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"

const AccordionCardMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) }
})

const settings = [
  {
    id: "profile",
    title: "Profile",
    body: ["Your name and picture are shown to everyone in the workspace.", "Your email stays private."]
  },
  {
    id: "notifications",
    title: "Notifications",
    body: ["Mentions and replies arrive by email.", "Everything else waits in the weekly digest."]
  },
  {
    id: "security",
    title: "Security",
    body: ["Two-factor sign-in is on.", "The last sign-in was from Oslo, two hours ago."]
  }
]

export const AccordionCard = Html.component({
  name: "AccordionCard",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionCardMessage
}).make({
  init: () => ({ open: ["notifications"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value })
  },
  view: (h, model) =>
    Accordion(h, {
      props: { value: model.open },
      onEmit: { Toggled: ({ value }) => AccordionCardMessage.ToggledAccordion({ value }) },
      view: (accordion) =>
        AccordionRoot(h, accordion, { variant: "card", class: "max-w-md" }).children(
          settings.map((section) =>
            AccordionItem(h, {
              key: section.id,
              props: { value: section.id },
              view: (item) =>
                AccordionItemRoot(h, item).children(
                  AccordionHeader(h, item).children(
                    AccordionTrigger(h, item).children(section.title)
                  ),
                  AccordionPanel(h, item)?.children(
                    AccordionContent(h).children(
                      section.body.map((line) => h.p.children(line))
                    )
                  )
                )
            })
          )
        )
    })
})
```

### With icons

Separate items with a leading icon, tinted through data-open while open.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"

const AccordionIconsMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) }
})

const steps = [
  {
    id: "install",
    title: "Install the packages",
    body: "Add @effect/ui and @effect/ui-kit to the project.",
    icon: "M12 3v12m0 0l-4-4m4 4l4-4M5 21h14"
  },
  {
    id: "tokens",
    title: "Copy the tokens",
    body: "One stylesheet holds every colour, radius and shadow the components read.",
    icon: "M12 3l9 5-9 5-9-5 9-5zm-9 9l9 5 9-5M3 16l9 5 9-5"
  },
  {
    id: "ship",
    title: "Ship it",
    body: "Copy a component's stylesheet, import the kit component and draw its parts.",
    icon: "M5 13l4 4L19 7"
  }
]

export const AccordionIcons = Html.component({
  name: "AccordionIcons",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionIconsMessage
}).make({
  init: () => ({ open: ["install"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value })
  },
  view: (h, model) =>
    Accordion(h, {
      props: { value: model.open },
      onEmit: { Toggled: ({ value }) => AccordionIconsMessage.ToggledAccordion({ value }) },
      view: (accordion) =>
        AccordionRoot(h, accordion, { variant: "separated", class: "max-w-md" }).children(
          steps.map((step) =>
            AccordionItem(h, {
              key: step.id,
              props: { value: step.id },
              view: (item) =>
                AccordionItemRoot(h, item).children(
                  AccordionHeader(h, item).children(
                    AccordionTrigger(h, item).children(
                      h.el("svg").attrs({
                        viewBox: "0 0 24 24",
                        fill: "none",
                        stroke: "currentColor",
                        "stroke-width": "2",
                        "stroke-linecap": "round",
                        "stroke-linejoin": "round",
                        "aria-hidden": "true"
                      }).children(h.el("path").attr("d", step.icon)),
                      step.title
                    )
                  ),
                  AccordionPanel(h, item)?.children(
                    AccordionContent(h).children(step.body)
                  )
                )
            })
          )
        )
    })
})
```

### Expand and collapse all

The open values live in the Model, so other controls can change them.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Accordion, AccordionItem } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AccordionContent,
  AccordionHeader,
  AccordionItemRoot,
  AccordionPanel,
  AccordionRoot,
  AccordionTrigger
} from "#ui/accordion"
import { Button } from "#ui/button"

const AccordionControlledMessage = UiSchema.TaggedEnum({
  ToggledAccordion: { value: Schema.Array(Schema.String) },
  ClickedExpandAll: {},
  ClickedCollapseAll: {}
})

const releases = [
  { id: "0.3", title: "Version 0.3", body: "Scroll areas, meters and an accordion that numbers its own items." },
  { id: "0.2", title: "Version 0.2", body: "Popups moved to the top layer, and every transition got a data attribute." },
  { id: "0.1", title: "Version 0.1", body: "The first release: buttons, switches and dialogs." }
]

export const AccordionControlled = Html.component({
  name: "AccordionControlled",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: AccordionControlledMessage
}).make({
  init: () => ({ open: ["0.3"] }),
  update: {
    ToggledAccordion: ($, { value }) => $.evolve({ open: value }),
    ClickedExpandAll: ($) => $.evolve({ open: releases.map((release) => release.id) }),
    ClickedCollapseAll: ($) => $.evolve({ open: [] })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-md flex-col gap-4").children(
      h.div.class("flex flex-wrap items-center gap-2").children(
        Button(h, { variant: "outline", size: "sm", onPress: AccordionControlledMessage.ClickedExpandAll() })
          .children("Expand all"),
        Button(h, { variant: "outline", size: "sm", onPress: AccordionControlledMessage.ClickedCollapseAll() })
          .children("Collapse all")
      ),
      Accordion(h, {
        props: { value: model.open, multiple: true },
        onEmit: { Toggled: ({ value }) => AccordionControlledMessage.ToggledAccordion({ value }) },
        view: (accordion) =>
          AccordionRoot(h, accordion, { class: "max-w-md" }).children(
            releases.map((release) =>
              AccordionItem(h, {
                key: release.id,
                props: { value: release.id },
                view: (item) =>
                  AccordionItemRoot(h, item).children(
                    AccordionHeader(h, item).children(
                      AccordionTrigger(h, item).children(release.title)
                    ),
                    AccordionPanel(h, item)?.children(
                      AccordionContent(h).children(release.body)
                    )
                  )
              })
            )
          )
      })
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `accordion.root` | The <div> around the items. |
| `item.root` | The <div> around an item's header and panel. |
| `item.header` | An <h1> to <h6> around the trigger. |
| `item.trigger` | The <button> that opens and closes the item's panel. |
| `item.panel` | The <div> with the content. Returns undefined once it has closed, unless kept mounted. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `ReadonlyArray<string>` | The values of the open items. Required: the consumer owns it. |
| `multiple` | `boolean` | Lets several items be open at once. Off by default. |
| `disabled` | `boolean` | Disables every item. |
| `keepMounted` | `boolean` | Closed panels stay in the page, with hidden. |
| `hiddenUntilFound` | `boolean` | Closed panels stay in the page as hidden="until-found", so find-in-page can open them. |
| `orientation` | `"vertical" \| "horizontal"` | Written as data-orientation on every part, for styling. |
| `AccordionItem: value` | `string` | The item's value, unique within its accordion. Required. |
| `AccordionItem: disabled` | `boolean` | Disables this item. |

### Events

| Event | Description |
| --- | --- |
| `Toggled` | The value the user asked for and the reason. Store it and pass it back as value. |
| `AccordionItem: Settled` | The panel's open or close transition finished. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-open / data-closed` | On the item's root, header and panel. |
| `data-panel-open` | On the trigger while its panel is open. |
| `data-disabled` | On every part of a disabled accordion or item. |
| `data-starting-style / data-ending-style` | On the item's root, trigger and panel: the first frame after opening, and while closing. |
| `data-index` | The item's position among the accordion's items. |
| `data-orientation` | The accordion's orientation, vertical by default. |
| `--accordion-panel-height / --accordion-panel-width` | CSS variables on the panel: its content's size in px while it opens and closes, auto otherwise. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
