Skip to content

Chart Accordion

Beta

A record's sections with their headers composed to the house rules, so a severity can never reach the screen without the words that explain it.

7 states23 props30.1 KB installedsince 0.3.0
npx @zoblocks/cli add chart-accordion
View sourceRegistry JSON ↗

Why it exists

Accordion will happily let a product build a header that says nothing, and at fourteen sections that produces a chart nobody reads.

This component closes that gap by composing the summary itself from a small, closed vocabulary. The type does the enforcing: passing severity without status is a build error, because a coloured rail with no words beside it is a signal that forced-colors mode discards, monochrome printing discards, and roughly one in twelve men cannot resolve. The expand-all control is here rather than on the primitive because expanding a whole record is a chart-shaped action — it is what makes the record searchable and printable in one press — and it has to know not to touch a withheld section.

Playground

Change a prop and watch the component and its code change with it.

Design language
Okonkwo, A. · MRN 4471902

Ideation 3 — active thoughts, no plan, no intent, no preparatory behaviour.

Props
Playground.tsx
import { ChartAccordion } from "@/components/zoblocks/chart-accordion";export default function Example() {  return (    <ChartAccordion      sections={chartSections}      toolbarLabel="Okonkwo, A. · MRN 4471902"      defaultOpenKeys={["risk"]}      toolbar      density="clinical"    />  );}

Examples

The cases worth copying. Open one in StackBlitz to run it with its dependencies installed.

The closed record already tells you where to look

Five sections, none opened. Severity, status, counts and timestamps make the record legible before the reader expands anything. The summary is the point, not decoration around the disclosure.

Open the sections that need attention

A record can start with selected sections open. The reader gets the relevant detail immediately without losing the summaries or the ability to expand the rest.

Every severity arrives with its words

Critical, high, normal and unknown all carry a status. The closed header never relies on colour alone to communicate clinical meaning.

Expand the record, without crossing a boundary

The toolbar opens every section the reader may access and closes them again. A withheld section stays closed: expand all is a chart action, not permission to disclose.

Withheld means withheld, not empty

A separately retained section says that it is restricted and why. It has no hidden children to reveal, and expanding the rest of the record does not change that boundary.

One failed section does not take down the record

A failed care-team section identifies its own incomplete content. The other sections remain available, and the reader is not left guessing whether the entire record loaded.

An empty record still has an identity

With no sections to display, the toolbar label still identifies whose record is being viewed. An empty result is distinguishable from a component that failed to render.

Installation

Terminal
npx @zoblocks/cli add chart-accordion

First install? Run zoblocks init once to say where your @/ alias points. The source is copied into your repository, along with anything it depends on.

Dependenciesclsxtailwind-merge

Usage

Props are the FHIR resource.

usage.tsx
import { ChartAccordion } from "@/components/zoblocks/chart-accordion";<ChartAccordion  toolbarLabel="Ada Lovelace · 38 · MRN 4471902"  headingLevel={2}  onDisclose={async (event) => audit.record(event)}  sections={[    {      key: "risk",      label: "Risk & suicidality",      severity: "critical",      status: "C-SSRS positive",      updatedAt: "2026-08-13T09:12:00+05:30",      children: <RiskPanel {...risk} />,    },    {      key: "meds",      label: "Medications",      severity: "high",      status: "Clozapine ANC due 18 Aug",      count: "4 active",      children: <MedicationList {...meds} />,    },    {      key: "psychotherapy",      label: "Psychotherapy notes",      access: { kind: "withheld", reason: "Kept separately by the author" },    },  ]}/>

Use it when

  • The main record view, where sections are read closed more often than open.
  • Any list of sections where at least one can carry a severity.
  • Surfaces that need to be printable in one action.

Avoid it when

  • Patient-facing surfaces — this is clinician density and clinician vocabulary. Compose Accordion directly.
  • Two or three sections. The toolbar and the summary vocabulary are overhead at that size.
  • As a layout for content with no state to summarise. Use Accordion.

API

Every prop is typed. Props not listed are forwarded to the root element.

ChartAccordion

23 props

23 props

sectionsrequired
readonly ChartSection[]
Default—
The record's sections, in the order the house reads them. Each carries its own summary, severity and access rules.
bordered
boolean
Default—
Draw the container border.
classNames
Partial<Record<AccordionSlot, string>>
Default—
Per-slot class names, matching Ant Design v6's semantic DOM.
collapsible
'header' | 'icon' | 'disabled'
Default—
Which part of the header activates the section.
defaultOpenKeys
readonly React.Key[]
Default—
Open on first render.
density
AccordionDensity
Default"clinical"
Overrides any inherited `data-zb-density`.
destroyOnHidden
boolean
Default—
Unmount a section's content when it closes. Ant Design v6 naming.
expandIcon
((props: { item: AccordionItem; isOpen: boolean; }) => React.ReactNode)
Default—
Replace the chevron. Receives the item and whether it is open.
expandIconPlacement
'start' | 'end'
Default—
Ant Design v6 naming — `expandIconPosition` was renamed in v6.
findable
boolean
Default—
Make collapsed content reachable by find-in-page and fragment navigation. On by default. Turning it off is a decision to make Ctrl+F miss content the record contains.

Page 1 of 3

Accessibility

Screen readers and semantics

  • Severity is never alone. The type requires a status alongside a severity, so the rail always has words beside it. The chip renders text plus colour plus a token-driven border, and the text is what survives forced-colors mode and a monochrome print.
  • Expand all is a real control, not a link. Both toolbar controls are buttons with a 24px minimum target, focusable in order, and they change the accordion's controlled state rather than reaching into the DOM.
  • Timestamps carry their precision. updatedAt renders inside a <time datetime> using the exact string the record holds, so a FHIR 2026-08 stays August rather than being widened to the first of the month.

Source

Exactly what lands in your repository, read from the published registry so it can never drift from what the CLI installs.

Show source261 lines
chart-accordion.tsx
"use client";/** * ChartAccordion — the record's sections, readable while closed. * * `Accordion` will let you build a header that says nothing. This one will not. * A section's summary is composed here from a small, closed vocabulary — a * status with a severity, a count, a time — so the two rules that matter cannot * be forgotten at the call site: * *   1. **Severity never travels alone.** A rail with no words is colour *      carrying meaning, which forced-colors mode discards, monochrome printing *      discards, and roughly one in twelve men cannot resolve. Passing *      `severity` without `status` is a type error. *   2. **A time is a time.** `updatedAt` is rendered from the string the record *      holds, at the precision the record holds it, beside its zone. A relative *      time alone ("3 hours ago") is not a clinical timestamp. * * Everything else is `Accordion`, including the access model. The toolbar is * here rather than there because expanding a whole chart is a chart-shaped * action: it is what makes the record printable and searchable in one press, * and it must never expand a section the reader may not have. */import * as React from "react";import { cn } from "@/lib/utils";import {  Accordion,  type AccordionDensity,  type AccordionProps,} from "@/components/zoblocks/accordion";import {  DEFAULT_ACCORDION_LOCALE,  isWithheld,  type AccessDescriptor,  type AccordionHeadingLevel,  type AccordionItem,  type AccordionSeverity,  type DisclosureEvent,} from "@/lib/zoblocks-accordion";interface ChartSectionBase {  key: React.Key;  /** The section's name, as the reader's vocabulary spells it. */  label: React.ReactNode;  /** Content. Omitted for a withheld section, which has none. */  children?: React.ReactNode;  /**   * The one fact that would change what the reader does next.   *   * Required alongside `severity`, because a coloured rail with nothing beside   * it is a signal only some readers receive.   */  status?: React.ReactNode;  /** How many things are in here. Rendered beside the status, never instead of it. */  count?: React.ReactNode;  /**   * When this section last changed, as the record spells it.   *   * A string rather than a Date: a FHIR `2026-08` means August, and widening it   * to the first of the month invents a precision nobody recorded.   */  updatedAt?: string;  access?: AccordionItem["access"];  pinned?: boolean;}/** * Severity and status travel together or not at all. * * Enforced in the type rather than at runtime, so the omission is a build * failure at the call site instead of a missing signal in a rendered chart. */export type ChartSection =  | (ChartSectionBase & { severity: AccordionSeverity; status: React.ReactNode })  | (ChartSectionBase & { severity?: undefined });export interface ChartAccordionProps extends Omit<  AccordionProps,  "items" | "activeKey" | "defaultActiveKey" | "accordion" | "onChange"> {  /**   * The record's sections, in the order the house reads them. Each carries its own summary,   * severity and access rules.   */  sections: readonly ChartSection[];  /** Open on first render. */  defaultOpenKeys?: readonly React.Key[];  /** Fired with the open sections whenever they change. */  onChange?: (keys: React.Key[]) => void;  /** Show "Expand all" and "Collapse all". On by default. */  toolbar?: boolean;  /** Leading content in the toolbar — usually who the record belongs to. */  toolbarLabel?: React.ReactNode;  headingLevel?: AccordionHeadingLevel;  density?: AccordionDensity;  onDisclose?: (event: DisclosureEvent) => boolean | Promise<boolean>;}const SEVERITY_CLASS: Record<AccordionSeverity, string> = {  critical: "zb-chip--critical",  high: "zb-chip--high",  low: "zb-chip--low",  normal: "zb-chip--normal",  unknown: "zb-chip--unknown",};/** * A severity chip. * * A literal lookup rather than an interpolated class name: Tailwind resolves * classes by scanning source text, so a class assembled at runtime produces no * CSS — which on a severity chip silently deletes the signal. * * This should route through StatusBadge once that component lands, so that * critical reads identically here, on a lab result, and on a medication. Until * then it uses the same `--zb-badge-*` tokens, which is what makes that a * refactor rather than a re-design. */function Chip({ severity, children }: { severity?: AccordionSeverity; children: React.ReactNode }) {  return (    <span className={cn("zb-chip", severity ? SEVERITY_CLASS[severity] : undefined)}>      {children}    </span>  );}function summaryFor(section: ChartSection): React.ReactNode {  const parts: React.ReactNode[] = [];  if (section.status !== undefined && section.status !== null) {    parts.push(      <Chip key="status" {...(section.severity ? { severity: section.severity } : {})}>        {section.status}      </Chip>,    );  }  if (section.count !== undefined && section.count !== null) {    parts.push(      <span key="count" className="zb-chart-accordion__count">        {section.count}      </span>,    );  }  if (section.updatedAt) {    parts.push(      <time key="time" className="zb-chart-accordion__time" dateTime={section.updatedAt}>        {section.updatedAt}      </time>,    );  }  return parts.length ? parts : undefined;}export function ChartAccordion({  sections,  defaultOpenKeys,  onChange,  toolbar = true,  toolbarLabel,  headingLevel = 3,  density = "clinical",  locale: localeOverride,  className,  ...rest}: ChartAccordionProps) {  const locale = React.useMemo(    () => ({ ...DEFAULT_ACCORDION_LOCALE, ...localeOverride }),    [localeOverride],  );  const [openKeys, setOpenKeys] = React.useState<React.Key[]>(() => [...(defaultOpenKeys ?? [])]);  const commit = React.useCallback(    (keys: React.Key[]) => {      setOpenKeys(keys);      onChange?.(keys);    },    [onChange],  );  const items = React.useMemo<AccordionItem[]>(    () =>      sections.map((section) => {        const summary = summaryFor(section);        const base = {          /*           * Typed from the target rather than inferred from the source.           *           * Both sides declare `React.Key`, but React 19 leaves that alias open           * for a host to extend, and Next does extend it. Compiled under this           * repository's config the two agree; compiled under the docs app's,           * the inferred literal picked up the widened alias and the declared           * one did not, so building the items failed to typecheck in the only           * project that renders them. Reading the type off `AccordionItem`           * makes them the same type by construction, under any host.           */          key: section.key as AccordionItem["key"],          label: section.label,          ...(summary === undefined ? {} : { summary }),          ...(section.severity ? { severity: section.severity } : {}),          ...(section.pinned ? { pinned: section.pinned } : {}),        };        // The withheld arm is a separate object literal rather than a spread,        // so the discriminated union still discriminates: TypeScript cannot see        // through a conditional spread to know `children` was never set.        const access = section.access as AccessDescriptor | undefined;        if (access?.kind === "withheld") {          return { ...base, access };        }        return {          ...base,          ...(access ? { access } : {}),          ...(section.children === undefined ? {} : { children: section.children }),        };      }),    [sections],  );  const expandable = React.useMemo(    () => items.filter((item) => !isWithheld(item)).map((item) => item.key),    [items],  );  return (    <div className={cn("zb-chart-accordion", className)}>      {toolbar ? (        <div className="zb-chart-accordion__toolbar">          {toolbarLabel ? (            <span className="zb-chart-accordion__toolbar-label">{toolbarLabel}</span>          ) : null}          <span className="zb-chart-accordion__toolbar-actions">            <button              type="button"              className="zb-chart-accordion__action"              onClick={() => commit([...expandable])}            >              {locale.expandAll}            </button>            <button type="button" className="zb-chart-accordion__action" onClick={() => commit([])}>              {locale.collapseAll}            </button>          </span>        </div>      ) : null}      <Accordion        {...rest}        items={items}        activeKey={openKeys}        onChange={commit}        headingLevel={headingLevel}        density={density}        locale={locale}      />    </div>  );}