Skip to content
WebJs
Menu

Collapsible

An interactive component which expands/collapses a panel.

Order #4189

Toggle details
Status Shipped

Shipping address

100 Market St, San Francisco

Items

2x Studio Headphones

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  collapsibleClass, collapsibleTriggerClass, collapsibleContentClass,
} from '#components/ui/collapsible.ts';
import { ChevronsUpDown } from '#lib/ui/lucide.ts';

// A native <details> hides everything but its <summary> while closed, so the
// always-visible status row rides inside the summary with the header.
export default function CollapsibleDemo() {
  return html`
    <details data-slot="collapsible" class=${cn(collapsibleClass(), 'flex w-[350px] flex-col gap-2')}>
      <summary data-slot="collapsible-trigger" class=${cn(collapsibleTriggerClass(), 'flex-col gap-2 font-normal')}>
        <span class="flex items-center justify-between gap-4 self-stretch px-4">
          <h4 class="text-sm font-semibold">Order #4189</h4>
          <span data-slot="button" data-variant="ghost" data-size="icon" class=${cn(buttonClass({ variant: 'ghost', size: 'icon' }), 'size-8')}>
            ${ChevronsUpDown()}
            <span class="sr-only">Toggle details</span>
          </span>
        </span>
        <span class="flex items-center justify-between self-stretch rounded-md border px-4 py-2 text-sm">
          <span class="text-muted-foreground">Status</span>
          <span class="font-medium">Shipped</span>
        </span>
      </summary>
      <div data-slot="collapsible-content" class=${cn(collapsibleContentClass(), 'flex flex-col gap-2')}>
        <div class="rounded-md border px-4 py-2 text-sm">
          <p class="font-medium">Shipping address</p>
          <p class="text-muted-foreground">100 Market St, San Francisco</p>
        </div>
        <div class="rounded-md border px-4 py-2 text-sm">
          <p class="font-medium">Items</p>
          <p class="text-muted-foreground">2x Studio Headphones</p>
        </div>
      </div>
    </details>
  `;
}
View Code

Installation

pnpm dlx @webjsdev/ui add collapsible

Usage

import {
  collapsibleClass,
  collapsibleContentClass,
  collapsibleTriggerClass,
} from '#components/ui/collapsible.ts';
<details data-slot="collapsible" class=${collapsibleClass()}>
  <summary data-slot="collapsible-trigger" class=${collapsibleTriggerClass()}>Can I use this in my project?</summary>
  <div data-slot="collapsible-content" class=${collapsibleContentClass()}>
    Yes. Free to use for personal and commercial projects. No attribution
    required.
  </div>
</details>

Composition

Use the following composition to build a collapsible:

collapsibleClass()           on a details element
├── collapsibleTriggerClass()  on its summary
└── collapsibleContentClass()  on a div

Controlled State

The collapsible is a native <details>, so the browser holds the state. Add the open attribute to render it expanded on first paint, set the open property to change it from code, and listen for the toggle event to follow it.

<details id="faq" data-slot="collapsible" class=${collapsibleClass()} open>
  <summary data-slot="collapsible-trigger" class=${collapsibleTriggerClass()}>Toggle</summary>
  <div data-slot="collapsible-content" class=${collapsibleContentClass()}>Content</div>
</details>
const details = document.querySelector('#faq');

details.open = false;
details.addEventListener('toggle', () => {
  console.log(details.open ? 'open' : 'closed');
});

Basic

Product details
This panel can be expanded or collapsed to reveal additional content.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';
import {
  collapsibleClass, collapsibleTriggerClass, collapsibleContentClass,
} from '#components/ui/collapsible.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

export default function CollapsibleBasic() {
  return html`
    <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto w-full max-w-sm')}>
      <div data-slot="card-content" class=${cardContentClass()}>
        <details data-slot="collapsible" class=${cn(collapsibleClass(), 'rounded-md open:bg-muted')}>
          <summary data-slot="collapsible-trigger" data-variant="ghost" data-size="default" class=${cn(collapsibleTriggerClass(), buttonClass({ variant: 'ghost' }), 'w-full')}>
            Product details
            ${ChevronDownIcon('ml-auto group-open:rotate-180')}
          </summary>
          <div data-slot="collapsible-content" class=${cn(collapsibleContentClass(), 'flex flex-col items-start gap-2 p-2.5 pt-0 text-sm')}>
            <div>
              This panel can be expanded or collapsed to reveal additional
              content.
            </div>
            <button type="button" data-slot="button" data-variant="default" data-size="xs" class=${buttonClass({ size: 'xs' })}>Learn More</button>
          </div>
        </details>
      </div>
    </div>
  `;
}
View Code

Settings Panel

Use a trigger button to reveal additional settings.

Radius
Set the corner radius of the element.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass, cardContentClass,
} from '#components/ui/card.ts';
import {
  collapsibleClass, collapsibleTriggerClass, collapsibleContentClass,
} from '#components/ui/collapsible.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';
import { inputClass } from '#components/ui/input.ts';
import { MaximizeIcon, MinimizeIcon } from '#lib/ui/lucide.ts';

const radiusField = (id: string, label: string) => html`
  <div role="group" data-slot="field" data-orientation="vertical" class=${fieldClass()}>
    <label data-slot="field-label" for=${id} class=${cn(fieldLabelClass(), 'sr-only')}>${label}</label>
    <input data-slot="input" id=${id} placeholder="0" value="0" class=${inputClass()}>
  </div>
`;

// A closed <details> shows only its <summary>, so the first row of fields sits
// outside it and the trigger is placed beside that row. The second row carries
// its own top padding, so the closed collapsible adds no row gap. The icon
// follows the native open state through group-open, with no script.
export default function CollapsibleSettings() {
  return html`
    <div data-slot="card" data-size="sm" class=${cn(cardClass({ size: 'sm' }), 'mx-auto w-full max-w-xs')}>
      <div data-slot="card-header" class=${cardHeaderClass()}>
        <div data-slot="card-title" class=${cardTitleClass()}>Radius</div>
        <div data-slot="card-description" class=${cardDescriptionClass()}>Set the corner radius of the element.</div>
      </div>
      <div data-slot="card-content" class=${cardContentClass()}>
        <div class="relative pe-10">
          <div data-slot="field-group" class=${cn(fieldGroupClass(), 'grid w-full grid-cols-2 gap-x-2 gap-y-0')}>
            ${radiusField('radius-x', 'Radius X')}
            ${radiusField('radius-y', 'Radius Y')}
            <details data-slot="collapsible" class=${cn(collapsibleClass(), 'col-span-full')}>
              <summary data-slot="collapsible-trigger" data-variant="outline" data-size="icon" aria-label="Toggle more radius fields" class=${cn(collapsibleTriggerClass(), buttonClass({ variant: 'outline', size: 'icon' }), 'absolute end-0 top-0 w-auto aspect-square')}>
                ${MaximizeIcon('group-open:hidden')}
                ${MinimizeIcon('hidden group-open:block')}
              </summary>
              <div data-slot="collapsible-content" class=${cn(collapsibleContentClass(), 'grid grid-cols-2 gap-2 pt-2')}>
                ${radiusField('radius-bottom-x', 'Radius X')}
                ${radiusField('radius-bottom-y', 'Radius Y')}
              </div>
            </details>
          </div>
        </div>
      </div>
    </div>
  `;
}
View Code

File Tree

Use nested collapsibles to build a file tree. In a conversation, this is the File Tree pattern.

components
ui
lib
hooks
types
public
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { cardClass, cardHeaderClass, cardContentClass } from '#components/ui/card.ts';
import {
  collapsibleClass, collapsibleContentClass,
} from '#components/ui/collapsible.ts';
import { ChevronRightIcon, FileIcon, FolderIcon } from '#lib/ui/lucide.ts';

type FileTreeItem = { name: string } | { name: string; items: FileTreeItem[] };

const fileTree: FileTreeItem[] = [
  {
    name: 'components',
    items: [
      {
        name: 'ui',
        items: [
          { name: 'button.tsx' },
          { name: 'card.tsx' },
          { name: 'dialog.tsx' },
          { name: 'input.tsx' },
          { name: 'select.tsx' },
          { name: 'table.tsx' },
        ],
      },
      { name: 'login-form.tsx' },
      { name: 'register-form.tsx' },
    ],
  },
  {
    name: 'lib',
    items: [{ name: 'utils.ts' }, { name: 'cn.ts' }, { name: 'api.ts' }],
  },
  {
    name: 'hooks',
    items: [
      { name: 'use-media-query.ts' },
      { name: 'use-debounce.ts' },
      { name: 'use-local-storage.ts' },
    ],
  },
  {
    name: 'types',
    items: [{ name: 'index.d.ts' }, { name: 'api.d.ts' }],
  },
  {
    name: 'public',
    items: [
      { name: 'favicon.ico' },
      { name: 'logo.svg' },
      { name: 'images' },
    ],
  },
  { name: 'app.tsx' },
  { name: 'layout.tsx' },
  { name: 'globals.css' },
  { name: 'package.json' },
  { name: 'tsconfig.json' },
  { name: 'README.md' },
  { name: '.gitignore' },
];

// Each folder is a native <details>. The chevron turns only for its OWN
// folder: [[open]>summary>&] matches the summary of an open details, where
// group-open would also match every folder nested inside an open one. The
// summary takes the button classes alone, since the trigger helper's text-sm
// would override the small button's text size.
const renderItem = (fileItem: FileTreeItem): unknown => {
  if ('items' in fileItem) {
    return html`
      <details data-slot="collapsible" class=${collapsibleClass()}>
        <summary data-slot="collapsible-trigger" data-variant="ghost" data-size="sm" class=${cn(buttonClass({ variant: 'ghost', size: 'sm' }), 'w-full cursor-pointer list-none justify-start transition-none hover:bg-accent hover:text-accent-foreground [&::-webkit-details-marker]:hidden')}>
          ${ChevronRightIcon('transition-transform [[open]>summary>&]:rotate-90')}
          ${FolderIcon()}
          ${fileItem.name}
        </summary>
        <div data-slot="collapsible-content" class=${cn(collapsibleContentClass(), 'mt-1 ml-5')}>
          <div class="flex flex-col gap-1">
            ${fileItem.items.map((child) => renderItem(child))}
          </div>
        </div>
      </details>
    `;
  }
  return html`
    <button type="button" data-slot="button" data-variant="link" data-size="sm" class=${cn(buttonClass({ variant: 'link', size: 'sm' }), 'w-full justify-start gap-2 text-foreground')}>
      ${FileIcon()}
      <span>${fileItem.name}</span>
    </button>
  `;
};

export default function CollapsibleFileTree() {
  return html`
    <div data-slot="card" data-size="sm" class=${cn(cardClass({ size: 'sm' }), 'mx-auto w-full max-w-[16rem] gap-2')}>
      <div data-slot="card-header" class=${cardHeaderClass()}>
        <ui-tabs value="explorer">
          <ui-tabs-list class="w-full">
            <ui-tabs-trigger value="explorer">Explorer</ui-tabs-trigger>
            <ui-tabs-trigger value="settings">Outline</ui-tabs-trigger>
          </ui-tabs-list>
        </ui-tabs>
      </div>
      <div data-slot="card-content" class=${cardContentClass()}>
        <div class="flex flex-col gap-1">
          ${fileTree.map((item) => renderItem(item))}
        </div>
      </div>
    </div>
  `;
}
View Code

RTL

To enable RTL support, see the RTL configuration guide.

الطلب #4189

Toggle details
الحالة تم الشحن

عنوان الشحن

100 Market St, San Francisco

العناصر

2x سماعات الاستوديو

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  collapsibleClass, collapsibleTriggerClass, collapsibleContentClass,
} from '#components/ui/collapsible.ts';
import { ChevronsUpDown } from '#lib/ui/lucide.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      orderNumber: 'Order #4189',
      status: 'Status',
      shipped: 'Shipped',
      shippingAddress: 'Shipping address',
      address: '100 Market St, San Francisco',
      items: 'Items',
      itemsDescription: '2x Studio Headphones',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      orderNumber: 'الطلب #4189',
      status: 'الحالة',
      shipped: 'تم الشحن',
      shippingAddress: 'عنوان الشحن',
      address: '100 Market St, San Francisco',
      items: 'العناصر',
      itemsDescription: '2x سماعات الاستوديو',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      orderNumber: 'הזמנה #4189',
      status: 'סטטוס',
      shipped: 'נשלח',
      shippingAddress: 'כתובת משלוח',
      address: '100 Market St, San Francisco',
      items: 'פריטים',
      itemsDescription: '2x אוזניות סטודיו',
    },
  },
};

// A native <details> hides everything but its <summary> while closed, so the
// always-visible status row rides inside the summary with the header.
export default function CollapsibleRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <details data-slot="collapsible" dir=${dir} lang=${lang} class=${cn(collapsibleClass(), 'flex w-[350px] flex-col gap-2')}>
      <summary data-slot="collapsible-trigger" class=${cn(collapsibleTriggerClass(), 'flex-col gap-2 font-normal')}>
        <span class="flex items-center justify-between gap-4 self-stretch px-4">
          <h4 class="text-sm font-semibold">${t.orderNumber}</h4>
          <span data-slot="button" data-variant="ghost" data-size="icon" class=${cn(buttonClass({ variant: 'ghost', size: 'icon' }), 'size-8')}>
            ${ChevronsUpDown()}
            <span class="sr-only">Toggle details</span>
          </span>
        </span>
        <span class="flex items-center justify-between self-stretch rounded-md border px-4 py-2 text-sm">
          <span class="text-muted-foreground">${t.status}</span>
          <span class="font-medium">${t.shipped}</span>
        </span>
      </summary>
      <div data-slot="collapsible-content" class=${cn(collapsibleContentClass(), 'flex flex-col gap-2')}>
        <div class="rounded-md border px-4 py-2 text-sm">
          <p class="font-medium">${t.shippingAddress}</p>
          <p class="text-muted-foreground">${t.address}</p>
        </div>
        <div class="rounded-md border px-4 py-2 text-sm">
          <p class="font-medium">${t.items}</p>
          <p class="text-muted-foreground">${t.itemsDescription}</p>
        </div>
      </div>
    </details>
  `;
}
View Code

API Reference

The collapsible is built on <details> and <summary>, so the browser supplies the open state, Enter and Space activation, focus and the expanded state a screen reader announces. Every part is a class helper.

collapsibleClass

collapsibleClass() is the root. It marks the <details> as a group, so its descendants can react to the open state with group-open:.

Attribute / EventTypeDescription
openbooleanRenders the collapsible expanded. Also a property you can set from code.
inertbooleanStops the trigger from taking focus or toggling, for a disabled collapsible.
toggleEventFired after the open state changes.

collapsibleTriggerClass

collapsibleTriggerClass() styles the <summary> and hides the native disclosure marker, so you render your own chevron. Put the classes on the <summary> itself, never on a button inside it.

OptionTypeDefault
disabledbooleanfalse

disabled is the visual state only. Add inert on the <details> as well to stop it toggling.

collapsibleContentClass

collapsibleContentClass() styles the content. The browser hides it while the collapsible is closed.

ElementAttributesOptions
<div>data-slot="collapsible-content"none