Filter pills
A row of pills, one per filter; each opens its filter in a panel that unfolds out of the pill.
Live example
89 of 256 cars
- Nissan Rogue2026 · 13 km$36,995
- Volkswagen Tiguan2026 · 70 km$39,995
- Mazda CX-52026 · 10 km$40,695
- Toyota RAV42026 · 88 km$41,695
Copy
Add the "Filter pills" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Filter pills: A row of pills, one per filter; each opens its filter in a panel that unfolds out of the pill.
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-pills.json
and skip the files below.
Otherwise save each file below at the path shown, from the project root (or inside src/ if the project keeps its code there). Keep the folder layout: the files import each other by relative paths.
Install these npm packages: npm install clsx tailwind-merge
### components/filters-ui/filters/filter-pills.tsx
```tsx
"use client";
import { useEffect, useId, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { useOverflows } from "../lib/overflow";
import { SCROLL } from "../lib/scroll";
import { CountPill } from "../ui/count-pill";
import { ClearAllButton, ShowButton } from "../ui/filters-head";
import { ChevronDownIcon, XIcon } from "../ui/icons";
import { SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextSwap } from "../ui/text-swap";
export type FilterPill = {
id: string;
/** The pill's name, e.g. "Price". */
label: string;
/** The value in words ("$15k to $45k"). Null or empty means the filter is unset. */
summary?: string | null;
/** For a pill that holds several filters, such as "More filters": how many of them are set. */ count?: number;
/** Clears what this pill holds. A set pill then shows a cross, and the panel a Clear button. */
onClear?: () => void;
/** An icon before the label, drawn in currentColor, 16px. */
icon?: ReactNode;
/** Width of the panel in px; never wider than the bar. Default 320. */
width?: number;
/** The filter itself, shown in the panel. */
content: ReactNode;
};
export type FilterPillsProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange"> &
Omit<StateProps, "emptyText"> & {
pills: readonly FilterPill[];
/** Accessible name of the bar. Default "Filters". */
label?: string;
/** Controlled open pill, by id. null closes. */
open?: string | null;
/** The pill open on first render. Its panel shows in place on any screen, so a page never loads behind a sheet. */
defaultOpen?: string | null;
onOpenChange?: (id: string | null) => void;
/** Clears every pill. "Clear all" shows at the end of the bar once a pill is set. */
onClearAll?: () => void;
clearAllLabel?: string;
/** The button at the foot of each panel, e.g. "Show 34 cars". It closes the panel; filters apply as they change. Default "Done". */
showLabel?: string;
onShow?: () => void;
formatCount?: (n: number) => string;
/** Formats the counts by default, e.g. "de-DE". Default "en-US". */
locale?: string;
};
type Mode = "panel" | "sheet";
type Layer = { id: string; key: number; mode: Mode; focus: boolean; closing: boolean; back: boolean };
type Rect = { left: number; top: number; width: number; height: number };
const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";
const REVEAL = "cubic-bezier(0.16, 1, 0.3, 1)";
const FOLD = "cubic-bezier(0.4, 0, 0.2, 1)";
const PHONE = "(max-width: 639px)";
const GAP = 8;
const FOCUSABLE =
'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
const PANEL_BG = "var(--fu-card,#1F1F1F)";
const PANEL_LINE = "var(--fu-line,#404040)";
const OPEN_LINE = "var(--fu-accent-soft,#8FAAFF)";
const PANEL_SHADOW = "0 18px 48px var(--fu-shadow,rgb(0 0 0/0.5))";
const NO_SHADOW = "0 0 0 transparent";
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const FOCUS_RING =
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
/**
* A row of pills, one per filter. Pressing a pill unfolds its panel out of the pill itself: the pill's outline grows
* into a 24px card under it while the filter rises in from a 6px blur, and folds back into the pill on close. A set
* pill shows its value and a cross; "Clear all" fades in at the end. The bar wraps; on phones a pill opens a sheet
* from the bottom instead. Filters apply as they change, so the panel's button only closes it.
* While loading each pill keeps its size with its words as placeholders; an error shows its line and Retry in place
* of the pills; disabled turns every pill off and leaves the crosses and Clear all out. No panel opens in any of them.
*/
export function FilterPills({
pills,
label = "Filters",
open: openProp,
defaultOpen = null,
onOpenChange,
onClearAll,
clearAllLabel = "Clear all",
showLabel = "Done",
onShow,
formatCount: formatCountProp,
locale,
status = "ready",
onRetry,
errorText = "Couldn't load the filters.",
disabled = false,
className,
...props
}: FilterPillsProps) {
const formatCount = formatCountProp ?? formatsFor(locale).number;
const id = useId();
const groups = useRef(new Map<string, HTMLDivElement>());
const triggers = useRef(new Map<string, HTMLButtonElement>());
const [inner, setInner] = useState<string | null>(defaultOpen);
// 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 loading, failed or disabled no panel shows: the open pill's panel folds away and comes back once ready.
const shown = !loading && status === "ready" && !disabled;
const openId = shown ? (openProp === undefined ? inner : openProp) : null;
const [how, setHow] = useState({ mode: "panel" as Mode, focus: false, back: false });
const counter = useRef(1);
const [layers, setLayers] = useState<Layer[]>(() =>
openId ? [{ id: openId, key: 0, mode: "panel", focus: false, closing: false, back: false }] : [],
);
// Each change of the open pill closes the panel that was open (it folds back into its pill) and opens the new one.
// A change of state hides or brings back a panel as a first render shows it: in place, leaving focus where it is.
const [wasShown, setWasShown] = useState(shown);
const byState = wasShown !== shown;
if (byState) setWasShown(shown);
const [seen, setSeen] = useState(openId);
if (seen !== openId) {
setSeen(openId);
const next = byState ? { mode: "panel" as Mode, focus: false, back: false } : how;
setLayers((list) => {
const out = list.flatMap((layer) => {
if (layer.closing) return layer.id === openId ? [] : [layer];
return layer.id === openId ? [layer] : [{ ...layer, closing: true, back: next.back }];
});
if (openId && !out.some((layer) => layer.id === openId)) {
out.push({ id: openId, key: counter.current++, mode: next.mode, focus: next.focus, closing: false, back: false });
}
return out;
});
}
const setOpen = (next: string | null) => {
if (openProp === undefined) setInner(next);
onOpenChange?.(next);
};
const openPill = (pillId: string, focus: boolean) => {
setHow({ mode: window.matchMedia(PHONE).matches ? "sheet" : "panel", focus, back: false });
setOpen(pillId);
};
/** back: focus returns to the pill (Escape, the panel's button). A press outside or Tab leaves focus where it went. */
const close = (back: boolean) => {
const layer = layers.find((l) => !l.closing);
setHow((h) => ({ ...h, back }));
setOpen(null);
if (back && layer?.mode === "panel") triggers.current.get(layer.id)?.focus({ preventScroll: true });
};
const closeRef = useRef(close);
useLayoutEffect(() => {
closeRef.current = close;
});
const current = layers.find((layer) => !layer.closing);
// A mouse closes the panel on press; a finger on a tap that did not move, so starting a scroll keeps it open.
useEffect(() => {
if (!current || current.mode !== "panel") return;
const group = groups.current.get(current.id);
// An inert bar is a still picture, such as a preview: a press elsewhere on the page leaves it open.
if (!group || group.closest("[inert]")) return;
const inside = (target: EventTarget | null) => target instanceof Node && group.contains(target);
let touch: { id: number; x: number; y: number } | null = null;
const onDown = (event: PointerEvent) => {
if (inside(event.target)) return;
if (event.pointerType === "mouse") closeRef.current(false);
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) closeRef.current(false);
touch = null;
};
const onCancel = () => {
touch = null;
};
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("pointerup", onUp, true);
document.addEventListener("pointercancel", onCancel, true);
return () => {
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("pointerup", onUp, true);
document.removeEventListener("pointercancel", onCancel, true);
};
}, [current?.key, current?.mode]);
const gone = (layer: Layer) => {
setLayers((list) => list.filter((l) => l.key !== layer.key));
if (layer.mode === "sheet" && layer.back) triggers.current.get(layer.id)?.focus({ preventScroll: true });
};
const anySet = pills.some((pill) => Boolean(pill.summary) || (pill.count ?? 0) > 0);
return (
<div role="group" aria-label={label} aria-disabled={disabled || undefined} className={cn("not-prose w-full", className)} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled}>
<div className="relative flex flex-wrap items-center gap-2">
{pills.map((pill) => {
const layer = layers.find((l) => l.id === pill.id && !l.closing) ?? layers.find((l) => l.id === pill.id);
return (
<Pill
key={pill.id}
pill={pill}
panelId={`${id}-${pill.id}`}
isOpen={current?.id === pill.id}
handoff={Boolean(current) && current?.id !== pill.id}
layer={layer}
showLabel={showLabel}
formatCount={formatCount}
disabled={disabled}
groupRef={(node) => {
if (node) groups.current.set(pill.id, node);
else groups.current.delete(pill.id);
}}
triggerRef={(node) => {
if (node) triggers.current.set(pill.id, node);
else triggers.current.delete(pill.id);
}}
onToggle={(focus) => (current?.id === pill.id ? close(focus) : openPill(pill.id, focus))}
onClose={close}
onShow={() => {
onShow?.();
close(true);
}}
onGone={gone}
/>
);
})}
{onClearAll && anySet && !disabled && (
<ClearAllButton
onClick={() => {
onClearAll();
const first = pills[0];
if (first) triggers.current.get(first.id)?.focus({ preventScroll: true });
}}
className={cn(
"transition-[background-color,color,scale,opacity,filter,translate] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
"text-[var(--fu-accent-soft,#8FAAFF)] hover:text-[var(--fu-accent-pale,#D1DDFF)] starting:translate-x-1 rtl:starting:-translate-x-1 starting:opacity-0 starting:blur-[2px]",
"relative pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-[3px] pointer-coarse:after:content-['']",
)}
>
<SkeletonText>{clearAllLabel}</SkeletonText>
</ClearAllButton>
)}
</div>
</StatusFrame>
</div>
);
}
type PillProps = {
pill: FilterPill;
panelId: string;
isOpen: boolean;
/** Another pill is open, so a panel closing here hands over to it. */
handoff: boolean;
layer: Layer | undefined;
showLabel: string;
formatCount?: (n: number) => string;
/** The cross is left out, as it cannot run. */
disabled: boolean;
groupRef: (node: HTMLDivElement | null) => void;
triggerRef: (node: HTMLButtonElement | null) => void;
onToggle: (focus: boolean) => void;
onClose: (back: boolean) => void;
onShow: () => void;
onGone: (layer: Layer) => void;
};
function Pill({ pill, panelId, isOpen, handoff, layer, showLabel, formatCount, disabled, groupRef, triggerRef, onToggle, onClose, onShow, onGone }: PillProps) {
const group = useRef<HTMLDivElement | null>(null);
const trigger = useRef<HTMLButtonElement | null>(null);
const skipClick = useRef(false);
const titleId = `${panelId}-title`;
const count = pill.count ?? 0;
// While a pointer is held down in the panel, as on a slider's handle, the pill keeps the value it had and takes the
// new one on release. A value that changes with every step of a drag would resize the pill, and push the pills
// after it, many times a second.
const [dragging, setDragging] = useState(false);
const [steady, setSteady] = useState(pill.summary ?? null);
if (!dragging && steady !== (pill.summary ?? null)) setSteady(pill.summary ?? null);
const summary = dragging ? steady : (pill.summary ?? null);
useEffect(() => {
if (!dragging) return;
const release = () => setDragging(false);
window.addEventListener("pointerup", release);
window.addEventListener("pointercancel", release);
return () => {
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", release);
};
}, [dragging]);
const valued = Boolean(summary);
const set = valued || count > 0;
const clearable = valued && Boolean(pill.onClear) && !disabled;
const raised = Boolean(layer && layer.mode === "panel");
// The last value stays in place while the cross and the value leave after a clear.
const [lastSummary, setLastSummary] = useState(summary ?? "");
if (summary && summary !== lastSummary) setLastSummary(summary);
// A change of value eases the pill to its new width over 200ms, measured without the leaving text. Until it gets
// there its words keep their full width and the pill's edge uncovers them; squeezed into the old width instead,
// the label would cut itself short ("Pr…") for those frames.
const width = useRef<number | null>(null);
const gliding = useRef<Animation | null>(null);
useLayoutEffect(() => {
const node = group.current;
if (!node) return;
const leaving = [...node.querySelectorAll<HTMLElement>("[data-swap] > [aria-hidden]")];
leaving.forEach((n) => (n.style.display = "none"));
const to = node.offsetWidth;
leaving.forEach((n) => (n.style.display = ""));
const from = width.current;
width.current = to;
if (from === null || from === to || reducedMotion()) return;
const glide = node.animate([{ width: `${from}px` }, { width: `${to}px` }], { duration: 200, easing: EASE });
gliding.current = glide;
node.dataset.gliding = "";
const settle = () => {
if (gliding.current !== glide) return;
gliding.current = null;
delete node.dataset.gliding;
};
glide.finished.then(settle, settle);
return () => glide.cancel();
}, [summary, count, clearable]);
const focusFirst = () => {
const panel = document.getElementById(panelId);
const first = panel?.querySelector<HTMLElement>(FOCUSABLE);
first?.focus();
};
const footer = (big: boolean) => (
<>
{pill.onClear ? (
<ClearAllButton onClick={pill.onClear} className={big ? "h-11" : "-ms-3 pointer-coarse:h-11"}>
Clear
</ClearAllButton>
) : (
<span />
)}
<ShowButton label={showLabel} onClick={onShow} className={big ? "h-11 flex-1" : "pointer-coarse:h-11"} />
</>
);
return (
<div
ref={(node) => {
group.current = node;
groupRef(node);
}}
data-state={isOpen ? "open" : "closed"}
data-set={set ? "true" : "false"}
onPointerDownCapture={(event) => {
const panel = document.getElementById(panelId);
if (event.target instanceof Node && panel?.contains(event.target)) setDragging(true);
}}
onKeyDown={(event) => {
if (event.key !== "Escape" || event.defaultPrevented || !isOpen || layer?.mode !== "panel") return;
event.preventDefault();
onClose(true);
}}
onBlur={(event) => {
if (!isOpen || layer?.mode !== "panel") return;
const next = event.relatedTarget;
if (next instanceof Node && !event.currentTarget.contains(next)) onClose(false);
}}
className={cn(
"group/pill inline-flex h-10 max-w-full min-w-0 items-center rounded-[12px] border data-[gliding]:overflow-hidden",
"transition-[background-color,border-color] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
set
? "border-[var(--fu-selected,#1F2747)] bg-[var(--fu-selected,#1F2747)] hover:border-[var(--fu-accent-soft,#8FAAFF)]/40"
: "border-[var(--fu-line,#404040)] bg-[var(--fu-card,#1F1F1F)] hover:border-[var(--fu-control-border,#737373)]",
"data-[state=open]:border-[var(--fu-accent-soft,#8FAAFF)] data-[state=open]:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
"has-[[data-pill-trigger]:focus-visible]:outline-2 has-[[data-pill-trigger]:focus-visible]:outline-offset-2 has-[[data-pill-trigger]:focus-visible]:outline-solid has-[[data-pill-trigger]:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
"forced-colors:border-[ButtonText]",
)}
>
<button
ref={(node) => {
trigger.current = node;
triggerRef(node);
}}
type="button"
data-pill-trigger=""
aria-haspopup="dialog"
aria-expanded={isOpen}
aria-controls={isOpen ? panelId : undefined}
onKeyDown={(event) => {
const { key } = event;
if (key !== "ArrowDown" && key !== "Enter" && key !== " ") return;
event.preventDefault();
if (key !== "ArrowDown") skipClick.current = true;
if (isOpen && key === "ArrowDown" && layer?.mode === "panel") focusFirst();
else onToggle(true);
}}
onKeyUp={() => {
setTimeout(() => {
skipClick.current = false;
});
}}
// A key that opened the panel has its keyup land inside it, so a press on the closed pill clears the skip. While
// open the skip stays: Safari does not focus a pressed button, so the panel closes on blur before this click.
onPointerDown={() => {
if (!isOpen) skipClick.current = false;
}}
onClick={() => {
if (skipClick.current) {
skipClick.current = false;
return;
}
onToggle(false);
}}
className={cn(
"relative flex h-full min-w-0 cursor-pointer items-center gap-2 rounded-[11px] ps-3.5 font-[inherit] text-[14px] leading-5 font-medium whitespace-nowrap outline-none group-data-[gliding]/pill:shrink-0",
"[-webkit-tap-highlight-color:transparent] pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-[3px] pointer-coarse:after:content-['']",
clearable ? "pe-1" : "pe-2.5",
raised && "z-[32]",
)}
>
{pill.icon && (
<span
aria-hidden="true"
className={cn(
"-ms-0.5 grid shrink-0 place-items-center transition-[color] duration-200",
set ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-mute,#BDBDBD)] group-data-[state=open]/pill:text-[var(--fu-accent-soft,#8FAAFF)]",
)}
>
{pill.icon}
</span>
)}
{/* A long label stops at 200px, and gives way before the value does; the whole words stay in the button's name.
The words take their own direction, so an English label on a right-to-left page loses its end, not its start. */}
<span
dir="auto"
className={cn(
"min-w-0 max-w-[200px] truncate transition-[color] duration-200 group-data-[gliding]/pill:shrink-0",
set ? "text-[var(--fu-accent-pale,#D1DDFF)]" : "text-[var(--fu-text,#F8F5F1)]",
)}
>
<SkeletonText>{pill.label}</SkeletonText>
</span>
{pill.summary && <span className="sr-only">, {pill.summary}</span>}
{count > 0 && <span className="sr-only">, {count} set</span>}
{valued && (
<>
<span aria-hidden="true" className="h-4 w-px shrink-0 bg-[var(--fu-accent-soft,#8FAAFF)]/30" />
<SkeletonText className="min-w-0 max-w-[200px] shrink-[0.25] group-data-[gliding]/pill:shrink-0">
<TextSwap
aria-hidden="true"
data-swap=""
dir="auto"
className="min-w-0 max-w-[200px] shrink-[0.25] grid-cols-[minmax(0,1fr)] font-normal text-[var(--fu-accent-soft,#8FAAFF)] tabular-nums [&>span]:truncate"
>
{summary || lastSummary}
</TextSwap>
</SkeletonText>
</>
)}
{count > 0 && <CountPill aria-hidden="true" on count={count} format={formatCount} className="-mx-0.5" />}
{!clearable && (
<ChevronDownIcon
size={16}
className={cn(
"shrink-0 transition-[rotate,color,opacity,filter,translate] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"starting:-translate-y-1 starting:opacity-0 starting:blur-[2px]",
set ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-mute,#BDBDBD)]",
"group-data-[state=open]/pill:rotate-180 group-data-[state=open]/pill:text-[var(--fu-accent-soft,#8FAAFF)]",
)}
/>
)}
</button>
{clearable && (
<button
type="button"
aria-label={`Clear ${pill.label.toLowerCase()}`}
onClick={() => {
pill.onClear?.();
trigger.current?.focus({ preventScroll: true });
}}
className={cn(
"relative me-1.5 grid size-7 shrink-0 cursor-pointer place-items-center rounded-[8px] text-[var(--fu-accent-soft,#8FAAFF)]",
"transition-[background-color,color,opacity,filter,translate] duration-150 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"starting:translate-y-1 starting:opacity-0 starting:blur-[2px]",
"hover:bg-[var(--fu-accent-soft,#8FAAFF)]/15 hover:text-[var(--fu-accent-pale,#D1DDFF)]",
"pointer-coarse:after:absolute pointer-coarse:after:-inset-2 pointer-coarse:after:content-['']",
FOCUS_RING,
"focus-visible:outline-offset-0",
raised && "z-[32]",
)}
>
<XIcon size={16} />
</button>
)}
{layer?.mode === "panel" && (
<PillPanel
key={layer.key}
id={panelId}
label={pill.label}
open={!layer.closing}
handoff={layer.closing && handoff}
focus={layer.focus}
set={set}
width={pill.width ?? 320}
footer={footer(false)}
onGone={() => onGone(layer)}
>
{pill.content}
</PillPanel>
)}
{layer?.mode === "sheet" && (
<PillSheet
key={layer.key}
id={panelId}
titleId={titleId}
title={pill.label}
summary={pill.summary ?? null}
open={!layer.closing}
onClose={() => onClose(true)}
footer={footer(true)}
onGone={() => onGone(layer)}
>
{pill.content}
</PillSheet>
)}
</div>
);
}
type PanelProps = {
id: string;
label: string;
open: boolean;
/** Closing because another pill opened: it fades where it is instead of folding back over the pills. */
handoff: boolean;
focus: boolean;
set: boolean;
width: number;
footer: ReactNode;
onGone: () => void;
children: ReactNode;
};
/**
* The panel under a pill. Its card starts as the pill's own outline and grows into place over 260ms while the filter,
* already in its final spot, is uncovered by it and rises 6px out of a 6px blur. Closing runs the other way: the filter
* blurs out and the card folds back into the pill. Offsets are layout values, so a zoomed or scaled page lines up.
*/
function PillPanel({ id, label, open, handoff, focus, set, width, footer, onGone, children }: PanelProps) {
const surface = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const scrollBox = useOverflows();
const placed = useRef<Rect | null>(null);
const done = useRef(onGone);
useLayoutEffect(() => {
done.current = onGone;
});
// The pill is the panel's parent and the bar the pill's; refs to them are not attached yet on a first render.
const pillOf = () => surface.current?.parentElement ?? null;
const pillRect = (): Rect | null => {
const node = pillOf();
return node ? { left: node.offsetLeft, top: node.offsetTop, width: node.offsetWidth, height: node.offsetHeight } : null;
};
// Right under its own pill, also when the bar wraps, so it never reads as another row's; the start edge lines up with
// the pill's (the right edge in RTL), kept inside the bar. Offsets are physical, from the bar's left. On phones, where only a panel open on first render shows in place, it sits under
// the whole bar instead, so the page never loads with pills hidden.
const panelRect = (pill: Rect): Rect | null => {
const bar = pillOf()?.parentElement;
const inner = content.current;
if (!bar || !inner) return null;
const room = bar.clientWidth;
const w = Math.min(width, room);
inner.style.width = `${w - 2}px`;
const left = Math.max(0, Math.min(isRtl(bar) ? pill.left + pill.width - w : pill.left, room - w));
const under = window.matchMedia(PHONE).matches ? bar.offsetHeight : pill.top + pill.height;
return { left, top: under + GAP, width: w, height: inner.offsetHeight + 2 };
};
// The corner under the pill's start edge keeps the pill's 12px radius when the edges line up: the card reads as grown
// out of the pill, and a pill on the next row, which starts at the same spot, never shows its corner behind the card.
const panelRadius = (rect: Rect) => {
const pill = pillRect();
const bar = pillOf()?.parentElement;
if (!pill || !bar) return "24px";
if (isRtl(bar)) return rect.left + rect.width === pill.left + pill.width ? "24px 12px 24px 24px" : "24px";
return rect.left === pill.left ? "12px 24px 24px 24px" : "24px";
};
const paint = (rect: Rect, look: "pill" | "panel" | "closed") => {
const node = surface.current;
if (!node) return;
node.style.left = `${rect.left}px`;
node.style.top = `${rect.top}px`;
node.style.width = `${rect.width}px`;
node.style.height = `${rect.height}px`;
node.style.borderRadius = look === "panel" ? panelRadius(rect) : "12px";
node.style.boxShadow = look === "panel" ? PANEL_SHADOW : NO_SHADOW;
node.style.borderColor = look === "panel" ? PANEL_LINE : look === "pill" ? OPEN_LINE : set ? "var(--fu-selected,#1F2747)" : PANEL_LINE;
node.style.backgroundColor = look === "panel" ? PANEL_BG : (pillOf() && getComputedStyle(pillOf()!).backgroundColor) || PANEL_BG;
};
// Keeps the filter where it ends up while the card around it moves: its offset runs the card's move backwards.
const hold = (card: Rect, final: Rect, rise: number) => {
const node = content.current;
if (node) node.style.translate = `${final.left - card.left}px ${final.top - card.top + rise}px`;
};
useLayoutEffect(() => {
const node = surface.current;
const inner = content.current;
const pill = pillRect();
const final = pill && panelRect(pill);
if (!node || !inner || !pill || !final) return;
placed.current = final;
if (reducedMotion()) {
paint(final, "panel");
hold(final, final, 0);
} else {
node.style.transition = "none";
inner.style.transition = "none";
paint(pill, "pill");
hold(pill, final, 6);
inner.style.opacity = "0";
inner.style.filter = "blur(6px)";
void node.offsetWidth;
const move = `260ms ${EASE}`;
node.style.transition = ["left", "top", "width", "height", "border-radius", "background-color", "border-color", "box-shadow"]
.map((p) => `${p} ${move}`)
.join(", ");
inner.style.transition = `translate ${move}, opacity 220ms ${REVEAL} 40ms, filter 220ms ${REVEAL} 40ms`;
paint(final, "panel");
hold(final, final, 0);
inner.style.opacity = "1";
inner.style.filter = "none";
}
if (focus) inner.querySelector<HTMLElement>(FOCUSABLE)?.focus();
// Runs once per panel: a new open mounts a new panel.
}, []);
// The card follows the filter's height (a list that grows) and the bar's width (a window resize) while open.
useEffect(() => {
const inner = content.current;
const node = surface.current;
const bar = pillOf()?.parentElement;
if (!open || !inner || !bar || !node) return;
let frame = 0;
const follow = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const pill = pillRect();
const final = pill && panelRect(pill);
const was = placed.current;
if (!final || !was) return;
if (final.left === was.left && final.top === was.top && final.width === was.width && final.height === was.height) return;
placed.current = final;
const quiet = reducedMotion();
const resize = final.width !== was.width || final.left !== was.left || final.top !== was.top;
node.style.transition = quiet || resize ? "none" : `height 300ms ${EASE}`;
inner.style.transition = "none";
paint(final, "panel");
hold(final, final, 0);
});
};
const observer = new ResizeObserver(follow);
observer.observe(inner);
observer.observe(bar);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
};
}, [open]);
useLayoutEffect(() => {
const node = surface.current;
const inner = content.current;
if (open || !node || !inner) return;
const pill = pillRect();
const final = placed.current;
if (reducedMotion() || !pill || !final) {
done.current();
return;
}
if (handoff) {
node.style.transition = "opacity 150ms ease-in-out, filter 150ms ease-in-out";
node.style.opacity = "0";
node.style.filter = "blur(2px)";
const timer = setTimeout(() => done.current(), 170);
return () => clearTimeout(timer);
}
const fold = `220ms ${FOLD}`;
node.style.transition = ["left", "top", "width", "height", "border-radius", "background-color", "border-color", "box-shadow"]
.map((p) => `${p} ${fold}`)
.join(", ");
inner.style.transition = `translate ${fold}, opacity 150ms ease-in-out, filter 150ms ease-in-out`;
paint(pill, "closed");
hold(pill, final, -4);
inner.style.opacity = "0";
inner.style.filter = "blur(2px)";
let finished = false;
const finish = () => {
if (finished) return;
finished = true;
done.current();
};
const timer = setTimeout(finish, 280);
const onEnd = (event: TransitionEvent) => {
if (event.target === node && event.propertyName === "height") finish();
};
node.addEventListener("transitionend", onEnd);
return () => {
clearTimeout(timer);
node.removeEventListener("transitionend", onEnd);
};
}, [open]);
return (
<div
ref={surface}
id={id}
role="dialog"
aria-label={label}
inert={!open}
// Written [left:0], not left-0, so shadcn's rtl option does not turn it into start-0 here or below.
// physical: placed from offsetLeft in script, which counts from the left in any direction.
className="absolute top-0 [left:0] z-30 box-border overflow-hidden border border-solid forced-colors:border-[CanvasText]"
>
{/* physical: moved by a translate measured from the left, as above. */}
<div ref={content} tabIndex={-1} className="absolute top-0 [left:0] flex flex-col text-[var(--fu-text,#F8F5F1)] outline-none will-change-[translate,opacity,filter]">
<div ref={scrollBox} className={cn("max-h-[min(560px,70vh)] overflow-y-auto data-[overflows]:overscroll-contain p-4", SCROLL)}>
{children}
</div>
<div className="flex items-center justify-between gap-2 px-4 pt-1 pb-4">{footer}</div>
</div>
</div>
);
}
type SheetProps = {
id: string;
titleId: string;
title: string;
summary: string | null;
open: boolean;
onClose: () => void;
footer: ReactNode;
onGone: () => void;
children: ReactNode;
};
/** A phone's panel: a modal sheet that slides up from the bottom over a dimmed page, with a Done-style footer. */
function PillSheet({ id, titleId, title, summary, open, onClose, footer, onGone, children }: SheetProps) {
const dialog = useRef<HTMLDialogElement>(null);
const sheet = useRef<HTMLDivElement>(null);
const [shown, setShown] = useState(false);
const done = useRef(onGone);
useLayoutEffect(() => {
done.current = onGone;
});
useLayoutEffect(() => {
const node = dialog.current;
if (!node) return;
const root = document.documentElement;
const overflow = root.style.overflow;
root.style.overflow = "hidden";
if (!node.open) node.showModal();
sheet.current?.focus({ preventScroll: true });
const frame = requestAnimationFrame(() => setShown(true));
return () => {
cancelAnimationFrame(frame);
root.style.overflow = overflow;
if (node.open) node.close();
};
}, []);
useEffect(() => {
const node = dialog.current;
if (open || !node) return;
setShown(false);
const lost = (el: Element | null) => !el || el === document.body || el.matches(":disabled") || Boolean(el.closest("[inert]"));
const finish = () => {
const was = document.activeElement;
const held = lost(was) || node.contains(was);
if (node.open) node.close();
// Closed by a change of state (loading or disabled), the sheet's own pill cannot take focus back, and the modal
// sheet kept the status frame from taking it: the frame takes it now, so focus is never lost to the page.
if (held && (lost(document.activeElement) || node.contains(document.activeElement))) {
node.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
}
done.current();
};
if (reducedMotion()) {
finish();
return;
}
const timer = setTimeout(finish, 340);
return () => clearTimeout(timer);
}, [open]);
return (
<dialog
ref={dialog}
id={id}
aria-labelledby={titleId}
data-state={shown ? "open" : "closed"}
onCancel={(event) => {
event.preventDefault();
onClose();
}}
className="group/sheet fixed inset-0 m-0 h-dvh border-0 max-h-none w-full max-w-none overflow-hidden bg-transparent p-0 text-[var(--fu-text,#F8F5F1)] backdrop:bg-transparent"
>
<div
aria-hidden="true"
onClick={onClose}
className="absolute inset-0 bg-[var(--fu-scrim,rgb(0_0_0/0.6))] opacity-0 transition-[opacity] duration-300 ease-out group-data-[state=open]/sheet:opacity-100 motion-reduce:transition-none"
/>
<div
ref={sheet}
tabIndex={-1}
className={cn(
"absolute inset-x-0 bottom-0 flex max-h-[88dvh] flex-col rounded-t-[24px] border-t border-[var(--fu-line,#404040)] bg-[var(--fu-card,#1F1F1F)] outline-none",
"translate-y-full transition-[translate] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] group-data-[state=open]/sheet:translate-y-0 motion-reduce:transition-none",
"group-data-[state=closed]/sheet:duration-300 group-data-[state=closed]/sheet:ease-[cubic-bezier(0.4,0,1,1)]",
)}
>
<div className="flex min-h-[60px] items-center gap-3 pe-2 ps-4">
<p id={titleId} className="m-0 min-w-0 flex-1 truncate text-[17px] leading-6 font-semibold">
{title}
{summary && <span className="ms-2 text-[15px] font-normal text-[var(--fu-accent-soft,#8FAAFF)] [unicode-bidi:isolate]">{summary}</span>}
</p>
<button
type="button"
aria-label="Close"
onClick={onClose}
className={cn(
"grid size-11 shrink-0 cursor-pointer place-items-center rounded-[10px] text-[var(--fu-mute,#BDBDBD)] transition-[background-color,color] duration-200 hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))] hover:text-[var(--fu-text,#F8F5F1)]",
FOCUS_RING,
"focus-visible:outline-offset-0",
)}
>
<XIcon size={20} />
</button>
</div>
<div className={cn("min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pt-1 pb-5", SCROLL)}>{children}</div>
<div className="flex items-center gap-2 border-t border-[var(--fu-card-border,#2A2A2A)] px-4 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]">
{footer}
</div>
</div>
</dialog>
);
}
```
### 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/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/lib/format.ts
```ts
// Numbers, prices, distances, percents and dates for one locale, built on Intl with no dependency. Pass any BCP 47
// tag ("de-DE", "ar-EG"); a tag Intl cannot read falls back to en-US instead of throwing. The default is en-US, never
// the browser's own locale, so the server and the browser always print the same text. UI words stay English.
export const DEFAULT_LOCALE = "en-US";
export type FormatOptions = {
/** ISO 4217 code for price and priceShort. Default "USD". */
currency?: string;
/** The unit of distance. Default "kilometer". */
unit?: "kilometer" | "mile";
};
/** Every formatter takes the value alone, so any of them can be passed straight to a format prop. */
export type Formats = {
/** The locale these formatters use, after any fallback. */
locale: string;
/** "1,234" in en-US, "1.234" in de-DE, up to three decimals. */
number: (value: number) => string;
/** A number with no group marks, such as a year: "2026", or "٢٠٢٦" in ar-EG. */
plain: (value: number) => string;
/** "45k", "1.2M". */
compact: (value: number) => string;
/** "$45,000" in en-US, "45.000 $" in de-DE: whole units of the currency. */
price: (value: number) => string;
/** "$45k" and "$97.5k" from a thousand up, "$950" below. */
priceShort: (value: number) => string;
/** "50,000 km" or "31,069 mi". */
distance: (value: number) => string;
/** A percentage given in percent, up to two decimals: 6.5 gives "6.5%" in en-US and "6,5 %" in de-DE. */
percent: (value: number) => string;
/** A day given as "YYYY-MM-DD", in words. Read in UTC, so it never shifts by a time zone. */
day: (iso: string, options: Intl.DateTimeFormatOptions) => string;
/** The name of a month, 0 for January. */
month: (index: number, style?: "long" | "short") => string;
/** The name of a weekday, 0 for Sunday. */
weekday: (index: number, style?: "long" | "short") => string;
/** The day weeks start on: 0 for Sunday, 1 for Monday, 6 for Saturday. */
firstDay: 0 | 1 | 5 | 6;
/** The locale's digits, 0 to 9: "0123456789", or "٠١٢٣٤٥٦٧٨٩" in ar-EG. */
digits: string;
/**
* Reads a number typed the locale's way, with an optional k or m: "45,000", "$45k" and "1.2m" in en-US, "45.000"
* and "1,2m" in de-DE. A unit such as "km" is not a suffix. Returns null when the text holds no number.
*/
readNumber: (text: string) => number | null;
};
/**
* A locale Intl has data for, or en-US. A well-formed tag with no data ("zz") would otherwise print in the
* runtime's own locale, which differs between server and browser.
*/
export function safeLocale(locale?: string): string {
if (!locale) return DEFAULT_LOCALE;
try {
const [tag] = Intl.getCanonicalLocales(locale);
if (!tag) return DEFAULT_LOCALE;
if (!Intl.NumberFormat.supportedLocalesOf(tag).length || !Intl.DateTimeFormat.supportedLocalesOf(tag).length) return DEFAULT_LOCALE;
return tag;
} catch {
return DEFAULT_LOCALE;
}
}
/** A currency code Intl can read, or USD. */
function safeCurrency(currency?: string): string {
if (!currency) return "USD";
try {
new Intl.NumberFormat(DEFAULT_LOCALE, { style: "currency", currency });
return currency.toUpperCase();
} catch {
return "USD";
}
}
// Where weeks start, by region, as CLDR 48 has it; every other region starts on Monday. A table rather than
// Intl.Locale weekInfo, which not every browser has, so the server and every browser agree.
const SUNDAY = new Set(
"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "),
);
const SATURDAY = new Set("AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
function firstDayOf(locale: string): 0 | 1 | 5 | 6 {
let region: string | undefined;
try {
region = new Intl.Locale(locale).maximize().region;
} catch {}
if (!region) return 0;
if (region === "MV") return 5;
if (SATURDAY.has(region)) return 6;
return SUNDAY.has(region) ? 0 : 1;
}
const cache = new Map<string, Formats>();
/** Formatters for one locale. Cheap to call on every render: each locale and option set is built once. */
export function formatsFor(locale?: string, options: FormatOptions = {}): Formats {
const tag = safeLocale(locale);
const currency = safeCurrency(options.currency);
const unit = options.unit === "mile" ? "mile" : "kilometer";
const key = `${tag}|${currency}|${unit}`;
const known = cache.get(key);
if (known) return known;
const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(tag, o);
const dates = new Map<string, Intl.DateTimeFormat>();
const df = (o: Intl.DateTimeFormatOptions) => {
const id = JSON.stringify(o);
let format = dates.get(id);
if (!format) {
format = new Intl.DateTimeFormat(tag, { ...o, timeZone: "UTC" });
dates.set(id, format);
}
return format;
};
// English writes thousands with a small k, as the filters always have.
const english = tag === "en" || tag.startsWith("en-");
const smallK = (text: string) => (english ? text.replace(/K\b/, "k") : text);
const number = nf({});
const plain = nf({ useGrouping: false, maximumFractionDigits: 20 });
const compact = nf({ notation: "compact", maximumFractionDigits: 1 });
const price = nf({ style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0 });
// One decimal is exact for a 1,000 unit ("$97.5k"); a 10,000 unit such as 万 takes two ("$9.75万").
const unitDigits = nf({ notation: "compact", useGrouping: false }).formatToParts(10000).filter((p) => p.type === "integer").map((p) => p.value).join("").length;
const priceShort = nf({ style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: Math.max(1, 3 - unitDigits) });
const distance = nf({ style: "unit", unit, maximumFractionDigits: 0 });
const percent = nf({ style: "percent", maximumFractionDigits: 2 });
const digits = plain.format(1234567890).replace(/^(.*)(.)$/, "$2$1");
const parts = number.formatToParts(12345.6);
const group = parts.find((p) => p.type === "group")?.value ?? ",";
const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";
const formats: Formats = {
locale: tag,
number: (value) => number.format(value),
plain: (value) => plain.format(value),
compact: (value) => smallK(compact.format(value)),
price: (value) => price.format(value),
priceShort: (value) => (Math.abs(value) >= 1000 ? smallK(priceShort.format(value)) : price.format(value)),
distance: (value) => distance.format(value),
percent: (value) => percent.format(value / 100),
day: (iso, o) => df(o).format(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)))),
month: (index, style = "long") => df({ month: style }).format(Date.UTC(2021, index, 1)),
// 3 January 2021 was a Sunday.
weekday: (index, style = "long") => df({ weekday: style }).format(Date.UTC(2021, 0, 3 + index)),
firstDay: firstDayOf(tag),
digits,
readNumber: (text) => {
let t = text.replace(/[\s ]/g, "");
for (let i = 0; i < 10; i++) t = t.split(digits[i]).join(String(i));
if (!/\s/.test(group)) t = t.split(group).join("");
// Marks typed in place of the locale's own: a Latin or Arabic comma where both marks are Arabic, a curly apostrophe for a straight one.
if (!/[.,]/.test(group + decimal)) t = t.replace(/[,\u060c]/g, "");
if (group === "'") t = t.split("\u2019").join("");
if (decimal !== ".") t = t.split(decimal).join(".");
const match = t.match(/(\d*\.?\d+)([km](?![a-z]))?/i);
if (!match) return null;
const scale = match[2] ? (match[2].toLowerCase() === "k" ? 1e3 : 1e6) : 1;
return Number(match[1]) * scale;
},
};
cache.set(key, formats);
return formats;
}
/** "1 result", "1,204 results": the default words for a count, with the number in the locale. */
export const resultsLabel = (n: number, locale?: string) => `${formatsFor(locale).number(n)} ${n === 1 ? "result" : "results"}`;
```
### components/filters-ui/lib/overflow.ts
```ts
import { useCallback, useRef } from "react";
/**
* A ref for a box that scrolls: it marks the box `data-overflows` while its content is taller than the box. Chromium
* counts a box with overflow-y auto as a scroll container even when it has nothing to scroll, so overscroll-contain on
* it stops the page from scrolling under the pointer or a finger. Such a box contains only while it overflows:
* `data-[overflows]:overscroll-contain`.
*/
export function useOverflows<T extends HTMLElement = HTMLDivElement>() {
const stop = useRef<(() => void) | null>(null);
return useCallback((node: T | null) => {
stop.current?.();
stop.current = null;
if (!node) return;
let live = true;
let settling = false;
const measure = () => {
if (!live) return;
node.toggleAttribute("data-overflows", node.scrollHeight > node.clientHeight + 1);
// Content that moves in (a rise, a slide) overflows until it lands, and landing resizes nothing: measure again then.
if (settling) return;
// Only animations still running: a finished one held by fill is listed too, and its settled promise would loop.
const moving = node
.getAnimations({ subtree: true })
.filter((animation) => animation.playState === "running" && animation.effect?.getComputedTiming().endTime !== Infinity);
if (!moving.length) return;
settling = true;
void Promise.allSettled(moving.map((animation) => animation.finished)).then(() => {
settling = false;
measure();
});
};
// A box stops growing at its max height while its content goes on, so the content is watched too.
const sizes = new ResizeObserver(measure);
const watch = () => {
sizes.disconnect();
sizes.observe(node);
for (const child of node.children) sizes.observe(child);
};
const children = new MutationObserver(watch);
watch();
children.observe(node, { childList: true });
stop.current = () => {
live = false;
sizes.disconnect();
children.disconnect();
};
}, []);
}
```
### components/filters-ui/lib/scroll.ts
```ts
/**
* A slim scrollbar for every box that scrolls: a 6px rounded thumb in the line colour on a clear track, stronger under
* the pointer, kept 2px off the side and 12px off each end so it never runs into a rounded corner.
* Chromium and Safari draw it from the ::-webkit-scrollbar parts. Firefox has none of those, so it alone gets the
* standard thin bar in the same colours: Chromium ignores the parts once scrollbar-width or scrollbar-color is set,
* so never add either beside this class.
*/
export const SCROLL =
"supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-width:thin] supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-color:var(--fu-line,#404040)_transparent] " +
"[&::-webkit-scrollbar]:size-2.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent " +
"[&::-webkit-scrollbar-track:vertical]:my-3 [&::-webkit-scrollbar-track:horizontal]:mx-3 " +
"[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-padding " +
"[&::-webkit-scrollbar-thumb]:bg-[var(--fu-line,#404040)] [&::-webkit-scrollbar-thumb:hover]:bg-[var(--fu-control-border,#737373)] [&::-webkit-scrollbar-thumb:active]:bg-[var(--fu-control-border,#737373)]";
```
### components/filters-ui/ui/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/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>
);
}
```
### components/filters-ui/ui/text-swap.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
export type TextSwapProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
/** The text to show. A change animates: the old text leaves upward, the new one rises in. */
children: string;
};
const EASE = "cubic-bezier(0.42, 0, 0.58, 1)";
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
/** Old text leaves over 150ms; new text enters over 170ms after 110ms; both move 4px through a 2px blur. */
export function TextSwap({ children, className, ...props }: TextSwapProps) {
const [shown, setShown] = useState(children);
const [leaving, setLeaving] = useState<{ text: string; key: number } | null>(null);
const nowRef = useRef<HTMLSpanElement>(null);
const oldRef = useRef<HTMLSpanElement>(null);
if (children !== shown) {
setLeaving(reducedMotion() ? null : { text: shown, key: (leaving?.key ?? 0) + 1 });
setShown(children);
}
useLayoutEffect(() => {
if (!leaving) return;
const out = oldRef.current?.animate(
[
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
{ opacity: 0, transform: "translateY(-4px)", filter: "blur(2px)" },
],
{ duration: 150, easing: EASE, fill: "forwards" },
);
const into = nowRef.current?.animate(
[
{ opacity: 0, transform: "translateY(4px)", filter: "blur(2px)" },
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
],
{ duration: 170, delay: 110, easing: EASE, fill: "backwards" },
);
const key = leaving.key;
const done = () => setLeaving((current) => (current?.key === key ? null : current));
if (into) into.onfinish = done;
else done();
return () => {
out?.cancel();
into?.cancel();
};
}, [leaving]);
return (
<span className={cn("inline-grid whitespace-nowrap", className)} {...props}>
<span ref={nowRef} className="[grid-area:1/1]">
{shown}
</span>
{leaving && (
<span ref={oldRef} key={leaving.key} aria-hidden="true" className="pointer-events-none [grid-area:1/1]">
{leaving.text}
</span>
)}
</span>
);
}
```
### components/filters-ui/ui/icons.tsx
```tsx
import type { ReactNode, SVGProps } from "react";
/*
* Icon paths from Lucide (https://lucide.dev), ISC License.
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT).
* All other copyright (c) for Lucide are held by Lucide Contributors 2022.
* Permission to use, copy, modify, and/or distribute this software for any purpose with or
* without fee is hereby granted, provided that the above copyright notice and this permission
* notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number };
function Icon({ size = 20, strokeWidth = 2, children, ...props }: IconProps & { children: ReactNode }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...props}
>
{children}
</svg>
);
}
export function ChevronDownIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m6 9 6 6 6-6" />
</Icon>
);
}
export function XIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</Icon>
);
}
export function CheckIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M20 6 9 17l-5-5" />
</Icon>
);
}
export function SearchIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function ArrowUpRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M7 7h10v10" />
<path d="M7 17 17 7" />
</Icon>
);
}
export function PlusIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="M12 5v14" />
</Icon>
);
}
export function CopyIcon(props: IconProps) {
return (
<Icon {...props}>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</Icon>
);
}
export function SlidersIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 4h-7" />
<path d="M10 4H3" />
<path d="M21 12h-9" />
<path d="M8 12H3" />
<path d="M21 20h-5" />
<path d="M12 20H3" />
<path d="M14 2v4" />
<path d="M8 10v4" />
<path d="M16 18v4" />
</Icon>
);
}
export function ArrowRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</Icon>
);
}
export function SearchXIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m13.5 8.5-5 5" />
<path d="m8.5 8.5 5 5" />
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function StarIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</Icon>
);
}
export function HistoryIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M12 7v5l4 2" />
</Icon>
);
}
export function ListTreeIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 12h-8" />
<path d="M21 6H8" />
<path d="M21 18h-8" />
<path d="M3 6v4c0 1.1.9 2 2 2h3" />
<path d="M3 10v6c0 1.1.9 2 2 2h3" />
</Icon>
);
}
export function CircleAlertIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</Icon>
);
}
```
### components/filters-ui/ui/status-frame.tsx
```tsx
"use client";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";
/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";
/**
* The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
* filter knows them all. Spread them into an item's own props type.
*/
export type StateProps = {
/** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
status?: Status;
/** Called by the Retry button. Without it the error line has no button. */
onRetry?: () => void;
/** The error line. Default "Couldn't load the options." */
errorText?: string;
/** The line shown in place of the options when there are none. Default "No options to show" */
emptyText?: string;
/** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
disabled?: boolean;
};
export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";
/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
type Mode = "ready" | "loading" | "error" | "empty";
/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);
export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
Omit<StateProps, "emptyText"> & {
/** There are no options: emptyText shows in place of the content. */
empty?: boolean;
emptyText?: ReactNode;
/** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
emptyArt?: string | ReactNode | null;
/** Words read once while loading. Default "Loading". */
loadingText?: string;
/** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
announce?: boolean;
retryLabel?: string;
children: ReactNode;
};
/**
* Wraps an item's content and gives it the shared states.
* - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
* placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
* - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
* status region that stays on the page.
* - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
* - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
* read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
* When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
* A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
* it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
* with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
* frame and let an inner frame around the part that fails speak.
*/
export function StatusFrame({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
empty = false,
emptyText = DEFAULT_EMPTY_TEXT,
emptyArt,
disabled = false,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
children,
...props
}: StatusFrameProps) {
const frame = useRef<HTMLDivElement>(null);
const outer = useLoading();
const saidAbove = useContext(SaidLoading);
const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";
// The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
const [lastStatus, setLastStatus] = useState(status);
const [arriving, setArriving] = useState(false);
if (status !== lastStatus) {
setLastStatus(status);
setArriving(lastStatus === "loading" && status === "ready");
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arriving]);
// Whether focus sat on a control inside, read just before a change of state is drawn.
const key = `${mode}|${disabled}`;
const drawnKey = useRef(key);
const focusWasInside = useRef(false);
if (key !== drawnKey.current && typeof document !== "undefined") {
const active = document.activeElement;
focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
}
useLayoutEffect(() => {
if (drawnKey.current === key) return;
drawnKey.current = key;
if (!focusWasInside.current) return;
focusWasInside.current = false;
const node = frame.current;
// The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
});
return (
<div
ref={frame}
tabIndex={-1}
data-status-frame=""
data-status={mode}
aria-busy={mode === "loading" || undefined}
className={cn(
"min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50 select-none",
className,
)}
{...props}
>
<SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
<LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
{mode === "empty" ? (
emptyArt === null ? (
<EmptyNote>{emptyText}</EmptyNote>
) : (
<EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
)
) : mode === "error" ? null : (
// display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
<fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
{children}
</fieldset>
)}
</LoadingContext.Provider>
</SaidLoading.Provider>
<StatusLine
status={mode === "loading" || mode === "error" ? mode : "ready"}
onRetry={onRetry}
errorText={errorText}
loadingText={saidAbove ? "" : loadingText}
announce={announce}
retryLabel={retryLabel}
/>
</div>
);
}
export type StatusLineProps = {
status?: Status;
/** Called by Retry. Without it the error line has no button. */
onRetry?: () => void;
errorText?: string;
loadingText?: string;
/** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
announce?: boolean;
retryLabel?: string;
/** Classes for the line while it shows an error, e.g. its margins. */
className?: string;
};
/**
* What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
* Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
* no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
* Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
*/
export function StatusLine({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
}: StatusLineProps) {
const error = status === "error";
const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
return (
// The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
<div className={error ? cn(ERROR_LINE, className) : "contents"}>
<p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
{error && <ErrorGlyph />}
{said && <span dir="auto">{said}</span>}
</p>
{error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
/**
* For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
* away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
* never dropped to the page.
*/
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
const drawn = useRef(key);
const had = useRef(false);
if (key !== drawn.current && typeof document !== "undefined") {
const active = document.activeElement;
had.current = !!scope.current && !!active && scope.current.contains(active);
}
useLayoutEffect(() => {
if (drawn.current === key) return;
drawn.current = key;
if (!had.current) return;
had.current = false;
const node = scope.current;
if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
});
}
```
### components/filters-ui/ui/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/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/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/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/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/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>
);
}
```
## What it does
- A pill's panel unfolds out of the pill: its outline grows into a card under it while the filter rises in from a blur, then folds back on close.
- A set pill turns blue and reads its value, "Price | $15k to $45k", with a cross to clear it; the pill eases to its new width as the value changes.
- Filters apply as they change, so the panel's "Show 34 cars" only closes it. Clear all fades in once anything is set.
- The bar wraps onto more rows instead of scrolling sideways. On phones a pill opens a sheet from the bottom with 44px targets.
## Props and value
FilterPills (components/filters-ui/filters/filter-pills.tsx) holds this value: None of its own: each pill shows a filter you keep in your own state. open is the id of the open pill, or null.
- pills: readonly FilterPill[] (required). One per pill, in order: { id, label, summary?, count?, onClear?, icon?, width?, content }.
- pill.summary: string | null (optional). The value in words, shown on the pill after its label. Null or empty means unset.
- pill.count: number (optional). For a pill that holds several filters, such as More filters: how many are set, shown as a count.
- pill.onClear: () => void (optional). Clears what the pill holds. A set pill then shows a cross, and its panel a Clear button.
- pill.content / pill.width: ReactNode / number (default — / 320). The filter shown in the panel, and the panel's width in px (never wider than the bar).
- label: string (default "Filters"). Accessible name of the bar.
- open / defaultOpen / onOpenChange: string | null / string | null / (id: string | null) => void (default closed). The open pill, controlled or not. A pill open on first render shows its panel in place, on phones too.
- onClearAll: () => void (optional). Clears every pill. "Clear all" fades in at the end of the bar once a pill is set.
- showLabel / onShow: string / () => void (default "Done"). The button at the foot of each panel, e.g. "Show 34 cars". It closes the panel; filters apply as they change.
- clearAllLabel / formatCount: string / (n: number) => string (default "Clear all" / 1,234). Words of Clear all, and the text in a pill's count.
- locale: string (default "en-US"). Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the filters."). The error line, in plain words.
- disabled: boolean (default false). Dims the bar, turns every pill off and leaves the crosses and Clear all out.
## States
Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.
- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. Each pill keeps its size and outline, and a set pill its fill, while its name, its value and Clear all draw as placeholders; no panel opens until the data is in. It is aria-busy and says "Loading" once; when status turns back to "ready" the data fades in once. No spinner.
- Error (status="error", with onRetry and errorText): one calm line and a Retry button that calls onRetry, in the filter's own place. The line and Retry take the pills' place. The default line is "Couldn't load the filters." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. Every pill is turned off and no panel opens; the crosses and Clear all are left out.
- Long labels (data, not a prop): A long name or value stops at 200px with an ellipsis, and the name gives way before the value; the whole words stay in the pill's spoken name.
- Many options (data, not a prop): The bar wraps onto as many rows as it needs, Clear all at the end of the last; it never scrolls sideways.
## Usage
A working example with a few made-up cars. Imports assume @/ points at the project root; change @/components/filters-ui if this project uses another alias.
```tsx
"use client";
import { useState } from "react";
import { ChipGroup } from "@/components/filters-ui/filters/chip-group";
import { FilterPills } from "@/components/filters-ui/filters/filter-pills";
import { RangeHistogram } from "@/components/filters-ui/filters/range-histogram";
import { SegmentedChoice } from "@/components/filters-ui/filters/segmented-choice";
import type { RangeValue } from "@/components/filters-ui/ui/range-chart";
type Car = { name: string; price: number; body: string; fuel: string; seats: number };
const CARS: Car[] = [
{ name: "Toyota Corolla", price: 22900, body: "Sedan", fuel: "Gas", seats: 5 },
{ name: "Honda Civic", price: 26500, body: "Sedan", fuel: "Gas", seats: 5 },
{ name: "Mazda CX-5", price: 28400, body: "SUV", fuel: "Gas", seats: 5 },
{ name: "Toyota RAV4", price: 31900, body: "SUV", fuel: "Hybrid", seats: 5 },
{ name: "Hyundai Tucson", price: 32700, body: "SUV", fuel: "Plug-in hybrid", seats: 5 },
{ name: "Subaru Outback", price: 34800, body: "SUV", fuel: "Gas", seats: 5 },
{ name: "Tesla Model 3", price: 36900, body: "Sedan", fuel: "Electric", seats: 5 },
{ name: "Honda Odyssey", price: 38400, body: "Minivan", fuel: "Gas", seats: 8 },
{ name: "Kia Sorento", price: 39500, body: "SUV", fuel: "Hybrid", seats: 7 },
{ name: "Kia Telluride", price: 42500, body: "SUV", fuel: "Gas", seats: 8 },
{ name: "Toyota Sienna", price: 44900, body: "Minivan", fuel: "Hybrid", seats: 8 },
{ name: "Tesla Model Y", price: 46900, body: "SUV", fuel: "Electric", seats: 7 },
{ name: "Toyota Highlander", price: 48700, body: "SUV", fuel: "Hybrid", seats: 8 },
{ name: "Ford F-150", price: 52900, body: "Truck", fuel: "Gas", seats: 6 },
{ name: "BMW X3", price: 58800, body: "SUV", fuel: "Plug-in hybrid", seats: 5 },
{ name: "Ford Mustang Mach-E", price: 66500, body: "SUV", fuel: "Electric", seats: 5 },
];
type Filters = { price: RangeValue; bodies: string[]; fuels: string[]; seats: number | null };
type Key = keyof Filters;
const EMPTY: Filters = { price: [null, null], bodies: [], fuels: [], seats: null };
const TESTS: Record<Key, (car: Car, f: Filters) => boolean> = {
price: (car, { price: [low, high] }) => (low === null || car.price >= low) && (high === null || car.price <= high),
bodies: (car, f) => !f.bodies.length || f.bodies.includes(car.body),
fuels: (car, f) => !f.fuels.length || f.fuels.includes(car.fuel),
seats: (car, f) => f.seats === null || car.seats >= f.seats,
};
// Each count leaves its own filter out, so it says how many cars picking that option would give.
const matching = (f: Filters, skip?: Key) =>
CARS.filter((car) => (Object.keys(TESTS) as Key[]).every((key) => key === skip || TESTS[key](car, f)));
const countBy = (f: Filters, skip: Key, value: (car: Car) => string | number) => {
const counts = new Map<string | number, number>();
for (const car of matching(f, skip)) counts.set(value(car), (counts.get(value(car)) ?? 0) + 1);
return counts;
};
const MIN = 0;
const MAX = 100000;
const STEP = 2500;
const BARS = 20;
const whole = new Intl.NumberFormat("en-US");
const tenths = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 });
const money = (value: number) => `$${whole.format(value)}`;
const short = (value: number) => (value >= 1000 ? `$${tenths.format(value / 1000)}k` : money(value));
const carCount = (n: number) => (n === 1 ? "1 car" : `${n} cars`);
function priceSummary([low, high]: RangeValue) {
if (low !== null && high !== null) return `${short(low)} to ${short(high)}`;
if (high !== null) return `Under ${short(high)}`;
if (low !== null) return `Over ${short(low)}`;
return null;
}
const list = (values: string[]) => (values.length <= 2 ? values.join(", ") : `${values.slice(0, 2).join(", ")} +${values.length - 2}`);
export default function FilterPillsExample() {
const [filters, setFilters] = useState<Filters>({ ...EMPTY, price: [15000, 45000] });
const set = (patch: Partial<Filters>) => setFilters((f) => ({ ...f, ...patch }));
const results = matching(filters);
const buckets = Array.from({ length: BARS }, () => 0);
for (const car of matching(filters, "price")) buckets[Math.min(BARS - 1, Math.floor((car.price / MAX) * BARS))] += 1;
const bodies = countBy(filters, "bodies", (car) => car.body);
const fuels = countBy(filters, "fuels", (car) => car.fuel);
const seats = matching(filters, "seats");
return (
<div className="w-full max-w-[560px]">
<FilterPills
label="Filters"
// Price starts open here, to show its panel.
defaultOpen="price"
showLabel={`Show ${carCount(results.length)}`}
onClearAll={() => setFilters(EMPTY)}
pills={[
{
id: "price",
label: "Price",
summary: priceSummary(filters.price),
onClear: () => set({ price: [null, null] }),
width: 360,
content: (
<RangeHistogram
min={MIN}
max={MAX}
step={STEP}
value={filters.price}
onChange={(price) => set({ price })}
buckets={buckets}
format={money}
labels={{ low: "Lowest price", high: "Highest price" }}
/>
),
},
{
id: "body",
label: "Body style",
summary: filters.bodies.length ? list(filters.bodies) : null,
onClear: () => set({ bodies: [] }),
content: (
<ChipGroup
label="Body style"
options={["SUV", "Sedan", "Minivan", "Truck"].map((body) => ({ value: body, label: body, count: bodies.get(body) ?? 0 }))}
value={filters.bodies}
onChange={(next) => set({ bodies: next })}
countLabel={carCount}
/>
),
},
{
id: "fuel",
label: "Fuel",
summary: filters.fuels.length ? list(filters.fuels) : null,
onClear: () => set({ fuels: [] }),
content: (
<ChipGroup
label="Fuel"
options={["Gas", "Hybrid", "Plug-in hybrid", "Electric"].map((fuel) => ({ value: fuel, label: fuel, count: fuels.get(fuel) ?? 0 }))}
value={filters.fuels}
onChange={(next) => set({ fuels: next })}
countLabel={carCount}
/>
),
},
{
id: "seats",
label: "Seats",
summary: filters.seats === null ? null : `${filters.seats}+`,
onClear: () => set({ seats: null }),
content: (
<SegmentedChoice<number | null>
label="Seats"
options={[
{ value: null, label: "Any" },
...[6, 7, 8].map((min) => ({ value: min, label: `${min}+`, count: seats.filter((car) => car.seats >= min).length })),
]}
value={filters.seats}
onChange={(next) => set({ seats: next })}
countLabel={carCount}
/>
),
},
]}
/>
<p aria-live="polite" className="mt-4 px-1 text-[14px] leading-5 tabular-nums">
<span className="font-medium">{results.length}</span> <span className="text-[var(--fu-dim,#929292)]">of {CARS.length} cars</span>
</p>
</div>
);
}
```
## Connect it to my data
Ask me which filters the bar should hold and where my items come from. Keep my filters in my own state, as the example does: each pill gets its filter as content, its value in words as summary, and an onClear. Pick 4 to 6 filters people use most and put the rest in a last pill such as More filters, with count set to how many of them are set. Count each option with every other filter applied but its own left out, and pass the number of matching items into showLabel. The panel opens in place under its pill, so put the bar where no parent clips overflow, as a toolbar above results usually is.
## 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-control-border: #737373;
--fu-control-hover: #A3A3A3;
--fu-dim: #929292;
--fu-field-border: #737373;
--fu-handle: #F8F5F1;
--fu-handle-edge: rgb(0 0 0/0.25);
--fu-hover: #333333;
--fu-hover-wash: rgb(255 255 255/0.14);
--fu-input: rgb(0 0 0/0);
--fu-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-scrim: rgb(0 0 0/0.6);
--fu-segment-track: #2A2A2A;
--fu-selected: #1F2747;
--fu-shadow: rgb(0 0 0/0.5);
--fu-skeleton: rgb(255 255 255/0.12);
--fu-skeleton-on: rgb(143 170 255/0.3);
--fu-surface-1: #171717;
--fu-surface-3: #2A2A2A;
--fu-text: #F8F5F1;
--fu-thumb: #404040;
--fu-wash: rgb(255 255 255/0.08);
}
```
To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).
```css
.light {
--fu-accent: #3B57E6;
--fu-accent-hover: #2F4AD0;
--fu-accent-pale: #253A9E;
--fu-accent-soft: #3049D2;
--fu-bar: rgb(255 255 255/0.94);
--fu-bar-out: #D6D6D2;
--fu-card: #FFFFFF;
--fu-card-border: #E5E5E2;
--fu-control-border: #787874;
--fu-control-hover: #5B5B57;
--fu-dim: #555552;
--fu-field-border: #949490;
--fu-handle: #FFFFFF;
--fu-handle-edge: rgb(29 27 24/0.55);
--fu-hover: rgb(29 27 24/0.11);
--fu-hover-wash: rgb(29 27 24/0.07);
--fu-input: #FFFFFF;
--fu-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-scrim: rgb(29 27 24/0.32);
--fu-segment-track: rgb(29 27 24/0.07);
--fu-selected: #E8EDFD;
--fu-shadow: rgb(36 36 33/0.12);
--fu-skeleton: rgb(29 27 24/0.09);
--fu-skeleton-on: rgb(48 73 210/0.18);
--fu-surface-1: #FFFFFF;
--fu-surface-3: rgb(29 27 24/0.07);
--fu-text: #1B1B19;
--fu-thumb: #FFFFFF;
--fu-wash: rgb(29 27 24/0.05);
}
```
Keep the sizes, corners, spacing and motion as they are.
## Direction and language
It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.
Pass locale (default "en-US") to print its numbers, prices and dates the way a language writes them and to read typed numbers that way, e.g. locale="de-DE". The words stay English: change them through the props.
## Keep the accessibility
- Pills are buttons with aria-expanded and aria-controls, read as their label and value ("Price, $15k to $45k").
- The panel is a non-modal dialog named after its pill; on phones the sheet is a modal dialog that keeps focus inside and gives it back on close.
- Each cross is a button named "Clear price"; the value swap and the unfold are skipped when reduced motion is asked for.
- Loading, the bar is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the bar. Disabled, the bar is aria-disabled and every pill is a disabled button.
- Each pill is one tab stop, and a set pill's cross is the next.
- Enter, Space or Down opens a pill and moves focus to the first control in its panel; Down on an open pill does the same.
- Escape closes the panel and returns to the pill; tabbing past the last control closes it too.
- While disabled no pill takes focus; in an error Tab reaches Retry.
When done, run the app, tell me which page to open, and show me the value changing as I use the filter.What it does
- A pill's panel unfolds out of the pill: its outline grows into a card under it while the filter rises in from a blur, then folds back on close.
- A set pill turns blue and reads its value, "Price | $15k to $45k", with a cross to clear it; the pill eases to its new width as the value changes.
- Filters apply as they change, so the panel's "Show 34 cars" only closes it. Clear all fades in once anything is set.
- The bar wraps onto more rows instead of scrolling sideways. On phones a pill opens a sheet from the bottom with 44px targets.
Keyboard
- Each pill is one tab stop, and a set pill's cross is the next.
- Enter, Space or Down opens a pill and moves focus to the first control in its panel; Down on an open pill does the same.
- Escape closes the panel and returns to the pill; tabbing past the last control closes it too.
- While disabled no pill takes focus; in an error Tab reaches Retry.
Props
Value. None of its own: each pill shows a filter you keep in your own state. open is the id of the open pill, or null.
| Prop | Description |
|---|---|
pillsRequired | One per pill, in order: { id, label, summary?, count?, onClear?, icon?, width?, content }. readonly FilterPill[] |
pill.summaryOptional | The value in words, shown on the pill after its label. Null or empty means unset. string | null |
pill.countOptional | For a pill that holds several filters, such as More filters: how many are set, shown as a count. number |
pill.onClearOptional | Clears what the pill holds. A set pill then shows a cross, and its panel a Clear button. () => void |
pill.content / pill.widthDefault — / 320 | The filter shown in the panel, and the panel's width in px (never wider than the bar). ReactNode / number |
labelDefault "Filters" | Accessible name of the bar. string |
open / defaultOpen / onOpenChangeDefault closed | The open pill, controlled or not. A pill open on first render shows its panel in place, on phones too. string | null / string | null / (id: string | null) => void |
onClearAllOptional | Clears every pill. "Clear all" fades in at the end of the bar once a pill is set. () => void |
showLabel / onShowDefault "Done" | The button at the foot of each panel, e.g. "Show 34 cars". It closes the panel; filters apply as they change. string / () => void |
clearAllLabel / formatCountDefault "Clear all" / 1,234 | Words of Clear all, and the text in a pill's count. string / (n: number) => string |
localeDefault "en-US" | Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English. string |
statusDefault "ready" | "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place. "ready" | "loading" | "error" |
onRetryOptional | Called by Retry in the error state. Without it the error line has no button. () => void |
errorTextDefault "Couldn't load the filters." | The error line, in plain words. string |
disabledDefault false | Dims the bar, turns every pill off and leaves the crosses and Clear all out. boolean |