Bar list
Tick options in a list where a soft bar behind each row shows its count, such as makes.
Live example
25 cars
Copy
Add the "Bar list" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Bar list: Tick options in a list where a soft bar behind each row shows its count, such as makes.
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/bar-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/bar-list.tsx
```tsx
"use client";
import { useId, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor, resultsLabel } from "../lib/format";
import { useOverflows } from "../lib/overflow";
import { SCROLL } from "../lib/scroll";
import { CheckIcon, ChevronDownIcon } from "../ui/icons";
import { placeholderLabels, SKELETON_FILL, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextSwap } from "../ui/text-swap";
export type BarListOption<V extends string = string> = { value: V; label: string; count: number };
export type BarListProps<V extends string = string> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
/** The rows, in a steady order (e.g. by total count), so rows never jump while counts change. */
options: readonly BarListOption<V>[];
/** The values that are ticked. */
value: readonly V[];
/** Called with the new list, in the order of the options. */
onChange: (value: V[]) => void; /** Accessible name of the list. */
label: string;
/** Plural word for the rows: "All 10 makes", "Fewer makes". Default "items". */
noun?: string;
/** How many rows show before "All N". Default 6. */
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;
};
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
/** A loading bar's share of the row: a calm falling ranking, the same whatever the data, so it never hints at counts. */
const loadingShare = (i: number) => Math.max(0.2, 0.86 * 0.8 ** i);
type RowProps = {
label: string;
count: number;
share: number;
/** The row's place in the list, for its loading bar. */
rank: number;
checked: boolean;
/** Just unticked under the pointer or keyboard at 0: it stays enabled until both have left it. */
kept: boolean;
format: (n: number) => string;
countLabel: (n: number) => string;
onToggle: (input: HTMLInputElement) => void;
onRelease: () => void;
};
// The whole row is the checkbox's label; the native box is hidden and drawn again. The bar behind the name is the row's
// count as a share of the largest one (a small share is a hairline), growing from the start edge, and eases to a new width over 480ms when other
// filters change the counts. A ticked row is tinted end to end under its bar. A long name wraps; the box and the count stay in the row.
// While loading the bar pulses at a calm falling width and the name and count draw as placeholders; the tick stays, as it is the person's.
function Row({ label, count, share, rank, checked, kept, format, countLabel, onToggle, onRelease }: RowProps) {
const { loading } = useLoading();
return (
<label
data-state={checked ? "on" : "off"}
onPointerLeave={(event) => kept && !event.currentTarget.contains(document.activeElement) && onRelease()}
className={cn(
"group/row relative isolate flex min-h-10 min-w-0 cursor-pointer items-center gap-3 rounded-[10px] py-2.5 pe-3 ps-3 text-[14px] leading-5 pointer-coarse:min-h-11",
"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-default transition-[opacity] duration-300 motion-reduce:transition-none",
count === 0 && !checked && !loading && "opacity-40",
)}
>
<span
aria-hidden="true"
className={cn(
"absolute inset-x-0 inset-y-[2px] -z-20 rounded-[7px] bg-[var(--fu-selected,#1F2747)] transition-[opacity] duration-200 motion-reduce:transition-none",
checked ? "opacity-100" : "opacity-0",
)}
/>
<span
aria-hidden="true"
className={cn(
"absolute inset-y-[2px] inset-s-[40px] -z-10 rounded-[6px] transition-[width,background-color] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
loading
? SKELETON_FILL
: checked
? "bg-[var(--fu-accent-soft,#8FAAFF)]/15"
: "bg-[var(--fu-share,rgb(255_255_255/0.05))] [@media(hover:hover)]:group-hover/row:bg-[var(--fu-share-hover,rgb(255_255_255/0.1))]",
)}
style={{ width: loading ? `calc((100% - 40px) * ${loadingShare(rank)})` : count > 0 ? `max(2px, calc((100% - 40px) * ${share}))` : 0 }}
/>
<input
type="checkbox"
checked={checked}
disabled={count === 0 && !checked && !kept}
aria-label={`${label}, ${countLabel(count)}`}
onChange={(event) => onToggle(event.currentTarget)}
onBlur={(event) => kept && !event.currentTarget.parentElement?.matches(":hover") && onRelease()}
className="peer absolute size-[18px] cursor-[inherit] opacity-0"
/>
<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)]",
"peer-checked:border-[var(--fu-accent-soft,#8FAAFF)] [@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-300 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={cn(
"ms-1.5 min-w-0 flex-1 [overflow-wrap:anywhere] transition-[color] duration-200",
checked ? "font-medium text-[var(--fu-accent-pale,#D1DDFF)]" : "text-[var(--fu-text,#F8F5F1)]",
)}
>
<SkeletonText>{label}</SkeletonText>
</span>
<SkeletonText className="shrink-0">
<TextSwap
aria-hidden="true"
className={cn(
"shrink-0 justify-items-end text-[13px] tabular-nums transition-[color] duration-200",
checked ? "font-medium text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-mute,#BDBDBD)]",
)}
>
{format(count)}
</TextSwap>
</SkeletonText>
</label>
);
}
/**
* A checklist where a soft bar behind each row shows its count as a share of the largest, so the list reads as a
* ranking at a glance. Bars and counts ease to their new values when other filters change them; ticked rows turn
* accent. The first `collapsedCount` rows show; "All N" opens the rest under them. A list taller than 11 rows scrolls
* in place, with half a row showing past the edge so it reads as more.
*/
export function BarList<V extends string = string>({
options,
value,
onChange,
label,
noun = "items",
collapsedCount = 6,
formatCount: formatCountProp,
countLabel: countLabelProp,
locale,
status = "ready",
onRetry,
errorText = `Couldn't load the ${noun}.`,
emptyText = `No ${noun} to show`,
disabled = false,
className,
...props
}: BarListProps<V>) {
const formatCount = formatCountProp ?? formatsFor(locale).number;
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const restId = useId();
// Opens on its own when a ticked row would be hidden.
const [all, setAll] = useState(() => options.slice(collapsedCount).some((option) => value.includes(option.value)));
const most = Math.max(0, ...options.map((option) => option.count));
const scrollBox = useOverflows();
// A row turned off under the pointer or keyboard would become disabled at 0 and drop focus; it stays as it is until
// focus and the pointer have both left it.
const [kept, setKept] = useState<V | null>(null);
const toggle = (v: V, input: HTMLInputElement) => {
const on = value.includes(v);
setKept(on && (document.activeElement === input || input.parentElement?.matches(":hover")) ? v : null);
onChange(options.flatMap((option) => ((option.value === v ? !on : value.includes(option.value)) ? [option.value] : [])));
};
// 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, stand-in rows keep the place the short list will take.
const listed: readonly BarListOption<V>[] =
loading && options.length === 0 ? placeholderLabels(collapsedCount).map((name, i) => ({ value: `${i}` as V, label: name, count: 0 })) : options;
const row = (option: BarListOption<V>, rank: number) => (
<li key={option.value} className="m-0 p-0">
<Row
label={option.label}
count={option.count}
share={most > 0 ? option.count / most : 0}
rank={rank}
checked={value.includes(option.value)}
kept={kept === option.value}
format={formatCount}
countLabel={countLabel}
onToggle={(input) => toggle(option.value, input)}
onRelease={() => setKept(null)}
/>
</li>
);
const rest = listed.slice(collapsedCount);
return (
<div role="group" aria-label={label} aria-disabled={disabled || undefined} className={className} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} empty={options.length === 0} emptyText={emptyText} disabled={disabled}>
<div className="flex flex-col">
{/* Every row scrolls in the same box, so all rows keep one width when a scrollbar shows. */}
<div ref={scrollBox} className={cn("max-h-[460px] overflow-y-auto data-[overflows]:overscroll-contain", SCROLL)}>
<ul className="m-0 flex list-none flex-col p-0">{listed.slice(0, collapsedCount).map(row)}</ul>
{rest.length > 0 && (
<div
id={restId}
inert={!all}
className={cn("grid transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none", SMOOTH, all ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}
>
<div className="min-h-0 overflow-hidden">
<ul
className={cn(
"m-0 flex list-none flex-col p-0 transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
all ? "translate-y-0 opacity-100 blur-none delay-[80ms]" : "-translate-y-1.5 opacity-0 blur-[6px]",
)}
>
{rest.map((option, i) => row(option, collapsedCount + i))}
</ul>
</div>
</div>
)}
</div>
{rest.length > 0 && (
<button
type="button"
aria-expanded={all}
aria-controls={restId}
onClick={() => setAll(!all)}
className={cn(
"relative mt-1 inline-flex h-9 cursor-pointer items-center gap-1 self-start rounded-[10px] px-3 text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)]",
"transition-[background-color] duration-200 motion-reduce:transition-none hover:bg-[var(--fu-wash,rgb(255_255_255/0.08))]",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1 pointer-coarse:after:content-['']",
)}
>
<SkeletonText>
<TextSwap>{all ? `Fewer ${noun}` : `All ${formatCount(options.length)} ${noun}`}</TextSwap>
</SkeletonText>
<ChevronDownIcon size={16} className={cn("transition-[rotate] duration-[480ms] motion-reduce:transition-none", SMOOTH, all && "rotate-180")} />
</button>
)}
</div>
</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/overflow.ts
```ts
import { useCallback, useRef } from "react";
/**
* A ref for a box that scrolls: it marks the box `data-overflows` while its content is taller than the box. Chromium
* counts a box with overflow-y auto as a scroll container even when it has nothing to scroll, so overscroll-contain on
* it stops the page from scrolling under the pointer or a finger. Such a box contains only while it overflows:
* `data-[overflows]:overscroll-contain`.
*/
export function useOverflows<T extends HTMLElement = HTMLDivElement>() {
const stop = useRef<(() => void) | null>(null);
return useCallback((node: T | null) => {
stop.current?.();
stop.current = null;
if (!node) return;
let live = true;
let settling = false;
const measure = () => {
if (!live) return;
node.toggleAttribute("data-overflows", node.scrollHeight > node.clientHeight + 1);
// Content that moves in (a rise, a slide) overflows until it lands, and landing resizes nothing: measure again then.
if (settling) return;
// Only animations still running: a finished one held by fill is listed too, and its settled promise would loop.
const moving = node
.getAnimations({ subtree: true })
.filter((animation) => animation.playState === "running" && animation.effect?.getComputedTiming().endTime !== Infinity);
if (!moving.length) return;
settling = true;
void Promise.allSettled(moving.map((animation) => animation.finished)).then(() => {
settling = false;
measure();
});
};
// A box stops growing at its max height while its content goes on, so the content is watched too.
const sizes = new ResizeObserver(measure);
const watch = () => {
sizes.disconnect();
sizes.observe(node);
for (const child of node.children) sizes.observe(child);
};
const children = new MutationObserver(watch);
watch();
children.observe(node, { childList: true });
stop.current = () => {
live = false;
sizes.disconnect();
children.disconnect();
};
}, []);
}
```
### 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/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/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/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/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/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/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/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-swap.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
export type TextSwapProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
/** The text to show. A change animates: the old text leaves upward, the new one rises in. */
children: string;
};
const EASE = "cubic-bezier(0.42, 0, 0.58, 1)";
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
/** Old text leaves over 150ms; new text enters over 170ms after 110ms; both move 4px through a 2px blur. */
export function TextSwap({ children, className, ...props }: TextSwapProps) {
const [shown, setShown] = useState(children);
const [leaving, setLeaving] = useState<{ text: string; key: number } | null>(null);
const nowRef = useRef<HTMLSpanElement>(null);
const oldRef = useRef<HTMLSpanElement>(null);
if (children !== shown) {
setLeaving(reducedMotion() ? null : { text: shown, key: (leaving?.key ?? 0) + 1 });
setShown(children);
}
useLayoutEffect(() => {
if (!leaving) return;
const out = oldRef.current?.animate(
[
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
{ opacity: 0, transform: "translateY(-4px)", filter: "blur(2px)" },
],
{ duration: 150, easing: EASE, fill: "forwards" },
);
const into = nowRef.current?.animate(
[
{ opacity: 0, transform: "translateY(4px)", filter: "blur(2px)" },
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
],
{ duration: 170, delay: 110, easing: EASE, fill: "backwards" },
);
const key = leaving.key;
const done = () => setLeaving((current) => (current?.key === key ? null : current));
if (into) into.onfinish = done;
else done();
return () => {
out?.cancel();
into?.cancel();
};
}, [leaving]);
return (
<span className={cn("inline-grid whitespace-nowrap", className)} {...props}>
<span ref={nowRef} className="[grid-area:1/1]">
{shown}
</span>
{leaving && (
<span ref={oldRef} key={leaving.key} aria-hidden="true" className="pointer-events-none [grid-area:1/1]">
{leaving.text}
</span>
)}
</span>
);
}
```
### 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>
);
}
```
### components/filters-ui/ui/segmented.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { onDirChange, readingKey, startOffset } from "../lib/direction";
import { formatsFor, resultsLabel } from "../lib/format";
import { CountPill } from "./count-pill";
import { SkeletonText } from "./skeleton";
export type SegmentedValue = string | number | null;
export type SegmentedOption<V extends SegmentedValue> = {
value: V;
label: ReactNode;
/** Shown in a count pill and read out with the label. Leave out for no pill ("Any"). */
count?: number;
disabled?: boolean;
};
export type SegmentedProps<V extends SegmentedValue> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> & {
options: readonly SegmentedOption<V>[];
value: V;
onChange: (value: V) => void;
/** Accessible name of the group. */
label: string;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts by default, e.g. "de-DE". */
locale?: string;
disabled?: boolean;
/** "equal": options with a count share the width equally, and a name too long to sit beside its count wraps with the count under it. "content": the same, except an option whose words need more keeps its own width (a name of several words may wrap beside its count instead). An option without a count ("Any") hugs its words while the control is under 340px wide. */
fit?: "equal" | "content";
};
// Forced colours drop the thumb's fill, so the chosen segment sits on the system highlight. Its colours stay as given:
// left to the browser, its words would sit on a backplate in the page colour.
const FORCED_ON =
"forced-colors:text-[HighlightText] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-offset-2 forced-colors:focus-visible:outline-[CanvasText]";
/**
* A segmented control: an option without a count ("Any") hugs its words while the control is under 340px wide (from 340px all share the width), the others share the rest equally, and one pill slides to the chosen one over 340ms.
* It is a radiogroup with one tab stop; arrow keys, Home and End move and select. Right to left, the options run from
* the right and Left and Right follow them. Long names wrap and the track grows. Inside a loading StatusFrame the
* words and counts of options with a count draw as placeholders; "Any" and the pill on the choice stay.
*/
export function Segmented<V extends SegmentedValue>({
options,
value,
onChange,
label,
formatCount,
countLabel,
locale,
disabled = false,
fit = "equal",
className,
style,
...props
}: SegmentedProps<V>) {
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
const words = countLabel ?? ((n: number) => resultsLabel(n, locale));
const count = formatCount ?? formatsFor(locale).number;
const index = options.findIndex((option) => Object.is(option.value, value));
const usable = (i: number) => !disabled && !options[i].disabled;
const [box, setBox] = useState<{ start: number; width: number; rtl: boolean } | null>(null);
const [placed, setPlaced] = useState(false);
// "Any" hugs its words only beside options that carry counts, and only while the track is narrow; a set without counts stays equal.
const counted = options.some((option) => option.count !== undefined);
const hugs = counted && options.some((option) => option.count === undefined);
const measuring = fit === "content" || hugs;
const tabStop = index >= 0 ? index : options.findIndex((_, i) => usable(i));
// Widths differ per option, so the pill takes the chosen button's measured box instead of a share of the track.
// Until it is measured, the chosen button paints its own pill, so the server render already shows the choice.
useLayoutEffect(() => {
const button = measuring && index >= 0 ? buttons.current[index] : null;
if (!button) return;
const measure = () => setBox({ start: startOffset(button), width: button.offsetWidth, rtl: getComputedStyle(button).direction === "rtl" });
measure();
const frame = requestAnimationFrame(() => setPlaced(true));
const observer = new ResizeObserver(measure);
buttons.current.forEach((b) => b && observer.observe(b));
const stop = onDirChange(measure);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
stop();
};
}, [measuring, index, options.length]);
const measured = measuring ? box : null;
const pick = (i: number) => {
buttons.current[i]?.focus();
if (i !== index) onChange(options[i].value);
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const from = Math.max(0, buttons.current.findIndex((b) => b === document.activeElement));
const n = options.length;
const walk = (start: number, step: number) => {
for (let k = 0, i = start; k < n; k++, i = (i + step + n) % n) if (usable(i)) return i;
return -1;
};
let next = -1;
switch (readingKey(event.key, event.currentTarget)) {
case "ArrowRight":
case "ArrowDown":
next = walk((from + 1) % n, 1);
break;
case "ArrowLeft":
case "ArrowUp":
next = walk((from - 1 + n) % n, -1);
break;
case "Home":
next = walk(0, 1);
break;
case "End":
next = walk(n - 1, -1);
break;
default:
return;
}
event.preventDefault();
if (next >= 0) pick(next);
};
return (
<div
role="radiogroup"
aria-label={label}
aria-disabled={disabled || undefined}
onKeyDown={onKeyDown}
className={cn("@container relative flex min-h-10 rounded-[12px] bg-[var(--fu-segment-track,#2A2A2A)] p-1", disabled && "opacity-50", className)}
style={style}
{...props}
>
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute top-1 bottom-1 inset-s-1 rounded-[9px] bg-[var(--fu-thumb,#404040)] [--flip:1] rtl:[--flip:-1]",
"forced-colors:bg-[Highlight] forced-colors:[forced-color-adjust:none]",
measuring ? placed && "transition-[left,right,width,opacity]" : "transition-[translate,opacity]",
"duration-[340ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
(index < 0 || (measuring && !measured)) && "opacity-0",
)}
style={
measuring
? // physical: the start offset is measured in script from the physical edge that is the start in this direction.
{ [measured?.rtl ? "right" : "left"]: measured?.start, width: measured?.width }
: { width: `calc((100% - 8px) / ${options.length})`, translate: `calc(var(--flip,1) * ${Math.max(index, 0) * 100}%) 0` }
}
/>
{options.map((option, i) => {
const on = i === index;
const off = !usable(i);
const hug = hugs && option.count === undefined;
return (
<button
key={String(option.value)}
ref={(node) => {
buttons.current[i] = node;
}}
type="button"
role="radio"
aria-checked={on}
tabIndex={i === tabStop ? 0 : -1}
disabled={off}
onClick={() => pick(i)}
className={cn(
"group/seg relative flex min-w-0 cursor-pointer items-center justify-center gap-x-1.5 gap-y-1 rounded-[9px] py-1.5 text-[14px] leading-5 font-medium",
hug ? "flex-none px-2.5 @min-[340px]:flex-1 @min-[340px]:px-0.5" : "flex-1 px-0.5",
// At least its longest word and its count, so a single word is never cut; a longer name wraps.
fit === "content" && !hug && "min-w-min",
// In an equal share, a name too long to sit beside its count takes its own lines and the count moves under it.
fit === "equal" && "flex-wrap content-center",
on && measuring && !measured && "bg-[var(--fu-thumb,#404040)] forced-colors:bg-[Highlight]",
"transition-[color,background-color,scale,opacity] duration-[340ms] ease-[cubic-bezier(0.22,1,0.36,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
// Hover and press fill with a faint thumb, so they preview the pick and still read on any track colour.
on
? "text-[var(--fu-text,#F8F5F1)]"
: cn(
"text-[var(--fu-mute,#BDBDBD)] enabled:hover:text-[var(--fu-text,#F8F5F1)]",
"enabled:hover:bg-[color-mix(in_srgb,var(--fu-thumb,#404040)_40%,transparent)] enabled:active:bg-[color-mix(in_srgb,var(--fu-thumb,#404040)_70%,transparent)]",
),
"disabled:cursor-not-allowed",
off && !disabled && !on && "opacity-40",
on && FORCED_ON,
)}
>
{/* Words wrap at spaces and the track grows; a single word too long for its segment ends in an ellipsis.
Words that wrap stop 8px short of the segment's edges; beside a count they never reach that width, so a
name on one line sits as it did. */}
<span className={cn("min-w-0 overflow-hidden text-center text-ellipsis", option.count !== undefined && "max-w-[calc(100%-12px)]")}>
{option.count === undefined ? option.label : <SkeletonText>{option.label}</SkeletonText>}
</span>
{option.count !== undefined && (
<>
<CountPill
aria-hidden="true"
count={option.count}
format={count}
className={cn(
"group-enabled/seg:group-hover/seg:bg-[var(--fu-pill-hover,rgb(255_255_255/0.16))] group-enabled/seg:group-hover/seg:text-[var(--fu-text,#F8F5F1)]",
on && "forced-colors:text-[HighlightText]",
)}
/>
<span className="sr-only">, {words(option.count)}</span>
</>
)}
</button>
);
})}
</div>
);
}
```
### 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/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>
);
}
```
## What it does
- A soft bar behind each row shows its count as a share of the largest, so the list reads as a ranking.
- When other filters change the counts, bars ease to their new width and the numbers swap.
- A ticked row turns accent: its bar, its name and its count.
- The first rows show; "All N" opens the rest. A row with a count of 0 is dimmed and cannot be ticked.
## Props and value
BarList (components/filters-ui/filters/bar-list.tsx) holds this value: V[], where V is a string: the ticked values, in the order of the options. [] is no filter.
- options: readonly { value: V; label: string; count: number }[] (required). The rows. Keep the order steady (e.g. by total count) so rows never jump while counts change.
- value: readonly V[] (required). The ticked values.
- onChange: (value: V[]) => void (required). Called with the new list, in the order of the options.
- label: string (required). Accessible name of the list.
- noun: string (default "items"). Plural word for the rows: "All 10 makes", "Fewer makes".
- collapsedCount: number (default 6). How many rows show before "All N".
- formatCount: (n: number) => string (default 1,234). Text of each count.
- countLabel: (n: number) => string (default "6 results"). Screen-reader words for a count, e.g. "6 cars".
- 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. Each row keeps its checkbox and its tick; its bar pulses at a calm falling width, like a ranking, and its name and count draw as placeholders. With no options yet it draws collapsedCount 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 line and Retry take the list's place, and "All N" hides with it. 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 list; the default names the noun: "No makes to show"
- Zero results (every count is 0): Every count is 0: the bars go, and each row stays in place, dimmed, and cannot be ticked; a ticked row can still be unticked.
- 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, and the bar grows with it.
- Many options (data, not a prop): The first collapsedCount rows show; "All N" opens the rest under them, and past 11 rows the list scrolls in place with half a row showing at its edge.
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 { BarList } from "@/components/filters-ui/filters/bar-list";
import { formatsFor } from "@/components/filters-ui/lib/format";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";
import { Segmented } from "@/components/filters-ui/ui/segmented";
type Body = "SUV" | "Sedan" | "Truck";
// Cars in stock per make and body style.
const STOCK: Record<string, Record<Body, number>> = {
Toyota: { SUV: 12, Sedan: 9, Truck: 4 },
Honda: { SUV: 9, Sedan: 11, Truck: 1 },
Ford: { SUV: 7, Sedan: 2, Truck: 12 },
Hyundai: { SUV: 8, Sedan: 4, Truck: 0 },
Tesla: { SUV: 6, Sedan: 5, Truck: 1 },
Chevrolet: { SUV: 3, Sedan: 1, Truck: 8 },
Kia: { SUV: 6, Sedan: 3, Truck: 0 },
Ram: { SUV: 0, Sedan: 0, Truck: 9 },
Mazda: { SUV: 5, Sedan: 2, Truck: 0 },
Subaru: { SUV: 5, Sedan: 1, Truck: 0 },
};
const MAKES = Object.keys(STOCK);
const BODIES: Body[] = ["SUV", "Sedan", "Truck"];
// How many cars match, for any makes ([] is all) and one body style (null is any).
const count = (makes: string[], body: Body | null) =>
(makes.length ? makes : MAKES).reduce((n, make) => n + BODIES.reduce((m, b) => m + (body === null || body === b ? STOCK[make][b] : 0), 0), 0);
const summaryOf = (makes: string[]) =>
makes.length === 0 ? null : makes.length <= 2 ? makes.join(", ") : `${makes.slice(0, 2).join(", ")} +${makes.length - 2}`;
export default function MakeBarsExample({ locale = "en-US" }: { locale?: string }) {
const { number } = formatsFor(locale);
const carCount = (n: number) => (n === 1 ? "1 car" : `${number(n)} cars`);
const [makes, setMakes] = useState<string[]>(["Toyota"]);
const [body, setBody] = useState<Body | null>(null);
// Each count leaves its own filter out, so it says what picking that option would give.
const makeOptions = MAKES.map((make) => ({ value: make, label: make, count: count([make], body) }));
const bodyOptions = [{ value: null, label: "Any" }, ...BODIES.map((b) => ({ value: b, label: b, count: count(makes, b) }))];
return (
<div className="flex w-full max-w-[320px] flex-col gap-3">
<FilterCard title="Make" summary={summaryOf(makes)} onClear={() => setMakes([])} defaultOpen>
<BarList label="Make" noun="makes" options={makeOptions} value={makes} onChange={setMakes} countLabel={carCount} locale={locale} />
</FilterCard>
<FilterCard title="Body style" summary={body} onClear={() => setBody(null)} defaultOpen>
<Segmented label="Body style" options={bodyOptions} value={body} onChange={setBody} countLabel={carCount} locale={locale} />
</FilterCard>
<p aria-live="polite" className="px-4 text-[14px] leading-5 tabular-nums">
<span className="font-medium">{number(count(makes, body))}</span> <span className="text-[var(--fu-dim,#929292)]">{count(makes, body) === 1 ? "car" : "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-hover: #333333;
--fu-hover-wash: rgb(255 255 255/0.14);
--fu-line: #404040;
--fu-mute: #BDBDBD;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(255 255 255/0.1);
--fu-pill-hover: rgb(255 255 255/0.16);
--fu-pill-square: #333333;
--fu-pill-text: #C8C8C8;
--fu-segment-track: #2A2A2A;
--fu-selected: #1F2747;
--fu-share: rgb(255 255 255/0.05);
--fu-share-hover: rgb(255 255 255/0.1);
--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-thumb: #404040;
--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-hover: rgb(29 27 24/0.11);
--fu-hover-wash: rgb(29 27 24/0.07);
--fu-line: #C4C4C0;
--fu-mute: #444442;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(29 27 24/0.06);
--fu-pill-hover: rgb(29 27 24/0.1);
--fu-pill-square: rgb(29 27 24/0.07);
--fu-pill-text: #3C3C3A;
--fu-segment-track: rgb(29 27 24/0.07);
--fu-selected: #E8EDFD;
--fu-share: rgb(29 27 24/0.04);
--fu-share-hover: rgb(29 27 24/0.07);
--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-thumb: #FFFFFF;
--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 in a named group; each reads as its name and count ("Ford, 12 cars").
- Bars are hidden from screen readers; the counts carry the meaning.
- "All N" has aria-expanded; hidden rows are inert. Motion is skipped when reduced motion is asked for.
- Loading, the group is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter. Disabled, the group is aria-disabled and every checkbox is disabled.
- Tab moves through each checkbox, then to "All N".
- Space ticks the focused row; a row unticked at 0 keeps focus until you leave 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
- A soft bar behind each row shows its count as a share of the largest, so the list reads as a ranking.
- When other filters change the counts, bars ease to their new width and the numbers swap.
- A ticked row turns accent: its bar, its name and its count.
- The first rows show; "All N" opens the rest. A row with a count of 0 is dimmed and cannot be ticked.
Keyboard
- Tab moves through each checkbox, then to "All N".
- Space ticks the focused row; a row unticked at 0 keeps focus until you leave it.
- While disabled nothing takes focus; in an error Tab reaches Retry.
Props
Value. V[], where V is a string: the ticked values, in the order of the options. [] is no filter.
| Prop | Description |
|---|---|
optionsRequired | The rows. Keep the order steady (e.g. by total count) so rows never jump while counts change. readonly { value: V; label: string; count: number }[] |
valueRequired | The ticked values. readonly V[] |
onChangeRequired | Called with the new list, in the order of the options. (value: V[]) => void |
labelRequired | Accessible name of the list. string |
nounDefault "items" | Plural word for the rows: "All 10 makes", "Fewer makes". string |
collapsedCountDefault 6 | How many rows show before "All N". number |
formatCountDefault 1,234 | Text of each count. (n: number) => string |
countLabelDefault "6 results" | Screen-reader words for a count, e.g. "6 cars". (n: number) => string |
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 |