Live example
34cars
Copy
Add the "Select" component from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Select: A field that opens a list to pick one value from, drawn in the filters' own style.
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/select.json
and skip the files below.
Otherwise save each file below at the path shown, from the project root (or inside src/ if the project keeps its code there). Keep the folder layout: the files import each other by relative paths.
Install these npm packages: npm install clsx tailwind-merge
### components/filters-ui/ui/select.tsx
```tsx
"use client";
import { useId, useLayoutEffect, useRef, useState, type ButtonHTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { ChevronDownIcon } from "./icons";
import { typesCharacter, keepRowInView, LIST_PANEL, ListCheck, ListCount, PopoverPanel, RowHighlight, useTypeAhead } from "./popover";
import { ARRIVING, SkeletonText, useLoading } from "./skeleton";
import { StatusFrame, type StateProps } from "./status-frame";
import { TextSwap } from "./text-swap";
export type SelectOption = {
value: string;
label: string;
disabled?: boolean;
/** How many items this choice gives. Shown as a short bar and a number; an option at 0 is dimmed and cannot be picked. */
count?: number;
};
export type SelectProps = Omit<
ButtonHTMLAttributes<HTMLButtonElement>,
"value" | "onChange" | "prefix" | "children" | "defaultValue" | "name" | "role"> &
StateProps & {
value: string;
onChange: (value: string) => void;
options: readonly SelectOption[];
/** Accessible name of the field and its list. Include the visible prefix in it ("From year" for "From"). */
label: string;
/** Muted text before the chosen value, e.g. "From". */
prefix?: ReactNode;
/** Shown, muted, while no option matches value. Default: the label of the option whose value is "". */
placeholder?: string;
/** Sends the value with a form under this name. */
name?: string;
/** A line at the top of the list, e.g. "Toyota models". Not read out: the label names the list. */
heading?: ReactNode;
/** Shown in the open list when there are no options, and muted in the field when there is no placeholder. Default "No choices". */
emptyText?: string;
/** Text of each count. Default 1,234. */
formatCount?: (n: number) => string;
/** Screen-reader words for a count, read after the option's name. Default "6 results". */
countLabel?: (n: number) => string;
/** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
locale?: string;
/** A quieter field (--fu-line border, dim text) while it waits on another choice, such as Model before a make. It still opens. */
waiting?: boolean;
/** Classes for the outer wrapper, e.g. its width. */
className?: string;
/** Draws the list open in place, for a still picture. Nothing responds. */
still?: boolean;
};
const PAGE = 10;
/**
* The value in the field. Inside a loading StatusFrame, its own or a filter's, a bar stands in for it; when the data
* arrives it fades in once. A component of its own, so it reads the frame Select draws around itself.
*/
function Value({ text, empty, waiting }: { text: string; empty: boolean; waiting: boolean }) {
const { loading, arriving } = useLoading();
if (loading) {
return (
<span className="min-w-0 flex-1 truncate tabular-nums">
<SkeletonText>{text}</SkeletonText>
</span>
);
}
return (
<TextSwap
data-empty={empty || undefined}
className={cn(
"min-w-0 flex-1 grid-cols-[minmax(0,1fr)] tabular-nums transition-[color] duration-[480ms] [&>span]:truncate",
waiting ? "text-[var(--fu-dim,#929292)]" : "data-[empty]:text-[var(--fu-mute,#BDBDBD)]",
arriving && ARRIVING,
)}
>
{text}
</TextSwap>
);
}
/**
* A select drawn like TextField (44px, 12px radius, --fu-field-border border, 15px text, a chevron) whose list grows out of the
* field in a panel of its own instead of the system menu. One highlight marks the active row; the chosen row is
* tinted with a check that draws in; options with counts show a bar for their share that grows in the first time the list opens.
* Focus stays on the field: arrows, Home, End, Page Up and Page Down move, typing finds an option by its first letters,
* Enter or Space picks, Escape closes. The option whose value is "" is the empty choice and shows muted, like a placeholder.
* Inside a loading StatusFrame the field keeps its box and a bar stands in for the value, which fades in once when it arrives.
*/
export function Select({
value,
onChange,
options,
label,
prefix,
placeholder,
name,
heading,
emptyText = "No choices",
status,
onRetry,
errorText = "Couldn't load the choices.",
formatCount,
countLabel: countLabelProp,
locale,
waiting = false,
className,
disabled,
still = false,
onKeyDown,
onClick,
...props
}: SelectProps) {
const id = useId();
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const labelId = `${id}-label`;
const listId = `${id}-list`;
const optionId = (v: string) => `${id}-option-${encodeURIComponent(v).replaceAll("%", "_")}`;
const trigger = useRef<HTMLButtonElement>(null);
const list = useRef<HTMLDivElement>(null);
const [isOpen, setOpen] = useState(false);
const open = still || isOpen;
const [active, setActive] = useState<string | null>(null);
// Tab picks the active option only when the keys put it there; a row under a resting pointer never commits.
const keyed = useRef(false);
// Enter and Space are handled on keydown; the click the browser then fires for the button is skipped.
const skipClick = useRef(false);
const typeAhead = useTypeAhead();
// Loading, from its own status or a StatusFrame around it, the field keeps its box and does not open.
const framed = useLoading();
if (isOpen && (status === "loading" || framed.loading)) setOpen(false);
const chosen = options.find((option) => option.value === value);
const empty = !chosen || value === "";
const shown = chosen?.label ?? placeholder ?? options.find((option) => option.value === "")?.label ?? (options.length ? "" : emptyText);
// An option at 0 cannot be picked, unless it is the current choice.
const usable = (option: SelectOption) => !option.disabled && (option.count !== 0 || option.value === value);
const enabled = options.filter(usable);
const counted = options.some((option) => option.count !== undefined);
// Bars are shares of the largest real choice; the empty choice ("Any") shows its count with no bar.
const most = Math.max(0, ...options.map((option) => (option.value === "" ? 0 : (option.count ?? 0))));
const indexOf = (v: string | null) => enabled.findIndex((option) => option.value === v);
const start = chosen && usable(chosen) ? chosen.value : (enabled[0]?.value ?? null);
const current = still ? (active ?? start) : active;
const reveal = (v: string) => {
const row = document.getElementById(optionId(v));
if (list.current && row) keepRowInView(list.current, row);
};
const moveTo = (index: number) => {
const option = enabled[Math.max(0, Math.min(enabled.length - 1, index))];
if (!option) return;
keyed.current = true;
setActive(option.value);
reveal(option.value);
};
const openAt = (v: string | null) => {
keyed.current = false;
setActive(v);
setOpen(true);
};
const choose = (v: string | null) => {
setOpen(false);
if (v !== null && v !== value) onChange(v);
};
// On open the list scrolls to the whole row nearest to putting the chosen option mid-panel, never past the end, so the
// top row is never cut. scrollTop, not scrollIntoView, so the page never scrolls.
useLayoutEffect(() => {
const box = list.current;
const target = open && current !== null ? document.getElementById(optionId(current)) : null;
if (!box || !target) return;
const rows = [...box.querySelectorAll<HTMLElement>("[role=option]")];
const inset = rows[0].offsetTop;
const end = box.scrollHeight - box.clientHeight;
const ideal = target.offsetTop + target.offsetHeight / 2 - box.clientHeight / 2;
let top = 0;
for (const row of rows) {
const at = row.offsetTop - inset;
if (at <= end && Math.abs(at - ideal) < Math.abs(top - ideal)) top = at;
}
box.scrollTop = top;
}, [open]);
const find = (char: string, from: string | null) => {
const at = typeAhead.find(char, enabled, indexOf(from));
if (isOpen) {
if (at >= 0) moveTo(at);
return;
}
openAt(at >= 0 ? enabled[at].value : from);
keyed.current = at >= 0;
};
const handleKey = (event: KeyboardEvent<HTMLButtonElement>) => {
if (event.nativeEvent.isComposing) return;
const { key } = event;
if (!isOpen) {
if (key === "ArrowDown" || key === "ArrowUp" || key === "Enter" || key === " ") {
event.preventDefault();
if (key === "Enter" || key === " ") skipClick.current = true;
openAt(start);
} else if (key === "Home" || key === "End") {
event.preventDefault();
openAt(enabled[key === "Home" ? 0 : enabled.length - 1]?.value ?? null);
keyed.current = true;
} else if (typesCharacter(event)) {
event.preventDefault();
find(key, start);
}
return;
}
const at = indexOf(active);
if (key === "ArrowDown" && !event.altKey) {
event.preventDefault();
moveTo(at < 0 ? 0 : at + 1);
} else if (key === "ArrowUp" && !event.altKey) {
event.preventDefault();
moveTo(at < 0 ? enabled.length - 1 : at - 1);
} else if (key === "Home" || key === "End") {
event.preventDefault();
moveTo(key === "Home" ? 0 : enabled.length - 1);
} else if (key === "PageDown" || key === "PageUp") {
event.preventDefault();
moveTo((at < 0 ? 0 : at) + (key === "PageDown" ? PAGE : -PAGE));
} else if (key === " " && typeAhead.running()) {
event.preventDefault();
find(key, active);
} else if (key === "Enter" || key === " " || (key === "ArrowUp" && event.altKey)) {
event.preventDefault();
skipClick.current = key !== "ArrowUp";
choose(active);
} else if (key === "ArrowDown" && event.altKey) {
event.preventDefault();
} else if (key === "Tab") {
choose(keyed.current ? active : null);
} else if (typesCharacter(event)) {
event.preventDefault();
find(key, active);
}
};
// With a status, the StatusFrame below dims the field and turns it off; without one, the field dims itself.
const field = (
<div className={cn("relative min-w-0", disabled && status === undefined && "pointer-events-none opacity-50", status === undefined && className)}>
<span id={labelId} hidden>
{label}
</span>
<button
ref={trigger}
type="button"
role="combobox"
aria-labelledby={labelId}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-activedescendant={open && current !== null ? optionId(current) : undefined}
data-waiting={waiting || undefined}
disabled={disabled}
tabIndex={still ? -1 : undefined}
onKeyDown={(event) => {
onKeyDown?.(event);
if (!event.defaultPrevented) handleKey(event);
}}
onKeyUp={() => {
setTimeout(() => {
skipClick.current = false;
});
}}
onClick={(event) => {
onClick?.(event);
if (skipClick.current) {
skipClick.current = false;
return;
}
if (isOpen) setOpen(false);
else openAt(start);
}}
className={cn(
"relative flex h-11 w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-[12px] border border-[var(--fu-field-border,#737373)] bg-[var(--fu-input,rgb(0_0_0/0))] pe-9 ps-3 text-start",
"font-[inherit] text-[15px] leading-5 text-[var(--fu-text,#F8F5F1)] outline-none [-webkit-tap-highlight-color:transparent]",
"transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none disabled:cursor-default",
"hover:border-[var(--fu-control-hover,#A3A3A3)] data-[waiting]:not-focus-visible:not-aria-expanded:border-[var(--fu-line,#404040)] data-[waiting]:not-focus-visible:not-aria-expanded:hover:border-[var(--fu-control-border,#737373)]",
"focus-visible:border-[var(--fu-accent-soft,#8FAAFF)] focus-visible:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)] focus-visible:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
"aria-expanded:border-[var(--fu-accent-soft,#8FAAFF)] aria-expanded:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)] aria-expanded:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
)}
{...props}
>
{prefix != null && (
<span aria-hidden="true" className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">
{prefix}
</span>
)}
<Value text={shown} empty={empty} waiting={waiting} />
<ChevronDownIcon
size={16}
className={cn(
"pointer-events-none absolute top-1/2 inset-e-3 -translate-y-1/2 text-[var(--fu-mute,#BDBDBD)]",
"transition-[rotate,color] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
open && "rotate-180 text-[var(--fu-accent-soft,#8FAAFF)]",
)}
/>
</button>
{name !== undefined && <input type="hidden" name={name} value={value} />}
<PopoverPanel
ref={list}
id={listId}
role="listbox"
aria-labelledby={labelId}
open={open}
still={still}
anchor={trigger}
onClose={() => setOpen(false)}
matchWidth
// Presses inside keep focus on the field, which carries the keys.
onPointerDown={(event) => event.preventDefault()}
className={LIST_PANEL}
>
<RowHighlight activeId={open && current !== null ? optionId(current) : null} open={open} />
{heading != null && (
<div aria-hidden="true" className="px-2.5 pt-1.5 pb-2 text-[12px] leading-4 font-medium text-[var(--fu-dim,#929292)]">
{heading}
</div>
)}
{options.length === 0 && (
// An option that cannot be picked, so the list still holds one and a screen reader says why it is empty.
<div role="option" aria-disabled="true" aria-selected={false} className="flex min-h-10 items-center px-2.5 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{emptyText}
</div>
)}
{options.map((option, order) => {
const selected = option.value === value;
const off = !usable(option);
return (
<div
key={option.value}
id={optionId(option.value)}
role="option"
aria-selected={selected}
aria-disabled={off || undefined}
aria-label={option.count === undefined ? undefined : `${option.label}, ${countLabel(option.count)}`}
data-active={option.value === current || undefined}
onPointerMove={() => {
if (off || option.value === active) return;
keyed.current = false;
setActive(option.value);
}}
onClick={() => {
if (!off) choose(option.value);
}}
className={cn(
"group/row relative flex min-h-10 cursor-pointer items-center gap-3 rounded-[9px] py-2 pe-2 ps-2.5 text-[14px] leading-5 tabular-nums select-none pointer-coarse:min-h-11",
"transition-[background-color,color] duration-200 motion-reduce:transition-none",
selected
? "bg-[var(--fu-selected,#1F2747)] font-medium text-[var(--fu-accent-pale,#D1DDFF)]"
: option.value === "" && "text-[var(--fu-mute,#BDBDBD)]",
off && "cursor-default opacity-40",
"forced-colors:data-[active]:bg-[Highlight] forced-colors:data-[active]:text-[HighlightText]",
)}
>
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{option.label}</span>{" "}
{counted && <ListCount count={option.count ?? 0} max={most} order={order} on={selected} bar={option.value !== ""} format={formatCount} locale={locale} />}
<ListCheck on={selected} />
</div>
);
})}
</PopoverPanel>
</div>
);
// Given a status, it carries its own states: loading as above, an error line with Retry in the field's place, and
// disabled, so focus on the field moves to the frame when it turns off. Inside a filter that has its own StatusFrame,
// leave status out and it follows that frame.
if (status === undefined) return field;
return (
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled} className={cn("flex min-h-11 flex-col justify-center", className)}>
{field}
</StatusFrame>
);
}
```
### components/filters-ui/lib/cn.ts
```ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
```
### components/filters-ui/lib/format.ts
```ts
// Numbers, prices, distances, percents and dates for one locale, built on Intl with no dependency. Pass any BCP 47
// tag ("de-DE", "ar-EG"); a tag Intl cannot read falls back to en-US instead of throwing. The default is en-US, never
// the browser's own locale, so the server and the browser always print the same text. UI words stay English.
export const DEFAULT_LOCALE = "en-US";
export type FormatOptions = {
/** ISO 4217 code for price and priceShort. Default "USD". */
currency?: string;
/** The unit of distance. Default "kilometer". */
unit?: "kilometer" | "mile";
};
/** Every formatter takes the value alone, so any of them can be passed straight to a format prop. */
export type Formats = {
/** The locale these formatters use, after any fallback. */
locale: string;
/** "1,234" in en-US, "1.234" in de-DE, up to three decimals. */
number: (value: number) => string;
/** A number with no group marks, such as a year: "2026", or "٢٠٢٦" in ar-EG. */
plain: (value: number) => string;
/** "45k", "1.2M". */
compact: (value: number) => string;
/** "$45,000" in en-US, "45.000 $" in de-DE: whole units of the currency. */
price: (value: number) => string;
/** "$45k" and "$97.5k" from a thousand up, "$950" below. */
priceShort: (value: number) => string;
/** "50,000 km" or "31,069 mi". */
distance: (value: number) => string;
/** A percentage given in percent, up to two decimals: 6.5 gives "6.5%" in en-US and "6,5 %" in de-DE. */
percent: (value: number) => string;
/** A day given as "YYYY-MM-DD", in words. Read in UTC, so it never shifts by a time zone. */
day: (iso: string, options: Intl.DateTimeFormatOptions) => string;
/** The name of a month, 0 for January. */
month: (index: number, style?: "long" | "short") => string;
/** The name of a weekday, 0 for Sunday. */
weekday: (index: number, style?: "long" | "short") => string;
/** The day weeks start on: 0 for Sunday, 1 for Monday, 6 for Saturday. */
firstDay: 0 | 1 | 5 | 6;
/** The locale's digits, 0 to 9: "0123456789", or "٠١٢٣٤٥٦٧٨٩" in ar-EG. */
digits: string;
/**
* Reads a number typed the locale's way, with an optional k or m: "45,000", "$45k" and "1.2m" in en-US, "45.000"
* and "1,2m" in de-DE. A unit such as "km" is not a suffix. Returns null when the text holds no number.
*/
readNumber: (text: string) => number | null;
};
/**
* A locale Intl has data for, or en-US. A well-formed tag with no data ("zz") would otherwise print in the
* runtime's own locale, which differs between server and browser.
*/
export function safeLocale(locale?: string): string {
if (!locale) return DEFAULT_LOCALE;
try {
const [tag] = Intl.getCanonicalLocales(locale);
if (!tag) return DEFAULT_LOCALE;
if (!Intl.NumberFormat.supportedLocalesOf(tag).length || !Intl.DateTimeFormat.supportedLocalesOf(tag).length) return DEFAULT_LOCALE;
return tag;
} catch {
return DEFAULT_LOCALE;
}
}
/** A currency code Intl can read, or USD. */
function safeCurrency(currency?: string): string {
if (!currency) return "USD";
try {
new Intl.NumberFormat(DEFAULT_LOCALE, { style: "currency", currency });
return currency.toUpperCase();
} catch {
return "USD";
}
}
// Where weeks start, by region, as CLDR 48 has it; every other region starts on Monday. A table rather than
// Intl.Locale weekInfo, which not every browser has, so the server and every browser agree.
const SUNDAY = new Set(
"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "),
);
const SATURDAY = new Set("AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
function firstDayOf(locale: string): 0 | 1 | 5 | 6 {
let region: string | undefined;
try {
region = new Intl.Locale(locale).maximize().region;
} catch {}
if (!region) return 0;
if (region === "MV") return 5;
if (SATURDAY.has(region)) return 6;
return SUNDAY.has(region) ? 0 : 1;
}
const cache = new Map<string, Formats>();
/** Formatters for one locale. Cheap to call on every render: each locale and option set is built once. */
export function formatsFor(locale?: string, options: FormatOptions = {}): Formats {
const tag = safeLocale(locale);
const currency = safeCurrency(options.currency);
const unit = options.unit === "mile" ? "mile" : "kilometer";
const key = `${tag}|${currency}|${unit}`;
const known = cache.get(key);
if (known) return known;
const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(tag, o);
const dates = new Map<string, Intl.DateTimeFormat>();
const df = (o: Intl.DateTimeFormatOptions) => {
const id = JSON.stringify(o);
let format = dates.get(id);
if (!format) {
format = new Intl.DateTimeFormat(tag, { ...o, timeZone: "UTC" });
dates.set(id, format);
}
return format;
};
// English writes thousands with a small k, as the filters always have.
const english = tag === "en" || tag.startsWith("en-");
const smallK = (text: string) => (english ? text.replace(/K\b/, "k") : text);
const number = nf({});
const plain = nf({ useGrouping: false, maximumFractionDigits: 20 });
const compact = nf({ notation: "compact", maximumFractionDigits: 1 });
const price = nf({ style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0 });
// One decimal is exact for a 1,000 unit ("$97.5k"); a 10,000 unit such as 万 takes two ("$9.75万").
const unitDigits = nf({ notation: "compact", useGrouping: false }).formatToParts(10000).filter((p) => p.type === "integer").map((p) => p.value).join("").length;
const priceShort = nf({ style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: Math.max(1, 3 - unitDigits) });
const distance = nf({ style: "unit", unit, maximumFractionDigits: 0 });
const percent = nf({ style: "percent", maximumFractionDigits: 2 });
const digits = plain.format(1234567890).replace(/^(.*)(.)$/, "$2$1");
const parts = number.formatToParts(12345.6);
const group = parts.find((p) => p.type === "group")?.value ?? ",";
const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";
const formats: Formats = {
locale: tag,
number: (value) => number.format(value),
plain: (value) => plain.format(value),
compact: (value) => smallK(compact.format(value)),
price: (value) => price.format(value),
priceShort: (value) => (Math.abs(value) >= 1000 ? smallK(priceShort.format(value)) : price.format(value)),
distance: (value) => distance.format(value),
percent: (value) => percent.format(value / 100),
day: (iso, o) => df(o).format(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)))),
month: (index, style = "long") => df({ month: style }).format(Date.UTC(2021, index, 1)),
// 3 January 2021 was a Sunday.
weekday: (index, style = "long") => df({ weekday: style }).format(Date.UTC(2021, 0, 3 + index)),
firstDay: firstDayOf(tag),
digits,
readNumber: (text) => {
let t = text.replace(/[\s ]/g, "");
for (let i = 0; i < 10; i++) t = t.split(digits[i]).join(String(i));
if (!/\s/.test(group)) t = t.split(group).join("");
// Marks typed in place of the locale's own: a Latin or Arabic comma where both marks are Arabic, a curly apostrophe for a straight one.
if (!/[.,]/.test(group + decimal)) t = t.replace(/[,\u060c]/g, "");
if (group === "'") t = t.split("\u2019").join("");
if (decimal !== ".") t = t.split(decimal).join(".");
const match = t.match(/(\d*\.?\d+)([km](?![a-z]))?/i);
if (!match) return null;
const scale = match[2] ? (match[2].toLowerCase() === "k" ? 1e3 : 1e6) : 1;
return Number(match[1]) * scale;
},
};
cache.set(key, formats);
return formats;
}
/** "1 result", "1,204 results": the default words for a count, with the number in the locale. */
export const resultsLabel = (n: number, locale?: string) => `${formatsFor(locale).number(n)} ${n === 1 ? "result" : "results"}`;
```
### components/filters-ui/ui/icons.tsx
```tsx
import type { ReactNode, SVGProps } from "react";
/*
* Icon paths from Lucide (https://lucide.dev), ISC License.
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT).
* All other copyright (c) for Lucide are held by Lucide Contributors 2022.
* Permission to use, copy, modify, and/or distribute this software for any purpose with or
* without fee is hereby granted, provided that the above copyright notice and this permission
* notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number };
function Icon({ size = 20, strokeWidth = 2, children, ...props }: IconProps & { children: ReactNode }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...props}
>
{children}
</svg>
);
}
export function ChevronDownIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m6 9 6 6 6-6" />
</Icon>
);
}
export function XIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</Icon>
);
}
export function CheckIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M20 6 9 17l-5-5" />
</Icon>
);
}
export function SearchIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function ArrowUpRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M7 7h10v10" />
<path d="M7 17 17 7" />
</Icon>
);
}
export function PlusIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="M12 5v14" />
</Icon>
);
}
export function CopyIcon(props: IconProps) {
return (
<Icon {...props}>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</Icon>
);
}
export function SlidersIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 4h-7" />
<path d="M10 4H3" />
<path d="M21 12h-9" />
<path d="M8 12H3" />
<path d="M21 20h-5" />
<path d="M12 20H3" />
<path d="M14 2v4" />
<path d="M8 10v4" />
<path d="M16 18v4" />
</Icon>
);
}
export function ArrowRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</Icon>
);
}
export function SearchXIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m13.5 8.5-5 5" />
<path d="m8.5 8.5 5 5" />
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function StarIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</Icon>
);
}
export function HistoryIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M12 7v5l4 2" />
</Icon>
);
}
export function ListTreeIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 12h-8" />
<path d="M21 6H8" />
<path d="M21 18h-8" />
<path d="M3 6v4c0 1.1.9 2 2 2h3" />
<path d="M3 10v6c0 1.1.9 2 2 2h3" />
</Icon>
);
}
export function CircleAlertIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</Icon>
);
}
```
### components/filters-ui/ui/popover.tsx
```tsx
"use client";
import { useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type Ref, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { CheckIcon } from "./icons";
export type PopoverCloseReason = "escape" | "outside" | "blur" | "away";
export type PopoverPanelProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
ref?: Ref<HTMLDivElement>;
open: boolean;
/** The trigger the panel opens against. */
anchor: RefObject<HTMLElement | null>;
/**
* Asks the owner to close: "escape", "outside" (a press outside the trigger and the panel), "blur" (focus moved
* outside both) or "away" (the trigger scrolled out of view). The owner sets open to false and moves focus if needed.
*/
onClose: (reason: PopoverCloseReason) => void;
/** Lines up the start edges, or the end edges with "end": the left edges in left-to-right, the right ones in RTL. Default "start". */
align?: "start" | "end";
/** At least as wide as the trigger. */
matchWidth?: boolean;
/** Widest the panel grows, in px; never wider than the screen less its margins. Default 320. */
maxWidth?: number;
/** Tallest the panel grows before it scrolls, in px; also capped by the room on its side. Default 320. */
maxHeight?: number;
/** Draws the panel open in place under the trigger, for a still picture. Nothing moves or listens. The owner needs position: relative. */
still?: boolean;
children: ReactNode;
};
const GAP = 6;
const EDGE_Y = 8;
const MIN_HEIGHT = 160;
const edgeX = (width: number) => (width < 640 ? 16 : 8);
/** Open panels, newest last: Escape closes only the newest. */
const layers: symbol[] = [];
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
// Browsers without popover support (before Chrome 114, Safari 17, Firefox 125) get a fixed panel in place instead.
function show(node: HTMLElement) {
if (typeof node.showPopover !== "function") {
node.style.display = "block";
return;
}
try {
if (!node.matches(":popover-open")) node.showPopover();
} catch {}
}
function hide(node: HTMLElement) {
if (typeof node.hidePopover !== "function") {
node.style.display = "none";
return;
}
try {
node.hidePopover();
} catch {}
}
/** The surface of a menu or list panel: 14px radius, the card colour, a --fu-line hairline, 6px inside, a deep soft shadow. */
export const LIST_PANEL =
"w-max rounded-[14px] border border-[var(--fu-line,#404040)] bg-[var(--fu-card,#1F1F1F)] p-1.5 shadow-[inset_0_1px_0_var(--fu-rim,rgb(255_255_255/0.04)),0_24px_48px_-12px_var(--fu-shadow-deep,rgb(0_0_0/0.8)),0_10px_20px_-8px_var(--fu-shadow,rgb(0_0_0/0.5))]";
/**
* A floating panel for menus and lists. It stays where it is in the DOM, so it inherits fonts and --fu-* variables and
* Tab reaches it right after its trigger, and opens on the browser's top layer (popover="manual"), so no overflow,
* transform or z-index around the trigger can clip or bury it. It opens below the trigger, or above when only that fits,
* keeps 8px from the screen edges (16px at the sides on phones) and follows the trigger while the page scrolls.
* It grows out of the trigger over 480ms (scale 0.98 to 1 from the trigger's side, through a 6px blur) and leaves
* over 160ms; it is inert while it leaves. Children can follow it through group/popover's data-state: closed, open,
* closing.
*/
export function PopoverPanel({
ref,
open,
anchor,
onClose,
align = "start",
matchWidth = false,
maxWidth = 320,
maxHeight = 320,
still = false,
className,
style,
children,
...props
}: PopoverPanelProps) {
const panel = useRef<HTMLDivElement | null>(null);
const [phase, setPhase] = useState<"hidden" | "open" | "closing">("hidden");
// Counts grow in only the first time the panel opens; after that they are already in place.
const [seen, setSeen] = useState(false);
// Which edges have rows scrolled out of view, so a soft fade there says the list goes on.
const [more, setMore] = useState({ top: false, bottom: false });
const side = useRef<"bottom" | "top">("bottom");
const close = useRef(onClose);
useLayoutEffect(() => {
close.current = onClose;
});
const setRef = (node: HTMLDivElement | null) => {
panel.current = node;
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
};
// Measures the trigger without its press scale (offset sizes around the rect's centre), then picks a side and a spot.
const place = (first: boolean) => {
const node = panel.current;
const trigger = anchor.current;
if (!node || !trigger) return;
const vw = document.documentElement.clientWidth;
const vh = document.documentElement.clientHeight;
const rect = trigger.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
const left = cx - trigger.offsetWidth / 2;
const right = cx + trigger.offsetWidth / 2;
const top = cy - trigger.offsetHeight / 2;
const bottom = cy + trigger.offsetHeight / 2;
if (!first && (bottom < 0 || top > vh || right < 0 || left > vw)) {
close.current("away");
return;
}
const mx = edgeX(vw);
const widest = Math.min(maxWidth, vw - 2 * mx);
node.style.maxWidth = `${widest}px`;
if (matchWidth) node.style.minWidth = `${Math.min(trigger.offsetWidth, widest)}px`;
node.style.maxHeight = `${maxHeight}px`;
const natural = node.offsetHeight;
const below = vh - EDGE_Y - bottom - GAP;
const above = top - GAP - EDGE_Y;
const roomOf = (s: "bottom" | "top") => (s === "bottom" ? below : above);
let next: "bottom" | "top";
if (!first && natural <= roomOf(side.current)) next = side.current;
else if (natural <= below) next = "bottom";
else if (natural <= above) next = "top";
else next = below >= above ? "bottom" : "top";
side.current = next;
node.style.maxHeight = `${Math.min(maxHeight, Math.max(MIN_HEIGHT, roomOf(next)))}px`;
const width = node.offsetWidth;
const height = node.offsetHeight;
const toRight = (align === "end") !== isRtl(trigger);
const x = Math.min(Math.max(mx, toRight ? right - width : left), vw - mx - width);
const y = next === "bottom" ? bottom + GAP : top - GAP - height;
node.style.left = `${Math.round(x)}px`;
node.style.top = `${Math.round(y)}px`;
node.style.transformOrigin = `${Math.round(cx - x)}px ${next === "bottom" ? "0" : "100%"}`;
node.dataset.side = next;
};
useLayoutEffect(() => {
const node = panel.current;
if (still || !node) return;
if (open) {
if (phase === "hidden") {
// Shown and placed in its closed look with no transition, then opened, so it enters from the trigger's side.
node.style.transition = "none";
show(node);
place(true);
void getComputedStyle(node).opacity;
node.style.transition = "";
}
setPhase("open");
setSeen(true);
} else if (phase === "open") {
setPhase(reducedMotion() ? "hidden" : "closing");
}
// place reads the latest props; phase is read as committed.
}, [open, still]);
useLayoutEffect(() => {
if (phase === "hidden" && !still && panel.current) hide(panel.current);
}, [phase, still]);
useEffect(() => {
const node = panel.current;
if (!node || (!still && phase !== "open")) return;
const measure = () => {
const top = node.scrollTop > 1;
const bottom = node.scrollTop + node.clientHeight < node.scrollHeight - 1;
setMore((now) => (now.top === top && now.bottom === bottom ? now : { top, bottom }));
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
node.addEventListener("scroll", measure, { passive: true });
return () => {
observer.disconnect();
node.removeEventListener("scroll", measure);
};
}, [phase, still]);
useEffect(() => {
const node = panel.current;
if (phase !== "closing" || !node) return;
const done = () => setPhase((now) => (now === "closing" ? "hidden" : now));
const timer = setTimeout(done, 190);
const onEnd = (event: TransitionEvent) => {
if (event.target === node && event.propertyName === "opacity") done();
};
node.addEventListener("transitionend", onEnd);
return () => {
clearTimeout(timer);
node.removeEventListener("transitionend", onEnd);
};
}, [phase]);
useEffect(() => {
const node = panel.current;
const trigger = anchor.current;
if (still || phase !== "open" || !node || !trigger) return;
const token = Symbol("layer");
layers.push(token);
let frame = 0;
const follow = (event?: Event) => {
if (event?.type === "scroll" && event.target instanceof Node && node.contains(event.target)) return;
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => place(false));
};
const observer = new ResizeObserver(() => follow());
observer.observe(trigger);
observer.observe(node);
window.addEventListener("scroll", follow, { capture: true, passive: true });
window.addEventListener("resize", follow);
window.visualViewport?.addEventListener("resize", follow);
const inside = (target: EventTarget | null) => target instanceof Node && (node.contains(target) || trigger.contains(target));
// A mouse closes on press; a finger or pen on a tap that did not move, so starting a scroll keeps the panel open.
// The press is never cancelled, so one click on another control both closes this and works there.
let touch: { id: number; x: number; y: number } | null = null;
const onDown = (event: PointerEvent) => {
if (inside(event.target)) return;
if (event.pointerType === "mouse") close.current("outside");
else touch = { id: event.pointerId, x: event.clientX, y: event.clientY };
};
const onUp = (event: PointerEvent) => {
if (touch && touch.id === event.pointerId && Math.hypot(event.clientX - touch.x, event.clientY - touch.y) < 10) close.current("outside");
touch = null;
};
const onCancel = () => {
touch = null;
};
const onKey = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.isComposing || layers.at(-1) !== token) return;
event.stopPropagation();
event.preventDefault();
close.current("escape");
};
const onFocusOut = (event: FocusEvent) => {
if (event.relatedTarget && !inside(event.relatedTarget)) close.current("blur");
};
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("pointerup", onUp, true);
document.addEventListener("pointercancel", onCancel, true);
window.addEventListener("keydown", onKey, true);
node.addEventListener("focusout", onFocusOut);
trigger.addEventListener("focusout", onFocusOut);
return () => {
layers.splice(layers.indexOf(token), 1);
cancelAnimationFrame(frame);
observer.disconnect();
window.removeEventListener("scroll", follow, { capture: true });
window.removeEventListener("resize", follow);
window.visualViewport?.removeEventListener("resize", follow);
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("pointerup", onUp, true);
document.removeEventListener("pointercancel", onCancel, true);
window.removeEventListener("keydown", onKey, true);
node.removeEventListener("focusout", onFocusOut);
trigger.removeEventListener("focusout", onFocusOut);
};
// place and the trigger are read live.
}, [phase, still]);
const state = still ? (open ? "open" : "closed") : phase === "hidden" ? "closed" : phase;
return (
<div
ref={setRef}
popover={still ? undefined : "manual"}
data-state={state}
data-unseen={!seen && !still && state === "closed" ? "" : undefined}
// Not while it is opening again before it finished leaving, so focus can move in.
inert={state === "closing" && !open}
style={still ? { maxWidth, maxHeight, ...style } : style}
className={cn(
// The browser's own popover look is reset: no inset, margin or padding, and these colours, not Canvas.
"group/popover m-0 box-border overflow-x-hidden overflow-y-auto overscroll-contain text-[var(--fu-text,#F8F5F1)] [-webkit-tap-highlight-color:transparent]",
SCROLL,
still
? cn("absolute top-full z-10 mt-1.5", align === "end" ? "inset-e-0" : "inset-s-0", matchWidth && "min-w-full", !open && "hidden")
: "fixed inset-auto z-50",
"transition-[opacity,translate,scale,filter] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"data-[state=open]:duration-[480ms] data-[state=closing]:duration-[160ms]",
"data-[state=closed]:pointer-events-none data-[state=closed]:scale-[0.98] data-[state=closed]:opacity-0 data-[state=closed]:blur-[6px]",
"data-[state=closing]:pointer-events-none data-[state=closing]:scale-[0.98] data-[state=closing]:opacity-0 data-[state=closing]:blur-[2px]",
"data-[side=bottom]:data-[state=closed]:-translate-y-1 data-[side=top]:data-[state=closed]:translate-y-1",
className,
)}
{...props}
>
<span aria-hidden="true" className={cn(FADE, "-top-1.5 -mt-1.5 mb-[-26px] bg-linear-to-b", more.top && "opacity-100")} />
{children}
<span aria-hidden="true" className={cn(FADE, "-bottom-1.5 mt-[-26px] -mb-1.5 bg-linear-to-t", more.bottom && "opacity-100")} />
</div>
);
}
// Pinned to the panel edge as it scrolls, over the rows and the highlight; it takes no room in the list. Sized for LIST_PANEL.
const FADE =
"pointer-events-none sticky z-[2] -mx-1.5 block h-8 from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-150 motion-reduce:transition-none forced-colors:hidden";
/** Scrolls a list panel just enough that `row` shows whole, with the panel's 4px inset around it. */
export function keepRowInView(panel: HTMLElement, row: HTMLElement) {
const top = row.offsetTop - 4;
const bottom = row.offsetTop + row.offsetHeight + 4;
if (top < panel.scrollTop) panel.scrollTop = top;
else if (bottom > panel.scrollTop + panel.clientHeight) panel.scrollTop = bottom - panel.clientHeight;
}
type Mark = { top: number; height: number; shown: boolean };
/**
* The one fill that marks a list's active row, moving straight to it. It lies over the rows, a
* light veil, so it shows on the chosen row's tint too. It fades in where it lands when the list opens, and stays put
* while the list fades out. Place it first inside the panel.
*/
export function RowHighlight({ activeId, open, pressed = false }: { activeId: string | null; open: boolean; pressed?: boolean }) {
const [mark, setMark] = useState<Mark | null>(null);
const [, remeasure] = useState(0);
const tries = useRef(0);
useLayoutEffect(() => {
if (!open) {
tries.current = 0;
return;
}
const node = activeId ? document.getElementById(activeId) : null;
// The panel may still be hidden on this pass (it is shown after its children's effects); measure again next frame,
// a few times at most, in case something else keeps it hidden.
if (node && !node.getClientRects().length) {
if (tries.current >= 3) return;
tries.current += 1;
const frame = requestAnimationFrame(() => remeasure((n) => n + 1));
return () => cancelAnimationFrame(frame);
}
tries.current = 0;
const next: Mark | null = node
? { top: node.offsetTop, height: node.offsetHeight, shown: true }
: mark && { ...mark, shown: false };
if (next?.top !== mark?.top || next?.height !== mark?.height || next?.shown !== mark?.shown) setMark(next);
});
return (
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-x-1.5 top-0 z-[1] rounded-[9px] transition-[opacity,background-color] duration-150 motion-reduce:transition-none forced-colors:hidden",
"ease-[cubic-bezier(0.22,1,0.36,1)]",
pressed ? "bg-[var(--fu-row-press,rgb(255_255_255/0.12))]" : "bg-[var(--fu-row-active,rgb(255_255_255/0.07))]",
!mark?.shown && "opacity-0",
)}
style={mark ? { translate: `0 ${mark.top}px`, height: mark.height } : undefined}
/>
);
}
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
/**
* The check on a chosen row. It draws itself in, from the short leg up, 140ms after its panel first opens; after that
* it is already in place. Takes its 16px place even when off, so rows line up.
*/
export function ListCheck({ on }: { on: boolean }) {
return (
<CheckIcon
size={16}
strokeWidth={2.5}
className={cn(
"shrink-0 text-[var(--fu-accent-soft,#8FAAFF)]",
on
? cn(
// The path is about 23 units long; a negative offset draws it from the short leg up.
"[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:0] [&_path]:transition-[stroke-dashoffset] [&_path]:delay-[140ms] [&_path]:duration-[420ms]",
"[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:[&_path]:transition-none",
"group-data-[unseen]/popover:[&_path]:[stroke-dashoffset:-23] group-data-[unseen]/popover:[&_path]:transition-none",
)
: "invisible",
)}
/>
);
}
/**
* A row's count as a short bar and a number. The bar is the count's share of `max`; bars grow in from the start edge as
* their panel first opens, one row after another (`order`), and ease to a new width when the count changes. With bar false
* only the number shows, in the same place, e.g. for "Any".
*/
export function ListCount({
count,
max,
order = 0,
on = false,
bar = true,
format,
locale,
}: {
count: number;
max: number;
order?: number;
on?: boolean;
bar?: boolean;
format?: (n: number) => string;
/** Formats the count when no format is given. */
locale?: string;
}) {
const share = max > 0 ? Math.min(1, count / max) : 0;
return (
<span aria-hidden="true" className="flex shrink-0 items-center gap-2.5">
<span className={cn("flex h-1 w-12 items-center rounded-full bg-[var(--fu-track,rgb(255_255_255/0.06))]", !bar && "invisible")}>
<span
className={cn(
"h-1 origin-left rtl:origin-right rounded-full transition-[scale,width,background-color] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[unseen]/popover:scale-x-0 group-data-[unseen]/popover:transition-none",
on
? "bg-[var(--fu-accent-soft,#8FAAFF)]"
: "bg-[var(--fu-rail,#4A4A4A)] group-data-[active]/row:bg-[var(--fu-control-border,#737373)]",
)}
// A count above 0 always shows a sliver, so only an empty option has no bar.
style={{ width: `${count > 0 ? Math.max(share * 100, 6) : 0}%`, transitionDelay: `${90 + Math.min(order, 10) * 22}ms, 0ms, 0ms` }}
/>
</span>
<span
className={cn(
"min-w-[3ch] text-end text-[13px] leading-5 tabular-nums transition-[color] duration-200",
on ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)] group-data-[active]/row:text-[var(--fu-mute,#BDBDBD)]",
)}
>
{(format ?? formatsFor(locale).number)(count)}
</span>
</span>
);
}
/**
* Finds a row by the letters typed in the last 500ms. One letter, or the same letter again and again, steps to the
* next row starting with it; a word keeps the current row while it still matches.
*/
export function useTypeAhead() {
const word = useRef("");
const lastKey = useRef(0);
const running = () => word.current !== "" && Date.now() - lastKey.current <= 500;
const find = <T extends { label: string }>(char: string, items: readonly T[], current: number): number => {
word.current = (running() ? word.current : "") + char.toLowerCase();
lastKey.current = Date.now();
const stepping = /^(.)\1*$/u.test(word.current);
const wanted = stepping ? [...word.current][0] : word.current;
// The rows in search order: from the next row (or the current one, for a word) round to the one before it.
const start = stepping ? current + 1 : Math.max(current, 0);
const order = items.map((_, index) => index);
const hit = [...order.slice(start), ...order.slice(0, start)].find((index) => items[index].label.toLowerCase().startsWith(wanted));
return hit ?? -1;
};
return { find, running };
}
/** True for a key press that types one character, not a shortcut. */
export const typesCharacter = (event: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }) =>
/^.$/u.test(event.key) && !(event.ctrlKey || event.metaKey || event.altKey);
```
### components/filters-ui/lib/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/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/skeleton.tsx
```tsx
"use client";
import { createContext, useContext, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
/** What StatusFrame tells the pieces under it: draw placeholders, or the data has just arrived and fades in once. */
export type LoadingState = { loading: boolean; arriving: boolean };
export const LoadingContext = createContext<LoadingState>({ loading: false, arriving: false });
/** The loading state of the nearest StatusFrame. Outside one, nothing is loading. */
export const useLoading = () => useContext(LoadingContext);
/**
* The placeholder fill: --fu-skeleton, pulsing to half of it every 2s (Tailwind's animate-pulse). It holds still when
* reduced motion is asked for, and turns to the system's grey text colour in forced colours, so it never vanishes.
*/
export const SKELETON_FILL =
"animate-pulse bg-[var(--fu-skeleton,rgb(255_255_255/0.12))] in-data-[state=on]:bg-[var(--fu-skeleton-on,rgb(143_170_255/0.3))] motion-reduce:animate-none forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]";
/** Content that has just replaced a placeholder: it fades in once over 300ms as it is inserted, and never again. */
export const ARRIVING = "transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none";
export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;
/**
* A pulsing placeholder block with no size of its own: give it the size and corners of what it stands for, from the
* same classes, e.g. "h-5 min-w-[22px] rounded-[6px]" for a count pill. Hidden from screen readers; the StatusFrame
* around it says "Loading" once.
*/
export function Skeleton({ className, ...props }: SkeletonProps) {
return <span aria-hidden="true" data-skeleton="" className={cn("block rounded-[6px]", SKELETON_FILL, className)} {...props} />;
}
export type SkeletonTextProps = {
children: ReactNode;
/** Draws the placeholder. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
/** Classes for the placeholder's box while loading. */
className?: string;
};
/**
* Words that draw as a rounded bar while loading. The words stay in the layout, unseen, so the bar is exactly as wide
* and as many lines tall as they are, and nothing moves when they arrive; then they fade in once.
*/
export function SkeletonText({ children, loading, className }: SkeletonTextProps) {
const state = useLoading();
if (loading ?? state.loading) {
return (
<span key="skeleton" className={cn("relative inline-block max-w-full align-top", className)}>
<span className="invisible">{children}</span>
<Skeleton className="absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]" />
</span>
);
}
if (state.arriving) {
return (
<span key="arrived" className={ARRIVING}>
{children}
</span>
);
}
return <>{children}</>;
}
/**
* Stand-in names for a list whose options have not come yet: a mix of lengths, so the placeholders do not read as a
* grid. Never shown; only their widths are.
*/
export function placeholderLabels(count: number): string[] {
const words = ["Placeholder", "Short", "A longer name", "Medium one", "Tiny", "Another name", "Middle", "Fairly long one"];
return Array.from({ length: count }, (_, i) => words[i % words.length]);
}
```
### components/filters-ui/ui/status-frame.tsx
```tsx
"use client";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";
/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";
/**
* The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
* filter knows them all. Spread them into an item's own props type.
*/
export type StateProps = {
/** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
status?: Status;
/** Called by the Retry button. Without it the error line has no button. */
onRetry?: () => void;
/** The error line. Default "Couldn't load the options." */
errorText?: string;
/** The line shown in place of the options when there are none. Default "No options to show" */
emptyText?: string;
/** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
disabled?: boolean;
};
export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";
/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
type Mode = "ready" | "loading" | "error" | "empty";
/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);
export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
Omit<StateProps, "emptyText"> & {
/** There are no options: emptyText shows in place of the content. */
empty?: boolean;
emptyText?: ReactNode;
/** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
emptyArt?: string | ReactNode | null;
/** Words read once while loading. Default "Loading". */
loadingText?: string;
/** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
announce?: boolean;
retryLabel?: string;
children: ReactNode;
};
/**
* Wraps an item's content and gives it the shared states.
* - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
* placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
* - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
* status region that stays on the page.
* - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
* - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
* read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
* When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
* A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
* it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
* with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
* frame and let an inner frame around the part that fails speak.
*/
export function StatusFrame({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
empty = false,
emptyText = DEFAULT_EMPTY_TEXT,
emptyArt,
disabled = false,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
children,
...props
}: StatusFrameProps) {
const frame = useRef<HTMLDivElement>(null);
const outer = useLoading();
const saidAbove = useContext(SaidLoading);
const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";
// The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
const [lastStatus, setLastStatus] = useState(status);
const [arriving, setArriving] = useState(false);
if (status !== lastStatus) {
setLastStatus(status);
setArriving(lastStatus === "loading" && status === "ready");
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arriving]);
// Whether focus sat on a control inside, read just before a change of state is drawn.
const key = `${mode}|${disabled}`;
const drawnKey = useRef(key);
const focusWasInside = useRef(false);
if (key !== drawnKey.current && typeof document !== "undefined") {
const active = document.activeElement;
focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
}
useLayoutEffect(() => {
if (drawnKey.current === key) return;
drawnKey.current = key;
if (!focusWasInside.current) return;
focusWasInside.current = false;
const node = frame.current;
// The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
});
return (
<div
ref={frame}
tabIndex={-1}
data-status-frame=""
data-status={mode}
aria-busy={mode === "loading" || undefined}
className={cn(
"min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50 select-none",
className,
)}
{...props}
>
<SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
<LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
{mode === "empty" ? (
emptyArt === null ? (
<EmptyNote>{emptyText}</EmptyNote>
) : (
<EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
)
) : mode === "error" ? null : (
// display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
<fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
{children}
</fieldset>
)}
</LoadingContext.Provider>
</SaidLoading.Provider>
<StatusLine
status={mode === "loading" || mode === "error" ? mode : "ready"}
onRetry={onRetry}
errorText={errorText}
loadingText={saidAbove ? "" : loadingText}
announce={announce}
retryLabel={retryLabel}
/>
</div>
);
}
export type StatusLineProps = {
status?: Status;
/** Called by Retry. Without it the error line has no button. */
onRetry?: () => void;
errorText?: string;
loadingText?: string;
/** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
announce?: boolean;
retryLabel?: string;
/** Classes for the line while it shows an error, e.g. its margins. */
className?: string;
};
/**
* What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
* Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
* no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
* Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
*/
export function StatusLine({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
}: StatusLineProps) {
const error = status === "error";
const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
return (
// The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
<div className={error ? cn(ERROR_LINE, className) : "contents"}>
<p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
{error && <ErrorGlyph />}
{said && <span dir="auto">{said}</span>}
</p>
{error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
/**
* For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
* away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
* never dropped to the page.
*/
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
const drawn = useRef(key);
const had = useRef(false);
if (key !== drawn.current && typeof document !== "undefined") {
const active = document.activeElement;
had.current = !!scope.current && !!active && scope.current.contains(active);
}
useLayoutEffect(() => {
if (drawn.current === key) return;
drawn.current = key;
if (!had.current) return;
had.current = false;
const node = scope.current;
if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
});
}
```
### components/filters-ui/ui/art-search.ts
```ts
/**
* The picture for "nothing matches" and "nothing here": a glass magnifier on a clear background, drawn 56px.
* It is a file, not code: the shadcn install saves it as public/filters-ui/search.svg. Copying by hand, save
* https://filtersui.com/filters-ui/search.svg there, or point this at a picture of your own. With no file the empty
* states show their words alone.
*/
export const SEARCH_ART = "/filters-ui/search.svg";
```
### components/filters-ui/ui/empty-note.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyNoteProps = HTMLAttributes<HTMLDivElement> & {
/** A 16px glyph in currentColor before the words. */
icon?: ReactNode;
/** A button or link after the words, e.g. "Clear search". */
action?: ReactNode;
};
/**
* A quiet one-line note in place of a list that has nothing in it: dim 14px words, an optional glyph and an optional
* action. No illustration and no box, so it sits in the space the options would take.
*/
export function EmptyNote({ icon, action, className, children, ...props }: EmptyNoteProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2", className)} {...props}>
<p className="flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{icon && (
<span aria-hidden="true" className="mt-0.5 shrink-0 [&_svg]:size-4">
{icon}
</span>
)}
<span dir="auto">{children}</span>
</p>
{action}
</div>
);
}
```
### components/filters-ui/ui/empty-state.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
/** The picture above the words: an image address, drawn 56px square, or any node of that size. */
art?: string | ReactNode;
/** The one line that says what is missing. */
title: ReactNode;
/** A link or button under the words, such as "Clear search". */
action?: ReactNode;
/** A second, quieter line under the title. */
children?: ReactNode;
};
// Each part arrives once, a beat after the one above it: the picture comes into focus, the words rise into place.
const ENTER =
"transition-[opacity,filter,translate,scale] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none starting:opacity-0";
/**
* What a list shows in the room its options would take when it has none: a picture, one line and an action, stacked
* in the middle. For a single quiet line with no picture, use EmptyNote.
*/
export function EmptyState({ art, title, action, className, children, ...props }: EmptyStateProps) {
return (
<div className={cn("flex min-w-0 max-w-full flex-col items-center text-center", className)} {...props}>
{art && (
<span aria-hidden="true" className={cn("mb-3 block size-14 shrink-0", ENTER, "starting:scale-[0.82] starting:blur-[6px]")}>
{typeof art === "string" ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={art} alt="" width={56} height={56} loading="lazy" decoding="async" draggable={false} className="size-full object-contain select-none" />
) : (
art
)}
</span>
)}
<p dir="auto" className={cn("max-w-full text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]", ENTER, "delay-[60ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{title}
</p>
{children && (
<p dir="auto" className={cn("mt-1 max-w-full text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]", ENTER, "delay-[90ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{children}
</p>
)}
{action && <div className={cn("mt-2 max-w-full", ENTER, "delay-[120ms] starting:translate-y-1.5")}>{action}</div>}
</div>
);
}
```
### components/filters-ui/ui/inline-error.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { buttonClasses } from "./button-classes";
import { CircleAlertIcon } from "./icons";
export const DEFAULT_RETRY_LABEL = "Retry";
/** The error line's layout: the words at the start, Retry at the end, wrapping under them when space runs out. */
export const ERROR_LINE = "flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2";
/** The words: 14px, muted, with a 16px dim alert glyph before them. */
export const ERROR_TEXT = "flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]";
/** The alert glyph that leads the words. Hidden from screen readers. */
export function ErrorGlyph() {
return <CircleAlertIcon size={16} className="mt-0.5 shrink-0 text-[var(--fu-dim,#929292)]" />;
}
export type RetryButtonProps = {
onRetry: () => void;
label?: string;
className?: string;
};
/**
* A small grey button that is never shown disabled. Before it calls onRetry it hands focus to the StatusFrame around
* it, which stays on the page while the content reloads, so focus is never lost with the button.
*/
export function RetryButton({ onRetry, label = DEFAULT_RETRY_LABEL, className }: RetryButtonProps) {
return (
<button
type="button"
onClick={(event) => {
event.currentTarget.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
onRetry();
}}
className={buttonClasses({ variant: "secondary", size: "sm", className })}
>
{label}
</button>
);
}
export type InlineErrorProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** One short line in plain words, e.g. "Couldn't load the options." */
text: string;
/** Shows Retry. Without it the line stands alone. */
onRetry?: () => void;
retryLabel?: string;
};
/**
* A calm error in the component's own area: one muted line and a Retry button. The line is a polite status region, so
* it is read out when it appears. Inside a StatusFrame use the frame's status="error" instead: it keeps one region on
* the page for loading and errors alike.
*/
export function InlineError({ text, onRetry, retryLabel, className, ...props }: InlineErrorProps) {
return (
<div className={cn(ERROR_LINE, className)} {...props}>
<p role="status" className={ERROR_TEXT}>
<ErrorGlyph />
<span dir="auto">{text}</span>
</p>
{onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
```
### components/filters-ui/ui/button-classes.ts
```ts
import { cn } from "../lib/cn";
// The button looks as class names. Kept apart from button.tsx, a client module, so server pages can call them too.
export type ButtonVariant = "primary" | "secondary" | "ghost" | "quiet" | "quiet-accent";
export type ButtonSize = "sm" | "md" | "lg";
export const BUTTON_BASE = cn(
"relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] font-[inherit] font-medium whitespace-nowrap no-underline select-none",
"[-webkit-tap-highlight-color:transparent] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
"active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"aria-busy:cursor-progress aria-busy:active:scale-100",
);
const VARIANTS: Record<ButtonVariant, string> = {
primary:
"bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)] hover:bg-[var(--fu-accent-hover,#3450D4)] forced-colors:border forced-colors:border-[ButtonText]",
secondary:
"bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]",
ghost: "bg-transparent text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
quiet: "bg-transparent text-[var(--fu-mute,#BDBDBD)] hover:text-[var(--fu-text,#F8F5F1)]",
"quiet-accent":
"bg-transparent text-[var(--fu-accent-soft,#8FAAFF)] decoration-1 underline-offset-[5px] hover:text-[var(--fu-accent-pale,#D1DDFF)] [@media(hover:hover)]:hover:underline",
};
// Below 44px a touch screen gets a taller invisible target through ::after.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:content-['']";
const SIZES: Record<ButtonSize, { box: string; before: string; after: string }> = {
sm: { box: cn("h-8 gap-1.5 px-3 text-[13px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-1.5"), before: "ps-2.5", after: "pe-2.5" },
md: { box: cn("h-10 gap-2 px-3.5 text-[15px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-0.5"), before: "ps-3", after: "pe-3" },
lg: { box: "h-11 gap-2 px-4 text-[15px] leading-5 [&_svg]:size-[18px]", before: "ps-3.5", after: "pe-3.5" },
};
/** The classes of a button, for a link or a router link that should look like one. */
export function buttonClasses({
variant = "primary",
size = "md",
before = false,
after = false,
className,
}: { variant?: ButtonVariant; size?: ButtonSize; before?: boolean; after?: boolean; className?: string } = {}) {
return cn(BUTTON_BASE, VARIANTS[variant], SIZES[size].box, before && SIZES[size].before, after && SIZES[size].after, className);
}
```
### components/filters-ui/ui/text-swap.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
export type TextSwapProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
/** The text to show. A change animates: the old text leaves upward, the new one rises in. */
children: string;
};
const EASE = "cubic-bezier(0.42, 0, 0.58, 1)";
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
/** Old text leaves over 150ms; new text enters over 170ms after 110ms; both move 4px through a 2px blur. */
export function TextSwap({ children, className, ...props }: TextSwapProps) {
const [shown, setShown] = useState(children);
const [leaving, setLeaving] = useState<{ text: string; key: number } | null>(null);
const nowRef = useRef<HTMLSpanElement>(null);
const oldRef = useRef<HTMLSpanElement>(null);
if (children !== shown) {
setLeaving(reducedMotion() ? null : { text: shown, key: (leaving?.key ?? 0) + 1 });
setShown(children);
}
useLayoutEffect(() => {
if (!leaving) return;
const out = oldRef.current?.animate(
[
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
{ opacity: 0, transform: "translateY(-4px)", filter: "blur(2px)" },
],
{ duration: 150, easing: EASE, fill: "forwards" },
);
const into = nowRef.current?.animate(
[
{ opacity: 0, transform: "translateY(4px)", filter: "blur(2px)" },
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
],
{ duration: 170, delay: 110, easing: EASE, fill: "backwards" },
);
const key = leaving.key;
const done = () => setLeaving((current) => (current?.key === key ? null : current));
if (into) into.onfinish = done;
else done();
return () => {
out?.cancel();
into?.cancel();
};
}, [leaving]);
return (
<span className={cn("inline-grid whitespace-nowrap", className)} {...props}>
<span ref={nowRef} className="[grid-area:1/1]">
{shown}
</span>
{leaving && (
<span ref={oldRef} key={leaving.key} aria-hidden="true" className="pointer-events-none [grid-area:1/1]">
{leaving.text}
</span>
)}
</span>
);
}
```
## What it does
- Looks like the text fields: 44px, a 1px border, the value after an optional prefix such as "From".
- The list grows out of the field on the page's top layer, so no card clips it, and opens on the chosen option, centred.
- Options with counts show a short bar for their share; the bars grow in, row after row, the first time the list opens.
- One highlight follows the pointer and the keys; the chosen row is tinted and its check draws in, so the two never get mixed up.
## Props and value
Select (components/filters-ui/ui/select.tsx) holds this value: string: the chosen option's value. "" is the usual value for an empty choice such as Any.
- value: string (required). The chosen value. One that matches no option shows the empty look.
- onChange: (value: string) => void (required). Called with the picked value.
- options: readonly { value: string; label: string; disabled?: boolean; count?: number }[] (required). The choices, in display order. A disabled one, or one with a count of 0, stays in place but cannot be picked. A count shows as a short bar and a number.
- label: string (required). Accessible name of the field and its list. Include the visible prefix ("From year" for "From").
- prefix: ReactNode (optional). Muted text before the value, e.g. "From".
- placeholder: string (default the label of the "" option). Shown, muted, while no option matches value.
- name: string (optional). Sends the value with a form under this name.
- formatCount / countLabel: (n: number) => string (default 1,234 / "6 results"). Text of each count, and the words read after an option's name, e.g. "6 cars".
- heading: ReactNode (optional). A line at the top of the list, e.g. "Toyota models".
- emptyText: string (default "No choices"). The quiet line in the open list when there are no options, also shown muted in the field when there is no placeholder.
- waiting: boolean (default false). A quieter field while it waits on another choice, such as Model before a make. It still opens.
- disabled: boolean (default false). Dims the field and blocks input.
- 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 choices."). The error line, in plain words.
## States
Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.
- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. The field keeps its box and prefix with a bar in place of the value, and does not open. Inside a filter's own loading StatusFrame it looks the same without a status of its own. 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 field's place. The default line is "Couldn't load the choices." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Empty (no options given, with emptyText): The field shows emptyText muted, "No choices" by default, unless a placeholder is given, and the open list holds the same quiet line.
- Zero results (every count is 0): Every option stays in the list, dimmed and aria-disabled, and cannot be picked; the current choice can still be picked again.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. The field is dimmed and does not open.
- Long labels (data, not a prop): The field ends a long value in an ellipsis; in the open list a long label wraps, its count and check staying at the end.
- Many options (data, not a prop): The list caps its height and scrolls, opening on the chosen option in the middle; Page Up, Page Down and typed digits jump.
## Usage
A working example. 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 { formatsFor } from "@/components/filters-ui/lib/format";
import { Select } from "@/components/filters-ui/ui/select";
import { TextSwap } from "@/components/filters-ui/ui/text-swap";
// Cars for sale per model year. No 2026 cars yet, so 2026 is dimmed in the list and cannot be picked.
const PER_YEAR: Record<number, number> = { 2017: 3, 2018: 4, 2019: 6, 2020: 5, 2021: 9, 2022: 7, 2023: 8, 2024: 6, 2025: 4, 2026: 0 };
const TIMELINE = Object.keys(PER_YEAR).map(Number);
const TALLEST = Math.max(...Object.values(PER_YEAR));
const carsFrom = (from: number | null) => TIMELINE.reduce((n, year) => (from === null || year >= from ? n + PER_YEAR[year] : n), 0);
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
export default function SelectExample({ locale = "en-US" }: { locale?: string }) {
const { number, plain } = formatsFor(locale);
const carCount = (n: number) => (n === 1 ? "1 car" : `${number(n)} cars`);
// Each year counts the cars it would show: that year or newer.
const options = [
{ value: "", label: "Any", count: carsFrom(null) },
...[...TIMELINE].reverse().map((year) => ({ value: String(year), label: plain(year), count: carsFrom(year) })),
];
const [from, setFrom] = useState("2021");
// Where the kept years start on the timeline, oldest first.
const cut = from === "" ? 0 : TIMELINE.indexOf(Number(from));
return (
<div className="w-full max-w-[320px]">
<Select label="From year" prefix="From" value={from} onChange={setFrom} options={options} countLabel={carCount} locale={locale} />
<div className="mt-2 rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] px-5 pt-4 pb-5">
<p aria-live="polite" className="flex items-baseline gap-1 text-[14px] leading-5 tabular-nums">
<TextSwap className="font-medium text-[var(--fu-text,#F8F5F1)]">{number(carsFrom(from === "" ? null : Number(from)))}</TextSwap>
<span className="text-[var(--fu-dim,#929292)]">cars</span>
</p>
{/* One mark per car, by model year. The kept years sit on a band whose edge slides to the new year; their marks
light up in a wave that starts at the band's edge. */}
<div aria-hidden="true" className="relative mt-5">
<span
className={`absolute -inset-y-2 -inset-e-[5px] rounded-[12px] bg-[var(--fu-selected,#1F2747)] transition-[left,right] duration-[480ms] motion-reduce:transition-none ${SMOOTH}`}
style={{ insetInlineStart: `calc(${cut} * (100% + 10px) / ${TIMELINE.length} - 5px)` }}
/>
<div className="relative grid grid-cols-10 items-end gap-2.5" style={{ height: TALLEST * 8 - 2 }}>
{TIMELINE.map((year, i) => (
<div key={year} className="flex flex-col-reverse gap-[2px]">
{Array.from({ length: PER_YEAR[year] }, (_, j) => (
<span
key={j}
className={`h-1.5 rounded-[2px] transition-[background-color] duration-300 motion-reduce:transition-none ${SMOOTH} ${
i >= cut ? "bg-[var(--fu-accent-soft,#8FAAFF)]" : "bg-[var(--fu-line,#404040)]"
}`}
style={{ transitionDelay: `${Math.abs(i - cut) * 40 + j * 14}ms` }}
/>
))}
</div>
))}
</div>
<div className="relative mt-2.5 grid grid-cols-10 gap-2.5 text-center text-[12px] leading-4 tabular-nums">
{TIMELINE.map((year, i) => (
<span
key={year}
className={`transition-[color] duration-300 motion-reduce:transition-none ${
i >= cut ? "text-[var(--fu-accent-pale,#D1DDFF)]" : "text-[var(--fu-dim,#929292)]"
}`}
>
’{plain(year).slice(2)}
</span>
))}
</div>
</div>
</div>
</div>
);
}
```
## Connect it to my data
Ask me which value it picks and where the choices come from. Map them to { value, label } with string values, and add { value: "", label: "Any" } first when the choice can be left open. Keep the value in my own state. Keep components/filters-ui/ui/popover.tsx as it is: it places the list on the page's top layer (the popover API: Chrome 114, Safari 17, Firefox 125 or newer).
## Keep the look
It is dark by default and needs no setup. To change colours, set these CSS variables on :root or on a parent element. These are the dark defaults:
```css
:root {
--fu-accent: #3B57E6;
--fu-accent-hover: #3450D4;
--fu-accent-pale: #D1DDFF;
--fu-accent-soft: #8FAAFF;
--fu-card: #1F1F1F;
--fu-card-border: #2A2A2A;
--fu-control-border: #737373;
--fu-control-hover: #A3A3A3;
--fu-dim: #929292;
--fu-field-border: #737373;
--fu-hover: #333333;
--fu-hover-wash: rgb(255 255 255/0.14);
--fu-input: rgb(0 0 0/0);
--fu-line: #404040;
--fu-mute: #BDBDBD;
--fu-on-accent: #FFFFFF;
--fu-rail: #4A4A4A;
--fu-rim: rgb(255 255 255/0.04);
--fu-row-active: rgb(255 255 255/0.07);
--fu-row-press: rgb(255 255 255/0.12);
--fu-selected: #1F2747;
--fu-shadow: rgb(0 0 0/0.5);
--fu-shadow-deep: rgb(0 0 0/0.8);
--fu-skeleton: rgb(255 255 255/0.12);
--fu-skeleton-on: rgb(143 170 255/0.3);
--fu-surface-3: #2A2A2A;
--fu-text: #F8F5F1;
--fu-track: rgb(255 255 255/0.06);
}
```
To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).
```css
.light {
--fu-accent: #3B57E6;
--fu-accent-hover: #2F4AD0;
--fu-accent-pale: #253A9E;
--fu-accent-soft: #3049D2;
--fu-card: #FFFFFF;
--fu-card-border: #E5E5E2;
--fu-control-border: #787874;
--fu-control-hover: #5B5B57;
--fu-dim: #555552;
--fu-field-border: #949490;
--fu-hover: rgb(29 27 24/0.11);
--fu-hover-wash: rgb(29 27 24/0.07);
--fu-input: #FFFFFF;
--fu-line: #C4C4C0;
--fu-mute: #444442;
--fu-on-accent: #FFFFFF;
--fu-rail: #D6D6D2;
--fu-rim: rgb(255 255 255/0.7);
--fu-row-active: rgb(29 27 24/0.05);
--fu-row-press: rgb(29 27 24/0.09);
--fu-selected: #E8EDFD;
--fu-shadow: rgb(36 36 33/0.12);
--fu-shadow-deep: rgb(36 36 33/0.16);
--fu-skeleton: rgb(29 27 24/0.09);
--fu-skeleton-on: rgb(48 73 210/0.18);
--fu-surface-3: rgb(29 27 24/0.07);
--fu-text: #1B1B19;
--fu-track: rgb(29 27 24/0.07);
}
```
Keep the sizes, corners, spacing and motion as they are.
## Direction and language
It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.
Pass locale (default "en-US") to print its numbers, prices and dates the way a language writes them and to read typed numbers that way, e.g. locale="de-DE". The words stay English: change them through the props.
## Keep the accessibility
- The field is a button with role="combobox", aria-expanded and aria-activedescendant; focus stays on it while the list is open.
- The list is a listbox of options with aria-selected on the chosen one and aria-disabled on the ones that cannot be picked.
- The visible prefix is hidden from screen readers; the label carries it.
- Loading, it is aria-busy, says "Loading" once and does not open; an error is read out politely, and Retry keeps focus in the field's place. Disabled, the field is a disabled button.
- Down, Up, Enter or Space opens the list; typing opens it on the first match.
- Up and Down move without wrapping; Home, End, Page Up and Page Down jump; typed letters or digits ("2015") find an option.
- Enter or Space picks; Escape closes without a change; Tab picks the option the keys moved to and moves on.
- While disabled or loading Tab skips the field; in an error Tab reaches Retry.
When done, run the app, tell me which page to open, and show me it working.What it does
- Looks like the text fields: 44px, a 1px border, the value after an optional prefix such as "From".
- The list grows out of the field on the page's top layer, so no card clips it, and opens on the chosen option, centred.
- Options with counts show a short bar for their share; the bars grow in, row after row, the first time the list opens.
- One highlight follows the pointer and the keys; the chosen row is tinted and its check draws in, so the two never get mixed up.
Keyboard
- Down, Up, Enter or Space opens the list; typing opens it on the first match.
- Up and Down move without wrapping; Home, End, Page Up and Page Down jump; typed letters or digits ("2015") find an option.
- Enter or Space picks; Escape closes without a change; Tab picks the option the keys moved to and moves on.
- While disabled or loading Tab skips the field; in an error Tab reaches Retry.
Props
Value. string: the chosen option's value. "" is the usual value for an empty choice such as Any.
| Prop | Description |
|---|---|
valueRequired | The chosen value. One that matches no option shows the empty look. string |
onChangeRequired | Called with the picked value. (value: string) => void |
optionsRequired | The choices, in display order. A disabled one, or one with a count of 0, stays in place but cannot be picked. A count shows as a short bar and a number. readonly { value: string; label: string; disabled?: boolean; count?: number }[] |
labelRequired | Accessible name of the field and its list. Include the visible prefix ("From year" for "From"). string |
prefixOptional | Muted text before the value, e.g. "From". ReactNode |
placeholderDefault the label of the "" option | Shown, muted, while no option matches value. string |
nameOptional | Sends the value with a form under this name. string |
formatCount / countLabelDefault 1,234 / "6 results" | Text of each count, and the words read after an option's name, e.g. "6 cars". (n: number) => string |
headingOptional | A line at the top of the list, e.g. "Toyota models". ReactNode |
emptyTextDefault "No choices" | The quiet line in the open list when there are no options, also shown muted in the field when there is no placeholder. string |
waitingDefault false | A quieter field while it waits on another choice, such as Model before a make. It still opens. boolean |
disabledDefault false | Dims the field and blocks input. boolean |
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 choices." | The error line, in plain words. string |