# Collapsible

A panel that a button shows and hides.

- Page: https://www.effectcn.com/components/collapsible
- Kind: Headless component with parts
- File: `src/ui/collapsible.ts`
- Built on: `Collapsible` 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/collapsible.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/collapsible.ts`

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

type CollapsibleParts = Component.Headless.Parts<typeof Collapsible>

const triggerBase = "text-[13px] font-medium transition-colors duration-150 " +
  "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:size-[15px] [&_svg]:shrink-0"

const triggerVariants = {
  row: "flex w-full items-center gap-2 rounded-sm px-2.5 py-2 text-left text-foreground hover:bg-accent " +
    "after:mr-1 after:ml-auto after:size-1.5 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:rotate-45",
  icon: "inline-flex size-8 shrink-0 items-center justify-center rounded-sm border border-input bg-background " +
    "text-foreground shadow-sm hover:bg-accent",
  link: "inline-flex items-center gap-1.5 rounded-xs text-muted-foreground underline-offset-4 " +
    "hover:text-foreground hover:underline"
} as const

export type CollapsibleTriggerVariant = keyof typeof triggerVariants

interface ClassOption {
  readonly class?: string | undefined
}

/** The `<div>` around the trigger and the panel. */
export const CollapsibleRoot = <Msg>(h: Html.H<Msg>, collapsible: CollapsibleParts, options: ClassOption = {}) =>
  collapsible.root(h.div.class(cn("w-full", options.class)))

/**
 * The button that opens and closes the panel: a full-width `row` with a chevron,
 * a square `icon` button, or a quiet `link`.
 */
export const CollapsibleTrigger = <Msg>(
  h: Html.H<Msg>,
  collapsible: CollapsibleParts,
  options: ClassOption & { readonly variant?: CollapsibleTriggerVariant | undefined } = {}
) =>
  collapsible.trigger(
    h.button.class(cn(triggerBase, triggerVariants[options.variant ?? "row"], options.class))
  )

/**
 * The panel, whose height animates from the kit's `--collapsible-panel-height`.
 * `undefined` once it has closed, so chain with `?.children(...)`. Keep padding
 * on its children, so it can shrink to nothing.
 */
export const CollapsiblePanel = <Msg>(h: Html.H<Msg>, collapsible: CollapsibleParts, options: ClassOption = {}) =>
  collapsible.panel(
    h.div.class(cn(
      "h-[var(--collapsible-panel-height)] overflow-hidden transition-[height] duration-200 ease-out " +
        "data-[starting-style]:h-0 data-[ending-style]:h-0",
      options.class
    ))
  )
```

```ts
import { CollapsibleRoot, CollapsibleTrigger, CollapsiblePanel } from "#ui/collapsible"
```

## Usage

An icon trigger in a header. The panel's height animates from the kit's CSS variable.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible } from "@effect/ui-kit"
import { Schema } from "effect"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleBasicMessage = UiSchema.TaggedEnum({
  ToggledCollapsible: { open: Schema.Boolean }
})

const row = "rounded-sm border px-3 py-2 font-mono text-[13px]"

export const CollapsibleBasic = Html.component({
  name: "CollapsibleBasic",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: CollapsibleBasicMessage
}).make({
  init: () => ({ open: false }),
  update: {
    ToggledCollapsible: ($, { open }) => $.evolve({ open })
  },
  view: (h, model) =>
    Collapsible(h, {
      props: { open: model.open },
      onEmit: {
        Toggled: ({ open }) => CollapsibleBasicMessage.ToggledCollapsible({ open }),
        Settled: () => undefined
      },
      view: (collapsible) =>
        CollapsibleRoot(h, collapsible, { class: "max-w-xs" }).children(
          h.div.class("mb-2 flex items-center justify-between gap-3 text-sm font-medium").children(
            h.span.children("@effect-ts starred 3 repositories"),
            CollapsibleTrigger(h, collapsible, { variant: "icon" }).attr("aria-label", "Toggle repositories").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", "M7 15l5 5 5-5M7 9l5-5 5 5"))
            )
          ),
          h.div.class(row).children("effect-ts/effect"),
          CollapsiblePanel(h, collapsible)?.children(
            h.div.class("grid gap-2 pt-2").children(
              h.div.class(row).children("effect-ts/ui"),
              h.div.class(row).children("effect-ts/website")
            )
          )
        )
    })
})
```

## Examples

### Show more

The trigger sits after the panel and reads its label from collapsible.open.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible } from "@effect/ui-kit"
import { Schema } from "effect"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleShowMoreMessage = UiSchema.TaggedEnum({
  ToggledCollapsible: { open: Schema.Boolean }
})

const first = ["Accordion", "Avatar", "Button"]
const rest = ["Checkbox", "Collapsible", "Dialog", "Meter"]

export const CollapsibleShowMore = Html.component({
  name: "CollapsibleShowMore",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: CollapsibleShowMoreMessage
}).make({
  init: () => ({ open: false }),
  update: {
    ToggledCollapsible: ($, { open }) => $.evolve({ open })
  },
  view: (h, model) =>
    Collapsible(h, {
      props: { open: model.open },
      onEmit: {
        Toggled: ({ open }) => CollapsibleShowMoreMessage.ToggledCollapsible({ open }),
        Settled: () => undefined
      },
      view: (collapsible) =>
        CollapsibleRoot(h, collapsible, { class: "max-w-xs" }).children(
          h.ul.class("m-0 grid list-none gap-2 p-0").children(
            first.map((name) => h.li.class("rounded-sm border px-3 py-2 text-[13px]").children(name))
          ),
          CollapsiblePanel(h, collapsible)?.children(
            h.ul.class("m-0 grid list-none gap-2 p-0 pt-2").children(
              rest.map((name) => h.li.class("rounded-sm border px-3 py-2 text-[13px]").children(name))
            )
          ),
          CollapsibleTrigger(h, collapsible, { variant: "link", class: "mt-3" }).children(
            collapsible.open ? "Show less" : `Show ${rest.length} more`
          )
        )
    })
})
```

### Sidebar sections

Several collapsibles in one view, each with a key, their open ids in one Model field.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible } from "@effect/ui-kit"
import { Schema } from "effect"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleSidebarMessage = UiSchema.TaggedEnum({
  ToggledSection: { id: Schema.String, open: Schema.Boolean }
})

const sections = [
  { id: "start", title: "Getting started", links: ["Introduction", "Installation", "Theming"] },
  { id: "components", title: "Components", links: ["Accordion", "Collapsible", "Dialog", "Tabs"] },
  { id: "guides", title: "Guides", links: ["Forms", "Server rendering"] }
]

export const CollapsibleSidebar = Html.component({
  name: "CollapsibleSidebar",
  model: Schema.Struct({ open: Schema.Array(Schema.String) }),
  message: CollapsibleSidebarMessage
}).make({
  init: () => ({ open: ["start"] }),
  update: {
    ToggledSection: ($, { id, open }) =>
      $.evolve({
        open: (ids) => open ? [...ids, id] : ids.filter((other) => other !== id)
      })
  },
  view: (h, model) =>
    h.nav.class("grid w-56 gap-0.5 rounded-lg border bg-card p-2").attr("aria-label", "Documentation").children(
      sections.map((section) =>
        Collapsible(h, {
          key: section.id,
          props: { open: model.open.includes(section.id) },
          onEmit: {
            Toggled: ({ open }) => CollapsibleSidebarMessage.ToggledSection({ id: section.id, open }),
            Settled: () => undefined
          },
          view: (collapsible) =>
            CollapsibleRoot(h, collapsible).children(
              CollapsibleTrigger(h, collapsible).children(section.title),
              CollapsiblePanel(h, collapsible)?.children(
                h.div.class("grid gap-px pt-0.5 pb-1.5 pl-3").children(
                  section.links.map((link) =>
                    h.a
                      .class(
                        "rounded-sm px-2.5 py-1.5 text-[13px] text-muted-foreground no-underline " +
                          "hover:bg-accent hover:text-foreground"
                      )
                      .attr("href", "#")
                      .children(link)
                  )
                )
              )
            )
        })
      )
    )
})
```

### Hidden until found

The browser's find-in-page searches the closed panel and asks to open it on a match.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible, CollapsibleToggleReason } from "@effect/ui-kit"
import { Schema } from "effect"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleHiddenUntilFoundMessage = UiSchema.TaggedEnum({
  ToggledCollapsible: { open: Schema.Boolean, reason: CollapsibleToggleReason }
})

export const CollapsibleHiddenUntilFound = Html.component({
  name: "CollapsibleHiddenUntilFound",
  model: Schema.Struct({ open: Schema.Boolean, reason: Schema.NullOr(CollapsibleToggleReason) }),
  message: CollapsibleHiddenUntilFoundMessage
}).make({
  init: () => ({ open: false, reason: null }),
  update: {
    ToggledCollapsible: ($, { open, reason }) => $.evolve({ open, reason })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-xs flex-col gap-3").children(
      // The closed panel stays in the page as hidden="until-found".
      Collapsible(h, {
        props: { open: model.open, hiddenUntilFound: true },
        onEmit: {
          Toggled: ({ open, reason }) => CollapsibleHiddenUntilFoundMessage.ToggledCollapsible({ open, reason }),
          Settled: () => undefined
        },
        view: (collapsible) =>
          CollapsibleRoot(h, collapsible).children(
            CollapsibleTrigger(h, collapsible).children("Where is the lighthouse?"),
            CollapsiblePanel(h, collapsible)?.children(
              h.p.class("m-0 px-2.5 pt-1 pb-2.5 text-[13px] leading-relaxed text-muted-foreground").children(
                "The lighthouse stands on Skerryvore, twelve miles off the coast of Tiree."
              )
            )
          )
      }),
      h.p.class("m-0 px-2.5 text-xs text-muted-foreground").children(
        model.reason === null
          ? "Use your browser's find-in-page to search for \"Skerryvore\"."
          : `Last toggled by: ${model.reason}`
      )
    )
})
```

### Keep mounted

With keepMounted the closed panel stays in the page, so what was typed in it survives.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible } from "@effect/ui-kit"
import { Schema } from "effect"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleKeepMountedMessage = UiSchema.TaggedEnum({
  ToggledCollapsible: { open: Schema.Boolean }
})

export const CollapsibleKeepMounted = Html.component({
  name: "CollapsibleKeepMounted",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: CollapsibleKeepMountedMessage
}).make({
  init: () => ({ open: true }),
  update: {
    ToggledCollapsible: ($, { open }) => $.evolve({ open })
  },
  view: (h, model) =>
    // The closed panel stays in the page with `hidden`, so the draft survives.
    Collapsible(h, {
      props: { open: model.open, keepMounted: true },
      onEmit: {
        Toggled: ({ open }) => CollapsibleKeepMountedMessage.ToggledCollapsible({ open }),
        Settled: () => undefined
      },
      view: (collapsible) =>
        CollapsibleRoot(h, collapsible, { class: "max-w-xs" }).children(
          CollapsibleTrigger(h, collapsible).children("Delivery note"),
          CollapsiblePanel(h, collapsible)?.children(
            h.div.class("p-1 pt-2").children(
              h.textarea
                .class(
                  "block min-h-20 w-full resize-y rounded-sm border border-input bg-background px-2.5 py-2 " +
                    "text-[13px] placeholder:text-muted-foreground"
                )
                .attrs({
                  "aria-label": "Delivery note",
                  placeholder: "Type a note, close the section and open it again."
                })
            )
          ),
          h.p.class("m-0 mt-2.5 px-2.5 text-xs text-muted-foreground").children(
            collapsible.open ? "The section is open." : "Closed, and the note is still in the page."
          )
        )
    })
})
```

### Disabled

A disabled trigger is a disabled button, and the panel keeps the state it had.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Collapsible } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from "#ui/collapsible"

const CollapsibleDisabledMessage = UiSchema.TaggedEnum({
  ToggledCollapsible: { open: Schema.Boolean },
  PressedLock: {}
})

export const CollapsibleDisabled = Html.component({
  name: "CollapsibleDisabled",
  model: Schema.Struct({ open: Schema.Boolean, locked: Schema.Boolean }),
  message: CollapsibleDisabledMessage
}).make({
  init: () => ({ open: true, locked: true }),
  update: {
    ToggledCollapsible: ($, { open }) => $.evolve({ open }),
    PressedLock: ($) => $.evolve({ locked: (locked) => !locked })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-xs flex-col items-start gap-3").children(
      Collapsible(h, {
        props: { open: model.open, disabled: model.locked },
        onEmit: {
          Toggled: ({ open }) => CollapsibleDisabledMessage.ToggledCollapsible({ open }),
          Settled: () => undefined
        },
        view: (collapsible) =>
          CollapsibleRoot(h, collapsible).children(
            CollapsibleTrigger(h, collapsible).children("Billing address"),
            CollapsiblePanel(h, collapsible)?.children(
              h.p.class("m-0 px-2.5 pt-1 pb-2.5 text-[13px] text-muted-foreground").children(
                "Storgata 1, 0155 Oslo, Norway"
              )
            )
          )
      }),
      Button(h, { variant: "outline", size: "sm", onPress: CollapsibleDisabledMessage.PressedLock() })
        .children(model.locked ? "Unlock the section" : "Lock the section")
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | Any element around the trigger and the panel. Optional. |
| `trigger` | The <button> that opens and closes the panel. |
| `panel` | Any element with the content. Returns undefined once it has closed, unless kept mounted. |
| `open, disabled, mounted, transitionStatus` | Plain values for markup that depends on the state. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the panel shows. Required: the consumer owns it. |
| `disabled` | `boolean` | Disables the trigger, and a find-in-page match emits nothing. |
| `keepMounted` | `boolean \| "css"` | true keeps the closed panel in the page with hidden. "css" keeps it with data-closed and no hidden, so CSS decides. |
| `hiddenUntilFound` | `boolean` | The closed panel stays as hidden="until-found", so find-in-page can reveal it. |
| `holdExit` | `boolean` | Keeps a closed panel in its ending state while true, for an exit animation the consumer runs. |

### Events

| Event | Description |
| --- | --- |
| `Toggled` | Asks for the value in open, with the reason: "trigger-press" or "find-in-page". |
| `Settled` | The transitions and animations of an open or a close finished. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-open / data-closed` | On the root and the panel. |
| `data-panel-open` | On the trigger while the panel is open. |
| `data-disabled` | On every part while disabled. |
| `data-starting-style` | For the first frame after the panel opens. |
| `data-ending-style` | While the panel closes. |
| `--collapsible-panel-height / --collapsible-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.
