v1.3.5
Filters

Recent searches

Your recent and saved searches under the search box, each with its filters and its count.

Live example

Saved

Family hybrid Hybrid · 7+ seats
City electric Electric · Under $40k
Weekend truck 4WD · Truck

Recent

Blue SUV Under $30k
Toyota RAV4 2020 or newer
Hatchback Under $25k
Silver AWD Under $35k

256 cars

256 of 256 cars

Direction
Locale
State

Copy

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

Recent searches: Your recent and saved searches under the search box, each with its filters and 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/recent-searches.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/recent-searches.tsx

```tsx
"use client";

import { Fragment, useEffect, useId, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { countOf, type Token, type Vocabulary } from "../lib/sentence";
import { CountPill } from "../ui/count-pill";
import { CheckIcon, HistoryIcon, StarIcon, XIcon } from "../ui/icons";
import { ARRIVING, placeholderLabels, SKELETON_FILL, SkeletonText, useLoading } from "../ui/skeleton";
import { SentenceSearch, type OwnRow, type OwnRowProps, type SentenceSearchProps } from "./sentence-search";

/** A search kept by the page: in Recent, or in Saved with a name. */
export type SavedSearch<State> = { id: string; value: State; name?: string };

export type RecentSearchesProps<Item, State> = Omit<SentenceSearchProps<Item, State>, "emptyRows" | "open" | "onOpenChange"> & {
  /** Newest first. A search that is also saved shows in Saved only. */
  recent: readonly SavedSearch<State>[];
  saved: readonly SavedSearch<State>[];
  /** A search worth keeping: called when the field loses focus with filters set, and with the old search when the box is cleared. */
  onSearch: (value: State) => void;
  /** "Save this search", or the star on a recent row. `name` is read from its tokens: "Blue SUV under $30k". */
  onSave: (value: State, name: string) => void;  /** The cross on a row, or Delete while it is highlighted. */
  onForget: (id: string) => void;
  /** How many recent searches show. */
  recentLimit?: number;
  /** The quiet line in the list while there are no recent and no saved searches. Default "No recent searches yet" */
  emptyText?: string;
};

const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const newId = () => Math.random().toString(36).slice(2, 10);

/** One string per search, whatever order its filters were added in. "" for a search with nothing set. */
export const signatureOf = <Item, State>(vocabulary: Vocabulary<Item, State>, value: State) =>
  vocabulary
    .tokens(value)
    .map((token) => `${token.key}:${token.label}`)
    .sort()
    .join("|");

/** Puts a search at the top of a recent list, once, keeping at most `limit`. A search with nothing set is skipped. */
export function remember<Item, State>(vocabulary: Vocabulary<Item, State>, list: SavedSearch<State>[], value: State, limit = 6) {
  const key = signatureOf(vocabulary, value);
  if (!key) return list;
  const same = list.find((entry) => signatureOf(vocabulary, entry.value) === key);
  if (same && list[0] === same) return list;
  return [{ id: same?.id ?? newId(), value }, ...list.filter((entry) => entry !== same)].slice(0, limit);
}

const PHRASE = /^(Under|Over|From|Up to|At least|At most|Less|More|Between|With|Without|Not|No) /;

/** A name read from a search's tokens: "Blue SUV under $30k". */
export const nameOf = <State,>(tokens: readonly Token<State>[]) =>
  tokens.map((token, i) => (i > 0 && PHRASE.test(token.label) ? token.label[0].toLowerCase() + token.label.slice(1) : token.label)).join(" ");

const wordsOf = <State,>(tokens: readonly Token<State>[]) => tokens.map((token) => token.label).join(" · ");

function Glyph({ children, tone = "dim" }: { children: ReactNode; tone?: "dim" | "accent" }) {
  return (
    <span
      aria-hidden="true"
      className={cn(
        "grid size-8 shrink-0 place-items-center rounded-[9px] transition-[background-color,color] duration-200 motion-reduce:transition-none",
        SMOOTH,
        tone === "accent"
          ? "bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-accent-soft,#8FAAFF)] group-aria-selected/row:bg-[var(--fu-selected,#1F2747)]"
          : "text-[var(--fu-dim,#929292)] group-aria-selected/row:text-[var(--fu-mute,#BDBDBD)]",
      )}
    >
      {children}
    </span>
  );
}

/**
 * A small press target inside a row, for the pointer only: the keys reach the same action through the row. A mouse
 * over it shows its tip above it (below near the top of the window), on the page's top layer, so neither the list's
 * scroll area nor the folded actions clip it.
 */
function RowAction({ tip, onPress, children }: { tip: string; onPress: () => void; children: ReactNode }) {
  const bubble = useRef<HTMLSpanElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  // A removed row takes its open tip with it: the browser closes a popover that leaves the page.
  useEffect(() => () => clearTimeout(timer.current), []);

  const show = (event: ReactPointerEvent<HTMLSpanElement>) => {
    const node = bubble.current;
    if (event.pointerType === "touch" || !node) return;
    clearTimeout(timer.current);
    if (!node.matches(":popover-open")) {
      try {
        node.showPopover();
      } catch {
        return;
      }
    }
    const box = event.currentTarget.getBoundingClientRect();
    const below = box.top < 40;
    node.style.left = `${box.left + box.width / 2}px`;
    node.style.top = `${below ? box.bottom + 6 : box.top - 6}px`;
    node.dataset.side = below ? "below" : "above";
    // Read the start position before the shown state, so the tip rises in rather than appearing.
    node.getBoundingClientRect();
    node.dataset.shown = "";
  };

  const hide = () => {
    const node = bubble.current;
    if (!node) return;
    delete node.dataset.shown;
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      if (node.matches(":popover-open")) node.hidePopover();
    }, 150);
  };

  return (
    <span
      aria-hidden="true"
      onPointerEnter={show}
      onPointerLeave={hide}
      onClick={(event) => {
        event.stopPropagation();
        hide();
        onPress();
      }}
      className={cn(
        "group/act relative grid size-7 shrink-0 cursor-pointer place-items-center rounded-[8px] text-[var(--fu-dim,#929292)]",
        "transition-[background-color,color] duration-150 motion-reduce:transition-none",
        "hover:bg-[var(--fu-hover,#333333)] hover:text-[var(--fu-text,#F8F5F1)]",
        "pointer-coarse:after:absolute pointer-coarse:after:-inset-2 pointer-coarse:after:content-['']",
      )}
    >
      {children}
      <span
        ref={bubble}
        popover="manual"
        className={cn(
          "pointer-events-none fixed inset-auto m-0 -translate-x-1/2 overflow-visible rounded-[8px] border-0 px-2 py-1 whitespace-nowrap",
          "bg-[var(--fu-text,#F8F5F1)] text-[12px] leading-4 font-medium text-[var(--fu-surface-1,#171717)]",
          "opacity-0 transition-[opacity,translate] duration-150 ease-in-out motion-reduce:transition-none data-shown:opacity-100",
          "data-[side=above]:translate-y-[calc(-100%+4px)] data-[side=above]:data-shown:-translate-y-full",
          "data-[side=below]:-translate-y-1 data-[side=below]:data-shown:translate-y-0",
        )}
      >
        {tip}
      </span>
    </span>
  );
}

/** The row's actions, folded away until the row is hovered or highlighted, so the counts keep one column at rest. */
function RowActions({ children, width }: { children: ReactNode; width: "one" | "two" }) {
  return (
    <span
      className={cn(
        "flex shrink-0 items-center justify-end overflow-hidden opacity-0 blur-[2px]",
        "w-0 transition-[width,opacity,filter] duration-200 motion-reduce:transition-none",
        SMOOTH,
        width === "one"
          ? "group-hover/row:w-8 group-aria-selected/row:w-8 pointer-coarse:w-8"
          : "group-hover/row:w-[60px] group-aria-selected/row:w-[60px] pointer-coarse:w-[60px]",
        "group-hover/row:opacity-100 group-hover/row:blur-none group-aria-selected/row:opacity-100 group-aria-selected/row:blur-none pointer-coarse:opacity-100 pointer-coarse:blur-none",
      )}
    >
      {children}
    </span>
  );
}

/** A forgotten row, drawn once more where it was while it blurs away; the rows under it glide up over it. */
function Leaving({ top, height, onDone, children }: { top: number; height: number; onDone: () => void; children: ReactNode }) {
  const node = useRef<HTMLDivElement>(null);
  const done = useRef(onDone);
  useLayoutEffect(() => {
    const fade = node.current?.animate(
      [
        { opacity: 1, filter: "blur(0)", scale: "1" },
        { opacity: 0, filter: "blur(4px)", scale: "0.98" },
      ],
      { duration: 220, easing: EASE, fill: "forwards" },
    );
    if (!fade) return done.current();
    fade.onfinish = () => done.current();
    return () => fade.cancel();
  }, []);
  return (
    <div
      ref={node}
      aria-hidden="true"
      style={{ top, height }}
      className="pointer-events-none absolute inset-x-1.5 flex items-center gap-3 rounded-[12px] pe-3 ps-2"
    >
      {children}
    </div>
  );
}

/** A filter of a recent search. While the searches load it is a pulsing pill of its own size; its words fade in once. */
function Chip({ children }: { children: string }) {
  const { loading, arriving } = useLoading();
  return (
    <span
      className={cn(
        "block h-6 max-w-full min-w-0 truncate rounded-full px-2.5 text-[13px] leading-6 whitespace-nowrap",
        loading
          ? cn(SKELETON_FILL, "text-transparent")
          : cn(
              "bg-[var(--fu-pill,rgb(255_255_255/0.1))] text-[var(--fu-text,#F8F5F1)] transition-[background-color,color] duration-200 motion-reduce:transition-none",
              SMOOTH,
              "group-aria-selected/row:bg-[var(--fu-selected,#1F2747)] group-aria-selected/row:text-[var(--fu-accent-pale,#D1DDFF)]",
            ),
      )}
    >
      {arriving ? <span className={ARRIVING}>{children}</span> : children}
    </span>
  );
}

/** Stand-in searches while the lists are on their way: three saved, two recent. Never shown; only their widths are. */
const LOADING_SAVED = 3;
const LOADING_RECENT = 2;

const TITLE = "px-3 pt-2 pb-1 text-[13px] leading-[18px] text-[var(--fu-mute,#BDBDBD)]";
const EMPTY = "px-3 pb-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]";

/**
 * The sentence search with your searches under it. While the box is empty and nothing is set, the list shows Saved and
 * Recent searches; highlight one and its filters show faintly in the box, with its count at the foot. Once something is
 * set, "Save this search" leads the suggestions. Keeping the lists is up to the page: pass them in and change them in
 * onSearch, onSave and onForget.
 */
export function RecentSearches<Item, State>({
  vocabulary,
  items,
  value,
  onChange,
  recent,
  saved,
  onSearch,
  onSave,
  onForget,
  recentLimit = 4,
  emptyText = "No recent searches yet",
  status = "ready",
  errorText = "Couldn't load your searches.",
  defaultOpen = false,
  formatCount,
  countLabel: countLabelProp,
  locale,
  className,
  onBlur,
  ...props
}: RecentSearchesProps<Item, State>) {
  const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
  const id = useId();
  const root = useRef<HTMLDivElement>(null);
  const drawn = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(defaultOpen);
  const [said, setSaid] = useState("");
  const [leaving, setLeaving] = useState<{ key: string; top: number; height: number; body: ReactNode } | null>(null);
  // Its own status, or the loading frame of an item around it.
  const loading = useLoading().loading || status === "loading";

  const tokens = vocabulary.tokens(value);
  const sig = signatureOf(vocabulary, value);
  const savedSigs = new Set(saved.map((entry) => signatureOf(vocabulary, entry.value)));
  const savedNow = sig ? saved.find((entry) => signatureOf(vocabulary, entry.value) === sig) : undefined;
  const recents = recent
    .filter((entry) => {
      const key = signatureOf(vocabulary, entry.value);
      return key && !savedSigs.has(key);
    })
    .slice(0, recentLimit);
  const pill = (n: number) => <CountPill count={n} locale={locale} {...(formatCount && { format: formatCount })} />;
  const rowId = (kind: "saved" | "recent", entryId: string) => `${id}-${kind}-${entryId}`;
  const saveId = `${id}-save`;

  // The last search handed to onSearch, so leaving the field twice does not report it twice.
  const reported = useRef("");
  const previous = useRef({ sig, value });
  const report = useRef(onSearch);
  useLayoutEffect(() => {
    report.current = onSearch;
  });
  useEffect(() => {
    const was = previous.current;
    if (was.sig && !sig && was.sig !== reported.current) {
      reported.current = was.sig;
      report.current(was.value);
    }
    previous.current = { sig, value };
  }, [sig, value]);

  // Opened on first render, the list has no focus to lose, so a press outside closes it. Not in an inert still picture,
  // such as a preview, where a press elsewhere on the page must leave it as drawn.
  useEffect(() => {
    if (!open || root.current?.closest("[inert]")) return;
    const onDown = (event: PointerEvent) => {
      if (!(event.target instanceof Node) || !root.current?.contains(event.target)) setOpen(false);
    };
    document.addEventListener("pointerdown", onDown, true);
    return () => document.removeEventListener("pointerdown", onDown, true);
  }, [open]);

  // A row that moves (one above it forgotten, or a recent search saved) glides from where it was; a new one rises in.
  const places = useRef(new Map<string, number>());
  useLayoutEffect(() => {
    const next = new Map<string, number>();
    const moving = !reducedMotion();
    for (const node of drawn.current?.querySelectorAll<HTMLElement>("[data-flip]") ?? []) {
      const key = node.dataset.flip!;
      const top = node.offsetTop;
      next.set(key, top);
      const was = places.current.get(key);
      if (!moving) continue;
      if (was !== undefined && was !== top) {
        node.animate([{ translate: `0 ${was - top}px` }, { translate: "0 0" }], { duration: 380, easing: EASE });
      } else if (was === undefined && places.current.size > 0) {
        node.animate(
          [
            { opacity: 0, filter: "blur(2px)", translate: "0 4px" },
            { opacity: 1, filter: "blur(0)", translate: "0 0" },
          ],
          { duration: 300, easing: EASE },
        );
      }
    }
    places.current = next;
  });

  const savedBody = (entry: SavedSearch<State>) => {
    const own = vocabulary.tokens(entry.value);
    return (
      <>
        <Glyph tone="accent">
          <StarIcon size={16} className="fill-current" />
        </Glyph>
        <span className="min-w-0 flex-1">
          <span className="line-clamp-2 text-[15px] leading-5 font-medium [overflow-wrap:anywhere] text-[var(--fu-text,#F8F5F1)]">
            <SkeletonText>{entry.name ?? nameOf(own)}</SkeletonText>
          </span>{" "}
          <span className="line-clamp-2 text-[13px] leading-[18px] [overflow-wrap:anywhere] text-[var(--fu-mute,#BDBDBD)]">
            <SkeletonText>{wordsOf(own)}</SkeletonText>
          </span>
        </span>
      </>
    );
  };

  const recentBody = (entry: SavedSearch<State>) => (
    <>
      <Glyph>
        <HistoryIcon size={16} />
      </Glyph>
      <span className="flex min-w-0 flex-1 flex-wrap items-center gap-1">
        {vocabulary.tokens(entry.value).map((token) => (
          <Fragment key={`${token.key}-${token.label}`}>
            <Chip>{token.label}</Chip>{" "}
          </Fragment>
        ))}
      </span>
    </>
  );

  const countCell = (entry: SavedSearch<State>) => (
    <span aria-hidden="true" className="flex shrink-0 items-center ps-2">
      {pill(countOf(vocabulary, items, entry.value))}
    </span>
  );

  const forget = (entry: SavedSearch<State>, kind: "saved" | "recent") => {
    const node = document.getElementById(rowId(kind, entry.id));
    if (node && !reducedMotion()) {
      const body = (
        <>
          {kind === "saved" ? savedBody(entry) : recentBody(entry)}
          {countCell(entry)}
        </>
      );
      setLeaving({ key: `${entry.id}-${Date.now()}`, top: node.offsetTop, height: node.offsetHeight, body });
    }
    setSaid(`Removed ${entry.name ?? wordsOf(vocabulary.tokens(entry.value))}`);
    onForget(entry.id);
  };

  const save = (target: State) => {
    const name = nameOf(vocabulary.tokens(target));
    setSaid(`Saved as ${name}`);
    onSave(target, name);
  };

  const pickRow = (entry: SavedSearch<State>, kind: "saved" | "recent"): OwnRow<State> => ({
    id: rowId(kind, entry.id),
    onSelect: () => onChange(entry.value),
    closes: true,
    onRemove: () => forget(entry, kind),
    preview: entry.value,
  });

  const spoken = (entry: SavedSearch<State>) => {
    const own = vocabulary.tokens(entry.value).map((token) => token.label).join(", ");
    return `${entry.name ? `${entry.name}: ` : ""}${own}, ${countLabel(countOf(vocabulary, items, entry.value))}`;
  };

  let rows: OwnRow<State>[];
  let render: (option: (id: string) => OwnRowProps) => ReactNode;

  if (!sig) {
    rows = [...saved.map((entry) => pickRow(entry, "saved")), ...recents.map((entry) => pickRow(entry, "recent"))];
    // Lists still on their way: stand-in rows hold their place under the headings.
    const standing = loading && rows.length === 0;
    const words = placeholderLabels(LOADING_SAVED + LOADING_RECENT * 2);
    render = (option) => (
      <div ref={drawn}>
        {leaving && (
          <Leaving key={leaving.key} top={leaving.top} height={leaving.height} onDone={() => setLeaving((now) => (now?.key === leaving.key ? null : now))}>
            {leaving.body}
          </Leaving>
        )}
        <div role="group" aria-label="Saved searches, Delete removes one">
          <p data-flip="saved-title" className={TITLE}>
            Saved
          </p>
          {standing &&
            words.slice(0, LOADING_SAVED).map((name, i) => (
              <div key={i} role="option" aria-selected={false} className="relative flex min-h-[52px] items-center gap-3 rounded-[12px] py-2 pe-3 ps-2">
                <Glyph tone="accent">
                  <StarIcon size={16} className="fill-current" />
                </Glyph>
                <span className="min-w-0 flex-1">
                  <span className="block text-[15px] leading-5 font-medium">
                    <SkeletonText>{name}</SkeletonText>
                  </span>{" "}
                  <span className="block text-[13px] leading-[18px]">
                    <SkeletonText>{`${words[i + 1]} · ${words[i + 2]}`}</SkeletonText>
                  </span>
                </span>
                <span aria-hidden="true" className="flex shrink-0 items-center ps-2">
                  <CountPill count={0} />
                </span>
              </div>
            ))}
          {saved.length === 0 && !standing && (
            <p data-flip="saved-empty" className={EMPTY}>
              Save a search to keep it here.
            </p>
          )}
          {saved.map((entry) => (
            <div
              key={entry.id}
              {...option(rowId("saved", entry.id))}
              data-flip={signatureOf(vocabulary, entry.value)}
              aria-label={spoken(entry)}
              className="group/row relative flex min-h-[52px] cursor-pointer items-center gap-3 rounded-[12px] py-2 pe-3 ps-2"
            >
              {savedBody(entry)}{" "}
              <span className="flex shrink-0 items-center">
                <RowActions width="one">
                  <RowAction tip="Remove" onPress={() => forget(entry, "saved")}>
                    <XIcon size={16} />
                  </RowAction>
                </RowActions>
                {countCell(entry)}
              </span>
            </div>
          ))}
        </div>
        <div role="group" aria-label="Recent searches, Delete removes one">
          <p data-flip="recent-title" className={cn(TITLE, "mt-1")}>
            Recent
          </p>
          {standing &&
            Array.from({ length: LOADING_RECENT }, (_, i) => (
              <div key={i} role="option" aria-selected={false} className="relative flex min-h-11 items-center gap-3 rounded-[12px] py-1.5 pe-3 ps-2">
                <Glyph>
                  <HistoryIcon size={16} />
                </Glyph>
                <span className="flex min-w-0 flex-1 flex-wrap items-center gap-1">
                  {words.slice(LOADING_SAVED + i * 2, LOADING_SAVED + i * 2 + 2).map((name) => (
                    <Chip key={name}>{name}</Chip>
                  ))}
                </span>
                <span aria-hidden="true" className="flex shrink-0 items-center ps-2">
                  <CountPill count={0} />
                </span>
              </div>
            ))}
          {recents.length === 0 && !standing && (
            <p data-flip="recent-empty" className={EMPTY}>
              Your searches show here.
            </p>
          )}
          {recents.map((entry) => (
            <div
              key={entry.id}
              {...option(rowId("recent", entry.id))}
              data-flip={signatureOf(vocabulary, entry.value)}
              aria-label={spoken(entry)}
              className="group/row relative flex min-h-11 cursor-pointer items-center gap-3 rounded-[12px] py-1.5 pe-3 ps-2"
            >
              {recentBody(entry)}{" "}
              <span className="flex shrink-0 items-center">
                <RowActions width="two">
                  <RowAction tip="Save" onPress={() => save(entry.value)}>
                    <StarIcon size={16} className="fill-transparent transition-[fill] duration-150 group-hover/act:fill-current motion-reduce:transition-none" />
                  </RowAction>
                  <RowAction tip="Remove" onPress={() => forget(entry, "recent")}>
                    <XIcon size={16} />
                  </RowAction>
                </RowActions>
                {countCell(entry)}
              </span>
            </div>
          ))}
        </div>
      </div>
    );
  } else {
    rows = savedNow ? [] : [{ id: saveId, onSelect: () => save(value) }];
    render = (option) => (
      <div ref={drawn} className="mb-1.5 border-b border-[var(--fu-line,#404040)] pb-1.5">
        {savedNow ? (
          <div className="flex min-h-[52px] items-center gap-3 py-2 pe-3 ps-2">
            <Glyph tone="accent">
              <CheckIcon
                size={16}
                strokeWidth={2.5}
                className={cn(
                  // The path is about 23 units long; it draws from the short leg up as the line appears.
                  "[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:0] [&_path]:transition-[stroke-dashoffset] [&_path]:duration-500 motion-reduce:[&_path]:transition-none",
                  "[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] starting:[&_path]:[stroke-dashoffset:-23]",
                )}
              />
            </Glyph>
            <span className="min-w-0 flex-1">
              <span className="block truncate text-[15px] leading-5 text-[var(--fu-mute,#BDBDBD)]">
                Saved as <span className="font-medium text-[var(--fu-text,#F8F5F1)]">{savedNow.name ?? nameOf(tokens)}</span>
              </span>
              <span className="block truncate text-[13px] leading-[18px] text-[var(--fu-dim,#929292)]">{wordsOf(tokens)}</span>
            </span>
          </div>
        ) : (
          <div
            {...option(saveId)}
            aria-label={`Save this search: ${tokens.map((token) => token.label).join(", ")}`}
            className="group/row relative flex min-h-[52px] cursor-pointer items-center gap-3 rounded-[12px] py-2 pe-3 ps-2"
          >
            <Glyph tone="accent">
              <StarIcon size={16} />
            </Glyph>
            <span className="min-w-0 flex-1">
              <span className="block truncate text-[15px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)]">Save this search</span>
              <span className="block truncate text-[13px] leading-[18px] text-[var(--fu-mute,#BDBDBD)]">{wordsOf(tokens)}</span>
            </span>
          </div>
        )}
      </div>
    );
  }

  return (
    <div
      ref={root}
      className={cn("w-full", className)}
      onBlur={(event) => {
        onBlur?.(event);
        if (root.current?.contains(event.relatedTarget) || !sig || sig === reported.current) return;
        reported.current = sig;
        onSearch(value);
      }}
    >
      <SentenceSearch
        vocabulary={vocabulary}
        items={items}
        value={value}
        onChange={onChange}
        open={open}
        onOpenChange={setOpen}
        countLabel={countLabel}
        locale={locale}
        {...(formatCount && { formatCount })}
        status={status}
        errorText={errorText}
        emptyRows={{
          rows,
          render,
          replace: !sig,
          ...(!sig && {
            emptyText,
            keys: [
              { key: "↑↓", label: "Move" },
              { key: "Enter", label: "Search" },
              { key: "Del", label: "Remove" },
            ],
          }),
        }}
        {...props}
      />
      <p aria-live="polite" className="sr-only">
        {said}
      </p>
    </div>
  );
}
```

### 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/sentence.ts

```ts
const MOST_ROWS = 7;
const FACET_ROWS = 4;
const COMPLETIONS = 3;
const CHIP_SEPARATOR = ", ";

// Reads a typed sentence into filters, and suggests what to add next.
//
// Nothing here knows the items: a Vocabulary says which words mean what. Terms are the named values
// ("SUV", "Toyota", "Blue"); rules are the phrases with numbers or meaning ("under 30k", "7 seats",
// "good in snow"). Swap the vocabulary and the same reader works for houses, jobs or shoes.
//
// Names match whole words in any script. Two limits: a plural is read as the name plus "s" (English), and a
// state is compared with JSON.stringify, so keep it plain data (no Set or Map).

/** A named value a word can set, e.g. the body style SUV. */
export type Term<State> = {
  /** Unique, and equal to the key of the token it adds. */
  key: string;
  label: string;
  /** The filter it belongs to, shown beside a suggestion: "Body style". */
  group: string;
  /** Other words for it: "crossover" for SUV. Plurals are read without listing them. */
  names?: readonly string[];
  /** Shown beside a suggestion instead of the group, e.g. a model's make. */
  hint?: string;
  /** Any CSS color, drawn as a dot beside the suggestion. */
  swatch?: string;
  /** A misspelt word close to this name is read as it: "telsa" as Tesla. */
  spellcheck?: boolean;
  /** The key of the term it narrows, e.g. a model's make. It completes a sentence that names that make, or none. */
  parent?: string;
  add: (state: State) => State;
};

/** One removable token in the box: a filter that is set. */
export type Token<State> = {
  /** Equal to the key of the term that adds it, when there is one. */
  key: string;
  label: string;
  /** The filter it belongs to: "Price". */
  group: string;
  hint?: string;
  swatch?: string;
  clear: (state: State) => State;
};

export type RuleContext<Item, State> = {
  items: readonly Item[];
  /** What is already set before the sentence, so "family" after a Sedan token adds nothing. */
  context: State;
  vocabulary: Vocabulary<Item, State>;
};

/** A phrase read before any name, in list order. Its words are used up as soon as it matches. */
export type Rule<Item, State> = {
  pattern: RegExp;
  read?: (draft: State, match: RegExpMatchArray, ctx: RuleContext<Item, State>) => State;
  /** Runs after every name is read, for a phrase that depends on the rest, e.g. "cheap truck". */
  finish?: (draft: State, ctx: RuleContext<Item, State>) => State;
};

/** A filter offered by name when the box is empty, or when its word is typed ("price"). */
export type Facet<Item, State> = {
  title: string;
  words: readonly string[];
  options: (state: State, items: readonly Item[]) => readonly Term<State>[];
  isSet: (state: State) => boolean;
  /** Options keep their own order (budgets, years); otherwise the most items come first. */
  stepped?: boolean;
};

export type Vocabulary<Item, State> = {
  empty: State;
  matches: (item: Item, state: State) => boolean;
  /** Adds `extra` to `base`; a filter with one answer takes the newer one. */
  merge: (base: State, extra: State) => State;
  /** The tokens for a state, in a fixed order. */
  tokens: (state: State) => Token<State>[];
  terms: readonly Term<State>[];
  rules?: readonly Rule<Item, State>[];
  facets?: readonly Facet<Item, State>[];
  /** Facet titles offered on an empty box with nothing set, then once something is set. */
  firstUp?: readonly string[];
  nextUp?: readonly string[];
  /** Suggestions for a typed number, such as "2020" or "under 30k". */
  numbers?: (typed: string, state: State, items: readonly Item[]) => Term<State>[];
  /** Words that say nothing, so leaving them unread is not worth a mention. */
  filler?: readonly string[];
  /** Everyday words one slip from a name, never fixed into it: "keep" (Jeep), "fold" (Ford). */
  notTypos?: readonly string[];
  /** Words that are never a name on their own, though a name starts with them: "car" and "cargo van". */
  stopNames?: readonly string[];
  /** Groups dropped last when nothing matches, as they name the thing itself: make and model. */
  dropLast?: readonly string[];
  /** describe() of a state with nothing set. */
  everything?: string;
};

/** A token and the words it was read from. */
export type ReadToken<State> = Token<State> & { from: string[] };

export type Correction = { word: string; name: string };

export type Reading<State> = {
  /** What the words alone say. Merge it into what is set with the vocabulary's merge. */
  value: State;
  /** In the order their words were typed. */
  tokens: ReadToken<State>[];
  /** Words it could not use, filler left out. */
  left: string[];
  /** Misspelt names it fixed. Empty unless read with fixTypos. */
  corrections: Correction[];
  /** The sentence it read, after fixes. */
  text: string;
};

export type Suggestion<State> = {
  key: string;
  label: string;
  hint?: string;
  swatch?: string;
  count: number;
  next: State;
  /** Words of the sentence the row leaves unread. */
  left?: string[];
  /** Keys of the tokens it adds, in the order their words were typed. */
  order: string[];
};

export type SuggestionGroup<State> = { title?: string; rows: Suggestion<State>[] };


export const fold = (text: string) =>
  text
    .toLowerCase()
    .normalize("NFD")
    .replace(/\p{M}/gu, "")
    .replace(/\s+/g, " ")
    .trim();

const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

// "rav4" reads "rav 4" and "rav-4"; a name ending in a letter may carry digits, as "rx350" does.
function namePattern(name: string) {
  const spelled = escape(fold(name))
    .replace(/[-\s]+/g, "[- ]?")
    .replace(/([a-z])(\d)/g, "$1[- ]?$2");
  const tail = /\p{L}$/u.test(name) ? "(?:s|\\d+[a-z]?)?" : "s?";
  return new RegExp(`(^|[^\\p{L}\\p{N}])${spelled}${tail}(?![\\p{L}\\p{N}])`, "u");
}

const namesOf = <State>(term: Term<State>) => [fold(term.label), ...(term.names ?? []).map(fold)];

/**
 * The start of a folded name that namePattern keeps letter for letter: up to its first hyphen or space, or the first
 * digit after a letter, where the pattern lets a gap in. A sentence without it cannot hold the name.
 */
function leadOf(name: string) {
  for (let i = 0; i < name.length; i++) {
    const ch = name[i];
    if (ch === "-" || /\s/.test(ch) || (i > 0 && /\d/.test(ch) && /[a-z]/.test(name[i - 1]))) return name.slice(0, i);
  }
  return name;
}

type Compiled<State> = { term: Term<State>; lead: string; length: number; readonly pattern: RegExp };
const compiled = new WeakMap<readonly Term<unknown>[], Compiled<unknown>[]>();

// A vocabulary holds a few hundred names and a sentence a handful of them, so a name's pattern is built when a
// sentence first holds its lead, not for every name up front.
function compile<State>(term: Term<State>, name: string): Compiled<State> {
  let pattern: RegExp | undefined;
  return {
    term,
    lead: leadOf(name),
    length: name.length,
    get pattern() {
      return (pattern ??= namePattern(name));
    },
  };
}

// Longest names first, so "Mustang Mach-E" wins over "Mustang" and "plug-in hybrid" over "hybrid".
function patternsOf<State>(terms: readonly Term<State>[]): Compiled<State>[] {
  const hit = compiled.get(terms as readonly Term<unknown>[]);
  if (hit) return hit as Compiled<State>[];
  const list = terms
    .flatMap((term) => namesOf(term).map((name) => compile(term, name)))
    .sort((a, b) => b.length - a.length);
  compiled.set(terms as readonly Term<unknown>[], list as Compiled<unknown>[]);
  return list;
}

const signatureOf = <State>(tokens: readonly Token<State>[]) =>
  tokens
    .map((token) => `${token.key}:${token.label}`)
    .sort()
    .join("|");

export const countOf = <Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], state: State) => {
  let n = 0;
  for (const item of items) if (vocabulary.matches(item, state)) n++;
  return n;
};

export const hasAny = <Item, State>(vocabulary: Vocabulary<Item, State>, state: State) => vocabulary.tokens(state).length > 0;

/** The tokens as words: "Blue, SUV, Under $30k". */
export function describe<Item, State>(vocabulary: Vocabulary<Item, State>, state: State) {
  const labels = vocabulary.tokens(state).map((token) => token.label);
  return labels.length ? labels.join(CHIP_SEPARATOR) : (vocabulary.everything ?? "Everything");
}

// Swapped letters count as one slip, so "telsa" is one edit from "tesla".
function editDistance(a: string, b: string) {
  const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
      if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
    }
  }
  return rows[a.length][b.length];
}

/**
 * The name a misspelt word is closest to: 4+ letters starting with the same letter, one slip allowed, two from
 * 7 letters. On a tie the longer name wins. Words in `notTypos` are never fixed.
 */
export function nearestName<State>(terms: readonly Term<State>[], word: string, notTypos: readonly string[] = []) {
  const typed = fold(word);
  if (typed.length < 4 || notTypos.includes(typed)) return null;
  const allowed = typed.length >= 7 ? 2 : 1;
  let best: { term: Term<State>; edits: number } | null = null;
  for (const term of terms) {
    if (!term.spellcheck) continue;
    const name = fold(term.label);
    if (name[0] !== typed[0] || Math.abs(name.length - typed.length) > allowed) continue;
    const edits = editDistance(typed, name);
    if (edits > allowed) continue;
    if (!best || edits < best.edits || (edits === best.edits && term.label.length > best.term.label.length)) best = { term, edits };
  }
  return best?.term ?? null;
}

const inSentenceOrder = <T extends { key: string }>(tokens: T[], places: ReadonlyMap<string, number>) =>
  tokens
    .map((token, i) => ({ token, at: places.get(token.key) ?? Number.MAX_SAFE_INTEGER, i }))
    .sort((a, b) => a.at - b.at || a.i - b.i)
    .map(({ token }) => token);

function parse<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], text: string, context: State) {
  const ctx: RuleContext<Item, State> = { items, context, vocabulary };
  const sources = new Map<string, string[]>();
  // Where each token's first word sits, so tokens follow the order the words were typed in.
  const places = new Map<string, number>();
  let draft = vocabulary.empty;
  let rest = ` ${fold(text)} `;

  const note = (before: Set<string>, words: string, at: number) => {
    for (const token of vocabulary.tokens(draft)) {
      if (before.has(token.key)) continue;
      sources.set(token.key, [...(sources.get(token.key) ?? []), words]);
      if (!places.has(token.key)) places.set(token.key, at);
    }
  };

  // Used words become spaces of the same length, so places stay true to the sentence.
  const take = (pattern: RegExp, use: (match: RegExpMatchArray) => State) => {
    const match = rest.match(pattern);
    if (!match) return null;
    const at = rest.search(pattern);
    const words = match[0].replace(/^[^\p{L}\p{N}$]+|[^\p{L}\p{N}]+$/gu, "");
    const before = new Set(vocabulary.tokens(draft).map((token) => token.key));
    draft = use(match);
    note(before, words, at);
    rest = rest.replace(pattern, (found) => " ".repeat(found.length));
    return { words, at };
  };

  const finishing: { rule: Rule<Item, State>; words: string; at: number }[] = [];
  for (const rule of vocabulary.rules ?? []) {
    const taken = take(rule.pattern, (match) => (rule.read ? rule.read(draft, match, ctx) : draft));
    if (taken && rule.finish) finishing.push({ rule, ...taken });
  }
  // A name typed twice is read twice, so its second copy is not reported as unused.
  for (const name of patternsOf(vocabulary.terms)) {
    // What is left of the sentence must hold the name's lead for its pattern to match, so most names stop here.
    if (!rest.includes(name.lead)) continue;
    while (take(name.pattern, () => name.term.add(draft)));
  }
  for (const { rule, words, at } of finishing) {
    const before = new Set(vocabulary.tokens(draft).map((token) => token.key));
    draft = rule.finish!(draft, ctx);
    note(before, words, at);
  }

  const filler = new Set(vocabulary.filler ?? []);
  const left = rest.split(/[^\p{L}\p{N}'-]+/u).filter((word) => word && !filler.has(word) && !/^\d+$/.test(word));
  const tokens = inSentenceOrder(
    vocabulary.tokens(draft).map((token) => ({ ...token, from: sources.get(token.key) ?? [] })),
    places,
  );
  return { value: draft, tokens, left, places };
}

/** The sentence with misspelt names fixed. A word still being typed (`typing`) is left alone, since it is short, not wrong. */
function fixTypos<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], text: string, typing: string | null) {
  const corrections: Correction[] = [];
  const fixed = parse(vocabulary, items, text, vocabulary.empty)
    .left.filter((word) => word !== typing)
    .reduce((sentence, word) => {
      const near = nearestName(vocabulary.terms, word, vocabulary.notTypos);
      if (!near) return sentence;
      corrections.push({ word, name: near.label });
      return sentence.replace(new RegExp(`(^|[^\\p{L}])${escape(word)}(?![\\p{L}])`, "iu"), `$1${near.label}`);
    }, text);
  return { text: fixed, corrections };
}

/**
 * Reads a sentence: "blue suv under 30k" gives Blue, SUV and Under $30k. `context` is what is already set, so words
 * typed after a token read as they would in one sentence. With fixTypos, misspelt names are fixed first.
 */
export function readSentence<Item, State>(
  vocabulary: Vocabulary<Item, State>,
  items: readonly Item[],
  text: string,
  { context = vocabulary.empty, fixTypos: fix = false }: { context?: State; fixTypos?: boolean } = {},
): Reading<State> {
  const { text: sentence, corrections } = fix ? fixTypos(vocabulary, items, text, null) : { text, corrections: [] };
  const { value, tokens, left } = parse(vocabulary, items, sentence, context);
  return { value, tokens, left, corrections, text: sentence };
}

const priced = <Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], term: Term<State>, state: State): Suggestion<State> => {
  const next = term.add(state);
  const before = new Set(vocabulary.tokens(state).map((token) => token.key));
  const order = vocabulary.tokens(next).filter((token) => !before.has(token.key)).map((token) => token.key);
  const row = { key: term.key, label: term.label, hint: term.hint ?? term.group, count: countOf(vocabulary, items, next), next, order };
  return term.swatch === undefined ? row : { ...row, swatch: term.swatch };
};

function uniqueResults<Item, State>(vocabulary: Vocabulary<Item, State>, rows: Suggestion<State>[]) {
  const seen = new Set<string>();
  return rows.filter((row) => {
    const result = signatureOf(vocabulary.tokens(row.next));
    if (seen.has(result)) return false;
    seen.add(result);
    return true;
  });
}

const changes = <State>(row: Suggestion<State>, state: State) => JSON.stringify(row.next) !== JSON.stringify(state);

function rankOf<State>(term: Term<State>, typed: string) {
  const names = namesOf(term);
  if (names.includes(typed)) return 0;
  if (names.some((name) => name.startsWith(typed))) return 1;
  if (names.some((name) => name.split(/[\s-]+/).some((word) => word.startsWith(typed)))) return 2;
  if (typed.length >= 3 && names.some((name) => name.includes(typed))) return 3;
  return null;
}

// After a make, a half word is likelier one of its models than a second make, which always has more items.
const ownChild = <Item, State>(vocabulary: Vocabulary<Item, State>, term: Term<State>, state: State) =>
  term.parent && vocabulary.tokens(state).some((token) => token.key === term.parent) ? 1 : 0;

/** One row for a reading, named by the tokens it would add, so the row says exactly what picking it does. */
function readingRow<Item, State>(
  vocabulary: Vocabulary<Item, State>,
  items: readonly Item[],
  key: string,
  state: State,
  next: State,
  fixed: boolean,
  left?: string[],
  places: ReadonlyMap<string, number> = new Map(),
): Suggestion<State> | null {
  const before = new Set(vocabulary.tokens(state).map((token) => `${token.key}:${token.label}`));
  const added = inSentenceOrder(
    vocabulary.tokens(next).filter((token) => !before.has(`${token.key}:${token.label}`)),
    places,
  );
  if (!added.length) return null;
  const one = added.length === 1 ? added[0] : undefined;
  return {
    key,
    label: added.map((token) => token.label).join(CHIP_SEPARATOR),
    hint: fixed ? "Did you mean" : one ? (one.hint ?? one.group) : "Add all",
    ...(one?.swatch !== undefined && { swatch: one.swatch }),
    count: countOf(vocabulary, items, next),
    next,
    ...(left?.length ? { left } : {}),
    order: added.map((token) => token.key),
  };
}

// Names the typed words end in the start of. Several words may spell the start of one name, as "mustang mach" does.
function namesStarted<State>(terms: readonly Term<State>[], words: string[]) {
  // No run of words longer than the longest name can start one, so only the last few words are tried.
  const longest = patternsOf(terms)[0]?.length ?? 0;
  let first = words.length;
  while (first > 0 && fold(words.slice(first - 1).join(" ")).length <= longest) first--;
  return terms.flatMap((term) => {
    const at = words.findIndex((_, index) => {
      if (index < first) return false;
      const rank = rankOf(term, fold(words.slice(index).join(" ")));
      return rank !== null && rank <= (index === words.length - 1 ? 2 : 1);
    });
    if (at < 0) return [];
    const tail = words.slice(at).join(" ");
    return [{ term, tail, span: words.length - at, rank: rankOf(term, fold(tail)) ?? 2 }];
  });
}

/** What Enter does with the words as typed: the whole reading, or that reading finished with a name the last word starts. */
function leadRows<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], text: string, state: State) {
  const words = /\S$/.test(text) ? text.trim().split(/\s+/) : [];
  const starts = namesStarted(vocabulary.terms, words);
  const half = starts.length ? words[words.length - 1] : null;
  const fixed = fixTypos(vocabulary, items, text, half ? fold(half) : null).text.trim();
  const whole = parse(vocabulary, items, fixed, state);
  const corrected = fixed !== text.trim();
  const reading = readingRow(vocabulary, items, "reading", state, vocabulary.merge(state, whole.value), corrected, whole.left, whole.places);

  // A last word the reading has no use for is still being typed. One it used, like the "car" of "electric car", is finished.
  const skipsHalf = half !== null && fixed.endsWith(half) && whole.left.includes(fold(half));
  if (!skipsHalf) return reading ? [reading] : [];

  const finished = uniqueResults(
    vocabulary,
    starts
      .flatMap(({ term, tail, span, rank }) => {
        if (!fixed.endsWith(tail)) return [];
        const head = fixed.slice(0, -tail.length).trim();
        // A single word that starts a name is already a row of its own.
        if (!head && span === 1) return [];
        const said = parse(vocabulary, items, head, vocabulary.empty).value;
        const saidTokens = vocabulary.tokens(said);
        if (head && !saidTokens.length) return [];
        if (term.parent) {
          const family = vocabulary.terms.find((other) => other.key === term.parent)?.group;
          if (saidTokens.some((token) => token.group === family) && !saidTokens.some((token) => token.key === term.parent)) return [];
        }
        // Read as one sentence, so a word like "cheap" sizes its budget to the finished name.
        const done = parse(vocabulary, items, `${head} ${term.label}`, state);
        const next = vocabulary.merge(state, term.add(done.value));
        const row = readingRow(vocabulary, items, `complete-${term.key}`, state, next, corrected, undefined, done.places);
        return row ? [{ row, span, rank, own: ownChild(vocabulary, term, vocabulary.merge(state, said)) }] : [];
      })
      .sort((a, b) => b.span - a.span || a.rank - b.rank || b.own - a.own || b.row.count - a.row.count)
      .map((entry) => entry.row),
  );
  const live = finished.filter((row) => row.count > 0);
  const completions = live.length ? live.slice(0, COMPLETIONS) : finished.slice(0, 1);
  return [...completions, ...(reading ? [reading] : [])];
}

/** The smallest change to a search that finds nothing which finds something: drop one filter, the newest first, the named thing last. */
function closestRow<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], state: State, dead: State): Suggestion<State> | null {
  const tokens = vocabulary.tokens(dead);
  const had = new Set(vocabulary.tokens(state).map((token) => `${token.key}:${token.label}`));
  const now = signatureOf(vocabulary.tokens(state));
  const last = new Set(vocabulary.dropLast ?? []);
  const singles = tokens
    .map((token) => {
      const next = token.clear(dead);
      const softness = had.has(`${token.key}:${token.label}`) ? 2 : last.has(token.group) ? 3 : 1;
      return { next, count: countOf(vocabulary, items, next), softness };
    })
    .filter((fix) => fix.count > 0 && signatureOf(vocabulary.tokens(fix.next)) !== now)
    .sort((a, b) => a.softness - b.softness || b.count - a.count);
  const deadWords = describe(vocabulary, dead);
  const fix =
    singles.find((option) => describe(vocabulary, option.next) !== deadWords) ??
    singles[0] ??
    tokens
      .flatMap((first, index) =>
        tokens.slice(index + 1).map((second) => {
          const next = second.clear(first.clear(dead));
          return { next, count: countOf(vocabulary, items, next) };
        }),
      )
      .filter((option) => option.count > 0)
      .sort((a, b) => b.count - a.count)[0];
  if (!fix) return null;
  const order = vocabulary.tokens(fix.next).map((token) => token.key);
  return { key: "closest", label: describe(vocabulary, fix.next), hint: "Closest", count: fix.count, next: fix.next, order };
}

// A first row that finds nothing hands Enter to the closest search that finds something, and stays right under it.
function withExit<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], rows: Suggestion<State>[], state: State) {
  const [first, ...rest] = rows;
  if (!first || first.count !== 0) return rows;
  const set = hasAny(vocabulary, state);
  const { swatch: _swatch, ...plain } = first;
  const exact = { ...plain, label: set ? describe(vocabulary, first.next) : first.label, hint: "No matches yet" };
  const exit = closestRow(vocabulary, items, state, first.next);
  return exit ? [exit, exact, ...rest] : [exact, ...rest];
}

function rowsOf<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], facet: Facet<Item, State>, state: State) {
  const rows = facet
    .options(state, items)
    .map((term) => priced(vocabulary, items, term, state))
    .filter((row) => row.count > 0 && changes(row, state));
  return facet.stepped ? rows : rows.sort((a, b) => b.count - a.count);
}

// What is worth asking next. A facet with one answer left, or an answer that keeps every item shown, narrows nothing.
function upNext<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], state: State) {
  const groups: SuggestionGroup<State>[] = [];
  const now = countOf(vocabulary, items, state);
  const names = (hasAny(vocabulary, state) ? vocabulary.nextUp : vocabulary.firstUp) ?? [];
  for (const name of names) {
    if (groups.length === 2) break;
    const facet = vocabulary.facets?.find((f) => f.title === name);
    if (!facet || facet.isSet(state)) continue;
    const rows = rowsOf(vocabulary, items, facet, state).filter((row) => row.count < now);
    if (rows.length < 2) continue;
    groups.push({ title: name, rows: rows.slice(0, groups.length ? FACET_ROWS - 1 : FACET_ROWS).map(({ hint: _hint, ...row }) => row) });
  }
  return groups;
}

/** The suggestion rows for what is typed, or the next filters to add while the box is empty. The first row is what Enter takes. */
export function suggest<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], text: string, state: State): SuggestionGroup<State>[] {
  const typed = fold(text);
  if (!typed) return upNext(vocabulary, items, state);

  const lead = leadRows(vocabulary, items, text, state);
  const numbers = (vocabulary.numbers?.(typed, state, items) ?? []).map((term) => priced(vocabulary, items, term, state));
  const stop = new Set(vocabulary.stopNames ?? []);
  // Ranked first, so only the names that match what is typed are counted against the items.
  const direct = (stop.has(typed) ? [] : vocabulary.terms)
    .flatMap((term) => {
      const rank = rankOf(term, typed);
      return rank === null ? [] : [{ row: priced(vocabulary, items, term, state), rank, own: ownChild(vocabulary, term, state) }];
    })
    .sort((a, b) => a.rank - b.rank || b.own - a.own || b.row.count - a.row.count)
    .map((entry) => entry.row);
  const facets = typed.length < 2 ? [] : (vocabulary.facets ?? []).filter((facet) => facet.words.some((word) => word.startsWith(typed)));
  const fromFacets = facets.flatMap((facet) => rowsOf(vocabulary, items, facet, state).slice(0, FACET_ROWS));

  const byKey = new Map([...numbers, ...direct, ...fromFacets].map((row) => [row.key, row]));
  const found = uniqueResults(vocabulary, [...lead, ...byKey.values()].filter((row) => changes(row, state)));
  // A misspelt name of more than one word, which no single word of it is near.
  const near = found.length ? null : nearestName(vocabulary.terms, typed, vocabulary.notTypos);
  const corrected = near ? readingRow(vocabulary, items, `fixed-${near.key}`, state, near.add(state), true) : null;
  const rows = corrected ? [corrected] : found;

  // The reading leads even when it finds nothing, so the way out can stand on top of it.
  const reading = lead[0] ?? numbers[0];
  const live = rows.filter((row) => row.count > 0 || row.key === reading?.key);
  const shown = uniqueResults(vocabulary, withExit(vocabulary, items, live.length ? live : rows, state)).slice(0, MOST_ROWS);
  return shown.length ? [{ rows: shown }] : [];
}

/** A word typed in full becomes a token on the space after it, unless a longer name could still follow. */
export function wholeWord<Item, State>(vocabulary: Vocabulary<Item, State>, items: readonly Item[], text: string, state: State) {
  const typed = fold(text);
  if (!typed) return null;
  const exact = vocabulary.terms.find((term) => namesOf(term).includes(typed));
  const longer = vocabulary.terms.some((term) => namesOf(term).some((name) => name.startsWith(`${typed} `)));
  return exact && !longer ? priced(vocabulary, items, exact, state) : null;
}

/** The rest of a row's label after what is typed, drawn faintly after the caret. */
export function ghostOf<State>(text: string, row?: Suggestion<State>) {
  if (!row || !text || /\s$/.test(text)) return "";
  // Cut at the folded length: fold drops a leading space and joins double ones, which the overlay still draws.
  const typed = fold(text);
  return fold(row.label).startsWith(typed) ? row.label.slice(typed.length) : "";
}

/** Where the typed part sits in a label. */
export function matchIn(label: string, text: string) {
  const typed = fold(text);
  const at = typed ? fold(label).indexOf(typed) : -1;
  return at < 0 ? null : { at, length: typed.length };
}
```

### components/filters-ui/ui/count-pill.tsx

```tsx
"use client";

import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import { ARRIVING, SKELETON_FILL, useLoading } from "./skeleton";

export type CountPillProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
  count: number;
  /** "default": 20px high, 6px radius. "square": 18px high, 5px radius, 11px text. */
  variant?: "default" | "square";
  /** Selected look: accent fill, --fu-on-accent text. */
  on?: boolean;
  format?: (n: number) => string;
  /** Formats the count when no format is given, e.g. "de-DE" prints 1.234. */
  locale?: string;
  /** A pulsing placeholder of the pill's own size. Default: the nearest StatusFrame's loading state. */
  loading?: boolean;
};

export function CountPill({ count, variant = "default", on = false, format, locale, loading: loadingProp, className, ...props }: CountPillProps) {
  const state = useLoading();
  const loading = loadingProp ?? state.loading;
  const text = (format ?? formatsFor(locale).number)(count);
  return (
    <span
      data-state={on ? "on" : "off"}
      className={cn(
        "inline-flex shrink-0 items-center justify-center font-medium tabular-nums",
        "transition-[background-color,color] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
        variant === "square"
          ? "h-[18px] min-w-5 rounded-[5px] px-[5px] text-[11px] leading-4"
          : "h-5 min-w-[22px] rounded-[6px] px-1.5 text-[12px] leading-4",
        loading
          ? SKELETON_FILL
          : on
            ? "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)]"
            : variant === "square"
              ? "bg-[var(--fu-pill-square,#333333)] text-[var(--fu-pill-text,#C8C8C8)]"
              : "bg-[var(--fu-pill,rgb(255_255_255/0.1))] text-[var(--fu-pill-text,#C8C8C8)]",
        className,
      )}
      {...props}
    >
      {/* While loading, the number holds the pill's width unseen; when it arrives it fades in once. */}
      {loading ? (
        <span key="skeleton" className="invisible">
          {text}
        </span>
      ) : state.arriving ? (
        <span key="arrived" className={ARRIVING}>
          {text}
        </span>
      ) : (
        text
      )}
    </span>
  );
}
```

### components/filters-ui/ui/skeleton.tsx

```tsx
"use client";

import { createContext, useContext, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";

/** What StatusFrame tells the pieces under it: draw placeholders, or the data has just arrived and fades in once. */
export type LoadingState = { loading: boolean; arriving: boolean };

export const LoadingContext = createContext<LoadingState>({ loading: false, arriving: false });

/** The loading state of the nearest StatusFrame. Outside one, nothing is loading. */
export const useLoading = () => useContext(LoadingContext);

/**
 * The placeholder fill: --fu-skeleton, pulsing to half of it every 2s (Tailwind's animate-pulse). It holds still when
 * reduced motion is asked for, and turns to the system's grey text colour in forced colours, so it never vanishes.
 */
export const SKELETON_FILL =
  "animate-pulse bg-[var(--fu-skeleton,rgb(255_255_255/0.12))] in-data-[state=on]:bg-[var(--fu-skeleton-on,rgb(143_170_255/0.3))] motion-reduce:animate-none forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]";

/** Content that has just replaced a placeholder: it fades in once over 300ms as it is inserted, and never again. */
export const ARRIVING = "transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none";

export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;

/**
 * A pulsing placeholder block with no size of its own: give it the size and corners of what it stands for, from the
 * same classes, e.g. "h-5 min-w-[22px] rounded-[6px]" for a count pill. Hidden from screen readers; the StatusFrame
 * around it says "Loading" once.
 */
export function Skeleton({ className, ...props }: SkeletonProps) {
  return <span aria-hidden="true" data-skeleton="" className={cn("block rounded-[6px]", SKELETON_FILL, className)} {...props} />;
}

export type SkeletonTextProps = {
  children: ReactNode;
  /** Draws the placeholder. Default: the nearest StatusFrame's loading state. */
  loading?: boolean;
  /** Classes for the placeholder's box while loading. */
  className?: string;
};

/**
 * Words that draw as a rounded bar while loading. The words stay in the layout, unseen, so the bar is exactly as wide
 * and as many lines tall as they are, and nothing moves when they arrive; then they fade in once.
 */
export function SkeletonText({ children, loading, className }: SkeletonTextProps) {
  const state = useLoading();
  if (loading ?? state.loading) {
    return (
      <span key="skeleton" className={cn("relative inline-block max-w-full align-top", className)}>
        <span className="invisible">{children}</span>
        <Skeleton className="absolute inset-x-0 inset-y-[0.22lh] rounded-[4px]" />
      </span>
    );
  }
  if (state.arriving) {
    return (
      <span key="arrived" className={ARRIVING}>
        {children}
      </span>
    );
  }
  return <>{children}</>;
}

/**
 * Stand-in names for a list whose options have not come yet: a mix of lengths, so the placeholders do not read as a
 * grid. Never shown; only their widths are.
 */
export function placeholderLabels(count: number): string[] {
  const words = ["Placeholder", "Short", "A longer name", "Medium one", "Tiny", "Another name", "Middle", "Fairly long one"];
  return Array.from({ length: count }, (_, i) => words[i % words.length]);
}
```

### components/filters-ui/ui/icons.tsx

```tsx
import type { ReactNode, SVGProps } from "react";

/*
 * Icon paths from Lucide (https://lucide.dev), ISC License.
 * Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT).
 * All other copyright (c) for Lucide are held by Lucide Contributors 2022.
 * Permission to use, copy, modify, and/or distribute this software for any purpose with or
 * without fee is hereby granted, provided that the above copyright notice and this permission
 * notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
 * SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

export type IconProps = Omit<SVGProps<SVGSVGElement>, "children"> & { size?: number };

function Icon({ size = 20, strokeWidth = 2, children, ...props }: IconProps & { children: ReactNode }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={strokeWidth}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
      {...props}
    >
      {children}
    </svg>
  );
}

export function ChevronDownIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="m6 9 6 6 6-6" />
    </Icon>
  );
}

export function XIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M18 6 6 18" />
      <path d="m6 6 12 12" />
    </Icon>
  );
}

export function CheckIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M20 6 9 17l-5-5" />
    </Icon>
  );
}

export function SearchIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <circle cx="11" cy="11" r="8" />
      <path d="m21 21-4.3-4.3" />
    </Icon>
  );
}

export function ArrowUpRightIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M7 7h10v10" />
      <path d="M7 17 17 7" />
    </Icon>
  );
}

export function PlusIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M5 12h14" />
      <path d="M12 5v14" />
    </Icon>
  );
}

export function CopyIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
      <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
    </Icon>
  );
}

export function SlidersIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M21 4h-7" />
      <path d="M10 4H3" />
      <path d="M21 12h-9" />
      <path d="M8 12H3" />
      <path d="M21 20h-5" />
      <path d="M12 20H3" />
      <path d="M14 2v4" />
      <path d="M8 10v4" />
      <path d="M16 18v4" />
    </Icon>
  );
}

export function ArrowRightIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M5 12h14" />
      <path d="m12 5 7 7-7 7" />
    </Icon>
  );
}

export function SearchXIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="m13.5 8.5-5 5" />
      <path d="m8.5 8.5 5 5" />
      <circle cx="11" cy="11" r="8" />
      <path d="m21 21-4.3-4.3" />
    </Icon>
  );
}

export function StarIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
    </Icon>
  );
}

export function HistoryIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
      <path d="M3 3v5h5" />
      <path d="M12 7v5l4 2" />
    </Icon>
  );
}

export function ListTreeIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <path d="M21 12h-8" />
      <path d="M21 6H8" />
      <path d="M21 18h-8" />
      <path d="M3 6v4c0 1.1.9 2 2 2h3" />
      <path d="M3 10v6c0 1.1.9 2 2 2h3" />
    </Icon>
  );
}

export function CircleAlertIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <circle cx="12" cy="12" r="10" />
      <path d="M12 8v4" />
      <path d="M12 16h.01" />
    </Icon>
  );
}
```

### components/filters-ui/filters/sentence-search.tsx

```tsx
"use client";

import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type HTMLAttributes, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { countOf, ghostOf, matchIn, readSentence, suggest, wholeWord, type Correction, type Suggestion, type Vocabulary } from "../lib/sentence";
import { CountPill } from "../ui/count-pill";
import { SearchIcon, XIcon } from "../ui/icons";
import { placeholderLabels, Skeleton, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";

/** A row of your own in the list while the box is empty, such as a saved search. */
export type OwnRow<State> = {
  /** Unique on the page: the row element's id. */
  id: string;
  /** Enter, or a press. */
  onSelect: () => void;
  /** Picking it closes the list. */
  closes?: boolean;
  /** Delete or Backspace while it is highlighted. */
  onRemove?: () => void;
  /** The value it sets: its tokens show faintly in the box, and its count at the foot, while it is highlighted. */
  preview?: State;
};

/** Spread on a row's element: its id, role, highlight and press. */
export type OwnRowProps = { id: string; role: "option"; "aria-selected": boolean; onPointerMove: () => void; onClick: () => void };

export type OwnRows<State> = {
  rows: readonly OwnRow<State>[];
  /** Draws the rows; spread option(row.id) on each row's element. Keep the elements out of positioned wrappers, so the highlight can find them. */
  render: (option: (id: string) => OwnRowProps) => ReactNode;
  /** Shown in place of the suggestions; otherwise above them. */
  replace?: boolean;
  /** Key hints for the foot of the list while these rows show. */
  keys?: readonly { key: string; label: string }[];
  /** A quiet line in the list's place while there are no rows, e.g. "No recent searches yet" */
  emptyText?: string;
};

export type SentenceSearchProps<Item, State> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
  Omit<StateProps, "emptyText"> & {
  /** The words it knows: names, phrases and how each one changes the value. */
  vocabulary: Vocabulary<Item, State>;
  /** Every item, for the counts. */
  items: readonly Item[];
  value: State;
  onChange: (value: State) => void;
  /** Accessible name of the field. */
  label?: string;
  /** Shown while nothing is set. Defaults to the label. */
  placeholder?: string;
  /** Shown once a token is in the box. */
  addPlaceholder?: string;
  /** The button that reads the whole sentence, shown when the box is 480px or wider. */
  submitLabel?: string;
  formatCount?: (n: number) => string;
  /** Screen-reader words for the result count and each suggestion's count: "6 results". */
  countLabel?: (n: number) => string;
  /** Formats the counts and their words by default, e.g. "de-DE". Default "en-US". */
  locale?: string;
  /** Text in the field on first render. */
  defaultText?: string;
  /** Suggestions open on first render. */
  defaultOpen?: boolean;
  /** The row highlighted on first render, by position, e.g. for a still picture of an open list. */
  defaultHighlight?: number;
  /** Focus the field on first render. */
  autoFocus?: boolean;
  /** Controlled open state of the list, with onOpenChange. */
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** Rows of your own while the box is empty, such as recent searches: in place of the suggestions, or above them. */
  emptyRows?: OwnRows<State>;
};

const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";
/** A 44px tap area on touch screens around a smaller drawn control. */
const TAP = "relative pointer-coarse:after:absolute pointer-coarse:after:-inset-[4px] pointer-coarse:after:rounded-[inherit]";
const quote = (words: readonly string[]) => words.map((word) => `“${word}”`).join(", ");
/** 40px for one line: a 22px line and 9px above and below. A longer name wraps and the row grows. */
const ROW = "relative flex min-h-10 items-center gap-2.5 rounded-[12px] px-3 py-[9px] text-[15px] leading-[22px]";
/** Stand-in rows while the counts load and no suggestion can be worked out yet. */
const LOADING_ROWS = 4;

function Label({ label, typed }: { label: string; typed: string }) {
  const hit = matchIn(label, typed);
  return (
    <span
      className={cn(
        "min-w-0 [overflow-wrap:anywhere]",
        // On the highlighted row the dim letters lift to mute, so they keep 4.5:1 against it.
        hit ? "text-[var(--fu-dim,#929292)] group-aria-selected/opt:text-[var(--fu-mute,#BDBDBD)]" : "text-[var(--fu-text,#F8F5F1)]",
      )}
    >
      <SkeletonText>
        {hit ? (
          <>
            {label.slice(0, hit.at)}
            <span className="font-medium text-[var(--fu-text,#F8F5F1)]">{label.slice(hit.at, hit.at + hit.length)}</span>
            {label.slice(hit.at + hit.length)}
          </>
        ) : (
          label
        )}
      </SkeletonText>
    </span>
  );
}

function Key({ name, children }: { name: string; children: string }) {
  return (
    <span className="flex items-center gap-1.5">
      <kbd className="rounded-[6px] border border-[var(--fu-control-border,#737373)] px-1.5 font-[inherit] text-[12px] leading-[18px] text-[var(--fu-text,#F8F5F1)]">
        {name}
      </kbd>
      {children}
    </span>
  );
}

/**
 * A search field that reads a typed sentence into filters: "blue suv under 30k" becomes three removable tokens.
 * Suggestions under it finish names, offer the next filter and fix misspelt names, each with its count.
 */
export function SentenceSearch<Item, State>({
  vocabulary,
  items,
  value,
  onChange,
  label = "Describe what you want",
  placeholder,
  addPlaceholder = "Add another filter",
  submitLabel = "Search",
  formatCount,
  countLabel: countLabelProp,
  locale,
  defaultText = "",
  defaultOpen = false,
  defaultHighlight,
  autoFocus = false,
  open: openProp,
  onOpenChange,
  emptyRows,
  status = "ready",
  onRetry,
  errorText = "Couldn't load the suggestions.",
  disabled = false,
  className,
  onFocus,
  onBlur,
  ...props
}: SentenceSearchProps<Item, State>) {
  const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
  const id = useId();
  const listId = `${id}-list`;
  const noteId = `${id}-note`;
  const optionId = (index: number) => `${id}-option-${index}`;
  const [text, setText] = useState(defaultText);
  const [openState, setOpenState] = useState(defaultOpen);
  const open = openProp ?? openState;
  const setOpen = (next: boolean) => {
    setOpenState(next);
    if (next !== open) onOpenChange?.(next);
  };
  // Where the arrow keys or the pointer left the highlight. Until then the best match leads.
  const [moved, setMoved] = useState<number | null>(defaultHighlight ?? null);
  const [order, setOrder] = useState<string[]>([]);
  const [unused, setUnused] = useState<string[]>([]);
  const [fixes, setFixes] = useState<Correction[]>([]);
  const root = useRef<HTMLDivElement>(null);
  const field = useRef<HTMLInputElement>(null);
  const panel = useRef<HTMLDivElement>(null);

  const applied = vocabulary.tokens(value);
  const keys = applied.map((token) => token.key);
  // Tokens stay in the order they were added, which is the order they were thought of.
  const kept = [...order.filter((key) => keys.includes(key)), ...keys.filter((key) => !order.includes(key))];
  if (kept.join("\n") !== order.join("\n")) setOrder(kept);
  const tokens = kept.flatMap((key) => applied.filter((token) => token.key === key));

  const suggested = useMemo(() => suggest(vocabulary, items, text, value), [vocabulary, items, text, value]);
  const count = useMemo(() => countOf(vocabulary, items, value), [vocabulary, items, value]);
  const typing = text.trim().length > 0;
  // Own rows come first; the suggestions follow them, or step aside for them.
  const own = typing ? undefined : emptyRows;
  const ownRows = own?.rows ?? [];
  const lead = ownRows.length;
  const replaced = own?.replace === true;
  const groups = useMemo(() => (replaced ? [] : suggested), [replaced, suggested]);
  const rows = useMemo(() => groups.flatMap((group) => group.rows), [groups]);
  // Its own status, or the loading frame of an item around it.
  const loading = useLoading().loading || status === "loading";
  // While the counts load or fail, the field keeps working but the rows cannot be picked: none is highlighted.
  const live = !loading && status !== "error" && !disabled;
  const total = live ? lead + rows.length : 0;
  const active = live ? Math.min(moved ?? (typing && rows.length ? 0 : -1), total - 1) : -1;
  const ownEmpty = own?.emptyText !== undefined && ownRows.length === 0;
  // The list shows a line instead of its rows: the error, or the own rows' empty note.
  const noted = status === "error" || (!loading && status === "ready" && ownEmpty);
  const shown = open && !disabled && (loading || status !== "ready" || own !== undefined || rows.length > 0);
  const idAt = (index: number) => (index < lead ? ownRows[index].id : optionId(index - lead));
  const ghost = shown ? ghostOf(text, rows[active - lead]) : "";
  const preview = shown && active >= 0 && active < lead ? ownRows[active].preview : undefined;
  const previewTokens = preview !== undefined ? vocabulary.tokens(preview) : [];
  const previewId = preview !== undefined ? ownRows[active].id : "";

  const [mark, setMark] = useState<{ top: number; height: number; slide: boolean } | null>(null);
  const marked = useRef(-1);
  useLayoutEffect(() => {
    const node = shown && active >= 0 ? document.getElementById(idAt(active)) : null;
    if (!node) {
      marked.current = -1;
      setMark(null);
      return;
    }
    const next = { top: node.offsetTop, height: node.offsetHeight, slide: marked.current >= 0 };
    marked.current = active;
    setMark((was) => (was && was.top === next.top && was.height === next.height ? was : next));
  }, [shown, active, rows, ownRows]);

  useEffect(() => {
    if (!autoFocus) return;
    const input = field.current;
    input?.focus();
    input?.setSelectionRange(input.value.length, input.value.length);
  }, [autoFocus]);

  // A list open without focus, from defaultOpen or open, has no blur to close it, so a press outside does. Not in an
  // inert still picture, such as a preview, where a press elsewhere on the page must leave it as drawn.
  useEffect(() => {
    if (!open || root.current?.closest("[inert]")) return;
    const onDown = (event: PointerEvent) => {
      const node = root.current;
      if (!node || node.contains(document.activeElement)) return;
      if (!(event.target instanceof Node) || !node.contains(event.target)) setOpen(false);
    };
    document.addEventListener("pointerdown", onDown, true);
    return () => document.removeEventListener("pointerdown", onDown, true);
  });

  const land = (next: State, left: string[] = [], added: readonly string[] = [], fixed: Correction[] = []) => {
    setOrder([...kept, ...added.filter((key) => !kept.includes(key))]);
    setMoved(null);
    setText("");
    setUnused(left);
    setFixes(fixed);
    onChange(next);
  };

  const pick = (row: Suggestion<State>) => land(row.next, row.left, row.order);

  // Reads the whole sentence, as the Search button does, with misspelt names fixed.
  const submit = () => {
    setOpen(false);
    setMoved(null);
    if (!typing) return;
    const reading = readSentence(vocabulary, items, text, { context: value, fixTypos: true });
    if (reading.tokens.length) {
      land(
        vocabulary.merge(value, reading.value),
        reading.left,
        reading.tokens.map((token) => token.key),
        reading.corrections,
      );
    } else setUnused(reading.left.length ? reading.left : [text.trim()]);
  };

  const type = (next: string) => {
    setMoved(null);
    setOpen(true);
    setUnused([]);
    setFixes([]);
    const end = next.match(/[\s,]+$/)?.[0];
    const word = end ? next.slice(0, -end.length) : next;
    // A comma right after a digit is the number's own mark, as in "60,000" or "1,5", until a space shows it ended the
    // number; so "under 60,000 km" waits for its unit instead of turning into a price at the comma.
    if (end && !(end === "," && /\p{Nd}$/u.test(word))) {
      const comma = end.includes(",");
      const whole = wholeWord(vocabulary, items, word, value);
      if (whole) return land(whole.next, [], whole.order);
      const best = comma ? suggest(vocabulary, items, word, value).flatMap((group) => group.rows)[0] : undefined;
      if (best) return pick(best);
      if (comma) return setText(`${word} `);
    }
    setText(next);
  };

  const move = (index: number) => {
    setMoved(index);
    document.getElementById(idAt(index))?.scrollIntoView({ block: "nearest" });
  };

  const choose = (row: OwnRow<State>) => {
    setMoved(null);
    if (row.closes) setOpen(false);
    row.onSelect();
  };

  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.nativeEvent.isComposing) return;
    const mine = shown && active >= 0 && active < lead ? ownRows[active] : undefined;
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      setOpen(true);
      if (!total) return;
      const step = event.key === "ArrowDown" ? 1 : -1;
      const from = shown ? active : -1;
      move((Math.max(from, step > 0 ? -1 : 0) + step + total) % total);
    } else if (event.key === "Enter") {
      event.preventDefault();
      if (mine) choose(mine);
      else if (shown && rows[active - lead]) pick(rows[active - lead]);
      else submit();
    } else if (event.key === "Tab" && !event.shiftKey && shown && status === "error" && panel.current?.querySelector("button")) {
      // Retry sits in the list, after the buttons in the box: Tab goes straight to it while the list shows it.
      event.preventDefault();
      panel.current.querySelector("button")?.focus();
    } else if (event.key === "Tab" && !event.shiftKey && shown && typing && rows[active]) {
      event.preventDefault();
      pick(rows[active]);
    } else if ((event.key === "Delete" || event.key === "Backspace") && !text && mine?.onRemove) {
      event.preventDefault();
      mine.onRemove();
    } else if (event.key === "Escape") {
      setOpen(false);
      setMoved(null);
    } else if (event.key === "Backspace" && !text && tokens.length) {
      event.preventDefault();
      setUnused([]);
      setFixes([]);
      onChange(tokens[tokens.length - 1].clear(value));
    }
  };

  const clearAll = () => {
    land(vocabulary.empty);
    field.current?.focus();
  };

  let index = -1;

  return (
    <div
      ref={root}
      className={cn("relative w-full @container", className)}
      onFocus={(event) => {
        const inList = panel.current?.contains(event.target) ?? false;
        // Retry hands focus to the list's frame as it reloads; the field takes it back, so typing goes on.
        if (inList && event.target.hasAttribute("data-status-frame")) field.current?.focus({ preventScroll: true });
        else if (event.target !== field.current && !inList) setOpen(false);
        onFocus?.(event);
      }}
      onBlur={(event) => {
        onBlur?.(event);
        if (root.current?.contains(event.relatedTarget)) return;
        setOpen(false);
        setMoved(null);
      }}
      {...props}
    >
      {/* Disabled turns off the field, the tokens and the buttons; loading and errors belong to the list below. */}
      <StatusFrame disabled={disabled} announce={false}>
      <div className="relative">
      <div
        onPointerDown={(event) => {
          if (event.target === event.currentTarget) {
            event.preventDefault();
            field.current?.focus();
          }
        }}
        className={cn(
          "flex cursor-text items-start gap-2 rounded-[12px] border border-[var(--fu-control-border,#737373)] bg-[var(--fu-search,#2A2A2A)] py-1.5 pe-1.5 ps-3.5",
          "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)]",
        )}
      >
        <span aria-hidden="true" className="pointer-events-none flex h-9 shrink-0 items-center text-[var(--fu-mute,#BDBDBD)]">
          <SearchIcon size={20} />
        </span>
        <ul className="flex min-h-9 min-w-0 flex-1 flex-wrap items-center gap-1.5 py-[5px]" onPointerDown={(event) => {
          if (event.target === event.currentTarget) {
            event.preventDefault();
            field.current?.focus();
          }
        }}>
          {tokens.map((token) => (
            <li key={token.key} className="min-w-0">
              <button
                type="button"
                aria-label={`Remove ${token.label}`}
                onPointerDown={(event) => event.preventDefault()}
                onClick={() => {
                  setUnused([]);
                  setFixes([]);
                  onChange(token.clear(value));
                  field.current?.focus();
                }}
                className={cn(
                  "relative flex h-[26px] max-w-full cursor-pointer items-center pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-[9px] gap-1 rounded-full border border-[var(--fu-token-edge,#D1DDFF)] bg-[var(--fu-token,#D1DDFF)] pe-[7px] ps-[11px]",
                  "font-[inherit] text-[14px] leading-5 font-medium text-[var(--fu-token-text,#171717)]",
                  "transition-[background-color,color,border-color,opacity,filter,scale] duration-300 motion-reduce:transition-none",
                  SMOOTH,
                  "starting:scale-[0.82] starting:opacity-0 starting:blur-[3px]",
                  "hover:bg-transparent hover:text-[var(--fu-accent-soft,#8FAAFF)] hover:border-[var(--fu-accent-soft,#8FAAFF)] active:scale-[0.97]",
                  "outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
                )}
              >
                <span className="truncate">{token.label}</span>
                <XIcon size={14} className="shrink-0" />
              </button>
            </li>
          ))}
          <li className="relative h-6 min-w-[140px] flex-1">
            {previewTokens.length > 0 && !tokens.length && (
              // The highlighted row's filters, tried on in the box without moving anything.
              <span
                aria-hidden="true"
                className="pointer-events-none absolute -inset-y-px inset-s-0 -inset-e-2 flex items-center gap-1.5 overflow-hidden [mask-image:linear-gradient(to_right,#000_calc(100%-24px),transparent)] rtl:[mask-image:linear-gradient(to_left,#000_calc(100%-24px),transparent)]"
              >
                {previewTokens.map((token, i) => (
                  <span
                    key={`${previewId}-${token.key}-${token.label}`}
                    style={{ transitionDelay: `${i * 45}ms` }}
                    className={cn(
                      "flex h-[26px] shrink-0 items-center rounded-full border border-dashed border-[var(--fu-accent-soft,#8FAAFF)] px-[11px] text-[14px] leading-5 font-medium whitespace-nowrap text-[var(--fu-accent-soft,#8FAAFF)]",
                      "transition-[opacity,filter,translate] duration-300 motion-reduce:transition-none",
                      SMOOTH,
                      "starting:-translate-x-1 rtl:starting:translate-x-1 starting:opacity-0 starting:blur-[3px]",
                    )}
                  >
                    {token.label}
                  </span>
                ))}
              </span>
            )}
            {ghost && (
              <span
                aria-hidden="true"
                className="pointer-events-none absolute inset-0 overflow-hidden text-[16px] leading-6 whitespace-pre text-[var(--fu-dim,#929292)]"
              >
                <span className="invisible">{text}</span>
                {ghost}
              </span>
            )}
            <input
              ref={field}
              role="combobox"
              aria-label={label}
              // In an error, or with nothing to list, the popup holds a line instead of a listbox: the field is
              // described by it. While loading the listbox is inert, so the field does not offer it.
              aria-expanded={shown && !noted && !loading}
              aria-controls={noted || loading ? undefined : listId}
              aria-describedby={noted ? noteId : undefined}
              aria-autocomplete="list"
              aria-activedescendant={shown && active >= 0 ? idAt(active) : undefined}
              autoComplete="off"
              autoCapitalize="off"
              spellCheck={false}
              enterKeyHint="search"
              placeholder={tokens.length ? addPlaceholder : previewTokens.length ? "" : (placeholder ?? label)}
              value={text}
              onChange={(event) => type(event.target.value)}
              onFocus={() => setOpen(true)}
              onClick={() => setOpen(true)}
              onKeyDown={onKeyDown}
              className={cn(
                "relative block h-6 w-full min-w-0 bg-transparent font-[inherit] text-[16px] leading-6 text-[var(--fu-text,#F8F5F1)] outline-none placeholder:text-[var(--fu-mute,#BDBDBD)]",
                previewTokens.length > 0 && !tokens.length && "caret-transparent",
              )}
            />
            {noted && (
              <span id={noteId} hidden>
                {status === "error" ? errorText : own?.emptyText}
              </span>
            )}
          </li>
        </ul>
        {(typing || tokens.length > 0) && (
          <button
            type="button"
            aria-label="Clear search"
            onPointerDown={(event) => event.preventDefault()}
            onClick={clearAll}
            className={cn(
              TAP,
              "grid size-9 shrink-0 cursor-pointer place-items-center rounded-[10px] text-[var(--fu-mute,#BDBDBD)]",
              "transition-[background-color,color,opacity,scale] duration-200 motion-reduce:transition-none starting:scale-[0.6] starting:opacity-0",
              "hover:bg-[var(--fu-hover,#333333)] hover:text-[var(--fu-text,#F8F5F1)]",
              "outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
            )}
          >
            <XIcon size={20} />
          </button>
        )}
        <button
          type="button"
          onPointerDown={(event) => event.preventDefault()}
          onClick={submit}
          className={cn(
            "hidden h-9 shrink-0 cursor-pointer items-center rounded-[10px] bg-[var(--fu-accent,#3B57E6)] px-3 font-[inherit] text-[14px] leading-5 font-medium text-[var(--fu-on-accent,#FFFFFF)] @min-[480px]:inline-flex",
            "transition-[background-color,scale] duration-200 hover:bg-[var(--fu-accent-hover,#3450D4)] 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)]",
          )}
        >
          {submitLabel}
        </button>
      </div>

      <div
        ref={panel}
        data-state={shown ? "open" : "closed"}
        // A press anywhere in the list, Retry included, leaves focus in the field.
        onPointerDown={(event) => event.preventDefault()}
        className={cn(
          "absolute inset-x-0 top-full z-30 mt-1.5 overflow-hidden rounded-[16px] border border-[var(--fu-menu-edge,#737373)] bg-[var(--fu-search,#2A2A2A)] shadow-[0_16px_40px_var(--fu-shadow,rgb(0_0_0/0.5))]",
          "origin-top transition-[opacity,translate,visibility] duration-[170ms] motion-reduce:transition-none",
          SMOOTH,
          "data-[state=closed]:invisible data-[state=closed]:translate-y-1.5 data-[state=closed]:opacity-0",
          "data-[state=open]:visible data-[state=open]:translate-y-0 data-[state=open]:opacity-100 data-[state=open]:duration-[260ms]",
        )}
      >
        {/* Loading draws the rows as placeholders and the count at the foot; an error or an empty note takes the place
            of the rows and the foot. */}
        <StatusFrame
          status={status}
          onRetry={onRetry}
          errorText={errorText}
          empty={ownEmpty}
          emptyText={own?.emptyText}
          className={cn("rounded-[16px]", noted && "min-h-11 py-1.5 pe-1.5 ps-[18px] [&>*]:min-h-8")}
        >
        <div
          id={listId}
          role="listbox"
          aria-label="Suggestions"
          className={cn("relative max-h-[min(56dvh,440px)] overflow-y-auto overscroll-contain p-1.5", SCROLL)}
        >
          <div
            aria-hidden="true"
            className={cn(
              "pointer-events-none absolute inset-x-1.5 top-0 rounded-[12px] bg-[var(--fu-row-hover,rgb(255_255_255/0.1))] motion-reduce:transition-none",
              mark?.slide && "transition-[translate,height] duration-200",
              SMOOTH,
              !mark && "opacity-0",
            )}
            style={mark ? { translate: `0 ${mark.top}px`, height: mark.height } : undefined}
          />
          {own?.render((rowId) => {
            const at = ownRows.findIndex((row) => row.id === rowId);
            return {
              id: rowId,
              role: "option",
              "aria-selected": shown && at >= 0 && at === active,
              onPointerMove: () => live && at >= 0 && moved !== at && setMoved(at),
              onClick: () => {
                if (at < 0 || !live) return;
                field.current?.focus();
                choose(ownRows[at]);
              },
            };
          })}
          {loading && !own && !rows.length && (
            <div role="group" aria-label="Matches">
              {placeholderLabels(LOADING_ROWS).map((name, i) => (
                <div key={i} role="option" aria-selected={false} className={ROW}>
                  <Label label={name} typed="" />{" "}
                  <span aria-hidden="true" className="ms-auto flex shrink-0 items-center ps-3">
                    <CountPill count={0} />
                  </span>
                </div>
              ))}
            </div>
          )}
          {groups.map((group) => (
            <div key={group.title ?? "matches"} role="group" aria-label={group.title ?? "Matches"}>
              {group.title && <p className="px-3 pt-2 pb-1 text-[13px] leading-[18px] text-[var(--fu-mute,#BDBDBD)]">{group.title}</p>}
              {group.rows.map((row) => {
                index += 1;
                const at = index;
                return (
                  <div
                    key={row.key}
                    id={optionId(at)}
                    role="option"
                    aria-selected={shown && at + lead === active}
                    aria-label={`${row.label}${row.hint ? `, ${row.hint}` : ""}, ${countLabel(row.count)}`}
                    onPointerMove={() => live && moved !== at + lead && setMoved(at + lead)}
                    onClick={() => {
                      if (!live) return;
                      pick(row);
                      field.current?.focus();
                    }}
                    className={cn(ROW, "group/opt cursor-pointer")}
                  >
                    {row.swatch &&
                      (loading ? (
                        <Skeleton className="size-4 shrink-0 rounded-full" />
                      ) : (
                        // The colour fades in once with the words when the counts arrive.
                        <SkeletonText loading={false}>
                          <span
                            aria-hidden="true"
                            className="block size-4 shrink-0 rounded-full border border-[var(--fu-control-border,#737373)]"
                            style={{ background: row.swatch }}
                          />
                        </SkeletonText>
                      ))}
                    <Label label={row.label} typed={text} />{" "}
                    <span aria-hidden="true" className="ms-auto flex shrink-0 items-center gap-2 ps-3">
                      {row.hint && (
                        <span className="text-[13px] leading-5 text-[var(--fu-mute,#BDBDBD)]">
                          <SkeletonText>{row.hint}</SkeletonText>
                        </span>
                      )}{" "}
                      <CountPill count={row.count} locale={locale} {...(formatCount && { format: formatCount })} />
                    </span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div
          aria-hidden="true"
          className="flex h-10 items-center gap-4 border-t border-[var(--fu-line,#404040)] px-3 text-[13px] leading-5 text-[var(--fu-mute,#BDBDBD)]"
        >
          <span className="hidden items-center gap-4 @min-[480px]:flex">
            {own?.keys ? (
              own.keys.map((hint) => (
                <Key key={hint.key} name={hint.key}>
                  {hint.label}
                </Key>
              ))
            ) : (
              <>
                <Key name="↑↓">Move</Key>
                <Key name="Enter">Add</Key>
                {typing ? <Key name="Tab">Complete</Key> : tokens.length > 0 && <Key name="⌫">Remove last</Key>}
              </>
            )}
          </span>
          <span className="ms-auto tabular-nums">
            <SkeletonText>{countLabel(preview !== undefined ? countOf(vocabulary, items, preview) : count)}</SkeletonText>
          </span>
        </div>
        </StatusFrame>
      </div>
      </div>

      <p aria-live="polite" className="text-[13px] leading-5 text-[var(--fu-dim,#929292)]">
        {fixes.length > 0 && <span className="mt-2 block px-4">Read {fixes.map((fix) => `“${fix.word}” as ${fix.name}`).join(", ")}</span>}
        {unused.length > 0 && <span className="mt-2 block px-4">Not used: {quote(unused)}</span>}
      </p>
      <p aria-live="polite" className="sr-only">
        {!loading && status === "ready" ? countLabel(count) : ""}
      </p>
      </StatusFrame>
    </div>
  );
}
```

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

```ts
/**
 * A slim scrollbar for every box that scrolls: a 6px rounded thumb in the line colour on a clear track, stronger under
 * the pointer, kept 2px off the side and 12px off each end so it never runs into a rounded corner.
 * Chromium and Safari draw it from the ::-webkit-scrollbar parts. Firefox has none of those, so it alone gets the
 * standard thin bar in the same colours: Chromium ignores the parts once scrollbar-width or scrollbar-color is set,
 * so never add either beside this class.
 */
export const SCROLL =
  "supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-width:thin] supports-[not(selector(::-webkit-scrollbar))]:[scrollbar-color:var(--fu-line,#404040)_transparent] " +
  "[&::-webkit-scrollbar]:size-2.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent " +
  "[&::-webkit-scrollbar-track:vertical]:my-3 [&::-webkit-scrollbar-track:horizontal]:mx-3 " +
  "[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-padding " +
  "[&::-webkit-scrollbar-thumb]:bg-[var(--fu-line,#404040)] [&::-webkit-scrollbar-thumb:hover]:bg-[var(--fu-control-border,#737373)] [&::-webkit-scrollbar-thumb:active]:bg-[var(--fu-control-border,#737373)]";
```

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

## What it does

- Focus the empty box and your Saved and Recent searches show, each with its filters and how many items it finds now.
- Highlight a row and its filters show faintly in the box, with its count at the foot; Enter or a press runs it.
- Once filters are set, "Save this search" leads the suggestions; saved, it turns into "Saved as" with a check.
- A cross or Delete removes a row: it blurs away and the rows under it glide up. Saving a recent row glides it into Saved.
- The page keeps the lists: pass them in and change them in onSearch, onSave and onForget.

## Props and value

RecentSearches (components/filters-ui/filters/recent-searches.tsx) holds this value: State, as in the sentence search: your own filters object. The recent and saved lists are yours too: { id, value, name? }[].

- vocabulary / items / value / onChange: Vocabulary<Item, State> / readonly Item[] / State / (value: State) => void (required). As in the sentence search: the words it knows, every item for the counts, and the filters that are set.
- recent: readonly { id: string; value: State }[] (required). Newest first. A search that is also saved shows under Saved only.
- saved: readonly { id: string; value: State; name?: string }[] (required). Saved searches, in your order. Without a name, the row is named from its filters.
- onSearch: (value: State) => void (required). A search worth keeping: when the field loses focus with filters set, and the old search when the box is cleared. remember(vocabulary, list, value) puts it on top of your list once.
- onSave: (value: State, name: string) => void (required). "Save this search" or the star on a recent row. name is read from its filters, e.g. "Blue SUV under $30k".
- onForget: (id: string) => void (required). The cross on a row, or Delete while it is highlighted. Remove the id from your lists.
- recentLimit: number (default 4). How many recent searches show.
- defaultOpen: boolean (default false). Shows the list on first render, before the field has focus. A press outside closes it, except inside an inert still picture.
- defaultHighlight: number (optional). The row highlighted on first render, by position, so its filters show in the box, e.g. for a still picture.
- label / placeholder / countLabel / formatCount: string / string / (n: number) => string / (n: number) => string (optional). As in the sentence search.
- 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 your searches."). The error line, in plain words.
- emptyText: string (default "No recent searches yet"). The line in the list while there are no recent and no saved searches.
- 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"): Only the list loads: the field keeps taking input, while Saved and Recent keep their headings and each search's name, filters and count draw as placeholders the size of the real ones, or stand-in rows hold their place while the lists are on their way; no row can be picked. 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 field keeps working; the list shows the line and Retry in place of the searches. The default line is "Couldn't load your searches." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Empty (no options given, with emptyText): No recent and no saved searches: the list holds a picture and one line in place of Saved and Recent, "No recent searches yet" by default.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. The field is off and the list does not open.
- Long labels (data, not a prop): A saved search's name and filters wrap onto a second line, then end in an ellipsis; a long filter in a recent row ends in one at the row's width. Every row is read out in full.
- Many options (data, not a prop): The list caps its height and scrolls; the highlight keeps its row in view as Up and Down move.

## 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 { RecentSearches, remember, type SavedSearch } from "@/components/filters-ui/filters/recent-searches";
import type { Term, Token, Vocabulary } from "@/components/filters-ui/lib/sentence";

type Car = { make: string; body: string; color: string; fuel: string; seats: number; price: number };

const CARS: Car[] = [
  { make: "Toyota", body: "SUV", color: "Blue", fuel: "Hybrid", seats: 5, price: 28900 },
  { make: "Toyota", body: "SUV", color: "White", fuel: "Gas", seats: 5, price: 29900 },
  { make: "Toyota", body: "SUV", color: "Black", fuel: "Hybrid", seats: 8, price: 47500 },
  { make: "Toyota", body: "Minivan", color: "White", fuel: "Hybrid", seats: 8, price: 39900 },
  { make: "Honda", body: "Sedan", color: "White", fuel: "Gas", seats: 5, price: 23995 },
  { make: "Honda", body: "SUV", color: "Blue", fuel: "Hybrid", seats: 5, price: 32900 },
  { make: "Honda", body: "Minivan", color: "Black", fuel: "Hybrid", seats: 8, price: 41200 },
  { make: "Ford", body: "Truck", color: "Red", fuel: "Gas", seats: 6, price: 38900 },
  { make: "Kia", body: "SUV", color: "White", fuel: "Gas", seats: 8, price: 44800 },
  { make: "Tesla", body: "Sedan", color: "White", fuel: "Electric", seats: 5, price: 37900 },
  { make: "Tesla", body: "SUV", color: "Blue", fuel: "Electric", seats: 5, price: 45900 },
  { make: "Hyundai", body: "SUV", color: "Blue", fuel: "Electric", seats: 5, price: 29800 },
];

type Search = { makes: string[]; bodies: string[]; colors: string[]; fuels: string[]; priceMax: number | null; seatsMin: number | null };
type ListKey = "makes" | "bodies" | "colors" | "fuels";

const EMPTY: Search = { makes: [], bodies: [], colors: [], fuels: [], priceMax: null, seatsMin: null };
const LISTS: [ListKey, string, string[]][] = [
  ["makes", "Make", ["Toyota", "Honda", "Ford", "Kia", "Tesla", "Hyundai"]],
  ["bodies", "Body style", ["SUV", "Sedan", "Truck", "Minivan"]],
  ["colors", "Colour", ["Black", "White", "Blue", "Red"]],
  ["fuels", "Fuel", ["Gas", "Hybrid", "Electric"]],
];

const unique = (values: string[]) => [...new Set(values)];

// The words the search knows; see the sentence search for a fuller vocabulary.
const TERMS: Term<Search>[] = LISTS.flatMap(([list, group, values]) =>
  values.map((value) => ({ key: `${list}-${value}`, label: value, group, add: (s: Search) => ({ ...s, [list]: unique([...s[list], value]) }) })),
);

function tokens(s: Search): Token<Search>[] {
  const out: Token<Search>[] = LISTS.flatMap(([list, group]) =>
    s[list].map((value) => ({ key: `${list}-${value}`, label: value, group, clear: (x: Search) => ({ ...x, [list]: x[list].filter((v) => v !== value) }) })),
  );
  if (s.priceMax !== null) out.push({ key: "price", label: `Under $${s.priceMax / 1000}k`, group: "Price", clear: (x) => ({ ...x, priceMax: null }) });
  if (s.seatsMin !== null) out.push({ key: "seats", label: `${s.seatsMin}+ seats`, group: "Seats", clear: (x) => ({ ...x, seatsMin: null }) });
  return out;
}

const vocabulary: Vocabulary<Car, Search> = {
  empty: EMPTY,
  matches: (car, s) =>
    (!s.makes.length || s.makes.includes(car.make)) &&
    (!s.bodies.length || s.bodies.includes(car.body)) &&
    (!s.colors.length || s.colors.includes(car.color)) &&
    (!s.fuels.length || s.fuels.includes(car.fuel)) &&
    (s.priceMax === null || car.price <= s.priceMax) &&
    (s.seatsMin === null || car.seats >= s.seatsMin),
  merge: (a, b) => ({
    makes: unique([...a.makes, ...b.makes]),
    bodies: unique([...a.bodies, ...b.bodies]),
    colors: unique([...a.colors, ...b.colors]),
    fuels: unique([...a.fuels, ...b.fuels]),
    priceMax: b.priceMax ?? a.priceMax,
    seatsMin: b.seatsMin ?? a.seatsMin,
  }),
  tokens,
  terms: TERMS,
  rules: [
    { pattern: /\b(?:under|below)\s+\$?(\d+)k\b/, read: (s, m) => ({ ...s, priceMax: Number(m[1]) * 1000 }) },
    { pattern: /\b(\d)\s*seats?\b/, read: (s, m) => ({ ...s, seatsMin: Number(m[1]) }) },
  ],
};

// Where the lists live is up to you: state for this visit, localStorage, or your server.
const SAVED: SavedSearch<Search>[] = [
  { id: "family", name: "Family hybrid", value: { ...EMPTY, fuels: ["Hybrid"], seatsMin: 7 } },
  { id: "city", name: "City electric", value: { ...EMPTY, fuels: ["Electric"], priceMax: 40000 } },
];
const RECENT: SavedSearch<Search>[] = [
  { id: "r1", value: { ...EMPTY, colors: ["Blue"], bodies: ["SUV"], priceMax: 30000 } },
  { id: "r2", value: { ...EMPTY, makes: ["Toyota"], bodies: ["Minivan"] } },
  { id: "r3", value: { ...EMPTY, makes: ["Tesla"] } },
];

const carCount = (n: number) => (n === 1 ? "1 car" : `${n} cars`);

export default function RecentSearchesExample() {
  const [search, setSearch] = useState<Search>(EMPTY);
  const [recent, setRecent] = useState(RECENT);
  const [saved, setSaved] = useState(SAVED);
  const results = CARS.filter((car) => vocabulary.matches(car, search));

  return (
    <div className="w-full max-w-[560px]">
      <RecentSearches
        vocabulary={vocabulary}
        items={CARS}
        value={search}
        onChange={setSearch}
        recent={recent}
        saved={saved}
        onSearch={(value) => setRecent((list) => remember(vocabulary, list, value))}
        onSave={(value, name) => setSaved((list) => [...list, { id: String(Date.now()), name, value }])}
        onForget={(id) => {
          setRecent((list) => list.filter((entry) => entry.id !== id));
          setSaved((list) => list.filter((entry) => entry.id !== id));
        }}
        label="Describe the car you want"
        countLabel={carCount}
      />
      <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 where recent and saved searches should live: state for this visit, localStorage, or my server for signed-in people. Keep the lists in my own state and change them in onSearch (remember(vocabulary, list, value) puts a search on top once), onSave (add { id, name, value }; offer a rename if I want one) and onForget (remove the id). Use my own sentence search vocabulary as it is; counts come from items and matches, so pass every item. Keep components/filters-ui/filters/sentence-search.tsx as it is: the rows show in its own list.

## 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-control-border: #737373;
  --fu-control-hover: #A3A3A3;
  --fu-dim: #929292;
  --fu-hover: #333333;
  --fu-hover-wash: rgb(255 255 255/0.14);
  --fu-line: #404040;
  --fu-menu-edge: #737373;
  --fu-mute: #BDBDBD;
  --fu-on-accent: #FFFFFF;
  --fu-pill: rgb(255 255 255/0.1);
  --fu-pill-square: #333333;
  --fu-pill-text: #C8C8C8;
  --fu-row-hover: rgb(255 255 255/0.1);
  --fu-search: #2A2A2A;
  --fu-selected: #1F2747;
  --fu-shadow: rgb(0 0 0/0.5);
  --fu-skeleton: rgb(255 255 255/0.12);
  --fu-skeleton-on: rgb(143 170 255/0.3);
  --fu-surface-1: #171717;
  --fu-surface-3: #2A2A2A;
  --fu-text: #F8F5F1;
  --fu-token: #D1DDFF;
  --fu-token-edge: #D1DDFF;
  --fu-token-text: #171717;
}
```

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-control-border: #787874;
  --fu-control-hover: #5B5B57;
  --fu-dim: #555552;
  --fu-hover: rgb(29 27 24/0.11);
  --fu-hover-wash: rgb(29 27 24/0.07);
  --fu-line: #C4C4C0;
  --fu-menu-edge: #C4C4C0;
  --fu-mute: #444442;
  --fu-on-accent: #FFFFFF;
  --fu-pill: rgb(29 27 24/0.06);
  --fu-pill-square: rgb(29 27 24/0.07);
  --fu-pill-text: #3C3C3A;
  --fu-row-hover: rgb(29 27 24/0.06);
  --fu-search: #FFFFFF;
  --fu-selected: #E8EDFD;
  --fu-shadow: rgb(36 36 33/0.12);
  --fu-skeleton: rgb(29 27 24/0.09);
  --fu-skeleton-on: rgb(48 73 210/0.18);
  --fu-surface-1: #FFFFFF;
  --fu-surface-3: rgb(29 27 24/0.07);
  --fu-text: #1B1B19;
  --fu-token: #E8EDFD;
  --fu-token-edge: #3049D2;
  --fu-token-text: #3049D2;
}
```

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 rows are options in the search's own listbox, so aria-activedescendant follows the highlight and each row is read with its filters and count.
- Saved and Recent are named groups that say Delete removes a row.
- Saving and removing are announced politely; the stars and crosses are for the pointer, with a tip on hover, and the keys do the same.
- Loading, the list is aria-busy and says "Loading" once, and the field does not mark it expanded; an error or the empty line is read out and describes the field, and Retry hands focus back to the field. Disabled, the field is disabled.
- Motion is skipped when reduced motion is asked for.
- Up and Down move through the rows; Enter runs the highlighted search.
- Delete or Backspace removes the highlighted row; Escape closes the list.
- Typing turns the list back into suggestions, as in the sentence search.
- While disabled nothing takes focus; in an error, Tab from the field reaches Retry in the list.

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

  • Focus the empty box and your Saved and Recent searches show, each with its filters and how many items it finds now.
  • Highlight a row and its filters show faintly in the box, with its count at the foot; Enter or a press runs it.
  • Once filters are set, "Save this search" leads the suggestions; saved, it turns into "Saved as" with a check.
  • A cross or Delete removes a row: it blurs away and the rows under it glide up. Saving a recent row glides it into Saved.
  • The page keeps the lists: pass them in and change them in onSearch, onSave and onForget.

Keyboard

  • Up and Down move through the rows; Enter runs the highlighted search.
  • Delete or Backspace removes the highlighted row; Escape closes the list.
  • Typing turns the list back into suggestions, as in the sentence search.
  • While disabled nothing takes focus; in an error, Tab from the field reaches Retry in the list.

Props

Value. State, as in the sentence search: your own filters object. The recent and saved lists are yours too: { id, value, name? }[].

RecentSearches props
PropDescription
vocabulary / items / value / onChange
Required

As in the sentence search: the words it knows, every item for the counts, and the filters that are set.

Vocabulary<Item, State> / readonly Item[] / State / (value: State) => void
recent
Required

Newest first. A search that is also saved shows under Saved only.

readonly { id: string; value: State }[]
saved
Required

Saved searches, in your order. Without a name, the row is named from its filters.

readonly { id: string; value: State; name?: string }[]
onSearch
Required

A search worth keeping: when the field loses focus with filters set, and the old search when the box is cleared. remember(vocabulary, list, value) puts it on top of your list once.

(value: State) => void
onSave
Required

"Save this search" or the star on a recent row. name is read from its filters, e.g. "Blue SUV under $30k".

(value: State, name: string) => void
onForget
Required

The cross on a row, or Delete while it is highlighted. Remove the id from your lists.

(id: string) => void
recentLimit
Default 4

How many recent searches show.

number
defaultOpen
Default false

Shows the list on first render, before the field has focus. A press outside closes it, except inside an inert still picture.

boolean
defaultHighlight
Optional

The row highlighted on first render, by position, so its filters show in the box, e.g. for a still picture.

number
label / placeholder / countLabel / formatCount
Optional

As in the sentence search.

string / string / (n: number) => string / (n: number) => string
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 your searches."

The error line, in plain words.

string
emptyText
Default "No recent searches yet"

The line in the list while there are no recent and no saved searches.

string
disabled
Default false

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

boolean

More filters