Live example
123 of 256 cars
Copy
Add the "Year range" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Year range: Pick a range from a few set values, such as model years.
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/range-select.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/range-select.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { RangeChart, type RangeValue } from "../ui/range-chart";
import { Select } from "../ui/select";
import { StatusFrame, type StateProps } from "../ui/status-frame";
export type RangeSelectProps<V extends number> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
Omit<StateProps, "emptyText"> & {
/** The values to pick from, in ascending order, e.g. model years. One bar each. */
options: readonly V[];
/** [from, to], both inclusive. null is an open end. */
value: [V | null, V | null];
onChange: (value: [V | null, V | null]) => void;
/** Item count per option, in the order of `options`. */
buckets?: readonly number[];
/** Picker, tooltip and screen-reader text for a value. Default: the number with no group marks, in the locale's digits. */
format?: (value: V) => string;
/** Picker order. Default "ascending"; "descending" puts the newest year first. */
pickerOrder?: "ascending" | "descending"; /** The open-end choice in both pickers. Default "Any". */
anyLabel?: string;
/** Visible picker prefixes. Default "From" and "To". */
prefixes?: { low?: string; high?: string };
/** Accessible names of the handles and pickers. Default: the prefixes. Keep the prefix word in them. */
labels?: { low?: string; high?: string };
/** Screen-reader words for a count in the pickers, e.g. "6 cars". Default "6 results". */
countLabel?: (n: number) => string;
/** Bar width as a share of its slot, so a chart with few bars can keep the rhythm of a denser one. Default 1. */
barScale?: number;
/** Formats values and counts by default, e.g. "ar-EG". Default "en-US". */
locale?: string;
};
const ANY = "";
/**
* A range over a few discrete values: a bar chart with two handles and From and To pickers under it, kept in step
* both ways. With buckets, each picker choice shows how many items picking it would give. Handles sit between bars, so the two may hold a single value. Picking From past To moves To along
* to the same value, and picking To before From moves From back: the pick always wins.
*/
export function RangeSelect<V extends number>({
options,
value,
onChange,
buckets,
format: formatProp,
pickerOrder = "ascending",
anyLabel = "Any",
prefixes,
labels,
countLabel,
barScale,
locale,
status = "ready",
onRetry,
errorText = "Couldn't load the counts.",
disabled = false,
className,
...props
}: RangeSelectProps<V>) {
const format = formatProp ?? formatsFor(locale).plain;
const n = options.length;
const lowPrefix = prefixes?.low ?? "From";
const highPrefix = prefixes?.high ?? "To";
const lowLabel = labels?.low ?? lowPrefix;
const highLabel = labels?.high ?? highPrefix;
// The chart runs over bar edges 0..n: From at edge i is options[i]; To at edge j is options[j - 1].
const indexOf = (v: V) => {
const at = options.findIndex((option) => option >= v);
return at < 0 ? n - 1 : at;
};
const edges: RangeValue = [value[0] === null ? null : indexOf(value[0]), value[1] === null ? null : indexOf(value[1]) + 1];
// The oldest From and the newest To exclude nothing, so they are the open ends.
const emit = ([low, high]: [V | null, V | null]) => {
const next: [V | null, V | null] = [low === options[0] ? null : low, high === options[n - 1] ? null : high];
if (next[0] !== value[0] || next[1] !== value[1]) onChange(next);
};
const fromEdges = ([low, high]: RangeValue) =>
emit([low === null ? null : options[low], high === null ? null : options[high - 1]]);
// With buckets, each choice counts what picking it would give, the other end included; a choice past the other end
// moves it along, as the pick does.
const within = (low: V | null, high: V | null) =>
buckets ? options.reduce((sum, option, i) => ((low === null || option >= low) && (high === null || option <= high) ? sum + (buckets[i] ?? 0) : sum), 0) : undefined;
const choicesFor = (end: "low" | "high") => [
{ value: ANY, label: anyLabel, count: end === "low" ? within(null, value[1]) : within(value[0], null) },
...(pickerOrder === "descending" ? [...options].reverse() : options).map((option) => ({
value: String(option),
label: format(option),
count:
end === "low"
? within(option, value[1] !== null && value[1] < option ? option : value[1])
: within(value[0] !== null && value[0] > option ? option : value[0], option),
})),
];
const read = (text: string) => (text === ANY ? null : (options.find((option) => String(option) === text) ?? null));
// The frame dims and blocks everything while disabled, so the chart and pickers are not dimmed a second time.
return (
<div className={cn("pt-1", className)} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled}>
<RangeChart
min={0}
max={n}
step={1}
value={edges}
onChange={fromEdges}
buckets={buckets}
format={(edge, handle) => format(options[Math.max(0, Math.min(n - 1, handle === "low" ? edge : edge - 1))])}
openLabel={format(options[n - 1])}
labels={{ low: lowLabel, high: highLabel }}
barScale={barScale}
locale={locale}
/>
<div className="mt-3 grid grid-cols-[repeat(auto-fit,minmax(min(100%,7rem),1fr))] gap-2">
<Select
label={lowLabel}
prefix={lowPrefix}
options={choicesFor("low")}
countLabel={countLabel}
locale={locale}
value={value[0] === null ? ANY : String(value[0])}
onChange={(text) => {
const low = read(text);
emit([low, low !== null && value[1] !== null && value[1] < low ? low : value[1]]);
}}
/>
<Select
label={highLabel}
prefix={highPrefix}
options={choicesFor("high")}
countLabel={countLabel}
locale={locale}
value={value[1] === null ? ANY : String(value[1])}
onChange={(text) => {
const high = read(text);
emit([high !== null && value[0] !== null && value[0] > high ? high : value[0], high]);
}}
/>
</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/ui/range-chart.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type PointerEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { isRtl, readingKey } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { EmptyNote } from "./empty-note";
import { SKELETON_FILL, useLoading } from "./skeleton";
/** [low, high]. null is an open end: no lower or no upper limit. */
export type RangeValue = [number | null, number | null];
type Handle = "low" | "high";
export type RangeChartProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> & {
min: number;
max: number;
step: number;
value: RangeValue;
onChange: (value: RangeValue) => void;
/** Item count per bar, spread evenly from min to max. Leave out for a plain slider. */
buckets?: readonly number[];
/** Tooltip and screen-reader text for a value. Gets the handle too, for scales where the high handle reads one step back. */
format?: (value: number, handle: "low" | "high") => string;
/** Tooltip text while the high end is open. Default: the top value and a plus ("$100,000+"). */
openLabel?: string;
/** One handle, for an upper limit only. The low end of `value` is ignored; the handle stops one step above min. */
single?: boolean;
/** Accessible names of the handles. */
labels?: { low?: string; high?: string };
/** Bar width as a share of its slot, so a chart with few bars can keep the rhythm of a denser one. Default 1. */
barScale?: number;
/**
* A handle that something outside the chart is dragging, a field of its own say, with the value under its pointer.
* The chart draws that handle there and raises the bars it passes, as in a drag of its own, without the tooltip.
*/
held?: { handle: "low" | "high"; value: number } | null;
/** Formats values when no format is given, e.g. "de-DE". */
locale?: string;
disabled?: boolean;
/**
* Draws pulsing columns in a calm hill and a pulsing rail, with no handles, in the space the chart takes.
* Default: the nearest StatusFrame's loading state.
*/
loading?: boolean;
/** Shown, quiet, in the bars' place when buckets is an empty list. Default "No items to show" */
emptyText?: ReactNode;
};
const HANDLE = 20;
/** Columns a loading chart draws when it has no buckets yet. */
const PLACEHOLDER_BARS = 20;
/** A loading column's height in percent: a soft hill, highest a third of the way along, as many prices are. */
export const hillAt = (i: number, n: number) => {
const x = (i + 0.5) / n;
return Math.round(18 + 64 * Math.exp(-(((x - 0.38) / 0.24) ** 2)));
};
// A press on a handle becomes a drag only after it travels this far, so a click does not show the tooltip.
const DRAG_FROM = 3;
const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));
// A handle stops at the end of the track, so the bars, the fill and the tooltip share the handle's travel.
const along = (fraction: number) => `calc(${HANDLE / 2}px + (100% - ${HANDLE}px) * ${fraction})`;
type Drag = { handle: Handle; fraction: number; moving: boolean };
/**
* A bar chart of how many items sit along a range, with one or two handles on a track under it.
* Each handle is backed by a visually hidden native range input for keyboards and screen readers. Right to left, the
* scale runs from the right: the minimum sits at the right end and the Left arrow raises a value.
*/
export function RangeChart({
min,
max,
step,
value,
onChange,
buckets,
format: formatProp,
openLabel,
single = false,
labels,
barScale = 1,
held,
locale,
disabled = false,
loading: loadingProp,
emptyText = "No items to show",
className,
...props
}: RangeChartProps) {
const status = useLoading();
const loading = loadingProp ?? status.loading;
const format: (value: number, handle: Handle) => string = formatProp ?? formatsFor(locale).number;
const root = useRef<HTMLDivElement>(null);
const tip = useRef<HTMLSpanElement>(null);
const grip = useRef<{ x: number; shift: number; handle: Handle; stacked: boolean; box: DOMRect } | null>(null);
const pressed = useRef(false);
const [drag, setDrag] = useState<Drag | null>(null);
const [lastHeld, setLastHeld] = useState<Handle>("high");
const [tipHalf, setTipHalf] = useState(0);
const span = max - min || 1;
const snap = (v: number) => clamp(min + Math.round((v - min) / step) * step, min, max);
const low = single ? min : clamp(value[0] ?? min, min, max);
const high = clamp(value[1] ?? max, Math.min(low + step, max), max);
const values = { low, high };
const fractionOf = (v: number) => (v - min) / span;
const stepFraction = step / span;
const emit = (nextLow: number, nextHigh: number) => {
const next: RangeValue = [single || nextLow <= min ? null : nextLow, nextHigh >= max ? null : nextHigh];
if (next[0] !== value[0] || next[1] !== value[1]) onChange(next);
};
// Handles never cross: each stops one step short of the other. Returns where the handle landed.
const moveTo = (handle: Handle, v: number) => {
if (handle === "low") {
const next = Math.min(snap(v), high - step);
emit(next, high);
return next;
}
const next = Math.max(snap(v), low + step);
emit(low, next);
return next;
};
// A drag passes the box it measured at press, so moves do not force a layout read each event.
const fractionAt = (clientX: number, box = root.current?.getBoundingClientRect()) => {
if (!box) return 0;
const fromStart = isRtl(root.current) ? box.right - clientX : clientX - box.left;
return clamp((fromStart - HANDLE / 2) / (box.width - HANDLE), 0, 1);
};
// Where each handle is drawn: a dragged one sits under the pointer, the other at its value. A handle held from
// outside is drawn the same way.
const pulled = !drag && held ? { handle: held.handle, fraction: clamp(fractionOf(held.value), 0, 1) } : null;
const shown = { low: fractionOf(low), high: fractionOf(high) };
if (drag) shown[drag.handle] = drag.fraction;
else if (pulled) shown[pulled.handle] = pulled.fraction;
const nearest = (v: number): Handle => {
if (single || v > high) return "high";
if (v < low) return "low";
return v - low < high - v ? "low" : "high";
};
// A press on a bar gives the nearest handle that bar's outer edge, so the bar stays in the range.
// A press on the rail moves the nearest handle to the step under the pointer.
const land = (clientX: number, onBar: boolean) => {
const at = min + fractionAt(clientX) * span;
if (onBar && buckets?.length) {
const size = span / buckets.length;
const bar = clamp(Math.floor((at - min) / size), 0, buckets.length - 1);
const handle = nearest(min + (bar + 0.5) * size);
return { handle, value: moveTo(handle, min + (handle === "low" ? bar : bar + 1) * size) };
}
const handle = nearest(at);
return { handle, value: moveTo(handle, at) };
};
const press = (event: PointerEvent<HTMLDivElement>) => {
pressed.current = false;
if (disabled || event.button !== 0) return;
const target = event.target as HTMLElement;
const handle = target.closest<HTMLElement>("[data-handle]")?.dataset.handle as Handle | undefined;
// A finger landing off a handle may be starting a scroll, so a tap waits for its click.
if (!handle && event.pointerType === "touch") return;
event.preventDefault();
pressed.current = true;
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {}
const box = event.currentTarget.getBoundingClientRect();
const landed = handle ? null : land(event.clientX, !!target.closest("[data-bars]"));
const held = handle ?? landed!.handle;
const startFraction = fractionOf(handle ? values[handle] : landed!.value);
// Handles one step apart overlap, so the first move picks which one is pulled out of the stack.
const stacked = !!handle && !single && high - low <= step;
grip.current = { x: event.clientX, shift: startFraction - fractionAt(event.clientX, box), handle: held, stacked, box };
setLastHeld(held);
setDrag({ handle: held, fraction: startFraction, moving: false });
(root.current?.querySelector(`input[data-for="${held}"]`) as HTMLInputElement | null)?.focus({ preventScroll: true });
};
const follow = (event: PointerEvent<HTMLDivElement>) => {
const g = grip.current;
if (!g || !drag) return;
if (!drag.moving && Math.abs(event.clientX - g.x) < DRAG_FROM) return;
if (g.stacked) {
const pulled: Handle = event.clientX < g.x !== isRtl(root.current) ? "low" : "high";
g.stacked = false;
if (pulled !== g.handle) {
g.shift += fractionOf(values[pulled]) - fractionOf(values[g.handle]);
g.handle = pulled;
setLastHeld(pulled);
(root.current?.querySelector(`input[data-for="${pulled}"]`) as HTMLInputElement | null)?.focus({ preventScroll: true });
}
}
const [floor, ceiling] =
g.handle === "low" ? [0, fractionOf(high) - stepFraction] : [fractionOf(low) + stepFraction, 1];
const fraction = clamp(fractionAt(event.clientX, g.box) + g.shift, floor, ceiling);
setDrag({ handle: g.handle, fraction, moving: true });
moveTo(g.handle, min + fraction * span);
};
const release = () => {
grip.current = null;
setDrag(null);
};
const dragging = !!drag?.moving;
const tipHandle = drag?.handle ?? lastHeld;
// An open end is no limit, so it does not read as the end value.
const textOf = (handle: Handle) =>
handle === "high" && value[1] === null ? (openLabel ?? `${format(max, "high")}+`) : format(values[handle], handle);
const tipText = textOf(tipHandle);
useLayoutEffect(() => {
if (tip.current) setTipHalf(tip.current.offsetWidth / 2);
}, [tipText]);
const tallest = Math.max(1, ...(buckets ?? []));
// While a handle is dragged, the bars it passes rise a little, in a soft wave centred on the handle.
const wave = dragging && drag ? drag.fraction : pulled ? pulled.fraction : null;
const bumpAt = wave !== null && buckets?.length ? wave * buckets.length - 0.5 : null;
const bumpOf = (i: number) => {
if (bumpAt === null) return 0;
const near = Math.max(0, 1 - Math.abs(i - bumpAt) / 2.4);
return near * near;
};
// The rise is a few fixed pixels plus a small share of the bar, so a short bar shows it as clearly as a tall one.
// It grows the height rather than scaling the bar, and stops at the top of the bar area: a card around the chart
// clips anything above it, which would cut the rounded top flat.
const heightOf = (share: number, bump: number) =>
bump ? `min(100%, calc(${share}% + ${bump} * var(--lift, 1) * (5px + ${0.13 * share}%)))` : `${share}%`;
const lowShown = single ? 0 : shown.low;
const handles: Handle[] = single ? ["high"] : ["low", "high"];
const columns = buckets?.length || PLACEHOLDER_BARS;
return (
<div
ref={root}
data-dragging={dragging || !!pulled || undefined}
data-disabled={disabled || undefined}
className={cn(
"group/range relative cursor-pointer touch-pan-y select-none [-webkit-tap-highlight-color:transparent]",
"data-[dragging]:cursor-grabbing data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className,
)}
onPointerDown={press}
onPointerMove={follow}
onPointerUp={release}
onPointerCancel={release}
onLostPointerCapture={release}
onClick={(event) => {
if (!pressed.current && !disabled) land(event.clientX, !!(event.target as HTMLElement).closest("[data-bars]"));
pressed.current = false;
}}
{...props}
>
{buckets && buckets.length === 0 && !loading && (
<EmptyNote className="mx-[10px] h-14 justify-center">{emptyText}</EmptyNote>
)}
{buckets && (buckets.length > 0 || loading) && (
<div
data-bars
aria-hidden
className="mx-[10px] flex h-14 items-end gap-[2px] motion-reduce:[--lift:0]"
// Many bars close their gaps up, a 2px gap at most and a quarter of a bar's slot at least, so bars never vanish.
style={columns > 40 ? { gap: `min(2px, calc(100% / ${columns * 4}))` } : undefined}
>
{loading
? Array.from({ length: columns }, (_, i) => (
<span
key={i}
className={cn(
"min-w-0 flex-1 rounded-t-[3px]",
SKELETON_FILL,
"transition-[height,background-color] duration-[420ms,200ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
)}
style={{ height: `${hillAt(i, columns)}%` }}
/>
))
: buckets.map((count, i) => {
const start = i / buckets.length;
const end = (i + 1) / buckets.length;
const cover = clamp((Math.min(end, shown.high) - Math.max(start, lowShown)) / (end - start), 0, 1);
const lit = cover > 0 ? Math.round((0.35 + 0.65 * cover) * 100) : 0;
const narrow = barScale !== 1;
const bar = (
<span
key={i}
className={cn(
"min-w-0 rounded-t-[3px]",
narrow ? "flex-none" : "flex-1",
"transition-[height,background-color] duration-[420ms,200ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
// While dragging, the wave follows the handle exactly; it eases back when the handle is let go.
"group-data-[dragging]/range:transition-none",
// Forced colours would drop the inline fill, and the chart with it.
"forced-colors:[forced-color-adjust:none]",
)}
style={{
height: heightOf(Math.max(count ? 8 : 3, (count / tallest) * 100), bumpOf(i)),
backgroundColor: `color-mix(in srgb, var(--fu-accent-soft,#8FAAFF) ${lit}%, var(--fu-bar-out,#4A4A4A))`,
// The bar a denser chart would draw: its slot plus one 2px gap, scaled, less the gap.
width: narrow ? `calc((100% + 2px) * ${barScale} - 2px)` : undefined,
} as CSSProperties}
/>
);
return narrow ? (
<span key={i} className="flex h-full min-w-0 flex-1 items-end justify-center">
{bar}
</span>
) : (
bar
);
})}
</div>
)}
<div className="relative h-6">
<span
aria-hidden
className={cn(
"absolute inset-x-0 top-[10px] h-1 rounded-[2px] transition-[background-color] duration-200 motion-reduce:transition-none",
loading ? SKELETON_FILL : "bg-[var(--fu-rail,#4A4A4A)] forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]",
)}
/>
<span
aria-hidden
className={cn(
"absolute top-[10px] h-1 rounded-[2px] bg-[var(--fu-accent-soft,#8FAAFF)] forced-colors:bg-[Highlight] forced-colors:[forced-color-adjust:none]",
// While loading the fill and handles are hidden; they fade in with the data.
loading && "opacity-0",
"transition-[left,right,opacity] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"group-data-[dragging]/range:transition-none",
)}
style={{ insetInlineStart: single ? 0 : along(lowShown), insetInlineEnd: along(1 - shown.high) }}
/>
{handles.map((handle) => {
const grabbed = (drag ?? pulled)?.handle === handle;
const label = labels?.[handle] ?? (handle === "low" ? "Minimum" : "Maximum");
return (
<span key={handle} className="contents">
<input
type="range"
data-for={handle}
aria-label={label}
aria-valuetext={
handle === "high" && value[1] === null ? "No maximum" : handle === "low" && value[0] === null ? "No minimum" : format(values[handle], handle)
}
min={single ? min + step : min}
max={max}
step={step}
value={values[handle]}
disabled={disabled}
onChange={(event) => moveTo(handle, Number(event.target.value))}
// Left and Right follow the screen in RTL too, the same in every browser.
onKeyDown={(event) => {
const key = readingKey(event.key, event.currentTarget);
if (key === event.key) return;
event.preventDefault();
moveTo(handle, values[handle] + (key === "ArrowRight" ? step : -step));
}}
className="peer pointer-events-none absolute inset-0 m-0 h-full w-full opacity-0"
/>
<span
data-handle={handle}
data-grabbed={grabbed || undefined}
className={cn(
loading && "opacity-0",
"absolute top-[2px] -ms-[10px] size-5 cursor-grab touch-none rounded-full bg-[var(--fu-handle,#F8F5F1)]",
"shadow-[0_0_0_0_color-mix(in_srgb,var(--fu-accent-soft,#8FAAFF)_28%,transparent),0_0_0_1px_var(--fu-handle-edge,rgb(0_0_0/0.25)),0_2px_6px_var(--fu-shadow,rgb(0_0_0/0.5))]",
"transition-[left,scale,box-shadow,opacity] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"before:absolute before:-inset-[10px] before:rounded-full before:content-['']",
"hover:scale-[1.15]",
"peer-focus-visible:z-[1] data-[grabbed]:z-[1] data-[grabbed]:scale-[1.15] data-[grabbed]:cursor-grabbing",
"data-[grabbed]:shadow-[0_0_0_6px_color-mix(in_srgb,var(--fu-accent-soft,#8FAAFF)_28%,transparent),0_0_0_1px_var(--fu-handle-edge,rgb(0_0_0/0.25)),0_2px_6px_var(--fu-shadow,rgb(0_0_0/0.5))]",
"group-data-[dragging]/range:data-[grabbed]:transition-[scale,box-shadow]",
"peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-solid peer-focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"forced-colors:bg-[CanvasText] forced-colors:[forced-color-adjust:none] forced-colors:peer-focus-visible:outline-[Highlight]",
)}
style={{ insetInlineStart: along(shown[handle]) }}
/>
</span>
);
})}
</div>
<span
ref={tip}
aria-hidden
data-state={dragging ? "open" : "closed"}
className={cn(
"pointer-events-none absolute bottom-10 z-[2] -translate-x-1/2 rtl:translate-x-1/2 rounded-[8px] px-2 py-1 whitespace-nowrap",
"bg-[var(--fu-text,#F8F5F1)] text-[13px] leading-[18px] font-medium text-[var(--fu-surface-1,#171717)] tabular-nums",
"transition-[opacity,translate] duration-150 ease-in-out motion-reduce:transition-none",
"data-[state=closed]:translate-y-1 data-[state=closed]:opacity-0",
)}
style={
{
insetInlineStart: `clamp(${tipHalf}px, ${along(shown[tipHandle])}, calc(100% - ${tipHalf}px))`,
} as CSSProperties
}
>
{tipText}
</span>
</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/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/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/select.tsx
```tsx
"use client";
import { useId, useLayoutEffect, useRef, useState, type ButtonHTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { ChevronDownIcon } from "./icons";
import { typesCharacter, keepRowInView, LIST_PANEL, ListCheck, ListCount, PopoverPanel, RowHighlight, useTypeAhead } from "./popover";
import { ARRIVING, SkeletonText, useLoading } from "./skeleton";
import { StatusFrame, type StateProps } from "./status-frame";
import { TextSwap } from "./text-swap";
export type SelectOption = {
value: string;
label: string;
disabled?: boolean;
/** How many items this choice gives. Shown as a short bar and a number; an option at 0 is dimmed and cannot be picked. */
count?: number;
};
export type SelectProps = Omit<
ButtonHTMLAttributes<HTMLButtonElement>,
"value" | "onChange" | "prefix" | "children" | "defaultValue" | "name" | "role"
> &
StateProps & {
value: string;
onChange: (value: string) => void;
options: readonly SelectOption[];
/** Accessible name of the field and its list. Include the visible prefix in it ("From year" for "From"). */
label: string;
/** Muted text before the chosen value, e.g. "From". */
prefix?: ReactNode;
/** Shown, muted, while no option matches value. Default: the label of the option whose value is "". */
placeholder?: string;
/** Sends the value with a form under this name. */
name?: string;
/** A line at the top of the list, e.g. "Toyota models". Not read out: the label names the list. */
heading?: ReactNode;
/** Shown in the open list when there are no options, and muted in the field when there is no placeholder. Default "No choices". */
emptyText?: string;
/** Text of each count. Default 1,234. */
formatCount?: (n: number) => string;
/** Screen-reader words for a count, read after the option's name. Default "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** A quieter field (--fu-line border, dim text) while it waits on another choice, such as Model before a make. It still opens. */
waiting?: boolean;
/** Classes for the outer wrapper, e.g. its width. */
className?: string;
/** Draws the list open in place, for a still picture. Nothing responds. */
still?: boolean;
};
const PAGE = 10;
/**
* The value in the field. Inside a loading StatusFrame, its own or a filter's, a bar stands in for it; when the data
* arrives it fades in once. A component of its own, so it reads the frame Select draws around itself.
*/
function Value({ text, empty, waiting }: { text: string; empty: boolean; waiting: boolean }) {
const { loading, arriving } = useLoading();
if (loading) {
return (
<span className="min-w-0 flex-1 truncate tabular-nums">
<SkeletonText>{text}</SkeletonText>
</span>
);
}
return (
<TextSwap
data-empty={empty || undefined}
className={cn(
"min-w-0 flex-1 grid-cols-[minmax(0,1fr)] tabular-nums transition-[color] duration-[480ms] [&>span]:truncate",
waiting ? "text-[var(--fu-dim,#929292)]" : "data-[empty]:text-[var(--fu-mute,#BDBDBD)]",
arriving && ARRIVING,
)}
>
{text}
</TextSwap>
);
}
/**
* A select drawn like TextField (44px, 12px radius, --fu-field-border border, 15px text, a chevron) whose list grows out of the
* field in a panel of its own instead of the system menu. One highlight marks the active row; the chosen row is
* tinted with a check that draws in; options with counts show a bar for their share that grows in the first time the list opens.
* Focus stays on the field: arrows, Home, End, Page Up and Page Down move, typing finds an option by its first letters,
* Enter or Space picks, Escape closes. The option whose value is "" is the empty choice and shows muted, like a placeholder.
* Inside a loading StatusFrame the field keeps its box and a bar stands in for the value, which fades in once when it arrives.
*/
export function Select({
value,
onChange,
options,
label,
prefix,
placeholder,
name,
heading,
emptyText = "No choices",
status,
onRetry,
errorText = "Couldn't load the choices.",
formatCount,
countLabel: countLabelProp,
locale,
waiting = false,
className,
disabled,
still = false,
onKeyDown,
onClick,
...props
}: SelectProps) {
const id = useId();
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const labelId = `${id}-label`;
const listId = `${id}-list`;
const optionId = (v: string) => `${id}-option-${encodeURIComponent(v).replaceAll("%", "_")}`;
const trigger = useRef<HTMLButtonElement>(null);
const list = useRef<HTMLDivElement>(null);
const [isOpen, setOpen] = useState(false);
const open = still || isOpen;
const [active, setActive] = useState<string | null>(null);
// Tab picks the active option only when the keys put it there; a row under a resting pointer never commits.
const keyed = useRef(false);
// Enter and Space are handled on keydown; the click the browser then fires for the button is skipped.
const skipClick = useRef(false);
const typeAhead = useTypeAhead();
// Loading, from its own status or a StatusFrame around it, the field keeps its box and does not open.
const framed = useLoading();
if (isOpen && (status === "loading" || framed.loading)) setOpen(false);
const chosen = options.find((option) => option.value === value);
const empty = !chosen || value === "";
const shown = chosen?.label ?? placeholder ?? options.find((option) => option.value === "")?.label ?? (options.length ? "" : emptyText);
// An option at 0 cannot be picked, unless it is the current choice.
const usable = (option: SelectOption) => !option.disabled && (option.count !== 0 || option.value === value);
const enabled = options.filter(usable);
const counted = options.some((option) => option.count !== undefined);
// Bars are shares of the largest real choice; the empty choice ("Any") shows its count with no bar.
const most = Math.max(0, ...options.map((option) => (option.value === "" ? 0 : (option.count ?? 0))));
const indexOf = (v: string | null) => enabled.findIndex((option) => option.value === v);
const start = chosen && usable(chosen) ? chosen.value : (enabled[0]?.value ?? null);
const current = still ? (active ?? start) : active;
const reveal = (v: string) => {
const row = document.getElementById(optionId(v));
if (list.current && row) keepRowInView(list.current, row);
};
const moveTo = (index: number) => {
const option = enabled[Math.max(0, Math.min(enabled.length - 1, index))];
if (!option) return;
keyed.current = true;
setActive(option.value);
reveal(option.value);
};
const openAt = (v: string | null) => {
keyed.current = false;
setActive(v);
setOpen(true);
};
const choose = (v: string | null) => {
setOpen(false);
if (v !== null && v !== value) onChange(v);
};
// On open the list scrolls to the whole row nearest to putting the chosen option mid-panel, never past the end, so the
// top row is never cut. scrollTop, not scrollIntoView, so the page never scrolls.
useLayoutEffect(() => {
const box = list.current;
const target = open && current !== null ? document.getElementById(optionId(current)) : null;
if (!box || !target) return;
const rows = [...box.querySelectorAll<HTMLElement>("[role=option]")];
const inset = rows[0].offsetTop;
const end = box.scrollHeight - box.clientHeight;
const ideal = target.offsetTop + target.offsetHeight / 2 - box.clientHeight / 2;
let top = 0;
for (const row of rows) {
const at = row.offsetTop - inset;
if (at <= end && Math.abs(at - ideal) < Math.abs(top - ideal)) top = at;
}
box.scrollTop = top;
}, [open]);
const find = (char: string, from: string | null) => {
const at = typeAhead.find(char, enabled, indexOf(from));
if (isOpen) {
if (at >= 0) moveTo(at);
return;
}
openAt(at >= 0 ? enabled[at].value : from);
keyed.current = at >= 0;
};
const handleKey = (event: KeyboardEvent<HTMLButtonElement>) => {
if (event.nativeEvent.isComposing) return;
const { key } = event;
if (!isOpen) {
if (key === "ArrowDown" || key === "ArrowUp" || key === "Enter" || key === " ") {
event.preventDefault();
if (key === "Enter" || key === " ") skipClick.current = true;
openAt(start);
} else if (key === "Home" || key === "End") {
event.preventDefault();
openAt(enabled[key === "Home" ? 0 : enabled.length - 1]?.value ?? null);
keyed.current = true;
} else if (typesCharacter(event)) {
event.preventDefault();
find(key, start);
}
return;
}
const at = indexOf(active);
if (key === "ArrowDown" && !event.altKey) {
event.preventDefault();
moveTo(at < 0 ? 0 : at + 1);
} else if (key === "ArrowUp" && !event.altKey) {
event.preventDefault();
moveTo(at < 0 ? enabled.length - 1 : at - 1);
} else if (key === "Home" || key === "End") {
event.preventDefault();
moveTo(key === "Home" ? 0 : enabled.length - 1);
} else if (key === "PageDown" || key === "PageUp") {
event.preventDefault();
moveTo((at < 0 ? 0 : at) + (key === "PageDown" ? PAGE : -PAGE));
} else if (key === " " && typeAhead.running()) {
event.preventDefault();
find(key, active);
} else if (key === "Enter" || key === " " || (key === "ArrowUp" && event.altKey)) {
event.preventDefault();
skipClick.current = key !== "ArrowUp";
choose(active);
} else if (key === "ArrowDown" && event.altKey) {
event.preventDefault();
} else if (key === "Tab") {
choose(keyed.current ? active : null);
} else if (typesCharacter(event)) {
event.preventDefault();
find(key, active);
}
};
// With a status, the StatusFrame below dims the field and turns it off; without one, the field dims itself.
const field = (
<div className={cn("relative min-w-0", disabled && status === undefined && "pointer-events-none opacity-50", status === undefined && className)}>
<span id={labelId} hidden>
{label}
</span>
<button
ref={trigger}
type="button"
role="combobox"
aria-labelledby={labelId}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-activedescendant={open && current !== null ? optionId(current) : undefined}
data-waiting={waiting || undefined}
disabled={disabled}
tabIndex={still ? -1 : undefined}
onKeyDown={(event) => {
onKeyDown?.(event);
if (!event.defaultPrevented) handleKey(event);
}}
onKeyUp={() => {
setTimeout(() => {
skipClick.current = false;
});
}}
onClick={(event) => {
onClick?.(event);
if (skipClick.current) {
skipClick.current = false;
return;
}
if (isOpen) setOpen(false);
else openAt(start);
}}
className={cn(
"relative flex h-11 w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-[12px] border border-[var(--fu-field-border,#737373)] bg-[var(--fu-input,rgb(0_0_0/0))] pe-9 ps-3 text-start",
"font-[inherit] text-[15px] leading-5 text-[var(--fu-text,#F8F5F1)] outline-none [-webkit-tap-highlight-color:transparent]",
"transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none disabled:cursor-default",
"hover:border-[var(--fu-control-hover,#A3A3A3)] data-[waiting]:not-focus-visible:not-aria-expanded:border-[var(--fu-line,#404040)] data-[waiting]:not-focus-visible:not-aria-expanded:hover:border-[var(--fu-control-border,#737373)]",
"focus-visible:border-[var(--fu-accent-soft,#8FAAFF)] focus-visible:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)] focus-visible:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
"aria-expanded:border-[var(--fu-accent-soft,#8FAAFF)] aria-expanded:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)] aria-expanded:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
)}
{...props}
>
{prefix != null && (
<span aria-hidden="true" className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">
{prefix}
</span>
)}
<Value text={shown} empty={empty} waiting={waiting} />
<ChevronDownIcon
size={16}
className={cn(
"pointer-events-none absolute top-1/2 inset-e-3 -translate-y-1/2 text-[var(--fu-mute,#BDBDBD)]",
"transition-[rotate,color] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
open && "rotate-180 text-[var(--fu-accent-soft,#8FAAFF)]",
)}
/>
</button>
{name !== undefined && <input type="hidden" name={name} value={value} />}
<PopoverPanel
ref={list}
id={listId}
role="listbox"
aria-labelledby={labelId}
open={open}
still={still}
anchor={trigger}
onClose={() => setOpen(false)}
matchWidth
// Presses inside keep focus on the field, which carries the keys.
onPointerDown={(event) => event.preventDefault()}
className={LIST_PANEL}
>
<RowHighlight activeId={open && current !== null ? optionId(current) : null} open={open} />
{heading != null && (
<div aria-hidden="true" className="px-2.5 pt-1.5 pb-2 text-[12px] leading-4 font-medium text-[var(--fu-dim,#929292)]">
{heading}
</div>
)}
{options.length === 0 && (
// An option that cannot be picked, so the list still holds one and a screen reader says why it is empty.
<div role="option" aria-disabled="true" aria-selected={false} className="flex min-h-10 items-center px-2.5 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{emptyText}
</div>
)}
{options.map((option, order) => {
const selected = option.value === value;
const off = !usable(option);
return (
<div
key={option.value}
id={optionId(option.value)}
role="option"
aria-selected={selected}
aria-disabled={off || undefined}
aria-label={option.count === undefined ? undefined : `${option.label}, ${countLabel(option.count)}`}
data-active={option.value === current || undefined}
onPointerMove={() => {
if (off || option.value === active) return;
keyed.current = false;
setActive(option.value);
}}
onClick={() => {
if (!off) choose(option.value);
}}
className={cn(
"group/row relative flex min-h-10 cursor-pointer items-center gap-3 rounded-[9px] py-2 pe-2 ps-2.5 text-[14px] leading-5 tabular-nums select-none pointer-coarse:min-h-11",
"transition-[background-color,color] duration-200 motion-reduce:transition-none",
selected
? "bg-[var(--fu-selected,#1F2747)] font-medium text-[var(--fu-accent-pale,#D1DDFF)]"
: option.value === "" && "text-[var(--fu-mute,#BDBDBD)]",
off && "cursor-default opacity-40",
"forced-colors:data-[active]:bg-[Highlight] forced-colors:data-[active]:text-[HighlightText]",
)}
>
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{option.label}</span>{" "}
{counted && <ListCount count={option.count ?? 0} max={most} order={order} on={selected} bar={option.value !== ""} format={formatCount} locale={locale} />}
<ListCheck on={selected} />
</div>
);
})}
</PopoverPanel>
</div>
);
// Given a status, it carries its own states: loading as above, an error line with Retry in the field's place, and
// disabled, so focus on the field moves to the frame when it turns off. Inside a filter that has its own StatusFrame,
// leave status out and it follows that frame.
if (status === undefined) return field;
return (
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled} className={cn("flex min-h-11 flex-col justify-center", className)}>
{field}
</StatusFrame>
);
}
```
### 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/popover.tsx
```tsx
"use client";
import { useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type Ref, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { CheckIcon } from "./icons";
export type PopoverCloseReason = "escape" | "outside" | "blur" | "away";
export type PopoverPanelProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
ref?: Ref<HTMLDivElement>;
open: boolean;
/** The trigger the panel opens against. */
anchor: RefObject<HTMLElement | null>;
/**
* Asks the owner to close: "escape", "outside" (a press outside the trigger and the panel), "blur" (focus moved
* outside both) or "away" (the trigger scrolled out of view). The owner sets open to false and moves focus if needed.
*/
onClose: (reason: PopoverCloseReason) => void;
/** Lines up the start edges, or the end edges with "end": the left edges in left-to-right, the right ones in RTL. Default "start". */
align?: "start" | "end";
/** At least as wide as the trigger. */
matchWidth?: boolean;
/** Widest the panel grows, in px; never wider than the screen less its margins. Default 320. */
maxWidth?: number;
/** Tallest the panel grows before it scrolls, in px; also capped by the room on its side. Default 320. */
maxHeight?: number;
/** Draws the panel open in place under the trigger, for a still picture. Nothing moves or listens. The owner needs position: relative. */
still?: boolean;
children: ReactNode;
};
const GAP = 6;
const EDGE_Y = 8;
const MIN_HEIGHT = 160;
const edgeX = (width: number) => (width < 640 ? 16 : 8);
/** Open panels, newest last: Escape closes only the newest. */
const layers: symbol[] = [];
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
// Browsers without popover support (before Chrome 114, Safari 17, Firefox 125) get a fixed panel in place instead.
function show(node: HTMLElement) {
if (typeof node.showPopover !== "function") {
node.style.display = "block";
return;
}
try {
if (!node.matches(":popover-open")) node.showPopover();
} catch {}
}
function hide(node: HTMLElement) {
if (typeof node.hidePopover !== "function") {
node.style.display = "none";
return;
}
try {
node.hidePopover();
} catch {}
}
/** The surface of a menu or list panel: 14px radius, the card colour, a --fu-line hairline, 6px inside, a deep soft shadow. */
export const LIST_PANEL =
"w-max rounded-[14px] border border-[var(--fu-line,#404040)] bg-[var(--fu-card,#1F1F1F)] p-1.5 shadow-[inset_0_1px_0_var(--fu-rim,rgb(255_255_255/0.04)),0_24px_48px_-12px_var(--fu-shadow-deep,rgb(0_0_0/0.8)),0_10px_20px_-8px_var(--fu-shadow,rgb(0_0_0/0.5))]";
/**
* A floating panel for menus and lists. It stays where it is in the DOM, so it inherits fonts and --fu-* variables and
* Tab reaches it right after its trigger, and opens on the browser's top layer (popover="manual"), so no overflow,
* transform or z-index around the trigger can clip or bury it. It opens below the trigger, or above when only that fits,
* keeps 8px from the screen edges (16px at the sides on phones) and follows the trigger while the page scrolls.
* It grows out of the trigger over 480ms (scale 0.98 to 1 from the trigger's side, through a 6px blur) and leaves
* over 160ms; it is inert while it leaves. Children can follow it through group/popover's data-state: closed, open,
* closing.
*/
export function PopoverPanel({
ref,
open,
anchor,
onClose,
align = "start",
matchWidth = false,
maxWidth = 320,
maxHeight = 320,
still = false,
className,
style,
children,
...props
}: PopoverPanelProps) {
const panel = useRef<HTMLDivElement | null>(null);
const [phase, setPhase] = useState<"hidden" | "open" | "closing">("hidden");
// Counts grow in only the first time the panel opens; after that they are already in place.
const [seen, setSeen] = useState(false);
// Which edges have rows scrolled out of view, so a soft fade there says the list goes on.
const [more, setMore] = useState({ top: false, bottom: false });
const side = useRef<"bottom" | "top">("bottom");
const close = useRef(onClose);
useLayoutEffect(() => {
close.current = onClose;
});
const setRef = (node: HTMLDivElement | null) => {
panel.current = node;
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
};
// Measures the trigger without its press scale (offset sizes around the rect's centre), then picks a side and a spot.
const place = (first: boolean) => {
const node = panel.current;
const trigger = anchor.current;
if (!node || !trigger) return;
const vw = document.documentElement.clientWidth;
const vh = document.documentElement.clientHeight;
const rect = trigger.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
const left = cx - trigger.offsetWidth / 2;
const right = cx + trigger.offsetWidth / 2;
const top = cy - trigger.offsetHeight / 2;
const bottom = cy + trigger.offsetHeight / 2;
if (!first && (bottom < 0 || top > vh || right < 0 || left > vw)) {
close.current("away");
return;
}
const mx = edgeX(vw);
const widest = Math.min(maxWidth, vw - 2 * mx);
node.style.maxWidth = `${widest}px`;
if (matchWidth) node.style.minWidth = `${Math.min(trigger.offsetWidth, widest)}px`;
node.style.maxHeight = `${maxHeight}px`;
const natural = node.offsetHeight;
const below = vh - EDGE_Y - bottom - GAP;
const above = top - GAP - EDGE_Y;
const roomOf = (s: "bottom" | "top") => (s === "bottom" ? below : above);
let next: "bottom" | "top";
if (!first && natural <= roomOf(side.current)) next = side.current;
else if (natural <= below) next = "bottom";
else if (natural <= above) next = "top";
else next = below >= above ? "bottom" : "top";
side.current = next;
node.style.maxHeight = `${Math.min(maxHeight, Math.max(MIN_HEIGHT, roomOf(next)))}px`;
const width = node.offsetWidth;
const height = node.offsetHeight;
const toRight = (align === "end") !== isRtl(trigger);
const x = Math.min(Math.max(mx, toRight ? right - width : left), vw - mx - width);
const y = next === "bottom" ? bottom + GAP : top - GAP - height;
node.style.left = `${Math.round(x)}px`;
node.style.top = `${Math.round(y)}px`;
node.style.transformOrigin = `${Math.round(cx - x)}px ${next === "bottom" ? "0" : "100%"}`;
node.dataset.side = next;
};
useLayoutEffect(() => {
const node = panel.current;
if (still || !node) return;
if (open) {
if (phase === "hidden") {
// Shown and placed in its closed look with no transition, then opened, so it enters from the trigger's side.
node.style.transition = "none";
show(node);
place(true);
void getComputedStyle(node).opacity;
node.style.transition = "";
}
setPhase("open");
setSeen(true);
} else if (phase === "open") {
setPhase(reducedMotion() ? "hidden" : "closing");
}
// place reads the latest props; phase is read as committed.
}, [open, still]);
useLayoutEffect(() => {
if (phase === "hidden" && !still && panel.current) hide(panel.current);
}, [phase, still]);
useEffect(() => {
const node = panel.current;
if (!node || (!still && phase !== "open")) return;
const measure = () => {
const top = node.scrollTop > 1;
const bottom = node.scrollTop + node.clientHeight < node.scrollHeight - 1;
setMore((now) => (now.top === top && now.bottom === bottom ? now : { top, bottom }));
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
node.addEventListener("scroll", measure, { passive: true });
return () => {
observer.disconnect();
node.removeEventListener("scroll", measure);
};
}, [phase, still]);
useEffect(() => {
const node = panel.current;
if (phase !== "closing" || !node) return;
const done = () => setPhase((now) => (now === "closing" ? "hidden" : now));
const timer = setTimeout(done, 190);
const onEnd = (event: TransitionEvent) => {
if (event.target === node && event.propertyName === "opacity") done();
};
node.addEventListener("transitionend", onEnd);
return () => {
clearTimeout(timer);
node.removeEventListener("transitionend", onEnd);
};
}, [phase]);
useEffect(() => {
const node = panel.current;
const trigger = anchor.current;
if (still || phase !== "open" || !node || !trigger) return;
const token = Symbol("layer");
layers.push(token);
let frame = 0;
const follow = (event?: Event) => {
if (event?.type === "scroll" && event.target instanceof Node && node.contains(event.target)) return;
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => place(false));
};
const observer = new ResizeObserver(() => follow());
observer.observe(trigger);
observer.observe(node);
window.addEventListener("scroll", follow, { capture: true, passive: true });
window.addEventListener("resize", follow);
window.visualViewport?.addEventListener("resize", follow);
const inside = (target: EventTarget | null) => target instanceof Node && (node.contains(target) || trigger.contains(target));
// A mouse closes on press; a finger or pen on a tap that did not move, so starting a scroll keeps the panel open.
// The press is never cancelled, so one click on another control both closes this and works there.
let touch: { id: number; x: number; y: number } | null = null;
const onDown = (event: PointerEvent) => {
if (inside(event.target)) return;
if (event.pointerType === "mouse") close.current("outside");
else touch = { id: event.pointerId, x: event.clientX, y: event.clientY };
};
const onUp = (event: PointerEvent) => {
if (touch && touch.id === event.pointerId && Math.hypot(event.clientX - touch.x, event.clientY - touch.y) < 10) close.current("outside");
touch = null;
};
const onCancel = () => {
touch = null;
};
const onKey = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.isComposing || layers.at(-1) !== token) return;
event.stopPropagation();
event.preventDefault();
close.current("escape");
};
const onFocusOut = (event: FocusEvent) => {
if (event.relatedTarget && !inside(event.relatedTarget)) close.current("blur");
};
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("pointerup", onUp, true);
document.addEventListener("pointercancel", onCancel, true);
window.addEventListener("keydown", onKey, true);
node.addEventListener("focusout", onFocusOut);
trigger.addEventListener("focusout", onFocusOut);
return () => {
layers.splice(layers.indexOf(token), 1);
cancelAnimationFrame(frame);
observer.disconnect();
window.removeEventListener("scroll", follow, { capture: true });
window.removeEventListener("resize", follow);
window.visualViewport?.removeEventListener("resize", follow);
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("pointerup", onUp, true);
document.removeEventListener("pointercancel", onCancel, true);
window.removeEventListener("keydown", onKey, true);
node.removeEventListener("focusout", onFocusOut);
trigger.removeEventListener("focusout", onFocusOut);
};
// place and the trigger are read live.
}, [phase, still]);
const state = still ? (open ? "open" : "closed") : phase === "hidden" ? "closed" : phase;
return (
<div
ref={setRef}
popover={still ? undefined : "manual"}
data-state={state}
data-unseen={!seen && !still && state === "closed" ? "" : undefined}
// Not while it is opening again before it finished leaving, so focus can move in.
inert={state === "closing" && !open}
style={still ? { maxWidth, maxHeight, ...style } : style}
className={cn(
// The browser's own popover look is reset: no inset, margin or padding, and these colours, not Canvas.
"group/popover m-0 box-border overflow-x-hidden overflow-y-auto overscroll-contain text-[var(--fu-text,#F8F5F1)] [-webkit-tap-highlight-color:transparent]",
SCROLL,
still
? cn("absolute top-full z-10 mt-1.5", align === "end" ? "inset-e-0" : "inset-s-0", matchWidth && "min-w-full", !open && "hidden")
: "fixed inset-auto z-50",
"transition-[opacity,translate,scale,filter] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"data-[state=open]:duration-[480ms] data-[state=closing]:duration-[160ms]",
"data-[state=closed]:pointer-events-none data-[state=closed]:scale-[0.98] data-[state=closed]:opacity-0 data-[state=closed]:blur-[6px]",
"data-[state=closing]:pointer-events-none data-[state=closing]:scale-[0.98] data-[state=closing]:opacity-0 data-[state=closing]:blur-[2px]",
"data-[side=bottom]:data-[state=closed]:-translate-y-1 data-[side=top]:data-[state=closed]:translate-y-1",
className,
)}
{...props}
>
<span aria-hidden="true" className={cn(FADE, "-top-1.5 -mt-1.5 mb-[-26px] bg-linear-to-b", more.top && "opacity-100")} />
{children}
<span aria-hidden="true" className={cn(FADE, "-bottom-1.5 mt-[-26px] -mb-1.5 bg-linear-to-t", more.bottom && "opacity-100")} />
</div>
);
}
// Pinned to the panel edge as it scrolls, over the rows and the highlight; it takes no room in the list. Sized for LIST_PANEL.
const FADE =
"pointer-events-none sticky z-[2] -mx-1.5 block h-8 from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-150 motion-reduce:transition-none forced-colors:hidden";
/** Scrolls a list panel just enough that `row` shows whole, with the panel's 4px inset around it. */
export function keepRowInView(panel: HTMLElement, row: HTMLElement) {
const top = row.offsetTop - 4;
const bottom = row.offsetTop + row.offsetHeight + 4;
if (top < panel.scrollTop) panel.scrollTop = top;
else if (bottom > panel.scrollTop + panel.clientHeight) panel.scrollTop = bottom - panel.clientHeight;
}
type Mark = { top: number; height: number; shown: boolean };
/**
* The one fill that marks a list's active row, moving straight to it. It lies over the rows, a
* light veil, so it shows on the chosen row's tint too. It fades in where it lands when the list opens, and stays put
* while the list fades out. Place it first inside the panel.
*/
export function RowHighlight({ activeId, open, pressed = false }: { activeId: string | null; open: boolean; pressed?: boolean }) {
const [mark, setMark] = useState<Mark | null>(null);
const [, remeasure] = useState(0);
const tries = useRef(0);
useLayoutEffect(() => {
if (!open) {
tries.current = 0;
return;
}
const node = activeId ? document.getElementById(activeId) : null;
// The panel may still be hidden on this pass (it is shown after its children's effects); measure again next frame,
// a few times at most, in case something else keeps it hidden.
if (node && !node.getClientRects().length) {
if (tries.current >= 3) return;
tries.current += 1;
const frame = requestAnimationFrame(() => remeasure((n) => n + 1));
return () => cancelAnimationFrame(frame);
}
tries.current = 0;
const next: Mark | null = node
? { top: node.offsetTop, height: node.offsetHeight, shown: true }
: mark && { ...mark, shown: false };
if (next?.top !== mark?.top || next?.height !== mark?.height || next?.shown !== mark?.shown) setMark(next);
});
return (
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-1.5 top-0 z-[1] rounded-[9px] transition-[opacity,background-color] duration-150 motion-reduce:transition-none forced-colors:hidden",
"ease-[cubic-bezier(0.22,1,0.36,1)]",
pressed ? "bg-[var(--fu-row-press,rgb(255_255_255/0.12))]" : "bg-[var(--fu-row-active,rgb(255_255_255/0.07))]",
!mark?.shown && "opacity-0",
)}
style={mark ? { translate: `0 ${mark.top}px`, height: mark.height } : undefined}
/>
);
}
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
/**
* The check on a chosen row. It draws itself in, from the short leg up, 140ms after its panel first opens; after that
* it is already in place. Takes its 16px place even when off, so rows line up.
*/
export function ListCheck({ on }: { on: boolean }) {
return (
<CheckIcon
size={16}
strokeWidth={2.5}
className={cn(
"shrink-0 text-[var(--fu-accent-soft,#8FAAFF)]",
on
? 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:0] [&_path]:transition-[stroke-dashoffset] [&_path]:delay-[140ms] [&_path]:duration-[420ms]",
"[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:[&_path]:transition-none",
"group-data-[unseen]/popover:[&_path]:[stroke-dashoffset:-23] group-data-[unseen]/popover:[&_path]:transition-none",
)
: "invisible",
)}
/>
);
}
/**
* A row's count as a short bar and a number. The bar is the count's share of `max`; bars grow in from the start edge as
* their panel first opens, one row after another (`order`), and ease to a new width when the count changes. With bar false
* only the number shows, in the same place, e.g. for "Any".
*/
export function ListCount({
count,
max,
order = 0,
on = false,
bar = true,
format,
locale,
}: {
count: number;
max: number;
order?: number;
on?: boolean;
bar?: boolean;
format?: (n: number) => string;
/** Formats the count when no format is given. */
locale?: string;
}) {
const share = max > 0 ? Math.min(1, count / max) : 0;
return (
<span aria-hidden="true" className="flex shrink-0 items-center gap-2.5">
<span className={cn("flex h-1 w-12 items-center rounded-full bg-[var(--fu-track,rgb(255_255_255/0.06))]", !bar && "invisible")}>
<span
className={cn(
"h-1 origin-left rtl:origin-right rounded-full transition-[scale,width,background-color] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[unseen]/popover:scale-x-0 group-data-[unseen]/popover:transition-none",
on
? "bg-[var(--fu-accent-soft,#8FAAFF)]"
: "bg-[var(--fu-rail,#4A4A4A)] group-data-[active]/row:bg-[var(--fu-control-border,#737373)]",
)}
// A count above 0 always shows a sliver, so only an empty option has no bar.
style={{ width: `${count > 0 ? Math.max(share * 100, 6) : 0}%`, transitionDelay: `${90 + Math.min(order, 10) * 22}ms, 0ms, 0ms` }}
/>
</span>
<span
className={cn(
"min-w-[3ch] text-end text-[13px] leading-5 tabular-nums transition-[color] duration-200",
on ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)] group-data-[active]/row:text-[var(--fu-mute,#BDBDBD)]",
)}
>
{(format ?? formatsFor(locale).number)(count)}
</span>
</span>
);
}
/**
* Finds a row by the letters typed in the last 500ms. One letter, or the same letter again and again, steps to the
* next row starting with it; a word keeps the current row while it still matches.
*/
export function useTypeAhead() {
const word = useRef("");
const lastKey = useRef(0);
const running = () => word.current !== "" && Date.now() - lastKey.current <= 500;
const find = <T extends { label: string }>(char: string, items: readonly T[], current: number): number => {
word.current = (running() ? word.current : "") + char.toLowerCase();
lastKey.current = Date.now();
const stepping = /^(.)\1*$/u.test(word.current);
const wanted = stepping ? [...word.current][0] : word.current;
// The rows in search order: from the next row (or the current one, for a word) round to the one before it.
const start = stepping ? current + 1 : Math.max(current, 0);
const order = items.map((_, index) => index);
const hit = [...order.slice(start), ...order.slice(0, start)].find((index) => items[index].label.toLowerCase().startsWith(wanted));
return hit ?? -1;
};
return { find, running };
}
/** True for a key press that types one character, not a shortcut. */
export const typesCharacter = (event: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }) =>
/^.$/u.test(event.key) && !(event.ctrlKey || event.metaKey || event.altKey);
```
### 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/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-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>
);
}
```
## What it does
- One bar per value; the handles sit between bars, so From and To may hold the same value.
- The pickers and the chart stay in step both ways.
- Picking From past To moves To along with it, and the other way round: the latest pick wins.
- The first and last values are open ends, so choosing them sets no limit.
- With buckets, each picker choice shows a short bar and the count picking it would give; a choice that gives none is dimmed.
## Props and value
RangeSelect (components/filters-ui/filters/range-select.tsx) holds this value: [V | null, V | null], where V is a number from options: [from, to], both inclusive. null is an open end.
- options: readonly number[] (required). The values to pick from, in ascending order, e.g. years. One bar each.
- value: [V | null, V | null] (required). [from, to], both inclusive. null is an open end.
- onChange: (value: [V | null, V | null]) => void (required). Called with the new range.
- buckets: readonly number[] (optional). Item count per option, in the order of options.
- format: (value: V) => string (default 2026). Picker, tooltip and screen-reader text for a value. The default prints the number with no group marks, in the locale's digits.
- pickerOrder: "ascending" | "descending" (default "ascending"). Order of the picker choices; "descending" puts the newest year first.
- anyLabel: string (default "Any"). The open-end choice in both pickers.
- prefixes: { low?: string; high?: string } (default From, To). Visible picker prefixes.
- labels: { low?: string; high?: string } (default the prefixes). Accessible names of the handles and pickers. Keep the prefix word in them.
- countLabel: (n: number) => string (default "6 results"). Screen-reader words for a count in the pickers, e.g. "6 cars".
- barScale: number (default 1). Bar width as a share of its slot.
- locale: string (default "en-US"). Formats values (with no group marks, so years read 2026) and counts by default, e.g. "ar-EG". 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 counts."). The error line, in plain words.
- 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 bars draw as pulsing columns and the rail pulses; the handles hide and each picker keeps its box and prefix with a placeholder bar for its value. 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 is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Zero results (every count is 0): The bars lie flat along the rail and every picker choice shows 0, dimmed; the handles still move.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable.
- Many options (data, not a prop): Many values: from 40 bars the gaps narrow, so no bar vanishes, and each picker's list scrolls.
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 { RangeSelect } from "@/components/filters-ui/filters/range-select";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";
type Car = { name: string; year: number };
const CARS: Car[] = [
{ name: "Honda Civic", year: 2017 },
{ name: "Ford Escape", year: 2018 },
{ name: "Toyota RAV4", year: 2019 },
{ name: "Mazda CX-5", year: 2019 },
{ name: "Subaru Outback", year: 2020 },
{ name: "Hyundai Tucson", year: 2021 },
{ name: "Toyota Camry", year: 2021 },
{ name: "Kia Sportage", year: 2022 },
{ name: "Tesla Model Y", year: 2023 },
{ name: "Honda CR-V", year: 2024 },
{ name: "Kia EV6", year: 2025 },
{ name: "Ford F-150", year: 2026 },
];
const YEARS = [2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026];
// One bar per year, in the order of YEARS.
const buckets = YEARS.map((year) => CARS.filter((car) => car.year === year).length);
type YearRange = [number | null, number | null];
function summaryOf([from, to]: YearRange) {
if (from !== null && from === to) return String(from);
if (from !== null && to !== null) return `${from} to ${to}`;
if (from !== null) return `${from} or newer`;
if (to !== null) return `${to} or older`;
return null;
}
export default function YearExample() {
const [years, setYears] = useState<YearRange>([null, null]);
const [from, to] = years;
const results = CARS.filter((car) => (from === null || car.year >= from) && (to === null || car.year <= to));
return (
<div className="w-full max-w-[320px]">
<FilterCard
title="Year"
summary={summaryOf(years)}
onClear={() => setYears([null, null])}
defaultOpen
>
<RangeSelect
options={YEARS}
value={years}
onChange={setYears}
buckets={buckets}
pickerOrder="descending"
labels={{ low: "From year", high: "To year" }}
countLabel={(n) => (n === 1 ? "1 car" : `${n} cars`)}
/>
</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-bar-out: #4A4A4A;
--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-handle: #F8F5F1;
--fu-handle-edge: rgb(0 0 0/0.25);
--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-rail: #4A4A4A;
--fu-rim: rgb(255 255 255/0.04);
--fu-row-active: rgb(255 255 255/0.07);
--fu-row-press: rgb(255 255 255/0.12);
--fu-selected: #1F2747;
--fu-shadow: rgb(0 0 0/0.5);
--fu-shadow-deep: rgb(0 0 0/0.8);
--fu-skeleton: rgb(255 255 255/0.12);
--fu-skeleton-on: rgb(143 170 255/0.3);
--fu-surface-1: #171717;
--fu-surface-3: #2A2A2A;
--fu-text: #F8F5F1;
--fu-track: rgb(255 255 255/0.06);
}
```
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-bar-out: #D6D6D2;
--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-handle: #FFFFFF;
--fu-handle-edge: rgb(29 27 24/0.55);
--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-rail: #D6D6D2;
--fu-rim: rgb(255 255 255/0.7);
--fu-row-active: rgb(29 27 24/0.05);
--fu-row-press: rgb(29 27 24/0.09);
--fu-selected: #E8EDFD;
--fu-shadow: rgb(36 36 33/0.12);
--fu-shadow-deep: rgb(36 36 33/0.16);
--fu-skeleton: rgb(29 27 24/0.09);
--fu-skeleton-on: rgb(48 73 210/0.18);
--fu-surface-1: #FFFFFF;
--fu-surface-3: rgb(29 27 24/0.07);
--fu-text: #1B1B19;
--fu-track: rgb(29 27 24/0.07);
}
```
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
- Handles are native range inputs whose spoken value is the year, not a bar number.
- Each picker is a Select: a combobox with a listbox, named with its visible prefix ("From year").
- Loading, it is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter. Disabled, the handles and pickers are disabled controls.
- Tab reaches each handle, then each picker.
- Arrow keys move the focused handle by one value. Right to left, the scale runs from the right: Left raises the value and Right lowers it.
- On a picker, Down, Enter or Space opens its list; arrows, Home, End and typed digits ("2015") move; Enter picks; Escape closes.
- While disabled the handles and pickers leave the tab order; 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
- One bar per value; the handles sit between bars, so From and To may hold the same value.
- The pickers and the chart stay in step both ways.
- Picking From past To moves To along with it, and the other way round: the latest pick wins.
- The first and last values are open ends, so choosing them sets no limit.
- With buckets, each picker choice shows a short bar and the count picking it would give; a choice that gives none is dimmed.
Keyboard
- Tab reaches each handle, then each picker.
- Arrow keys move the focused handle by one value. Right to left, the scale runs from the right: Left raises the value and Right lowers it.
- On a picker, Down, Enter or Space opens its list; arrows, Home, End and typed digits ("2015") move; Enter picks; Escape closes.
- While disabled the handles and pickers leave the tab order; in an error Tab reaches Retry.
Props
Value. [V | null, V | null], where V is a number from options: [from, to], both inclusive. null is an open end.
| Prop | Description |
|---|---|
optionsRequired | The values to pick from, in ascending order, e.g. years. One bar each. readonly number[] |
valueRequired | [from, to], both inclusive. null is an open end. [V | null, V | null] |
onChangeRequired | Called with the new range. (value: [V | null, V | null]) => void |
bucketsOptional | Item count per option, in the order of options. readonly number[] |
formatDefault 2026 | Picker, tooltip and screen-reader text for a value. The default prints the number with no group marks, in the locale's digits. (value: V) => string |
pickerOrderDefault "ascending" | Order of the picker choices; "descending" puts the newest year first. "ascending" | "descending" |
anyLabelDefault "Any" | The open-end choice in both pickers. string |
prefixesDefault From, To | Visible picker prefixes. { low?: string; high?: string } |
labelsDefault the prefixes | Accessible names of the handles and pickers. Keep the prefix word in them. { low?: string; high?: string } |
countLabelDefault "6 results" | Screen-reader words for a count in the pickers, e.g. "6 cars". (n: number) => string |
barScaleDefault 1 | Bar width as a share of its slot. number |
localeDefault "en-US" | Formats values (with no group marks, so years read 2026) and counts by default, e.g. "ar-EG". 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 counts." | The error line, in plain words. 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 |