Multi-Open Accordion with Controls
Accordion where any number of sections stay open, under a toolbar with Expand all, Collapse all and a running open count. Use it to fold a long record into titled field groups.
How it differs. Independent panels under a group toolbar: bulk buttons go inert when they would do nothing, the open set is controllable for deep links, and a panel can render its fields as a description list.
Install
pnpm dlx shadcn@latest add @hazine/accordion-multi-open-controlsAdds 1 file, 1 shadcn primitive (button), 2 Hazine items (@hazine/heading, @hazine/use-controllable-state), and 2 packages (lucide-react, class-variance-authority).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/accordion-multi-open-controls.tsx, 347 lines
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { ChevronDown, ChevronsDownUp, ChevronsUpDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Heading, type HeadingLevel } from "@/components/hazine/heading"
import { useControllableState } from "@/hooks/use-controllable-state"
export interface AccordionField {
label: string
/** Left out or empty renders the `emptyValueLabel` text. */
value?: string
}
export interface AccordionSection {
value: string
title: string
/** Short text at the end of the header: a count, a status or the reason a section is locked. */
meta?: string
/** Rendered as a description list at the top of the panel. */
fields?: AccordionField[]
/** Free content, rendered after `fields`. */
content?: React.ReactNode
/** Keeps its current state. The header stays focusable, so `meta` can say why. */
disabled?: boolean
}
type BulkAction = "expand" | "collapse"
const SLOT = "accordion-multi-open-controls"
const ROOT_SELECTOR = `[data-slot="${SLOT}"]`
const TRIGGER_SELECTOR = `[data-slot="${SLOT}-trigger"]`
const SKELETON_WIDTHS = ["w-36", "w-48", "w-28", "w-40"]
export const accordionMultiOpenControlsVariants = cva(
"group/trigger flex w-full items-center gap-3 px-2 text-start text-sm transition-colors duration-100 hover:bg-muted/50 active:bg-muted",
{
variants: {
density: {
compact: "min-h-8 py-1.5",
default: "min-h-10 py-2",
comfortable: "min-h-12 py-3",
},
},
defaultVariants: {
density: "default",
},
}
)
const triggerStateClass =
"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground aria-disabled:pointer-events-none"
const chevronClass =
"size-4 shrink-0 text-muted-foreground group-aria-expanded/trigger:rotate-180 group-aria-disabled/trigger:opacity-50 motion-safe:transition-transform motion-safe:duration-200 motion-safe:ease-out"
// A bulk button that would do nothing keeps focus, so it is aria-disabled, not disabled.
const bulkButtonClass = "aria-disabled:pointer-events-none aria-disabled:opacity-50"
function defaultFormatCount(open: number, total: number) {
return `${open} of ${total} open`
}
function Fields({
fields,
emptyValueLabel,
}: {
fields: AccordionField[]
emptyValueLabel: string
}) {
return (
<dl data-slot={`${SLOT}-fields`}>
{fields.map((field, index) => (
<div
key={`${index}-${field.label}`}
className="grid gap-x-4 gap-y-0.5 py-1.5 @md:grid-cols-3"
>
<dt className="text-muted-foreground">{field.label}</dt>
<dd className="min-w-0 break-words tabular-nums @md:col-span-2">
{field.value ? (
field.value
) : (
<span className="text-muted-foreground">{emptyValueLabel}</span>
)}
</dd>
</div>
))}
</dl>
)
}
function Skeleton({ rowClass }: { rowClass: string }) {
return SKELETON_WIDTHS.map((width) => (
<div
key={width}
aria-hidden="true"
className={cn(rowClass, "pointer-events-none")}
>
<span
className={cn("h-4 rounded-md bg-muted motion-safe:animate-pulse", width)}
/>
</div>
))
}
export interface AccordionMultiOpenControlsProps
extends
Omit<React.ComponentProps<"div">, "defaultValue" | "onChange" | "children">,
VariantProps<typeof accordionMultiOpenControlsVariants> {
items: AccordionSection[]
/** Values of the open sections, in the order of `items`. */
value?: string[]
defaultValue?: string[]
onValueChange?: (value: string[]) => void
/** Rank of every section header. */
headingLevel?: HeadingLevel
/** Accessible name of the toolbar that holds the two bulk buttons. */
controlsLabel?: string
expandLabel?: string
collapseLabel?: string
/** Count beside the toolbar. It is a status region, so every change is announced. */
formatCount?: (open: number, total: number) => string
/** Text shown for a field without a value. */
emptyValueLabel?: string
loading?: boolean
loadingLabel?: string
/** Shown in place of the sections when `items` is empty. */
empty?: React.ReactNode
}
export function AccordionMultiOpenControls({
items,
value: valueProp,
defaultValue,
onValueChange,
headingLevel = 3,
controlsLabel = "Section controls",
expandLabel = "Expand all",
collapseLabel = "Collapse all",
formatCount = defaultFormatCount,
emptyValueLabel = "Not set",
loading = false,
loadingLabel = "Loading sections",
empty = "No sections to show.",
density = "default",
className,
...props
}: AccordionMultiOpenControlsProps) {
const baseId = React.useId()
const [value, setValue] = useControllableState<string[]>({
value: valueProp,
defaultValue: defaultValue ?? [],
onChange: onValueChange,
})
const [toolbarIndex, setToolbarIndex] = React.useState(0)
const openSet = new Set(value)
const openCount = items.filter((item) => openSet.has(item.value)).length
const enabledItems = loading ? [] : items.filter((item) => !item.disabled)
const canExpand = enabledItems.some((item) => !openSet.has(item.value))
const canCollapse = enabledItems.some((item) => openSet.has(item.value))
// APG: a panel is a region landmark only while there are few enough to scan.
const labelled = items.length <= 6
const rowClass = accordionMultiOpenControlsVariants({ density })
const countText = loading
? loadingLabel
: items.length > 0
? formatCount(openCount, items.length)
: null
// Values that match no section stay in front, the rest follow `items`,
// so the array is the same however the user reached this set.
function commit(next: Set<string>) {
const known = new Set(items.map((item) => item.value))
const ordered = [
...value.filter((entry) => !known.has(entry)),
...items.filter((item) => next.has(item.value)).map((item) => item.value),
]
setValue(ordered)
}
function toggle(item: AccordionSection) {
if (item.disabled) return
const next = new Set(value)
if (!next.delete(item.value)) next.add(item.value)
commit(next)
}
function bulk(action: BulkAction) {
if (action === "expand" ? !canExpand : !canCollapse) return
const next = new Set(value)
for (const item of enabledItems) {
if (action === "expand") next.add(item.value)
else next.delete(item.value)
}
commit(next)
}
function handleTriggerKeyDown(event: React.KeyboardEvent<HTMLButtonElement>) {
const root = event.currentTarget.closest(ROOT_SELECTOR)
// An accordion placed inside a panel keeps its own arrow-key scope.
const triggers = Array.from(
root?.querySelectorAll<HTMLButtonElement>(TRIGGER_SELECTOR) ?? []
).filter((trigger) => trigger.closest(ROOT_SELECTOR) === root)
const index = triggers.indexOf(event.currentTarget)
const target = {
ArrowDown: triggers[(index + 1) % triggers.length],
ArrowUp: triggers[(index - 1 + triggers.length) % triggers.length],
Home: triggers[0],
End: triggers[triggers.length - 1],
}[event.key]
if (!target) return
event.preventDefault()
target.focus()
}
function handleToolbarKeyDown(event: React.KeyboardEvent<HTMLButtonElement>) {
// Two buttons: either arrow lands on the other one, in both directions of text.
const other = 1 - toolbarIndex
const next = { ArrowLeft: other, ArrowRight: other, Home: 0, End: 1 }[
event.key
]
if (next === undefined) return
event.preventDefault()
const buttons = event.currentTarget.parentElement?.querySelectorAll("button")
buttons?.[next]?.focus()
}
const bulkButtons = [
{ action: "expand", label: expandLabel, enabled: canExpand, Icon: ChevronsUpDown },
{ action: "collapse", label: collapseLabel, enabled: canCollapse, Icon: ChevronsDownUp },
] as const
return (
<div
data-slot="accordion-multi-open-controls"
data-density={density}
aria-busy={loading || undefined}
className={cn("@container w-full text-sm", className)}
{...props}
>
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 px-2 pb-3">
<p
role="status"
data-slot={`${SLOT}-count`}
className="font-medium tabular-nums text-foreground"
>
{countText}
</p>
<div
role="toolbar"
aria-label={controlsLabel}
aria-orientation="horizontal"
data-slot={`${SLOT}-toolbar`}
className="flex flex-wrap items-center gap-2"
>
{bulkButtons.map(({ action, label, enabled, Icon }, index) => (
<Button
key={action}
type="button"
variant="outline"
size="sm"
data-action={action}
tabIndex={toolbarIndex === index ? 0 : -1}
aria-disabled={!enabled}
onClick={() => bulk(action)}
onFocus={() => setToolbarIndex(index)}
onKeyDown={handleToolbarKeyDown}
className={bulkButtonClass}
>
<Icon aria-hidden="true" />
{label}
</Button>
))}
</div>
</div>
<div
data-slot={`${SLOT}-list`}
className="divide-y divide-border border-y border-border"
>
{loading ? <Skeleton rowClass={rowClass} /> : null}
{!loading && items.length === 0 ? (
<div
data-slot={`${SLOT}-empty`}
className="px-2 py-6 text-muted-foreground"
>
{empty}
</div>
) : null}
{(loading ? [] : items).map((item, index) => {
const open = openSet.has(item.value)
const triggerId = `${baseId}-trigger-${index}`
const panelId = `${baseId}-panel-${index}`
return (
<div
key={item.value}
data-slot={`${SLOT}-item`}
data-state={open ? "open" : "closed"}
>
<Heading level={headingLevel} className="flex">
<button
type="button"
id={triggerId}
aria-expanded={open}
aria-controls={panelId}
aria-disabled={item.disabled || undefined}
data-slot={`${SLOT}-trigger`}
onClick={() => toggle(item)}
onKeyDown={handleTriggerKeyDown}
className={cn(rowClass, triggerStateClass)}
>
<span className="flex min-w-0 flex-1 flex-col gap-x-4 gap-y-0.5 @md:flex-row @md:items-baseline @md:justify-between">
<span className="min-w-0 break-words font-semibold group-aria-disabled/trigger:opacity-50">
{item.title}
</span>
{item.meta ? (
<span className="font-normal tabular-nums text-muted-foreground @md:shrink-0">
{item.meta}
</span>
) : null}
</span>
<ChevronDown aria-hidden="true" className={chevronClass} />
</button>
</Heading>
<div
id={panelId}
role={labelled ? "region" : undefined}
aria-labelledby={labelled ? triggerId : undefined}
hidden={!open}
data-slot={`${SLOT}-panel`}
className="px-2 pt-0.5 pb-4"
>
{item.fields && item.fields.length > 0 ? (
<Fields fields={item.fields} emptyValueLabel={emptyValueLabel} />
) : null}
{item.content}
</div>
</div>
)
})}
</div>
</div>
)
}
The demo in the preview, 305 lines
"use client"
import * as React from "react"
import {
AccordionMultiOpenControls,
type AccordionSection,
} from "@/components/hazine/accordion-multi-open-controls"
function plural(count: number, one: string, many: string) {
return `${count} ${count === 1 ? one : many}`
}
function formatSections(open: number, total: number) {
return `${open} of ${plural(total, "section", "sections")} open`
}
// The header count is derived from the fields, so it cannot drift from the panel.
function withFieldCount(section: AccordionSection): AccordionSection {
const fields = section.fields ?? []
const missing = fields.filter((field) => !field.value).length
const count = plural(fields.length, "field", "fields")
return {
...section,
meta: missing > 0 ? `${count}, ${missing} not set` : count,
}
}
const SUPPLIER_SECTIONS: AccordionSection[] = [
{
value: "company",
title: "Company",
fields: [
{ label: "Legal name", value: "Hallberg Marine Supply AB" },
{ label: "Registration number", value: "556842-1973" },
{ label: "VAT ID", value: "SE556842197301" },
{ label: "Registered address", value: "Fiskhamnsgatan 8, 414 58 Gothenburg, Sweden" },
],
},
{
value: "contacts",
title: "Contacts",
fields: [
{ label: "Account manager", value: "Ylva Norrgard" },
{ label: "Orders inbox", value: "orders@hallbergmarine.example" },
{ label: "Phone", value: "+46 31 555 01 42" },
{ label: "Escalation contact" },
],
},
{
value: "payment",
title: "Payment terms",
fields: [
{ label: "Currency", value: "SEK" },
{ label: "Terms", value: "Net 30" },
{ label: "Early payment", value: "2% off when paid within 10 days" },
{ label: "Credit limit", value: "SEK 750,000" },
{ label: "Bank account", value: "SE35 5000 0000 0549 1000 0003" },
],
},
{
value: "shipping",
title: "Shipping",
fields: [
{ label: "Incoterm", value: "FCA Gothenburg" },
{ label: "Lead time", value: "12 business days" },
{ label: "Carrier", value: "Nordsund Freight" },
],
},
{
value: "compliance",
title: "Compliance",
fields: [
{ label: "ISO 9001 certificate", value: "Valid to Aug 31, 2027" },
{ label: "Sanctions screening", value: "Cleared Oct 2, 2026" },
{ label: "Conflict minerals statement" },
],
},
].map(withFieldCount)
// The measure sits one level inside the full-width root, so a canvas that sizes
// the root of a demo cannot stretch the content.
function Frame({ className, children }: { className: string; children: React.ReactNode }) {
return (
<div className="w-full">
<div className={`mx-auto flex flex-col ${className}`}>{children}</div>
</div>
)
}
export default function AccordionMultiOpenControlsDemo() {
const [open, setOpen] = React.useState(["company", "payment"])
const query = open.length > 0 ? `?open=${open.join(",")}` : ""
return (
<Frame className="max-w-xl gap-4">
<p className="px-2 text-sm text-pretty text-muted-foreground">
<span className="font-medium text-foreground">
Hallberg Marine Supply.
</span>{" "}
Supplier record, last reviewed{" "}
<time dateTime="2026-10-02">Oct 2, 2026</time>.
</p>
<AccordionMultiOpenControls
items={SUPPLIER_SECTIONS}
value={open}
onValueChange={setOpen}
formatCount={formatSections}
controlsLabel="Supplier record sections"
/>
<p className="px-2 text-xs text-muted-foreground">
Link to this view:{" "}
<span className="font-mono break-all text-foreground">
/suppliers/hallberg-marine{query}
</span>
</p>
</Frame>
)
}
const LOCKED_SECTIONS: AccordionSection[] = SUPPLIER_SECTIONS.map((section) => {
if (section.value === "payment") {
return { ...section, disabled: true, meta: "Finance only" }
}
if (section.value === "compliance") {
return { ...section, disabled: true, meta: "Always shown during an audit" }
}
return section
})
function DisabledScenario() {
return (
<Frame className="max-w-xl gap-3">
<AccordionMultiOpenControls
items={LOCKED_SECTIONS}
defaultValue={["company", "compliance"]}
formatCount={formatSections}
/>
<p className="px-2 text-xs text-pretty text-muted-foreground">
Locked sections keep their state. Expand all and Collapse all change
the other three.
</p>
</Frame>
)
}
function LoadingScenario() {
return (
<Frame className="max-w-xl">
<AccordionMultiOpenControls
items={[]}
loading
loadingLabel="Loading supplier record"
/>
</Frame>
)
}
function EmptyScenario() {
return (
<Frame className="max-w-xl">
<AccordionMultiOpenControls
items={[]}
empty={
<>
This supplier has no details yet. Sections appear here as soon as
the onboarding form is submitted.{" "}
<a
href="#send-onboarding-form"
className="inline-flex min-h-6 items-center rounded-sm font-medium text-foreground underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
>
Send the onboarding form
</a>
</>
}
/>
</Frame>
)
}
const CHECKLIST_SECTIONS: AccordionSection[] = [
{
value: "samples",
title: "Request product samples",
meta: "Done Sep 18",
content: (
<p className="max-w-prose text-muted-foreground">
Three stainless shackles and one mooring swivel arrived on Sep 18. The
lab report is attached to the supplier record.
</p>
),
},
{
value: "audit",
title: "Schedule the site audit",
meta: "Due Nov 20",
content: (
<div className="flex max-w-prose flex-col gap-3 text-muted-foreground">
<p>
A site audit is required before the first purchase order above SEK
250,000. Propose two dates and the audit team confirms one.
</p>
<p>
Audits at the Gothenburg plant run Tuesday to Thursday and take one
working day.
</p>
</div>
),
},
{
value: "contract",
title: "Sign the framework agreement",
meta: "Waiting on audit",
content: (
<p className="max-w-prose text-muted-foreground">
Legal sends the agreement once the audit report is filed. Signing
unlocks purchase orders for this supplier.
</p>
),
},
]
function CustomContentScenario() {
return (
<Frame className="max-w-xl">
<AccordionMultiOpenControls
items={CHECKLIST_SECTIONS}
defaultValue={["audit"]}
density="comfortable"
headingLevel={4}
formatCount={(open, total) =>
`${open} of ${plural(total, "step", "steps")} open`
}
controlsLabel="Onboarding steps"
/>
</Frame>
)
}
const WAREHOUSES = [
"Gothenburg",
"Malmo",
"Aarhus",
"Stavanger",
"Bergen",
"Turku",
"Gdansk",
"Klaipeda",
"Rostock",
"Esbjerg",
"Tallinn",
"Riga",
"Kalmar",
"Oulu",
]
const OVERFLOW_SECTIONS: AccordionSection[] = [
{
value: "contract",
title:
"Framework agreement for stainless deck hardware, mooring equipment and replacement parts across all Nordic and Baltic warehouses",
fields: [
{ label: "Contract reference", value: "FA-2026-000418-HALLBERG-MARINE-SUPPLY-NORDIC-BALTIC" },
{
label: "Scope",
value:
"Covers every catalogue line in groups 40 to 47, including parts ordered on behalf of charter customers and items drop shipped from the Gothenburg plant.",
},
{ label: "Annual volume commitment", value: "SEK 12,480,000" },
{ label: "Renewal notice" },
],
},
...WAREHOUSES.map((city, index) => ({
value: `warehouse-${index + 1}`,
title: `${city} warehouse`,
fields: [
{ label: "Receiving dock", value: `Dock ${(index % 4) + 1}` },
{ label: "Receiving hours", value: "Weekdays, 7:00 AM to 3:30 PM" },
{ label: "Pallets per delivery", value: String(18 + index * 2) },
],
})),
].map(withFieldCount)
function OverflowScenario() {
return (
<Frame className="max-w-sm">
<AccordionMultiOpenControls
items={OVERFLOW_SECTIONS}
defaultValue={["contract", "warehouse-3"]}
density="compact"
formatCount={formatSections}
expandLabel="Expand all warehouses and terms"
collapseLabel="Collapse all"
/>
</Frame>
)
}
export const scenarios = {
disabled: DisabledScenario,
loading: LoadingScenario,
empty: EmptyScenario,
"custom-content": CustomContentScenario,
overflow: OverflowScenario,
}
Props13
- itemsrequired
- AccordionSection[]
- value
- string[]
- Values of the open sections, in the order of `items`.
- defaultValue
- string[]
- onValueChange
- (value: string[]) => void
- headingLevel
- HeadingLevel = 3
- Rank of every section header.
- controlsLabel
- string = "Section controls"
- Accessible name of the toolbar that holds the two bulk buttons.
- expandLabel
- string = "Expand all"
- collapseLabel
- string = "Collapse all"
- formatCount
- (open: number, total: number) => string = defaultFormatCount
- Count beside the toolbar. It is a status region, so every change is announced.
- emptyValueLabel
- string = "Not set"
- Text shown for a field without a value.
- loading
- boolean = false
- loadingLabel
- string = "Loading sections"
- empty
- React.ReactNode = "No sections to show."
- Shown in place of the sections when `items` is empty.
Also accepts every prop of Omit<React.ComponentProps<"div">, "defaultValue" | "onChange" | "children"> and VariantProps<typeof accordionMultiOpenControlsVariants>.
Accessibility
- Keyboard
Keyboard support for Multi-Open Accordion with Controls Key Effect Tab Moves to the toolbar, then to each section header and into any open panel, in document order Arrow Left, Arrow Right in the toolbar Moves between Expand all and Collapse all Home, End in the toolbar Moves to the first or last bulk button Enter or Space on a bulk button Opens or closes every section that is not locked, and announces the new count Enter or Space on a header Opens or closes that section and announces the new count. A locked header does nothing Arrow Up, Arrow Down on a header Moves to the previous or next header, wrapping at the ends Home, End on a header Moves to the first or last header - Screen reader
Each header is a heading that wraps a button with aria-expanded and aria-controls. Panels are labelled regions while there are six or fewer. The bulk buttons sit in a labelled toolbar and use aria-disabled so focus is never lost. The open count beside them is a status region, so every change is announced.
- Announces: {open} of {total} open
- Announces: Loading sections
- Reduced motion
- Panels open and close instantly in every mode. The chevron rotation is not animated, and the loading skeleton does not pulse.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies5
- button
- @hazine/heading
- @hazine/use-controllable-state
- lucide-react
- class-variance-authority
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.