Live example
16 of 256 cars
Copy
Add the "Sentence search" filter from FiltersUI to this project. It is free and MIT licensed, from filtersui.com.
Sentence search: Type a sentence, such as "blue suv under 30k", and it turns into filters.
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/sentence-search.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/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/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/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/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/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
- Reads a typed sentence into removable tokens: "blue suv under 30k" gives Blue, SUV and Under $30k.
- A word typed in full turns into a token on the space after it.
- Suggestions finish a half-typed name, offer the next filter, and show how many items each would leave.
- Fixes misspelt names: "telsa" is read as Tesla.
- When nothing matches, the first suggestion is the closest search that finds something.
## Props and value
SentenceSearch (components/filters-ui/filters/sentence-search.tsx) holds this value: State: your own filters object. The vocabulary says how each word changes it, and which tokens it shows.
- vocabulary: Vocabulary<Item, State> (required). The words it knows: names (terms), phrases with numbers or meaning (rules), how to merge two values and the tokens a value shows.
- items: readonly Item[] (required). Every item, for the result count and the count on each suggestion.
- value: State (required). The filters that are set.
- onChange: (value: State) => void (required). Called with the new filters when a token is added or removed.
- label: string (default "Describe what you want"). Accessible name of the field, and the placeholder while nothing is set.
- placeholder: string (default the label). Placeholder while nothing is set.
- addPlaceholder: string (default "Add another filter"). Placeholder once a token is in the box.
- submitLabel: string (default "Search"). The button that reads the whole sentence. It shows when the box is 480px or wider.
- formatCount: (n: number) => string (default 1,234). Text in each suggestion's count pill.
- countLabel: (n: number) => string (default "6 results"). Words for a count, e.g. "6 cars": the result count under the suggestions, and each count read aloud.
- defaultText / defaultOpen / autoFocus: string / boolean / boolean (default "" / false / false). Text in the field, open suggestions and focus on first render.
- defaultHighlight: number (optional). The row highlighted on first render, by position, e.g. for a still picture of an open list.
- open / onOpenChange: boolean / (open: boolean) => void (optional). The list's open state, when you control it.
- emptyRows: OwnRows<State> (optional). Rows of your own while the box is empty, in place of the suggestions or above them, such as recent searches. Its emptyText is a quiet line in their place while there are none.
- locale: string (default "en-US"). Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the suggestions."). The error line, in plain words.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.
## States
Keep each of these states as it is. Set status from my data fetch: "loading" while it runs, "error" when it fails, with onRetry running it again.
- Loading (status="loading"): Only the list loads: the field and its tokens keep taking input, while the open list draws its rows and the count at its foot as placeholders the size of the real ones, so nothing moves when they arrive, and 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 open list shows the line and Retry in place of the suggestions. The default line is "Couldn't load the suggestions." The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. The field, the tokens, Clear and Search are all off, and the list does not open.
- Long labels (data, not a prop): A long token ends in an ellipsis at the width of the box, with its full words in its "Remove …" name; a long suggestion wraps onto another line, its hint and count staying at the end.
## 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 { SentenceSearch } from "@/components/filters-ui/filters/sentence-search";
import type { Term, Token, Vocabulary } from "@/components/filters-ui/lib/sentence";
type Car = { make: string; model: string; body: string; color: string; fuel: string; seats: number; price: number };
const CARS: Car[] = [
{ make: "Toyota", model: "RAV4", body: "SUV", color: "Blue", fuel: "Hybrid", seats: 5, price: 28900 },
{ make: "Toyota", model: "RAV4", body: "SUV", color: "White", fuel: "Gas", seats: 5, price: 29900 },
{ make: "Toyota", model: "Highlander", body: "SUV", color: "Black", fuel: "Hybrid", seats: 8, price: 47500 },
{ make: "Toyota", model: "Corolla", body: "Sedan", color: "Blue", fuel: "Gas", seats: 5, price: 21900 },
{ make: "Honda", model: "Civic", body: "Sedan", color: "White", fuel: "Gas", seats: 5, price: 23995 },
{ make: "Honda", model: "CR-V", body: "SUV", color: "Blue", fuel: "Hybrid", seats: 5, price: 32900 },
{ make: "Honda", model: "Odyssey", body: "Minivan", color: "Black", fuel: "Gas", seats: 8, price: 41200 },
{ make: "Ford", model: "F-150", body: "Truck", color: "Red", fuel: "Gas", seats: 6, price: 38900 },
{ make: "Ford", model: "Escape", body: "SUV", color: "Black", fuel: "Plug-in hybrid", seats: 5, price: 31400 },
{ make: "Kia", model: "Telluride", body: "SUV", color: "White", fuel: "Gas", seats: 8, price: 44800 },
{ make: "Tesla", model: "Model 3", body: "Sedan", color: "White", fuel: "Electric", seats: 5, price: 37900 },
{ make: "Tesla", model: "Model Y", body: "SUV", color: "Blue", fuel: "Electric", seats: 5, price: 45900 },
];
type Search = { makes: string[]; bodies: string[]; colors: string[]; fuels: string[]; priceMax: number | null; seatsMin: number | null };
const EMPTY: Search = { makes: [], bodies: [], colors: [], fuels: [], priceMax: null, seatsMin: null };
type ListKey = "makes" | "bodies" | "colors" | "fuels";
const unique = (values: string[]) => [...new Set(values)];
const toggleOn = (list: ListKey, value: string) => (s: Search) => ({ ...s, [list]: unique([...s[list], value]) });
// The words this search knows. Swap these lists for your own fields.
const terms = (list: ListKey, group: string, values: string[], extra: Partial<Term<Search>> = {}): Term<Search>[] =>
values.map((value) => ({ key: `${list}-${value}`, label: value, group, add: toggleOn(list, value), ...extra }));
const TERMS: Term<Search>[] = [
...terms("makes", "Make", unique(CARS.map((car) => car.make)), { spellcheck: true }),
...terms("bodies", "Body style", ["SUV", "Sedan", "Truck", "Minivan"]),
...terms("colors", "Colour", ["Black", "White", "Blue", "Red"]),
...terms("fuels", "Fuel", ["Gas", "Hybrid", "Plug-in hybrid", "Electric"]),
];
const whole = new Intl.NumberFormat("en-US");
const money = (value: number) => (value % 1000 === 0 ? `$${value / 1000}k` : `$${whole.format(value)}`);
const dollars = (digits: string, k?: string) => {
const value = Number(digits.replace(/,/g, ""));
return k || value < 1000 ? value * 1000 : value;
};
function tokens(s: Search): Token<Search>[] {
const lists = [
["makes", "Make"],
["bodies", "Body style"],
["colors", "Colour"],
["fuels", "Fuel"],
] as const;
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 ${money(s.priceMax)}`, 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|up to)\s+\$?\s*([\d,]+)\s*(k)?\b/, read: (s, m) => ({ ...s, priceMax: dollars(m[1], m[2]) }) },
{ pattern: /\b(\d)\s*(?:seats?|seater)\b/, read: (s, m) => ({ ...s, seatsMin: Number(m[1]) }) },
],
facets: [
{ title: "Body style", words: ["body", "type"], options: () => TERMS.filter((t) => t.group === "Body style"), isSet: (s) => s.bodies.length > 0 },
{ title: "Colour", words: ["colour", "color"], options: () => TERMS.filter((t) => t.group === "Colour"), isSet: (s) => s.colors.length > 0 },
{ title: "Fuel", words: ["fuel"], options: () => TERMS.filter((t) => t.group === "Fuel"), isSet: (s) => s.fuels.length > 0 },
{
title: "Price",
words: ["price", "budget"],
options: () => [30000, 40000].map((max) => ({ key: `price-${max}`, label: `Under ${money(max)}`, group: "Price", add: (s: Search) => ({ ...s, priceMax: max }) })),
isSet: (s) => s.priceMax !== null,
stepped: true,
},
],
firstUp: ["Body style", "Fuel"],
nextUp: ["Body style", "Colour", "Fuel", "Price"],
filler: "a an the any with and or for in on of car cars".split(" "),
notTypos: ["fold", "food", "fork", "form", "fort"],
stopNames: ["car", "cars"],
everything: "Every car",
};
const carCount = (n: number) => (n === 1 ? "1 car" : `${n} cars`);
export default function SentenceSearchExample() {
const [search, setSearch] = useState<Search>(EMPTY);
const results = CARS.filter((car) => vocabulary.matches(car, search));
return (
<div className="w-full max-w-[560px]">
<SentenceSearch
vocabulary={vocabulary}
items={CARS}
value={search}
onChange={setSearch}
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
The words live in a Vocabulary object: terms are the names it knows (each with a key, label, group, other names and how it adds itself to the value), rules are phrases with numbers or meaning (a RegExp and how it changes the value, read in order before any name), tokens(value) lists the removable tokens, merge adds one value to another, and matches(item, value) says whether an item passes. Ask me which fields my items have and where they come from. Then replace the example's vocabulary with my own: one term list per field, rules for my number phrases (prices, dates, sizes), the tokens and the matches test. Each term key must equal the key of the token it adds; the order of tokens and the suggestion rows rely on it. Optional parts: facets with firstUp and nextUp give the suggestions shown while the box is empty, numbers suggests for a typed number, filler lists words not worth reporting as unused, stopNames words that are never a name alone, and notTypos everyday words never fixed into a name. Keep components/filters-ui/lib/sentence.ts as it is: it knows no field names. Counts come from items and matches, so pass every item, not only the ones on screen.
## 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-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-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-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-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-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-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 field is a combobox with a listbox popup: aria-expanded, aria-controls and aria-activedescendant follow the highlight, and every option has an id.
- Each token is a button named "Remove SUV".
- The result count is announced politely as it changes, as are the words it did not use.
- Loading, the list is aria-busy and says "Loading" once, and the field does not mark it expanded; an error is read out politely and describes the field, and Retry hands focus back to the field. Disabled, the field and every button in the box are disabled.
- Focus is always visible; motion is skipped when reduced motion is asked for.
- Up and Down move through the suggestions; Enter takes the highlighted one, or reads the whole sentence when the list is closed.
- Tab completes the highlighted suggestion while typing; Escape closes the list.
- Backspace in an empty field removes the last token; Shift+Tab reaches each token's remove button.
- 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
- Reads a typed sentence into removable tokens: "blue suv under 30k" gives Blue, SUV and Under $30k.
- A word typed in full turns into a token on the space after it.
- Suggestions finish a half-typed name, offer the next filter, and show how many items each would leave.
- Fixes misspelt names: "telsa" is read as Tesla.
- When nothing matches, the first suggestion is the closest search that finds something.
Keyboard
- Up and Down move through the suggestions; Enter takes the highlighted one, or reads the whole sentence when the list is closed.
- Tab completes the highlighted suggestion while typing; Escape closes the list.
- Backspace in an empty field removes the last token; Shift+Tab reaches each token's remove button.
- While disabled nothing takes focus; in an error, Tab from the field reaches Retry in the list.
Props
Value. State: your own filters object. The vocabulary says how each word changes it, and which tokens it shows.
| Prop | Description |
|---|---|
vocabularyRequired | The words it knows: names (terms), phrases with numbers or meaning (rules), how to merge two values and the tokens a value shows. Vocabulary<Item, State> |
itemsRequired | Every item, for the result count and the count on each suggestion. readonly Item[] |
valueRequired | The filters that are set. State |
onChangeRequired | Called with the new filters when a token is added or removed. (value: State) => void |
labelDefault "Describe what you want" | Accessible name of the field, and the placeholder while nothing is set. string |
placeholderDefault the label | Placeholder while nothing is set. string |
addPlaceholderDefault "Add another filter" | Placeholder once a token is in the box. string |
submitLabelDefault "Search" | The button that reads the whole sentence. It shows when the box is 480px or wider. string |
formatCountDefault 1,234 | Text in each suggestion's count pill. (n: number) => string |
countLabelDefault "6 results" | Words for a count, e.g. "6 cars": the result count under the suggestions, and each count read aloud. (n: number) => string |
defaultText / defaultOpen / autoFocusDefault "" / false / false | Text in the field, open suggestions and focus on first render. string / boolean / boolean |
defaultHighlightOptional | The row highlighted on first render, by position, e.g. for a still picture of an open list. number |
open / onOpenChangeOptional | The list's open state, when you control it. boolean / (open: boolean) => void |
emptyRowsOptional | Rows of your own while the box is empty, in place of the suggestions or above them, such as recent searches. Its emptyText is a quiet line in their place while there are none. OwnRows<State> |
localeDefault "en-US" | Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English. string |
statusDefault "ready" | "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place. "ready" | "loading" | "error" |
onRetryOptional | Called by Retry in the error state. Without it the error line has no button. () => void |
errorTextDefault "Couldn't load the suggestions." | The error line, in plain words. string |
disabledDefault false | Dims the whole filter, blocks pointer and keyboard input and reads as unavailable. boolean |