v1.3.5
Filters

No results

When the filters find nothing, it offers the smallest changes that bring results back, each with its count.

Live example

Try:

No cars match

Try one of these changes.

0 of 256 cars

Direction
Locale
State

Copy

Claude Code
Cursor
v0
Lovable
Other
Add the "No results" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.

No results: When the filters find nothing, it offers the smallest changes that bring results back, each with its count.

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/no-results.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/no-results.tsx

```tsx
"use client";

import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { findFixes, type Fix, type RelaxMap } from "../lib/relax";
import { SEARCH_ART } from "../ui/art-search";
import { ArrowRightIcon } from "../ui/icons";
import { placeholderLabels, SKELETON_FILL, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";

export type CountNoun = { one: string; other: string };

export type NoResultsProps<Item, State> = Omit<HTMLAttributes<HTMLElement>, "onChange" | "title"> &
  Omit<StateProps, "emptyText"> & {
  /** Every item, for the count each fix would give. */
  items: readonly Item[];
  /** The filters that find nothing. */
  value: State;
  /** Called with the filters a fix gives. */
  onChange: (value: State) => void;
  /** Does an item pass these filters? */  matches: (item: Item, state: State) => boolean;
  /** How each filter can be loosened. */
  relax: RelaxMap<State>;
  /** Default "No results". */
  title?: string;
  /** Default "Try one of these changes.", or a nudge to clear filters when no change helps. */
  description?: string;
  /** Default { one: "result", other: "results" }. */
  noun?: CountNoun;
  /** Default: the number in the locale ("1,204"). */
  formatCount?: (n: number) => string;
  /** Formats the counts by default, e.g. "de-DE". Default "en-US". */
  locale?: string;
  /** How many fixes to offer. Default 3. */
  limit?: number;
  /** When given, a Clear all button closes the card. */
  onClearAll?: () => void;
  clearAllLabel?: string;
  /** What a fix says a press does, in its count's place, while it is pointed at: dropping its filters, or loosening one. Default "Remove" and "Apply". */
  removeLabel?: string;
  applyLabel?: string;
  /** Heading level of the title. Default 3. */
  headingLevel?: 2 | 3 | 4 | 5 | 6;
};

const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const noop = () => () => {};

/** False while hydrating server HTML, true for anything rendered on the client: only the latter animates in. */
const useClientRender = () => useSyncExternalStore(noop, () => true, () => false);

/** A loading bar's share of the row while there are no fixes yet: calm and falling, so it never hints at counts. */
const loadingShare = (i: number) => Math.max(0.3, 0.9 - i * 0.22);

/** Stand-in fixes while the counts are on their way: one change each, only their widths are shown. */
function placeholderFixes<State>(limit: number, state: State): Fix<State>[] {
  const words = placeholderLabels(limit * 3);
  return Array.from({ length: limit }, (_, i) => ({
    id: `placeholder-${i}`,
    changes: [{ key: "placeholder", label: words[i * 3 + 1], from: words[i * 3 + 2], to: words[i * 3], removed: false }],
    state,
    count: 0,
  }));
}

function spoken<State>(fix: Fix<State>, verb: string, noun: CountNoun, format: (n: number) => string) {
  // The verb, then the changes in the order the row shows them, so the name holds the visible words:
  // "Remove: Seats 7+ → Any, 3 cars".
  const changes = fix.changes.map((c) => `${c.label} ${c.from} → ${c.to}`).join("; ");
  return `${verb}: ${changes}, ${format(fix.count)} ${fix.count === 1 ? noun.one : noun.other}`;
}

/**
 * Shown where results would be when the filters find nothing: the smallest changes that bring some back, each with
 * its count and a soft bar to compare them. Pointing at a fix crosses out the value it replaces and puts what a press
 * does in the count's place: Remove when it drops its filters, Apply when it loosens one. One press applies it.
 * Loading, the title stays and each fix keeps its place with placeholders for its words, count and bar; an error shows
 * its line and Retry in place of the fixes, and Clear all still works.
 */
export function NoResults<Item, State>({
  items,
  value,
  onChange,
  matches,
  relax,
  title = "No results",
  description,
  noun = { one: "result", other: "results" },
  formatCount: formatCountProp,
  locale,
  limit = 3,
  onClearAll,
  clearAllLabel = "Clear all",
  removeLabel = "Remove",
  applyLabel = "Apply",
  headingLevel = 3,
  status = "ready",
  onRetry,
  errorText = "Couldn't load the changes.",
  disabled = false,
  className,
  ...props
}: NoResultsProps<Item, State>) {
  const formatCount = formatCountProp ?? formatsFor(locale).number;
  const id = useId();
  // 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 failed = status === "error";
  const fixes = useMemo(() => findFixes({ items, value, matches, relax, limit }), [items, value, matches, relax, limit]);
  const most = Math.max(1, ...fixes.map((fix) => fix.count));
  // Until the counts are in, it cannot know that no change helps, so it says what it will offer.
  const said = description ?? (fixes.length || status !== "ready" ? "Try one of these changes." : "No small change finds anything. Clear a few filters.");
  const placeholders = loading && fixes.length === 0;
  const shownFixes = placeholders ? placeholderFixes(limit, value) : fixes;
  const Heading = `h${headingLevel}` as const;

  // Rows rise in one after another and their bars grow, whenever a new set of fixes shows on the client. Nothing
  // cancels them on cleanup: they belong to these rows, and a remount in Strict Mode would otherwise lose them.
  const rows = useRef<HTMLUListElement>(null);
  const client = useClientRender();
  const animateFirst = useRef(client);
  const shownKey = fixes.map((fix) => fix.id).join(",");
  const lastKey = useRef<string | null>(null);
  useLayoutEffect(() => {
    const first = lastKey.current === null;
    if (lastKey.current === shownKey) return;
    lastKey.current = shownKey;
    if ((first && !animateFirst.current) || reducedMotion() || !rows.current) return;
    // Each bar grows out of its start edge, which is the right one in RTL.
    const hidden = getComputedStyle(rows.current).direction === "rtl" ? "inset(0 0 0 100% round 8px)" : "inset(0 100% 0 0 round 8px)";
    rows.current.querySelectorAll<HTMLElement>("[data-fix-row]").forEach((row, i) => {
      row.querySelector<HTMLElement>("[data-fix-content]")?.animate(
        [
          { opacity: 0, transform: "translateY(6px)", filter: "blur(6px)" },
          { opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
        ],
        { duration: 480, delay: i * 40, easing: EASE, fill: "backwards" },
      );
      row
        .querySelector<HTMLElement>("[data-fix-bar]")
        ?.animate([{ clipPath: hidden }, { clipPath: "inset(0 0 0 0 round 8px)" }], {
          duration: 720,
          delay: 140 + i * 60,
          easing: EASE,
          fill: "backwards",
        });
    });
  }, [shownKey]);

  // Said once the card is on screen, so a screen reader hears it even though it mounts with its text. While the counts
  // load or fail, the status line under the title speaks instead.
  const [announce, setAnnounce] = useState("");
  useEffect(() => {
    const words =
      status !== "ready" ? "" : `${title}. ${fixes.length ? `${fixes.length} ${fixes.length === 1 ? "change brings" : "changes bring"} ${noun.other} back.` : said}`;
    const timer = setTimeout(() => setAnnounce(words), 120);
    return () => clearTimeout(timer);
  }, [title, said, fixes.length, noun.other, status]);

  return (
    <section
      aria-labelledby={`${id}-title`}
      className={cn(
        "not-prose overflow-hidden rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-text,#F8F5F1)]",
        className,
      )}
      {...props}
    >
      {/* The outer frame holds the whole card: no input while loading, and dimmed and off while disabled. The fixes have a
          frame of their own, which says "Loading" and the error, so an error stands under the title and Clear all stays. */}
      <StatusFrame status={loading ? "loading" : "ready"} disabled={disabled} announce={false} className="rounded-[23px] focus-visible:-outline-offset-2">
        <div className="flex items-center gap-3 px-4 pt-4 pb-3">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={SEARCH_ART} alt="" width={44} height={44} loading="lazy" decoding="async" draggable={false} className="size-11 shrink-0 object-contain select-none" />
          <div className="min-w-0">
            <Heading id={`${id}-title`} className="m-0 text-[15px] font-semibold leading-5">
              {title}
            </Heading>
            <p id={`${id}-said`} className="m-0 mt-0.5 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
              <span dir="auto">{said}</span>
            </p>
          </div>
        </div>

        <StatusFrame status={status} onRetry={onRetry} errorText={errorText} className={failed ? "mx-4 mb-4" : undefined}>
          {shownFixes.length > 0 && (
            <ul ref={rows} aria-labelledby={`${id}-said`} className="m-0 flex list-none flex-col gap-0.5 px-2 pb-2">
              {shownFixes.map((fix, i) => {
                const verb = fix.changes.every((change) => change.removed) ? removeLabel : applyLabel;
                return (
                <li key={fix.id} data-fix-row="">
                  <button
                    type="button"
                    aria-label={spoken(fix, verb, noun, formatCount)}
                    onClick={() => onChange(fix.state)}
                    className={cn(
                      "group/fix relative isolate flex min-h-12 w-full cursor-pointer items-center gap-3 rounded-[16px] py-2.5 pe-3 ps-4 text-start font-[inherit] text-[14px] leading-5 text-inherit",
                      "transition-[background-color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] active:scale-[0.99] active:duration-75 motion-reduce:transition-none",
                      "[@media(hover:hover)]:hover:bg-[var(--fu-card-hover,#262626)] focus-visible:bg-[var(--fu-card-hover,#262626)]",
                      "outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
                    )}
                  >
                    {/* Grey at rest, and blue on the fix in hand. Bars stop short of the count, so they read as a chart. */}
                    <span
                      aria-hidden="true"
                      data-fix-bar=""
                      style={{ width: `max(40px, calc((100% - 72px) * ${placeholders ? loadingShare(i) : fix.count / most}))` }}
                      className={cn(
                        "absolute inset-y-1 inset-s-1 -z-10 rounded-[12px]",
                        loading ? SKELETON_FILL : "bg-[var(--fu-share-hover,rgb(255_255_255/0.1))]",
                        "transition-[width,background-color] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                        "group-hover/fix:bg-[var(--fu-selected,#1F2747)] group-focus-visible/fix:bg-[var(--fu-selected,#1F2747)]",
                      )}
                    />
                    <span aria-hidden="true" data-fix-content="" className="flex min-w-0 flex-1 items-center gap-3">
                      <span className="flex min-w-0 flex-1 flex-col gap-1">
                        {fix.changes.map((change) => (
                          <span key={change.key} className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5">
                            <span className="text-[13px] text-[var(--fu-dim,#929292)]">
                              <SkeletonText>{change.label}</SkeletonText>
                            </span>{" "}
                            {/* When old and new do not fit on one line, the new value moves to the next one whole, never cut. The arrow
                                stays with the old value, which is cut short when it alone fills the line. */}
                            <span className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5">
                              <span className="flex min-w-0 items-center gap-x-1.5">
                                <span className="relative truncate text-[var(--fu-mute,#BDBDBD)] transition-[color] duration-200 group-hover/fix:text-[var(--fu-dim,#929292)] group-focus-visible/fix:text-[var(--fu-dim,#929292)]">
                                  <SkeletonText>{change.from}</SkeletonText>
                                  <span
                                    className={cn(
                                      "absolute inset-x-[-2px] top-1/2 h-px origin-left rtl:origin-right scale-x-0 bg-current",
                                      "transition-[scale] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                                      "group-hover/fix:scale-x-100 group-focus-visible/fix:scale-x-100",
                                    )}
                                  />
                                </span>{" "}
                                <ArrowRightIcon
                                  size={12}
                                  strokeWidth={2.25}
                                  className="shrink-0 text-[var(--fu-dim,#929292)] transition-[translate,color] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] [--flip:1] rtl:[--flip:-1] rtl:-scale-x-100 group-hover/fix:translate-x-[calc(var(--flip,1)*0.125rem)] group-hover/fix:text-[var(--fu-mute,#BDBDBD)] motion-reduce:transition-none"
                                />
                              </span>
                              {" "}
                              <span className="font-medium transition-[color] duration-200 group-hover/fix:text-[var(--fu-accent-pale,#D1DDFF)] group-focus-visible/fix:text-[var(--fu-accent-pale,#D1DDFF)]">
                                <SkeletonText>{change.to}</SkeletonText>
                              </span>
                            </span>
                          </span>
                        ))}
                      </span>{" "}
                      {/* The count and the verb share one place, as wide as the wider of the two, so nothing moves when they swap. */}
                      <span className="grid shrink-0 items-center justify-items-end tabular-nums">
                        <span
                          className={cn(
                            "[grid-area:1/1] transition-[opacity,translate] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                            !loading && "group-hover/fix:-translate-y-1 group-hover/fix:opacity-0 group-focus-visible/fix:-translate-y-1 group-focus-visible/fix:opacity-0",
                          )}
                        >
                          <SkeletonText>
                            <span className="text-[15px] font-medium text-[var(--fu-accent-soft,#8FAAFF)]">{formatCount(fix.count)}</span>
                            <span className="text-[13px] text-[var(--fu-dim,#929292)]"> {fix.count === 1 ? noun.one : noun.other}</span>
                          </SkeletonText>
                        </span>
                        {/* Loading, the verb stays in place unseen, so the row is as wide as it will be when the fixes are back. */}
                        <span
                          className={cn(
                            "translate-y-1 text-[14px] font-medium text-[var(--fu-accent-pale,#D1DDFF)] opacity-0 [grid-area:1/1]",
                            "transition-[opacity,translate] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                            loading
                              ? "invisible"
                              : "group-hover/fix:translate-y-0 group-hover/fix:opacity-100 group-focus-visible/fix:translate-y-0 group-focus-visible/fix:opacity-100",
                          )}
                        >
                          {verb}
                        </span>
                      </span>
                    </span>
                  </button>
                </li>
                );
              })}
            </ul>
          )}
        </StatusFrame>

        {onClearAll && (
          <div className="mx-4 flex min-h-12 items-center justify-between gap-3 border-t border-[var(--fu-card-border,#2A2A2A)] py-1">
            <span className="text-[13px] leading-5 text-[var(--fu-dim,#929292)]">Or start again</span>
            <button
              type="button"
              onClick={onClearAll}
              className={cn(
                "relative -me-2.5 inline-flex h-9 cursor-pointer items-center rounded-[10px] px-2.5 font-[inherit] text-[14px] font-medium leading-5 text-[var(--fu-accent-soft,#8FAAFF)]",
                "transition-[color,background-color,scale] duration-200 hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))] hover:text-[var(--fu-accent-pale,#D1DDFF)] active:scale-[0.97] motion-reduce:transition-none",
                "outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
                "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1 pointer-coarse:after:content-['']",
              )}
            >
              {clearAllLabel}
            </button>
          </div>
        )}
      </StatusFrame>

      <p className="sr-only" aria-live="polite">
        {announce}
      </p>
    </section>
  );
}
```

### components/filters-ui/lib/cn.ts

```ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```

### components/filters-ui/lib/format.ts

```ts
// Numbers, prices, distances, percents and dates for one locale, built on Intl with no dependency. Pass any BCP 47
// tag ("de-DE", "ar-EG"); a tag Intl cannot read falls back to en-US instead of throwing. The default is en-US, never
// the browser's own locale, so the server and the browser always print the same text. UI words stay English.

export const DEFAULT_LOCALE = "en-US";

export type FormatOptions = {
  /** ISO 4217 code for price and priceShort. Default "USD". */
  currency?: string;
  /** The unit of distance. Default "kilometer". */
  unit?: "kilometer" | "mile";
};

/** Every formatter takes the value alone, so any of them can be passed straight to a format prop. */
export type Formats = {
  /** The locale these formatters use, after any fallback. */
  locale: string;
  /** "1,234" in en-US, "1.234" in de-DE, up to three decimals. */
  number: (value: number) => string;
  /** A number with no group marks, such as a year: "2026", or "٢٠٢٦" in ar-EG. */
  plain: (value: number) => string;
  /** "45k", "1.2M". */
  compact: (value: number) => string;
  /** "$45,000" in en-US, "45.000 $" in de-DE: whole units of the currency. */
  price: (value: number) => string;
  /** "$45k" and "$97.5k" from a thousand up, "$950" below. */
  priceShort: (value: number) => string;
  /** "50,000 km" or "31,069 mi". */
  distance: (value: number) => string;
  /** A percentage given in percent, up to two decimals: 6.5 gives "6.5%" in en-US and "6,5 %" in de-DE. */
  percent: (value: number) => string;
  /** A day given as "YYYY-MM-DD", in words. Read in UTC, so it never shifts by a time zone. */
  day: (iso: string, options: Intl.DateTimeFormatOptions) => string;
  /** The name of a month, 0 for January. */
  month: (index: number, style?: "long" | "short") => string;
  /** The name of a weekday, 0 for Sunday. */
  weekday: (index: number, style?: "long" | "short") => string;
  /** The day weeks start on: 0 for Sunday, 1 for Monday, 6 for Saturday. */
  firstDay: 0 | 1 | 5 | 6;
  /** The locale's digits, 0 to 9: "0123456789", or "٠١٢٣٤٥٦٧٨٩" in ar-EG. */
  digits: string;
  /**
   * Reads a number typed the locale's way, with an optional k or m: "45,000", "$45k" and "1.2m" in en-US, "45.000"
   * and "1,2m" in de-DE. A unit such as "km" is not a suffix. Returns null when the text holds no number.
   */
  readNumber: (text: string) => number | null;
};

/**
 * A locale Intl has data for, or en-US. A well-formed tag with no data ("zz") would otherwise print in the
 * runtime's own locale, which differs between server and browser.
 */
export function safeLocale(locale?: string): string {
  if (!locale) return DEFAULT_LOCALE;
  try {
    const [tag] = Intl.getCanonicalLocales(locale);
    if (!tag) return DEFAULT_LOCALE;
    if (!Intl.NumberFormat.supportedLocalesOf(tag).length || !Intl.DateTimeFormat.supportedLocalesOf(tag).length) return DEFAULT_LOCALE;
    return tag;
  } catch {
    return DEFAULT_LOCALE;
  }
}

/** A currency code Intl can read, or USD. */
function safeCurrency(currency?: string): string {
  if (!currency) return "USD";
  try {
    new Intl.NumberFormat(DEFAULT_LOCALE, { style: "currency", currency });
    return currency.toUpperCase();
  } catch {
    return "USD";
  }
}

// Where weeks start, by region, as CLDR 48 has it; every other region starts on Monday. A table rather than
// Intl.Locale weekInfo, which not every browser has, so the server and every browser agree.
const SUNDAY = new Set(
  "AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "),
);
const SATURDAY = new Set("AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));

function firstDayOf(locale: string): 0 | 1 | 5 | 6 {
  let region: string | undefined;
  try {
    region = new Intl.Locale(locale).maximize().region;
  } catch {}
  if (!region) return 0;
  if (region === "MV") return 5;
  if (SATURDAY.has(region)) return 6;
  return SUNDAY.has(region) ? 0 : 1;
}

const cache = new Map<string, Formats>();

/** Formatters for one locale. Cheap to call on every render: each locale and option set is built once. */
export function formatsFor(locale?: string, options: FormatOptions = {}): Formats {
  const tag = safeLocale(locale);
  const currency = safeCurrency(options.currency);
  const unit = options.unit === "mile" ? "mile" : "kilometer";
  const key = `${tag}|${currency}|${unit}`;
  const known = cache.get(key);
  if (known) return known;

  const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(tag, o);
  const dates = new Map<string, Intl.DateTimeFormat>();
  const df = (o: Intl.DateTimeFormatOptions) => {
    const id = JSON.stringify(o);
    let format = dates.get(id);
    if (!format) {
      format = new Intl.DateTimeFormat(tag, { ...o, timeZone: "UTC" });
      dates.set(id, format);
    }
    return format;
  };
  // English writes thousands with a small k, as the filters always have.
  const english = tag === "en" || tag.startsWith("en-");
  const smallK = (text: string) => (english ? text.replace(/K\b/, "k") : text);

  const number = nf({});
  const plain = nf({ useGrouping: false, maximumFractionDigits: 20 });
  const compact = nf({ notation: "compact", maximumFractionDigits: 1 });
  const price = nf({ style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0 });
  // One decimal is exact for a 1,000 unit ("$97.5k"); a 10,000 unit such as 万 takes two ("$9.75万").
  const unitDigits = nf({ notation: "compact", useGrouping: false }).formatToParts(10000).filter((p) => p.type === "integer").map((p) => p.value).join("").length;
  const priceShort = nf({ style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: Math.max(1, 3 - unitDigits) });
  const distance = nf({ style: "unit", unit, maximumFractionDigits: 0 });
  const percent = nf({ style: "percent", maximumFractionDigits: 2 });

  const digits = plain.format(1234567890).replace(/^(.*)(.)$/, "$2$1");
  const parts = number.formatToParts(12345.6);
  const group = parts.find((p) => p.type === "group")?.value ?? ",";
  const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";

  const formats: Formats = {
    locale: tag,
    number: (value) => number.format(value),
    plain: (value) => plain.format(value),
    compact: (value) => smallK(compact.format(value)),
    price: (value) => price.format(value),
    priceShort: (value) => (Math.abs(value) >= 1000 ? smallK(priceShort.format(value)) : price.format(value)),
    distance: (value) => distance.format(value),
    percent: (value) => percent.format(value / 100),
    day: (iso, o) => df(o).format(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)))),
    month: (index, style = "long") => df({ month: style }).format(Date.UTC(2021, index, 1)),
    // 3 January 2021 was a Sunday.
    weekday: (index, style = "long") => df({ weekday: style }).format(Date.UTC(2021, 0, 3 + index)),
    firstDay: firstDayOf(tag),
    digits,
    readNumber: (text) => {
      let t = text.replace(/[\s  ‎‏؜]/g, "");
      for (let i = 0; i < 10; i++) t = t.split(digits[i]).join(String(i));
      if (!/\s/.test(group)) t = t.split(group).join("");
      // Marks typed in place of the locale's own: a Latin or Arabic comma where both marks are Arabic, a curly apostrophe for a straight one.
      if (!/[.,]/.test(group + decimal)) t = t.replace(/[,\u060c]/g, "");
      if (group === "'") t = t.split("\u2019").join("");
      if (decimal !== ".") t = t.split(decimal).join(".");
      const match = t.match(/(\d*\.?\d+)([km](?![a-z]))?/i);
      if (!match) return null;
      const scale = match[2] ? (match[2].toLowerCase() === "k" ? 1e3 : 1e6) : 1;
      return Number(match[1]) * scale;
    },
  };
  cache.set(key, formats);
  return formats;
}

/** "1 result", "1,204 results": the default words for a count, with the number in the locale. */
export const resultsLabel = (n: number, locale?: string) => `${formatsFor(locale).number(n)} ${n === 1 ? "result" : "results"}`;
```

### components/filters-ui/lib/relax.ts

```ts
// Finds the smallest changes to a set of filters that bring results back, for a "no results" state.
//
// A relax map says how each filter can be loosened: its name, its value in words, and looser values, nearest first.
// A list filter (fuel, colour) usually has one step, Any; a limit has one step per notch out, then Any.
// Fixes change one filter where that is enough, and two where no single change finds anything.

export type RelaxStep<State> = {
  /** The looser value in words, e.g. "Under $25k" or "Any". */
  value: string;
  /** The filters with this one loosened. Change only this filter, so two steps can be applied one after the other. */
  apply: (state: State) => State;
};

export type RelaxFacet<State> = {
  /** The filter's name, e.g. "Price". */
  label: string;
  /** The value in words, e.g. "Under $20k", or null while the filter is not set. */
  value: (state: State) => string | null;
  /** Looser values, nearest first. */
  steps: (state: State) => readonly RelaxStep<State>[];
};

export type RelaxMap<State> = Record<string, RelaxFacet<State>>;

export type FixChange = {
  key: string;
  label: string;
  from: string;
  to: string;
  /** True when the change leaves the filter unset, rather than looser. */
  removed: boolean;
};

export type Fix<State> = {
  /** Stable while the same changes are offered. */
  id: string;
  changes: FixChange[];
  /** The filters with the changes made. */
  state: State;
  /** How many items they find. */
  count: number;
};

/**
 * Steps for a filter that holds one value or a limit: each looser value in `looser` (nearest first), then Any.
 * No steps while `current` is null.
 */
export function loosen<State, V>(
  current: V | null,
  looser: readonly V[],
  set: (state: State, value: V | null) => State,
  format: (value: V) => string = String,
  any = "Any",
): RelaxStep<State>[] {
  if (current === null) return [];
  return [
    ...looser.map((value) => ({ value: format(value), apply: (state: State) => set(state, value) })),
    { value: any, apply: (state: State) => set(state, null) },
  ];
}

type Facet<State> = { key: string; label: string; from: string; steps: readonly RelaxStep<State>[] };

/**
 * Up to `limit` fixes for filters that find nothing. Each set filter is loosened by its nearest step that finds
 * something; where none does, it is paired with another such filter, nearest steps first. Fixes that change one
 * filter come first, then the ones that find most.
 */
export function findFixes<Item, State>({
  items,
  value,
  matches,
  relax,
  limit = 3,
}: {
  items: readonly Item[];
  value: State;
  matches: (item: Item, state: State) => boolean;
  relax: RelaxMap<State>;
  limit?: number;
}): Fix<State>[] {
  const count = (state: State) => {
    let n = 0;
    for (const item of items) if (matches(item, state)) n++;
    return n;
  };

  const facets: Facet<State>[] = [];
  for (const [key, facet] of Object.entries(relax)) {
    const from = facet.value(value);
    const steps = from === null ? [] : facet.steps(value);
    if (from !== null && steps.length) facets.push({ key, label: facet.label, from, steps });
  }

  const fixOf = (picks: [Facet<State>, number][], state: State, n: number): Fix<State> => {
    const changes = picks.map(([facet, i]) => ({
      key: facet.key,
      label: facet.label,
      from: facet.from,
      to: facet.steps[i].value,
      removed: relax[facet.key].value(state) === null,
    }));
    return { id: changes.map((c) => `${c.key}:${c.to}`).join("|"), changes, state, count: n };
  };

  const fixes: Fix<State>[] = [];
  const stuck: Facet<State>[] = [];
  for (const facet of facets) {
    let found = false;
    for (let i = 0; i < facet.steps.length && !found; i++) {
      const state = facet.steps[i].apply(value);
      const n = count(state);
      if (n > 0) {
        fixes.push(fixOf([[facet, i]], state, n));
        found = true;
      }
    }
    if (!found) stuck.push(facet);
  }

  // Pairs, only of filters that no single change frees: the nearest pair of steps wins, the larger count breaks a tie.
  if (fixes.length < limit) {
    for (let a = 0; a < stuck.length; a++) {
      for (let b = a + 1; b < stuck.length; b++) {
        const [one, two] = [stuck[a], stuck[b]];
        let best: Fix<State> | null = null;
        for (let cost = 0; cost <= one.steps.length + two.steps.length - 2 && !best; cost++) {
          for (let i = Math.max(0, cost - two.steps.length + 1); i <= Math.min(cost, one.steps.length - 1); i++) {
            const state = two.steps[cost - i].apply(one.steps[i].apply(value));
            const n = count(state);
            if (n > 0 && (!best || n > best.count)) best = fixOf([[one, i], [two, cost - i]], state, n);
          }
        }
        if (best) fixes.push(best);
      }
    }
  }

  return fixes.sort((x, y) => x.changes.length - y.changes.length || y.count - x.count).slice(0, limit);
}
```

### 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/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/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);
}
```

## What it does

- Loosens each filter in use by its nearest step that finds something: "Under $20k" to "Under $25k", "7+" to "Any".
- Where no single change helps, it pairs two filters, nearest steps first.
- Each fix shows its count over a soft bar, so the fixes compare at a glance.
- Pointing at a fix crosses out the value it replaces and shows what a press does in the count's place: Remove when it drops its filters, Apply when it loosens one. One press applies it.
- Works with any data: a list of looser steps for each filter (the relax prop), not the component, knows your fields.

## Props and value

NoResults (components/filters-ui/filters/no-results.tsx) holds this value: State: your own filters object. It reads the filters that find nothing and hands back the filters a fix gives.

- items: readonly Item[] (required). Every item, to count what each fix would find.
- value: State (required). The filters that find nothing.
- onChange: (value: State) => void (required). Called with the filters a fix gives.
- matches: (item: Item, state: State) => boolean (required). Whether an item passes the filters: the same test the results use.
- relax: RelaxMap<State> (required). How each filter loosens: its name, its value in words, and looser values, nearest first. loosen() builds the steps for a value or a limit.
- title / description: string / string (default "No results" / "Try one of these changes."). The card's heading and the line under it.
- noun: { one: string; other: string } (default result, results). The word after each count, e.g. car and cars.
- formatCount: (n: number) => string (default 1,234). Text for each count.
- limit: number (default 3). How many fixes to offer.
- onClearAll: () => void (optional). When given, a Clear all button closes the card.
- removeLabel / applyLabel: string / string (default "Remove" / "Apply"). What a fix says a press does while it is pointed at: dropping its filters, or loosening one.
- headingLevel: 2 | 3 | 4 | 5 | 6 (default 3). Level of the title.
- locale: string (default "en-US"). Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the changes."). The error line, in plain words.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.

## States

Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.

- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. The title stays; each fix keeps its place with placeholders for its words, its count and its bar. With no items yet it draws limit stand-in fixes. It is aria-busy and says "Loading" once; when status turns back to "ready" the data fades in once. No spinner.
- Error (status="error", with onRetry and errorText): one calm line and a Retry button that calls onRetry, in the filter's own place. The line and Retry sit under the title in place of the fixes; Clear all still works. The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. Every fix and Clear all are off; the title stays readable.
- Long labels (data, not a prop): A fix's filter name and new value wrap onto more lines; the old value, crossed out, stays on one line and is cut short. The count and the bar stay at the end, and the row's name holds every word.

## 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 { useEffect, useRef, useState } from "react";
import { NoResults } from "@/components/filters-ui/filters/no-results";
import { loosen, type RelaxMap } from "@/components/filters-ui/lib/relax";

type Fuel = "Gas" | "Hybrid" | "Electric";
type Car = { name: string; price: number; fuel: Fuel; seats: number };

const CARS: Car[] = [
  { name: "Hyundai Elantra", price: 16900, fuel: "Hybrid", seats: 5 },
  { name: "Toyota Corolla", price: 18400, fuel: "Hybrid", seats: 5 },
  { name: "Kia Niro", price: 19500, fuel: "Hybrid", seats: 5 },
  { name: "Honda Civic", price: 17900, fuel: "Gas", seats: 5 },
  { name: "Kia Carnival", price: 19400, fuel: "Gas", seats: 8 },
  { name: "Honda Odyssey", price: 19800, fuel: "Gas", seats: 8 },
  { name: "Mazda CX-5", price: 21900, fuel: "Gas", seats: 5 },
  { name: "Ford Explorer", price: 23800, fuel: "Gas", seats: 7 },
  { name: "Toyota Highlander", price: 24500, fuel: "Hybrid", seats: 8 },
  { name: "Toyota RAV4", price: 26900, fuel: "Hybrid", seats: 5 },
  { name: "Toyota Sienna", price: 28900, fuel: "Hybrid", seats: 8 },
  { name: "Tesla Model Y", price: 34900, fuel: "Electric", seats: 7 },
];

type Filters = { maxPrice: number | null; fuel: Fuel | null; minSeats: number | null };

const matches = (car: Car, f: Filters) =>
  (f.maxPrice === null || car.price <= f.maxPrice) &&
  (f.fuel === null || car.fuel === f.fuel) &&
  (f.minSeats === null || car.seats >= f.minSeats);

const short = (n: number) => `$${n / 1000}k`;
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const PRICES = [20000, 25000, 30000, 40000];
const SEATS = [8, 7, 6];

// How each filter loosens, nearest first; "Any" always comes last.
const relax: RelaxMap<Filters> = {
  price: {
    label: "Price",
    value: (f) => (f.maxPrice === null ? null : `Under ${short(f.maxPrice)}`),
    steps: (f) =>
      loosen(f.maxPrice, PRICES.filter((p) => p > (f.maxPrice ?? 0)), (s: Filters, maxPrice) => ({ ...s, maxPrice }), (p) => `Under ${short(p)}`),
  },
  seats: {
    label: "Seats",
    value: (f) => (f.minSeats === null ? null : `${f.minSeats}+`),
    steps: (f) =>
      loosen(f.minSeats, SEATS.filter((n) => n < (f.minSeats ?? 0)), (s: Filters, minSeats) => ({ ...s, minSeats }), (n) => `${n}+`),
  },
  fuel: {
    label: "Fuel",
    value: (f) => f.fuel,
    steps: (f) => loosen(f.fuel, [], (s: Filters, fuel) => ({ ...s, fuel })),
  },
};

export default function NoResultsExample() {
  const [filters, setFilters] = useState<Filters>({ maxPrice: 20000, fuel: "Hybrid", minSeats: 7 });
  const results = CARS.filter((car) => matches(car, filters));
  const list = useRef<HTMLUListElement>(null);

  // Once a fix brings cars back, focus moves to them.
  const found = results.length > 0;
  useEffect(() => {
    if (found) list.current?.focus();
  }, [found]);

  return (
    <div className="w-full max-w-[400px]">
      {found ? (
        <ul
          ref={list}
          tabIndex={-1}
          aria-label="Results"
          className="rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] p-2 outline-none"
        >
          {results.map((car) => (
            <li key={car.name} className="flex h-12 items-center justify-between gap-3 px-3 text-[15px] leading-5 tabular-nums">
              <span className="min-w-0 truncate">
                <span className="font-medium">{car.name}</span>{" "}
                <span className="text-[13px] text-[var(--fu-dim,#929292)]">
                  {car.fuel}, {car.seats} seats
                </span>
              </span>
              <span className="shrink-0 font-medium text-[var(--fu-accent-soft,#8FAAFF)]">{money.format(car.price)}</span>
            </li>
          ))}
        </ul>
      ) : (
        <NoResults
          items={CARS}
          value={filters}
          onChange={setFilters}
          matches={matches}
          relax={relax}
          title="No cars match"
          noun={{ one: "car", other: "cars" }}
        />
      )}
      <p aria-live="polite" className="mt-3 px-4 text-[14px] leading-5 tabular-nums">
        <span className="font-medium">{results.length}</span> <span className="text-[var(--fu-dim,#929292)]">of {CARS.length} cars</span>
      </p>
    </div>
  );
}
```

## Connect it to my data

Ask me where my items and my filters come from. Pass every item, my filters object, and a matches(item, filters) test: the same test my results use. Then write a relax map with one entry per filter: its name, its value in words (null while it is not set), and steps, the looser values nearest first, each with its words and how it changes my filters. loosen(current, looser, set, format) builds the steps for a single value or a limit, and adds Any at the end; a list filter usually has no looser value, only Any. Show the card in place of the results when nothing matches, and move focus to the results after a fix. Keep components/filters-ui/lib/relax.ts as it is: it knows no field names.

## 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-dim: #929292;
  --fu-hover: #333333;
  --fu-hover-wash: rgb(255 255 255/0.14);
  --fu-mute: #BDBDBD;
  --fu-on-accent: #FFFFFF;
  --fu-selected: #1F2747;
  --fu-share-hover: rgb(255 255 255/0.1);
  --fu-skeleton: rgb(255 255 255/0.12);
  --fu-skeleton-on: rgb(143 170 255/0.3);
  --fu-surface-3: #2A2A2A;
  --fu-text: #F8F5F1;
}
```

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-dim: #555552;
  --fu-hover: rgb(29 27 24/0.11);
  --fu-hover-wash: rgb(29 27 24/0.07);
  --fu-mute: #444442;
  --fu-on-accent: #FFFFFF;
  --fu-selected: #E8EDFD;
  --fu-share-hover: rgb(29 27 24/0.07);
  --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;
}
```

Keep the sizes, corners, spacing and motion as they are.

## Direction and language

It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.
Pass locale (default "en-US") to print its numbers, prices and dates the way a language writes them and to read typed numbers that way, e.g. locale="de-DE". The words stay English: change them through the props.

## Keep the accessibility

- Each fix is read with what a press does, its change and its count: "Remove: Seats 7+ → Any, 8 cars".
- When the card shows, its title and how many fixes it has are announced politely.
- After a fix, move focus to the results, as the example does.
- Motion is skipped when reduced motion is asked for.
- Loading, it is aria-busy and says "Loading" once instead of the fixes; an error is read out politely, and Retry keeps focus in the card. Disabled, every fix and Clear all is a disabled button.
- Each fix is a button: Tab moves between them, Enter or Space applies one.
- While disabled no fix and not Clear all takes focus; in an error Tab reaches Retry, then Clear all.

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

  • Loosens each filter in use by its nearest step that finds something: "Under $20k" to "Under $25k", "7+" to "Any".
  • Where no single change helps, it pairs two filters, nearest steps first.
  • Each fix shows its count over a soft bar, so the fixes compare at a glance.
  • Pointing at a fix crosses out the value it replaces and shows what a press does in the count's place: Remove when it drops its filters, Apply when it loosens one. One press applies it.
  • Works with any data: a list of looser steps for each filter (the relax prop), not the component, knows your fields.

Keyboard

  • Each fix is a button: Tab moves between them, Enter or Space applies one.
  • While disabled no fix and not Clear all takes focus; in an error Tab reaches Retry, then Clear all.

Props

Value. State: your own filters object. It reads the filters that find nothing and hands back the filters a fix gives.

NoResults props
PropDescription
items
Required

Every item, to count what each fix would find.

readonly Item[]
value
Required

The filters that find nothing.

State
onChange
Required

Called with the filters a fix gives.

(value: State) => void
matches
Required

Whether an item passes the filters: the same test the results use.

(item: Item, state: State) => boolean
relax
Required

How each filter loosens: its name, its value in words, and looser values, nearest first. loosen() builds the steps for a value or a limit.

RelaxMap<State>
title / description
Default "No results" / "Try one of these changes."

The card's heading and the line under it.

string / string
noun
Default result, results

The word after each count, e.g. car and cars.

{ one: string; other: string }
formatCount
Default 1,234

Text for each count.

(n: number) => string
limit
Default 3

How many fixes to offer.

number
onClearAll
Optional

When given, a Clear all button closes the card.

() => void
removeLabel / applyLabel
Default "Remove" / "Apply"

What a fix says a press does while it is pointed at: dropping its filters, or loosening one.

string / string
headingLevel
Default 3

Level of the title.

2 | 3 | 4 | 5 | 6
locale
Default "en-US"

Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.

string
status
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.

"ready" | "loading" | "error"
onRetry
Optional

Called by Retry in the error state. Without it the error line has no button.

() => void
errorText
Default "Couldn't load the changes."

The error line, in plain words.

string
disabled
Default false

Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.

boolean

More filters