Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 469
feat(headless): add Accordion primitive#8475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
0105e4b1dcdcd240bdf6d8b06f02ca1985a5a6d8bbf13cdb6File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| # Accordion | ||
| A vertically stacked set of collapsible sections. Supports single or multiple open panels, keyboard navigation, and CSS-driven expand/collapse animations. | ||
| ## When to Use | ||
| - FAQ sections, settings panels, or any UI where content should be shown/hidden in discrete sections. | ||
| - When you need accessible expand/collapse with proper ARIA attributes and keyboard support. | ||
| - Prefer Accordion over manual show/hide toggles — it handles focus management, ARIA, and animation lifecycle automatically. | ||
| ## Usage | ||
| ```tsx | ||
| import { Accordion } from '@/primitives/accordion'; | ||
| <Accordion.Root | ||
| type='single' | ||
| defaultValue={['item-1']} | ||
| > | ||
| <Accordion.Item value='item-1'> | ||
| <Accordion.Header> | ||
| <Accordion.Trigger>Section 1</Accordion.Trigger> | ||
| </Accordion.Header> | ||
| <Accordion.Panel>Content for section 1</Accordion.Panel> | ||
| </Accordion.Item> | ||
| <Accordion.Item value='item-2'> | ||
| <Accordion.Header> | ||
| <Accordion.Trigger>Section 2</Accordion.Trigger> | ||
| </Accordion.Header> | ||
| <Accordion.Panel>Content for section 2</Accordion.Panel> | ||
| </Accordion.Item> | ||
| </Accordion.Root>; | ||
| ``` | ||
| ### Controlled | ||
| ```tsx | ||
| const [value, setValue] = useState<string[]>(['item-1']); | ||
| <Accordion.Root | ||
| value={value} | ||
| onValueChange={setValue} | ||
| > | ||
| {/* ... */} | ||
| </Accordion.Root>; | ||
| ``` | ||
| ## Parts | ||
| | Part | Default Element | Description | | ||
| | ------------------- | --------------- | ---------------------------------- | | ||
| | `Accordion.Root` | `<div>` | Root wrapper, provides context | | ||
| | `Accordion.Item` | `<div>` | Wraps a single collapsible section | | ||
| | `Accordion.Header` | `<h3>` | Heading wrapper for the trigger | | ||
| | `Accordion.Trigger` | `<button>` | Clickable toggle for its panel | | ||
| | `Accordion.Panel` | `<div>` | Collapsible content area | | ||
| ## Props | ||
| ### `Accordion.Root` | ||
| | Prop | Type | Default | Description | | ||
| | --------------- | --------------------------- | ------------ | ----------------------------------------- | | ||
| | `value` | `string[]` | — | Controlled open items | | ||
| | `defaultValue` | `string[]` | `[]` | Initial open items (uncontrolled) | | ||
| | `onValueChange` | `(value: string[]) => void` | — | Called when open items change | | ||
| | `type` | `"single" \| "multiple"` | `"multiple"` | `"single"` enforces at most one open item | | ||
| | `disabled` | `boolean` | `false` | Disables all items | | ||
| ### `Accordion.Item` | ||
| | Prop | Type | Default | Description | | ||
| | ---------- | --------- | ------------- | ------------------------------- | | ||
| | `value` | `string` | **required** | Unique identifier for this item | | ||
| | `disabled` | `boolean` | inherits root | Disables this specific item | | ||
| ### `Accordion.Header` | ||
| No additional props. Renders as `<h3>` by default. | ||
| ### `Accordion.Trigger` | ||
| No additional props. Renders as `<button>` by default. | ||
| ### `Accordion.Panel` | ||
| No additional props. Renders as `<div>` by default. | ||
| All parts accept a `render` prop for polymorphic rendering and standard HTML attributes for their default element. | ||
| ## Keyboard Navigation | ||
| | Key | Action | | ||
| | ----------------- | ------------------------------ | | ||
| | `ArrowDown` | Move focus to next trigger | | ||
| | `ArrowUp` | Move focus to previous trigger | | ||
| | `Enter` / `Space` | Toggle the focused item | | ||
| ## Data Attributes | ||
| | Attribute | Applies To | Description | | ||
| | ------------------ | -------------------- | ------------------------------------------------- | | ||
| | `data-cl-slot` | All parts | Identifies each part (e.g. `"accordion-trigger"`) | | ||
| | `data-cl-open` | Item, Trigger, Panel | Present when the item is expanded | | ||
| | `data-cl-closed` | Item, Trigger, Panel | Present when the item is collapsed | | ||
| | `data-cl-disabled` | Item, Trigger | Present when the item is disabled | | ||
| ## CSS Animation | ||
| `Accordion.Panel` exposes a `--cl-accordion-panel-height` CSS custom property set to the panel's `scrollHeight` in pixels. Use this for height-based expand/collapse animations: | ||
| ```css | ||
| [data-cl-slot='accordion-panel'] { | ||
| overflow: hidden; | ||
| height: var(--cl-accordion-panel-height); | ||
| transition: height 200ms ease; | ||
| } | ||
| [data-cl-slot='accordion-panel'][data-cl-closed] { | ||
| height: 0; | ||
| } | ||
| ``` | ||
| The panel suppresses the enter animation on initial mount — only subsequent opens animate. | ||
| ## ARIA | ||
| - Trigger: `aria-expanded`, `aria-controls` (pointing to its panel), `aria-disabled` | ||
| - Panel: `role="region"`, `aria-labelledby` (pointing to its trigger) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { createContext, useContext } from 'react'; | ||
| export interface AccordionContextValue { | ||
| value: string[]; | ||
| toggle: (itemValue: string) => void; | ||
| disabled: boolean; | ||
| accordionId: string; | ||
| } | ||
| export const AccordionContext = createContext<AccordionContextValue | null>(null); | ||
| export function useAccordionContext() { | ||
| const ctx = useContext(AccordionContext); | ||
| if (!ctx) { | ||
| throw new Error('Accordion compound components must be used within <Accordion.Root>'); | ||
| } | ||
| return ctx; | ||
| } | ||
| export interface AccordionItemContextValue { | ||
| itemValue: string; | ||
| open: boolean; | ||
| disabled: boolean; | ||
| triggerId: string; | ||
| panelId: string; | ||
| } | ||
| export const AccordionItemContext = createContext<AccordionItemContextValue | null>(null); | ||
| export function useAccordionItemContext() { | ||
| const ctx = useContext(AccordionItemContext); | ||
| if (!ctx) { | ||
| throw new Error('Accordion.Trigger/Header/Panel must be used within <Accordion.Item>'); | ||
| } | ||
| return ctx; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| 'use client'; | ||
| import { type ComponentProps, mergeProps, renderElement } from '../../utils/render-element'; | ||
| export type AccordionHeaderProps = ComponentProps<'h3'>; | ||
| export function AccordionHeader(props: AccordionHeaderProps) { | ||
alexcarpenter marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const { render, ...otherProps } = props; | ||
| const defaultProps = { | ||
| 'data-cl-slot': 'accordion-header', | ||
| }; | ||
| return renderElement({ | ||
| defaultTagName: 'h3', | ||
| render, | ||
| props: mergeProps<'h3'>(defaultProps, otherProps), | ||
| }); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| 'use client'; | ||
| import { useMemo } from 'react'; | ||
| import { type ComponentProps, mergeProps, renderElement } from '../../utils/render-element'; | ||
| import { AccordionItemContext, type AccordionItemContextValue, useAccordionContext } from './accordion-context'; | ||
| export interface AccordionItemProps extends ComponentProps<'div'> { | ||
| /** Unique value identifying this item. */ | ||
| value: string; | ||
| /** Disable this specific item. */ | ||
| disabled?: boolean; | ||
| } | ||
| export function AccordionItem(props: AccordionItemProps) { | ||
alexcarpenter marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const { render, value: itemValue, disabled: itemDisabled, ...otherProps } = props; | ||
| const ctx = useAccordionContext(); | ||
| const open = ctx.value.includes(itemValue); | ||
| const disabled = itemDisabled ?? ctx.disabled; | ||
| const triggerId = `${ctx.accordionId}-trigger-${itemValue}`; | ||
| const panelId = `${ctx.accordionId}-panel-${itemValue}`; | ||
| const itemContextValue = useMemo<AccordionItemContextValue>( | ||
| () => ({ itemValue, open, disabled, triggerId, panelId }), | ||
| [itemValue, open, disabled, triggerId, panelId], | ||
| ); | ||
| const state = { open, disabled }; | ||
| const defaultProps = { | ||
| 'data-cl-slot': 'accordion-item', | ||
| }; | ||
| return ( | ||
| <AccordionItemContext.Provider value={itemContextValue}> | ||
| {renderElement({ | ||
| defaultTagName: 'div', | ||
| render, | ||
| state, | ||
| stateAttributesMapping: { | ||
| open: (v: boolean): Record<string, string> | null => (v ? { 'data-cl-open': '' } : { 'data-cl-closed': '' }), | ||
| disabled: (v: boolean) => (v ? { 'data-cl-disabled': '' } : null), | ||
| }, | ||
| props: mergeProps<'div'>(defaultProps, otherProps), | ||
| })} | ||
| </AccordionItemContext.Provider> | ||
| ); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| 'use client'; | ||
| import { useMergeRefs } from '@floating-ui/react'; | ||
| import { type RefObject, useLayoutEffect, useRef, useState } from 'react'; | ||
| import { useTransition } from '../../hooks/use-transition'; | ||
| import { type ComponentProps, mergeProps, renderElement } from '../../utils/render-element'; | ||
| import { useAccordionItemContext } from './accordion-context'; | ||
| export type AccordionPanelProps = ComponentProps<'div'>; | ||
| export function AccordionPanel(props: AccordionPanelProps) { | ||
| const { render, ref: consumerRef, ...otherProps } = props; | ||
| const { open, triggerId, panelId } = useAccordionItemContext(); | ||
| const panelRef = useRef<HTMLElement | null>(null); | ||
| // Merge the consumer ref with the internal panelRef so passing a ref does not | ||
| // clobber the ref the panel relies on for height measurement. | ||
| const combinedRef = useMergeRefs([panelRef, consumerRef]); | ||
| const [height, setHeight] = useState<number | undefined>(undefined); | ||
| // Track whether open has ever transitioned from true→false. | ||
| // Until that happens, skip enter animations (prevents animate-on-load). | ||
| const hasBeenClosed = useRef(false); | ||
| if (!open) { | ||
| hasBeenClosed.current = true; | ||
| } | ||
| const { mounted, transitionProps } = useTransition({ | ||
| open, | ||
| ref: panelRef as RefObject<HTMLElement>, | ||
| }); | ||
| // Measure the content height and keep it in sync via ResizeObserver | ||
| useLayoutEffect(() => { | ||
| if (!mounted) { | ||
| return; | ||
| } | ||
| const panel = panelRef.current; | ||
| if (!panel) { | ||
| return; | ||
| } | ||
| // Measure scrollHeight of the panel's content | ||
| const measure = () => { | ||
| setHeight(panel.scrollHeight); | ||
| }; | ||
| measure(); | ||
| const ro = new ResizeObserver(measure); | ||
| // Observe children mutations that affect height | ||
| ro.observe(panel, { box: 'border-box' }); | ||
| return () => ro.disconnect(); | ||
| }, [mounted]); | ||
| const state = { open }; | ||
| // Skip enter animation for panels that have never been closed | ||
| const effectiveTransitionProps = !hasBeenClosed.current | ||
| ? { | ||
| ...transitionProps, | ||
| 'data-cl-starting-style': undefined, | ||
| style: undefined, | ||
| } | ||
| : transitionProps; | ||
| const defaultProps: Record<string, unknown> = { | ||
| 'data-cl-slot': 'accordion-panel', | ||
| id: panelId, | ||
| role: 'region' as const, | ||
| 'aria-labelledby': triggerId, | ||
| ref: combinedRef, | ||
| ...effectiveTransitionProps, | ||
| style: { | ||
| '--cl-accordion-panel-height': height != null ? `${height}px` : undefined, | ||
| ...effectiveTransitionProps.style, | ||
| }, | ||
| }; | ||
| const merged = mergeProps<'div'>(defaultProps, otherProps); | ||
| // The wired id is owned by the primitive: a consumer-supplied id must not | ||
| // override it, or the trigger/panel aria pairing would silently break. | ||
| merged.id = panelId; | ||
| return renderElement({ | ||
| defaultTagName: 'div', | ||
| render, | ||
| enabled: mounted, | ||
| state, | ||
| stateAttributesMapping: { | ||
| open: (v: boolean): Record<string, string> | null => (v ? { 'data-cl-open': '' } : { 'data-cl-closed': '' }), | ||
| }, | ||
| props: merged, | ||
| }); | ||
| } | ||
alexcarpenter marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.