Live example
192 of 256 cars
Copy
Add the "Date range" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Date range: Pick a first and last day on a calendar, or a preset such as Last 7 days.
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/date-range.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/date-range.tsx
```tsx
"use client";
import {
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type CSSProperties,
type HTMLAttributes,
type KeyboardEvent,
} from "react";
import { cn } from "../lib/cn";
import { isRtl, onDirChange, readingKey } from "../lib/direction";
import { formatsFor, resultsLabel, type Formats } from "../lib/format";
import { ChevronDownIcon } from "../ui/icons";
import { Skeleton, SKELETON_FILL, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextField } from "../ui/text-field";
import { TextSwap } from "../ui/text-swap";
/** * A span of days. { last: 7 } is the last 7 days with today, and moves on as the days pass. { start, end } are fixed
* days, "YYYY-MM-DD", both included. null is any time.
*/
export type DateRangeValue = { last: number } | { start: string; end: string } | null;
export type DatePreset = { label: string; last: number };
export const DEFAULT_DATE_PRESETS: readonly DatePreset[] = [
{ label: "Today", last: 1 },
{ label: "Last 3 days", last: 3 },
{ label: "Last 7 days", last: 7 },
{ label: "Last 30 days", last: 30 },
];
export type DateRangeProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
Omit<StateProps, "emptyText"> & {
value: DateRangeValue;
onChange: (value: DateRangeValue) => void;
/** Today as "YYYY-MM-DD". Default: the visitor's own date, read in the browser, so the server never guesses it. */
today?: string;
/** The quick picks between Any time and Custom. */
presets?: readonly DatePreset[];
/** Items on one day ("YYYY-MM-DD"): the small number under each date and the count beside each preset. */
countOf?: (date: string) => number;
/** Every item, whatever its date: the count beside Any time. */
total?: number;
/** Accessible name of the presets and the calendar, e.g. "Listed". */
label?: string;
anyLabel?: string;
customLabel?: string;
/** Days after today can be picked too. Default false: they show dimmed. */
allowFuture?: boolean;
/** The first day of the week: 0 is Sunday, 1 Monday, 6 Saturday. Default: the locale's (Sunday in en-US, Monday in de-DE). */
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
formatCount?: (n: number) => string;
/** Screen-reader words for a count: "6 results". */
countLabel?: (n: number) => string;
/**
* Month and weekday names, the first day of the week, the order of typed dates ("3.11." in de-DE) and the numbers
* follow it, e.g. "de-DE". Default "en-US". The words of the presets stay as given.
*/
locale?: string;
};
const DAY = 86_400_000;
const pad = (n: number) => String(n).padStart(2, "0");
const parts = (iso: string) => [Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10))] as const;
const timeOf = (iso: string) => Date.UTC(...parts(iso));
const isoOf = (time: number) => {
const d = new Date(time);
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
};
const daysIn = (year: number, month: number) => new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
export const addDays = (iso: string, days: number) => isoOf(timeOf(iso) + days * DAY);
/** The day of iso in month, clamped to the month's last day. */
const sameDayIn = (month: string, iso: string) => {
const [year, m] = parts(month);
return `${month.slice(0, 7)}-${pad(Math.min(parts(iso)[2], daysIn(year, m)))}`;
};
/** Whole days from one date to another: 1 from today to tomorrow. */
export const daysBetween = (from: string, to: string) => Math.round((timeOf(to) - timeOf(from)) / DAY);
const firstOfMonth = (iso: string) => `${iso.slice(0, 7)}-01`;
const addMonths = (iso: string, months: number) => {
const [y, m, d] = parts(iso);
const first = new Date(Date.UTC(y, m + months, 1));
const year = first.getUTCFullYear();
const month = first.getUTCMonth();
return isoOf(Date.UTC(year, month, Math.min(d, daysIn(year, month))));
};
const minIso = (a: string, b: string) => (a < b ? a : b);
const maxIso = (a: string, b: string) => (a > b ? a : b);
/** The fixed days a value covers, given today, or null for any time. */
export function resolveDateRange(value: DateRangeValue, today: string): { start: string; end: string } | null {
if (!value) return null;
if ("last" in value) return { start: addDays(today, -(Math.max(1, value.last) - 1)), end: today };
return { start: minIso(value.start, value.end), end: maxIso(value.start, value.end) };
}
const yearOf = (iso: string) => Number(iso.slice(0, 4));
// "19. Okt." reads as "19 Okt": a dot that ends an abbreviation or a day number goes.
const noDots = (text: string) => text.replace(/\.(?=\s|$)/g, "");
// US English keeps its hand-built dates; every other locale, English ones too, takes its own from Intl.
const english = (f: Formats) => f.locale === "en" || f.locale === "en-US";
const weekdayOf = (iso: string) => new Date(timeOf(iso)).getUTCDay();
// "Nov 3", with the year only when it is not this year's.
const shortDay = (f: Formats, iso: string, today: string | null) =>
noDots(f.day(iso, { month: "short", day: "numeric", ...(today && yearOf(today) === yearOf(iso) ? {} : { year: "numeric" }) }));
const spokenDay = (f: Formats, iso: string) => f.day(iso, { weekday: "long", month: "long", day: "numeric", year: "numeric" });
// A day cell's name: the grid is named by its month and year, and the day number comes last in every locale, so the
// count read after it follows it, as on screen ("Sonntag, November 1, 6 cars").
const cellDay = (f: Formats, iso: string) =>
english(f)
? f.day(iso, { weekday: "long", month: "long", day: "numeric" })
: `${f.weekday(weekdayOf(iso))}, ${f.month(parts(iso)[1])} ${f.plain(parts(iso)[2])}`;
// English keeps its three-letter months and two-letter weekdays; other locales take their own short forms.
const monthShort = (f: Formats, m: number) => (english(f) ? f.month(m).slice(0, 3) : f.month(m, "short"));
const weekdayHead = (f: Formats, i: number) => {
if (english(f)) return f.weekday(i).slice(0, 2);
const short = f.weekday(i, "short");
return short.length > 3 ? new Intl.DateTimeFormat(f.locale, { weekday: "narrow", timeZone: "UTC" }).format(Date.UTC(2021, 0, 3 + i)) : short;
};
function describe(f: Formats, value: DateRangeValue, presets: readonly DatePreset[], today: string | null, long: boolean) {
if (!value) return null;
if ("last" in value) return presets.find((p) => p.last === value.last)?.label ?? (value.last === 1 ? "Today" : `Last ${f.number(value.last)} days`);
const start = minIso(value.start, value.end);
const end = maxIso(value.start, value.end);
const month = long ? "long" : "short";
const thisYear = (iso: string) => !!today && yearOf(today) === yearOf(iso);
const sameMonth = start.slice(0, 7) === end.slice(0, 7);
if (!english(f)) {
const day = (iso: string, withYear: boolean) => noDots(f.day(iso, { month, day: "numeric", ...(withYear ? { year: "numeric" } : {}) }));
if (start === end) return day(start, !thisYear(start));
// Both ends whole: a bare last day or year after a day-first date reads as unfinished ("3. Nov. to 9").
if (yearOf(start) !== yearOf(end) || !thisYear(end)) return `${day(start, true)} to ${day(end, true)}`;
return `${day(start, false)} to ${day(end, false)}`;
}
const name = (iso: string) => (long ? f.month(parts(iso)[1]) : monthShort(f, parts(iso)[1]));
const day = (iso: string) => `${name(iso)} ${f.plain(parts(iso)[2])}`;
const tail = (iso: string) => (thisYear(iso) ? "" : `, ${f.plain(yearOf(iso))}`);
if (start === end) return `${day(start)}${tail(start)}`;
if (yearOf(start) !== yearOf(end)) return `${day(start)}, ${f.plain(yearOf(start))} to ${day(end)}, ${f.plain(yearOf(end))}`;
return `${day(start)} to ${sameMonth ? f.plain(parts(end)[2]) : day(end)}${tail(end)}`;
}
/**
* The value in words: a preset's label, "Nov 3", "Nov 3 to 9" or "Oct 28 to Nov 3". The year shows only when it is
* not today's. Dates follow the locale ("3. Nov." in de-DE); the joining words stay English.
*/
export const formatDateRange = (
value: DateRangeValue,
presets: readonly DatePreset[] = DEFAULT_DATE_PRESETS,
today: string | null = null,
locale?: string,
) => describe(formatsFor(locale), value, presets, today, false);
const ENGLISH_MONTHS = Array.from({ length: 12 }, (_, m) => formatsFor().month(m).toLowerCase());
/** Days written before months in the locale's numeric dates, as "3.11." in de-DE. */
const dayFirst = (locale: string) => {
const order = new Intl.DateTimeFormat(locale, { day: "numeric", month: "numeric", timeZone: "UTC" }).formatToParts(0).map((p) => p.type);
return order.indexOf("day") < order.indexOf("month");
};
/**
* A date written as the locale writes it ("11月3日", "3 בנוב׳ 2025"), found by writing the days out: with no year, the
* latest such day up to today; with one, a day of that year as the locale's calendar counts it.
*/
function shownDay(f: Formats, typed: string, today: string, norm: (text: string) => string) {
const year = typed.match(/\d{4}/)?.[0];
let from = today;
let days = 366;
if (year) {
// 2569 in th-TH is 2026.
const offset = Number(norm(f.day(today, { year: "numeric" })).match(/\d+/)?.[0] ?? yearOf(today)) - yearOf(today);
const gregorian = Number(year) - offset;
if (gregorian < 1000 || gregorian > 9998) return null;
// Another calendar's year can start in any month, so its neighbours are searched too.
from = `${offset ? gregorian + 1 : gregorian}-12-31`;
days = offset ? 3 * 366 : 366;
}
const forms = (["short", "long"] as const).map((month): Intl.DateTimeFormatOptions => ({ month, day: "numeric", ...(year ? { year: "numeric" } : {}) }));
for (let i = 0; i < days; i++) {
const iso = addDays(from, -i);
if (forms.some((o) => norm(f.day(iso, o)) === typed)) return iso;
}
return null;
}
/**
* Reads a typed date: "Nov 3", "November 3, 2026", "3 Nov", "11/3", "11/3/26", "2026-11-03", "today" or "yesterday".
* With a locale it also reads that locale's month names and digits, and takes numeric dates in its order: "3.11." and
* "3/11/26" are 3 November in de-DE. It reads back any date as the fields show it ("11月3日" in ja-JP). With no year it
* takes the latest such day that is not after today. Returns null for anything else.
*/
export function parseDate(text: string, today: string, locale?: string): string | null {
const f = formatsFor(locale);
const months = english(f) ? ENGLISH_MONTHS : Array.from({ length: 12 }, (_, m) => f.month(m).toLocaleLowerCase(f.locale));
const shortMonths = english(f) ? [] : Array.from({ length: 12 }, (_, m) => f.month(m, "short").toLocaleLowerCase(f.locale).replace(/\./g, ""));
const swap = !english(f) && dayFirst(f.locale);
const norm = (text: string) => {
let typed = text;
for (let i = 0; i < 10; i++) typed = typed.split(f.digits[i]).join(String(i));
return typed
.trim()
.toLocaleLowerCase(f.locale)
.replace(/(\d)(st|nd|rd|th)\b/g, "$1")
.replace(/[.,\u060c]/g, " ")
.replace(/\s+/g, " ")
.trim();
};
const t = norm(text);
if (!t) return null;
if (t === "today") return today;
if (t === "yesterday") return addDays(today, -1);
let y: number | null = null;
let m: number | null = null;
let d: number | null = null;
let match: RegExpMatchArray | null;
const monthAt = (word: string) => {
if (word.length < 3 && !shortMonths.includes(word)) return -1;
const at = months.findIndex((name) => name.startsWith(word));
if (at >= 0) return at;
const short = shortMonths.indexOf(word);
return short >= 0 ? short : ENGLISH_MONTHS.findIndex((name) => word.length >= 3 && name.startsWith(word));
};
if ((match = t.match(/^(\d{4})[-/ ](\d{1,2})[-/ ](\d{1,2})$/))) [y, m, d] = [Number(match[1]), Number(match[2]) - 1, Number(match[3])];
else if ((match = t.match(swap ? /^(\d{1,2})[/ -](\d{1,2})(?:[/ -](\d{2}|\d{4}))?$/ : /^(\d{1,2})[/-](\d{1,2})(?:[/-](\d{2}|\d{4}))?$/))) {
[m, d] = swap ? [Number(match[2]) - 1, Number(match[1])] : [Number(match[1]) - 1, Number(match[2])];
if (match[3]) y = match[3].length === 2 ? 2000 + Number(match[3]) : Number(match[3]);
} else if ((match = t.match(/^(\p{L}+) (\d{1,2})(?: (\d{4}))?$/u)) && monthAt(match[1]) >= 0) {
[m, d] = [monthAt(match[1]), Number(match[2])];
if (match[3]) y = Number(match[3]);
} else if ((match = t.match(/^(\d{1,2}) (\p{L}+)(?: (\d{4}))?$/u)) && monthAt(match[2]) >= 0) {
[m, d] = [monthAt(match[2]), Number(match[1])];
if (match[3]) y = Number(match[3]);
} else return shownDay(f, t, today, norm);
if (m === null || d === null || m < 0 || m > 11 || d < 1) return null;
const guess = y === null;
let year = y ?? Number(today.slice(0, 4));
// Steps back past years without the day, so Feb 29 finds the last leap year; 8 covers the gap at 2100.
if (guess) for (let i = 0; i < 8 && (d > daysIn(year, m) || `${year}-${pad(m + 1)}-${pad(d)}` > today); i++) year -= 1;
if (d > daysIn(year, m)) return null;
return `${year}-${pad(m + 1)}-${pad(d)}`;
}
const localToday = () => {
const now = new Date();
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
};
// Checked each minute, so a page left open past midnight moves on to the new day.
const subscribeToDay = (onChange: () => void) => {
const timer = setInterval(onChange, 60_000);
return () => clearInterval(timer);
};
const noDay = () => null;
/** Today as "YYYY-MM-DD" in the visitor's time zone, or null during the server render and hydration, so the two always match. */
export const useToday = () => useSyncExternalStore(subscribeToDay, localToday, noDay);
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
const FOCUS_RING = "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
type Band = { start: string; end: string } | null;
type Growth = { band: Band; before: Band; toward: "start" | "end" };
/**
* Presets (Any time, Today, Last 3, 7 and 30 days, Custom) over a one-month calendar and typed From and To fields.
* Picking a day starts a range; the band follows the pointer day by day until a second pick ends it. Each day can carry
* its count. The calendar is a keyboard grid: arrows by day and week, Page Up and Page Down by month, with Shift by year.
* Right to left, the week runs from the right, previous and next swap sides, and Left and Right follow the screen.
*/
export function DateRange({
value,
onChange,
today: todayProp,
presets = DEFAULT_DATE_PRESETS,
countOf,
total,
label = "Dates",
anyLabel = "Any time",
customLabel = "Custom",
allowFuture = false,
weekStartsOn: weekStartsOnProp,
formatCount: formatCountProp,
countLabel: countLabelProp,
locale,
status = "ready",
onRetry,
errorText = "Couldn't load the counts.",
disabled = false,
className,
...props
}: DateRangeProps) {
// 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 f = formatsFor(locale);
const weekStartsOn = weekStartsOnProp ?? f.firstDay;
const formatCount = formatCountProp ?? f.number;
const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
const id = useId();
const browserToday = useToday();
const today = todayProp ?? browserToday;
// Custom pressed while the value still matches a preset: it stays checked until the value changes.
const [customFor, setCustomFor] = useState<DateRangeValue | undefined>(undefined);
const [pending, setPending] = useState<{ anchor: string; before: DateRangeValue } | null>(null);
const [preview, setPreview] = useState<string | null>(null);
const [viewMonth, setViewMonth] = useState<string | null>(null);
const [focusDay, setFocusDay] = useState<string | null>(null);
const [mode, setMode] = useState<"days" | "months">("days");
const [said, setSaid] = useState("");
const grid = useRef<HTMLDivElement>(null);
const months = useRef<HTMLDivElement>(null);
const focusAfterRender = useRef<"day" | "month" | null>(null);
const range = today ? resolveDateRange(value, today) : null;
const shownMonth = viewMonth ?? (today ? firstOfMonth(range?.end ?? today) : null);
// The grid's one tab stop. When the shown month moved without it (a year step, the month view), the same day of the
// shown month takes it, so the grid never loses its tab stop.
const wanted = focusDay ?? range?.end ?? today;
const focused = wanted && shownMonth && wanted.slice(0, 7) !== shownMonth.slice(0, 7) ? sameDayIn(shownMonth, wanted) : wanted;
const pickable = (iso: string) => allowFuture || !today || iso <= today;
// A value set from outside, such as a Clear on the card around it, ends a half-picked range; the one day the pick set
// keeps it. Compared by content, so a parent that hands back an equal new object does not end it.
const valueKey = !value ? "" : "last" in value ? `last ${value.last}` : `${value.start}/${value.end}`;
const [seenValue, setSeenValue] = useState(valueKey);
if (valueKey !== seenValue) {
setSeenValue(valueKey);
if (pending && valueKey !== `${pending.anchor}/${pending.anchor}`) {
setPending(null);
setPreview(null);
setSaid("");
}
}
// While a range is half picked, the band runs from its first day to the day under the pointer or the keys.
const band: Band = pending ? { start: minIso(pending.anchor, preview ?? pending.anchor), end: maxIso(pending.anchor, preview ?? pending.anchor) } : range;
const bandKey = band ? `${band.start}/${band.end}` : "";
const [growth, setGrowth] = useState<Growth>({ band, before: band, toward: "end" });
const nextToward = useRef<"start" | "end">("end");
if ((growth.band ? `${growth.band.start}/${growth.band.end}` : "") !== bandKey) {
setGrowth({ band, before: growth.band, toward: nextToward.current });
}
// Counts per day are read once per countOf and kept, so a long typed range or a pointer sweep does not count again.
const daily = useMemo(() => new Map<string, number>(), [countOf]);
const dayCount = (day: string) => {
let n = daily.get(day);
if (n === undefined) {
n = countOf ? countOf(day) : 0;
daily.set(day, n);
}
return n;
};
const sum = (r: Band) => {
if (!countOf || !r) return null;
let all = 0;
for (let day = r.start; day <= r.end; day = addDays(day, 1)) all += dayCount(day);
return all;
};
// The month the calendar showed before, kept on screen while it slides out.
const [leaving, setLeaving] = useState<{ month: string; dir: 1 | -1; key: number } | null>(null);
const showMonth = (month: string) => {
if (!shownMonth || month === shownMonth) return;
if (!reducedMotion()) setLeaving({ month: shownMonth, dir: month > shownMonth ? 1 : -1, key: (leaving?.key ?? 0) + 1 });
setViewMonth(month);
};
const commit = (next: DateRangeValue) => {
onChange(next);
const r = next && today ? resolveDateRange(next, today) : null;
const total = sum(r);
const text = describe(f, next, presets, today, true) ?? anyLabel;
setSaid(total === null || !next ? text : `${text}, ${countLabel(total)}`);
};
const pickDay = (iso: string) => {
if (!pickable(iso)) return;
setFocusDay(iso);
if (iso.slice(0, 7) !== shownMonth?.slice(0, 7)) showMonth(firstOfMonth(iso));
if (pending) {
const start = minIso(pending.anchor, iso);
const end = maxIso(pending.anchor, iso);
nextToward.current = iso >= pending.anchor ? "end" : "start";
setPending(null);
setPreview(null);
commit({ start, end });
return;
}
nextToward.current = "end";
setPending({ anchor: iso, before: value });
setPreview(null);
onChange({ start: iso, end: iso });
setSaid(`${spokenDay(f, iso)}. Now pick the last day, or press Escape.`);
};
const dropPending = () => {
if (!pending) return false;
nextToward.current = "end";
onChange(pending.before);
setPending(null);
setPreview(null);
setSaid("Range dropped.");
return true;
};
// Preset choices: Any time, each preset, then Custom.
const custom = customFor === value || (value !== null && !("last" in value && presets.some((p) => p.last === value.last)));
const choices = [
{ key: "any", label: anyLabel, value: null as DateRangeValue, on: !custom && value === null, count: (total ?? null) as number | null },
...presets.map((p) => ({
key: `last-${p.last}`,
label: p.label,
value: { last: p.last } as DateRangeValue,
on: !custom && value !== null && "last" in value && value.last === p.last,
count: today ? sum(resolveDateRange({ last: p.last }, today)) : null,
})),
{ key: "custom", label: customLabel, value: null as DateRangeValue, on: custom, count: custom && range && !pending ? sum(range) : null },
];
const choose = (index: number, viaPointer: boolean) => {
const choice = choices[index];
setPending(null);
setPreview(null);
if (choice.key === "custom") {
setCustomFor(value);
if (viaPointer) {
focusAfterRender.current = "day";
setMode("days");
}
return;
}
setCustomFor(undefined);
nextToward.current = "end";
if (choice.value && today) {
showMonth(firstOfMonth(today));
setFocusDay(today);
}
commit(choice.value);
};
// The checked preset's wash is measured onto it; until measured, the checked button paints its own.
const presetButtons = useRef<(HTMLButtonElement | null)[]>([]);
const checkedIndex = choices.findIndex((c) => c.on);
const [wash, setWash] = useState<{ left: number; top: number; width: number; height: number } | null>(null);
const [washPlaced, setWashPlaced] = useState(false);
// An error unmounts the buttons, so each status change measures them again.
useLayoutEffect(() => {
const button = presetButtons.current[checkedIndex];
if (!button) return;
const measure = () => setWash({ left: button.offsetLeft, top: button.offsetTop, width: button.offsetWidth, height: button.offsetHeight });
measure();
const frame = requestAnimationFrame(() => setWashPlaced(true));
const observer = new ResizeObserver(measure);
observer.observe(button);
if (button.parentElement) observer.observe(button.parentElement);
const stop = onDirChange(measure);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
stop();
};
}, [checkedIndex, status]);
const onPresetKeys = (event: KeyboardEvent<HTMLDivElement>) => {
const from = Math.max(0, presetButtons.current.findIndex((b) => b === document.activeElement));
const n = choices.length;
const next = { ArrowRight: from + 1, ArrowDown: from + 1, ArrowLeft: from - 1, ArrowUp: from - 1, Home: 0, End: n - 1 }[readingKey(event.key, event.currentTarget)];
if (next === undefined) return;
event.preventDefault();
const index = (next + n) % n;
presetButtons.current[index]?.focus();
choose(index, false);
};
// Focus follows the keys into a new month once it has rendered.
useLayoutEffect(() => {
const target = focusAfterRender.current;
if (!target) return;
focusAfterRender.current = null;
const root = target === "day" ? grid.current : months.current;
root?.querySelector<HTMLElement>('[tabindex="0"]')?.focus({ preventScroll: true });
});
const moveFocus = (iso: string) => {
setFocusDay(iso);
if (pending) setPreview(iso);
if (shownMonth && iso.slice(0, 7) !== shownMonth.slice(0, 7)) showMonth(firstOfMonth(iso));
focusAfterRender.current = "day";
};
const onGridKeys = (event: KeyboardEvent<HTMLDivElement>) => {
if (!focused || disabled) return;
const weekday = (weekdayOf(focused) - weekStartsOn + 7) % 7;
const key = readingKey(event.key, event.currentTarget);
const moves: Record<string, () => string> = {
ArrowLeft: () => addDays(focused, -1),
ArrowRight: () => addDays(focused, 1),
ArrowUp: () => addDays(focused, -7),
ArrowDown: () => addDays(focused, 7),
Home: () => addDays(focused, -weekday),
End: () => addDays(focused, 6 - weekday),
PageUp: () => addMonths(focused, event.shiftKey ? -12 : -1),
PageDown: () => addMonths(focused, event.shiftKey ? 12 : 1),
};
if (moves[key]) {
event.preventDefault();
moveFocus(moves[key]());
} else if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
pickDay(focused);
} else if (event.key === "Escape" && dropPending()) {
event.stopPropagation();
}
};
const step = (by: number) => {
if (!shownMonth) return;
if (mode === "months") {
setViewMonth(addMonths(shownMonth, by * 12));
return;
}
showMonth(addMonths(shownMonth, by));
if (focused) setFocusDay(addMonths(focused, by));
};
// Day cells: the band segment under each day grows or shrinks one day after another, from the end that stayed put,
// counted within the month on screen so days out of view never hold the sweep up.
const timingIn = (first: string, last: string) => {
const clip = (b: Band) => (b && b.end >= first && b.start <= last ? { start: maxIso(b.start, first), end: minIso(b.end, last) } : null);
const now = clip(growth.band);
const before = clip(growth.before);
const toward = growth.toward;
const order = (day: string) => {
const inNow = !!now && day >= now.start && day <= now.end;
const inBefore = !!before && day >= before.start && day <= before.end;
if (now && before) {
if (inNow && !inBefore) return day < before.start ? daysBetween(day, before.start) : daysBetween(before.end, day);
if (inBefore && !inNow) return day < now.start ? daysBetween(before.start, day) : daysBetween(day, before.end);
// A day that becomes an end as the band shrinks onto it changes last.
if (day === now.start && before.start < now.start) return daysBetween(before.start, now.start);
if (day === now.end && before.end > now.end) return daysBetween(now.end, before.end);
return 0;
}
if (now && inNow) return toward === "end" ? daysBetween(day, now.end) : daysBetween(now.start, day);
if (before && inBefore) return toward === "end" ? daysBetween(before.start, day) : daysBetween(day, before.end);
return 0;
};
const changed =
now && before
? Math.abs(daysBetween(before.start, now.start)) + Math.abs(daysBetween(before.end, now.end))
: now
? daysBetween(now.start, now.end)
: before
? daysBetween(before.start, before.end)
: 0;
// Each segment runs while the one before it finishes, so the band sweeps on without gaps and slows as it lands.
const slots = changed + 1;
const sweep = Math.min(440, Math.max(150, slots * 36));
const landing = (t: number) => 1 - Math.pow(1 - Math.min(1, t), 2.2);
return (day: string) => {
const k = order(day);
const from = landing(k / slots);
return { delay: Math.round(sweep * from), duration: Math.max(16, Math.round(sweep * (landing((k + 1) / slots) - from))) };
};
};
const weekdays = Array.from({ length: 7 }, (_, i) => (i + weekStartsOn) % 7);
const weeksOf = (month: string) => {
const [y, m] = parts(month);
const lead = (new Date(Date.UTC(y, m, 1)).getUTCDay() - weekStartsOn + 7) % 7;
const total = daysIn(y, m);
return Array.from({ length: Math.ceil((lead + total) / 7) }, (_, w) =>
Array.from({ length: 7 }, (_, c) => {
const d = w * 7 + c - lead + 1;
return d >= 1 && d <= total ? `${month.slice(0, 8)}${pad(d)}` : null;
}),
);
};
// A band that runs on into the month before or after fades out over the empty days of the week, so it reads as going
// on rather than cut off.
const runOn = (cells: number, side: "start" | "end", on: boolean, delay: number) =>
cells > 0 && (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-y-0 from-transparent to-[var(--fu-selected,#1F2747)] pointer-coarse:inset-y-0.5 forced-colors:hidden",
"transition-opacity duration-200 ease-out motion-reduce:transition-none",
side === "start" ? "start-0 bg-linear-to-r rtl:bg-linear-to-l" : "end-0 bg-linear-to-l rtl:bg-linear-to-r",
on ? "opacity-100" : "opacity-0",
)}
style={{ width: `calc(${cells} * 100% / 7 + 0.5px)`, transitionDelay: `${on ? delay : 0}ms` }}
/>
);
const renderGrid = (month: string, live: boolean) => {
const [year, monthIndex] = parts(month);
const first = `${month.slice(0, 8)}01`;
const last = `${month.slice(0, 8)}${pad(daysIn(year, monthIndex))}`;
const timingOf = timingIn(month, last);
const weeks = weeksOf(month);
const fromBefore = !!band && band.start < first && band.end >= first;
const intoAfter = !!band && band.end > last && band.start <= last;
return weeks.map((week, w) => (
// Keyed by month, so a new month mounts fresh instead of animating the old days' bands away.
<div key={`${month}-${w}`} role={live ? "row" : undefined} className="relative grid grid-cols-7">
{w === 0 && runOn(week.indexOf(first), "start", fromBefore, timingOf(first).delay)}
{w === weeks.length - 1 && runOn(6 - week.indexOf(last), "end", intoAfter, timingOf(last).delay)}
{week.map((day, c) => {
if (!day) return <div key={c} role={live ? "gridcell" : undefined} className="h-10 pointer-coarse:h-11" />;
const n = Number(day.slice(8, 10));
const isToday = day === today;
const can = pickable(day);
// While loading, a day's count is a placeholder and its number keeps the plain colour.
const count = countOf && can && !loading ? dayCount(day) : null;
const countLoading = !!countOf && can && loading;
const inBand = !!band && day >= band.start && day <= band.end;
const isStart = !!band && day === band.start;
const isEnd = !!band && day === band.end;
const single = isStart && isEnd;
const isEdge = isStart || isEnd;
const isPreviewEnd = !!pending && !!preview && preview !== pending.anchor && day === preview;
const selected = !!range && day >= range.start && day <= range.end;
const timing = timingOf(day);
const before = !band || day < band.start;
// The band is square where it wraps to the next week or runs into another month. Under a filled circle it also
// stops square, at the circle's middle, so the circle closes it; a round end there would pinch in beside the
// circle. Under the outlined circle of a day being pointed at, it runs on to the circle's edge and rounds with
// it, so the outline holds the band's end.
const roundStart = isStart && isPreviewEnd;
const roundEnd = isEnd && isPreviewEnd;
const endInset = isPreviewEnd ? "calc(50% - 20px)" : "50%";
return (
<div
key={c}
role={live ? "gridcell" : undefined}
tabIndex={live ? (day === focused && !disabled ? 0 : -1) : undefined}
aria-selected={live ? selected : undefined}
aria-disabled={live && !can ? true : undefined}
aria-current={live && isToday ? "date" : undefined}
aria-label={live ? `${cellDay(f, day)}${count !== null ? `, ${countLabel(count)}` : ""}` : undefined}
data-day={day}
onClick={live ? () => pickDay(day) : undefined}
onPointerEnter={live && pending && can ? () => setPreview(day) : undefined}
onFocus={live ? () => setFocusDay(day) : undefined}
className={cn(
"group/day relative flex h-10 items-center justify-center outline-none pointer-coarse:h-11",
can ? "cursor-pointer" : "cursor-default",
)}
>
<span
aria-hidden="true"
className={cn(
"absolute inset-y-0 bg-[var(--fu-selected,#1F2747)] pointer-coarse:inset-y-0.5",
"transition-[clip-path,left,right,border-radius] ease-linear motion-reduce:transition-none",
roundStart ? "rounded-s-[20px]" : "rounded-s-none",
roundEnd ? "rounded-e-[20px]" : "rounded-e-none",
// Out of the band, a segment is clipped to nothing at the band's side, so it grows in from there.
inBand && !single
? "[clip-path:inset(0_0_0_0)]"
: before
? "[clip-path:inset(0_0_0_100%)] rtl:[clip-path:inset(0_100%_0_0)]"
: "[clip-path:inset(0_100%_0_0)] rtl:[clip-path:inset(0_0_0_100%)]",
)}
style={{
// Neighbouring segments overlap by a pixel, so no seam shows between days.
insetInlineStart: inBand && isStart && !single ? endInset : -0.5,
insetInlineEnd: inBand && isEnd && !single ? endInset : -0.5,
transitionDelay: `${timing.delay}ms`,
transitionDuration: `${timing.duration}ms`,
}}
/>
<span
aria-hidden="true"
className={cn(
"relative flex size-10 flex-col items-center justify-center rounded-full",
"transition-[color,background-color,box-shadow,scale] duration-[180ms] motion-reduce:transition-none",
SMOOTH,
isEdge && !isPreviewEnd
? "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)]"
: isPreviewEnd
? "text-[var(--fu-accent-pale,#D1DDFF)] shadow-[inset_0_0_0_1.5px_var(--fu-accent-soft,#8FAAFF)]"
: inBand
? "text-[var(--fu-accent-pale,#D1DDFF)]"
: can
? count === 0
? "text-[var(--fu-dim,#929292)]"
: "text-[var(--fu-text,#F8F5F1)]"
: "text-[var(--fu-line,#404040)]",
isToday && !isEdge && !isPreviewEnd && "shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)]",
// Forced colours drop the band's fill, so the picked days take the system highlight instead.
(inBand || isEdge) && "forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:[forced-color-adjust:none]",
can && !isEdge && !inBand && "group-hover/day:bg-[var(--fu-item-hover,#2A2A2A)]",
can && "group-active/day:scale-[0.94] group-active/day:duration-75",
live && "group-focus-visible/day:outline-2 group-focus-visible/day:outline-offset-1 group-focus-visible/day:outline-solid group-focus-visible/day:outline-[var(--fu-accent-soft,#8FAAFF)]",
)}
// The day's colours change as the band reaches it; a hover never waits.
style={{ transitionDelay: isEdge ? `${timing.delay}ms` : `${timing.delay}ms, 0ms, 0ms, 0ms` }}
>
<span className="text-[14px] font-medium leading-4 tabular-nums">{f.plain(n)}</span>{" "}
{/* Every date keeps the count's line, so the numbers sit on one baseline whether a day has items or not. */}
{countOf && (
<span
className={cn(
"mt-px h-3 text-[10px] leading-3 tabular-nums transition-colors duration-[180ms] motion-reduce:transition-none",
isEdge && !isPreviewEnd ? "text-[var(--fu-on-accent-mute,#E1E7FF)]" : inBand ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)]",
(inBand || isEdge) && "forced-colors:text-[HighlightText]",
)}
style={{ transitionDelay: `${timing.delay}ms` }}
>
{countLoading ? (
<Skeleton className="mx-auto mt-[3px] h-1.5 w-3.5 rounded-full" />
) : count ? (
// Not a placeholder here: SkeletonText only fades the count in once when it arrives.
<SkeletonText loading={false}>{formatCount(count)}</SkeletonText>
) : (
""
)}
</span>
)}
</span>
</div>
);
})}
</div>
));
};
// The month crossfade: the old grid leaves 8px toward where it went, through a 2px blur, as the new one arrives.
const leavingRef = useRef<HTMLDivElement>(null);
const arrivingRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (!leaving) return;
// The months move the way the arrows point: in RTL the next month comes in from the left.
const shift = 8 * leaving.dir * (isRtl(arrivingRef.current) ? -1 : 1);
const timing = { duration: 220, easing: "cubic-bezier(0.22, 1, 0.36, 1)" };
const out = leavingRef.current?.animate(
[
{ opacity: 1, transform: "translateX(0)", filter: "blur(0)" },
{ opacity: 0, transform: `translateX(${-shift}px)`, filter: "blur(2px)" },
],
{ ...timing, fill: "forwards" },
);
const into = arrivingRef.current?.animate(
[
{ opacity: 0, transform: `translateX(${shift}px)`, filter: "blur(2px)" },
{ opacity: 1, transform: "translateX(0)", filter: "blur(0)" },
],
{ ...timing, delay: 40, 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]);
const monthLabelId = `${id}-month`;
const viewYear = shownMonth ? Number(shownMonth.slice(0, 4)) : null;
const heading = shownMonth ? (mode === "months" ? f.plain(viewYear ?? 0) : f.day(shownMonth, { month: "long", year: "numeric" })) : "";
// The twelve-month view: one cell per month of the shown year, with its count.
const [monthFocus, setMonthFocus] = useState<number | null>(null);
const focusedMonth = monthFocus ?? (shownMonth ? parts(shownMonth)[1] : 0);
const monthCount = (m: number) => {
if (!countOf || viewYear === null || !today) return null;
const first = `${viewYear}-${pad(m + 1)}-01`;
const lastDay = `${viewYear}-${pad(m + 1)}-${pad(daysIn(viewYear, m))}`;
if (!allowFuture && first > today) return null;
return sum({ start: first, end: allowFuture ? lastDay : minIso(lastDay, today) });
};
const openMonth = (m: number) => {
if (viewYear === null) return;
const target = `${viewYear}-${pad(m + 1)}-01`;
if (!allowFuture && today && target > today) return;
setMode("days");
setViewMonth(target);
const day = focused ? Math.min(Number(focused.slice(8, 10)), daysIn(viewYear, m)) : 1;
const next = `${target.slice(0, 8)}${pad(day)}`;
setFocusDay(allowFuture || !today ? next : minIso(next, today));
focusAfterRender.current = "day";
};
const onMonthKeys = (event: KeyboardEvent<HTMLDivElement>) => {
const moves: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -3, ArrowDown: 3 };
const key = readingKey(event.key, event.currentTarget);
if (moves[key] !== undefined) {
event.preventDefault();
const next = focusedMonth + moves[key];
if (next < 0 || next > 11) {
if (shownMonth) setViewMonth(addMonths(shownMonth, next < 0 ? -12 : 12));
setMonthFocus((next + 12) % 12);
} else setMonthFocus(next);
focusAfterRender.current = "month";
} else if (event.key === "Escape") {
event.stopPropagation();
setMode("days");
focusAfterRender.current = "day";
}
};
const fieldsDisabled = !today;
const root = useRef<HTMLDivElement>(null);
const [wide, setWide] = useState(false);
useLayoutEffect(() => {
const node = root.current;
if (!node) return;
const observer = new ResizeObserver(() => setWide(node.offsetWidth >= 500));
observer.observe(node);
return () => observer.disconnect();
}, []);
// On a narrow card the calendar comes first and the presets sit under it; on a wide one the presets are a rail on the
// left. The DOM follows, so the tab order matches what is seen.
const presetsBlock = (
<div
key="presets"
role="radiogroup"
aria-label={label}
onKeyDown={onPresetKeys}
className={cn(
"relative grid grid-cols-2 gap-1 self-start border-t border-[var(--fu-card-border,#2A2A2A)] pt-3",
"@min-[500px]:col-start-1 @min-[500px]:row-start-1 @min-[500px]:grid-cols-1 @min-[500px]:border-t-0 @min-[500px]:pt-0",
)}
>
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute rounded-[9px] bg-[var(--fu-selected,#1F2747)]",
"forced-colors:bg-[Highlight] forced-colors:[forced-color-adjust:none]",
washPlaced && "transition-[opacity] duration-[360ms]",
SMOOTH,
"motion-reduce:transition-none",
(checkedIndex < 0 || !wash) && "opacity-0",
)}
style={wash ?? undefined}
/>
{choices.map((choice, i) => (
<button
key={choice.key}
ref={(node) => {
presetButtons.current[i] = node;
}}
type="button"
role="radio"
aria-checked={choice.on}
tabIndex={i === Math.max(0, checkedIndex) ? 0 : -1}
onClick={() => choose(i, true)}
className={cn(
"group/preset relative flex min-h-9 min-w-0 cursor-pointer items-center gap-1.5 rounded-[9px] px-3 py-2 text-start text-[14px] leading-5 font-medium pointer-coarse:min-h-11 @min-[500px]:justify-between @min-[500px]:gap-3",
"transition-[color,background-color,scale] duration-200 active:scale-[0.98] active:duration-75 motion-reduce:transition-none",
SMOOTH,
FOCUS_RING,
choice.on
? cn("text-[var(--fu-accent-pale,#D1DDFF)]", !wash && "bg-[var(--fu-selected,#1F2747)] forced-colors:bg-[Highlight]")
: "text-[var(--fu-mute,#BDBDBD)] hover:bg-[var(--fu-item-hover,#2A2A2A)] hover:text-[var(--fu-text,#F8F5F1)]",
// Forced colours drop the wash, so the chosen preset sits on the system highlight; left to the browser,
// its words would sit on a backplate in the page colour.
choice.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 long label wraps; the count stays beside its first line. */}
<span className="min-w-0 [overflow-wrap:anywhere]">{choice.label}</span>
{choice.count !== null && (
<>
<span
aria-hidden="true"
className={cn(
"inline-flex h-5 min-w-[22px] shrink-0 items-center justify-center rounded-[6px] px-1.5 text-[12px] leading-4 font-medium tabular-nums transition-[background-color,color] duration-200 motion-reduce:transition-none",
loading
? SKELETON_FILL
: choice.on
? "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)]"
: "bg-[var(--fu-pill,rgb(255_255_255/0.1))] text-[var(--fu-pill-text,#C8C8C8)]",
!loading && choice.on && "forced-colors:bg-transparent forced-colors:text-[HighlightText]",
)}
>
{loading ? (
<span className="invisible">{formatCount(choice.count)}</span>
) : (
<SkeletonText loading={false}>
<TextSwap>{formatCount(choice.count)}</TextSwap>
</SkeletonText>
)}
</span>
<span className="sr-only">, {countLabel(choice.count)}</span>
</>
)}
</button>
))}
</div>
);
const calendarBlock = (
<div
key="calendar"
className="min-w-0 @min-[500px]:col-start-2 @min-[500px]:row-start-1 @min-[500px]:border-s @min-[500px]:border-[var(--fu-card-border,#2A2A2A)] @min-[500px]:ps-6"
>
<div className="flex h-9 items-center justify-between gap-2">
<button
type="button"
id={monthLabelId}
aria-expanded={mode === "months"}
aria-label={heading ? `${heading}, ${mode === "months" ? "back to days" : "choose a month"}` : "Choose a month"}
onClick={() => {
setMonthFocus(null);
setMode(mode === "days" ? "months" : "days");
focusAfterRender.current = mode === "days" ? "month" : "day";
}}
className={cn(
"relative -ms-2 flex h-9 min-w-0 cursor-pointer items-center gap-1 rounded-[10px] px-2 text-[15px] leading-5 font-semibold text-[var(--fu-text,#F8F5F1)]",
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1 pointer-coarse:after:content-['']",
"transition-colors duration-200 hover:bg-[var(--fu-item-hover,#2A2A2A)]",
FOCUS_RING,
)}
>
<TextSwap>{heading || " "}</TextSwap>
<ChevronDownIcon
size={16}
className={cn("shrink-0 text-[var(--fu-mute,#BDBDBD)] transition-[rotate] duration-[480ms] motion-reduce:transition-none", SMOOTH, mode === "months" && "rotate-180")}
/>
</button>
<div className="flex shrink-0 gap-1.5">
{([-1, 1] as const).map((by) => (
<button
key={by}
type="button"
aria-label={mode === "months" ? (by < 0 ? "Previous year" : "Next year") : by < 0 ? "Previous month" : "Next month"}
onClick={() => step(by)}
className={cn(
"grid size-9 cursor-pointer place-items-center rounded-[10px] border border-[var(--fu-line,#404040)] text-[var(--fu-mute,#BDBDBD)]",
"transition-[border-color,background-color,color,scale] duration-200 hover:border-[var(--fu-control-border,#737373)] hover:bg-[var(--fu-item-hover,#2A2A2A)] hover:text-[var(--fu-text,#F8F5F1)]",
"active:scale-[0.94] active:duration-75 motion-reduce:transition-none",
"pointer-coarse:relative pointer-coarse:after:absolute pointer-coarse:after:-inset-1 pointer-coarse:after:content-['']",
FOCUS_RING,
)}
>
<ChevronDownIcon size={18} className={by < 0 ? "rotate-90 rtl:-rotate-90" : "-rotate-90 rtl:rotate-90"} />
</button>
))}
</div>
</div>
<div className="relative mt-2">
<div
inert={mode !== "days"}
className={cn(
"transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none",
mode === "days" ? "opacity-100" : "pointer-events-none -translate-y-1 opacity-0 blur-[2px]",
)}
>
<div aria-hidden="true" className="grid h-8 grid-cols-7 items-center text-center text-[12px] leading-4 text-[var(--fu-dim,#929292)]">
{weekdays.map((i) => (
<abbr key={i} title={f.weekday(i)} className="no-underline">
{weekdayHead(f, i)}
</abbr>
))}
</div>
{/* The grid's height follows the month's weeks, so a four-week February does not leave a gap. */}
<div
className={cn(
"relative h-[calc(var(--weeks)*40px)] overflow-hidden pointer-coarse:h-[calc(var(--weeks)*44px)]",
"transition-[height] duration-[220ms] motion-reduce:transition-none",
SMOOTH,
)}
style={{ "--weeks": shownMonth ? weeksOf(shownMonth).length : 5 } as CSSProperties}
>
<div
ref={(node) => {
grid.current = node;
arrivingRef.current = node;
}}
role="grid"
aria-labelledby={monthLabelId}
aria-multiselectable="true"
aria-disabled={disabled || undefined}
onKeyDown={onGridKeys}
onPointerLeave={() => pending && setPreview(null)}
className={cn("transition-opacity duration-[480ms] motion-reduce:transition-none", SMOOTH, !shownMonth && "opacity-0")}
>
{shownMonth && renderGrid(shownMonth, true)}
</div>
{leaving && (
<div ref={leavingRef} key={leaving.key} inert aria-hidden="true" className="pointer-events-none absolute inset-0">
{renderGrid(leaving.month, false)}
</div>
)}
</div>
</div>
<div
ref={months}
role="group"
aria-label={viewYear !== null ? `Months of ${f.plain(viewYear)}` : "Months"}
inert={mode !== "months"}
onKeyDown={onMonthKeys}
className={cn(
"absolute inset-0 grid grid-cols-3 grid-rows-4 gap-1 py-2",
"transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none",
mode === "months" ? "opacity-100" : "pointer-events-none translate-y-1 opacity-0 blur-[2px]",
)}
>
{Array.from({ length: 12 }, (_, m) => monthShort(f, m)).map((name, m) => {
const first = viewYear !== null ? `${viewYear}-${pad(m + 1)}-01` : "";
const lastDay = viewYear !== null ? `${viewYear}-${pad(m + 1)}-${pad(daysIn(viewYear, m))}` : "";
const can = !!first && (allowFuture || !today || first <= today);
const covered = !!range && !!first && range.start <= lastDay && range.end >= first;
const isShown = shownMonth === first;
const holdsToday = !!today && today.slice(0, 7) === first.slice(0, 7);
const count = mode === "months" && !loading ? monthCount(m) : null;
return (
<button
key={name}
type="button"
tabIndex={m === focusedMonth ? 0 : -1}
aria-current={isShown || undefined}
aria-disabled={!can || undefined}
/* Named as shown: short month, then its count. The group around it names the year. */
aria-label={`${name}${count !== null ? `, ${countLabel(count)}` : ""}`}
onClick={() => openMonth(m)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
openMonth(m);
}
}}
className={cn(
"flex flex-col items-center justify-center rounded-[10px] text-[14px] leading-4 font-medium",
"transition-[background-color,color,box-shadow,scale] duration-200 motion-reduce:transition-none",
SMOOTH,
FOCUS_RING,
can ? "cursor-pointer active:scale-[0.97] active:duration-75" : "cursor-default text-[var(--fu-line,#404040)]",
can && (covered ? "bg-[var(--fu-selected,#1F2747)] text-[var(--fu-accent-pale,#D1DDFF)]" : "text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-item-hover,#2A2A2A)]"),
holdsToday && "shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)]",
)}
>
{name}{" "}
{countOf && (
<span className={cn("mt-1 h-3 text-[10px] leading-3 font-normal tabular-nums", covered ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)]")}>
{count ? formatCount(count) : ""}
</span>
)}
</button>
);
})}
</div>
</div>
<div className="mt-3 grid grid-cols-2 gap-2">
<DateField
label={`${label}: from`}
placeholder="From"
shown={range ? shortDay(f, range.start, today) : ""}
disabled={fieldsDisabled}
read={(text) => (today ? parseDate(text, today, locale) : null)}
onCommit={(day) => {
if (!today) return;
setPending(null);
setPreview(null);
if (day === null) return commit(null);
const start = allowFuture ? day : minIso(day, today);
const end = range ? maxIso(range.end, start) : allowFuture ? start : today;
nextToward.current = "end";
showMonth(firstOfMonth(start));
setFocusDay(start);
commit({ start, end });
}}
/>
<DateField
label={`${label}: to`}
placeholder="To"
shown={range ? shortDay(f, range.end, today) : ""}
disabled={fieldsDisabled}
read={(text) => (today ? parseDate(text, today, locale) : null)}
onCommit={(day) => {
if (!today) return;
setPending(null);
setPreview(null);
if (day === null) return commit(null);
const end = allowFuture ? day : minIso(day, today);
const start = range ? minIso(range.start, end) : end;
nextToward.current = "start";
showMonth(firstOfMonth(end));
setFocusDay(end);
commit({ start, end });
}}
/>
</div>
</div>
);
return (
<div ref={root} className={cn("@container", className)} {...props}>
<StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled}>
<div className="grid gap-4 @min-[500px]:grid-cols-[168px_minmax(0,1fr)] @min-[500px]:gap-6">
{wide ? [presetsBlock, calendarBlock] : [calendarBlock, presetsBlock]}
</div>
</StatusFrame>
<p aria-live="polite" className="sr-only">
{said}
</p>
</div>
);
}
type DateFieldProps = {
label: string;
placeholder: string;
shown: string;
disabled: boolean;
read: (text: string) => string | null;
onCommit: (day: string | null) => void;
};
// Shows the day; while focused it holds what is typed, and commits on Enter or leaving. Text it cannot read puts the day back.
function DateField({ label, placeholder, shown, disabled, read, onCommit }: DateFieldProps) {
const [draft, setDraft] = useState<string | null>(null);
const commit = () => {
if (draft === null) return;
setDraft(null);
if (!draft.trim()) return onCommit(null);
const day = read(draft);
if (day !== null) onCommit(day);
};
return (
<TextField
label={label}
placeholder={placeholder}
autoComplete="off"
enterKeyHint="done"
spellCheck={false}
value={draft ?? shown}
readOnly={disabled}
onChange={setDraft}
onClear={() => {
setDraft(null);
onCommit(null);
}}
clearLabel={`Clear ${label.replace(/:.*/, "").toLowerCase()} dates`}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
commit();
} else if (event.key === "Escape" && draft !== null) {
event.stopPropagation();
setDraft(null);
}
}}
className="pe-2"
inputClassName="tabular-nums"
/>
);
}
```
### 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/ui/icons.tsx
```tsx
import type { ReactNode, SVGProps } from "react";
/*
* Icon paths from Lucide (https://lucide.dev), ISC License.
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT).
* All other copyright (c) for Lucide are held by Lucide Contributors 2022.
* Permission to use, copy, modify, and/or distribute this software for any purpose with or
* without fee is hereby granted, provided that the above copyright notice and this permission
* notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number };
function Icon({ size = 20, strokeWidth = 2, children, ...props }: IconProps & { children: ReactNode }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...props}
>
{children}
</svg>
);
}
export function ChevronDownIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m6 9 6 6 6-6" />
</Icon>
);
}
export function XIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</Icon>
);
}
export function CheckIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M20 6 9 17l-5-5" />
</Icon>
);
}
export function SearchIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function ArrowUpRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M7 7h10v10" />
<path d="M7 17 17 7" />
</Icon>
);
}
export function PlusIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="M12 5v14" />
</Icon>
);
}
export function CopyIcon(props: IconProps) {
return (
<Icon {...props}>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</Icon>
);
}
export function SlidersIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 4h-7" />
<path d="M10 4H3" />
<path d="M21 12h-9" />
<path d="M8 12H3" />
<path d="M21 20h-5" />
<path d="M12 20H3" />
<path d="M14 2v4" />
<path d="M8 10v4" />
<path d="M16 18v4" />
</Icon>
);
}
export function ArrowRightIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</Icon>
);
}
export function SearchXIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="m13.5 8.5-5 5" />
<path d="m8.5 8.5 5 5" />
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Icon>
);
}
export function StarIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
</Icon>
);
}
export function HistoryIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M12 7v5l4 2" />
</Icon>
);
}
export function ListTreeIcon(props: IconProps) {
return (
<Icon {...props}>
<path d="M21 12h-8" />
<path d="M21 6H8" />
<path d="M21 18h-8" />
<path d="M3 6v4c0 1.1.9 2 2 2h3" />
<path d="M3 10v6c0 1.1.9 2 2 2h3" />
</Icon>
);
}
export function CircleAlertIcon(props: IconProps) {
return (
<Icon {...props}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</Icon>
);
}
```
### components/filters-ui/ui/skeleton.tsx
```tsx
"use client";
import { createContext, useContext, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
/** What StatusFrame tells the pieces under it: draw placeholders, or the data has just arrived and fades in once. */
export type LoadingState = { loading: boolean; arriving: boolean };
export const LoadingContext = createContext<LoadingState>({ loading: false, arriving: false });
/** The loading state of the nearest StatusFrame. Outside one, nothing is loading. */
export const useLoading = () => useContext(LoadingContext);
/**
* The placeholder fill: --fu-skeleton, pulsing to half of it every 2s (Tailwind's animate-pulse). It holds still when
* reduced motion is asked for, and turns to the system's grey text colour in forced colours, so it never vanishes.
*/
export const SKELETON_FILL =
"animate-pulse bg-[var(--fu-skeleton,rgb(255_255_255/0.12))] in-data-[state=on]:bg-[var(--fu-skeleton-on,rgb(143_170_255/0.3))] motion-reduce:animate-none forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]";
/** Content that has just replaced a placeholder: it fades in once over 300ms as it is inserted, and never again. */
export const ARRIVING = "transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none";
export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;
/**
* A pulsing placeholder block with no size of its own: give it the size and corners of what it stands for, from the
* same classes, e.g. "h-5 min-w-[22px] rounded-[6px]" for a count pill. Hidden from screen readers; the StatusFrame
* around it says "Loading" once.
*/
export function Skeleton({ className, ...props }: SkeletonProps) {
return <span aria-hidden="true" data-skeleton="" className={cn("block rounded-[6px]", SKELETON_FILL, className)} {...props} />;
}
export type SkeletonTextProps = {
children: ReactNode;
/** Draws the placeholder. Default: the nearest StatusFrame's loading state. */
loading?: boolean;
/** Classes for the placeholder's box while loading. */
className?: string;
};
/**
* Words that draw as a rounded bar while loading. The words stay in the layout, unseen, so the bar is exactly as wide
* and as many lines tall as they are, and nothing moves when they arrive; then they fade in once.
*/
export function SkeletonText({ children, loading, className }: SkeletonTextProps) {
const state = useLoading();
if (loading ?? state.loading) {
return (
<span key="skeleton" className={cn("relative inline-block max-w-full align-top", className)}>
<span className="invisible">{children}</span>
<Skeleton className="absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]" />
</span>
);
}
if (state.arriving) {
return (
<span key="arrived" className={ARRIVING}>
{children}
</span>
);
}
return <>{children}</>;
}
/**
* Stand-in names for a list whose options have not come yet: a mix of lengths, so the placeholders do not read as a
* grid. Never shown; only their widths are.
*/
export function placeholderLabels(count: number): string[] {
const words = ["Placeholder", "Short", "A longer name", "Medium one", "Tiny", "Another name", "Middle", "Fairly long one"];
return Array.from({ length: count }, (_, i) => words[i % words.length]);
}
```
### components/filters-ui/ui/status-frame.tsx
```tsx
"use client";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";
/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";
/**
* The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
* filter knows them all. Spread them into an item's own props type.
*/
export type StateProps = {
/** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
status?: Status;
/** Called by the Retry button. Without it the error line has no button. */
onRetry?: () => void;
/** The error line. Default "Couldn't load the options." */
errorText?: string;
/** The line shown in place of the options when there are none. Default "No options to show" */
emptyText?: string;
/** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
disabled?: boolean;
};
export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";
/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;
type Mode = "ready" | "loading" | "error" | "empty";
/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);
export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
Omit<StateProps, "emptyText"> & {
/** There are no options: emptyText shows in place of the content. */
empty?: boolean;
emptyText?: ReactNode;
/** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
emptyArt?: string | ReactNode | null;
/** Words read once while loading. Default "Loading". */
loadingText?: string;
/** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
announce?: boolean;
retryLabel?: string;
children: ReactNode;
};
/**
* Wraps an item's content and gives it the shared states.
* - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
* placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
* - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
* status region that stays on the page.
* - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
* - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
* read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
* When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
* A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
* it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
* with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
* frame and let an inner frame around the part that fails speak.
*/
export function StatusFrame({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
empty = false,
emptyText = DEFAULT_EMPTY_TEXT,
emptyArt,
disabled = false,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
children,
...props
}: StatusFrameProps) {
const frame = useRef<HTMLDivElement>(null);
const outer = useLoading();
const saidAbove = useContext(SaidLoading);
const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";
// The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
const [lastStatus, setLastStatus] = useState(status);
const [arriving, setArriving] = useState(false);
if (status !== lastStatus) {
setLastStatus(status);
setArriving(lastStatus === "loading" && status === "ready");
}
useEffect(() => {
if (!arriving) return;
const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
return () => clearTimeout(timer);
}, [arriving]);
// Whether focus sat on a control inside, read just before a change of state is drawn.
const key = `${mode}|${disabled}`;
const drawnKey = useRef(key);
const focusWasInside = useRef(false);
if (key !== drawnKey.current && typeof document !== "undefined") {
const active = document.activeElement;
focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
}
useLayoutEffect(() => {
if (drawnKey.current === key) return;
drawnKey.current = key;
if (!focusWasInside.current) return;
focusWasInside.current = false;
const node = frame.current;
// The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
});
return (
<div
ref={frame}
tabIndex={-1}
data-status-frame=""
data-status={mode}
aria-busy={mode === "loading" || undefined}
className={cn(
"min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
disabled && "pointer-events-none opacity-50 select-none",
className,
)}
{...props}
>
<SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
<LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
{mode === "empty" ? (
emptyArt === null ? (
<EmptyNote>{emptyText}</EmptyNote>
) : (
<EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
)
) : mode === "error" ? null : (
// display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
<fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
{children}
</fieldset>
)}
</LoadingContext.Provider>
</SaidLoading.Provider>
<StatusLine
status={mode === "loading" || mode === "error" ? mode : "ready"}
onRetry={onRetry}
errorText={errorText}
loadingText={saidAbove ? "" : loadingText}
announce={announce}
retryLabel={retryLabel}
/>
</div>
);
}
export type StatusLineProps = {
status?: Status;
/** Called by Retry. Without it the error line has no button. */
onRetry?: () => void;
errorText?: string;
loadingText?: string;
/** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
announce?: boolean;
retryLabel?: string;
/** Classes for the line while it shows an error, e.g. its margins. */
className?: string;
};
/**
* What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
* Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
* no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
* Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
*/
export function StatusLine({
status = "ready",
onRetry,
errorText = DEFAULT_ERROR_TEXT,
loadingText = DEFAULT_LOADING_TEXT,
announce = true,
retryLabel,
className,
}: StatusLineProps) {
const error = status === "error";
const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
return (
// The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
<div className={error ? cn(ERROR_LINE, className) : "contents"}>
<p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
{error && <ErrorGlyph />}
{said && <span dir="auto">{said}</span>}
</p>
{error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
/**
* For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
* away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
* never dropped to the page.
*/
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
const drawn = useRef(key);
const had = useRef(false);
if (key !== drawn.current && typeof document !== "undefined") {
const active = document.activeElement;
had.current = !!scope.current && !!active && scope.current.contains(active);
}
useLayoutEffect(() => {
if (drawn.current === key) return;
drawn.current = key;
if (!had.current) return;
had.current = false;
const node = scope.current;
if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
});
}
```
### components/filters-ui/ui/art-search.ts
```ts
/**
* The picture for "nothing matches" and "nothing here": a glass magnifier on a clear background, drawn 56px.
* It is a file, not code: the shadcn install saves it as public/filters-ui/search.svg. Copying by hand, save
* https://filtersui.com/filters-ui/search.svg there, or point this at a picture of your own. With no file the empty
* states show their words alone.
*/
export const SEARCH_ART = "/filters-ui/search.svg";
```
### components/filters-ui/ui/empty-note.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyNoteProps = HTMLAttributes<HTMLDivElement> & {
/** A 16px glyph in currentColor before the words. */
icon?: ReactNode;
/** A button or link after the words, e.g. "Clear search". */
action?: ReactNode;
};
/**
* A quiet one-line note in place of a list that has nothing in it: dim 14px words, an optional glyph and an optional
* action. No illustration and no box, so it sits in the space the options would take.
*/
export function EmptyNote({ icon, action, className, children, ...props }: EmptyNoteProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2", className)} {...props}>
<p className="flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
{icon && (
<span aria-hidden="true" className="mt-0.5 shrink-0 [&_svg]:size-4">
{icon}
</span>
)}
<span dir="auto">{children}</span>
</p>
{action}
</div>
);
}
```
### components/filters-ui/ui/empty-state.tsx
```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";
export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
/** The picture above the words: an image address, drawn 56px square, or any node of that size. */
art?: string | ReactNode;
/** The one line that says what is missing. */
title: ReactNode;
/** A link or button under the words, such as "Clear search". */
action?: ReactNode;
/** A second, quieter line under the title. */
children?: ReactNode;
};
// Each part arrives once, a beat after the one above it: the picture comes into focus, the words rise into place.
const ENTER =
"transition-[opacity,filter,translate,scale] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none starting:opacity-0";
/**
* What a list shows in the room its options would take when it has none: a picture, one line and an action, stacked
* in the middle. For a single quiet line with no picture, use EmptyNote.
*/
export function EmptyState({ art, title, action, className, children, ...props }: EmptyStateProps) {
return (
<div className={cn("flex min-w-0 max-w-full flex-col items-center text-center", className)} {...props}>
{art && (
<span aria-hidden="true" className={cn("mb-3 block size-14 shrink-0", ENTER, "starting:scale-[0.82] starting:blur-[6px]")}>
{typeof art === "string" ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={art} alt="" width={56} height={56} loading="lazy" decoding="async" draggable={false} className="size-full object-contain select-none" />
) : (
art
)}
</span>
)}
<p dir="auto" className={cn("max-w-full text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]", ENTER, "delay-[60ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{title}
</p>
{children && (
<p dir="auto" className={cn("mt-1 max-w-full text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]", ENTER, "delay-[90ms] starting:translate-y-1.5 starting:blur-[2px]")}>
{children}
</p>
)}
{action && <div className={cn("mt-2 max-w-full", ENTER, "delay-[120ms] starting:translate-y-1.5")}>{action}</div>}
</div>
);
}
```
### components/filters-ui/ui/inline-error.tsx
```tsx
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { buttonClasses } from "./button-classes";
import { CircleAlertIcon } from "./icons";
export const DEFAULT_RETRY_LABEL = "Retry";
/** The error line's layout: the words at the start, Retry at the end, wrapping under them when space runs out. */
export const ERROR_LINE = "flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2";
/** The words: 14px, muted, with a 16px dim alert glyph before them. */
export const ERROR_TEXT = "flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]";
/** The alert glyph that leads the words. Hidden from screen readers. */
export function ErrorGlyph() {
return <CircleAlertIcon size={16} className="mt-0.5 shrink-0 text-[var(--fu-dim,#929292)]" />;
}
export type RetryButtonProps = {
onRetry: () => void;
label?: string;
className?: string;
};
/**
* A small grey button that is never shown disabled. Before it calls onRetry it hands focus to the StatusFrame around
* it, which stays on the page while the content reloads, so focus is never lost with the button.
*/
export function RetryButton({ onRetry, label = DEFAULT_RETRY_LABEL, className }: RetryButtonProps) {
return (
<button
type="button"
onClick={(event) => {
event.currentTarget.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
onRetry();
}}
className={buttonClasses({ variant: "secondary", size: "sm", className })}
>
{label}
</button>
);
}
export type InlineErrorProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
/** One short line in plain words, e.g. "Couldn't load the options." */
text: string;
/** Shows Retry. Without it the line stands alone. */
onRetry?: () => void;
retryLabel?: string;
};
/**
* A calm error in the component's own area: one muted line and a Retry button. The line is a polite status region, so
* it is read out when it appears. Inside a StatusFrame use the frame's status="error" instead: it keeps one region on
* the page for loading and errors alike.
*/
export function InlineError({ text, onRetry, retryLabel, className, ...props }: InlineErrorProps) {
return (
<div className={cn(ERROR_LINE, className)} {...props}>
<p role="status" className={ERROR_TEXT}>
<ErrorGlyph />
<span dir="auto">{text}</span>
</p>
{onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
</div>
);
}
```
### components/filters-ui/ui/button-classes.ts
```ts
import { cn } from "../lib/cn";
// The button looks as class names. Kept apart from button.tsx, a client module, so server pages can call them too.
export type ButtonVariant = "primary" | "secondary" | "ghost" | "quiet" | "quiet-accent";
export type ButtonSize = "sm" | "md" | "lg";
export const BUTTON_BASE = cn(
"relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] font-[inherit] font-medium whitespace-nowrap no-underline select-none",
"[-webkit-tap-highlight-color:transparent] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
"active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100",
"outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
"aria-busy:cursor-progress aria-busy:active:scale-100",
);
const VARIANTS: Record<ButtonVariant, string> = {
primary:
"bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)] hover:bg-[var(--fu-accent-hover,#3450D4)] forced-colors:border forced-colors:border-[ButtonText]",
secondary:
"bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]",
ghost: "bg-transparent text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
quiet: "bg-transparent text-[var(--fu-mute,#BDBDBD)] hover:text-[var(--fu-text,#F8F5F1)]",
"quiet-accent":
"bg-transparent text-[var(--fu-accent-soft,#8FAAFF)] decoration-1 underline-offset-[5px] hover:text-[var(--fu-accent-pale,#D1DDFF)] [@media(hover:hover)]:hover:underline",
};
// Below 44px a touch screen gets a taller invisible target through ::after.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:content-['']";
const SIZES: Record<ButtonSize, { box: string; before: string; after: string }> = {
sm: { box: cn("h-8 gap-1.5 px-3 text-[13px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-1.5"), before: "ps-2.5", after: "pe-2.5" },
md: { box: cn("h-10 gap-2 px-3.5 text-[15px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-0.5"), before: "ps-3", after: "pe-3" },
lg: { box: "h-11 gap-2 px-4 text-[15px] leading-5 [&_svg]:size-[18px]", before: "ps-3.5", after: "pe-3.5" },
};
/** The classes of a button, for a link or a router link that should look like one. */
export function buttonClasses({
variant = "primary",
size = "md",
before = false,
after = false,
className,
}: { variant?: ButtonVariant; size?: ButtonSize; before?: boolean; after?: boolean; className?: string } = {}) {
return cn(BUTTON_BASE, VARIANTS[variant], SIZES[size].box, before && SIZES[size].before, after && SIZES[size].after, className);
}
```
### components/filters-ui/ui/text-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/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/text-swap.tsx
```tsx
"use client";
import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
export type TextSwapProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
/** The text to show. A change animates: the old text leaves upward, the new one rises in. */
children: string;
};
const EASE = "cubic-bezier(0.42, 0, 0.58, 1)";
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
/** Old text leaves over 150ms; new text enters over 170ms after 110ms; both move 4px through a 2px blur. */
export function TextSwap({ children, className, ...props }: TextSwapProps) {
const [shown, setShown] = useState(children);
const [leaving, setLeaving] = useState<{ text: string; key: number } | null>(null);
const nowRef = useRef<HTMLSpanElement>(null);
const oldRef = useRef<HTMLSpanElement>(null);
if (children !== shown) {
setLeaving(reducedMotion() ? null : { text: shown, key: (leaving?.key ?? 0) + 1 });
setShown(children);
}
useLayoutEffect(() => {
if (!leaving) return;
const out = oldRef.current?.animate(
[
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
{ opacity: 0, transform: "translateY(-4px)", filter: "blur(2px)" },
],
{ duration: 150, easing: EASE, fill: "forwards" },
);
const into = nowRef.current?.animate(
[
{ opacity: 0, transform: "translateY(4px)", filter: "blur(2px)" },
{ opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
],
{ duration: 170, delay: 110, easing: EASE, fill: "backwards" },
);
const key = leaving.key;
const done = () => setLeaving((current) => (current?.key === key ? null : current));
if (into) into.onfinish = done;
else done();
return () => {
out?.cancel();
into?.cancel();
};
}, [leaving]);
return (
<span className={cn("inline-grid whitespace-nowrap", className)} {...props}>
<span ref={nowRef} className="[grid-area:1/1]">
{shown}
</span>
{leaving && (
<span ref={oldRef} key={leaving.key} aria-hidden="true" className="pointer-events-none [grid-area:1/1]">
{leaving.text}
</span>
)}
</span>
);
}
```
### components/filters-ui/ui/filter-card.tsx
```tsx
"use client";
import { useId, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { ChevronDownIcon } from "./icons";
export type FilterCardProps = Omit<HTMLAttributes<HTMLElement>, "title" | "children"> & {
title: string;
/** The value in words ("Under $45k"). Shown on the closed card; null or empty means the filter is unset. */
summary?: string | null;
/** Clears this one filter. When given, a Clear button takes the summary's place while open or hovered. */
onClear?: () => void;
/** Controlled open state. Leave undefined to let the card manage it. */
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Looks like a closed card but cannot be opened or focused, e.g. a filter whose body is not ready. */
disabled?: boolean;
/** Accessible name of the Clear button. Default "Clear {title}". */
clearLabel?: string;
/** Heading level wrapping the head button. Default 3. */
headingLevel?: 2 | 3 | 4 | 5 | 6;
bodyClassName?: string;
children?: ReactNode;
};
const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
// The summary and Clear share one slot and trade places over 150ms through a 2px blur and 4px shift.
const SUMMARY_HIDDEN = "opacity-0 blur-[2px] -translate-y-1";
const SUMMARY_HIDES_WHEN = [
"group-data-[state=open]/card:opacity-0 group-data-[state=open]/card:blur-[2px] group-data-[state=open]/card:-translate-y-1",
"group-hover/slot:opacity-0 group-hover/slot:blur-[2px] group-hover/slot:-translate-y-1",
"group-focus-within/slot:opacity-0 group-focus-within/slot:blur-[2px] group-focus-within/slot:-translate-y-1",
].join(" ");
// Hovering anywhere on a closed card offers Clear in the summary's place.
const SUMMARY_HIDES_ON_CARD_HOVER = "group-hover/card:opacity-0 group-hover/card:blur-[2px] group-hover/card:-translate-y-1";
const CLEAR_SHOWS_ON_CARD_HOVER = "group-hover/card:opacity-100 group-hover/card:blur-none group-hover/card:translate-y-0";
// A hidden Clear takes no taps: only a pointer that can hover reveals it before a click.
const CLEAR_HIDDEN = "pointer-events-none opacity-0 blur-[2px] translate-y-1 [@media(hover:hover)]:pointer-events-auto";
const CLEAR_SHOWS_WHEN = [
"group-data-[state=open]/card:pointer-events-auto group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none group-data-[state=open]/card:translate-y-0",
"group-hover/slot:opacity-100 group-hover/slot:blur-none group-hover/slot:translate-y-0",
"group-focus-within/slot:opacity-100 group-focus-within/slot:blur-none group-focus-within/slot:translate-y-0",
].join(" ");
const FOCUS_RING =
"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
/**
* One filter in a rounded card: a 52px head (title, value summary or Clear, chevron) that opens a body.
* Opening animates the height over 480ms and reveals the content from a 6px blur, 6px lower.
*/
export function FilterCard({
title,
summary,
onClear,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
clearLabel,
headingLevel = 3,
className,
bodyClassName,
children,
...props
}: FilterCardProps) {
const id = useId();
const headId = `${id}-head`;
const bodyId = `${id}-body`;
const head = useRef<HTMLButtonElement>(null);
const [innerOpen, setInnerOpen] = useState(defaultOpen);
const open = !disabled && (openProp ?? innerOpen);
const set = Boolean(summary);
// The last summary stays in place while it fades out after a clear.
const [lastSummary, setLastSummary] = useState(summary ?? "");
if (summary && summary !== lastSummary) setLastSummary(summary);
const setOpen = (next: boolean) => {
if (openProp === undefined) setInnerOpen(next);
onOpenChange?.(next);
};
const Heading = `h${headingLevel}` as const;
const swap = cn(
"transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none",
"group-data-[state=open]/card:duration-[480ms] group-data-[state=open]/card:ease-[cubic-bezier(0.22,1,0.36,1)]",
);
return (
<section
data-state={open ? "open" : "closed"}
data-set={set ? "true" : "false"}
className={cn(
"not-prose group/card relative overflow-hidden rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-text,#F8F5F1)]",
"transition-[background-color,border-color,opacity] duration-200 motion-reduce:transition-none",
"[@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:border-[var(--fu-line,#404040)] [@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:bg-[var(--fu-card-hover,#262626)]",
// The head button sits flush in a clipped card, so its focus ring is drawn around the card.
"has-[[data-filter-card-head]:focus-visible]:outline-2 has-[[data-filter-card-head]:focus-visible]:outline-offset-2 has-[[data-filter-card-head]:focus-visible]:outline-solid has-[[data-filter-card-head]:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
className,
)}
{...props}
>
<Heading className="m-0 -mb-0.5 text-[15px] font-semibold leading-5 text-[var(--fu-text,#F8F5F1)]">
<button
ref={head}
type="button"
id={headId}
data-filter-card-head=""
aria-expanded={open}
aria-controls={bodyId}
disabled={disabled}
onClick={() => setOpen(!open)}
className={cn(
"flex h-[52px] w-full cursor-pointer items-center gap-3 rounded-[23px] px-4 text-start font-[inherit] text-inherit disabled:cursor-default",
"outline-none",
)}
>
<span className="min-w-0 truncate">{title}</span>
{set && <span className="sr-only">, {summary}</span>}
{set && (
<span aria-hidden="true" className="invisible min-w-0 max-w-[calc((100%+32px)*0.55)] shrink-0 truncate text-[14px] font-normal">
{summary}
</span>
)}
<ChevronDownIcon
size={20}
className={cn(
"ms-auto shrink-0 text-[var(--fu-mute,#BDBDBD)] group-has-[[data-filter-card-head]:disabled]/card:opacity-40 transition-[rotate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:rotate-180",
)}
/>
</button>
</Heading>
{onClear && (
<div
inert={!set}
data-filter-card-slot=""
className="group/slot pointer-events-none absolute inset-e-[46px] top-4 grid h-5 max-w-[55%] justify-items-end text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]"
>
<span aria-hidden="true" className={cn("pointer-events-none max-w-full truncate font-normal [grid-area:1/1]", swap, set ? SUMMARY_HIDES_WHEN : SUMMARY_HIDDEN, set && !disabled && SUMMARY_HIDES_ON_CARD_HOVER)}>
{summary || lastSummary}
</span>
<button
type="button"
tabIndex={set ? 0 : -1}
aria-label={clearLabel ?? `Clear ${title.toLowerCase()}`}
onClick={() => {
onClear();
head.current?.focus();
}}
className={cn(
"relative -my-0.5 cursor-pointer rounded-[6px] py-0.5 font-medium [grid-area:1/1] before:absolute before:inset-x-0 before:-inset-y-2 before:content-['']",
FOCUS_RING,
"focus-visible:outline-offset-2",
swap,
CLEAR_HIDDEN,
set && CLEAR_SHOWS_WHEN,
set && !disabled && CLEAR_SHOWS_ON_CARD_HOVER,
)}
>
Clear
</button>
</div>
)}
{!onClear && set && (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-e-[46px] top-4 max-w-[55%] truncate text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]",
swap,
"group-data-[state=open]/card:opacity-0",
)}
>
{summary}
</span>
)}
<div
id={bodyId}
role="region"
aria-labelledby={headId}
inert={!open}
className={cn(
"grid grid-rows-[0fr] transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:grid-rows-[1fr]",
)}
>
<div className="min-h-0 overflow-hidden">
<div
className={cn(
// pt-0.5 makes up the head's -2px margin, so content starts right under the 52px head.
"px-4 pt-0.5 pb-4",
"translate-y-1.5 opacity-0 blur-[6px] transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
SMOOTH,
"group-data-[state=open]/card:translate-y-0 group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none",
"group-data-[state=open]/card:delay-[120ms] group-data-[state=open]/card:duration-[460ms] group-data-[state=open]/card:ease-[cubic-bezier(0.16,1,0.3,1)]",
bodyClassName,
)}
>
{children}
</div>
</div>
</div>
</section>
);
}
```
## What it does
- Presets pick the last 1, 3, 7 or 30 days in one press; the chosen one is tinted and each shows its count.
- On the calendar, the first pick starts a range and the band follows the pointer day by day until the second pick ends it.
- Each day shows how many items it holds; days after today are dimmed and cannot be picked.
- The month name opens a twelve-month view; typed dates read "Nov 3", "11/3" or "2026-11-03".
- Exports formatDateRange for the card's summary and resolveDateRange to turn a value into two dates.
## Props and value
DateRange (components/filters-ui/filters/date-range.tsx) holds this value: { last: number } | { start: string; end: string } | null: the last N days with today (it moves on as days pass), two fixed days as "YYYY-MM-DD", both included, or null for any time.
- value: DateRangeValue (required). The range: { last: 7 }, { start: "2026-11-03", end: "2026-11-09" } or null.
- onChange: (value: DateRangeValue) => void (required). Called with the new range. A first pick on the calendar sends a one-day range; the second pick widens it.
- today: string (default the visitor's date). Today as "YYYY-MM-DD". Left out, it is read in the browser after the first render, so server and browser always agree.
- presets: readonly { label: string; last: number }[] (default Today, Last 3, 7 and 30 days). The quick picks between Any time and Custom.
- countOf: (date: string) => number (optional). Items on one day. Shown as a small number under each date and summed beside each preset. Leave out for a plain calendar.
- total: number (optional). Every item, whatever its date: the count beside Any time.
- label: string (default "Dates"). Accessible name of the presets and the start of the fields' names, e.g. "Listed".
- anyLabel / customLabel: string / string (default "Any time" / "Custom"). The first and last preset.
- allowFuture: boolean (default false). Lets days after today be picked. Off, they show dimmed.
- weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6 (default the locale's). The first day of the week: 0 is Sunday, 1 Monday, 6 Saturday. Default: Sunday in en-US, Monday in de-DE, Saturday in ar-EG.
- formatCount / countLabel: (n: number) => string (default 1,234 / "6 results"). Text of each count, and its words for screen readers, e.g. "6 cars".
- locale: string (default "en-US"). Month and weekday names, the first day of the week, the order of typed dates ("3.11." in de-DE) and the numbers. The presets' words stay as given.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the counts."). The error line, in plain words.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.
It sits inside FilterCard (components/filters-ui/ui/filter-card.tsx), the card with the title, the value in words and a Clear button:
- title: string (required). The card's heading, e.g. "Price".
- summary: string | null (optional). The value in words, shown on the closed card. Null or empty means the filter is unset.
- onClear: () => void (optional). Clears this filter. When given, a Clear button takes the summary's place while open or hovered.
- open / defaultOpen / onOpenChange: boolean / boolean / (open: boolean) => void (default closed). Controlled or uncontrolled open state.
- headingLevel: 2 | 3 | 4 | 5 | 6 (default 3). Heading level around the head button.
- bodyClassName: string (optional). Classes for the body, e.g. to tune the space under the content.
## States
Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.
- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. Day numbers stay; each day's count, each preset's count and the typed fields draw as placeholders. It is aria-busy and says "Loading" once; when status turns back to "ready" the data fades in once. No spinner.
- Error (status="error", with onRetry and errorText): one calm line and a Retry button that calls onRetry, in the filter's own place. The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Zero results (every count is 0): countOf gives 0 for every day: the days show no count and dim, and every preset counts 0.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. The presets, the month buttons and the fields are disabled, and the calendar's days leave the tab order.
- Long labels (data, not a prop): A long preset label wraps; its count stays beside it.
While it is disabled, leave FilterCard's onClear out, so the card offers no Clear.
## Usage
A working example with a few made-up cars. Imports assume @/ points at the project root; change @/components/filters-ui if this project uses another alias.
```tsx
"use client";
import { useState } from "react";
import { addDays, DateRange, formatDateRange, useToday, type DateRangeValue } from "@/components/filters-ui/filters/date-range";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";
// Days since each car was listed, so the demo always has recent listings. Real data would carry the date itself.
const CARS = [
{ name: "Toyota RAV4", daysAgo: 0 },
{ name: "Honda Civic", daysAgo: 0 },
{ name: "Mazda CX-5", daysAgo: 1 },
{ name: "Kia Telluride", daysAgo: 2 },
{ name: "Ford F-150", daysAgo: 4 },
{ name: "Tesla Model 3", daysAgo: 6 },
{ name: "Subaru Outback", daysAgo: 9 },
{ name: "Hyundai Tucson", daysAgo: 12 },
{ name: "BMW X3", daysAgo: 15 },
{ name: "Toyota Corolla", daysAgo: 19 },
{ name: "Jeep Wrangler", daysAgo: 24 },
{ name: "Honda CR-V", daysAgo: 29 },
{ name: "Ford Mustang", daysAgo: 33 },
{ name: "Volvo XC60", daysAgo: 38 },
{ name: "Nissan Rogue", daysAgo: 44 },
{ name: "Audi Q5", daysAgo: 49 },
{ name: "Mini Cooper", daysAgo: 53 },
{ name: "Chevrolet Bolt", daysAgo: 58 },
];
const carCount = (n: number) => (n === 1 ? "1 car" : `${n} cars`);
export default function ListedExample() {
const [listed, setListed] = useState<DateRangeValue>({ last: 30 });
// Today is null until the page runs in the browser, so the server render never guesses the date.
const today = useToday();
const dayOf = (daysAgo: number) => (today ? addDays(today, -daysAgo) : "");
const results = CARS.filter(({ daysAgo }) => {
if (!listed) return true;
if ("last" in listed) return daysAgo < listed.last;
return dayOf(daysAgo) >= listed.start && dayOf(daysAgo) <= listed.end;
});
return (
<div className="w-full max-w-[320px]">
<FilterCard title="Listed" summary={formatDateRange(listed, undefined, today)} onClear={() => setListed(null)} defaultOpen>
<DateRange
label="Listed"
value={listed}
onChange={setListed}
countOf={(day) => CARS.filter(({ daysAgo }) => dayOf(daysAgo) === day).length}
total={CARS.length}
countLabel={carCount}
/>
</FilterCard>
<p className="mt-3 px-4 text-[14px] leading-5 tabular-nums">
<span className="font-medium">{results.length}</span> <span className="text-[var(--fu-dim,#929292)]">of {CARS.length} cars</span>
</p>
</div>
);
}
```
## Connect it to my data
Ask me which date field it filters and where the items come from. Keep the value as it is: { last: N } stays relative, so a saved search for the last 7 days still means the last 7 days tomorrow. To filter, turn the value into two dates with resolveDateRange(value, today) and keep items whose date, as "YYYY-MM-DD" in the visitor's time zone, falls between them, both days included. Give countOf the number of items on each day, counted with every other filter applied and this one left out. Use formatDateRange for the card's summary. Read today with useToday() or pass the today prop; never compute it during the server render, or the server and the browser will disagree near midnight.
## Keep the look
It is dark by default and needs no setup. To change colours, set these CSS variables on :root or on a parent element. These are the dark defaults:
```css
:root {
--fu-accent: #3B57E6;
--fu-accent-hover: #3450D4;
--fu-accent-pale: #D1DDFF;
--fu-accent-soft: #8FAAFF;
--fu-card: #1F1F1F;
--fu-card-border: #2A2A2A;
--fu-card-hover: #262626;
--fu-control-border: #737373;
--fu-control-hover: #A3A3A3;
--fu-dim: #929292;
--fu-field-border: #737373;
--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-on-accent-mute: #E1E7FF;
--fu-pill: rgb(255 255 255/0.1);
--fu-pill-text: #C8C8C8;
--fu-selected: #1F2747;
--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-wash: rgb(255 255 255/0.08);
}
```
To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).
```css
.light {
--fu-accent: #3B57E6;
--fu-accent-hover: #2F4AD0;
--fu-accent-pale: #253A9E;
--fu-accent-soft: #3049D2;
--fu-card: #FFFFFF;
--fu-card-border: #E5E5E2;
--fu-card-hover: #F8F8F6;
--fu-control-border: #787874;
--fu-control-hover: #5B5B57;
--fu-dim: #555552;
--fu-field-border: #949490;
--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-on-accent-mute: #E1E7FF;
--fu-pill: rgb(29 27 24/0.06);
--fu-pill-text: #3C3C3A;
--fu-selected: #E8EDFD;
--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-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
- The presets are a radiogroup; the calendar is a grid of gridcells, labelled by the month, with aria-selected on the days in the range and aria-current on today.
- Each day reads in full with its count ("Tuesday, November 10, 2026, 4 cars"); a day after today is aria-disabled.
- Every change is announced politely, as words and a count ("November 3 to 9, 12 cars").
- Loading, it is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter. Disabled, the grid is aria-disabled.
- Motion is skipped when reduced motion is asked for.
- The presets are one tab stop: arrow keys move and pick.
- In the calendar, arrows move by day and week, Home and End go to the week's ends, Page Up and Page Down change month, with Shift a year.
- Right to left the week runs from the right, so Left moves to the next day and Right to the day before.
- Enter or Space picks the first day, then the last; Escape drops a half-picked range.
- In a date field, Enter or leaving it applies what was typed; Escape puts it back.
- While disabled nothing takes focus and the arrows do nothing; 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
- Presets pick the last 1, 3, 7 or 30 days in one press; the chosen one is tinted and each shows its count.
- On the calendar, the first pick starts a range and the band follows the pointer day by day until the second pick ends it.
- Each day shows how many items it holds; days after today are dimmed and cannot be picked.
- The month name opens a twelve-month view; typed dates read "Nov 3", "11/3" or "2026-11-03".
- Exports formatDateRange for the card's summary and resolveDateRange to turn a value into two dates.
Keyboard
- The presets are one tab stop: arrow keys move and pick.
- In the calendar, arrows move by day and week, Home and End go to the week's ends, Page Up and Page Down change month, with Shift a year.
- Right to left the week runs from the right, so Left moves to the next day and Right to the day before.
- Enter or Space picks the first day, then the last; Escape drops a half-picked range.
- In a date field, Enter or leaving it applies what was typed; Escape puts it back.
- While disabled nothing takes focus and the arrows do nothing; in an error Tab reaches Retry.
Props
Value. { last: number } | { start: string; end: string } | null: the last N days with today (it moves on as days pass), two fixed days as "YYYY-MM-DD", both included, or null for any time.
| Prop | Description |
|---|---|
valueRequired | The range: { last: 7 }, { start: "2026-11-03", end: "2026-11-09" } or null. DateRangeValue |
onChangeRequired | Called with the new range. A first pick on the calendar sends a one-day range; the second pick widens it. (value: DateRangeValue) => void |
todayDefault the visitor's date | Today as "YYYY-MM-DD". Left out, it is read in the browser after the first render, so server and browser always agree. string |
presetsDefault Today, Last 3, 7 and 30 days | The quick picks between Any time and Custom. readonly { label: string; last: number }[] |
countOfOptional | Items on one day. Shown as a small number under each date and summed beside each preset. Leave out for a plain calendar. (date: string) => number |
totalOptional | Every item, whatever its date: the count beside Any time. number |
labelDefault "Dates" | Accessible name of the presets and the start of the fields' names, e.g. "Listed". string |
anyLabel / customLabelDefault "Any time" / "Custom" | The first and last preset. string / string |
allowFutureDefault false | Lets days after today be picked. Off, they show dimmed. boolean |
weekStartsOnDefault the locale's | The first day of the week: 0 is Sunday, 1 Monday, 6 Saturday. Default: Sunday in en-US, Monday in de-DE, Saturday in ar-EG. 0 | 1 | 2 | 3 | 4 | 5 | 6 |
formatCount / countLabelDefault 1,234 / "6 results" | Text of each count, and its words for screen readers, e.g. "6 cars". (n: number) => string |
localeDefault "en-US" | Month and weekday names, the first day of the week, the order of typed dates ("3.11." in de-DE) and the numbers. The presets' words stay as given. string |
statusDefault "ready" | "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place. "ready" | "loading" | "error" |
onRetryOptional | Called by Retry in the error state. Without it the error line has no button. () => void |
errorTextDefault "Couldn't load the counts." | The error line, in plain words. string |
disabledDefault false | Dims the whole filter, blocks pointer and keyboard input and reads as unavailable. boolean |
The card: FilterCard
| Prop | Description |
|---|---|
titleRequired | The card's heading, e.g. "Price". string |
summaryOptional | The value in words, shown on the closed card. Null or empty means the filter is unset. string | null |
onClearOptional | Clears this filter. When given, a Clear button takes the summary's place while open or hovered. () => void |
open / defaultOpen / onOpenChangeDefault closed | Controlled or uncontrolled open state. boolean / boolean / (open: boolean) => void |
headingLevelDefault 3 | Heading level around the head button. 2 | 3 | 4 | 5 | 6 |
bodyClassNameOptional | Classes for the body, e.g. to tune the space under the content. string |