Searchable list
Search a long list and tick items and their sub-items, such as makes and models.
Live example
36 of 256 cars
Copy
Add the "Searchable list" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Searchable list: Search a long list and tick items and their sub-items, such as makes and models.
Needs: React 19, Tailwind CSS 4.2 or later and TypeScript. If this project uses another setup, adapt the classes, keep the look.
## Install
If this project has a components.json, run: npx shadcn@latest add https://filtersui.com/r/searchable-list.json
and skip the files below.
Otherwise save each file below at the path shown, from the project root (or inside src/ if the project keeps its code there). Keep the folder layout: the files import each other by relative paths.
Install these npm packages: npm install clsx tailwind-merge
### components/filters-ui/filters/searchable-list.tsx
```tsx
"use client";
import { useEffect, useId, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { formatsFor, resultsLabel } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { SEARCH_ART } from "../ui/art-search";
import { CountPill } from "../ui/count-pill";
import { EmptyState } from "../ui/empty-state";
import { CheckIcon, SearchIcon } from "../ui/icons";
import { placeholderLabels, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextField } from "../ui/text-field";
export type SearchableListChild = {
value: string;
label: string;
count: number;
};
export type SearchableListOption = SearchableListChild & {
/** Shown indented under the option once it is ticked. Values need only be unique within their parent. */ children?: readonly SearchableListChild[];
};
/** One ticked option and the children that narrow it. No children means the whole option. */
export type SearchableListPick = {
value: string;
children: string[];
};
export type SearchableListProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
/** In display order: the first `collapsedCount` make the short list, the rest show after "All N". */
options: readonly SearchableListOption[];
value: readonly SearchableListPick[];
onChange: (value: SearchableListPick[]) => void;
/** Accessible name of the list. */
label: string;
/** Plural noun for the options: "Search makes", "All 21 makes", "No makes match". */
noun?: string;
collapsedCount?: number;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/**
* "card" (default): the look inside a FilterCard. "panel": a 48px search, 20px filled checkboxes, 17px names, counts as
* plain numbers and rows flush with the field, as in the Filter panel block. The list grows in place for its scrolling
* parent rather than scrolling in a box of its own.
*/
variant?: "card" | "panel";
};
const ROW_HEIGHT = 36;
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
// Swapped letters count as one slip, so "telsa" is one edit from "tesla".
function editDistance(a: string, b: string) {
const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
}
}
return rows[a.length][b.length];
}
/** The closest name with results, for a word of 4+ letters: one slip allowed, two past 5 letters. On a tie the longer name wins. */
function nearestName(typed: string, options: readonly SearchableListOption[]) {
if (typed.length < 4) return null;
const allowed = typed.length > 5 ? 2 : 1;
// Names further apart in length than the slips allowed cannot match, so a long paste costs nothing.
const names = options
.flatMap((o) => [o, ...(o.children ?? [])])
.filter((o) => o.count > 0 && Math.abs(o.label.length - typed.length) <= allowed);
const [best] = names
.map((o) => ({ name: o.label, edits: editDistance(typed, o.label.toLowerCase()) }))
.filter((o) => o.edits <= allowed)
.sort((a, b) => a.edits - b.edits || b.name.length - a.name.length);
return best?.name ?? null;
}
// Names in the panel look are already semibold, so there the letters around the match dim instead.
function Marked({ text, query, panel = false }: { text: string; query: string; panel?: boolean }) {
const at = query ? text.toLowerCase().indexOf(query) : -1;
if (at < 0) return <>{text}</>;
if (panel) {
const dim = "text-[var(--fu-dim,#929292)]";
return (
<>
<span className={dim}>{text.slice(0, at)}</span>
{text.slice(at, at + query.length)}
<span className={dim}>{text.slice(at + query.length)}</span>
</>
);
}
return (
<>
{text.slice(0, at)}
<b className="font-semibold">{text.slice(at, at + query.length)}</b>
{text.slice(at + query.length)}
</>
);
}
/** Opens and closes with the card's own motion: height over 480ms, content in from a 6px blur, 6px lower. */
function Reveal({ open, children }: { open: boolean; children: ReactNode }) {
return (
<div
inert={!open}
data-state={open ? "open" : "closed"}
className={cn(
"group/reveal grid grid-rows-[0fr] transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"data-[state=open]:grid-rows-[1fr]",
)}
>
<div className="min-h-0 overflow-hidden">
<div
className={cn(
"translate-y-1.5 opacity-0 blur-[6px] transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/reveal:translate-y-0 group-data-[state=open]/reveal:opacity-100 group-data-[state=open]/reveal:blur-none",
"group-data-[state=open]/reveal:delay-[120ms] group-data-[state=open]/reveal:duration-[460ms] group-data-[state=open]/reveal:ease-[cubic-bezier(0.16,1,0.3,1)]",
)}
>
{children}
</div>
</div>
</div>
);
}
type RowProps = {
label: string;
query: string;
count: number;
checked: boolean;
disabled: boolean;
nested?: boolean;
panel: boolean;
formatCount: (n: number) => string;
countLabel: (n: number) => string;
onToggle: (input: HTMLInputElement) => void;
onBlur: () => void;
};
// The whole row is the checkbox's label. A long name wraps onto more lines; the box and the count stay in the row. The native box is hidden and drawn again: 18px, 5px radius, the tile's selected fill with an accent check that draws in.
// The panel look draws it 20px with 6px corners, filled with the accent and an --fu-on-accent check once ticked.
function Row({ label, query, count, checked, disabled, nested, panel, formatCount, countLabel, onToggle, onBlur }: RowProps) {
const { loading } = useLoading();
return (
<label
data-state={checked ? "on" : "off"}
className={cn(
"group/row relative flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 rounded-[12px] py-2 pe-3 text-[14px] leading-5 text-[var(--fu-text,#F8F5F1)]",
nested ? "ps-[40px]" : "ps-3",
// 17px names on a 24px line, 6px above and below: 36px, as the card look's 20px line with 8px.
panel && "rounded-[10px] py-1.5 pe-2 text-[17px] leading-6 font-semibold pointer-coarse:min-h-11",
panel && (nested ? "ps-[38px]" : "ps-2"),
"transition-[background-color,opacity] duration-200 motion-reduce:transition-none",
"[@media(hover:hover)]:has-[input:enabled]:hover:bg-[var(--fu-wash,rgb(255_255_255/0.08))]",
// Drawn inside the row, so neither the scroll area nor the card can clip it.
"has-[input:focus-visible]:outline-2 has-[input:focus-visible]:-outline-offset-2 has-[input:focus-visible]:outline-solid has-[input:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
"has-[input:disabled]:cursor-not-allowed",
count === 0 && !checked && !loading && "opacity-40",
)}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
aria-label={`${label}, ${countLabel(count)}`}
onChange={(event) => onToggle(event.currentTarget)}
onBlur={onBlur}
className={cn("peer absolute size-[18px] cursor-[inherit] opacity-0", panel && "size-5")}
/>
<span
aria-hidden="true"
className={cn(
"grid size-[18px] shrink-0 place-items-center rounded-[5px] border border-[var(--fu-control-border,#737373)] text-[var(--fu-accent-soft,#8FAAFF)]",
"transition-[background-color,border-color] duration-200 motion-reduce:transition-none",
SMOOTH,
"[@media(hover:hover)]:group-hover/row:peer-enabled:border-[var(--fu-control-hover,#A3A3A3)]",
panel
? "size-5 rounded-[6px] border-[1.5px] bg-[var(--fu-field-wash,rgb(255_255_255/0.03))] text-[var(--fu-on-accent,#FFFFFF)] peer-checked:border-[var(--fu-accent,#3B57E6)] peer-checked:bg-[var(--fu-accent,#3B57E6)] [@media(hover:hover)]:group-hover/row:peer-checked:border-[var(--fu-accent,#3B57E6)]"
: "peer-checked:border-[var(--fu-accent-soft,#8FAAFF)] peer-checked:bg-[var(--fu-selected,#1F2747)] [@media(hover:hover)]:group-hover/row:peer-checked:border-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
<CheckIcon
size={14}
strokeWidth={3}
className={cn(
// The path is about 23 units long; a negative offset draws it from the short leg up.
"[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:-23] [&_path]:transition-[stroke-dashoffset] [&_path]:duration-200 motion-reduce:[&_path]:transition-none",
"[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] group-data-[state=on]/row:[&_path]:[stroke-dashoffset:0]",
)}
/>
</span>
<span aria-hidden="true" className="min-w-0 flex-1 [overflow-wrap:anywhere]">
<SkeletonText>
<Marked text={label} query={query} panel={panel} />
</SkeletonText>
</span>
{panel ? (
<span aria-hidden="true" className="shrink-0 font-normal tabular-nums text-[var(--fu-mute,#BDBDBD)]">
<SkeletonText>{formatCount(count)}</SkeletonText>
</span>
) : (
<CountPill aria-hidden="true" variant="square" on={checked} count={count} format={formatCount} />
)}
</label>
);
}
/**
* A search field over a checklist whose options open their own children when ticked, e.g. makes and their models.
* The short list shows the first `collapsedCount` options and grows with what is ticked; "All N" adds the rest inside a
* scroll area capped at 320px. Typing filters options and children at once, holding the short list's height so the card
* does not jump per key; a typo with no match offers the nearest name.
*/
export function SearchableList({
options,
value,
onChange,
label,
noun = "items",
collapsedCount = 8,
formatCount: formatCountProp,
countLabel: countLabelProp,
locale,
variant = "card",
status = "ready",
onRetry,
errorText = `Couldn't load the ${noun}.`,
emptyText = `No ${noun} to show`,
disabled = false,
className,
...props
}: SearchableListProps) {
const formatCount = formatCountProp ?? formatsFor(locale).number;
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const panel = variant === "panel";
const listId = useId();
const [query, setQuery] = useState("");
const [all, setAll] = useState(false);
const field = useRef<HTMLDivElement>(null);
const scroller = useRef<HTMLDivElement>(null);
const content = useRef<HTMLUListElement>(null);
const [fade, setFade] = useState({ top: false, bottom: false });
// A row turned off at 0 would become disabled under the pointer or keyboard and drop focus; it stays enabled until it loses focus.
const [kept, setKept] = useState<string | null>(null);
// Ticked options past the short list stay in it while it is short, and do not vanish when unticked there.
const tickedLater = value.map((p) => p.value).filter((v) => options.findIndex((o) => o.value === v) >= collapsedCount);
const [pinned, setPinned] = useState<string[]>(tickedLater);
if (tickedLater.some((v) => !pinned.includes(v))) setPinned([...pinned, ...tickedLater.filter((v) => !pinned.includes(v))]);
if (value.length === 0 && pinned.length > 0 && !all) setPinned([]);
const pickOf = (v: string) => value.find((p) => p.value === v);
const toggleParent = (v: string, input: HTMLInputElement) => {
const on = Boolean(pickOf(v));
setKept(on && document.activeElement === input ? v : null);
onChange(on ? value.filter((p) => p.value !== v) : [...value, { value: v, children: [] }]);
};
// Ticking a child ticks its parent too; a child narrows the parent to the children ticked.
const toggleChild = (parent: string, child: string, input: HTMLInputElement) => {
const pick = pickOf(parent);
const on = Boolean(pick?.children.includes(child));
setKept(on && document.activeElement === input ? `${parent}\n${child}` : null);
if (!pick) return onChange([...value, { value: parent, children: [child] }]);
const children = on ? pick.children.filter((c) => c !== child) : [...pick.children, child];
onChange(value.map((p) => (p.value === parent ? { ...p, children } : p)));
};
useEffect(() => {
const node = scroller.current;
const inner = content.current;
if (!node || !inner) return;
const measure = () => {
const top = node.scrollTop > 1;
const bottom = node.scrollTop + node.clientHeight < node.scrollHeight - 1;
setFade((f) => (f.top === top && f.bottom === bottom ? f : { top, bottom }));
};
measure();
node.addEventListener("scroll", measure, { passive: true });
const observer = new ResizeObserver(measure);
observer.observe(node);
observer.observe(inner);
return () => {
node.removeEventListener("scroll", measure);
observer.disconnect();
};
// The frame takes the list away in an error or with no options; its listeners go on the new box when it is back.
}, [status, options.length === 0]);
// Its own status, or the loading frame of an item around it, such as a block's card.
const loading = useLoading().loading || status === "loading";
// While the options are on their way, a short list of stand-ins keeps the place they will take.
const listed: readonly SearchableListOption[] =
loading && options.length === 0 ? placeholderLabels(collapsedCount).map((name) => ({ value: name, label: name, count: 0 })) : options;
const typed = loading ? "" : query.trim().toLowerCase();
const parentRow = (option: SearchableListOption, q: string) => {
const checked = Boolean(pickOf(option.value));
return (
<Row
label={option.label}
query={q}
count={option.count}
checked={checked}
disabled={option.count === 0 && !checked && kept !== option.value}
panel={panel}
formatCount={formatCount}
countLabel={countLabel}
onToggle={(input) => toggleParent(option.value, input)}
onBlur={() => kept === option.value && setKept(null)}
/>
);
};
const childRows = (option: SearchableListOption, children: readonly SearchableListChild[], q: string) => {
const pick = pickOf(option.value);
return (
<ul aria-label={option.label} className="m-0 list-none p-0">
{children.map((child) => {
const key = `${option.value}\n${child.value}`;
const checked = Boolean(pick?.children.includes(child.value));
return (
<li key={child.value} className="m-0 p-0">
<Row
nested
label={child.label}
query={q}
count={child.count}
checked={checked}
disabled={child.count === 0 && !checked && kept !== key}
panel={panel}
formatCount={formatCount}
countLabel={countLabel}
onToggle={(input) => toggleChild(option.value, child.value, input)}
onBlur={() => kept === key && setKept(null)}
/>
</li>
);
})}
</ul>
);
};
let rows: ReactNode;
let found = 0;
if (typed) {
const matches = options.flatMap((option) => {
const children = option.children ?? [];
const self = option.label.toLowerCase().includes(typed);
const kids = children.filter((c) => c.label.toLowerCase().includes(typed));
return self || kids.length ? [{ option, self, kids }] : [];
});
found = matches.length;
rows = matches.map(({ option, self, kids }) => {
const checked = Boolean(pickOf(option.value));
const showAll = !kids.length || (checked && self);
return (
<li key={option.value} className="m-0 p-0">
{parentRow(option, typed)}
{(option.children?.length ?? 0) > 0 && (
<Reveal open={checked || kids.length > 0}>{childRows(option, showAll ? option.children! : kids, typed)}</Reveal>
)}
</li>
);
});
} else {
rows = listed.map((option, i) => {
const item = (
<>
{parentRow(option, "")}
{(option.children?.length ?? 0) > 0 && <Reveal open={Boolean(pickOf(option.value))}>{childRows(option, option.children!, "")}</Reveal>}
</>
);
return (
<li key={option.value} className="m-0 p-0">
{i < collapsedCount ? item : <Reveal open={all || pinned.includes(option.value)}>{item}</Reveal>}
</li>
);
});
}
const none = Boolean(typed) && found === 0;
const near = none ? nearestName(typed, options) : null;
const more = listed.length > collapsedCount;
return (
<div className={cn("min-w-0", className)} {...props}>
<StatusFrame
status={status}
onRetry={onRetry}
errorText={errorText}
empty={options.length === 0}
emptyText={emptyText}
disabled={disabled}
className={cn(panel && "rounded-[14px]")}
>
<div ref={field}>
<TextField
type="search"
value={query}
onChange={setQuery}
label={`Search ${noun}`}
placeholder={`Search ${noun}`}
prefix={<SearchIcon size={panel ? 20 : 16} className="block" />}
clearLabel="Clear search"
autoComplete="off"
spellCheck={false}
className={panel ? "h-12 gap-3 bg-[var(--fu-field-wash,rgb(255_255_255/0.03))] px-3.5 text-[17px]" : undefined}
inputClassName="[&::-webkit-search-cancel-button]:appearance-none"
onKeyDown={(event) => {
if (event.key === "Escape" && query) {
event.stopPropagation();
event.preventDefault();
setQuery("");
}
}}
/>
</div>
{/* In the panel look the list reaches 8px past the field on each side, so boxes and counts line up with its edges.
The panel scrolls the whole list itself, so there the list neither scrolls in its own box nor holds its height while typing.
Opened in full, the scroll box reaches 10px into the card's padding and the rows keep the width of this box
(100cqi), so the scrollbar sits beside the rows and no count moves when it appears. */}
<div className={cn("relative mt-2", panel ? "-mx-2" : "@container")}>
<div
ref={scroller}
id={listId}
className={cn(
all && !panel && ["-me-2.5 max-h-80 scroll-py-7 overflow-x-hidden overflow-y-auto overscroll-contain", SCROLL],
)}
style={typed && !panel && !none ? { minHeight: collapsedCount * ROW_HEIGHT } : undefined}
>
<ul ref={content} aria-label={label} className={cn("m-0 list-none p-0", all && !panel && "w-[100cqi]")}>
{rows}
</ul>
</div>
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-0 top-0 h-6 bg-linear-to-b from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 motion-reduce:transition-none",
fade.top && "opacity-100",
)}
/>
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-linear-to-t from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 motion-reduce:transition-none",
fade.bottom && "opacity-100",
)}
/>
</div>
{/* Nothing matches: the picture, the line and one way on sit in the middle of the room the short list takes,
so the card keeps its height. The region stays on the page, so the line is read out when it arrives. */}
<div
role="status"
className={cn(none && "grid place-items-center px-3", none && panel && "px-0 py-6")}
style={none && !panel ? { minHeight: collapsedCount * ROW_HEIGHT } : undefined}
>
{none && (
<EmptyState
art={SEARCH_ART}
title={
<span className="flex min-w-0 justify-center">
<span className="shrink-0">No {noun} match </span>
<span className="min-w-0 truncate">“{query.trim()}</span>
<span className="shrink-0">”</span>
</span>
}
action={
<button
type="button"
onClick={() => {
setQuery(near ?? "");
field.current?.querySelector("input")?.focus();
}}
className={cn(
"relative cursor-pointer rounded-[6px] text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)] transition-[color] duration-200 before:absolute before:inset-x-0 before:-inset-y-2 before:content-[''] hover:text-[var(--fu-accent-pale,#D1DDFF)]",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
{near ? `Did you mean ${near}?` : "Clear search"}
</button>
}
/>
)}
</div>
{!typed && more && (
<button
type="button"
aria-expanded={all}
aria-controls={listId}
onClick={() => {
if (all) setPinned(tickedLater);
setAll(!all);
}}
className={cn(
"group/more relative mt-1.5 ms-3 cursor-pointer rounded-[6px] text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)] transition-[color] duration-200 hover:text-[var(--fu-accent-pale,#D1DDFF)] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-['']",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
panel && "mt-2 ms-0 text-[15px] pointer-coarse:before:-inset-y-3",
)}
>
{/* A 1px line draws in under the words from the start edge while it is hovered or focused. */}
<span
className={cn(
"bg-[linear-gradient(currentColor,currentColor)] bg-[length:0%_1px] bg-[position:0_100%] rtl:bg-[position:100%_100%] bg-no-repeat pb-px",
"transition-[background-size] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"[@media(hover:hover)]:group-hover/more:bg-[length:100%_1px] group-focus-visible/more:bg-[length:100%_1px]",
)}
>
<SkeletonText>{all ? "Show fewer" : `All ${formatCount(listed.length)} ${noun}`}</SkeletonText>
</span>
</button>
)}
</StatusFrame>
</div>
);
}
```
### components/filters-ui/lib/cn.ts
```ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
```
### components/filters-ui/lib/format.ts
```ts
// Numbers, prices, distances, percents and dates for one locale, built on Intl with no dependency. Pass any BCP 47
// tag ("de-DE", "ar-EG"); a tag Intl cannot read falls back to en-US instead of throwing. The default is en-US, never
// the browser's own locale, so the server and the browser always print the same text. UI words stay English.
export const DEFAULT_LOCALE = "en-US";
export type FormatOptions = {
/** ISO 4217 code for price and priceShort. Default "USD". */
currency?: string;
/** The unit of distance. Default "kilometer". */
unit?: "kilometer" | "mile";
};
/** Every formatter takes the value alone, so any of them can be passed straight to a format prop. */
export type Formats = {
/** The locale these formatters use, after any fallback. */
locale: string;
/** "1,234" in en-US, "1.234" in de-DE, up to three decimals. */
number: (value: number) => string;
/** A number with no group marks, such as a year: "2026", or "٢٠٢٦" in ar-EG. */
plain: (value: number) => string;
/** "45k", "1.2M". */
compact: (value: number) => string;
/** "$45,000" in en-US, "45.000 $" in de-DE: whole units of the currency. */
price: (value: number) => string;
/** "$45k" and "$97.5k" from a thousand up, "$950" below. */
priceShort: (value: number) => string;
/** "50,000 km" or "31,069 mi". */
distance: (value: number) => string;
/** A percentage given in percent, up to two decimals: 6.5 gives "6.5%" in en-US and "6,5 %" in de-DE. */
percent: (value: number) => string;
/** A day given as "YYYY-MM-DD", in words. Read in UTC, so it never shifts by a time zone. */
day: (iso: string, options: Intl.DateTimeFormatOptions) => string;
/** The name of a month, 0 for January. */
month: (index: number, style?: "long" | "short") => string;
/** The name of a weekday, 0 for Sunday. */
weekday: (index: number, style?: "long" | "short") => string;
/** The day weeks start on: 0 for Sunday, 1 for Monday, 6 for Saturday. */
firstDay: 0 | 1 | 5 | 6;
/** The locale's digits, 0 to 9: "0123456789", or "٠١٢٣٤٥٦٧٨٩" in ar-EG. */
digits: string;
/**
* Reads a number typed the locale's way, with an optional k or m: "45,000", "$45k" and "1.2m" in en-US, "45.000"
* and "1,2m" in de-DE. A unit such as "km" is not a suffix. Returns null when the text holds no number.
*/
readNumber: (text: string) => number | null;
};
/**
* A locale Intl has data for, or en-US. A well-formed tag with no data ("zz") would otherwise print in the
* runtime's own locale, which differs between server and browser.
*/
export function safeLocale(locale?: string): string {
if (!locale) return DEFAULT_LOCALE;
try {
const [tag] = Intl.getCanonicalLocales(locale);
if (!tag) return DEFAULT_LOCALE;
if (!Intl.NumberFormat.supportedLocalesOf(tag).length || !Intl.DateTimeFormat.supportedLocalesOf(tag).length) return DEFAULT_LOCALE;
return tag;
} catch {
return DEFAULT_LOCALE;
}
}
/** A currency code Intl can read, or USD. */
function safeCurrency(currency?: string): string {
if (!currency) return "USD";
try {
new Intl.NumberFormat(DEFAULT_LOCALE, { style: "currency", currency });
return currency.toUpperCase();
} catch {
return "USD";
}
}
// Where weeks start, by region, as CLDR 48 has it; every other region starts on Monday. A table rather than
// Intl.Locale weekInfo, which not every browser has, so the server and every browser agree.
const SUNDAY = new Set(
"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "),
);
const SATURDAY = new Set("AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
function firstDayOf(locale: string): 0 | 1 | 5 | 6 {
let region: string | undefined;
try {
region = new Intl.Locale(locale).maximize().region;
} catch {}
if (!region) return 0;
if (region === "MV") return 5;
if (SATURDAY.has(region)) return 6;
return SUNDAY.has(region) ? 0 : 1;
}
const cache = new Map<string, Formats>();
/** Formatters for one locale. Cheap to call on every render: each locale and option set is built once. */
export function formatsFor(locale?: string, options: FormatOptions = {}): Formats {
const tag = safeLocale(locale);
const currency = safeCurrency(options.currency);
const unit = options.unit === "mile" ? "mile" : "kilometer";
const key = `${tag}|${currency}|${unit}`;
const known = cache.get(key);
if (known) return known;
const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(tag, o);
const dates = new Map<string, Intl.DateTimeFormat>();
const df = (o: Intl.DateTimeFormatOptions) => {
const id = JSON.stringify(o);
let format = dates.get(id);
if (!format) {
format = new Intl.DateTimeFormat(tag, { ...o, timeZone: "UTC" });
dates.set(id, format);
}
return format;
};
// English writes thousands with a small k, as the filters always have.
const english = tag === "en" || tag.startsWith("en-");
const smallK = (text: string) => (english ? text.replace(/K\b/, "k") : text);
const number = nf({});
const plain = nf({ useGrouping: false, maximumFractionDigits: 20 });
const compact = nf({ notation: "compact", maximumFractionDigits: 1 });
const price = nf({ style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0 });
// One decimal is exact for a 1,000 unit ("$97.5k"); a 10,000 unit such as 万 takes two ("$9.75万").
const unitDigits = nf({ notation: "compact", useGrouping: false }).formatToParts(10000).filter((p) => p.type === "integer").map((p) => p.value).join("").length;
const priceShort = nf({ style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: Math.max(1, 3 - unitDigits) });
const distance = nf({ style: "unit", unit, maximumFractionDigits: 0 });
const percent = nf({ style: "percent", maximumFractionDigits: 2 });
const digits = plain.format(1234567890).replace(/^(.*)(.)$/, "$2$1");
const parts = number.formatToParts(12345.6);
const group = parts.find((p) => p.type === "group")?.value ?? ",";
const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";
const formats: Formats = {
locale: tag,
number: (value) => number.format(value),
plain: (value) => plain.format(value),
compact: (value) => smallK(compact.format(value)),
price: (value) => price.format(value),
priceShort: (value) => (Math.abs(value) >= 1000 ? smallK(priceShort.format(value)) : price.format(value)),
distance: (value) => distance.format(value),
percent: (value) => percent.format(value / 100),
day: (iso, o) => df(o).format(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)))),
month: (index, style = "long") => df({ month: style }).format(Date.UTC(2021, index, 1)),
// 3 January 2021 was a Sunday.
weekday: (index, style = "long") => df({ weekday: style }).format(Date.UTC(2021, 0, 3 + index)),
firstDay: firstDayOf(tag),
digits,
readNumber: (text) => {
let t = text.replace(/[\s ]/g, "");
for (let i = 0; i < 10; i++) t = t.split(digits[i]).join(String(i));
if (!/\s/.test(group)) t = t.split(group).join("");
// Marks typed in place of the locale's own: a Latin or Arabic comma where both marks are Arabic, a curly apostrophe for a straight one.
if (!/[.,]/.test(group + decimal)) t = t.replace(/[,\u060c]/g, "");
if (group === "'") t = t.split("\u2019").join("");
if (decimal !== ".") t = t.split(decimal).join(".");
const match = t.match(/(\d*\.?\d+)([km](?![a-z]))?/i);
if (!match) return null;
const scale = match[2] ? (match[2].toLowerCase() === "k" ? 1e3 : 1e6) : 1;
return Number(match[1]) * scale;
},
};
cache.set(key, formats);
return formats;
}
/** "1 result", "1,204 results": the default words for a count, with the number in the locale. */
export const resultsLabel = (n: number, locale?: string) => `${formatsFor(locale).number(n)} ${n === 1 ? "result" : "results"}`;
```
### components/filters-ui/lib/scroll.ts
```ts
/**
* A slim scrollbar for every box that scrolls: a 6px rounded thumb in the line colour on a clear track, stronger under
* the pointer, kept 2px off the side and 12px off each end so it never runs into a rounded corner.
* Chromium and Safari draw it from the ::-webkit-scrollbar parts. Firefox has none of those, so it alone gets the
* standard thin bar in the same colours: Chromium ignores the parts once scrollbar-width or scrollbar-color is set,
* so never add either beside this class.
*/
export const SCROLL =
"supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-width:thin] supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-color:var(--fu-line,#404040)_transparent] " +
"[&::-webkit-scrollbar]:size-2.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent " +
"[&::-webkit-scrollbar-track:vertical]:my-3 [&::-webkit-scrollbar-track:horizontal]:mx-3 " +
"[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-padding " +
"[&::-webkit-scrollbar-thumb]:bg-[var(--fu-line,#404040)] [&::-webkit-scrollbar-thumb:hover]:bg-[var(--fu-control-border,#737373)] [&::-webkit-scrollbar-thumb:active]:bg-[var(--fu-control-border,#737373)]";
```
### components/filters-ui/ui/art-search.ts
```ts
/**
* The picture for "nothing matches" and "nothing here": a glass magnifier on a clear background, drawn 56px.
* It is a file, not code: the shadcn install saves it as public/filters-ui/search.svg. Copying by hand, save
* https://filtersui.com/filters-ui/search.svg there, or point this at a picture of your own. With no file the empty
* states show their words alone.
*/
export const SEARCH_ART = "/filters-ui/search.svg";
```
### components/filters-ui/ui/count-pill.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { ARRIVING, SKELETON_FILL, useLoading } from "./skeleton";
export type CountPillProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
count: number;
/** "default": 20px high, 6px radius. "square": 18px high, 5px radius, 11px text. */
variant?: "default" | "square";
/** Selected look: accent fill, --fu-on-accent text. */
on?: boolean;
format?: (n: number) => string;
/** Formats the count when no format is given, e.g. "de-DE" prints 1.234. */
locale?: string;
/** A pulsing placeholder of the pill's own size. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
};
export function CountPill({ count, variant = "default", on = false, format, locale, loading: loadingProp, className, ...props }: CountPillProps) {
const state = useLoading();
const loading = loadingProp ?? state.loading;
const text = (format ?? formatsFor(locale).number)(count);
return (
<span
data-state={on ? "on" : "off"}
className={cn(
"inline-flex shrink-0 items-center justify-center font-medium tabular-nums",
"transition-[background-color,color] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
variant === "square"
? "h-[18px] min-w-5 rounded-[5px] px-[5px] text-[11px] leading-4"
: "h-5 min-w-[22px] rounded-[6px] px-1.5 text-[12px] leading-4",
loading
? SKELETON_FILL
: on
? "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)]"
: variant === "square"
? "bg-[var(--fu-pill-square,#333333)] text-[var(--fu-pill-text,#C8C8C8)]"
: "bg-[var(--fu-pill,rgb(255_255_255/0.1))] text-[var(--fu-pill-text,#C8C8C8)]",
className,
)}
{...props}
>
{/* While loading, the number holds the pill's width unseen; when it arrives it fades in once. */}
{loading ? (
<span key="skeleton" className="invisible">
{text}
</span>
) : state.arriving ? (
<span key="arrived" className={ARRIVING}>
{text}
</span>
) : (
text
)}
</span>
);
}
```
### components/filters-ui/ui/skeleton.tsx
```tsx
"use client";
import { createContext, useContext, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
/** What StatusFrame tells the pieces under it: draw placeholders, or the data has just arrived and fades in once. */
export type LoadingState = { loading: boolean; arriving: boolean };
export const LoadingContext = createContext<LoadingState>({ loading: false, arriving: false });
/** The loading state of the nearest StatusFrame. Outside one, nothing is loading. */
export const useLoading = () => useContext(LoadingContext);
/**
* The placeholder fill: --fu-skeleton, pulsing to half of it every 2s (Tailwind's animate-pulse). It holds still when
* reduced motion is asked for, and turns to the system's grey text colour in forced colours, so it never vanishes.
*/
export const SKELETON_FILL =
"animate-pulse bg-[var(--fu-skeleton,rgb(255_255_255/0.12))] in-data-[state=on]:bg-[var(--fu-skeleton-on,rgb(143_170_255/0.3))] motion-reduce:animate-none forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]";
/** Content that has just replaced a placeholder: it fades in once over 300ms as it is inserted, and never again. */
export const ARRIVING = "transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none";
export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;
/**
* A pulsing placeholder block with no size of its own: give it the size and corners of what it stands for, from the
* same classes, e.g. "h-5 min-w-[22px] rounded-[6px]" for a count pill. Hidden from screen readers; the StatusFrame
* around it says "Loading" once.
*/
export function Skeleton({ className, ...props }: SkeletonProps) {
return <span aria-hidden="true" data-skeleton="" className={cn("block rounded-[6px]", SKELETON_FILL, className)} {...props} />;
}
export type SkeletonTextProps = {
children: ReactNode;
/** Draws the placeholder. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
/** Classes for the placeholder's box while loading. */
className?: string;
};
/**
* Words that draw as a rounded bar while loading. The words stay in the layout, unseen, so the bar is exactly as wide
* and as many lines tall as they are, and nothing moves when they arrive; then they fade in once.
*/
export function SkeletonText({ children, loading, className }: SkeletonTextProps) {
const state = useLoading();
if (loading ?? state.loading) {
return (
<span key="skeleton" className={cn("relative inline-block max-w-full align-top", className)}>
<span className="invisible">{children}</span>
<Skeleton className="absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]" />
</span>
);
}
if (state.arriving) {
return (
<span key="arrived" className={ARRIVING}>
{children}
</span>
);
}
return <>{children}</>;
}
/**
* Stand-in names for a list whose options have not come yet: a mix of lengths, so the placeholders do not read as a
* grid. Never shown; only their widths are.
*/
export function placeholderLabels(count: number): string[] {
const words = ["Placeholder", "Short", "A longer name", "Medium one", "Tiny", "Another name", "Middle", "Fairly long one"];
return Array.from({ length: count }, (_, i) => words[i % words.length]);
}
```
### components/filters-ui/ui/empty-state.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
/** The picture above the words: an image address, drawn 56px square, or any node of that size. */
art?: string | ReactNode;
/** The one line that says what is missing. */
title: ReactNode;
/** A link or button under the words, such as "Clear search". */
action?: ReactNode;
/** A second, quieter line under the title. */
children?: ReactNode;
};
// Each part arrives once, a beat after the one above it: the picture comes into focus, the words rise into place.
const ENTER =
"transition-[opacity,filter,translate,scale] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none starting:opacity-0";
/**
* What a list shows in the room its options would take when it has none: a picture, one line and an action, stacked
* in the middle. For a single quiet line with no picture, use EmptyNote.
*/
export function EmptyState({ art, title, action, className, children, ...props }: EmptyStateProps) {
return (
<div className={cn("flex min-w-0 max-w-full flex-col items-center text-center", className)} {...props}>
{art && (
<span aria-hidden="true" className={cn("mb-3 block size-14 shrink-0", ENTER, "starting:scale-[0.82] starting:blur-[6px]")}>
{typeof art === "string" ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={art} alt="" width={56} height={56} loading="lazy" decoding="async" draggable={false} className="size-full object-contain select-none" />
) : (
art
)}
</span>
)}
<p dir="auto" className={cn("max-w-full text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]", ENTER, "delay-[60ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{title}
</p>
{children && (
<p dir="auto" className={cn("mt-1 max-w-full text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]", ENTER, "delay-[90ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{children}
</p>
)}
{action && <div className={cn("mt-2 max-w-full", ENTER, "delay-[120ms] starting:translate-y-1.5")}>{action}</div>}
</div>
);
}
```
### components/filters-ui/ui/icons.tsx
```tsx
import type { ReactNode, SVGProps } from "react";
/*
* Icon paths from Lucide (https://lucide.dev), ISC License.
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT).
* All other copyright (c) for Lucide are held by Lucide Contributors 2022.
* Permission to use, copy, modify, and/or distribute this software for any purpose with or
* without fee is hereby granted, provided that the above copyright notice and this permission
* notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number };
function Icon({ size = 20, strokeWidth = 2, children, ...props }: IconProps & { children: ReactNode }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...props}
>
{children}
</svg>
);
}
export function ChevronDownIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m6 9 6 6 6-6" />
</Icon>
);
}
export function XIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</Icon>
);
}
export function CheckIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M20 6 9 17l-5-5" />
</Icon>
);
}
export function SearchIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function ArrowUpRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M7 7h10v10" />
<path d="M7 17 17 7" />
</Icon>
);
}
export function PlusIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="M12 5v14" />
</Icon>
);
}
export function CopyIcon(props: IconProps) {
return (
<Icon {...props}>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</Icon>
);
}
export function SlidersIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 4h-7" />
<path d="M10 4H3" />
<path d="M21 12h-9" />
<path d="M8 12H3" />
<path d="M21 20h-5" />
<path d="M12 20H3" />
<path d="M14 2v4" />
<path d="M8 10v4" />
<path d="M16 18v4" />
</Icon>
);
}
export function ArrowRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</Icon>
);
}
export function SearchXIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m13.5 8.5-5 5" />
<path d="m8.5 8.5 5 5" />
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function StarIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</Icon>
);
}
export function HistoryIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M12 7v5l4 2" />
</Icon>
);
}
export function ListTreeIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 12h-8" />
<path d="M21 6H8" />
<path d="M21 18h-8" />
<path d="M3 6v4c0 1.1.9 2 2 2h3" />
<path d="M3 10v6c0 1.1.9 2 2 2h3" />
</Icon>
);
}
export function CircleAlertIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</Icon>
);
}
```
### components/filters-ui/ui/status-frame.tsx
```tsx
"use client";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";
/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";
/**
* The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
* filter knows them all. Spread them into an item's own props type.
*/
export type StateProps = {
/** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
status?: Status;
/** Called by the Retry button. Without it the error line has no button. */
onRetry?: () => void;
/** The error line. Default "Couldn't load the options." */
errorText?: string;
/** The line shown in place of the options when there are none. Default "No options to show" */
emptyText?: string;
/** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
disabled?: boolean;
};
export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";
/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
type Mode = "ready" | "loading" | "error" | "empty";
/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);
export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
Omit<StateProps, "emptyText"> & {
/** There are no options: emptyText shows in place of the content. */
empty?: boolean;
emptyText?: ReactNode;
/** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
emptyArt?: string | ReactNode | null;
/** Words read once while loading. Default "Loading". */
loadingText?: string;
/** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
announce?: boolean;
retryLabel?: string;
children: ReactNode;
};
/**
* Wraps an item's content and gives it the shared states.
* - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
* placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
* - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
* status region that stays on the page.
* - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
* - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
* read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
* When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
* A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
* it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
* with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
* frame and let an inner frame around the part that fails speak.
*/
export function StatusFrame({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
empty = false,
emptyText = DEFAULT_EMPTY_TEXT,
emptyArt,
disabled = false,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
children,
...props
}: StatusFrameProps) {
const frame = useRef<HTMLDivElement>(null);
const outer = useLoading();
const saidAbove = useContext(SaidLoading);
const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";
// The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
const [lastStatus, setLastStatus] = useState(status);
const [arriving, setArriving] = useState(false);
if (status !== lastStatus) {
setLastStatus(status);
setArriving(lastStatus === "loading" && status === "ready");
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arriving]);
// Whether focus sat on a control inside, read just before a change of state is drawn.
const key = `${mode}|${disabled}`;
const drawnKey = useRef(key);
const focusWasInside = useRef(false);
if (key !== drawnKey.current && typeof document !== "undefined") {
const active = document.activeElement;
focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
}
useLayoutEffect(() => {
if (drawnKey.current === key) return;
drawnKey.current = key;
if (!focusWasInside.current) return;
focusWasInside.current = false;
const node = frame.current;
// The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
});
return (
<div
ref={frame}
tabIndex={-1}
data-status-frame=""
data-status={mode}
aria-busy={mode === "loading" || undefined}
className={cn(
"min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50 select-none",
className,
)}
{...props}
>
<SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
<LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
{mode === "empty" ? (
emptyArt === null ? (
<EmptyNote>{emptyText}</EmptyNote>
) : (
<EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
)
) : mode === "error" ? null : (
// display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
<fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
{children}
</fieldset>
)}
</LoadingContext.Provider>
</SaidLoading.Provider>
<StatusLine
status={mode === "loading" || mode === "error" ? mode : "ready"}
onRetry={onRetry}
errorText={errorText}
loadingText={saidAbove ? "" : loadingText}
announce={announce}
retryLabel={retryLabel}
/>
</div>
);
}
export type StatusLineProps = {
status?: Status;
/** Called by Retry. Without it the error line has no button. */
onRetry?: () => void;
errorText?: string;
loadingText?: string;
/** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
announce?: boolean;
retryLabel?: string;
/** Classes for the line while it shows an error, e.g. its margins. */
className?: string;
};
/**
* What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
* Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
* no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
* Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
*/
export function StatusLine({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
}: StatusLineProps) {
const error = status === "error";
const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
return (
// The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
<div className={error ? cn(ERROR_LINE, className) : "contents"}>
<p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
{error && <ErrorGlyph />}
{said && <span dir="auto">{said}</span>}
</p>
{error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
/**
* For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
* away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
* never dropped to the page.
*/
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
const drawn = useRef(key);
const had = useRef(false);
if (key !== drawn.current && typeof document !== "undefined") {
const active = document.activeElement;
had.current = !!scope.current && !!active && scope.current.contains(active);
}
useLayoutEffect(() => {
if (drawn.current === key) return;
drawn.current = key;
if (!had.current) return;
had.current = false;
const node = scope.current;
if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
});
}
```
### components/filters-ui/ui/empty-note.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyNoteProps = HTMLAttributes<HTMLDivElement> & {
/** A 16px glyph in currentColor before the words. */
icon?: ReactNode;
/** A button or link after the words, e.g. "Clear search". */
action?: ReactNode;
};
/**
* A quiet one-line note in place of a list that has nothing in it: dim 14px words, an optional glyph and an optional
* action. No illustration and no box, so it sits in the space the options would take.
*/
export function EmptyNote({ icon, action, className, children, ...props }: EmptyNoteProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2", className)} {...props}>
<p className="flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{icon && (
<span aria-hidden="true" className="mt-0.5 shrink-0 [&_svg]:size-4">
{icon}
</span>
)}
<span dir="auto">{children}</span>
</p>
{action}
</div>
);
}
```
### components/filters-ui/ui/inline-error.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { buttonClasses } from "./button-classes";
import { CircleAlertIcon } from "./icons";
export const DEFAULT_RETRY_LABEL = "Retry";
/** The error line's layout: the words at the start, Retry at the end, wrapping under them when space runs out. */
export const ERROR_LINE = "flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2";
/** The words: 14px, muted, with a 16px dim alert glyph before them. */
export const ERROR_TEXT = "flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]";
/** The alert glyph that leads the words. Hidden from screen readers. */
export function ErrorGlyph() {
return <CircleAlertIcon size={16} className="mt-0.5 shrink-0 text-[var(--fu-dim,#929292)]" />;
}
export type RetryButtonProps = {
onRetry: () => void;
label?: string;
className?: string;
};
/**
* A small grey button that is never shown disabled. Before it calls onRetry it hands focus to the StatusFrame around
* it, which stays on the page while the content reloads, so focus is never lost with the button.
*/
export function RetryButton({ onRetry, label = DEFAULT_RETRY_LABEL, className }: RetryButtonProps) {
return (
<button
type="button"
onClick={(event) => {
event.currentTarget.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
onRetry();
}}
className={buttonClasses({ variant: "secondary", size: "sm", className })}
>
{label}
</button>
);
}
export type InlineErrorProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** One short line in plain words, e.g. "Couldn't load the options." */
text: string;
/** Shows Retry. Without it the line stands alone. */
onRetry?: () => void;
retryLabel?: string;
};
/**
* A calm error in the component's own area: one muted line and a Retry button. The line is a polite status region, so
* it is read out when it appears. Inside a StatusFrame use the frame's status="error" instead: it keeps one region on
* the page for loading and errors alike.
*/
export function InlineError({ text, onRetry, retryLabel, className, ...props }: InlineErrorProps) {
return (
<div className={cn(ERROR_LINE, className)} {...props}>
<p role="status" className={ERROR_TEXT}>
<ErrorGlyph />
<span dir="auto">{text}</span>
</p>
{onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
```
### components/filters-ui/ui/button-classes.ts
```ts
import { cn } from "../lib/cn";
// The button looks as class names. Kept apart from button.tsx, a client module, so server pages can call them too.
export type ButtonVariant = "primary" | "secondary" | "ghost" | "quiet" | "quiet-accent";
export type ButtonSize = "sm" | "md" | "lg";
export const BUTTON_BASE = cn(
"relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] font-[inherit] font-medium whitespace-nowrap no-underline select-none",
"[-webkit-tap-highlight-color:transparent] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
"active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"aria-busy:cursor-progress aria-busy:active:scale-100",
);
const VARIANTS: Record<ButtonVariant, string> = {
primary:
"bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)] hover:bg-[var(--fu-accent-hover,#3450D4)] forced-colors:border forced-colors:border-[ButtonText]",
secondary:
"bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]",
ghost: "bg-transparent text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
quiet: "bg-transparent text-[var(--fu-mute,#BDBDBD)] hover:text-[var(--fu-text,#F8F5F1)]",
"quiet-accent":
"bg-transparent text-[var(--fu-accent-soft,#8FAAFF)] decoration-1 underline-offset-[5px] hover:text-[var(--fu-accent-pale,#D1DDFF)] [@media(hover:hover)]:hover:underline",
};
// Below 44px a touch screen gets a taller invisible target through ::after.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:content-['']";
const SIZES: Record<ButtonSize, { box: string; before: string; after: string }> = {
sm: { box: cn("h-8 gap-1.5 px-3 text-[13px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-1.5"), before: "ps-2.5", after: "pe-2.5" },
md: { box: cn("h-10 gap-2 px-3.5 text-[15px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-0.5"), before: "ps-3", after: "pe-3" },
lg: { box: "h-11 gap-2 px-4 text-[15px] leading-5 [&_svg]:size-[18px]", before: "ps-3.5", after: "pe-3.5" },
};
/** The classes of a button, for a link or a router link that should look like one. */
export function buttonClasses({
variant = "primary",
size = "md",
before = false,
after = false,
className,
}: { variant?: ButtonVariant; size?: ButtonSize; before?: boolean; after?: boolean; className?: string } = {}) {
return cn(BUTTON_BASE, VARIANTS[variant], SIZES[size].box, before && SIZES[size].before, after && SIZES[size].after, className);
}
```
### components/filters-ui/ui/text-field.tsx
```tsx
"use client";
import { useRef, type InputHTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { DragHandle, type NumberDrag } from "./drag-handle";
import { XIcon } from "./icons";
import { ARRIVING, Skeleton, useLoading } from "./skeleton";
export type TextFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "onChange" | "prefix" | "size"> & {
value: string;
onChange: (value: string) => void;
/** Accessible name. Shown only to screen readers; the placeholder is the visible label. */
label: string;
/** Text or an icon before the value, e.g. "$". */
prefix?: ReactNode;
/** Shows a 16px clear button while the field has a value. Defaults to emptying the value. */
onClear?: () => void;
clearLabel?: string;
/** For a field that holds a number: a handle to drag it along a scale, as on a slider. See DragHandle. */
drag?: NumberDrag;
className?: string;
inputClassName?: string;
};
/** 44px field, 12px radius, 1px --fu-field-border border, 15px text, optional prefix and clear X. */
export function TextField({
value,
onChange,
label,
prefix,
onClear,
clearLabel,
drag,
className,
inputClassName,
disabled,
...props
}: TextFieldProps) {
const input = useRef<HTMLInputElement>(null);
const filled = value.length > 0;
// Inside a loading StatusFrame the box stays and a bar stands in for the words, which fade in once when they arrive.
const { loading, arriving } = useLoading();
return (
<div
className={cn(
"flex h-11 min-w-0 items-center gap-1.5 rounded-[12px] border border-[var(--fu-field-border,#737373)] bg-[var(--fu-input,rgb(0_0_0/0))] px-3",
"text-[15px] leading-5 text-[var(--fu-text,#F8F5F1)] transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none",
"hover:border-[var(--fu-control-hover,#A3A3A3)] focus-within:border-[var(--fu-accent-soft,#8FAAFF)] focus-within:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
"focus-within:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50",
drag && "group/field relative isolate",
className,
)}
onPointerDown={(event) => {
if (event.target === event.currentTarget) {
event.preventDefault();
input.current?.focus();
}
}}
>
{prefix != null && <span className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">{prefix}</span>}
{loading && <Skeleton className="h-3 w-[45%] max-w-28 rounded-[4px]" />}
<input
key={loading ? "loading" : "ready"}
ref={input}
value={value}
onChange={(event) => onChange(event.target.value)}
aria-label={label}
disabled={disabled}
className={cn(
"h-full min-w-0 flex-1 bg-transparent text-ellipsis text-inherit tabular-nums outline-none",
"placeholder:text-[var(--fu-mute,#BDBDBD)]",
inputClassName,
loading && "sr-only",
arriving && ARRIVING,
)}
{...props}
/>
{filled && !loading && (
<button
type="button"
aria-label={clearLabel ?? `Clear ${label.toLowerCase()}`}
onClick={() => {
if (onClear) onClear();
else onChange("");
input.current?.focus();
}}
className={cn(
// Above the drag handle's layer, so the cross can always be pressed.
"relative z-[1] -me-1 grid size-6 shrink-0 cursor-pointer place-items-center rounded-[6px] text-[var(--fu-mute,#BDBDBD)]",
"transition-colors duration-150 hover:text-[var(--fu-text,#F8F5F1)]",
"focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
<XIcon size={16} />
</button>
)}
{drag && !loading && !disabled && <DragHandle drag={drag} input={input} />}
</div>
);
}
```
### components/filters-ui/ui/drag-handle.tsx
```tsx
"use client";
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
export type NumberDrag = {
/** The number the field holds; null while it is empty. */
value: number | null;
/** The scale the field's width stands for. */
min: number;
max: number;
/** Dragged values snap to this. */
step: number;
onChange: (value: number) => void;
/** Where the handle stands while the field is empty. Default "min". */
emptyAt?: "min" | "max";
/** The lowest and highest value a drag may reach, inside min and max: the other end of a range, say. */
floor?: number;
ceiling?: number;
/**
* Called on each move of a drag with the value under the pointer, before it snaps to a step, and with null when the
* handle is let go: for a chart that should move with the handle.
*/
onHold?: (value: number | null) => void;
};
type Press = { start: number; width: number; rtl: boolean; grab: number; x: number; last: number | null; moved: boolean; settled: boolean };
/**
* Turns a number field into a slider as well. With a mouse over the field a thin handle shows where the value stands
* along the field's width; dragging it fills the field up to the handle and moves the value in steps. A press that does
* not move puts the caret in the field instead, with its text picked. The field needs the classes "group/field relative
* isolate": the fill and the handle are drawn behind its text, and only a strip over the handle takes the pointer.
* While a drag runs the layer carries data-dragging, which a field that grows with its text can use to hold its width.
* With the pointer on the handle itself it grows and takes the accent colour, as it does while dragged, so it reads as
* the thing to grab. The accent keeps the digits it crosses readable, which a light handle would not.
*/
export function DragHandle({ drag, input, pad = 12 }: { drag: NumberDrag; input: RefObject<HTMLInputElement | null>; pad?: number }) {
const { value, min, max, step, onChange, emptyAt = "min" } = drag;
const strip = useRef<HTMLSpanElement>(null);
const press = useRef<Press | null>(null);
const [dragging, setDragging] = useState(false);
const [near, setNear] = useState(false);
const hold = useRef(drag.onHold);
hold.current = drag.onHold;
const span = max - min || 1;
const share = (n: number) => Math.min(1, Math.max(0, (n - min) / span));
const at = share(value ?? (emptyAt === "max" ? max : min));
// A CSS variable set on the field while dragging takes over from the value, so the handle follows the pointer between steps.
const place = `calc(${pad}px + var(--drag-at, ${at}) * (100% - ${pad * 2}px))`;
const pointerShare = (x: number, p: Press) => {
const f = (x - p.start) / p.width;
return p.rtl ? 1 - f : f;
};
/** Takes the field's box as it is now and keeps the handle where the pointer holds it. */
const measure = (p: Press, x: number, held: number) => {
const box = strip.current?.parentElement?.getBoundingClientRect();
if (!box) return;
p.start = box.left + pad;
p.width = Math.max(1, box.width - pad * 2);
p.grab = pointerShare(x, p) - held;
};
// A drag cut short by the field going away (loading, disabled) must not leave its place on the field.
useEffect(() => {
const field = strip.current?.parentElement;
return () => {
field?.style.removeProperty("--drag-at");
if (press.current?.moved) hold.current?.(null);
};
}, []);
const down = (event: PointerEvent<HTMLSpanElement>) => {
// A frame turns its filter off with a disabled fieldset; the strip is no control, so it asks the field.
if (event.button !== 0 || !strip.current || input.current?.matches(":disabled")) return;
// Keeps the press from starting a text selection or moving focus; a press that never moves focuses the field on release.
event.preventDefault();
const p: Press = { start: 0, width: 1, rtl: isRtl(strip.current), grab: 0, x: event.clientX, last: value, moved: false, settled: false };
measure(p, event.clientX, at);
press.current = p;
event.currentTarget.setPointerCapture(event.pointerId);
};
const move = (event: PointerEvent<HTMLSpanElement>) => {
const p = press.current;
if (!p) return;
if (!p.moved) {
if (Math.abs(event.clientX - p.x) < 3) return;
// A field that grows with its text takes its widest size for the drag (see data-dragging); the next move
// measures it at that size, so the handle stays under the pointer from then on.
p.moved = true;
setDragging(true);
return;
}
if (!p.settled) {
p.settled = true;
measure(p, event.clientX, share(p.last ?? (emptyAt === "max" ? max : min)));
}
const floor = drag.floor ?? min;
const ceiling = drag.ceiling ?? max;
const to = Math.min(share(ceiling), Math.max(share(floor), pointerShare(event.clientX, p) - p.grab));
strip.current?.parentElement?.style.setProperty("--drag-at", String(to));
drag.onHold?.(min + to * span);
// Snapped to the step, kept between the floor and the ceiling (a typed floor may sit off the steps), and written
// with the step's own decimals, so 0.1 steps do not come out as 0.30000000000000004.
const snapped = Math.min(ceiling, Math.max(floor, min + Math.round((to * span) / step) * step));
const next = Number(snapped.toFixed((String(step).split(".")[1] ?? "").length));
if (next !== p.last) {
p.last = next;
onChange(next);
}
};
const up = (event: PointerEvent<HTMLSpanElement>, cancelled = false) => {
const p = press.current;
if (!p) return;
press.current = null;
strip.current?.parentElement?.style.removeProperty("--drag-at");
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(false);
if (p.moved) drag.onHold?.(null);
if (!p.moved && !cancelled) {
input.current?.focus();
input.current?.select();
}
};
return (
<>
<span
aria-hidden="true"
data-dragging={dragging || undefined}
data-near={near || dragging || undefined}
className="group/drag pointer-events-none absolute inset-0 -z-10 overflow-hidden rounded-[inherit]"
>
<span
className="absolute inset-y-0 inset-s-0 bg-[var(--fu-wash,rgb(255_255_255/0.08))] opacity-0 transition-opacity duration-200 motion-reduce:transition-none group-data-[dragging]/drag:opacity-100"
style={{ width: place }}
/>
<span
// Centred on its place with a start margin, which follows the field's own direction: a left-to-right
// number pill keeps it right inside a right-to-left page, where a mirrored translate would not.
className={cn(
"absolute top-1/2 -ms-[1.5px] h-5 w-[3px] -translate-y-1/2 rounded-full bg-[var(--fu-control-border,#737373)] opacity-0 in-[fieldset:disabled]:hidden",
"transition-[opacity,background-color,scale] duration-150 motion-reduce:transition-none forced-colors:bg-[CanvasText]",
"pointer-fine:group-hover/field:opacity-100 group-data-[near]/drag:bg-[var(--fu-accent,#3B57E6)] group-data-[near]/drag:opacity-100",
"group-data-[near]/drag:scale-x-150 group-data-[near]/drag:scale-y-125",
)}
style={{ insetInlineStart: place } as CSSProperties}
/>
</span>
<span
ref={strip}
aria-hidden="true"
onPointerDown={down}
onPointerMove={move}
onPointerUp={(event) => up(event)}
onPointerCancel={(event) => up(event, true)}
onPointerEnter={() => setNear(true)}
onPointerLeave={() => setNear(false)}
// Inside a <label> a click would hand focus to the field after a drag; focus is given on release instead.
onClick={(event) => event.preventDefault()}
className="pointer-events-none absolute inset-y-0 -ms-2 w-4 cursor-ew-resize touch-none in-[fieldset:disabled]:hidden pointer-fine:pointer-events-auto"
style={{ insetInlineStart: place } as CSSProperties}
/>
</>
);
}
```
### components/filters-ui/lib/direction.ts
```ts
// Right-to-left helpers for positions and keys worked out in script. Each reads the direction from the element
// itself, so it is right when only a parent sets dir="rtl".
/** True when the element lays out right to left. */
export const isRtl = (node: Element | null | undefined) => !!node && getComputedStyle(node).direction === "rtl";
/**
* The arrow key as a step in reading order: in right-to-left, ArrowLeft moves forward and ArrowRight back, as the
* ARIA patterns ask for horizontal widgets. Every other key comes back as it is.
*/
export function readingKey(key: string, node: Element | null | undefined): string {
if ((key !== "ArrowLeft" && key !== "ArrowRight") || !isRtl(node)) return key;
return key === "ArrowLeft" ? "ArrowRight" : "ArrowLeft";
}
/** A child's offset from its offset parent's start edge: its offsetLeft, or the distance from the right in RTL. */
export function startOffset(node: HTMLElement): number {
if (!isRtl(node)) return node.offsetLeft;
const parent = node.offsetParent as HTMLElement | null;
return (parent?.clientWidth ?? 0) - node.offsetLeft - node.offsetWidth;
}
/** Calls back whenever a dir attribute on the page changes, so a position measured in script can be taken again. */
export function onDirChange(callback: () => void): () => void {
if (typeof MutationObserver === "undefined") return () => {};
const observer = new MutationObserver(callback);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["dir"], subtree: true });
return () => observer.disconnect();
}
```
### components/filters-ui/ui/filter-card.tsx
```tsx
"use client";
import { useId, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { ChevronDownIcon } from "./icons";
export type FilterCardProps = Omit<HTMLAttributes<HTMLElement>, "title" | "children"> & {
title: string;
/** The value in words ("Under $45k"). Shown on the closed card; null or empty means the filter is unset. */
summary?: string | null;
/** Clears this one filter. When given, a Clear button takes the summary's place while open or hovered. */
onClear?: () => void;
/** Controlled open state. Leave undefined to let the card manage it. */
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Looks like a closed card but cannot be opened or focused, e.g. a filter whose body is not ready. */
disabled?: boolean;
/** Accessible name of the Clear button. Default "Clear {title}". */
clearLabel?: string;
/** Heading level wrapping the head button. Default 3. */
headingLevel?: 2 | 3 | 4 | 5 | 6;
bodyClassName?: string;
children?: ReactNode;
};
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
// The summary and Clear share one slot and trade places over 150ms through a 2px blur and 4px shift.
const SUMMARY_HIDDEN = "opacity-0 blur-[2px] -translate-y-1";
const SUMMARY_HIDES_WHEN = [
"group-data-[state=open]/card:opacity-0 group-data-[state=open]/card:blur-[2px] group-data-[state=open]/card:-translate-y-1",
"group-hover/slot:opacity-0 group-hover/slot:blur-[2px] group-hover/slot:-translate-y-1",
"group-focus-within/slot:opacity-0 group-focus-within/slot:blur-[2px] group-focus-within/slot:-translate-y-1",
].join(" ");
// Hovering anywhere on a closed card offers Clear in the summary's place.
const SUMMARY_HIDES_ON_CARD_HOVER = "group-hover/card:opacity-0 group-hover/card:blur-[2px] group-hover/card:-translate-y-1";
const CLEAR_SHOWS_ON_CARD_HOVER = "group-hover/card:opacity-100 group-hover/card:blur-none group-hover/card:translate-y-0";
// A hidden Clear takes no taps: only a pointer that can hover reveals it before a click.
const CLEAR_HIDDEN = "pointer-events-none opacity-0 blur-[2px] translate-y-1 [@media(hover:hover)]:pointer-events-auto";
const CLEAR_SHOWS_WHEN = [
"group-data-[state=open]/card:pointer-events-auto group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none group-data-[state=open]/card:translate-y-0",
"group-hover/slot:opacity-100 group-hover/slot:blur-none group-hover/slot:translate-y-0",
"group-focus-within/slot:opacity-100 group-focus-within/slot:blur-none group-focus-within/slot:translate-y-0",
].join(" ");
const FOCUS_RING =
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
/**
* One filter in a rounded card: a 52px head (title, value summary or Clear, chevron) that opens a body.
* Opening animates the height over 480ms and reveals the content from a 6px blur, 6px lower.
*/
export function FilterCard({
title,
summary,
onClear,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
clearLabel,
headingLevel = 3,
className,
bodyClassName,
children,
...props
}: FilterCardProps) {
const id = useId();
const headId = `${id}-head`;
const bodyId = `${id}-body`;
const head = useRef<HTMLButtonElement>(null);
const [innerOpen, setInnerOpen] = useState(defaultOpen);
const open = !disabled && (openProp ?? innerOpen);
const set = Boolean(summary);
// The last summary stays in place while it fades out after a clear.
const [lastSummary, setLastSummary] = useState(summary ?? "");
if (summary && summary !== lastSummary) setLastSummary(summary);
const setOpen = (next: boolean) => {
if (openProp === undefined) setInnerOpen(next);
onOpenChange?.(next);
};
const Heading = `h${headingLevel}` as const;
const swap = cn(
"transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none",
"group-data-[state=open]/card:duration-[480ms] group-data-[state=open]/card:ease-[cubic-bezier(0.22,1,0.36,1)]",
);
return (
<section
data-state={open ? "open" : "closed"}
data-set={set ? "true" : "false"}
className={cn(
"not-prose group/card relative overflow-hidden rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-text,#F8F5F1)]",
"transition-[background-color,border-color,opacity] duration-200 motion-reduce:transition-none",
"[@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:border-[var(--fu-line,#404040)] [@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:bg-[var(--fu-card-hover,#262626)]",
// The head button sits flush in a clipped card, so its focus ring is drawn around the card.
"has-[[data-filter-card-head]:focus-visible]:outline-2 has-[[data-filter-card-head]:focus-visible]:outline-offset-2 has-[[data-filter-card-head]:focus-visible]:outline-solid has-[[data-filter-card-head]:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
className,
)}
{...props}
>
<Heading className="m-0 -mb-0.5 text-[15px] font-semibold leading-5 text-[var(--fu-text,#F8F5F1)]">
<button
ref={head}
type="button"
id={headId}
data-filter-card-head=""
aria-expanded={open}
aria-controls={bodyId}
disabled={disabled}
onClick={() => setOpen(!open)}
className={cn(
"flex h-[52px] w-full cursor-pointer items-center gap-3 rounded-[23px] px-4 text-start font-[inherit] text-inherit disabled:cursor-default",
"outline-none",
)}
>
<span className="min-w-0 truncate">{title}</span>
{set && <span className="sr-only">, {summary}</span>}
{set && (
<span aria-hidden="true" className="invisible min-w-0 max-w-[calc((100%+32px)*0.55)] shrink-0 truncate text-[14px] font-normal">
{summary}
</span>
)}
<ChevronDownIcon
size={20}
className={cn(
"ms-auto shrink-0 text-[var(--fu-mute,#BDBDBD)] group-has-[[data-filter-card-head]:disabled]/card:opacity-40 transition-[rotate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:rotate-180",
)}
/>
</button>
</Heading>
{onClear && (
<div
inert={!set}
data-filter-card-slot=""
className="group/slot pointer-events-none absolute inset-e-[46px] top-4 grid h-5 max-w-[55%] justify-items-end text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]"
>
<span aria-hidden="true" className={cn("pointer-events-none max-w-full truncate font-normal [grid-area:1/1]", swap, set ? SUMMARY_HIDES_WHEN : SUMMARY_HIDDEN, set && !disabled && SUMMARY_HIDES_ON_CARD_HOVER)}>
{summary || lastSummary}
</span>
<button
type="button"
tabIndex={set ? 0 : -1}
aria-label={clearLabel ?? `Clear ${title.toLowerCase()}`}
onClick={() => {
onClear();
head.current?.focus();
}}
className={cn(
"relative -my-0.5 cursor-pointer rounded-[6px] py-0.5 font-medium [grid-area:1/1] before:absolute before:inset-x-0 before:-inset-y-2 before:content-['']",
FOCUS_RING,
"focus-visible:outline-offset-2",
swap,
CLEAR_HIDDEN,
set && CLEAR_SHOWS_WHEN,
set && !disabled && CLEAR_SHOWS_ON_CARD_HOVER,
)}
>
Clear
</button>
</div>
)}
{!onClear && set && (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-e-[46px] top-4 max-w-[55%] truncate text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]",
swap,
"group-data-[state=open]/card:opacity-0",
)}
>
{summary}
</span>
)}
<div
id={bodyId}
role="region"
aria-labelledby={headId}
inert={!open}
className={cn(
"grid grid-rows-[0fr] transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:grid-rows-[1fr]",
)}
>
<div className="min-h-0 overflow-hidden">
<div
className={cn(
// pt-0.5 makes up the head's -2px margin, so content starts right under the 52px head.
"px-4 pt-0.5 pb-4",
"translate-y-1.5 opacity-0 blur-[6px] transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:translate-y-0 group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none",
"group-data-[state=open]/card:delay-[120ms] group-data-[state=open]/card:duration-[460ms] group-data-[state=open]/card:ease-[cubic-bezier(0.16,1,0.3,1)]",
bodyClassName,
)}
>
{children}
</div>
</div>
</div>
</section>
);
}
```
## What it does
- Typing filters options and sub-options at once and marks the matching letters.
- Ticking an option opens its sub-options; ticking a sub-option narrows the option to it.
- The short list grows with what is ticked; "All N" shows the rest in a scroll area.
- A typo with no match offers the nearest name: "Toyta" gives "Did you mean Toyota?".
- A row with a count of 0 is dimmed and cannot be ticked.
## Props and value
SearchableList (components/filters-ui/filters/searchable-list.tsx) holds this value: { value: string; children: string[] }[]: one entry per ticked option, with the sub-options that narrow it. Empty children means the whole option. [] is no filter.
- options: readonly { value: string; label: string; count: number; children?: { value: string; label: string; count: number }[] }[] (required). In display order: the first collapsedCount make the short list, the rest show after "All N".
- value: readonly { value: string; children: string[] }[] (required). The ticked options and their ticked sub-options.
- onChange: (value: { value: string; children: string[] }[]) => void (required). Called with the new picks.
- label: string (required). Accessible name of the list.
- noun: string (default "items"). Plural word for the options: "Search makes", "All 21 makes", "No makes match".
- collapsedCount: number (default 8). How many options the short list shows.
- formatCount: (n: number) => string (default 1,234). Text in each count pill.
- countLabel: (n: number) => string (default "6 results"). Screen-reader words for a count, e.g. "6 cars".
- variant: "card" | "panel" (default "card"). "panel": a 48px search, 20px filled checkboxes, 17px names and plain counts, for a list that sits in a panel rather than a card. The list grows in place and the panel scrolls it.
- locale: string (default "en-US"). Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the <noun>."). The error line, in plain words.
- emptyText: string (default "No <noun> to show"). The line shown under a small picture, in place of the options, when there are none.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.
It sits inside FilterCard (components/filters-ui/ui/filter-card.tsx), the card with the title, the value in words and a Clear button:
- title: string (required). The card's heading, e.g. "Price".
- summary: string | null (optional). The value in words, shown on the closed card. Null or empty means the filter is unset.
- onClear: () => void (optional). Clears this filter. When given, a Clear button takes the summary's place while open or hovered.
- open / defaultOpen / onOpenChange: boolean / boolean / (open: boolean) => void (default closed). Controlled or uncontrolled open state.
- headingLevel: 2 | 3 | 4 | 5 | 6 (default 3). Heading level around the head button.
- bodyClassName: string (optional). Classes for the body, e.g. to tune the space under the content.
## States
Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.
- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. The search field, the first collapsedCount rows and their counts draw as placeholders; with no options yet it draws stand-in rows. It is aria-busy and says "Loading" once; when status turns back to "ready" the data fades in once. No spinner.
- Error (status="error", with onRetry and errorText): one calm line and a Retry button that calls onRetry, in the filter's own place. The default line names the noun: "Couldn't load the makes." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Empty (no options given, with emptyText): A picture and one line in place of the search and the list; the default names the noun: "No makes to show"
- Zero results (every count is 0): every option stays where it is, dimmed, and cannot be turned on; one that is on can still be turned off.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable.
- Long labels (data, not a prop): A long name wraps onto more lines; the checkbox and the count stay in the row.
- Many options (data, not a prop): The short list shows collapsedCount rows; "All N" opens the rest in a scroll area, and the search narrows them.
While it is disabled, leave FilterCard's onClear out, so the card offers no Clear.
## Usage
A working example with a few made-up cars. Imports assume @/ points at the project root; change @/components/filters-ui if this project uses another alias.
```tsx
"use client";
import { useState } from "react";
import { SearchableList, type SearchableListOption, type SearchableListPick } from "@/components/filters-ui/filters/searchable-list";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";
type Car = { make: string; model: string };
const CARS: Car[] = [
{ make: "Toyota", model: "RAV4" },
{ make: "Toyota", model: "RAV4" },
{ make: "Toyota", model: "Corolla" },
{ make: "Toyota", model: "Camry" },
{ make: "Honda", model: "CR-V" },
{ make: "Honda", model: "Civic" },
{ make: "Honda", model: "Civic" },
{ make: "Ford", model: "F-150" },
{ make: "Ford", model: "Mustang" },
{ make: "Mazda", model: "CX-5" },
{ make: "Mazda", model: "MX-5" },
{ make: "Hyundai", model: "Tucson" },
{ make: "Kia", model: "Telluride" },
{ make: "Subaru", model: "Outback" },
{ make: "Tesla", model: "Model 3" },
];
const SHORT_LIST = 5;
const carCount = (n: number) => (n === 1 ? "1 car" : `${n} cars`);
// Makes with the most cars first, each with its models.
function optionsOf(cars: Car[]): SearchableListOption[] {
const makes = [...new Set(cars.map((c) => c.make))];
const count = (make: string) => cars.filter((c) => c.make === make).length;
return makes
.sort((a, b) => count(b) - count(a) || a.localeCompare(b))
.map((make) => ({
value: make,
label: make,
count: count(make),
children: [...new Set(cars.filter((c) => c.make === make).map((c) => c.model))].map((model) => ({
value: model,
label: model,
count: cars.filter((c) => c.make === make && c.model === model).length,
})),
}));
}
const options = optionsOf(CARS);
// A make with models ticked keeps only those models; a make with none keeps all of them.
const matches = (car: Car, picks: SearchableListPick[]) =>
picks.length === 0 ||
picks.some((p) => p.value === car.make && (p.children.length === 0 || p.children.includes(car.model)));
function summaryOf(picks: SearchableListPick[]) {
const names = picks.flatMap((p) => (p.children.length ? p.children : [p.value]));
if (names.length === 0) return null;
return names.length <= 2 ? names.join(", ") : `${names.slice(0, 2).join(", ")} +${names.length - 2}`;
}
export default function MakeAndModelExample() {
const [makes, setMakes] = useState<SearchableListPick[]>([]);
const results = CARS.filter((car) => matches(car, makes));
return (
<div className="w-full max-w-[320px]">
<FilterCard
title="Make and model"
summary={summaryOf(makes)}
onClear={() => setMakes([])}
defaultOpen
>
<SearchableList
label="Make and model"
noun="makes"
collapsedCount={SHORT_LIST}
options={options}
value={makes}
onChange={setMakes}
countLabel={carCount}
/>
</FilterCard>
<p aria-live="polite" className="mt-3 px-4 text-[14px] leading-5 tabular-nums">
<span className="font-medium">{results.length}</span> <span className="text-[var(--fu-dim,#929292)]">of {CARS.length} cars</span>
</p>
</div>
);
}
```
## Connect it to my data
Ask me which field it filters and where the list of items comes from. Counts are numbers I pass in: work them out from my items, and when there are other filters on the page, count each option with every other filter applied but this one left out, so a count says how many results picking it would give.
## Keep the look
It is dark by default and needs no setup. To change colours, set these CSS variables on :root or on a parent element. These are the dark defaults:
```css
:root {
--fu-accent: #3B57E6;
--fu-accent-hover: #3450D4;
--fu-accent-pale: #D1DDFF;
--fu-accent-soft: #8FAAFF;
--fu-card: #1F1F1F;
--fu-card-border: #2A2A2A;
--fu-card-hover: #262626;
--fu-control-border: #737373;
--fu-control-hover: #A3A3A3;
--fu-dim: #929292;
--fu-field-border: #737373;
--fu-field-wash: rgb(255 255 255/0.03);
--fu-hover: #333333;
--fu-hover-wash: rgb(255 255 255/0.14);
--fu-input: rgb(0 0 0/0);
--fu-line: #404040;
--fu-mute: #BDBDBD;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(255 255 255/0.1);
--fu-pill-square: #333333;
--fu-pill-text: #C8C8C8;
--fu-selected: #1F2747;
--fu-skeleton: rgb(255 255 255/0.12);
--fu-skeleton-on: rgb(143 170 255/0.3);
--fu-surface-3: #2A2A2A;
--fu-text: #F8F5F1;
--fu-wash: rgb(255 255 255/0.08);
}
```
To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).
```css
.light {
--fu-accent: #3B57E6;
--fu-accent-hover: #2F4AD0;
--fu-accent-pale: #253A9E;
--fu-accent-soft: #3049D2;
--fu-card: #FFFFFF;
--fu-card-border: #E5E5E2;
--fu-card-hover: #F8F8F6;
--fu-control-border: #787874;
--fu-control-hover: #5B5B57;
--fu-dim: #555552;
--fu-field-border: #949490;
--fu-field-wash: #FFFFFF;
--fu-hover: rgb(29 27 24/0.11);
--fu-hover-wash: rgb(29 27 24/0.07);
--fu-input: #FFFFFF;
--fu-line: #C4C4C0;
--fu-mute: #444442;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(29 27 24/0.06);
--fu-pill-square: rgb(29 27 24/0.07);
--fu-pill-text: #3C3C3A;
--fu-selected: #E8EDFD;
--fu-skeleton: rgb(29 27 24/0.09);
--fu-skeleton-on: rgb(48 73 210/0.18);
--fu-surface-3: rgb(29 27 24/0.07);
--fu-text: #1B1B19;
--fu-wash: rgb(29 27 24/0.05);
}
```
Keep the sizes, corners, spacing and motion as they are.
## Direction and language
It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.
Pass locale (default "en-US") to print its numbers, prices and dates the way a language writes them and to read typed numbers that way, e.g. locale="de-DE". The words stay English: change them through the props.
## Keep the accessibility
- Rows are native checkboxes; the whole row is the label and reads as name and count.
- Sub-options sit in their own list named after their option.
- "No match" and the suggestion are announced through a status region; "All N" has aria-expanded.
- Loading, it is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter. Disabled, the field and checkboxes are disabled.
- Tab moves from the search field through each checkbox, then to "All N".
- Space ticks the focused row; Escape in the search field clears it.
- While disabled nothing takes focus; in an error Tab reaches Retry.
When done, run the app, tell me which page to open, and show me the value changing as I use the filter.What it does
- Typing filters options and sub-options at once and marks the matching letters.
- Ticking an option opens its sub-options; ticking a sub-option narrows the option to it.
- The short list grows with what is ticked; "All N" shows the rest in a scroll area.
- A typo with no match offers the nearest name: "Toyta" gives "Did you mean Toyota?".
- A row with a count of 0 is dimmed and cannot be ticked.
Keyboard
- Tab moves from the search field through each checkbox, then to "All N".
- Space ticks the focused row; Escape in the search field clears it.
- While disabled nothing takes focus; in an error Tab reaches Retry.
Props
Value. { value: string; children: string[] }[]: one entry per ticked option, with the sub-options that narrow it. Empty children means the whole option. [] is no filter.
| Prop | Description |
|---|---|
optionsRequired | In display order: the first collapsedCount make the short list, the rest show after "All N". readonly { value: string; label: string; count: number; children?: { value: string; label: string; count: number }[] }[] |
valueRequired | The ticked options and their ticked sub-options. readonly { value: string; children: string[] }[] |
onChangeRequired | Called with the new picks. (value: { value: string; children: string[] }[]) => void |
labelRequired | Accessible name of the list. string |
nounDefault "items" | Plural word for the options: "Search makes", "All 21 makes", "No makes match". string |
collapsedCountDefault 8 | How many options the short list shows. number |
formatCountDefault 1,234 | Text in each count pill. (n: number) => string |
countLabelDefault "6 results" | Screen-reader words for a count, e.g. "6 cars". (n: number) => string |
variantDefault "card" | "panel": a 48px search, 20px filled checkboxes, 17px names and plain counts, for a list that sits in a panel rather than a card. The list grows in place and the panel scrolls it. "card" | "panel" |
localeDefault "en-US" | Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English. string |
statusDefault "ready" | "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place. "ready" | "loading" | "error" |
onRetryOptional | Called by Retry in the error state. Without it the error line has no button. () => void |
errorTextDefault "Couldn't load the <noun>." | The error line, in plain words. string |
emptyTextDefault "No <noun> to show" | The line shown under a small picture, in place of the options, when there are none. string |
disabledDefault false | Dims the whole filter, blocks pointer and keyboard input and reads as unavailable. boolean |
The card: FilterCard
| Prop | Description |
|---|---|
titleRequired | The card's heading, e.g. "Price". string |
summaryOptional | The value in words, shown on the closed card. Null or empty means the filter is unset. string | null |
onClearOptional | Clears this filter. When given, a Clear button takes the summary's place while open or hovered. () => void |
open / defaultOpen / onOpenChangeDefault closed | Controlled or uncontrolled open state. boolean / boolean / (open: boolean) => void |
headingLevelDefault 3 | Heading level around the head button. 2 | 3 | 4 | 5 | 6 |
bodyClassNameOptional | Classes for the body, e.g. to tune the space under the content. string |