Filter panel
Every car filter in one tall panel, as rows that open and close, with Clear all and a Show button.
Live example
Filters, 2 set
11 carsCopy
Add the "Filter panel" block from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Filter panel: Every car filter in one tall panel, as rows that open and close, with Clear all and a Show button.
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/filter-panel.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/blocks/filter-panel.tsx
```tsx
"use client";
import { useDeferredValue, useEffect, useId, useMemo, useRef, useState, type HTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { BodyIcon } from "../demo/body-icons";
import { BODIES, CARS, COLORS, COLOR_PAINTS, DRIVES, FUELS, type Car, type Condition, type Transmission } from "../demo/cars";
import {
CAR_FACET_TITLES,
EMPTY_CAR_FILTERS,
FACET_FIELDS,
KM_MAX,
KM_STEP,
MAKES_UP_FRONT,
PRICE_MAX,
PRICE_MIN,
PRICE_STEP,
YEARS,
bodyCounts,
clearFacet,
colorCounts, conditionOptions,
driveCounts,
carFormats,
fuelCounts,
kmBuckets,
makeOptions,
matchingCars,
priceBuckets,
seatOptions,
summaryOf,
transmissionOptions,
yearBuckets,
type CarFacet,
type CarFilters,
} from "../demo/cars-facets";
import { ChipGroup } from "../filters/chip-group";
import { ColorSwatches } from "../filters/color-swatches";
import { IconTiles } from "../filters/icon-tiles";
import { RangeHistogram } from "../filters/range-histogram";
import { RangeSelect } from "../filters/range-select";
import { SearchableList } from "../filters/searchable-list";
import { SegmentedChoice } from "../filters/segmented-choice";
import { UpperLimit } from "../filters/upper-limit";
import { ShowButton } from "../ui/filters-head";
import { ChevronDownIcon } from "../ui/icons";
import { StatusFrame, StatusLine, useFocusKept, type StateProps } from "../ui/status-frame";
import { TextSwap } from "../ui/text-swap";
/** Sidebar order: the filters people reach for first come first. */
export const FILTER_PANEL_FACETS: CarFacet[] = ["price", "make", "body", "year", "km", "fuel", "seats", "transmission", "drive", "condition", "color"];
/** The height of a row's head; an open head stays pinned at the top of the scroll area while its body scrolls under it. */
const HEAD = 56;
/** The height of the bottom fade, which an opening body is scrolled clear of. */
const FADE = 56;
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
const FOCUS =
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
// The summary and Clear share one slot and trade places over 150ms through a 2px blur and 4px shift, as on FilterCard.
const SWAP = "transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none";
const GONE_UP = "opacity-0 blur-[2px] -translate-y-1";
const GONE_DOWN = "opacity-0 blur-[2px] translate-y-1";
const SHOWN = "opacity-100 blur-none translate-y-0";
// Rose along the top, violet down the left, amber to teal down the right; each fades out about 28px in from the edge.
const EDGE_LIGHT = {
top: "linear-gradient(90deg, color-mix(in srgb, var(--fu-glow-rose,#EC8092) 20%, transparent), color-mix(in srgb, var(--fu-glow-rose,#EC8092) 13%, transparent) 50%, color-mix(in srgb, var(--fu-glow-amber,#F59E6C) 16%, transparent))",
left: "linear-gradient(180deg, color-mix(in srgb, var(--fu-glow-rose,#EC8092) 20%, transparent), color-mix(in srgb, var(--fu-glow-violet,#8A6CFF) 17%, transparent) 35%, color-mix(in srgb, var(--fu-glow-violet,#8A6CFF) 15%, transparent) 75%, color-mix(in srgb, var(--fu-glow-blue,#4C6BFF) 8%, transparent))",
right: "linear-gradient(180deg, color-mix(in srgb, var(--fu-glow-amber,#F59E6C) 17%, transparent), color-mix(in srgb, var(--fu-glow-teal,#2DD4BF) 13%, transparent) 45%, color-mix(in srgb, var(--fu-glow-teal,#2DD4BF) 11%, transparent) 80%, color-mix(in srgb, var(--fu-glow-blue,#4C6BFF) 5%, transparent))",
};
// Alpha masks: only the opacity of these stops counts, not their colour.
const MASK_DOWN = "linear-gradient(180deg, #000, rgb(0 0 0 / 0.4) 35%, transparent)";
const MASK_RIGHT = "linear-gradient(90deg, #000, rgb(0 0 0 / 0.4) 35%, transparent)";
const MASK_LEFT = "linear-gradient(270deg, #000, rgb(0 0 0 / 0.4) 35%, transparent)";
/** The rim, and with glow a faint coloured light along the edges. Drawn over the rows, so pinned heads never hide it. */
function Edge({ glow }: { glow: boolean }) {
return (
<span aria-hidden="true" className="pointer-events-none absolute inset-0 z-20 overflow-hidden rounded-[inherit]">
<span
className={cn(
"absolute inset-0 rounded-[inherit]",
glow ? "shadow-[inset_0_0_0_1px_var(--fu-line,#404040)]" : "shadow-[inset_0_0_0_1px_var(--fu-card-border,#2A2A2A)]",
)}
/>
{glow && (
<>
<span className="absolute inset-x-0 top-0 h-14" style={{ backgroundImage: EDGE_LIGHT.top, maskImage: MASK_DOWN }} />
{/* physical: the glow is lighting, not reading order, so its colours stay on the same sides in RTL. Brackets, so shadcn's rtl option leaves both alone. */}
<span className="absolute inset-y-0 [left:0] w-12" style={{ backgroundImage: EDGE_LIGHT.left, maskImage: MASK_RIGHT }} />
{/* physical: as above. */}
<span className="absolute inset-y-0 [right:0] w-12" style={{ backgroundImage: EDGE_LIGHT.right, maskImage: MASK_LEFT }} />
</>
)}
</span>
);
}
type RowProps = {
title: string;
summary: string | null;
/** Left out while the panel is disabled: the row then offers no Clear. */
onClear?: () => void;
open: boolean;
onToggle: (row: HTMLElement) => void;
onHeadKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => void;
headingLevel: 3 | 4 | 5;
children: ReactNode;
};
/**
* One filter as a row: a 56px head (title, the value in words or Clear, chevron) over a body that opens with the
* FilterCard motion. While open, the head stays pinned as its body scrolls under it.
*/
function PanelRow({ title, summary, onClear, open, onToggle, onHeadKeyDown, headingLevel, children }: RowProps) {
const id = useId();
const headId = `${id}-head`;
const bodyId = `${id}-body`;
const head = useRef<HTMLButtonElement>(null);
const row = useRef<HTMLElement>(null);
const set = Boolean(summary);
const Heading = `h${headingLevel}` as const;
// The last summary stays in place while it fades out after a clear.
const [lastSummary, setLastSummary] = useState(summary ?? "");
if (summary && summary !== lastSummary) setLastSummary(summary);
return (
<section ref={row} data-panel-row="" data-state={open ? "open" : "closed"} className="relative">
<div
className={cn(
"group/head sticky top-0 z-10 transition-[background-color] motion-reduce:transition-none",
SMOOTH,
// An open row's head keeps the panel's own surface: it stays in place while its filter scrolls under it, so
// it has to cover what passes, and no more than that.
open ? "bg-[var(--fu-card,#1F1F1F)] duration-[480ms]" : "duration-200 [@media(hover:hover)]:hover:bg-[var(--fu-card-hover,#262626)]",
)}
>
<Heading className="m-0 text-[16px] font-semibold leading-6 text-[var(--fu-text,#F8F5F1)]">
<button
ref={head}
type="button"
id={headId}
data-panel-row-head=""
aria-expanded={open}
aria-controls={bodyId}
onClick={() => row.current && onToggle(row.current)}
onKeyDown={onHeadKeyDown}
className={cn(
"flex w-full cursor-pointer items-center gap-4 rounded-[16px] px-5 text-start font-[inherit] text-inherit [-webkit-tap-highlight-color:transparent]",
FOCUS,
"focus-visible:-outline-offset-4",
)}
style={{ height: HEAD }}
>
<span className="min-w-0 truncate">{title}</span>
{set && <span className="sr-only">, {summary}</span>}
{set && (
// Half the head's width, as the visible slot: 50% here would be half the button's box, 40px narrower.
<span aria-hidden="true" className="invisible ms-auto min-w-0 max-w-[calc((100%+40px)*0.5)] shrink-0 truncate text-[16px] font-normal">
{summary}
</span>
)}
<ChevronDownIcon
size={22}
className={cn(
"shrink-0 text-[var(--fu-mute,#BDBDBD)] transition-[rotate,color] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
!set && "ms-auto",
open && "rotate-180",
"[@media(hover:hover)]:group-hover/head:text-[var(--fu-text,#F8F5F1)]",
)}
/>
</button>
</Heading>
<div
inert={!set}
className="group/slot pointer-events-none absolute top-0 inset-e-[58px] grid max-w-[50%] items-center justify-items-end text-[16px] leading-6 text-[var(--fu-accent-soft,#8FAAFF)]"
style={{ height: HEAD }}
>
<span
aria-hidden="true"
className={cn(
"max-w-full truncate [grid-area:1/1]",
SWAP,
set && !open ? SHOWN : GONE_UP,
// Hovering a closed row, or tabbing to its Clear, offers Clear in the summary's place.
set && !open && onClear && "[@media(hover:hover)]:group-hover/head:opacity-0 [@media(hover:hover)]:group-hover/head:blur-[2px] [@media(hover:hover)]:group-hover/head:-translate-y-1",
set && !open && onClear && "group-focus-within/slot:opacity-0 group-focus-within/slot:blur-[2px] group-focus-within/slot:-translate-y-1",
)}
>
{summary || lastSummary}
</span>
{onClear && (
<button
type="button"
tabIndex={set ? 0 : -1}
aria-label={`Clear ${title.toLowerCase()}`}
onClick={() => {
onClear();
head.current?.focus();
}}
className={cn(
"relative cursor-pointer rounded-[6px] font-medium [grid-area:1/1] [-webkit-tap-highlight-color:transparent]",
// The press area runs the full height of the head.
"before:absolute before:-inset-x-2 before:-inset-y-4 before:content-['']",
FOCUS,
"focus-visible:outline-offset-2",
SWAP,
set && open ? cn(SHOWN, "pointer-events-auto") : GONE_DOWN,
set &&
!open &&
"[@media(hover:hover)]:pointer-events-auto [@media(hover:hover)]:group-hover/head:opacity-100 [@media(hover:hover)]:group-hover/head:blur-none [@media(hover:hover)]:group-hover/head:translate-y-0",
set && !open && "focus-visible:opacity-100 focus-visible:blur-none focus-visible:translate-y-0",
)}
>
Clear
</button>
)}
</div>
</div>
<div
id={bodyId}
role="region"
aria-labelledby={headId}
inert={!open}
className={cn(
"grid transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
open ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
)}
>
<div className="min-h-0 overflow-hidden">
<div
className={cn(
"px-5 pt-1.5 pb-5 transition-[opacity,filter,translate] motion-reduce:transition-none",
open
? "translate-y-0 opacity-100 blur-none delay-[120ms] duration-[460ms] ease-[cubic-bezier(0.16,1,0.3,1)]"
: cn("translate-y-1.5 opacity-0 blur-[6px] duration-[480ms]", SMOOTH),
)}
>
{children}
</div>
</div>
</div>
</section>
);
}
export type FilterPanelProps = Omit<HTMLAttributes<HTMLElement>, "onChange"> &
Omit<StateProps, "emptyText"> & {
cars?: readonly Car[];
defaultFilters?: CarFilters;
/** Rows open on first render. Several may be open at once. */
defaultOpen?: CarFacet[];
onShow?: (cars: Car[]) => void;
/** Level of the Filters heading; row headings sit one below. Default 2. */
headingLevel?: 2 | 3 | 4;
/** A faint coloured light along the panel's edges. Default false. */
glow?: boolean;
/** Numbers, prices and distances follow it, e.g. "de-DE". Default "en-US". */
locale?: string;
};
/**
* Every car filter as a row in one tall panel, like a search page's sidebar: a head (Filters, how many are set,
* Clear all), the rows between soft fades, and Show N cars pinned at the bottom. Closed rows keep their value in
* words, so the closed panel reads as the whole search. Give it a height (or a max height) and the rows scroll.
* status and disabled reach every row's filter through a frame of its own, quiet, as the head says the state once:
* loading draws each filter's placeholders and the number in Show; an error shows its line in each open row and once
* under the head, with the one Retry; disabled turns every filter off and leaves Clear and Clear all out.
*/
export function FilterPanel({
cars = CARS,
defaultFilters = EMPTY_CAR_FILTERS,
defaultOpen = [],
onShow,
headingLevel = 2,
glow = false,
locale,
status = "ready",
onRetry,
errorText = "Couldn't load the cars.",
disabled = false,
className,
...props
}: FilterPanelProps) {
const titleId = useId();
const root = useRef<HTMLElement>(null);
const dragged = useRef(false);
const [filters, setFilters] = useState(defaultFilters);
const [open, setOpen] = useState<CarFacet[]>(defaultOpen);
const scroller = useRef<HTMLDivElement>(null);
const list = useRef<HTMLDivElement>(null);
const topFade = useRef<HTMLDivElement>(null);
const bottomFade = useRef<HTMLDivElement>(null);
// A row just closed from its pinned place, held flush with the top until the panel scrolls.
const held = useRef<HTMLElement | null>(null);
const follow = useRef(0);
const f = carFormats(locale);
const matches = matchingCars(filters, cars);
const setCount = FILTER_PANEL_FACETS.filter((facet) => summaryOf(filters, facet, locale) !== null).length;
const [lastSetCount, setLastSetCount] = useState(setCount || 1);
if (setCount > 0 && setCount !== lastSetCount) setLastSetCount(setCount);
const set = (patch: Partial<CarFilters>) => setFilters((f) => ({ ...f, ...patch }));
const heads = () => [...(list.current?.querySelectorAll<HTMLButtonElement>("[data-panel-row-head]") ?? [])];
// Clear all hides once nothing is set, so focus moves to the first row rather than dropping to the page.
const clearAll = () => {
setFilters(EMPTY_CAR_FILTERS);
heads()[0]?.focus();
};
// Up and Down move between row heads, Home and End jump to the first and last, as in a WAI accordion.
const onHeadKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
const all = heads();
const at = all.indexOf(event.currentTarget);
const target =
event.key === "ArrowDown" ? all[at + 1] : event.key === "ArrowUp" ? all[at - 1] : event.key === "Home" ? all[0] : event.key === "End" ? all.at(-1) : undefined;
if (!target) return;
event.preventDefault();
target.focus();
};
const toggle = (facet: CarFacet, row: HTMLElement) => {
const node = scroller.current;
if (!node) return;
cancelAnimationFrame(follow.current);
const headTop = row.offsetTop + row.clientTop;
if (open.includes(facet)) {
// Closing a pinned head would carry it up out of view with its body; scroll to it so it stays where it was pinned.
if (headTop < node.scrollTop) {
node.scrollTop = headTop;
held.current = row;
}
setOpen((rows) => rows.filter((f) => f !== facet));
return;
}
setOpen((rows) => [...rows, facet]);
// As the body grows, scroll along so its end stays clear of the bottom fade, but never past its head reaching the top.
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const until = performance.now() + (reduced ? 0 : 560);
const step = () => {
const want = Math.min(headTop, row.offsetTop + row.offsetHeight - node.clientHeight + FADE);
if (want > node.scrollTop + 0.5) node.scrollTop = want;
if (performance.now() < until) follow.current = requestAnimationFrame(step);
};
follow.current = requestAnimationFrame(step);
};
// The fades follow the scroll without re-rendering the rows. Under a pinned head the top fade starts below it.
useEffect(() => {
const node = scroller.current;
const inner = list.current;
if (!node || !inner) return;
const measure = () => {
const top = node.scrollTop;
let below = 0;
for (const row of inner.querySelectorAll<HTMLElement>("[data-panel-row][data-state=open]")) {
const end = row.offsetTop + row.offsetHeight;
if (row.offsetTop <= top + 1 && end > top) below = Math.max(0, Math.min(HEAD, end - top));
}
if (held.current) {
if (Math.abs(held.current.offsetTop + held.current.clientTop - top) <= 1) below = HEAD;
else held.current = null;
}
if (topFade.current) {
topFade.current.style.top = `${below}px`;
topFade.current.dataset.shown = String(top > 1);
}
if (bottomFade.current) bottomFade.current.dataset.shown = String(top + node.clientHeight < node.scrollHeight - 1);
};
measure();
// A wheel or touch hands the scroll back to the person while an opening row is being followed.
const stop = () => cancelAnimationFrame(follow.current);
node.addEventListener("scroll", measure, { passive: true });
node.addEventListener("wheel", stop, { passive: true });
node.addEventListener("touchstart", stop, { passive: true });
const observer = new ResizeObserver(measure);
observer.observe(node);
observer.observe(inner);
return () => {
node.removeEventListener("scroll", measure);
node.removeEventListener("wheel", stop);
node.removeEventListener("touchstart", stop);
observer.disconnect();
stop();
};
}, []);
const bodyOf = (facet: CarFacet, filters: CarFilters): ReactNode => {
switch (facet) {
case "price":
return (
<RangeHistogram
locale={locale}
min={PRICE_MIN}
max={PRICE_MAX}
step={PRICE_STEP}
value={[filters.priceMin, filters.priceMax]}
onChange={([priceMin, priceMax]) => set({ priceMin, priceMax })}
buckets={priceBuckets(filters, cars)}
format={f.money}
labels={{ low: "Lowest price", high: "Highest price" }}
/>
);
case "make":
return (
<SearchableList
locale={locale}
variant="panel"
label="Make and model"
noun="makes"
collapsedCount={MAKES_UP_FRONT}
options={makeOptions(filters, cars)}
value={filters.makes.map((p) => ({ value: p.make, children: p.models }))}
onChange={(picks) => set({ makes: picks.map((p) => ({ make: p.value, models: p.children })) })}
countLabel={f.carCount}
/>
);
case "body": {
const counts = bodyCounts(filters, cars);
return (
<IconTiles
locale={locale}
label="Body style"
options={BODIES.map((b) => ({ value: b, label: b, icon: <BodyIcon body={b} />, count: counts.get(b) ?? 0 }))}
value={filters.bodies}
onChange={(bodies) => set({ bodies })}
countLabel={f.carCount}
/>
);
}
case "year":
return (
<RangeSelect
locale={locale}
options={YEARS}
value={[filters.yearMin, filters.yearMax]}
onChange={([yearMin, yearMax]) => set({ yearMin, yearMax })}
buckets={yearBuckets(filters, cars)}
pickerOrder="descending"
labels={{ low: "From year", high: "To year" }}
/>
);
case "km":
return (
<UpperLimit
locale={locale}
min={0}
max={KM_MAX}
step={KM_STEP}
value={filters.kmMax}
onChange={(kmMax) => set({ kmMax })}
buckets={kmBuckets(filters, cars)}
format={f.km}
label="Maximum kilometres"
/>
);
case "fuel": {
const counts = fuelCounts(filters, cars);
return (
<ChipGroup
locale={locale}
label="Fuel"
options={FUELS.map((v) => ({ value: v, label: v, count: counts.get(v) ?? 0 }))}
value={filters.fuels}
onChange={(fuels) => set({ fuels })}
countLabel={f.carCount}
/>
);
}
case "seats":
return (
<SegmentedChoice<number | null>
locale={locale}
label="Seats"
options={seatOptions(filters, cars, locale)}
value={filters.seatsMin}
onChange={(seatsMin) => set({ seatsMin })}
countLabel={f.carCount}
/>
);
case "transmission":
return (
<SegmentedChoice<Transmission | null>
locale={locale}
label="Transmission"
fit="content"
options={transmissionOptions(filters, cars)}
value={filters.transmission}
onChange={(transmission) => set({ transmission })}
countLabel={f.carCount}
/>
);
case "drive": {
const counts = driveCounts(filters, cars);
return (
<ChipGroup
locale={locale}
label="Drivetrain"
options={DRIVES.map((v) => ({ value: v, label: v, count: counts.get(v) ?? 0 }))}
value={filters.drives}
onChange={(drives) => set({ drives })}
countLabel={f.carCount}
/>
);
}
case "condition":
return (
<SegmentedChoice<Condition | null>
locale={locale}
label="New or used"
options={conditionOptions(filters, cars)}
value={filters.condition}
onChange={(condition) => set({ condition })}
countLabel={f.carCount}
/>
);
case "color": {
const counts = colorCounts(filters, cars);
return (
<ColorSwatches
locale={locale}
label="Colour"
options={COLORS.map((c) => ({ value: c, label: c, color: COLOR_PAINTS[c], count: counts.get(c) ?? 0 }))}
value={filters.colors}
onChange={(colors) => set({ colors })}
countLabel={f.carCount}
/>
);
}
}
};
const framed = (facet: CarFacet, from: CarFilters) => (
<StatusFrame status={status} errorText={errorText} disabled={disabled} announce={false}>
{bodyOf(facet, from)}
</StatusFrame>
);
// While a handle is dragged, a row whose own filter did not change draws from the deferred filters, so only the
// dragged row renders at once and the others' counts follow when the main thread is free. Taps and keys update every row together.
const dragging = dragged.current;
const later = useDeferredValue(filters);
const from = dragging ? later : filters;
const settled = useMemo(() => new Map(FILTER_PANEL_FACETS.map((facet) => [facet, framed(facet, from)])), [from, cars, locale, status, errorText, disabled]);
const bodyFor = (facet: CarFacet) => (dragging && FACET_FIELDS[facet].some((key) => filters[key] !== later[key]) ? framed(facet, filters) : settled.get(facet));
const Heading = `h${headingLevel}` as const;
const rowLevel = (headingLevel + 1) as 3 | 4 | 5;
const anySet = setCount > 0;
// Clear all hides while disabled, as when nothing is set.
const canClear = anySet && !disabled;
// A Clear that leaves while disabled, or Retry once it reloads: focus that sat on it moves to the panel.
useFocusKept(root, `${status}|${disabled}`);
return (
<section
ref={root}
aria-labelledby={titleId}
// Retry hands focus to the panel, which stays while it reloads.
tabIndex={-1}
data-status-frame=""
className={cn(
"not-prose relative isolate flex min-h-0 w-full flex-col overflow-hidden rounded-[24px] bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-text,#F8F5F1)]",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
className,
)}
onPointerMoveCapture={(event) => (dragged.current = event.buttons !== 0)}
onPointerUpCapture={() => (dragged.current = false)}
onPointerCancelCapture={() => (dragged.current = false)}
onClickCapture={() => (dragged.current = false)}
onKeyDownCapture={() => (dragged.current = false)}
{...props}
>
<div data-panel-head="" className="flex h-[60px] shrink-0 items-center gap-3 border-b border-[var(--fu-line,#404040)] pe-3 ps-5">
<Heading id={titleId} className="m-0 flex min-w-0 items-baseline gap-2 text-[22px] font-semibold leading-7 text-[var(--fu-text,#F8F5F1)]">
Filters
<span
aria-hidden="true"
className={cn("font-normal tabular-nums text-[var(--fu-dim,#929292)]", SWAP, anySet ? SHOWN : GONE_DOWN)}
>
<TextSwap>{formatsFor(locale).number(anySet ? setCount : lastSetCount)}</TextSwap>
</span>
{anySet && <span className="sr-only">, {formatsFor(locale).number(setCount)} set</span>}
</Heading>
<span className="sr-only" aria-live="polite" aria-atomic="true">
{f.carCount(matches.length)}
</span>
<button
type="button"
inert={!canClear}
onClick={clearAll}
className={cn(
"relative ms-auto inline-flex h-9 shrink-0 cursor-pointer items-center rounded-[10px] px-2.5 text-[16px] font-medium leading-5 text-[var(--fu-accent-soft,#8FAAFF)] [-webkit-tap-highlight-color:transparent]",
"hover:text-[var(--fu-accent-pale,#D1DDFF)] pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1 pointer-coarse:after:content-['']",
FOCUS,
"focus-visible:outline-offset-0",
SWAP,
"transition-[opacity,filter,translate,color]",
canClear ? SHOWN : GONE_DOWN,
)}
>
Clear all
</button>
</div>
<StatusLine
status={status}
onRetry={onRetry}
errorText={errorText}
className="shrink-0 justify-start gap-x-4 border-b border-[var(--fu-line,#404040)] px-5 py-3"
/>
<div className="relative flex min-h-0 flex-1 flex-col">
<div
ref={scroller}
className={cn("min-h-0 flex-1 overflow-y-auto overscroll-contain scroll-pt-14 scroll-pb-12", SCROLL)}
>
<div ref={list} className="relative divide-y divide-[var(--fu-line,#404040)]">
{FILTER_PANEL_FACETS.map((facet) => (
<PanelRow
key={facet}
title={CAR_FACET_TITLES[facet]}
summary={summaryOf(filters, facet, locale)}
onClear={disabled ? undefined : () => setFilters((f) => clearFacet(f, facet))}
open={open.includes(facet)}
onToggle={(row) => toggle(facet, row)}
onHeadKeyDown={onHeadKeyDown}
headingLevel={rowLevel}
>
{bodyFor(facet)}
</PanelRow>
))}
</div>
</div>
<div
ref={topFade}
aria-hidden="true"
data-shown="false"
className="pointer-events-none absolute inset-x-0 top-0 z-10 h-8 bg-linear-to-b from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 data-[shown=true]:opacity-100 motion-reduce:transition-none"
/>
<div
ref={bottomFade}
aria-hidden="true"
data-shown="false"
className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-14 bg-linear-to-t from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 data-[shown=true]:opacity-100 motion-reduce:transition-none"
/>
</div>
<div className="shrink-0 border-t border-[var(--fu-line,#404040)] p-4">
<ShowButton label={`Show ${f.carCount(matches.length)}`} onClick={onShow && (() => onShow(matches))} loading={status === "loading"} className="h-11 w-full" />
</div>
<Edge glow={glow} />
</section>
);
}
```
### components/filters-ui/lib/cn.ts
```ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
```
### components/filters-ui/lib/format.ts
```ts
// Numbers, prices, distances, percents and dates for one locale, built on Intl with no dependency. Pass any BCP 47
// tag ("de-DE", "ar-EG"); a tag Intl cannot read falls back to en-US instead of throwing. The default is en-US, never
// the browser's own locale, so the server and the browser always print the same text. UI words stay English.
export const DEFAULT_LOCALE = "en-US";
export type FormatOptions = {
/** ISO 4217 code for price and priceShort. Default "USD". */
currency?: string;
/** The unit of distance. Default "kilometer". */
unit?: "kilometer" | "mile";
};
/** Every formatter takes the value alone, so any of them can be passed straight to a format prop. */
export type Formats = {
/** The locale these formatters use, after any fallback. */
locale: string;
/** "1,234" in en-US, "1.234" in de-DE, up to three decimals. */
number: (value: number) => string;
/** A number with no group marks, such as a year: "2026", or "٢٠٢٦" in ar-EG. */
plain: (value: number) => string;
/** "45k", "1.2M". */
compact: (value: number) => string;
/** "$45,000" in en-US, "45.000 $" in de-DE: whole units of the currency. */
price: (value: number) => string;
/** "$45k" and "$97.5k" from a thousand up, "$950" below. */
priceShort: (value: number) => string;
/** "50,000 km" or "31,069 mi". */
distance: (value: number) => string;
/** A percentage given in percent, up to two decimals: 6.5 gives "6.5%" in en-US and "6,5 %" in de-DE. */
percent: (value: number) => string;
/** A day given as "YYYY-MM-DD", in words. Read in UTC, so it never shifts by a time zone. */
day: (iso: string, options: Intl.DateTimeFormatOptions) => string;
/** The name of a month, 0 for January. */
month: (index: number, style?: "long" | "short") => string;
/** The name of a weekday, 0 for Sunday. */
weekday: (index: number, style?: "long" | "short") => string;
/** The day weeks start on: 0 for Sunday, 1 for Monday, 6 for Saturday. */
firstDay: 0 | 1 | 5 | 6;
/** The locale's digits, 0 to 9: "0123456789", or "٠١٢٣٤٥٦٧٨٩" in ar-EG. */
digits: string;
/**
* Reads a number typed the locale's way, with an optional k or m: "45,000", "$45k" and "1.2m" in en-US, "45.000"
* and "1,2m" in de-DE. A unit such as "km" is not a suffix. Returns null when the text holds no number.
*/
readNumber: (text: string) => number | null;
};
/**
* A locale Intl has data for, or en-US. A well-formed tag with no data ("zz") would otherwise print in the
* runtime's own locale, which differs between server and browser.
*/
export function safeLocale(locale?: string): string {
if (!locale) return DEFAULT_LOCALE;
try {
const [tag] = Intl.getCanonicalLocales(locale);
if (!tag) return DEFAULT_LOCALE;
if (!Intl.NumberFormat.supportedLocalesOf(tag).length || !Intl.DateTimeFormat.supportedLocalesOf(tag).length) return DEFAULT_LOCALE;
return tag;
} catch {
return DEFAULT_LOCALE;
}
}
/** A currency code Intl can read, or USD. */
function safeCurrency(currency?: string): string {
if (!currency) return "USD";
try {
new Intl.NumberFormat(DEFAULT_LOCALE, { style: "currency", currency });
return currency.toUpperCase();
} catch {
return "USD";
}
}
// Where weeks start, by region, as CLDR 48 has it; every other region starts on Monday. A table rather than
// Intl.Locale weekInfo, which not every browser has, so the server and every browser agree.
const SUNDAY = new Set(
"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "),
);
const SATURDAY = new Set("AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
function firstDayOf(locale: string): 0 | 1 | 5 | 6 {
let region: string | undefined;
try {
region = new Intl.Locale(locale).maximize().region;
} catch {}
if (!region) return 0;
if (region === "MV") return 5;
if (SATURDAY.has(region)) return 6;
return SUNDAY.has(region) ? 0 : 1;
}
const cache = new Map<string, Formats>();
/** Formatters for one locale. Cheap to call on every render: each locale and option set is built once. */
export function formatsFor(locale?: string, options: FormatOptions = {}): Formats {
const tag = safeLocale(locale);
const currency = safeCurrency(options.currency);
const unit = options.unit === "mile" ? "mile" : "kilometer";
const key = `${tag}|${currency}|${unit}`;
const known = cache.get(key);
if (known) return known;
const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(tag, o);
const dates = new Map<string, Intl.DateTimeFormat>();
const df = (o: Intl.DateTimeFormatOptions) => {
const id = JSON.stringify(o);
let format = dates.get(id);
if (!format) {
format = new Intl.DateTimeFormat(tag, { ...o, timeZone: "UTC" });
dates.set(id, format);
}
return format;
};
// English writes thousands with a small k, as the filters always have.
const english = tag === "en" || tag.startsWith("en-");
const smallK = (text: string) => (english ? text.replace(/K\b/, "k") : text);
const number = nf({});
const plain = nf({ useGrouping: false, maximumFractionDigits: 20 });
const compact = nf({ notation: "compact", maximumFractionDigits: 1 });
const price = nf({ style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0 });
// One decimal is exact for a 1,000 unit ("$97.5k"); a 10,000 unit such as 万 takes two ("$9.75万").
const unitDigits = nf({ notation: "compact", useGrouping: false }).formatToParts(10000).filter((p) => p.type === "integer").map((p) => p.value).join("").length;
const priceShort = nf({ style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: Math.max(1, 3 - unitDigits) });
const distance = nf({ style: "unit", unit, maximumFractionDigits: 0 });
const percent = nf({ style: "percent", maximumFractionDigits: 2 });
const digits = plain.format(1234567890).replace(/^(.*)(.)$/, "$2$1");
const parts = number.formatToParts(12345.6);
const group = parts.find((p) => p.type === "group")?.value ?? ",";
const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";
const formats: Formats = {
locale: tag,
number: (value) => number.format(value),
plain: (value) => plain.format(value),
compact: (value) => smallK(compact.format(value)),
price: (value) => price.format(value),
priceShort: (value) => (Math.abs(value) >= 1000 ? smallK(priceShort.format(value)) : price.format(value)),
distance: (value) => distance.format(value),
percent: (value) => percent.format(value / 100),
day: (iso, o) => df(o).format(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)))),
month: (index, style = "long") => df({ month: style }).format(Date.UTC(2021, index, 1)),
// 3 January 2021 was a Sunday.
weekday: (index, style = "long") => df({ weekday: style }).format(Date.UTC(2021, 0, 3 + index)),
firstDay: firstDayOf(tag),
digits,
readNumber: (text) => {
let t = text.replace(/[\s ]/g, "");
for (let i = 0; i < 10; i++) t = t.split(digits[i]).join(String(i));
if (!/\s/.test(group)) t = t.split(group).join("");
// Marks typed in place of the locale's own: a Latin or Arabic comma where both marks are Arabic, a curly apostrophe for a straight one.
if (!/[.,]/.test(group + decimal)) t = t.replace(/[,\u060c]/g, "");
if (group === "'") t = t.split("\u2019").join("");
if (decimal !== ".") t = t.split(decimal).join(".");
const match = t.match(/(\d*\.?\d+)([km](?![a-z]))?/i);
if (!match) return null;
const scale = match[2] ? (match[2].toLowerCase() === "k" ? 1e3 : 1e6) : 1;
return Number(match[1]) * scale;
},
};
cache.set(key, formats);
return formats;
}
/** "1 result", "1,204 results": the default words for a count, with the number in the locale. */
export const resultsLabel = (n: number, locale?: string) => `${formatsFor(locale).number(n)} ${n === 1 ? "result" : "results"}`;
```
### components/filters-ui/lib/scroll.ts
```ts
/**
* A slim scrollbar for every box that scrolls: a 6px rounded thumb in the line colour on a clear track, stronger under
* the pointer, kept 2px off the side and 12px off each end so it never runs into a rounded corner.
* Chromium and Safari draw it from the ::-webkit-scrollbar parts. Firefox has none of those, so it alone gets the
* standard thin bar in the same colours: Chromium ignores the parts once scrollbar-width or scrollbar-color is set,
* so never add either beside this class.
*/
export const SCROLL =
"supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-width:thin] supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-color:var(--fu-line,#404040)_transparent] " +
"[&::-webkit-scrollbar]:size-2.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent " +
"[&::-webkit-scrollbar-track:vertical]:my-3 [&::-webkit-scrollbar-track:horizontal]:mx-3 " +
"[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-padding " +
"[&::-webkit-scrollbar-thumb]:bg-[var(--fu-line,#404040)] [&::-webkit-scrollbar-thumb:hover]:bg-[var(--fu-control-border,#737373)] [&::-webkit-scrollbar-thumb:active]:bg-[var(--fu-control-border,#737373)]";
```
### components/filters-ui/demo/body-icons.tsx
```tsx
import type { SVGProps } from "react";
// Side profiles, one per body style: the outline, then the x of each wheel centre.
export const PROFILES = {
SUV: [
"M16 100c0-13 4-22 18-26l46-10 26-30c4-5 9-7 15-7h104c8 0 14 2 19 8l26 34 26 6c6 2 8 6 8 13v24c0 4-3 6-7 6h-16a29 29 0 0 0-56 0H106a29 29 0 0 0-56 0H24c-5 0-8-4-8-12z",
[78, 253],
],
Sedan: [
"M18 100c0-11 5-20 19-24l52-11c20-17 43-27 74-27 30 0 54 8 75 25l40 7c12 2 24 9 24 22v12c0 5-3 8-8 8h-20a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-12z",
[76, 246],
],
Truck: [
"M14 102c0-14 5-23 19-27l44-9 26-28c4-5 9-7 15-7h62c7 0 11 4 12 10l2 25h104c5 0 8 3 8 8v30c0 5-3 8-8 8h-30a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H22c-5 0-8-4-8-10z",
[76, 240],
],
Hatchback: [
"M26 100c0-11 5-20 19-24l44-11c20-18 41-28 72-29 28 0 50 7 66 26l32 16c8 5 13 12 13 22v8c0 4-3 6-7 6h-23a29 29 0 0 0-56 0H112a29 29 0 0 0-56 0H34c-5 0-8-4-8-14z",
[84, 214],
],
Coupe: [
"M14 100c0-10 5-17 18-21l66-13c22-16 44-24 72-24 32 0 56 11 76 29l34 7c14 3 26 8 26 20v8c0 8-3 10-8 10h-22a29 29 0 0 0-56 0H106a29 29 0 0 0-56 0H22c-5 0-8-4-8-16z",
[78, 248],
],
Minivan: [
"M18 102c0-13 5-22 18-26l40-10 36-32c5-5 11-7 18-7h124c9 0 14 3 19 9l18 31c4 6 6 12 6 20v21c0 4-3 6-7 6h-24a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-12z",
[76, 238],
],
Van: [
"M18 102c0-14 4-23 16-27l34-10 22-36c3-5 8-8 14-8h186c8 0 14 6 14 14v75c0 4-3 6-7 6h-29a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-14z",
[76, 240],
],
Convertible: [
"M18 100c0-11 5-19 18-23l58-10 18-22 8 1-14 21h116l42 8c11 2 22 8 22 21v10c0 7-3 10-8 10h-22a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-16z",
[76, 228],
],
} satisfies Record<string, [string, [number, number]]>;
export type BodyStyle = keyof typeof PROFILES;
/** A car's side profile in currentColor. The wheels are ringed in var(--tile-bg) so they read as cut out of the body. */
export function BodyIcon({ body, ...props }: SVGProps<SVGSVGElement> & { body: BodyStyle }) {
const [outline, wheels] = PROFILES[body];
return (
<svg viewBox="0 0 320 140" height={28} aria-hidden="true" focusable="false" {...props}>
<path d={outline} fill="currentColor" />
{wheels.map((x) => (
<circle key={x} cx={x} cy={112} r={19} fill="currentColor" stroke="var(--tile-bg,var(--fu-card,#1F1F1F))" strokeWidth={7} />
))}
</svg>
);
}
```
### components/filters-ui/demo/cars.ts
```ts
// Demo data: 256 invented car listings, generated from a fixed seed so every
// visitor sees the same list. Make and model names are only labels for the demo.
export type Body = "SUV" | "Sedan" | "Truck" | "Hatchback" | "Coupe" | "Minivan" | "Van" | "Convertible";
export type Fuel = "Gas" | "Hybrid" | "Plug-in hybrid" | "Electric" | "Diesel";
export type Drive = "AWD" | "4WD" | "FWD" | "RWD";
export type Transmission = "Automatic" | "Manual";
export type Condition = "New" | "Used";
export type Color = "Black" | "White" | "Gray" | "Silver" | "Blue" | "Red" | "Green" | "Brown";
// A null is a detail the listing never gave, as real feeds often do.
export type Car = {
id: string;
make: string;
model: string;
body: Body;
year: number;
km: number | null;
price: number;
fuel: Fuel | null;
drive: Drive | null;
transmission: Transmission | null;
color: Color | null;
seats: number | null;
condition: Condition;
/** Days since the listing went up: 0 is today, 59 the oldest. */
listed: number;
};
type Model = {
make: string;
model: string;
body: Body;
price: number;
trims: number;
fuels: Fuel[];
drives: Drive[];
seats: number;
manual?: boolean;
};
const MODELS: Model[] = [
{ make: "Toyota", model: "RAV4", body: "SUV", price: 39000, trims: 4, fuels: ["Gas", "Hybrid"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Toyota", model: "Corolla", body: "Sedan", price: 27000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["FWD"], seats: 5 },
{ make: "Toyota", model: "Camry", body: "Sedan", price: 35000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["FWD", "AWD"], seats: 5 },
{ make: "Toyota", model: "Highlander", body: "SUV", price: 53000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["AWD"], seats: 8 },
{ make: "Toyota", model: "Tacoma", body: "Truck", price: 52000, trims: 3, fuels: ["Gas"], drives: ["4WD"], seats: 5, manual: true },
{ make: "Toyota", model: "Sienna", body: "Minivan", price: 54000, trims: 3, fuels: ["Hybrid"], drives: ["FWD", "AWD"], seats: 8 },
{ make: "Honda", model: "CR-V", body: "SUV", price: 40000, trims: 4, fuels: ["Gas", "Hybrid"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Honda", model: "Civic", body: "Sedan", price: 31000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["FWD"], seats: 5, manual: true },
{ make: "Honda", model: "Accord", body: "Sedan", price: 40000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["FWD"], seats: 5 },
{ make: "Honda", model: "Odyssey", body: "Minivan", price: 53000, trims: 3, fuels: ["Gas"], drives: ["FWD"], seats: 8 },
{ make: "Ford", model: "F-150", body: "Truck", price: 62000, trims: 4, fuels: ["Gas", "Hybrid"], drives: ["4WD"], seats: 6 },
{ make: "Ford", model: "Escape", body: "SUV", price: 37000, trims: 3, fuels: ["Gas", "Hybrid", "Plug-in hybrid"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Ford", model: "Mustang", body: "Coupe", price: 52000, trims: 2, fuels: ["Gas"], drives: ["RWD"], seats: 4, manual: true },
{ make: "Ford", model: "Mustang Mach-E", body: "SUV", price: 57000, trims: 2, fuels: ["Electric"], drives: ["AWD", "RWD"], seats: 5 },
{ make: "Ford", model: "Transit", body: "Van", price: 60000, trims: 2, fuels: ["Gas"], drives: ["RWD", "AWD"], seats: 3 },
{ make: "Chevrolet", model: "Silverado 1500", body: "Truck", price: 60000, trims: 4, fuels: ["Gas", "Diesel"], drives: ["4WD"], seats: 6 },
{ make: "Chevrolet", model: "Equinox", body: "SUV", price: 36000, trims: 3, fuels: ["Gas"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Chevrolet", model: "Bolt EUV", body: "SUV", price: 42000, trims: 2, fuels: ["Electric"], drives: ["FWD"], seats: 5 },
{ make: "Chevrolet", model: "Corvette", body: "Coupe", price: 98000, trims: 2, fuels: ["Gas"], drives: ["RWD"], seats: 2 },
{ make: "GMC", model: "Sierra 1500", body: "Truck", price: 66000, trims: 3, fuels: ["Gas", "Diesel"], drives: ["4WD"], seats: 6 },
{ make: "Hyundai", model: "Tucson", body: "SUV", price: 37000, trims: 3, fuels: ["Gas", "Hybrid", "Plug-in hybrid"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Hyundai", model: "Elantra", body: "Sedan", price: 27000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["FWD"], seats: 5, manual: true },
{ make: "Hyundai", model: "Ioniq 5", body: "SUV", price: 58000, trims: 3, fuels: ["Electric"], drives: ["AWD", "RWD"], seats: 5 },
{ make: "Kia", model: "Sportage", body: "SUV", price: 37000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Kia", model: "Telluride", body: "SUV", price: 55000, trims: 3, fuels: ["Gas"], drives: ["AWD"], seats: 8 },
{ make: "Kia", model: "EV6", body: "SUV", price: 60000, trims: 3, fuels: ["Electric"], drives: ["AWD", "RWD"], seats: 5 },
{ make: "Mazda", model: "CX-5", body: "SUV", price: 38000, trims: 3, fuels: ["Gas"], drives: ["AWD"], seats: 5 },
{ make: "Mazda", model: "Mazda3 Sport", body: "Hatchback", price: 31000, trims: 3, fuels: ["Gas"], drives: ["FWD", "AWD"], seats: 5, manual: true },
{ make: "Mazda", model: "MX-5", body: "Convertible", price: 43000, trims: 2, fuels: ["Gas"], drives: ["RWD"], seats: 2, manual: true },
{ make: "Subaru", model: "Outback", body: "SUV", price: 42000, trims: 3, fuels: ["Gas"], drives: ["AWD"], seats: 5 },
{ make: "Subaru", model: "Crosstrek", body: "SUV", price: 34000, trims: 3, fuels: ["Gas"], drives: ["AWD"], seats: 5, manual: true },
{ make: "Volkswagen", model: "Golf GTI", body: "Hatchback", price: 41000, trims: 2, fuels: ["Gas"], drives: ["FWD"], seats: 5, manual: true },
{ make: "Volkswagen", model: "Tiguan", body: "SUV", price: 40000, trims: 3, fuels: ["Gas"], drives: ["AWD"], seats: 7 },
{ make: "Tesla", model: "Model 3", body: "Sedan", price: 58000, trims: 3, fuels: ["Electric"], drives: ["RWD", "AWD"], seats: 5 },
{ make: "Tesla", model: "Model Y", body: "SUV", price: 64000, trims: 2, fuels: ["Electric"], drives: ["AWD"], seats: 5 },
{ make: "BMW", model: "3 Series", body: "Sedan", price: 58000, trims: 2, fuels: ["Gas"], drives: ["AWD"], seats: 5 },
{ make: "BMW", model: "X3", body: "SUV", price: 64000, trims: 2, fuels: ["Gas", "Plug-in hybrid"], drives: ["AWD"], seats: 5 },
{ make: "Mercedes-Benz", model: "GLC", body: "SUV", price: 66000, trims: 2, fuels: ["Gas"], drives: ["AWD"], seats: 5 },
{ make: "Audi", model: "Q5", body: "SUV", price: 63000, trims: 3, fuels: ["Gas", "Plug-in hybrid"], drives: ["AWD"], seats: 5 },
{ make: "Jeep", model: "Wrangler", body: "SUV", price: 56000, trims: 3, fuels: ["Gas", "Plug-in hybrid"], drives: ["4WD"], seats: 5, manual: true },
{ make: "Jeep", model: "Grand Cherokee", body: "SUV", price: 62000, trims: 3, fuels: ["Gas", "Plug-in hybrid"], drives: ["4WD"], seats: 5 },
{ make: "Ram", model: "1500", body: "Truck", price: 64000, trims: 3, fuels: ["Gas"], drives: ["4WD"], seats: 6 },
{ make: "Nissan", model: "Rogue", body: "SUV", price: 37000, trims: 3, fuels: ["Gas"], drives: ["AWD", "FWD"], seats: 5 },
{ make: "Nissan", model: "Sentra", body: "Sedan", price: 26000, trims: 3, fuels: ["Gas"], drives: ["FWD"], seats: 5 },
{ make: "Lexus", model: "RX", body: "SUV", price: 72000, trims: 3, fuels: ["Gas", "Hybrid"], drives: ["AWD"], seats: 5 },
{ make: "Volvo", model: "XC60", body: "SUV", price: 64000, trims: 3, fuels: ["Gas", "Plug-in hybrid"], drives: ["AWD"], seats: 5 },
{ make: "Mini", model: "Cooper Convertible", body: "Convertible", price: 44000, trims: 2, fuels: ["Gas"], drives: ["FWD"], seats: 4 },
{ make: "Chrysler", model: "Pacifica", body: "Minivan", price: 60000, trims: 3, fuels: ["Gas", "Plug-in hybrid"], drives: ["FWD", "AWD"], seats: 7 },
];
/** The paint each colour option shows as its swatch. */
export const COLOR_PAINTS: Record<Color, string> = {
Black: "#2B2D31",
White: "#E8E8E6",
Gray: "#6E7379",
Silver: "#B4B8BD",
Blue: "#2F5AA8",
Red: "#B5322E",
Green: "#3E6B52",
Brown: "#6B4F3A",
};
const COLOR_WEIGHTS: [Color, number][] = [
["White", 24],
["Black", 24],
["Gray", 18],
["Silver", 10],
["Blue", 10],
["Red", 8],
["Green", 3],
["Brown", 3],
];
export const THIS_YEAR = 2026;
const GENERATED = 240;
// A few hand-placed listings so common searches have matches.
type Fixed = Omit<Car, "id" | "condition" | "listed">;
const FIXED: Fixed[] = [
{ year: 2021, make: "Toyota", model: "RAV4", price: 29900, km: 58210, body: "SUV", fuel: "Gas", drive: "AWD", transmission: "Automatic", color: "Gray", seats: 5 },
{ year: 2021, make: "Toyota", model: "RAV4", price: 32495, km: 44120, body: "SUV", fuel: "Gas", drive: "AWD", transmission: "Automatic", color: "White", seats: 5 },
{ year: 2021, make: "Toyota", model: "RAV4", price: 36900, km: 31870, body: "SUV", fuel: "Hybrid", drive: "AWD", transmission: "Automatic", color: "Blue", seats: 5 },
{ year: 2021, make: "Toyota", model: "RAV4", price: 33795, km: 62400, body: "SUV", fuel: "Gas", drive: "AWD", transmission: "Automatic", color: "Green", seats: 5 },
{ year: 2021, make: "Toyota", model: "RAV4", price: 35995, km: 51230, body: "SUV", fuel: "Gas", drive: "AWD", transmission: "Automatic", color: "Black", seats: 5 },
{ year: 2022, make: "Honda", model: "Civic", price: 23995, km: 49800, body: "Sedan", fuel: "Gas", drive: "FWD", transmission: "Automatic", color: "White", seats: 5 },
{ year: 2022, make: "Honda", model: "Civic", price: 26495, km: 38210, body: "Sedan", fuel: "Gas", drive: "FWD", transmission: "Automatic", color: "Blue", seats: 5 },
{ year: 2022, make: "Honda", model: "Civic", price: 29895, km: 27640, body: "Sedan", fuel: "Gas", drive: "FWD", transmission: "Automatic", color: "Black", seats: 5 },
{ year: 2020, make: "Ford", model: "F-150", price: 38900, km: 84210, body: "Truck", fuel: "Gas", drive: "4WD", transmission: "Automatic", color: "White", seats: 6 },
{ year: 2020, make: "Ford", model: "F-150", price: 45495, km: 71840, body: "Truck", fuel: "Gas", drive: "4WD", transmission: "Automatic", color: "Black", seats: 6 },
{ year: 2020, make: "Ford", model: "F-150", price: 40250, km: 96300, body: "Truck", fuel: "Gas", drive: "4WD", transmission: "Automatic", color: "Red", seats: 6 },
{ year: 2022, make: "Toyota", model: "RAV4", price: 33995, km: 41200, body: "SUV", fuel: "Hybrid", drive: "AWD", transmission: "Automatic", color: "Silver", seats: 5 },
{ year: 2021, make: "Honda", model: "CR-V", price: 32900, km: 52100, body: "SUV", fuel: "Hybrid", drive: "AWD", transmission: "Automatic", color: "Gray", seats: 5 },
{ year: 2022, make: "Kia", model: "Sportage", price: 31495, km: 36700, body: "SUV", fuel: "Hybrid", drive: "AWD", transmission: "Automatic", color: "White", seats: 5 },
{ year: 2023, make: "Tesla", model: "Model 3", price: 37900, km: 28400, body: "Sedan", fuel: "Electric", drive: "RWD", transmission: "Automatic", color: "White", seats: 5 },
{ year: 2022, make: "Tesla", model: "Model 3", price: 41495, km: 44100, body: "Sedan", fuel: "Electric", drive: "AWD", transmission: "Automatic", color: "Black", seats: 5 },
];
function seeded(seed: number) {
let state = seed;
return () => {
state = (state + 0x6d2b79f5) | 0;
let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
};
}
// Each random draw stays in place even where its result is unused, so the list never shifts.
function generate(): Omit<Car, "id">[] {
const random = seeded(20261030);
const pick = <T,>(items: T[]) => items[Math.floor(random() * items.length)];
const between = (low: number, high: number) => low + random() * (high - low);
const color = (): Color => {
let roll = random() * COLOR_WEIGHTS.reduce((sum, [, weight]) => sum + weight, 0);
for (const [name, weight] of COLOR_WEIGHTS) {
roll -= weight;
if (roll <= 0) return name;
}
return "Gray";
};
const drafts: Omit<Car, "id" | "listed">[] = Array.from({ length: GENERATED }, (_, index) => {
const model = MODELS[index % MODELS.length];
const isNew = random() < 0.16;
const age = isNew ? 0 : Math.floor(between(1, 10));
const trimIndex = Math.floor(random() * model.trims);
const fuel = pick(model.fuels);
const km = isNew
? Math.round(between(5, 90))
: Math.round((age * between(11000, 19000)) / 100) * 100 + Math.round(between(0, 90));
// Value falls about 11% a year; higher trims and electrified cars cost more.
const value =
model.price * Math.pow(0.89, age) * (1 + trimIndex * 0.07) * (fuel === "Gas" || fuel === "Diesel" ? 1 : 1.08) - km * 0.02;
const spread = isNew ? 0 : Math.round(between(-2800, 2200) / 50) * 50;
const price = Math.max(4995, Math.round((value + spread) / 100) * 100 - 5);
random();
random();
const drive = pick(model.drives);
const transmission: Transmission = model.manual && random() < 0.3 ? "Manual" : "Automatic";
return {
make: model.make,
model: model.model,
body: model.body,
year: THIS_YEAR - age,
km,
price,
fuel,
drive,
transmission,
color: color(),
seats: model.seats,
condition: isNew ? "New" : "Used",
};
});
// Second pass, own seed: how many days ago each went up (newer listings are more common, as older cars sell), and
// some listings leave details out.
const blankRandom = seeded(20261031);
const blank = (share: number) => blankRandom() < share;
const skipOnce = new Set(["CR-V", "Crosstrek", "Tucson"]);
return drafts.map((car) => {
const listed = Math.min(120, Math.floor(-Math.log(1 - blankRandom()) * 21));
for (let i = 0; i < 3; i++) blankRandom();
const skips = car.condition === "Used" && skipOnce.delete(car.model);
if (!skips) blankRandom();
blankRandom();
blank(0.08);
const transmission = blank(0.45) ? null : car.transmission;
const drive = blank(0.08) ? null : car.drive;
const color = blank(0.07) ? null : car.color;
const seats = blank(0.06) ? null : car.seats;
const fuel = blank(0.03) ? null : car.fuel;
const km = car.condition === "Used" && blank(0.03) ? null : car.km;
return { ...car, transmission, drive, color, seats, fuel, km, listed };
});
}
// Days since each featured listing went up.
const FIXED_LISTED = [3, 12, 27, 6, 41, 9, 2, 18, 33, 14, 51, 5, 22, 11, 7, 16];
export const CARS: Car[] = [
...FIXED.map((car, index) => ({ ...car, id: `fixed-${index + 1}`, condition: "Used" as const, listed: FIXED_LISTED[index] })),
...generate().map((car, index) => ({ ...car, id: `car-${index + 1}` })),
];
export const MAKES = [...new Set(MODELS.map((model) => model.make))].sort();
export const MODELS_OF: Record<string, string[]> = Object.fromEntries(
MAKES.map((make) => [make, MODELS.filter((model) => model.make === make).map((model) => model.model)]),
);
export const BODIES: Body[] = ["SUV", "Sedan", "Truck", "Hatchback", "Coupe", "Minivan", "Van", "Convertible"];
export const FUELS: Fuel[] = ["Gas", "Hybrid", "Plug-in hybrid", "Electric", "Diesel"];
export const DRIVES: Drive[] = ["AWD", "4WD", "FWD", "RWD"];
export const TRANSMISSIONS: Transmission[] = ["Automatic", "Manual"];
export const CONDITIONS: Condition[] = ["New", "Used"];
export const COLORS: Color[] = ["Black", "White", "Gray", "Silver", "Blue", "Red", "Green", "Brown"];
```
### components/filters-ui/demo/cars-facets.ts
```ts
import { createFacets, histogram } from "../lib/facets";
import { formatsFor } from "../lib/format";
import { CARS, THIS_YEAR, TRANSMISSIONS, type Body, type Car, type Color, type Condition, type Drive, type Fuel, type Transmission } from "./cars";
/** A ticked make and the models that narrow it; no models means every model of that make. */
export type MakePick = { make: string; models: string[] };
export type CarFilters = {
condition: Condition | null;
priceMin: number | null;
priceMax: number | null;
makes: MakePick[];
bodies: Body[];
yearMin: number | null;
yearMax: number | null;
kmMax: number | null;
fuels: Fuel[];
drives: Drive[];
transmission: Transmission | null;
colors: Color[];
seatsMin: number | null;
/** How long ago the listing went up, in days, both ends included: 0 and 6 is the last 7 days. null is an open end. */
listedMin: number | null;
listedMax: number | null;
};
export const EMPTY_CAR_FILTERS: CarFilters = {
condition: null,
priceMin: null,
priceMax: null,
makes: [],
bodies: [],
yearMin: null,
yearMax: null,
kmMax: null,
fuels: [],
drives: [],
transmission: null,
colors: [],
seatsMin: null,
listedMin: null,
listedMax: null,
};
export type CarFacet =
| "condition"
| "price"
| "make"
| "body"
| "year"
| "km"
| "fuel"
| "drive"
| "transmission"
| "color"
| "seats"
| "listed";
export const PRICE_MIN = 0;
export const PRICE_MAX = 100000;
export const PRICE_STEP = 2500;
/** The price chart: 20 bars of $5,000 from $0 to $100k; a dearer car counts in the last bar. */
export const PRICE_BARS = 20;
/** The kilometres scale: a limit at KM_MAX is no limit. */
export const KM_MAX = 150000;
export const KM_STEP = 5000;
/** The kilometres chart: 15 bars of 10,000 km; a car past 150,000 km counts in the last bar. */
export const KM_BARS = 15;
/** Model years on offer, oldest first: one bar and one picker choice each. */
export const YEARS = Array.from({ length: 10 }, (_, i) => THIS_YEAR - 9 + i);
export const SEAT_MINIMUMS = [6, 7, 8];
// A car missing the detail fails a facet that is set, and passes one that is not.
const known = <T,>(value: T | null, test: (value: T) => boolean) => value !== null && test(value);
export const carFacets = createFacets<Car, CarFilters, CarFacet>({
condition: (car, f) => !f.condition || car.condition === f.condition,
price: (car, f) => (f.priceMin === null || car.price >= f.priceMin) && (f.priceMax === null || car.price <= f.priceMax),
make: (car, f) => !f.makes.length || f.makes.some((p) => p.make === car.make && (!p.models.length || p.models.includes(car.model))),
body: (car, f) => !f.bodies.length || f.bodies.includes(car.body),
year: (car, f) => (f.yearMin === null || car.year >= f.yearMin) && (f.yearMax === null || car.year <= f.yearMax),
km: (car, f) => f.kmMax === null || known(car.km, (km) => km <= f.kmMax!),
fuel: (car, f) => !f.fuels.length || known(car.fuel, (fuel) => f.fuels.includes(fuel)),
drive: (car, f) => !f.drives.length || known(car.drive, (drive) => f.drives.includes(drive)),
transmission: (car, f) => !f.transmission || car.transmission === f.transmission,
color: (car, f) => !f.colors.length || known(car.color, (color) => f.colors.includes(color)),
seats: (car, f) => f.seatsMin === null || known(car.seats, (seats) => seats >= f.seatsMin!),
listed: (car, f) => (f.listedMin === null || car.listed >= f.listedMin) && (f.listedMax === null || car.listed <= f.listedMax),
});
/** Cars per price bar among those matching every other filter, so the bars show what moving the price could reach. */
export const priceBuckets = (f: CarFilters, cars: readonly Car[] = CARS) =>
histogram(carFacets.pool(cars, f, "price"), (car) => car.price, { min: PRICE_MIN, max: PRICE_MAX, count: PRICE_BARS });
/** Cars per model year (in YEARS order) among those matching every other filter. */
export const yearBuckets = (f: CarFilters, cars: readonly Car[] = CARS) => {
const counts = carFacets.countBy(cars, f, "year", (car) => car.year);
return YEARS.map((year) => counts.get(year) ?? 0);
};
/** Cars per kilometres bar among those matching every other filter. A car with no kilometres on record has no bar. */
export const kmBuckets = (f: CarFilters, cars: readonly Car[] = CARS) =>
histogram(carFacets.pool(cars, f, "km"), (car) => car.km, { min: 0, max: KM_MAX, count: KM_BARS });
/** Seat options: Any, then "at least" each minimum, counted with the seats choice left out. Digits follow the locale. */
export const seatOptions = (f: CarFilters, cars: readonly Car[] = CARS, locale?: string) => [
{ value: null, label: "Any" },
...SEAT_MINIMUMS.map((min) => ({
value: min,
label: `${formatsFor(locale).plain(min)}+`,
count: carFacets.countIf(cars, f, "seats", (car) => car.seats !== null && car.seats >= min),
})),
];
/** New or used: Any, then Used and New, counted with the condition choice left out. */
export const conditionOptions = (f: CarFilters, cars: readonly Car[] = CARS) => {
const counts = carFacets.countBy(cars, f, "condition", (car) => car.condition);
return [
{ value: null, label: "Any" },
...(["Used", "New"] as const).map((c) => ({ value: c, label: c, count: counts.get(c) ?? 0 })),
];
};
/** Transmission: Any, then each gearbox, counted with the transmission choice left out. */
export const transmissionOptions = (f: CarFilters, cars: readonly Car[] = CARS) => {
const counts = carFacets.countBy(cars, f, "transmission", (car) => car.transmission);
return [{ value: null, label: "Any" }, ...TRANSMISSIONS.map((t) => ({ value: t, label: t, count: counts.get(t) ?? 0 }))];
};
/** Cars per fuel, with the fuel choice left out. A car with no fuel on record is not counted. */
export const fuelCounts = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.countBy(cars, f, "fuel", (car) => car.fuel);
/** Cars per day since listed (0 is today), with the listed choice left out. */
export const listedCounts = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.countBy(cars, f, "listed", (car) => car.listed);
/** Cars per drivetrain, with the drivetrain choice left out. */
export const driveCounts = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.countBy(cars, f, "drive", (car) => car.drive);
/** How many makes the short list shows before "All N makes". */
export const MAKES_UP_FRONT = 8;
export type MakeOption = {
value: string;
label: string;
count: number;
children: { value: string; label: string; count: number }[];
};
/**
* Every make in `cars`, the most listed first (MAKES_UP_FRONT of them), then the rest A to Z; each with its models in
* listing order. Counts leave the make and model choice out, except that a make narrowed to some models counts only those.
*/
export function makeOptions(f: CarFilters, cars: readonly Car[] = CARS): MakeOption[] {
const totals = new Map<string, number>();
const modelsOf = new Map<string, string[]>();
for (const car of cars) {
totals.set(car.make, (totals.get(car.make) ?? 0) + 1);
const models = modelsOf.get(car.make) ?? [];
if (!models.includes(car.model)) models.push(car.model);
modelsOf.set(car.make, models);
}
const narrowed = new Map(f.makes.map((p) => [p.make, p.models]));
const makeCounts = new Map<string, number>();
const modelCounts = new Map<string, number>();
for (const car of carFacets.pool(cars, f, "make")) {
const models = narrowed.get(car.make);
if (!models?.length || models.includes(car.model)) makeCounts.set(car.make, (makeCounts.get(car.make) ?? 0) + 1);
const key = `${car.make}\n${car.model}`;
modelCounts.set(key, (modelCounts.get(key) ?? 0) + 1);
}
const byName = (a: string, b: string) => a.localeCompare(b, "en");
const front = [...totals.keys()].sort((a, b) => totals.get(b)! - totals.get(a)! || byName(a, b)).slice(0, MAKES_UP_FRONT);
const rest = [...totals.keys()].filter((make) => !front.includes(make)).sort(byName);
return [...front, ...rest].map((make) => ({
value: make,
label: make,
count: makeCounts.get(make) ?? 0,
children: modelsOf.get(make)!.map((model) => ({ value: model, label: model, count: modelCounts.get(`${make}\n${model}`) ?? 0 })),
}));
}
/** Cars per body style, with the body choice left out. */
export const bodyCounts = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.countBy(cars, f, "body", (car) => car.body);
/** Cars per colour, with the colour choice left out. */
export const colorCounts = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.countBy(cars, f, "color", (car) => car.color);
export const matchingCars = (f: CarFilters, cars: readonly Car[] = CARS) => carFacets.filter(cars, f);
/** The fields each facet sets. */
export const FACET_FIELDS: Record<CarFacet, (keyof CarFilters)[]> = {
condition: ["condition"],
price: ["priceMin", "priceMax"],
make: ["makes"],
body: ["bodies"],
year: ["yearMin", "yearMax"],
km: ["kmMax"],
fuel: ["fuels"],
drive: ["drives"],
transmission: ["transmission"],
color: ["colors"],
seats: ["seatsMin"],
listed: ["listedMin", "listedMax"],
};
/** What one facet's Clear does. */
export function clearFacet(f: CarFilters, facet: CarFacet): CarFilters {
const e = EMPTY_CAR_FILTERS;
switch (facet) {
case "condition":
return { ...f, condition: e.condition };
case "price":
return { ...f, priceMin: null, priceMax: null };
case "make":
return { ...f, makes: [] };
case "body":
return { ...f, bodies: [] };
case "year":
return { ...f, yearMin: null, yearMax: null };
case "km":
return { ...f, kmMax: null };
case "fuel":
return { ...f, fuels: [] };
case "drive":
return { ...f, drives: [] };
case "transmission":
return { ...f, transmission: null };
case "color":
return { ...f, colors: [] };
case "seats":
return { ...f, seatsMin: null };
case "listed":
return { ...f, listedMin: null, listedMax: null };
}
}
/** The cars' words for numbers in one locale. Each takes the value alone, so it can go straight to a format prop. */
export type CarFormats = {
/** "$45,000", or "45.000 $" in de-DE. */
money: (value: number) => string;
/** "$45k" or "$97.5k" from a thousand up, "$950" below. */
moneyShort: (value: number) => string;
/** "1 car", "6 cars", "1,204 cars". The words stay English. */
carCount: (n: number) => string;
/** "50,000 km" */
km: (value: number) => string;
};
const carFormatsByLocale = new Map<string, CarFormats>();
/** The cars' formats for a locale. Default en-US. */
export function carFormats(locale?: string): CarFormats {
const f = formatsFor(locale);
let known = carFormatsByLocale.get(f.locale);
if (!known) {
known = { money: f.price, moneyShort: f.priceShort, carCount: (n) => (n === 1 ? `${f.number(1)} car` : `${f.number(n)} cars`), km: f.distance };
carFormatsByLocale.set(f.locale, known);
}
return known;
}
export const { money: formatMoney, moneyShort: formatMoneyShort, carCount: formatCarCount, km: formatKm } = carFormats();
/** "SUV", "SUV, Minivan", then two values and a count of the rest: "SUV, Minivan +1". */
export const listSummary = (values: readonly string[]) =>
values.length === 0 ? null : values.length <= 2 ? values.join(", ") : `${values.slice(0, 2).join(", ")} +${values.length - 2}`;
/** The closed card's summary for one facet, or null when the facet is unset. Numbers follow the locale; words stay English. */
export function summaryOf(f: CarFilters, facet: CarFacet, locale?: string): string | null {
const { moneyShort, km } = carFormats(locale);
const year = formatsFor(locale).plain;
switch (facet) {
case "condition":
return f.condition;
case "price":
if (f.priceMin !== null && f.priceMax !== null) return `${moneyShort(f.priceMin)} to ${moneyShort(f.priceMax)}`;
if (f.priceMax !== null) return `Under ${moneyShort(f.priceMax)}`;
if (f.priceMin !== null) return `Over ${moneyShort(f.priceMin)}`;
return null;
case "make":
return listSummary(f.makes.flatMap((p) => (p.models.length ? p.models : [p.make])));
case "body":
return listSummary(f.bodies);
case "year":
if (f.yearMin !== null && f.yearMin === f.yearMax) return year(f.yearMin);
if (f.yearMin !== null && f.yearMax !== null) return `${year(f.yearMin)} to ${year(f.yearMax)}`;
if (f.yearMin !== null) return `${year(f.yearMin)} or newer`;
if (f.yearMax !== null) return `${year(f.yearMax)} or older`;
return null;
case "km":
return f.kmMax === null ? null : `Under ${km(f.kmMax)}`;
case "fuel":
return listSummary(f.fuels);
case "drive":
return listSummary(f.drives);
case "transmission":
return f.transmission;
case "color":
return listSummary(f.colors);
case "seats":
return f.seatsMin === null ? null : `${year(f.seatsMin)}+`;
case "listed":
return listedSummary(f.listedMin, f.listedMax, locale);
}
}
/** "Today", "Last 7 days", "3 days ago" or "7 to 13 days ago": days rather than dates, so it reads the same on any day. */
function listedSummary(min: number | null, max: number | null, locale?: string): string | null {
if (min === null && max === null) return null;
const n = formatsFor(locale).number;
const daysAgo = (d: number) => (d === 0 ? "today" : d === 1 ? "yesterday" : `${n(d)} days ago`);
const from = min ?? 0;
if (max === null) return from === 0 ? null : from === 1 ? "Before today" : `${n(from)} or more days ago`;
if (from === 0) return max === 0 ? "Today" : `Last ${n(max + 1)} days`;
if (from === max) return daysAgo(from).replace(/^./, (c) => c.toUpperCase());
return `${n(from)} to ${n(max)} days ago`;
}
/** Card titles, in the designer's wording. */
export const CAR_FACET_TITLES: Record<CarFacet, string> = {
price: "Price",
seats: "Seats",
year: "Year",
km: "Kilometres",
condition: "New or used",
body: "Body style",
drive: "Drivetrain",
color: "Colour",
fuel: "Fuel",
make: "Make and model",
transmission: "Transmission",
listed: "Listed",
};
/** The board's three columns, as drawn. */
export const CAR_FACET_COLUMNS: CarFacet[][] = [
["price", "seats", "year", "km", "condition"],
["body", "drive"],
["color", "fuel", "make", "transmission"],
];
export const isEmpty = (f: CarFilters) =>
(Object.keys(CAR_FACET_TITLES) as CarFacet[]).every((facet) => summaryOf(f, facet) === null);
```
### components/filters-ui/lib/facets.ts
```ts
// Faceted counting for filter UIs.
//
// Each facet has a test that says whether an item passes that facet's current choice
// (and passes when the facet is unset). An option's count is taken with its own facet
// left out, so it tells how many items picking that option would show.
export type FacetTest<Item, State> = (item: Item, state: State) => boolean;
export type FacetTests<Item, State, Key extends string = string> = Record<Key, FacetTest<Item, State>>;
export type Facets<Item, State, Key extends string> = {
/** Does the item pass every facet, optionally leaving one out? */
matches: (item: Item, state: State, skip?: Key) => boolean;
/** Items that pass every facet. */
filter: (items: readonly Item[], state: State) => Item[];
/** Items that pass every facet except `facet`: the pool its own options are counted in. */
pool: (items: readonly Item[], state: State, facet: Key) => Item[];
/**
* Count per option value for `facet`, with that facet's own choice left out.
* `valueOf` may return one value, several, or null (the item has none and is not counted).
*/
countBy: <Value>(
items: readonly Item[],
state: State,
facet: Key,
valueOf: (item: Item) => Value | readonly Value[] | null | undefined,
) => Map<Value, number>;
/** How many items in the facet's pool satisfy `predicate`, e.g. "seats at least 7". */
countIf: (items: readonly Item[], state: State, facet: Key, predicate: (item: Item) => boolean) => number;
};
export function createFacets<Item, State, Key extends string>(
tests: FacetTests<Item, State, Key>,
): Facets<Item, State, Key> {
const keys = Object.keys(tests) as Key[];
const matches = (item: Item, state: State, skip?: Key) =>
keys.every((key) => key === skip || tests[key](item, state));
const pool = (items: readonly Item[], state: State, facet: Key) =>
items.filter((item) => matches(item, state, facet));
function countBy<Value>(
items: readonly Item[],
state: State,
facet: Key,
valueOf: (item: Item) => Value | readonly Value[] | null | undefined,
) {
const counts = new Map<Value, number>();
for (const item of items) {
if (!matches(item, state, facet)) continue;
const value = valueOf(item);
if (value === null || value === undefined) continue;
const list = (Array.isArray(value) ? value : [value]) as Value[];
for (const v of new Set(list)) counts.set(v, (counts.get(v) ?? 0) + 1);
}
return counts;
}
return {
matches,
pool,
countBy,
filter: (items, state) => items.filter((item) => matches(item, state)),
countIf: (items, state, facet, predicate) => {
let n = 0;
for (const item of items) if (matches(item, state, facet) && predicate(item)) n++;
return n;
},
};
}
/**
* Counts items into `count` equal buckets over [min, max], e.g. the bars of a range chart.
* A value past either end lands in the end bucket; null is not counted.
*/
export function histogram<Item>(
items: readonly Item[],
valueOf: (item: Item) => number | null | undefined,
{ min, max, count }: { min: number; max: number; count: number },
): number[] {
const buckets = Array.from({ length: count }, () => 0);
const size = (max - min) / count;
for (const item of items) {
const value = valueOf(item);
if (value === null || value === undefined || Number.isNaN(value)) continue;
buckets[Math.max(0, Math.min(count - 1, Math.floor((value - min) / size)))] += 1;
}
return buckets;
}
```
### components/filters-ui/filters/chip-group.tsx
```tsx
"use client";
import { useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { CountPill } from "../ui/count-pill";
import { foldOptions, ShowAllButton } from "../ui/show-all";
import { placeholderLabels, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
export type ChipOption<V extends string> = {
value: V;
label: string;
count: number;
};
export type ChipGroupProps<V extends string> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
options: readonly ChipOption<V>[];
value: readonly V[];
onChange: (value: V[]) => void;
/** Accessible name of the group. */
label: string;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** How many chips show before "Show all N". Chips that are on always show. Default 12. */
collapsedCount?: number;
};
// 32px high: a 20px line, 5px above and below and a 1px border. A name longer than the whole row wraps inside its chip.
const CHIP =
"inline-flex min-h-8 max-w-full min-w-0 items-center gap-1.5 rounded-[16px] border py-[5px] pe-1.5 ps-3 font-[inherit] text-start text-[14px] leading-5";
// Forced colours draw every chip's edge alike and drop fills, so a chosen chip takes the system highlight. Its colours
// stay as given: left to the browser, its words would sit on a backplate in the page colour.
const FORCED_ON =
"forced-colors:border-[Highlight] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-[CanvasText]";
const FORCED_ON_PILL = "forced-colors:bg-transparent forced-colors:text-[HighlightText]";
/** Placeholder chips while the options are on their way. */
const LOADING_CHIPS = 5;
/**
* Rounded toggle chips that wrap onto rows, each a name and a count. Several can be on. A long list shows its first
* collapsedCount chips, the ones that are on, and "Show all N" for the rest.
*/
export function ChipGroup<V extends string>({
options,
value,
onChange,
label,
formatCount,
countLabel: countLabelProp,
locale,
collapsedCount = 12,
status = "ready",
onRetry,
errorText,
emptyText,
disabled = false,
className,
...props
}: ChipGroupProps<V>) {
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
// An option turned off under the pointer or keyboard would become disabled at 0, or leave a folded list, and drop
// focus; it stays as it is until focus and the pointer have both left it.
const [kept, setKept] = useState<V | null>(null);
const [all, setAll] = useState(false);
const toggle = (v: V, button: HTMLButtonElement) => {
const on = value.includes(v);
setKept(on && (document.activeElement === button || button.matches(":hover")) ? v : null);
onChange(on ? value.filter((x) => x !== v) : [...value, v]);
};
// Its own status, or the loading frame of an item around it, such as a block's card.
const loading = useLoading().loading || status === "loading";
const { folds, shown } = foldOptions(options, {
collapsedCount,
expanded: all,
isOn: (o) => value.includes(o.value),
isKept: (o) => kept === o.value,
loading,
});
return (
<div role="group" aria-label={label} aria-disabled={disabled || undefined} className={cn("pt-0.5", className)} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} empty={options.length === 0} emptyText={emptyText} disabled={disabled}>
<div className="flex flex-wrap gap-2">
{loading && options.length === 0
? placeholderLabels(LOADING_CHIPS).map((name, i) => (
<span key={i} className={cn(CHIP, "border-[var(--fu-line,#404040)]")}>
<SkeletonText>{name}</SkeletonText> <CountPill count={0} className="rounded-full" />
</span>
))
: shown.map((option) => {
const on = value.includes(option.value);
return (
<button
key={option.value}
type="button"
aria-pressed={on}
aria-label={`${option.label}, ${countLabel(option.count)}`}
disabled={option.count === 0 && !on && kept !== option.value}
onBlur={(event) => kept === option.value && !event.currentTarget.matches(":hover") && setKept(null)}
onPointerLeave={(event) => kept === option.value && document.activeElement !== event.currentTarget && setKept(null)}
onClick={(event) => toggle(option.value, event.currentTarget)}
data-state={on ? "on" : "off"}
className={cn(
CHIP,
"cursor-pointer",
"transition-[background-color,border-color,color,scale,opacity] duration-200 ease-[cubic-bezier(0.42,0,0.58,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
// While loading, a chip that is on stays on; the others take a quieter edge.
on
? "border-[var(--fu-accent-soft,#8FAAFF)] bg-[var(--fu-selected,#1F2747)]"
: loading
? "border-[var(--fu-line,#404040)]"
: "border-[var(--fu-control-border,#737373)] enabled:hover:border-[var(--fu-control-hover,#A3A3A3)] enabled:hover:bg-[var(--fu-item-hover,#2A2A2A)]",
"disabled:cursor-not-allowed",
option.count === 0 && !on && !loading && "opacity-40",
on && FORCED_ON,
)}
>
<span aria-hidden="true" className={cn("min-w-0 [overflow-wrap:anywhere] text-[var(--fu-text,#F8F5F1)]", on && "forced-colors:text-[HighlightText]")}>
<SkeletonText>{option.label}</SkeletonText>
</span>{" "}
<CountPill aria-hidden="true" on={on} count={option.count} format={formatCount} locale={locale} className={cn("rounded-full", on && !loading && FORCED_ON_PILL)} />
</button>
);
})}
{folds && <ShowAllButton total={options.length} expanded={all} onToggle={() => setAll(!all)} locale={locale} />}
</div>
</StatusFrame>
</div>
);
}
```
### components/filters-ui/ui/count-pill.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { ARRIVING, SKELETON_FILL, useLoading } from "./skeleton";
export type CountPillProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
count: number;
/** "default": 20px high, 6px radius. "square": 18px high, 5px radius, 11px text. */
variant?: "default" | "square";
/** Selected look: accent fill, --fu-on-accent text. */
on?: boolean;
format?: (n: number) => string;
/** Formats the count when no format is given, e.g. "de-DE" prints 1.234. */
locale?: string;
/** A pulsing placeholder of the pill's own size. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
};
export function CountPill({ count, variant = "default", on = false, format, locale, loading: loadingProp, className, ...props }: CountPillProps) {
const state = useLoading();
const loading = loadingProp ?? state.loading;
const text = (format ?? formatsFor(locale).number)(count);
return (
<span
data-state={on ? "on" : "off"}
className={cn(
"inline-flex shrink-0 items-center justify-center font-medium tabular-nums",
"transition-[background-color,color] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
variant === "square"
? "h-[18px] min-w-5 rounded-[5px] px-[5px] text-[11px] leading-4"
: "h-5 min-w-[22px] rounded-[6px] px-1.5 text-[12px] leading-4",
loading
? SKELETON_FILL
: on
? "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)]"
: variant === "square"
? "bg-[var(--fu-pill-square,#333333)] text-[var(--fu-pill-text,#C8C8C8)]"
: "bg-[var(--fu-pill,rgb(255_255_255/0.1))] text-[var(--fu-pill-text,#C8C8C8)]",
className,
)}
{...props}
>
{/* While loading, the number holds the pill's width unseen; when it arrives it fades in once. */}
{loading ? (
<span key="skeleton" className="invisible">
{text}
</span>
) : state.arriving ? (
<span key="arrived" className={ARRIVING}>
{text}
</span>
) : (
text
)}
</span>
);
}
```
### components/filters-ui/ui/skeleton.tsx
```tsx
"use client";
import { createContext, useContext, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
/** What StatusFrame tells the pieces under it: draw placeholders, or the data has just arrived and fades in once. */
export type LoadingState = { loading: boolean; arriving: boolean };
export const LoadingContext = createContext<LoadingState>({ loading: false, arriving: false });
/** The loading state of the nearest StatusFrame. Outside one, nothing is loading. */
export const useLoading = () => useContext(LoadingContext);
/**
* The placeholder fill: --fu-skeleton, pulsing to half of it every 2s (Tailwind's animate-pulse). It holds still when
* reduced motion is asked for, and turns to the system's grey text colour in forced colours, so it never vanishes.
*/
export const SKELETON_FILL =
"animate-pulse bg-[var(--fu-skeleton,rgb(255_255_255/0.12))] in-data-[state=on]:bg-[var(--fu-skeleton-on,rgb(143_170_255/0.3))] motion-reduce:animate-none forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]";
/** Content that has just replaced a placeholder: it fades in once over 300ms as it is inserted, and never again. */
export const ARRIVING = "transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none";
export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;
/**
* A pulsing placeholder block with no size of its own: give it the size and corners of what it stands for, from the
* same classes, e.g. "h-5 min-w-[22px] rounded-[6px]" for a count pill. Hidden from screen readers; the StatusFrame
* around it says "Loading" once.
*/
export function Skeleton({ className, ...props }: SkeletonProps) {
return <span aria-hidden="true" data-skeleton="" className={cn("block rounded-[6px]", SKELETON_FILL, className)} {...props} />;
}
export type SkeletonTextProps = {
children: ReactNode;
/** Draws the placeholder. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
/** Classes for the placeholder's box while loading. */
className?: string;
};
/**
* Words that draw as a rounded bar while loading. The words stay in the layout, unseen, so the bar is exactly as wide
* and as many lines tall as they are, and nothing moves when they arrive; then they fade in once.
*/
export function SkeletonText({ children, loading, className }: SkeletonTextProps) {
const state = useLoading();
if (loading ?? state.loading) {
return (
<span key="skeleton" className={cn("relative inline-block max-w-full align-top", className)}>
<span className="invisible">{children}</span>
<Skeleton className="absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]" />
</span>
);
}
if (state.arriving) {
return (
<span key="arrived" className={ARRIVING}>
{children}
</span>
);
}
return <>{children}</>;
}
/**
* Stand-in names for a list whose options have not come yet: a mix of lengths, so the placeholders do not read as a
* grid. Never shown; only their widths are.
*/
export function placeholderLabels(count: number): string[] {
const words = ["Placeholder", "Short", "A longer name", "Medium one", "Tiny", "Another name", "Middle", "Fairly long one"];
return Array.from({ length: count }, (_, i) => words[i % words.length]);
}
```
### components/filters-ui/ui/show-all.tsx
```tsx
"use client";
import type { ButtonHTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
/**
* What a long list shows while folded: its first `collapsedCount` options and any that are on. Two hidden options are
* not worth a button, so the list folds only when it would hide three or more, and never while it is loading.
* `isKept` marks an option past the fold that was just turned off while it held focus or the pointer: it stays until
* both have left it, so focus is never dropped and nothing moves under the pointer.
*/
export function foldOptions<T>(
options: readonly T[],
{
collapsedCount,
expanded,
isOn,
isKept,
loading = false,
}: { collapsedCount: number; expanded: boolean; isOn: (option: T) => boolean; isKept?: (option: T) => boolean; loading?: boolean },
): { folds: boolean; shown: readonly T[] } {
const folds = !loading && options.length > collapsedCount + 2;
return {
folds,
shown: folds && !expanded ? options.filter((option, i) => i < collapsedCount || isOn(option) || isKept?.(option)) : options,
};
}
export type ShowAllButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children" | "onClick" | "type"> & {
/** How many options the whole list holds: "Show all 24". */
total: number;
/** The whole list shows; the button then reads "Show fewer". */
expanded: boolean;
onToggle: () => void;
/** Formats the number, e.g. "de-DE". Default "en-US". */
locale?: string;
};
/**
* The text button that opens a folded list, in the accent colour: "Show all N", then "Show fewer". A 1px line draws in
* under the words from the start edge while it is hovered or focused. It carries aria-expanded.
*/
export function ShowAllButton({ total, expanded, onToggle, locale, className, ...props }: ShowAllButtonProps) {
return (
<button
type="button"
aria-expanded={expanded}
onClick={onToggle}
className={cn(
"group/more relative inline-flex h-8 cursor-pointer items-center rounded-[6px] px-1 text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)]",
"transition-[color,scale] duration-200 hover:text-[var(--fu-accent-pale,#D1DDFF)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
className,
)}
{...props}
>
<span
className={cn(
"bg-[linear-gradient(currentColor,currentColor)] bg-[length:0%_1px] bg-[position:0_100%] rtl:bg-[position:100%_100%] bg-no-repeat pb-px",
"transition-[background-size] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"[@media(hover:hover)]:group-hover/more:bg-[length:100%_1px] group-focus-visible/more:bg-[length:100%_1px]",
)}
>
{expanded ? "Show fewer" : `Show all ${formatsFor(locale).number(total)}`}
</span>
</button>
);
}
```
### components/filters-ui/ui/status-frame.tsx
```tsx
"use client";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";
/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";
/**
* The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
* filter knows them all. Spread them into an item's own props type.
*/
export type StateProps = {
/** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
status?: Status;
/** Called by the Retry button. Without it the error line has no button. */
onRetry?: () => void;
/** The error line. Default "Couldn't load the options." */
errorText?: string;
/** The line shown in place of the options when there are none. Default "No options to show" */
emptyText?: string;
/** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
disabled?: boolean;
};
export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";
/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
type Mode = "ready" | "loading" | "error" | "empty";
/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);
export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
Omit<StateProps, "emptyText"> & {
/** There are no options: emptyText shows in place of the content. */
empty?: boolean;
emptyText?: ReactNode;
/** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
emptyArt?: string | ReactNode | null;
/** Words read once while loading. Default "Loading". */
loadingText?: string;
/** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
announce?: boolean;
retryLabel?: string;
children: ReactNode;
};
/**
* Wraps an item's content and gives it the shared states.
* - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
* placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
* - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
* status region that stays on the page.
* - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
* - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
* read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
* When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
* A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
* it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
* with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
* frame and let an inner frame around the part that fails speak.
*/
export function StatusFrame({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
empty = false,
emptyText = DEFAULT_EMPTY_TEXT,
emptyArt,
disabled = false,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
children,
...props
}: StatusFrameProps) {
const frame = useRef<HTMLDivElement>(null);
const outer = useLoading();
const saidAbove = useContext(SaidLoading);
const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";
// The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
const [lastStatus, setLastStatus] = useState(status);
const [arriving, setArriving] = useState(false);
if (status !== lastStatus) {
setLastStatus(status);
setArriving(lastStatus === "loading" && status === "ready");
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arriving]);
// Whether focus sat on a control inside, read just before a change of state is drawn.
const key = `${mode}|${disabled}`;
const drawnKey = useRef(key);
const focusWasInside = useRef(false);
if (key !== drawnKey.current && typeof document !== "undefined") {
const active = document.activeElement;
focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
}
useLayoutEffect(() => {
if (drawnKey.current === key) return;
drawnKey.current = key;
if (!focusWasInside.current) return;
focusWasInside.current = false;
const node = frame.current;
// The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
});
return (
<div
ref={frame}
tabIndex={-1}
data-status-frame=""
data-status={mode}
aria-busy={mode === "loading" || undefined}
className={cn(
"min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50 select-none",
className,
)}
{...props}
>
<SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
<LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
{mode === "empty" ? (
emptyArt === null ? (
<EmptyNote>{emptyText}</EmptyNote>
) : (
<EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
)
) : mode === "error" ? null : (
// display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
<fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
{children}
</fieldset>
)}
</LoadingContext.Provider>
</SaidLoading.Provider>
<StatusLine
status={mode === "loading" || mode === "error" ? mode : "ready"}
onRetry={onRetry}
errorText={errorText}
loadingText={saidAbove ? "" : loadingText}
announce={announce}
retryLabel={retryLabel}
/>
</div>
);
}
export type StatusLineProps = {
status?: Status;
/** Called by Retry. Without it the error line has no button. */
onRetry?: () => void;
errorText?: string;
loadingText?: string;
/** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
announce?: boolean;
retryLabel?: string;
/** Classes for the line while it shows an error, e.g. its margins. */
className?: string;
};
/**
* What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
* Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
* no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
* Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
*/
export function StatusLine({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
}: StatusLineProps) {
const error = status === "error";
const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
return (
// The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
<div className={error ? cn(ERROR_LINE, className) : "contents"}>
<p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
{error && <ErrorGlyph />}
{said && <span dir="auto">{said}</span>}
</p>
{error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
/**
* For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
* away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
* never dropped to the page.
*/
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
const drawn = useRef(key);
const had = useRef(false);
if (key !== drawn.current && typeof document !== "undefined") {
const active = document.activeElement;
had.current = !!scope.current && !!active && scope.current.contains(active);
}
useLayoutEffect(() => {
if (drawn.current === key) return;
drawn.current = key;
if (!had.current) return;
had.current = false;
const node = scope.current;
if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
});
}
```
### components/filters-ui/ui/art-search.ts
```ts
/**
* The picture for "nothing matches" and "nothing here": a glass magnifier on a clear background, drawn 56px.
* It is a file, not code: the shadcn install saves it as public/filters-ui/search.svg. Copying by hand, save
* https://filtersui.com/filters-ui/search.svg there, or point this at a picture of your own. With no file the empty
* states show their words alone.
*/
export const SEARCH_ART = "/filters-ui/search.svg";
```
### components/filters-ui/ui/empty-note.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyNoteProps = HTMLAttributes<HTMLDivElement> & {
/** A 16px glyph in currentColor before the words. */
icon?: ReactNode;
/** A button or link after the words, e.g. "Clear search". */
action?: ReactNode;
};
/**
* A quiet one-line note in place of a list that has nothing in it: dim 14px words, an optional glyph and an optional
* action. No illustration and no box, so it sits in the space the options would take.
*/
export function EmptyNote({ icon, action, className, children, ...props }: EmptyNoteProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2", className)} {...props}>
<p className="flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{icon && (
<span aria-hidden="true" className="mt-0.5 shrink-0 [&_svg]:size-4">
{icon}
</span>
)}
<span dir="auto">{children}</span>
</p>
{action}
</div>
);
}
```
### components/filters-ui/ui/empty-state.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
/** The picture above the words: an image address, drawn 56px square, or any node of that size. */
art?: string | ReactNode;
/** The one line that says what is missing. */
title: ReactNode;
/** A link or button under the words, such as "Clear search". */
action?: ReactNode;
/** A second, quieter line under the title. */
children?: ReactNode;
};
// Each part arrives once, a beat after the one above it: the picture comes into focus, the words rise into place.
const ENTER =
"transition-[opacity,filter,translate,scale] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none starting:opacity-0";
/**
* What a list shows in the room its options would take when it has none: a picture, one line and an action, stacked
* in the middle. For a single quiet line with no picture, use EmptyNote.
*/
export function EmptyState({ art, title, action, className, children, ...props }: EmptyStateProps) {
return (
<div className={cn("flex min-w-0 max-w-full flex-col items-center text-center", className)} {...props}>
{art && (
<span aria-hidden="true" className={cn("mb-3 block size-14 shrink-0", ENTER, "starting:scale-[0.82] starting:blur-[6px]")}>
{typeof art === "string" ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={art} alt="" width={56} height={56} loading="lazy" decoding="async" draggable={false} className="size-full object-contain select-none" />
) : (
art
)}
</span>
)}
<p dir="auto" className={cn("max-w-full text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]", ENTER, "delay-[60ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{title}
</p>
{children && (
<p dir="auto" className={cn("mt-1 max-w-full text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]", ENTER, "delay-[90ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{children}
</p>
)}
{action && <div className={cn("mt-2 max-w-full", ENTER, "delay-[120ms] starting:translate-y-1.5")}>{action}</div>}
</div>
);
}
```
### components/filters-ui/ui/inline-error.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { buttonClasses } from "./button-classes";
import { CircleAlertIcon } from "./icons";
export const DEFAULT_RETRY_LABEL = "Retry";
/** The error line's layout: the words at the start, Retry at the end, wrapping under them when space runs out. */
export const ERROR_LINE = "flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2";
/** The words: 14px, muted, with a 16px dim alert glyph before them. */
export const ERROR_TEXT = "flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]";
/** The alert glyph that leads the words. Hidden from screen readers. */
export function ErrorGlyph() {
return <CircleAlertIcon size={16} className="mt-0.5 shrink-0 text-[var(--fu-dim,#929292)]" />;
}
export type RetryButtonProps = {
onRetry: () => void;
label?: string;
className?: string;
};
/**
* A small grey button that is never shown disabled. Before it calls onRetry it hands focus to the StatusFrame around
* it, which stays on the page while the content reloads, so focus is never lost with the button.
*/
export function RetryButton({ onRetry, label = DEFAULT_RETRY_LABEL, className }: RetryButtonProps) {
return (
<button
type="button"
onClick={(event) => {
event.currentTarget.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
onRetry();
}}
className={buttonClasses({ variant: "secondary", size: "sm", className })}
>
{label}
</button>
);
}
export type InlineErrorProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** One short line in plain words, e.g. "Couldn't load the options." */
text: string;
/** Shows Retry. Without it the line stands alone. */
onRetry?: () => void;
retryLabel?: string;
};
/**
* A calm error in the component's own area: one muted line and a Retry button. The line is a polite status region, so
* it is read out when it appears. Inside a StatusFrame use the frame's status="error" instead: it keeps one region on
* the page for loading and errors alike.
*/
export function InlineError({ text, onRetry, retryLabel, className, ...props }: InlineErrorProps) {
return (
<div className={cn(ERROR_LINE, className)} {...props}>
<p role="status" className={ERROR_TEXT}>
<ErrorGlyph />
<span dir="auto">{text}</span>
</p>
{onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
```
### components/filters-ui/ui/button-classes.ts
```ts
import { cn } from "../lib/cn";
// The button looks as class names. Kept apart from button.tsx, a client module, so server pages can call them too.
export type ButtonVariant = "primary" | "secondary" | "ghost" | "quiet" | "quiet-accent";
export type ButtonSize = "sm" | "md" | "lg";
export const BUTTON_BASE = cn(
"relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] font-[inherit] font-medium whitespace-nowrap no-underline select-none",
"[-webkit-tap-highlight-color:transparent] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
"active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"aria-busy:cursor-progress aria-busy:active:scale-100",
);
const VARIANTS: Record<ButtonVariant, string> = {
primary:
"bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)] hover:bg-[var(--fu-accent-hover,#3450D4)] forced-colors:border forced-colors:border-[ButtonText]",
secondary:
"bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]",
ghost: "bg-transparent text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
quiet: "bg-transparent text-[var(--fu-mute,#BDBDBD)] hover:text-[var(--fu-text,#F8F5F1)]",
"quiet-accent":
"bg-transparent text-[var(--fu-accent-soft,#8FAAFF)] decoration-1 underline-offset-[5px] hover:text-[var(--fu-accent-pale,#D1DDFF)] [@media(hover:hover)]:hover:underline",
};
// Below 44px a touch screen gets a taller invisible target through ::after.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:content-['']";
const SIZES: Record<ButtonSize, { box: string; before: string; after: string }> = {
sm: { box: cn("h-8 gap-1.5 px-3 text-[13px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-1.5"), before: "ps-2.5", after: "pe-2.5" },
md: { box: cn("h-10 gap-2 px-3.5 text-[15px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-0.5"), before: "ps-3", after: "pe-3" },
lg: { box: "h-11 gap-2 px-4 text-[15px] leading-5 [&_svg]:size-[18px]", before: "ps-3.5", after: "pe-3.5" },
};
/** The classes of a button, for a link or a router link that should look like one. */
export function buttonClasses({
variant = "primary",
size = "md",
before = false,
after = false,
className,
}: { variant?: ButtonVariant; size?: ButtonSize; before?: boolean; after?: boolean; className?: string } = {}) {
return cn(BUTTON_BASE, VARIANTS[variant], SIZES[size].box, before && SIZES[size].before, after && SIZES[size].after, className);
}
```
### components/filters-ui/ui/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/filters/color-swatches.tsx
```tsx
"use client";
import { useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { foldOptions, ShowAllButton } from "../ui/show-all";
import { ARRIVING, placeholderLabels, SKELETON_FILL, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
export type ColorSwatchOption<V extends string> = {
value: V;
label: string;
/** Any CSS colour for the dot. */
color: string;
count: number;
};
export type ColorSwatchesProps<V extends string> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
options: readonly ColorSwatchOption<V>[];
value: readonly V[];
onChange: (value: V[]) => void;
/** Accessible name of the group. */
label: string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** How many swatches show before "Show all N". Swatches that are on always show. Default 12. */
collapsedCount?: number;
};
const SWATCH = "flex min-w-0 flex-col items-center gap-1 rounded-[12px] pt-3 pb-1 font-[inherit] text-[13px] leading-[18px] text-[var(--fu-swatch-text,#EDEAE6)]";
// A long name wraps at its spaces under the dot, centred; a single word too long for the column ends in an ellipsis
// (the swatch's accessible name keeps it whole), so a word is never broken in two.
const NAME = "max-w-full overflow-hidden px-1 text-center text-ellipsis";
// Forced colours drop fills, so a chosen swatch takes the system highlight. Its colours stay as given: left to the
// browser, its name would sit on a backplate in the page colour.
const FORCED_ON =
"forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-offset-2 forced-colors:focus-visible:outline-[CanvasText]";
/** Placeholder swatches while the options are on their way. */
const LOADING_SWATCHES = 8;
/**
* A four-column grid of colour dots with their names. Several can be on. A long list shows its first collapsedCount
* swatches, the ones that are on, and "Show all N" for the rest.
*/
export function ColorSwatches<V extends string>({
options,
value,
onChange,
label,
countLabel: countLabelProp,
locale,
collapsedCount = 12,
status = "ready",
onRetry,
errorText,
emptyText,
disabled = false,
className,
...props
}: ColorSwatchesProps<V>) {
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
// An option turned off under the pointer or keyboard would become disabled at 0, or leave a folded list, and drop
// focus; it stays as it is until focus and the pointer have both left it.
const [kept, setKept] = useState<V | null>(null);
const toggle = (v: V, button: HTMLButtonElement) => {
const on = value.includes(v);
setKept(on && (document.activeElement === button || button.matches(":hover")) ? v : null);
onChange(on ? value.filter((x) => x !== v) : [...value, v]);
};
const [all, setAll] = useState(false);
// Its own status, or the loading frame of an item around it, such as a block's card.
const loading = useLoading().loading || status === "loading";
const { folds, shown } = foldOptions(options, {
collapsedCount,
expanded: all,
isOn: (o) => value.includes(o.value),
isKept: (o) => kept === o.value,
loading,
});
return (
<div role="group" aria-label={label} aria-disabled={disabled || undefined} className={className} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} empty={options.length === 0} emptyText={emptyText} disabled={disabled}>
<div className="grid grid-cols-4 gap-2">
{loading && options.length === 0
? placeholderLabels(LOADING_SWATCHES).map((name, i) => (
<span key={i} className={SWATCH}>
<Dot color="" on={false} />
<span className={NAME}>
<SkeletonText>{name.slice(0, 6)}</SkeletonText>
</span>
</span>
))
: shown.map((option) => {
const on = value.includes(option.value);
// Nothing has this colour with the other filters as they are.
const none = option.count === 0 && !on && !loading;
return (
<button
key={option.value}
type="button"
aria-pressed={on}
aria-label={`${option.label}, ${countLabel(option.count)}`}
disabled={option.count === 0 && !on && kept !== option.value}
onBlur={(event) => kept === option.value && !event.currentTarget.matches(":hover") && setKept(null)}
onPointerLeave={(event) => kept === option.value && document.activeElement !== event.currentTarget && setKept(null)}
onClick={(event) => toggle(option.value, event.currentTarget)}
data-state={on ? "on" : "off"}
className={cn(
SWATCH,
"group/swatch relative cursor-pointer",
"transition-[background-color,scale,opacity] duration-[260ms] ease-[cubic-bezier(0.22,1,0.36,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
on ? "bg-[var(--fu-wash,rgb(255_255_255/0.08))]" : "enabled:hover:bg-[var(--fu-wash,rgb(255_255_255/0.08))]",
"disabled:cursor-not-allowed",
none && "opacity-40 disabled:hover:opacity-80",
on && FORCED_ON,
)}
>
<Dot color={option.color} on={on} />
<span
aria-hidden="true"
className={cn(NAME, none && "transition-opacity duration-150 motion-reduce:transition-none group-disabled/swatch:group-hover/swatch:opacity-0")}
>
<SkeletonText>{option.label}</SkeletonText>
</span>
{/* A swatch shows no count, so pointing at one that is off says why, on its name's first line. */}
{none && (
<span
aria-hidden="true"
className="absolute inset-x-0 top-11 truncate px-1 text-center opacity-0 transition-opacity duration-150 motion-reduce:transition-none group-disabled/swatch:group-hover/swatch:opacity-100"
>
{countLabel(0)}
</span>
)}
</button>
);
})}
{folds && <ShowAllButton total={options.length} expanded={all} onToggle={() => setAll(!all)} locale={locale} className="col-span-4 justify-self-start" />}
</div>
</StatusFrame>
</div>
);
}
/**
* The 28px dot. While loading it is a round placeholder with no paint (a chosen one keeps its ring); the paint fades in
* once when it arrives.
*/
function Dot({ color, on }: { color: string; on: boolean }) {
const { loading, arriving } = useLoading();
return (
<span
key={loading ? "skeleton" : "paint"}
aria-hidden="true"
className={cn(
"size-7 shrink-0 rounded-full border-2",
"transition-[border-color,box-shadow] duration-[260ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
on
? "border-[var(--fu-text,#F8F5F1)] shadow-[0_0_0_3px_color-mix(in_srgb,var(--fu-text,#F8F5F1)_18%,transparent)] forced-colors:border-[HighlightText]"
: loading
? "border-transparent"
: "border-[var(--fu-control-border,#737373)] shadow-[0_0_0_0_color-mix(in_srgb,var(--fu-text,#F8F5F1)_18%,transparent)] group-enabled/swatch:group-hover/swatch:border-[color-mix(in_srgb,var(--fu-control-border,#737373),var(--fu-text,#F8F5F1))]",
// A swatch's paint is its meaning, so forced colours keep it.
loading ? SKELETON_FILL : "forced-colors:[forced-color-adjust:none]",
arriving && ARRIVING,
)}
style={loading ? undefined : { backgroundColor: color }}
/>
);
}
```
### components/filters-ui/filters/icon-tiles.tsx
```tsx
"use client";
import { useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { CountPill } from "../ui/count-pill";
import { foldOptions, ShowAllButton } from "../ui/show-all";
import { ARRIVING, placeholderLabels, Skeleton, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
export type IconTileOption<V extends string> = {
value: V;
label: string;
/** Any SVG. It draws in currentColor; `var(--tile-bg)` is the tile's own background, for cut-outs. */
icon: ReactNode;
count: number;
};
export type IconTilesProps<V extends string> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
options: readonly IconTileOption<V>[];
value: readonly V[];
onChange: (value: V[]) => void;
/** Accessible name of the group. */
label: string;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** How many tiles show before "Show all N". Tiles that are on always show. Default 8. */
collapsedCount?: number;
};
const TILE = "flex min-w-0 flex-col gap-1.5 rounded-[16px] border px-3 py-2.5 text-start font-[inherit]";
// A long name wraps at its spaces, with the count beside its first line; a single word too long for the tile ends in
// an ellipsis (the tile's accessible name keeps it whole), so a word is never broken in two.
const NAME_ROW = "flex min-w-0 items-start justify-between gap-1";
const NAME = "min-w-0 overflow-hidden text-[14px] leading-5 text-ellipsis text-[var(--fu-text,#F8F5F1)]";
// Forced colours draw every tile's edge alike and drop fills, so a chosen tile takes the system highlight. Its colours
// stay as given: left to the browser, its words would sit on a backplate in the page colour.
const FORCED_ON =
"forced-colors:border-[Highlight] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:[--tile-bg:Highlight] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-[CanvasText]";
const FORCED_ON_PILL = "forced-colors:bg-transparent forced-colors:text-[HighlightText]";
/** Placeholder tiles while the options are on their way. */
const LOADING_TILES = 4;
/**
* A two-column grid of toggle tiles, each an icon over a name and a count. Several can be on. A long list shows its
* first collapsedCount tiles, the ones that are on, and "Show all N" for the rest.
*/
export function IconTiles<V extends string>({
options,
value,
onChange,
label,
formatCount,
countLabel: countLabelProp,
locale,
collapsedCount = 8,
status = "ready",
onRetry,
errorText,
emptyText,
disabled = false,
className,
...props
}: IconTilesProps<V>) {
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
// An option turned off under the pointer or keyboard would become disabled at 0, or leave a folded list, and drop
// focus; it stays as it is until focus and the pointer have both left it.
const [kept, setKept] = useState<V | null>(null);
const toggle = (v: V, button: HTMLButtonElement) => {
const on = value.includes(v);
setKept(on && (document.activeElement === button || button.matches(":hover")) ? v : null);
onChange(on ? value.filter((x) => x !== v) : [...value, v]);
};
const [all, setAll] = useState(false);
// Its own status, or the loading frame of an item around it, such as a block's card.
const loading = useLoading().loading || status === "loading";
const { folds, shown } = foldOptions(options, {
collapsedCount,
expanded: all,
isOn: (o) => value.includes(o.value),
isKept: (o) => kept === o.value,
loading,
});
return (
<div role="group" aria-label={label} aria-disabled={disabled || undefined} className={className} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} empty={options.length === 0} emptyText={emptyText} disabled={disabled}>
<div className="grid grid-cols-2 gap-2">
{loading && options.length === 0
? placeholderLabels(LOADING_TILES).map((name, i) => (
<span key={i} className={cn(TILE, "border-[var(--fu-line,#404040)]")}>
<TileIcon>{null}</TileIcon>
<span className={NAME_ROW}>
<span className={NAME}>
<SkeletonText>{name}</SkeletonText>
</span>{" "}
<CountPill variant="square" count={0} className="mt-px" />
</span>
</span>
))
: shown.map((option) => {
const on = value.includes(option.value);
return (
<button
key={option.value}
type="button"
aria-pressed={on}
aria-label={`${option.label}, ${countLabel(option.count)}`}
disabled={option.count === 0 && !on && kept !== option.value}
onBlur={(event) => kept === option.value && !event.currentTarget.matches(":hover") && setKept(null)}
onPointerLeave={(event) => kept === option.value && document.activeElement !== event.currentTarget && setKept(null)}
onClick={(event) => toggle(option.value, event.currentTarget)}
data-state={on ? "on" : "off"}
className={cn(
TILE,
"group/tile cursor-pointer",
"bg-[var(--tile-bg)] [--tile-bg:var(--fu-card,#1F1F1F)]",
"transition-[background-color,border-color,color,scale,opacity] duration-200 ease-[cubic-bezier(0.42,0,0.58,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"[&_svg_*]:transition-[fill,stroke] [&_svg_*]:duration-200 motion-reduce:[&_svg_*]:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
// While loading, a tile that is on stays on; the others take a quieter edge.
on
? "border-[var(--fu-accent-soft,#8FAAFF)] text-[var(--fu-accent-soft,#8FAAFF)] [--tile-bg:var(--fu-selected,#1F2747)]"
: loading
? "border-[var(--fu-line,#404040)] text-[var(--fu-mute,#BDBDBD)]"
: "border-[var(--fu-control-border,#737373)] text-[var(--fu-mute,#BDBDBD)] enabled:hover:border-[var(--fu-control-hover,#A3A3A3)] enabled:hover:text-[var(--fu-accent-soft,#8FAAFF)] enabled:hover:[--tile-bg:var(--fu-item-hover,#2A2A2A)]",
"disabled:cursor-not-allowed",
option.count === 0 && !on && !loading && "opacity-40",
on && FORCED_ON,
)}
>
<TileIcon>{option.icon}</TileIcon>
<span aria-hidden="true" className={NAME_ROW}>
<span className={cn(NAME, on && "forced-colors:text-[HighlightText]")}>
<SkeletonText>{option.label}</SkeletonText>
</span>{" "}
<CountPill variant="square" on={on} count={option.count} format={formatCount} locale={locale} className={cn("mt-px", on && !loading && FORCED_ON_PILL)} />
</span>
</button>
);
})}
{folds && <ShowAllButton total={options.length} expanded={all} onToggle={() => setAll(!all)} locale={locale} className="col-span-2 justify-self-start" />}
</div>
</StatusFrame>
</div>
);
}
/** The icon row: a rounded placeholder of the icon's height while loading; the icon fades in once when it arrives. */
function TileIcon({ children }: { children: ReactNode }) {
const { loading, arriving } = useLoading();
return (
<span key={loading ? "skeleton" : "icon"} aria-hidden="true" className={cn("flex h-7 justify-center [&>svg]:h-7 [&>svg]:w-auto", arriving && ARRIVING)}>
{loading ? <Skeleton className="h-7 w-16 rounded-[10px]" /> : children}
</span>
);
}
```
### components/filters-ui/filters/range-histogram.tsx
```tsx
"use client";
import { useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import type { NumberDrag } from "../ui/drag-handle";
import { RangeChart, type RangeValue } from "../ui/range-chart";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextField } from "../ui/text-field";
export type RangeHistogramProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
min: number;
max: number;
step: number;
value: RangeValue;
onChange: (value: RangeValue) => void;
/** Item count per bar, spread evenly from min to max. */
buckets?: readonly number[];
/** Field, tooltip and screen-reader text for a value, e.g. "$45,000". Default: the number in the locale. */
format?: (value: number) => string;
/**
* Reads a typed value. Default: the first number in the text, read with the locale's marks ("45.000" is 45000 in
* de-DE), with an optional k or m suffix, or null when there is none.
*/
parse?: (text: string) => number | null;
/** Formats and reads numbers by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** Tooltip text while the high end is open. Default: the top value and a plus. */
openLabel?: string;
/** One handle and one field, for an upper limit only. */
single?: boolean;
/** Field placeholders. Default "Minimum" and "Maximum". */
placeholders?: { low?: string; high?: string };
/** Accessible names of the handles and fields, e.g. "Lowest price". Default: the placeholders. */
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;
/** Says loading and errors out loud. Off when the chart sits inside another filter that says them once, as in Budget. Default true. */
announce?: boolean;
};
/** A range chart with typed Minimum and Maximum fields under it, kept in step both ways. */
export function RangeHistogram({
min,
max,
step,
value,
onChange,
buckets,
format: formatProp,
parse: parseProp,
locale,
openLabel,
single = false,
placeholders,
labels,
barScale,
status = "ready",
onRetry,
errorText = "Couldn't load the counts.",
emptyText = "No items to show",
disabled = false,
announce = true,
className,
...props
}: RangeHistogramProps) {
const formats = formatsFor(locale);
const format = formatProp ?? formats.number;
const parse = parseProp ?? formats.readNumber;
const lowPlaceholder = placeholders?.low ?? "Minimum";
const highPlaceholder = placeholders?.high ?? "Maximum";
const lowLabel = labels?.low ?? lowPlaceholder;
const highLabel = labels?.high ?? highPlaceholder;
// The handle a field is dragging, and where: the chart moves it and raises its bars as in a drag of its own.
const [held, setHeld] = useState<{ handle: "low" | "high"; value: number } | null>(null);
const holding = (handle: "low" | "high") => (at: number | null) => setHeld(at === null ? null : { handle, value: at });
// A typed number snaps outwards to the step, so nothing typed is left out, and stays inside the range, one step clear of the other end.
// An empty field, or a value at the very end, leaves that end open.
const commit = (end: 0 | 1, typed: number | null) => {
const next: RangeValue = [single ? null : value[0], value[1]];
if (typed === null) next[end] = null;
else {
const round = end === 0 ? Math.floor : Math.ceil;
const snapped = Math.min(max, Math.max(min, min + round((typed - min) / step) * step));
if (end === 0) {
const ceiling = (value[1] ?? max) - step;
next[0] = snapped <= min ? null : Math.min(snapped, ceiling);
} else {
const floor = (single ? min : (value[0] ?? min)) + step;
next[1] = snapped >= max ? null : Math.max(snapped, floor);
}
}
if (next[0] !== value[0] || next[1] !== value[1]) onChange(next);
};
// The frame dims and blocks everything while disabled, so the chart and fields are not dimmed a second time.
return (
<div className={cn("pt-1", className)} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled} announce={announce}>
<RangeChart
min={min}
max={max}
step={step}
value={value}
onChange={onChange}
buckets={buckets}
format={format}
openLabel={openLabel}
single={single}
labels={{ low: lowLabel, high: highLabel }}
barScale={barScale}
held={held}
locale={locale}
emptyText={emptyText}
/>
<div className={cn("mt-3 grid gap-2", single ? "grid-cols-1" : "grid-cols-[repeat(auto-fit,minmax(min(100%,7rem),1fr))]")}>
{!single && (
<RangeField
value={value[0]}
format={format}
parse={parse}
label={lowLabel}
placeholder={lowPlaceholder}
onCommit={(typed) => commit(0, typed)}
scale={{ min, max, step, emptyAt: "min", ceiling: (value[1] ?? max) - step, onHold: holding("low") }}
/>
)}
<RangeField
value={value[1]}
format={format}
parse={parse}
label={highLabel}
placeholder={highPlaceholder}
onCommit={(typed) => commit(1, typed)}
scale={{ min, max, step, emptyAt: "max", floor: (single ? min : (value[0] ?? min)) + step, onHold: holding("high") }}
/>
</div>
</StatusFrame>
</div>
);
}
type RangeFieldProps = {
value: number | null;
format: (value: number) => string;
parse: (text: string) => number | null;
label: string;
placeholder: string;
onCommit: (value: number | null) => void;
/** The scale the field's drag handle moves along. */
scale: Omit<NumberDrag, "value" | "onChange">;
};
// Shows the formatted value; while focused it holds what the person types, and commits on Enter or blur. Dragging its
// handle commits each step.
function RangeField({ value, format, parse, label, placeholder, onCommit, scale }: RangeFieldProps) {
const [draft, setDraft] = useState<string | null>(null);
const shown = value === null ? "" : format(value);
const commit = () => {
if (draft === null) return;
setDraft(null);
const typed = draft.trim() ? parse(draft) : null;
// Text that reads as no number puts the field back rather than dropping the limit.
if (draft.trim() && (typed === null || !Number.isFinite(typed))) return;
onCommit(typed);
};
return (
<TextField
label={label}
placeholder={placeholder}
inputMode="numeric"
autoComplete="off"
enterKeyHint="done"
value={draft ?? shown}
onChange={setDraft}
onClear={() => {
setDraft(null);
onCommit(null);
}}
onBlur={commit}
drag={{
...scale,
value,
onChange: (dragged) => {
setDraft(null);
onCommit(dragged);
},
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
commit();
} else if (event.key === "Escape" && draft !== null) {
event.stopPropagation();
setDraft(null);
}
}}
inputClassName="tabular-nums"
/>
);
}
```
### components/filters-ui/ui/drag-handle.tsx
```tsx
"use client";
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
export type NumberDrag = {
/** The number the field holds; null while it is empty. */
value: number | null;
/** The scale the field's width stands for. */
min: number;
max: number;
/** Dragged values snap to this. */
step: number;
onChange: (value: number) => void;
/** Where the handle stands while the field is empty. Default "min". */
emptyAt?: "min" | "max";
/** The lowest and highest value a drag may reach, inside min and max: the other end of a range, say. */
floor?: number;
ceiling?: number;
/**
* Called on each move of a drag with the value under the pointer, before it snaps to a step, and with null when the
* handle is let go: for a chart that should move with the handle.
*/
onHold?: (value: number | null) => void;
};
type Press = { start: number; width: number; rtl: boolean; grab: number; x: number; last: number | null; moved: boolean; settled: boolean };
/**
* Turns a number field into a slider as well. With a mouse over the field a thin handle shows where the value stands
* along the field's width; dragging it fills the field up to the handle and moves the value in steps. A press that does
* not move puts the caret in the field instead, with its text picked. The field needs the classes "group/field relative
* isolate": the fill and the handle are drawn behind its text, and only a strip over the handle takes the pointer.
* While a drag runs the layer carries data-dragging, which a field that grows with its text can use to hold its width.
* With the pointer on the handle itself it grows and takes the accent colour, as it does while dragged, so it reads as
* the thing to grab. The accent keeps the digits it crosses readable, which a light handle would not.
*/
export function DragHandle({ drag, input, pad = 12 }: { drag: NumberDrag; input: RefObject<HTMLInputElement | null>; pad?: number }) {
const { value, min, max, step, onChange, emptyAt = "min" } = drag;
const strip = useRef<HTMLSpanElement>(null);
const press = useRef<Press | null>(null);
const [dragging, setDragging] = useState(false);
const [near, setNear] = useState(false);
const hold = useRef(drag.onHold);
hold.current = drag.onHold;
const span = max - min || 1;
const share = (n: number) => Math.min(1, Math.max(0, (n - min) / span));
const at = share(value ?? (emptyAt === "max" ? max : min));
// A CSS variable set on the field while dragging takes over from the value, so the handle follows the pointer between steps.
const place = `calc(${pad}px + var(--drag-at, ${at}) * (100% - ${pad * 2}px))`;
const pointerShare = (x: number, p: Press) => {
const f = (x - p.start) / p.width;
return p.rtl ? 1 - f : f;
};
/** Takes the field's box as it is now and keeps the handle where the pointer holds it. */
const measure = (p: Press, x: number, held: number) => {
const box = strip.current?.parentElement?.getBoundingClientRect();
if (!box) return;
p.start = box.left + pad;
p.width = Math.max(1, box.width - pad * 2);
p.grab = pointerShare(x, p) - held;
};
// A drag cut short by the field going away (loading, disabled) must not leave its place on the field.
useEffect(() => {
const field = strip.current?.parentElement;
return () => {
field?.style.removeProperty("--drag-at");
if (press.current?.moved) hold.current?.(null);
};
}, []);
const down = (event: PointerEvent<HTMLSpanElement>) => {
// A frame turns its filter off with a disabled fieldset; the strip is no control, so it asks the field.
if (event.button !== 0 || !strip.current || input.current?.matches(":disabled")) return;
// Keeps the press from starting a text selection or moving focus; a press that never moves focuses the field on release.
event.preventDefault();
const p: Press = { start: 0, width: 1, rtl: isRtl(strip.current), grab: 0, x: event.clientX, last: value, moved: false, settled: false };
measure(p, event.clientX, at);
press.current = p;
event.currentTarget.setPointerCapture(event.pointerId);
};
const move = (event: PointerEvent<HTMLSpanElement>) => {
const p = press.current;
if (!p) return;
if (!p.moved) {
if (Math.abs(event.clientX - p.x) < 3) return;
// A field that grows with its text takes its widest size for the drag (see data-dragging); the next move
// measures it at that size, so the handle stays under the pointer from then on.
p.moved = true;
setDragging(true);
return;
}
if (!p.settled) {
p.settled = true;
measure(p, event.clientX, share(p.last ?? (emptyAt === "max" ? max : min)));
}
const floor = drag.floor ?? min;
const ceiling = drag.ceiling ?? max;
const to = Math.min(share(ceiling), Math.max(share(floor), pointerShare(event.clientX, p) - p.grab));
strip.current?.parentElement?.style.setProperty("--drag-at", String(to));
drag.onHold?.(min + to * span);
// Snapped to the step, kept between the floor and the ceiling (a typed floor may sit off the steps), and written
// with the step's own decimals, so 0.1 steps do not come out as 0.30000000000000004.
const snapped = Math.min(ceiling, Math.max(floor, min + Math.round((to * span) / step) * step));
const next = Number(snapped.toFixed((String(step).split(".")[1] ?? "").length));
if (next !== p.last) {
p.last = next;
onChange(next);
}
};
const up = (event: PointerEvent<HTMLSpanElement>, cancelled = false) => {
const p = press.current;
if (!p) return;
press.current = null;
strip.current?.parentElement?.style.removeProperty("--drag-at");
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(false);
if (p.moved) drag.onHold?.(null);
if (!p.moved && !cancelled) {
input.current?.focus();
input.current?.select();
}
};
return (
<>
<span
aria-hidden="true"
data-dragging={dragging || undefined}
data-near={near || dragging || undefined}
className="group/drag pointer-events-none absolute inset-0 -z-10 overflow-hidden rounded-[inherit]"
>
<span
className="absolute inset-y-0 inset-s-0 bg-[var(--fu-wash,rgb(255_255_255/0.08))] opacity-0 transition-opacity duration-200 motion-reduce:transition-none group-data-[dragging]/drag:opacity-100"
style={{ width: place }}
/>
<span
// Centred on its place with a start margin, which follows the field's own direction: a left-to-right
// number pill keeps it right inside a right-to-left page, where a mirrored translate would not.
className={cn(
"absolute top-1/2 -ms-[1.5px] h-5 w-[3px] -translate-y-1/2 rounded-full bg-[var(--fu-control-border,#737373)] opacity-0 in-[fieldset:disabled]:hidden",
"transition-[opacity,background-color,scale] duration-150 motion-reduce:transition-none forced-colors:bg-[CanvasText]",
"pointer-fine:group-hover/field:opacity-100 group-data-[near]/drag:bg-[var(--fu-accent,#3B57E6)] group-data-[near]/drag:opacity-100",
"group-data-[near]/drag:scale-x-150 group-data-[near]/drag:scale-y-125",
)}
style={{ insetInlineStart: place } as CSSProperties}
/>
</span>
<span
ref={strip}
aria-hidden="true"
onPointerDown={down}
onPointerMove={move}
onPointerUp={(event) => up(event)}
onPointerCancel={(event) => up(event, true)}
onPointerEnter={() => setNear(true)}
onPointerLeave={() => setNear(false)}
// Inside a <label> a click would hand focus to the field after a drag; focus is given on release instead.
onClick={(event) => event.preventDefault()}
className="pointer-events-none absolute inset-y-0 -ms-2 w-4 cursor-ew-resize touch-none in-[fieldset:disabled]:hidden pointer-fine:pointer-events-auto"
style={{ insetInlineStart: place } as CSSProperties}
/>
</>
);
}
```
### components/filters-ui/lib/direction.ts
```ts
// Right-to-left helpers for positions and keys worked out in script. Each reads the direction from the element
// itself, so it is right when only a parent sets dir="rtl".
/** True when the element lays out right to left. */
export const isRtl = (node: Element | null | undefined) => !!node && getComputedStyle(node).direction === "rtl";
/**
* The arrow key as a step in reading order: in right-to-left, ArrowLeft moves forward and ArrowRight back, as the
* ARIA patterns ask for horizontal widgets. Every other key comes back as it is.
*/
export function readingKey(key: string, node: Element | null | undefined): string {
if ((key !== "ArrowLeft" && key !== "ArrowRight") || !isRtl(node)) return key;
return key === "ArrowLeft" ? "ArrowRight" : "ArrowLeft";
}
/** A child's offset from its offset parent's start edge: its offsetLeft, or the distance from the right in RTL. */
export function startOffset(node: HTMLElement): number {
if (!isRtl(node)) return node.offsetLeft;
const parent = node.offsetParent as HTMLElement | null;
return (parent?.clientWidth ?? 0) - node.offsetLeft - node.offsetWidth;
}
/** Calls back whenever a dir attribute on the page changes, so a position measured in script can be taken again. */
export function onDirChange(callback: () => void): () => void {
if (typeof MutationObserver === "undefined") return () => {};
const observer = new MutationObserver(callback);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["dir"], subtree: true });
return () => observer.disconnect();
}
```
### components/filters-ui/ui/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/ui/text-field.tsx
```tsx
"use client";
import { useRef, type InputHTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { DragHandle, type NumberDrag } from "./drag-handle";
import { XIcon } from "./icons";
import { ARRIVING, Skeleton, useLoading } from "./skeleton";
export type TextFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "onChange" | "prefix" | "size"> & {
value: string;
onChange: (value: string) => void;
/** Accessible name. Shown only to screen readers; the placeholder is the visible label. */
label: string;
/** Text or an icon before the value, e.g. "$". */
prefix?: ReactNode;
/** Shows a 16px clear button while the field has a value. Defaults to emptying the value. */
onClear?: () => void;
clearLabel?: string;
/** For a field that holds a number: a handle to drag it along a scale, as on a slider. See DragHandle. */
drag?: NumberDrag;
className?: string;
inputClassName?: string;
};
/** 44px field, 12px radius, 1px --fu-field-border border, 15px text, optional prefix and clear X. */
export function TextField({
value,
onChange,
label,
prefix,
onClear,
clearLabel,
drag,
className,
inputClassName,
disabled,
...props
}: TextFieldProps) {
const input = useRef<HTMLInputElement>(null);
const filled = value.length > 0;
// Inside a loading StatusFrame the box stays and a bar stands in for the words, which fade in once when they arrive.
const { loading, arriving } = useLoading();
return (
<div
className={cn(
"flex h-11 min-w-0 items-center gap-1.5 rounded-[12px] border border-[var(--fu-field-border,#737373)] bg-[var(--fu-input,rgb(0_0_0/0))] px-3",
"text-[15px] leading-5 text-[var(--fu-text,#F8F5F1)] transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none",
"hover:border-[var(--fu-control-hover,#A3A3A3)] focus-within:border-[var(--fu-accent-soft,#8FAAFF)] focus-within:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
"focus-within:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50",
drag && "group/field relative isolate",
className,
)}
onPointerDown={(event) => {
if (event.target === event.currentTarget) {
event.preventDefault();
input.current?.focus();
}
}}
>
{prefix != null && <span className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">{prefix}</span>}
{loading && <Skeleton className="h-3 w-[45%] max-w-28 rounded-[4px]" />}
<input
key={loading ? "loading" : "ready"}
ref={input}
value={value}
onChange={(event) => onChange(event.target.value)}
aria-label={label}
disabled={disabled}
className={cn(
"h-full min-w-0 flex-1 bg-transparent text-ellipsis text-inherit tabular-nums outline-none",
"placeholder:text-[var(--fu-mute,#BDBDBD)]",
inputClassName,
loading && "sr-only",
arriving && ARRIVING,
)}
{...props}
/>
{filled && !loading && (
<button
type="button"
aria-label={clearLabel ?? `Clear ${label.toLowerCase()}`}
onClick={() => {
if (onClear) onClear();
else onChange("");
input.current?.focus();
}}
className={cn(
// Above the drag handle's layer, so the cross can always be pressed.
"relative z-[1] -me-1 grid size-6 shrink-0 cursor-pointer place-items-center rounded-[6px] text-[var(--fu-mute,#BDBDBD)]",
"transition-colors duration-150 hover:text-[var(--fu-text,#F8F5F1)]",
"focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
<XIcon size={16} />
</button>
)}
{drag && !loading && !disabled && <DragHandle drag={drag} input={input} />}
</div>
);
}
```
### components/filters-ui/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/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/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/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/filters/searchable-list.tsx
```tsx
"use client";
import { useEffect, useId, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { formatsFor, resultsLabel } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { SEARCH_ART } from "../ui/art-search";
import { CountPill } from "../ui/count-pill";
import { EmptyState } from "../ui/empty-state";
import { CheckIcon, SearchIcon } from "../ui/icons";
import { placeholderLabels, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextField } from "../ui/text-field";
export type SearchableListChild = {
value: string;
label: string;
count: number;
};
export type SearchableListOption = SearchableListChild & {
/** Shown indented under the option once it is ticked. Values need only be unique within their parent. */
children?: readonly SearchableListChild[];
};
/** One ticked option and the children that narrow it. No children means the whole option. */
export type SearchableListPick = {
value: string;
children: string[];
};
export type SearchableListProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
/** In display order: the first `collapsedCount` make the short list, the rest show after "All N". */
options: readonly SearchableListOption[];
value: readonly SearchableListPick[];
onChange: (value: SearchableListPick[]) => void;
/** Accessible name of the list. */
label: string;
/** Plural noun for the options: "Search makes", "All 21 makes", "No makes match". */
noun?: string;
collapsedCount?: number;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/**
* "card" (default): the look inside a FilterCard. "panel": a 48px search, 20px filled checkboxes, 17px names, counts as
* plain numbers and rows flush with the field, as in the Filter panel block. The list grows in place for its scrolling
* parent rather than scrolling in a box of its own.
*/
variant?: "card" | "panel";
};
const ROW_HEIGHT = 36;
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
// Swapped letters count as one slip, so "telsa" is one edit from "tesla".
function editDistance(a: string, b: string) {
const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
}
}
return rows[a.length][b.length];
}
/** The closest name with results, for a word of 4+ letters: one slip allowed, two past 5 letters. On a tie the longer name wins. */
function nearestName(typed: string, options: readonly SearchableListOption[]) {
if (typed.length < 4) return null;
const allowed = typed.length > 5 ? 2 : 1;
// Names further apart in length than the slips allowed cannot match, so a long paste costs nothing.
const names = options
.flatMap((o) => [o, ...(o.children ?? [])])
.filter((o) => o.count > 0 && Math.abs(o.label.length - typed.length) <= allowed);
const [best] = names
.map((o) => ({ name: o.label, edits: editDistance(typed, o.label.toLowerCase()) }))
.filter((o) => o.edits <= allowed)
.sort((a, b) => a.edits - b.edits || b.name.length - a.name.length);
return best?.name ?? null;
}
// Names in the panel look are already semibold, so there the letters around the match dim instead.
function Marked({ text, query, panel = false }: { text: string; query: string; panel?: boolean }) {
const at = query ? text.toLowerCase().indexOf(query) : -1;
if (at < 0) return <>{text}</>;
if (panel) {
const dim = "text-[var(--fu-dim,#929292)]";
return (
<>
<span className={dim}>{text.slice(0, at)}</span>
{text.slice(at, at + query.length)}
<span className={dim}>{text.slice(at + query.length)}</span>
</>
);
}
return (
<>
{text.slice(0, at)}
<b className="font-semibold">{text.slice(at, at + query.length)}</b>
{text.slice(at + query.length)}
</>
);
}
/** Opens and closes with the card's own motion: height over 480ms, content in from a 6px blur, 6px lower. */
function Reveal({ open, children }: { open: boolean; children: ReactNode }) {
return (
<div
inert={!open}
data-state={open ? "open" : "closed"}
className={cn(
"group/reveal grid grid-rows-[0fr] transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"data-[state=open]:grid-rows-[1fr]",
)}
>
<div className="min-h-0 overflow-hidden">
<div
className={cn(
"translate-y-1.5 opacity-0 blur-[6px] transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/reveal:translate-y-0 group-data-[state=open]/reveal:opacity-100 group-data-[state=open]/reveal:blur-none",
"group-data-[state=open]/reveal:delay-[120ms] group-data-[state=open]/reveal:duration-[460ms] group-data-[state=open]/reveal:ease-[cubic-bezier(0.16,1,0.3,1)]",
)}
>
{children}
</div>
</div>
</div>
);
}
type RowProps = {
label: string;
query: string;
count: number;
checked: boolean;
disabled: boolean;
nested?: boolean;
panel: boolean;
formatCount: (n: number) => string;
countLabel: (n: number) => string;
onToggle: (input: HTMLInputElement) => void;
onBlur: () => void;
};
// The whole row is the checkbox's label. A long name wraps onto more lines; the box and the count stay in the row. The native box is hidden and drawn again: 18px, 5px radius, the tile's selected fill with an accent check that draws in.
// The panel look draws it 20px with 6px corners, filled with the accent and an --fu-on-accent check once ticked.
function Row({ label, query, count, checked, disabled, nested, panel, formatCount, countLabel, onToggle, onBlur }: RowProps) {
const { loading } = useLoading();
return (
<label
data-state={checked ? "on" : "off"}
className={cn(
"group/row relative flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 rounded-[12px] py-2 pe-3 text-[14px] leading-5 text-[var(--fu-text,#F8F5F1)]",
nested ? "ps-[40px]" : "ps-3",
// 17px names on a 24px line, 6px above and below: 36px, as the card look's 20px line with 8px.
panel && "rounded-[10px] py-1.5 pe-2 text-[17px] leading-6 font-semibold pointer-coarse:min-h-11",
panel && (nested ? "ps-[38px]" : "ps-2"),
"transition-[background-color,opacity] duration-200 motion-reduce:transition-none",
"[@media(hover:hover)]:has-[input:enabled]:hover:bg-[var(--fu-wash,rgb(255_255_255/0.08))]",
// Drawn inside the row, so neither the scroll area nor the card can clip it.
"has-[input:focus-visible]:outline-2 has-[input:focus-visible]:-outline-offset-2 has-[input:focus-visible]:outline-solid has-[input:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
"has-[input:disabled]:cursor-not-allowed",
count === 0 && !checked && !loading && "opacity-40",
)}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
aria-label={`${label}, ${countLabel(count)}`}
onChange={(event) => onToggle(event.currentTarget)}
onBlur={onBlur}
className={cn("peer absolute size-[18px] cursor-[inherit] opacity-0", panel && "size-5")}
/>
<span
aria-hidden="true"
className={cn(
"grid size-[18px] shrink-0 place-items-center rounded-[5px] border border-[var(--fu-control-border,#737373)] text-[var(--fu-accent-soft,#8FAAFF)]",
"transition-[background-color,border-color] duration-200 motion-reduce:transition-none",
SMOOTH,
"[@media(hover:hover)]:group-hover/row:peer-enabled:border-[var(--fu-control-hover,#A3A3A3)]",
panel
? "size-5 rounded-[6px] border-[1.5px] bg-[var(--fu-field-wash,rgb(255_255_255/0.03))] text-[var(--fu-on-accent,#FFFFFF)] peer-checked:border-[var(--fu-accent,#3B57E6)] peer-checked:bg-[var(--fu-accent,#3B57E6)] [@media(hover:hover)]:group-hover/row:peer-checked:border-[var(--fu-accent,#3B57E6)]"
: "peer-checked:border-[var(--fu-accent-soft,#8FAAFF)] peer-checked:bg-[var(--fu-selected,#1F2747)] [@media(hover:hover)]:group-hover/row:peer-checked:border-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
<CheckIcon
size={14}
strokeWidth={3}
className={cn(
// The path is about 23 units long; a negative offset draws it from the short leg up.
"[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:-23] [&_path]:transition-[stroke-dashoffset] [&_path]:duration-200 motion-reduce:[&_path]:transition-none",
"[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] group-data-[state=on]/row:[&_path]:[stroke-dashoffset:0]",
)}
/>
</span>
<span aria-hidden="true" className="min-w-0 flex-1 [overflow-wrap:anywhere]">
<SkeletonText>
<Marked text={label} query={query} panel={panel} />
</SkeletonText>
</span>
{panel ? (
<span aria-hidden="true" className="shrink-0 font-normal tabular-nums text-[var(--fu-mute,#BDBDBD)]">
<SkeletonText>{formatCount(count)}</SkeletonText>
</span>
) : (
<CountPill aria-hidden="true" variant="square" on={checked} count={count} format={formatCount} />
)}
</label>
);
}
/**
* A search field over a checklist whose options open their own children when ticked, e.g. makes and their models.
* The short list shows the first `collapsedCount` options and grows with what is ticked; "All N" adds the rest inside a
* scroll area capped at 320px. Typing filters options and children at once, holding the short list's height so the card
* does not jump per key; a typo with no match offers the nearest name.
*/
export function SearchableList({
options,
value,
onChange,
label,
noun = "items",
collapsedCount = 8,
formatCount: formatCountProp,
countLabel: countLabelProp,
locale,
variant = "card",
status = "ready",
onRetry,
errorText = `Couldn't load the ${noun}.`,
emptyText = `No ${noun} to show`,
disabled = false,
className,
...props
}: SearchableListProps) {
const formatCount = formatCountProp ?? formatsFor(locale).number;
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const panel = variant === "panel";
const listId = useId();
const [query, setQuery] = useState("");
const [all, setAll] = useState(false);
const field = useRef<HTMLDivElement>(null);
const scroller = useRef<HTMLDivElement>(null);
const content = useRef<HTMLUListElement>(null);
const [fade, setFade] = useState({ top: false, bottom: false });
// A row turned off at 0 would become disabled under the pointer or keyboard and drop focus; it stays enabled until it loses focus.
const [kept, setKept] = useState<string | null>(null);
// Ticked options past the short list stay in it while it is short, and do not vanish when unticked there.
const tickedLater = value.map((p) => p.value).filter((v) => options.findIndex((o) => o.value === v) >= collapsedCount);
const [pinned, setPinned] = useState<string[]>(tickedLater);
if (tickedLater.some((v) => !pinned.includes(v))) setPinned([...pinned, ...tickedLater.filter((v) => !pinned.includes(v))]);
if (value.length === 0 && pinned.length > 0 && !all) setPinned([]);
const pickOf = (v: string) => value.find((p) => p.value === v);
const toggleParent = (v: string, input: HTMLInputElement) => {
const on = Boolean(pickOf(v));
setKept(on && document.activeElement === input ? v : null);
onChange(on ? value.filter((p) => p.value !== v) : [...value, { value: v, children: [] }]);
};
// Ticking a child ticks its parent too; a child narrows the parent to the children ticked.
const toggleChild = (parent: string, child: string, input: HTMLInputElement) => {
const pick = pickOf(parent);
const on = Boolean(pick?.children.includes(child));
setKept(on && document.activeElement === input ? `${parent}\n${child}` : null);
if (!pick) return onChange([...value, { value: parent, children: [child] }]);
const children = on ? pick.children.filter((c) => c !== child) : [...pick.children, child];
onChange(value.map((p) => (p.value === parent ? { ...p, children } : p)));
};
useEffect(() => {
const node = scroller.current;
const inner = content.current;
if (!node || !inner) return;
const measure = () => {
const top = node.scrollTop > 1;
const bottom = node.scrollTop + node.clientHeight < node.scrollHeight - 1;
setFade((f) => (f.top === top && f.bottom === bottom ? f : { top, bottom }));
};
measure();
node.addEventListener("scroll", measure, { passive: true });
const observer = new ResizeObserver(measure);
observer.observe(node);
observer.observe(inner);
return () => {
node.removeEventListener("scroll", measure);
observer.disconnect();
};
// The frame takes the list away in an error or with no options; its listeners go on the new box when it is back.
}, [status, options.length === 0]);
// Its own status, or the loading frame of an item around it, such as a block's card.
const loading = useLoading().loading || status === "loading";
// While the options are on their way, a short list of stand-ins keeps the place they will take.
const listed: readonly SearchableListOption[] =
loading && options.length === 0 ? placeholderLabels(collapsedCount).map((name) => ({ value: name, label: name, count: 0 })) : options;
const typed = loading ? "" : query.trim().toLowerCase();
const parentRow = (option: SearchableListOption, q: string) => {
const checked = Boolean(pickOf(option.value));
return (
<Row
label={option.label}
query={q}
count={option.count}
checked={checked}
disabled={option.count === 0 && !checked && kept !== option.value}
panel={panel}
formatCount={formatCount}
countLabel={countLabel}
onToggle={(input) => toggleParent(option.value, input)}
onBlur={() => kept === option.value && setKept(null)}
/>
);
};
const childRows = (option: SearchableListOption, children: readonly SearchableListChild[], q: string) => {
const pick = pickOf(option.value);
return (
<ul aria-label={option.label} className="m-0 list-none p-0">
{children.map((child) => {
const key = `${option.value}\n${child.value}`;
const checked = Boolean(pick?.children.includes(child.value));
return (
<li key={child.value} className="m-0 p-0">
<Row
nested
label={child.label}
query={q}
count={child.count}
checked={checked}
disabled={child.count === 0 && !checked && kept !== key}
panel={panel}
formatCount={formatCount}
countLabel={countLabel}
onToggle={(input) => toggleChild(option.value, child.value, input)}
onBlur={() => kept === key && setKept(null)}
/>
</li>
);
})}
</ul>
);
};
let rows: ReactNode;
let found = 0;
if (typed) {
const matches = options.flatMap((option) => {
const children = option.children ?? [];
const self = option.label.toLowerCase().includes(typed);
const kids = children.filter((c) => c.label.toLowerCase().includes(typed));
return self || kids.length ? [{ option, self, kids }] : [];
});
found = matches.length;
rows = matches.map(({ option, self, kids }) => {
const checked = Boolean(pickOf(option.value));
const showAll = !kids.length || (checked && self);
return (
<li key={option.value} className="m-0 p-0">
{parentRow(option, typed)}
{(option.children?.length ?? 0) > 0 && (
<Reveal open={checked || kids.length > 0}>{childRows(option, showAll ? option.children! : kids, typed)}</Reveal>
)}
</li>
);
});
} else {
rows = listed.map((option, i) => {
const item = (
<>
{parentRow(option, "")}
{(option.children?.length ?? 0) > 0 && <Reveal open={Boolean(pickOf(option.value))}>{childRows(option, option.children!, "")}</Reveal>}
</>
);
return (
<li key={option.value} className="m-0 p-0">
{i < collapsedCount ? item : <Reveal open={all || pinned.includes(option.value)}>{item}</Reveal>}
</li>
);
});
}
const none = Boolean(typed) && found === 0;
const near = none ? nearestName(typed, options) : null;
const more = listed.length > collapsedCount;
return (
<div className={cn("min-w-0", className)} {...props}>
<StatusFrame
status={status}
onRetry={onRetry}
errorText={errorText}
empty={options.length === 0}
emptyText={emptyText}
disabled={disabled}
className={cn(panel && "rounded-[14px]")}
>
<div ref={field}>
<TextField
type="search"
value={query}
onChange={setQuery}
label={`Search ${noun}`}
placeholder={`Search ${noun}`}
prefix={<SearchIcon size={panel ? 20 : 16} className="block" />}
clearLabel="Clear search"
autoComplete="off"
spellCheck={false}
className={panel ? "h-12 gap-3 bg-[var(--fu-field-wash,rgb(255_255_255/0.03))] px-3.5 text-[17px]" : undefined}
inputClassName="[&::-webkit-search-cancel-button]:appearance-none"
onKeyDown={(event) => {
if (event.key === "Escape" && query) {
event.stopPropagation();
event.preventDefault();
setQuery("");
}
}}
/>
</div>
{/* In the panel look the list reaches 8px past the field on each side, so boxes and counts line up with its edges.
The panel scrolls the whole list itself, so there the list neither scrolls in its own box nor holds its height while typing.
Opened in full, the scroll box reaches 10px into the card's padding and the rows keep the width of this box
(100cqi), so the scrollbar sits beside the rows and no count moves when it appears. */}
<div className={cn("relative mt-2", panel ? "-mx-2" : "@container")}>
<div
ref={scroller}
id={listId}
className={cn(
all && !panel && ["-me-2.5 max-h-80 scroll-py-7 overflow-x-hidden overflow-y-auto overscroll-contain", SCROLL],
)}
style={typed && !panel && !none ? { minHeight: collapsedCount * ROW_HEIGHT } : undefined}
>
<ul ref={content} aria-label={label} className={cn("m-0 list-none p-0", all && !panel && "w-[100cqi]")}>
{rows}
</ul>
</div>
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-0 top-0 h-6 bg-linear-to-b from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 motion-reduce:transition-none",
fade.top && "opacity-100",
)}
/>
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-linear-to-t from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-200 motion-reduce:transition-none",
fade.bottom && "opacity-100",
)}
/>
</div>
{/* Nothing matches: the picture, the line and one way on sit in the middle of the room the short list takes,
so the card keeps its height. The region stays on the page, so the line is read out when it arrives. */}
<div
role="status"
className={cn(none && "grid place-items-center px-3", none && panel && "px-0 py-6")}
style={none && !panel ? { minHeight: collapsedCount * ROW_HEIGHT } : undefined}
>
{none && (
<EmptyState
art={SEARCH_ART}
title={
<span className="flex min-w-0 justify-center">
<span className="shrink-0">No {noun} match </span>
<span className="min-w-0 truncate">“{query.trim()}</span>
<span className="shrink-0">”</span>
</span>
}
action={
<button
type="button"
onClick={() => {
setQuery(near ?? "");
field.current?.querySelector("input")?.focus();
}}
className={cn(
"relative cursor-pointer rounded-[6px] text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)] transition-[color] duration-200 before:absolute before:inset-x-0 before:-inset-y-2 before:content-[''] hover:text-[var(--fu-accent-pale,#D1DDFF)]",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
{near ? `Did you mean ${near}?` : "Clear search"}
</button>
}
/>
)}
</div>
{!typed && more && (
<button
type="button"
aria-expanded={all}
aria-controls={listId}
onClick={() => {
if (all) setPinned(tickedLater);
setAll(!all);
}}
className={cn(
"group/more relative mt-1.5 ms-3 cursor-pointer rounded-[6px] text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)] transition-[color] duration-200 hover:text-[var(--fu-accent-pale,#D1DDFF)] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-['']",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
panel && "mt-2 ms-0 text-[15px] pointer-coarse:before:-inset-y-3",
)}
>
{/* A 1px line draws in under the words from the start edge while it is hovered or focused. */}
<span
className={cn(
"bg-[linear-gradient(currentColor,currentColor)] bg-[length:0%_1px] bg-[position:0_100%] rtl:bg-[position:100%_100%] bg-no-repeat pb-px",
"transition-[background-size] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"[@media(hover:hover)]:group-hover/more:bg-[length:100%_1px] group-focus-visible/more:bg-[length:100%_1px]",
)}
>
<SkeletonText>{all ? "Show fewer" : `All ${formatCount(listed.length)} ${noun}`}</SkeletonText>
</span>
</button>
)}
</StatusFrame>
</div>
);
}
```
### components/filters-ui/filters/segmented-choice.tsx
```tsx
"use client";
import { Segmented, type SegmentedOption, type SegmentedProps, type SegmentedValue } from "../ui/segmented";
import { useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
export type SegmentedChoiceProps<V extends SegmentedValue> = SegmentedProps<V> & Omit<StateProps, "emptyText">;
/**
* Pick one value, or none ("Any"), from a few options with counts.
* An option whose count is 0 is dimmed and disabled, unless it is the current choice.
*/
export function SegmentedChoice<V extends SegmentedValue>({
options,
value,
status = "ready",
onRetry,
errorText,
disabled = false,
className,
style,
...props
}: SegmentedChoiceProps<V>) {
// While loading, by its own status or in the loading frame of an item around it (a block's card), the counts are
// not known yet, so no option is dimmed for a 0.
const loading = useLoading().loading || status === "loading";
const shown: SegmentedOption<V>[] = options.map((option) => ({
...option,
disabled: option.disabled || (!loading && option.count === 0 && !Object.is(option.value, value)),
}));
// The frame dims and blocks the control while disabled, so the control is not dimmed a second time.
return (
<div className={className} style={style}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled}>
<Segmented options={shown} value={value} aria-disabled={disabled || undefined} {...props} />
</StatusFrame>
</div>
);
}
```
### components/filters-ui/ui/segmented.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { onDirChange, readingKey, startOffset } from "../lib/direction";
import { formatsFor, resultsLabel } from "../lib/format";
import { CountPill } from "./count-pill";
import { SkeletonText } from "./skeleton";
export type SegmentedValue = string | number | null;
export type SegmentedOption<V extends SegmentedValue> = {
value: V;
label: ReactNode;
/** Shown in a count pill and read out with the label. Leave out for no pill ("Any"). */
count?: number;
disabled?: boolean;
};
export type SegmentedProps<V extends SegmentedValue> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> & {
options: readonly SegmentedOption<V>[];
value: V;
onChange: (value: V) => void;
/** Accessible name of the group. */
label: string;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts by default, e.g. "de-DE". */
locale?: string;
disabled?: boolean;
/** "equal": options with a count share the width equally, and a name too long to sit beside its count wraps with the count under it. "content": the same, except an option whose words need more keeps its own width (a name of several words may wrap beside its count instead). An option without a count ("Any") hugs its words while the control is under 340px wide. */
fit?: "equal" | "content";
};
// Forced colours drop the thumb's fill, so the chosen segment sits on the system highlight. Its colours stay as given:
// left to the browser, its words would sit on a backplate in the page colour.
const FORCED_ON =
"forced-colors:text-[HighlightText] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-offset-2 forced-colors:focus-visible:outline-[CanvasText]";
/**
* A segmented control: an option without a count ("Any") hugs its words while the control is under 340px wide (from 340px all share the width), the others share the rest equally, and one pill slides to the chosen one over 340ms.
* It is a radiogroup with one tab stop; arrow keys, Home and End move and select. Right to left, the options run from
* the right and Left and Right follow them. Long names wrap and the track grows. Inside a loading StatusFrame the
* words and counts of options with a count draw as placeholders; "Any" and the pill on the choice stay.
*/
export function Segmented<V extends SegmentedValue>({
options,
value,
onChange,
label,
formatCount,
countLabel,
locale,
disabled = false,
fit = "equal",
className,
style,
...props
}: SegmentedProps<V>) {
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
const words = countLabel ?? ((n: number) => resultsLabel(n, locale));
const count = formatCount ?? formatsFor(locale).number;
const index = options.findIndex((option) => Object.is(option.value, value));
const usable = (i: number) => !disabled && !options[i].disabled;
const [box, setBox] = useState<{ start: number; width: number; rtl: boolean } | null>(null);
const [placed, setPlaced] = useState(false);
// "Any" hugs its words only beside options that carry counts, and only while the track is narrow; a set without counts stays equal.
const counted = options.some((option) => option.count !== undefined);
const hugs = counted && options.some((option) => option.count === undefined);
const measuring = fit === "content" || hugs;
const tabStop = index >= 0 ? index : options.findIndex((_, i) => usable(i));
// Widths differ per option, so the pill takes the chosen button's measured box instead of a share of the track.
// Until it is measured, the chosen button paints its own pill, so the server render already shows the choice.
useLayoutEffect(() => {
const button = measuring && index >= 0 ? buttons.current[index] : null;
if (!button) return;
const measure = () => setBox({ start: startOffset(button), width: button.offsetWidth, rtl: getComputedStyle(button).direction === "rtl" });
measure();
const frame = requestAnimationFrame(() => setPlaced(true));
const observer = new ResizeObserver(measure);
buttons.current.forEach((b) => b && observer.observe(b));
const stop = onDirChange(measure);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
stop();
};
}, [measuring, index, options.length]);
const measured = measuring ? box : null;
const pick = (i: number) => {
buttons.current[i]?.focus();
if (i !== index) onChange(options[i].value);
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const from = Math.max(0, buttons.current.findIndex((b) => b === document.activeElement));
const n = options.length;
const walk = (start: number, step: number) => {
for (let k = 0, i = start; k < n; k++, i = (i + step + n) % n) if (usable(i)) return i;
return -1;
};
let next = -1;
switch (readingKey(event.key, event.currentTarget)) {
case "ArrowRight":
case "ArrowDown":
next = walk((from + 1) % n, 1);
break;
case "ArrowLeft":
case "ArrowUp":
next = walk((from - 1 + n) % n, -1);
break;
case "Home":
next = walk(0, 1);
break;
case "End":
next = walk(n - 1, -1);
break;
default:
return;
}
event.preventDefault();
if (next >= 0) pick(next);
};
return (
<div
role="radiogroup"
aria-label={label}
aria-disabled={disabled || undefined}
onKeyDown={onKeyDown}
className={cn("@container relative flex min-h-10 rounded-[12px] bg-[var(--fu-segment-track,#2A2A2A)] p-1", disabled && "opacity-50", className)}
style={style}
{...props}
>
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute top-1 bottom-1 inset-s-1 rounded-[9px] bg-[var(--fu-thumb,#404040)] [--flip:1] rtl:[--flip:-1]",
"forced-colors:bg-[Highlight] forced-colors:[forced-color-adjust:none]",
measuring ? placed && "transition-[left,right,width,opacity]" : "transition-[translate,opacity]",
"duration-[340ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
(index < 0 || (measuring && !measured)) && "opacity-0",
)}
style={
measuring
? // physical: the start offset is measured in script from the physical edge that is the start in this direction.
{ [measured?.rtl ? "right" : "left"]: measured?.start, width: measured?.width }
: { width: `calc((100% - 8px) / ${options.length})`, translate: `calc(var(--flip,1) * ${Math.max(index, 0) * 100}%) 0` }
}
/>
{options.map((option, i) => {
const on = i === index;
const off = !usable(i);
const hug = hugs && option.count === undefined;
return (
<button
key={String(option.value)}
ref={(node) => {
buttons.current[i] = node;
}}
type="button"
role="radio"
aria-checked={on}
tabIndex={i === tabStop ? 0 : -1}
disabled={off}
onClick={() => pick(i)}
className={cn(
"group/seg relative flex min-w-0 cursor-pointer items-center justify-center gap-x-1.5 gap-y-1 rounded-[9px] py-1.5 text-[14px] leading-5 font-medium",
hug ? "flex-none px-2.5 @min-[340px]:flex-1 @min-[340px]:px-0.5" : "flex-1 px-0.5",
// At least its longest word and its count, so a single word is never cut; a longer name wraps.
fit === "content" && !hug && "min-w-min",
// In an equal share, a name too long to sit beside its count takes its own lines and the count moves under it.
fit === "equal" && "flex-wrap content-center",
on && measuring && !measured && "bg-[var(--fu-thumb,#404040)] forced-colors:bg-[Highlight]",
"transition-[color,background-color,scale,opacity] duration-[340ms] ease-[cubic-bezier(0.22,1,0.36,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
// Hover and press fill with a faint thumb, so they preview the pick and still read on any track colour.
on
? "text-[var(--fu-text,#F8F5F1)]"
: cn(
"text-[var(--fu-mute,#BDBDBD)] enabled:hover:text-[var(--fu-text,#F8F5F1)]",
"enabled:hover:bg-[color-mix(in_srgb,var(--fu-thumb,#404040)_40%,transparent)] enabled:active:bg-[color-mix(in_srgb,var(--fu-thumb,#404040)_70%,transparent)]",
),
"disabled:cursor-not-allowed",
off && !disabled && !on && "opacity-40",
on && FORCED_ON,
)}
>
{/* Words wrap at spaces and the track grows; a single word too long for its segment ends in an ellipsis.
Words that wrap stop 8px short of the segment's edges; beside a count they never reach that width, so a
name on one line sits as it did. */}
<span className={cn("min-w-0 overflow-hidden text-center text-ellipsis", option.count !== undefined && "max-w-[calc(100%-12px)]")}>
{option.count === undefined ? option.label : <SkeletonText>{option.label}</SkeletonText>}
</span>
{option.count !== undefined && (
<>
<CountPill
aria-hidden="true"
count={option.count}
format={count}
className={cn(
"group-enabled/seg:group-hover/seg:bg-[var(--fu-pill-hover,rgb(255_255_255/0.16))] group-enabled/seg:group-hover/seg:text-[var(--fu-text,#F8F5F1)]",
on && "forced-colors:text-[HighlightText]",
)}
/>
<span className="sr-only">, {words(option.count)}</span>
</>
)}
</button>
);
})}
</div>
);
}
```
### components/filters-ui/filters/upper-limit.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import type { StateProps } from "../ui/status-frame";
import { RangeHistogram } from "./range-histogram";
export type UpperLimitProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
StateProps & {
min: number;
/** The top of the scale. A limit here, or null, means no limit. */
max: number;
step: number;
/** The limit, or null for none. */
value: number | null;
onChange: (value: number | null) => void;
/** Item count per bar, spread evenly from min to max. */
buckets?: readonly number[];
/** Field, tooltip and screen-reader text for a value, e.g. "50,000 km". Default: the number in the locale. */
format?: (value: number) => string;
/** Reads a typed value. Default: the first number in the text, read with the locale's marks, with an optional k or m suffix. */
parse?: (text: string) => number | null;
/** Formats and reads numbers by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** Tooltip text while there is no limit. Default "Any". */
openLabel?: string;
/** Field placeholder. Default "Maximum". */
placeholder?: string;
/** Accessible name of the handle and the field. Default: the placeholder. */
label?: 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;
};
/**
* One upper limit: a bar chart with a single handle and one typed field under it, kept in step both ways.
* A typed value snaps to the step and stays at least one step above min; an empty field, or the top, is no limit.
* The states (status, onRetry, errorText, emptyText, disabled) are the price range's: "Couldn't load the counts." and
* "No items to show" by default.
*/
export function UpperLimit({
value,
onChange,
openLabel = "Any",
placeholder = "Maximum",
label,
...props
}: UpperLimitProps) {
return (
<RangeHistogram
single
value={[null, value]}
onChange={([, high]) => onChange(high)}
openLabel={openLabel}
placeholders={{ high: placeholder }}
labels={{ high: label ?? placeholder }}
{...props}
/>
);
}
```
### components/filters-ui/ui/filters-head.tsx
```tsx
"use client";
import { useEffect, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { ARRIVING, SKELETON_FILL, useLoading } from "./skeleton";
import { TextSwap } from "./text-swap";
export type CountNoun = { one: string; other: string };
type SharedProps = {
/** How many results the current filters give. */
count: number;
/** The result noun. Default { one: "result", other: "results" }. */
noun?: CountNoun;
/** Formats the number in the button. Default Intl en-US ("1,204"). */
formatCount?: (n: number) => string;
/** Formats the count when no formatCount is given, e.g. "de-DE". Default "en-US". */
locale?: string;
/** Override the whole button label. Default "Show {count} {noun}". */
showLabel?: (count: number) => string;
onShow?: () => void;
onClearAll?: () => void;
/** False hides "Clear all" (nothing to clear). Default true. */
canClear?: boolean;
clearAllLabel?: string;
/** The count is on its way: the number in Show draws as a placeholder of its width. Default false. */
loading?: boolean;
};
function labelOf({ count, noun = { one: "result", other: "results" }, formatCount, locale, showLabel }: SharedProps) {
return showLabel ? showLabel(count) : `Show ${(formatCount ?? formatsFor(locale).number)(count)} ${count === 1 ? noun.one : noun.other}`;
}
const PRESS =
"transition-[background-color,color,scale] duration-200 ease-out active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100";
const FOCUS =
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
/** Quiet text button, 40px high. */
export function ClearAllButton({ className, children = "Clear all", ...props }: HTMLAttributes<HTMLButtonElement> & { children?: ReactNode }) {
return (
<button
type="button"
className={cn(
"inline-flex h-10 shrink-0 cursor-pointer items-center justify-center whitespace-nowrap rounded-[10px] px-3.5 text-[15px] font-medium leading-5 text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
PRESS,
FOCUS,
className,
)}
{...props}
>
{children}
</button>
);
}
/** The first number in a label, in any script, with the marks that group its digits: "1,234", "1.234", "١٬٢٣٤". */
const NUMBER = /\p{Nd}(?:[\p{Nd}.,\u066B\u066C\u00A0\u202F\u2009\u2019']*\p{Nd})?/u;
/** How long an arriving number keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
export type ShowButtonProps = Omit<HTMLAttributes<HTMLButtonElement>, "children"> & {
label: string;
/** The count is on its way: the number in the label draws as a soft bar of its width. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
};
/**
* Primary accent button whose label swaps with TextSwap as the count changes. While loading, the number in its label
* draws as a placeholder of the number's own width, so the button keeps its size; it fades in once when it arrives.
*/
export function ShowButton({ label, loading: loadingProp, className, ...props }: ShowButtonProps) {
const frame = useLoading();
const loading = loadingProp ?? frame.loading;
const [was, setWas] = useState(loading);
const [arrived, setArrived] = useState(false);
if (was !== loading) {
setWas(loading);
setArrived(was && !loading);
}
useEffect(() => {
if (!arrived) return;
const timer = setTimeout(() => setArrived(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arrived]);
const number = loading || arrived ? NUMBER.exec(label) : null;
return (
<button
type="button"
className={cn(
"inline-flex h-10 shrink-0 cursor-pointer items-center justify-center rounded-[10px] bg-[var(--fu-accent,#3B57E6)] px-3.5 text-[15px] font-medium leading-5 text-[var(--fu-on-accent,#FFFFFF)] tabular-nums hover:bg-[var(--fu-accent-hover,#3450D4)]",
PRESS,
FOCUS,
className,
)}
{...props}
>
{number ? (
// The same boxes as TextSwap's, so nothing moves between the placeholder, the arrival and the swap after it.
<span className="inline-grid whitespace-nowrap">
<span className="[grid-area:1/1]">
{label.slice(0, number.index)}
{loading ? (
<span key="skeleton" className="relative inline-block align-top">
<span className="invisible">{number[0]}</span>
<span
aria-hidden="true"
className={cn("absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]", SKELETON_FILL, "bg-[var(--fu-on-accent,#FFFFFF)]/30")}
/>
</span>
) : (
<span key="arrived" className={ARRIVING}>
{number[0]}
</span>
)}
{label.slice(number.index + number[0].length)}
</span>
</span>
) : (
<TextSwap>{label}</TextSwap>
)}
</button>
);
}
export type FiltersHeadProps = SharedProps &
Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
/** Default "Filters". */
title?: ReactNode;
headingLevel?: 1 | 2 | 3;
/** Classes for the Clear all / Show wrapper, e.g. "max-sm:hidden" when a FiltersBar carries them on phones. */
actionsClassName?: string;
};
/** "Filters" at the start; "Clear all" and "Show N results" at the end. The count is announced politely. */
export function FiltersHead({
title = "Filters",
headingLevel = 2,
count,
noun,
formatCount,
locale,
showLabel,
onShow,
onClearAll,
canClear = true,
clearAllLabel,
loading = false,
actionsClassName,
className,
...props
}: FiltersHeadProps) {
const Heading = `h${headingLevel}` as const;
const label = labelOf({ count, noun, formatCount, locale, showLabel });
return (
<div className={cn("not-prose flex min-h-10 items-center gap-2", className)} {...props}>
<Heading className="m-0 me-auto text-[26px] font-semibold leading-8 text-[var(--fu-text,#F8F5F1)]">{title}</Heading>
<span className="sr-only" aria-live="polite" aria-atomic="true">
{label.replace(/^Show /, "")}
</span>
<div className={cn("flex items-center gap-2", actionsClassName)}>
{canClear && <ClearAllButton onClick={onClearAll}>{clearAllLabel ?? "Clear all"}</ClearAllButton>}
<ShowButton label={label} onClick={onShow} loading={loading} />
</div>
</div>
);
}
export type FiltersBarProps = SharedProps &
HTMLAttributes<HTMLDivElement> & {
/** Slides the bar in or out (opacity and 18px). Default true. */
visible?: boolean;
};
/**
* The floating bar for phones: Clear all and Show N in a pill, pinned to the bottom centre.
* Pair it with a FiltersHead and show it while the head's own button is scrolled out of view.
*/
export function FiltersBar({
visible = true,
count,
noun,
formatCount,
locale,
showLabel,
onShow,
onClearAll,
canClear = true,
clearAllLabel,
loading = false,
className,
...props
}: FiltersBarProps) {
const label = labelOf({ count, noun, formatCount, locale, showLabel });
return (
<div
inert={!visible}
data-state={visible ? "visible" : "hidden"}
className={cn(
"fixed bottom-[max(26px,env(safe-area-inset-bottom))] left-1/2 z-40 flex -translate-x-1/2 gap-2 rounded-[20px] border border-[var(--fu-hover,#333333)] bg-[var(--fu-bar,rgb(31_31_31/0.94))] p-2 shadow-[0_16px_40px_var(--fu-shadow,rgb(0_0_0/0.5))] backdrop-blur-md",
"transition-[opacity,translate] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"data-[state=hidden]:pointer-events-none data-[state=hidden]:translate-y-[18px] data-[state=hidden]:opacity-0",
className,
)}
{...props}
>
{canClear && <ClearAllButton onClick={onClearAll}>{clearAllLabel ?? "Clear all"}</ClearAllButton>}
<ShowButton label={label} onClick={onShow} loading={loading} />
</div>
);
}
```
## What it does
- Eleven filters stacked as rows in one panel. Several can be open at once.
- A closed row keeps its value in words, so the closed panel reads as the whole search.
- An open row's head stays pinned at the top while its list scrolls under it, so Clear is always in reach.
- Clear on a row clears that filter; Clear all shows once anything is set.
- Show N cars stays pinned at the bottom, and the rows fade out at the top and bottom edges.
## Props and value
FilterPanel (components/filters-ui/blocks/filter-panel.tsx) holds this value: The panel keeps its own filters. onShow receives the matching cars.
- cars: readonly Car[] (default 256 sample cars). The listings to filter.
- defaultFilters: CarFilters (default nothing set). The filters on first render.
- defaultOpen: CarFacet[] (default []). Rows open on first render. Several can be open at once.
- onShow: (cars: Car[]) => void (optional). Called by Show N cars with the matching cars.
- glow: boolean (default false). A faint coloured light along the panel's edges.
- headingLevel: 2 | 3 | 4 (default 2). Level of the Filters heading; row headings sit one below.
- className: string (optional). Give the panel a height or a max height, e.g. h-[600px], and the rows scroll between the head and Show.
- locale: string (default "en-US"). Numbers, prices and distances on every card follow it, e.g. "de-DE". 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 cars."). The error line, in plain words.
- disabled: boolean (default false). Turns every row's filter off and leaves Clear and Clear all out; the rows still open and Show stays.
## 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"): The filters take no input, but every row keeps its head and value and still opens; each open row's filter draws placeholders the size of its real content, so nothing moves when the data arrives, and the number in Show draws as one. 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): Each open row shows one calm line in place of its filter, and the line shows once more under the head with one Retry button that calls onRetry; rows still open and close. The default line is "Couldn't load the cars." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Disabled (disabled): Every row's filter is dimmed, takes no pointer or keyboard input and is read as unavailable, and the rows still open to show it; Clear on each row and Clear all are left out, and Show stays.
## 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 { FilterPanel } from "@/components/filters-ui/blocks/filter-panel";
import { EMPTY_CAR_FILTERS } from "@/components/filters-ui/demo/cars-facets";
// The panel keeps its own filters and counts; onShow gets the cars that match.
// Give it a height or a max height, as a sidebar would, and the rows scroll between the head and Show.
export default function FilterPanelExample() {
return (
<FilterPanel
className="mx-auto h-[600px] max-w-[400px]"
defaultFilters={{ ...EMPTY_CAR_FILTERS, priceMax: 45000, makes: [{ make: "Toyota", models: ["RAV4"] }] }}
defaultOpen={["make"]}
onShow={(cars) => console.log(`Show ${cars.length} cars`)}
/>
);
}
```
## Connect it to my data
The panel filters a list of Car records (components/filters-ui/demo/cars.ts) and counts every option itself in components/filters-ui/demo/cars-facets.ts. Ask me where my records come from and which of my fields match each row. Then map my records onto the Car type, or change Car and the facet tests in cars-facets.ts to my fields, and remove the rows I have no field for from FILTER_PANEL_FACETS and bodyOf in components/filters-ui/blocks/filter-panel.tsx. Keep the counting as it is: each option is counted with every other filter applied and its own left out. In a page sidebar, give the panel a height, such as sticky top-4 h-[calc(100dvh-32px)], so the rows scroll and Show stays in view.
## 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: rgb(31 31 31/0.94);
--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-field-wash: rgb(255 255 255/0.03);
--fu-glow-amber: #F59E6C;
--fu-glow-blue: #4C6BFF;
--fu-glow-rose: #EC8092;
--fu-glow-teal: #2DD4BF;
--fu-glow-violet: #8A6CFF;
--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-item-hover: #2A2A2A;
--fu-line: #404040;
--fu-mute: #BDBDBD;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(255 255 255/0.1);
--fu-pill-hover: rgb(255 255 255/0.16);
--fu-pill-square: #333333;
--fu-pill-text: #C8C8C8;
--fu-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-segment-track: #2A2A2A;
--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-swatch-text: #EDEAE6;
--fu-text: #F8F5F1;
--fu-thumb: #404040;
--fu-track: rgb(255 255 255/0.06);
--fu-wash: rgb(255 255 255/0.08);
}
```
To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).
```css
.light {
--fu-accent: #3B57E6;
--fu-accent-hover: #2F4AD0;
--fu-accent-pale: #253A9E;
--fu-accent-soft: #3049D2;
--fu-bar: rgb(255 255 255/0.94);
--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-field-wash: #FFFFFF;
--fu-glow-amber: #F29358;
--fu-glow-blue: #4C6BFF;
--fu-glow-rose: #E8708A;
--fu-glow-teal: #1FC2AD;
--fu-glow-violet: #8A6CFF;
--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-item-hover: #F2F2F0;
--fu-line: #C4C4C0;
--fu-mute: #444442;
--fu-on-accent: #FFFFFF;
--fu-pill: rgb(29 27 24/0.06);
--fu-pill-hover: rgb(29 27 24/0.1);
--fu-pill-square: rgb(29 27 24/0.07);
--fu-pill-text: #3C3C3A;
--fu-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-segment-track: rgb(29 27 24/0.07);
--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-swatch-text: #363634;
--fu-text: #1B1B19;
--fu-thumb: #FFFFFF;
--fu-track: rgb(29 27 24/0.07);
--fu-wash: rgb(29 27 24/0.05);
}
```
Keep the sizes, corners, spacing and motion as they are.
## Direction and language
It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.
Pass locale (default "en-US") to print its numbers, prices and dates the way a language writes them and to read typed numbers that way, e.g. locale="de-DE". The words stay English: change them through the props.
## Keep the accessibility
- Each row head is a heading holding a button with aria-expanded and aria-controls; the body is a region named by its head.
- A closed row's value is read with its title, and each Clear button is named, e.g. "Clear price".
- The result count is announced politely as it changes.
- Loading, every row's filter is aria-busy and the panel says "Loading" once; an error is read out once, and Retry hands focus to the panel. Disabled, every filter's controls are disabled.
- Focus is always visible; motion is skipped when reduced motion is asked for.
- Tab runs Clear all, then each row head with its Clear and its open body, then Show.
- Enter or Space opens and closes a row; Up and Down move between row heads; Home and End jump to the first and last.
- In an error Tab reaches Retry under the head; while disabled Tab skips every filter's controls and only the row heads and Show take focus.
When done, run the app, tell me which page to open, and show me the result count changing as I use the filters.What it does
- Eleven filters stacked as rows in one panel. Several can be open at once.
- A closed row keeps its value in words, so the closed panel reads as the whole search.
- An open row's head stays pinned at the top while its list scrolls under it, so Clear is always in reach.
- Clear on a row clears that filter; Clear all shows once anything is set.
- Show N cars stays pinned at the bottom, and the rows fade out at the top and bottom edges.
Keyboard
- Tab runs Clear all, then each row head with its Clear and its open body, then Show.
- Enter or Space opens and closes a row; Up and Down move between row heads; Home and End jump to the first and last.
- In an error Tab reaches Retry under the head; while disabled Tab skips every filter's controls and only the row heads and Show take focus.
Props
Value. The panel keeps its own filters. onShow receives the matching cars.
| Prop | Description |
|---|---|
carsDefault 256 sample cars | The listings to filter. readonly Car[] |
defaultFiltersDefault nothing set | The filters on first render. CarFilters |
defaultOpenDefault [] | Rows open on first render. Several can be open at once. CarFacet[] |
onShowOptional | Called by Show N cars with the matching cars. (cars: Car[]) => void |
glowDefault false | A faint coloured light along the panel's edges. boolean |
headingLevelDefault 2 | Level of the Filters heading; row headings sit one below. 2 | 3 | 4 |
classNameOptional | Give the panel a height or a max height, e.g. h-[600px], and the rows scroll between the head and Show. string |
localeDefault "en-US" | Numbers, prices and distances on every card follow it, e.g. "de-DE". 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 cars." | The error line, in plain words. string |
disabledDefault false | Turns every row's filter off and leaves Clear and Clear all out; the rows still open and Show stays. boolean |