Disclosure
A native <details> that animates height and opacity both ways and reverses mid-flight. Wrap several in a DisclosureGroup for single-open behaviour built on the details name attribute.
Preview
Can I change my plan later?
Yes. Upgrades apply immediately and downgrades take effect at the end of the current billing period.
Is there a free trial?
Every plan starts with a 14-day trial. No card is needed until you decide to keep it, and you can export your data at any time.
Which payment methods do you accept?
- Major credit and debit cards
- Bank transfer for annual plans
- Invoices for teams of ten or more
How do I cancel?
Open Settings, then Billing, and choose Cancel plan. You keep access until the period ends.
Install
npx shadcn@latest add @dxbh-ui/disclosure
Add the @dxbh-ui registry to components.json once:
{
"registries": {
"@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
}
}Usage
"use client";
import { Disclosure, DisclosureGroup } from "@/components/ui/disclosure/disclosure";
const faqs = [
{
q: "Can I change my plan later?",
a: "Yes. Upgrades apply immediately and downgrades take effect at the end of the current billing period.",
},
{
q: "Is there a free trial?",
a: (
<>
Every plan starts with a 14-day trial. No card is needed until you decide to keep it, and you can{" "}
<a href="#" className="font-medium text-foreground underline underline-offset-4">
export your data
</a>{" "}
at any time.
</>
),
},
{
q: "Which payment methods do you accept?",
a: (
<ul className="list-disc space-y-1 pl-5">
<li>Major credit and debit cards</li>
<li>Bank transfer for annual plans</li>
<li>Invoices for teams of ten or more</li>
</ul>
),
},
{
q: "How do I cancel?",
a: "Open Settings, then Billing, and choose Cancel plan. You keep access until the period ends.",
},
];
export default function DisclosureDemo() {
return (
<div className="w-full max-w-md">
<DisclosureGroup className="border-t border-border">
{faqs.map((item, i) => (
<Disclosure key={item.q} summary={item.q} defaultOpen={i === 0}>
{item.a}
</Disclosure>
))}
</DisclosureGroup>
</div>
);
}Props
| Prop | Type | Default |
|---|---|---|
summary*The always-visible row, such as a question. | ReactNode | — |
children*The revealed content. | ReactNode | — |
defaultOpenOpen on first render, including on the server. | boolean | false |
onOpenChangeCalled when it starts opening or closing. | (open: boolean) => void | — |
nameNative exclusive group name when used without DisclosureGroup (siblings close without animation). | string | — |
contentClassNameClasses for the content wrapper. | string | — |
DisclosureGroup.nameShared details name for the group's items. | string | generated |
Polish
- Native details and summary keep semantics, find-in-page and the no-JS fallback.
- Open and close both interpolate height with opacity, the one place dxbh-ui animates height. Clicking mid-flight reverses from the current height.
- Exits run about 20% faster than enters (220ms in, 180ms out) on the dxbh-ui ease-out curve.
- Exclusive groups use details name; the closing sibling drops the name while it animates so the browser doesn't snap it shut.
- Keyboard toggles (Enter, Space) are instant: keyboard actions never animate.
- The chevron rotates with ease-out as soon as the state flips, not when the close finishes.
- Reduced motion keeps an opacity fade and drops height and rotation.
- Summary presses to 0.98 and shows a focus-visible ring. Answers take any ReactNode, not just a string.
- Apricot's Radix accordion and its brand colours are replaced by native elements and the shadcn palette.
Source
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
type DetailsHTMLAttributes,
type HTMLAttributes,
type MouseEvent,
type ReactNode,
type SyntheticEvent,
} from "react";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { prefersReducedMotion } from "@/hooks/use-reduced-motion";
// Height animates here and nowhere else in dxbh-ui, paired with opacity the way
// Sonner does it. Exits run about 20% faster than enters.
const OPEN_MS = 220;
const CLOSE_MS = 180;
const EASE = "var(--ease-out, cubic-bezier(0.23, 1, 0.32, 1))";
type Frames = { height?: [number, number]; opacity: [string, string] };
/**
* Runs one height/opacity transition on `panel` from wherever it is now.
* CSS transitions retarget, so calling this again mid-flight reverses
* smoothly. Returns a function that cancels the pending completion.
*/
function play(panel: HTMLElement, frames: Frames, ms: number, done: () => void) {
const props = frames.height ? ["height", "opacity"] : ["opacity"];
panel.style.transition = "none";
panel.style.overflow = "hidden";
if (frames.height) panel.style.height = `${frames.height[0]}px`;
panel.style.opacity = frames.opacity[0];
void panel.getBoundingClientRect(); // commit the start frame
panel.style.transition = props.map((p) => `${p} ${ms}ms ${EASE}`).join(", ");
if (frames.height) panel.style.height = `${frames.height[1]}px`;
panel.style.opacity = frames.opacity[1];
const stop = () => {
panel.removeEventListener("transitionend", onEnd);
clearTimeout(timer);
};
function onEnd(event?: TransitionEvent) {
if (event && (event.target !== panel || event.propertyName !== props[0])) return;
stop();
done();
}
panel.addEventListener("transitionend", onEnd);
// transitionend never fires in a hidden tab or when nothing changed.
const timer = setTimeout(onEnd, ms + 60);
return stop;
}
function clearMotion(panel: HTMLElement) {
panel.style.transition = "";
panel.style.height = "";
panel.style.opacity = "";
panel.style.overflow = "";
}
type Member = { close: (instant: boolean) => void; isOpen: () => boolean };
type GroupContext = {
name: string;
register: (id: string, member: Member) => () => void;
closeOthers: (id: string, instant: boolean) => void;
};
const DisclosureGroupContext = createContext<GroupContext | null>(null);
export type DisclosureGroupProps = HTMLAttributes<HTMLDivElement> & {
/** The shared `<details name>`. Defaults to a generated id. */
name?: string;
};
/**
* Makes its Disclosures exclusive: opening one closes the others. Uses the
* native `<details name>` attribute, so it works before hydration and with
* find-in-page, and animates the sibling closing instead of snapping it shut.
*/
export function DisclosureGroup({ name, className, children, ...props }: DisclosureGroupProps) {
const generated = useId();
const groupName = name ?? `disclosure-${generated.replace(/[^\w-]/g, "")}`;
const members = useRef(new Map<string, Member>());
const context = useMemo<GroupContext>(
() => ({
name: groupName,
register(id, member) {
members.current.set(id, member);
return () => void members.current.delete(id);
},
closeOthers(id, instant) {
for (const [other, member] of members.current) {
if (other !== id && member.isOpen()) member.close(instant);
}
},
}),
[groupName],
);
return (
<DisclosureGroupContext.Provider value={context}>
<div className={cn("flex flex-col", className)} {...props}>
{children}
</div>
</DisclosureGroupContext.Provider>
);
}
export type DisclosureProps = Omit<
DetailsHTMLAttributes<HTMLDetailsElement>,
"open" | "onToggle" | "children" | "summary"
> & {
/** The always-visible row, such as a question. */
summary: ReactNode;
/** The revealed content, such as an answer. Any node: links, lists, code. */
children: ReactNode;
/** Open on first render, including the server render. */
defaultOpen?: boolean;
/** Called when the disclosure starts opening or closing. */
onOpenChange?: (open: boolean) => void;
/** Classes for the content wrapper. */
contentClassName?: string;
};
/**
* A native `<details>` whose open and close both animate height and opacity.
* The toggle is intercepted because CSS alone cannot animate the close: the
* browser hides the content the moment `[open]` goes away.
*/
export function Disclosure({
summary,
children,
defaultOpen = false,
onOpenChange,
name,
className,
contentClassName,
...props
}: DisclosureProps) {
const group = useContext(DisclosureGroupContext);
const id = useId();
const detailsRef = useRef<HTMLDetailsElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const [initialOpen] = useState(defaultOpen);
const [open, setOpen] = useState(defaultOpen);
// Where the element is heading while a transition runs.
const phase = useRef<"opening" | "closing" | null>(null);
const cancel = useRef<(() => void) | null>(null);
const groupName = group?.name ?? name;
const restoreName = useCallback(() => {
const details = detailsRef.current;
if (details && groupName) details.setAttribute("name", groupName);
}, [groupName]);
const toggle = useCallback(
(next: boolean, instant: boolean) => {
const details = detailsRef.current;
const panel = panelRef.current;
if (!details || !panel) return;
cancel.current?.();
cancel.current = null;
setOpen(next);
onOpenChange?.(next);
if (next) {
// Close siblings first: they drop the shared name while they animate,
// so opening this one doesn't make the browser snap them shut.
group?.closeOthers(id, instant);
restoreName();
} else if (groupName) {
details.removeAttribute("name");
}
if (instant) {
phase.current = null;
details.open = next;
clearMotion(panel);
restoreName();
return;
}
const reduced = prefersReducedMotion();
const fromHeight = panel.getBoundingClientRect().height;
const fromOpacity = phase.current ? getComputedStyle(panel).opacity : next ? "0" : "1";
phase.current = next ? "opening" : "closing";
if (next) {
details.open = true;
const frames: Frames = reduced
? { opacity: [fromOpacity, "1"] }
: { height: [fromHeight, panel.scrollHeight], opacity: [fromOpacity, "1"] };
cancel.current = play(panel, frames, OPEN_MS, () => {
phase.current = null;
cancel.current = null;
clearMotion(panel);
});
return;
}
const frames: Frames = reduced
? { opacity: [fromOpacity, "0"] }
: { height: [fromHeight, 0], opacity: [fromOpacity, "0"] };
cancel.current = play(panel, frames, CLOSE_MS, () => {
phase.current = null;
cancel.current = null;
details.open = false;
clearMotion(panel);
restoreName();
});
},
[group, groupName, id, onOpenChange, restoreName],
);
const isOpen = useCallback(() => phase.current === "opening" || (phase.current === null && !!detailsRef.current?.open), []);
useEffect(() => group?.register(id, { close: (instant) => toggle(false, instant), isOpen }), [group, id, toggle, isOpen]);
useEffect(() => () => cancel.current?.(), []);
const onSummaryClick = (event: MouseEvent<HTMLElement>) => {
event.preventDefault();
const details = detailsRef.current;
if (!details) return;
const next = phase.current ? phase.current === "closing" : !details.open;
// detail is 0 for Enter/Space: keyboard toggles never animate.
toggle(next, event.detail === 0);
};
// Opened or closed by something other than the summary: find-in-page,
// the browser closing a named sibling, or a script setting `open`.
const onToggle = (event: SyntheticEvent<HTMLDetailsElement>) => {
if (phase.current) return;
const nowOpen = event.currentTarget.open;
if (nowOpen === open) return;
setOpen(nowOpen);
onOpenChange?.(nowOpen);
if (panelRef.current) clearMotion(panelRef.current);
};
return (
<details
ref={detailsRef}
name={groupName}
open={initialOpen}
onToggle={onToggle}
data-state={open ? "open" : "closed"}
className={cn("group/disclosure border-b border-border", className)}
{...props}
>
<summary
onClick={onSummaryClick}
className={cn(
"flex min-h-12 cursor-pointer list-none items-center justify-between gap-4 rounded-md py-3 text-left text-sm font-medium outline-none select-none",
"transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.98] motion-reduce:active:scale-100",
"focus-visible:ring-2 focus-visible:ring-ring/50 [&::-webkit-details-marker]:hidden",
)}
>
<span className="min-w-0">{summary}</span>
<ChevronDown
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground transition-transform duration-(--duration-modal,240ms) ease-out group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none"
/>
</summary>
<div ref={panelRef}>
<div className={cn("pb-4 text-sm leading-relaxed text-muted-foreground", contentClassName)}>{children}</div>
</div>
</details>
);
}Extracted from moments-website/components/marketing/faq-disclosure.tsx at f1d46a9, Apricot/src/components/AboutAccordion.tsx at ec7cef6.