v1.3.5
Filters

Icon tiles

Pick one or more types by icon, such as body styles.

Live example

133 of 256 cars

Direction
Locale
State

Copy

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

Icon tiles: Pick one or more types by icon, such as body styles.

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/icon-tiles.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/icon-tiles.tsx

```tsx
"use client";

import { useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { resultsLabel } from "../lib/format";
import { CountPill } from "../ui/count-pill";
import { foldOptions, ShowAllButton } from "../ui/show-all";
import { ARRIVING, placeholderLabels, Skeleton, SkeletonText, useLoading } from "../ui/skeleton";
import { StatusFrame, type StateProps } from "../ui/status-frame";

export type IconTileOption<V extends string> = {
  value: V;
  label: string;
  /** Any SVG. It draws in currentColor; `var(--tile-bg)` is the tile's own background, for cut-outs. */
  icon: ReactNode;
  count: number;
};

export type IconTilesProps<V extends string> = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
  StateProps & {
    options: readonly IconTileOption<V>[];
    value: readonly V[];    onChange: (value: V[]) => void;
    /** Accessible name of the group. */
    label: string;
    formatCount?: (n: number) => string;
    /** Screen-reader words for a count: "6 results". */
    countLabel?: (n: number) => string;
    /** Formats the counts and their spoken words by default, e.g. "de-DE". Default "en-US". */
    locale?: string;
    /** How many tiles show before "Show all N". Tiles that are on always show. Default 8. */
    collapsedCount?: number;
  };

const TILE = "flex min-w-0 flex-col gap-1.5 rounded-[16px] border px-3 py-2.5 text-start font-[inherit]";
// A long name wraps at its spaces, with the count beside its first line; a single word too long for the tile ends in
// an ellipsis (the tile's accessible name keeps it whole), so a word is never broken in two.
const NAME_ROW = "flex min-w-0 items-start justify-between gap-1";
const NAME = "min-w-0 overflow-hidden text-[14px] leading-5 text-ellipsis text-[var(--fu-text,#F8F5F1)]";
// Forced colours draw every tile's edge alike and drop fills, so a chosen tile takes the system highlight. Its colours
// stay as given: left to the browser, its words would sit on a backplate in the page colour.
const FORCED_ON =
  "forced-colors:border-[Highlight] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:[--tile-bg:Highlight] forced-colors:[forced-color-adjust:none] forced-colors:focus-visible:outline-[CanvasText]";
const FORCED_ON_PILL = "forced-colors:bg-transparent forced-colors:text-[HighlightText]";

/** Placeholder tiles while the options are on their way. */
const LOADING_TILES = 4;

/**
 * A two-column grid of toggle tiles, each an icon over a name and a count. Several can be on. A long list shows its
 * first collapsedCount tiles, the ones that are on, and "Show all N" for the rest.
 */
export function IconTiles<V extends string>({
  options,
  value,
  onChange,
  label,
  formatCount,
  countLabel: countLabelProp,
  locale,
  collapsedCount = 8,
  status = "ready",
  onRetry,
  errorText,
  emptyText,
  disabled = false,
  className,
  ...props
}: IconTilesProps<V>) {
  const countLabel = countLabelProp ?? ((n: number) => resultsLabel(n, locale));
  // An option turned off under the pointer or keyboard would become disabled at 0, or leave a folded list, and drop
  // focus; it stays as it is until focus and the pointer have both left it.
  const [kept, setKept] = useState<V | null>(null);
  const toggle = (v: V, button: HTMLButtonElement) => {
    const on = value.includes(v);
    setKept(on && (document.activeElement === button || button.matches(":hover")) ? v : null);
    onChange(on ? value.filter((x) => x !== v) : [...value, v]);
  };
  const [all, setAll] = useState(false);

  // Its own status, or the loading frame of an item around it, such as a block's card.
  const loading = useLoading().loading || status === "loading";
  const { folds, shown } = foldOptions(options, {
    collapsedCount,
    expanded: all,
    isOn: (o) => value.includes(o.value),
    isKept: (o) => kept === o.value,
    loading,
  });

  return (
    <div role="group" aria-label={label} aria-disabled={disabled || undefined} className={className} {...props}>
      <StatusFrame status={status} onRetry={onRetry} errorText={errorText} empty={options.length === 0} emptyText={emptyText} disabled={disabled}>
        <div className="grid grid-cols-2 gap-2">
          {loading && options.length === 0
            ? placeholderLabels(LOADING_TILES).map((name, i) => (
                <span key={i} className={cn(TILE, "border-[var(--fu-line,#404040)]")}>
                  <TileIcon>{null}</TileIcon>
                  <span className={NAME_ROW}>
                    <span className={NAME}>
                      <SkeletonText>{name}</SkeletonText>
                    </span>{" "}
                    <CountPill variant="square" count={0} className="mt-px" />
                  </span>
                </span>
              ))
            : shown.map((option) => {
                const on = value.includes(option.value);
                return (
                  <button
                    key={option.value}
                    type="button"
                    aria-pressed={on}
                    aria-label={`${option.label}, ${countLabel(option.count)}`}
                    disabled={option.count === 0 && !on && kept !== option.value}
                    onBlur={(event) => kept === option.value && !event.currentTarget.matches(":hover") && setKept(null)}
                    onPointerLeave={(event) => kept === option.value && document.activeElement !== event.currentTarget && setKept(null)}
                    onClick={(event) => toggle(option.value, event.currentTarget)}
                    data-state={on ? "on" : "off"}
                    className={cn(
                      TILE,
                      "group/tile cursor-pointer",
                      "bg-[var(--tile-bg)] [--tile-bg:var(--fu-card,#1F1F1F)]",
                      "transition-[background-color,border-color,color,scale,opacity] duration-200 ease-[cubic-bezier(0.42,0,0.58,1)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
                      "[&_svg_*]:transition-[fill,stroke] [&_svg_*]:duration-200 motion-reduce:[&_svg_*]: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)]",
                      // While loading, a tile that is on stays on; the others take a quieter edge.
                      on
                        ? "border-[var(--fu-accent-soft,#8FAAFF)] text-[var(--fu-accent-soft,#8FAAFF)] [--tile-bg:var(--fu-selected,#1F2747)]"
                        : loading
                          ? "border-[var(--fu-line,#404040)] text-[var(--fu-mute,#BDBDBD)]"
                          : "border-[var(--fu-control-border,#737373)] text-[var(--fu-mute,#BDBDBD)] enabled:hover:border-[var(--fu-control-hover,#A3A3A3)] enabled:hover:text-[var(--fu-accent-soft,#8FAAFF)] enabled:hover:[--tile-bg:var(--fu-item-hover,#2A2A2A)]",
                      "disabled:cursor-not-allowed",
                      option.count === 0 && !on && !loading && "opacity-40",
                      on && FORCED_ON,
                    )}
                  >
                    <TileIcon>{option.icon}</TileIcon>
                    <span aria-hidden="true" className={NAME_ROW}>
                      <span className={cn(NAME, on && "forced-colors:text-[HighlightText]")}>
                        <SkeletonText>{option.label}</SkeletonText>
                      </span>{" "}
                      <CountPill variant="square" on={on} count={option.count} format={formatCount} locale={locale} className={cn("mt-px", on && !loading && FORCED_ON_PILL)} />
                    </span>
                  </button>
                );
              })}
          {folds && <ShowAllButton total={options.length} expanded={all} onToggle={() => setAll(!all)} locale={locale} className="col-span-2 justify-self-start" />}
        </div>
      </StatusFrame>
    </div>
  );
}

/** The icon row: a rounded placeholder of the icon's height while loading; the icon fades in once when it arrives. */
function TileIcon({ children }: { children: ReactNode }) {
  const { loading, arriving } = useLoading();
  return (
    <span key={loading ? "skeleton" : "icon"} aria-hidden="true" className={cn("flex h-7 justify-center [&>svg]:h-7 [&>svg]:w-auto", arriving && ARRIVING)}>
      {loading ? <Skeleton className="h-7 w-16 rounded-[10px]" /> : children}
    </span>
  );
}
```

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

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

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

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

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

export const DEFAULT_LOCALE = "en-US";

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

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

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

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

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

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

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

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

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

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

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

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

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

### components/filters-ui/ui/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/show-all.tsx

```tsx
"use client";

import type { ButtonHTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";

/**
 * What a long list shows while folded: its first `collapsedCount` options and any that are on. Two hidden options are
 * not worth a button, so the list folds only when it would hide three or more, and never while it is loading.
 * `isKept` marks an option past the fold that was just turned off while it held focus or the pointer: it stays until
 * both have left it, so focus is never dropped and nothing moves under the pointer.
 */
export function foldOptions<T>(
  options: readonly T[],
  {
    collapsedCount,
    expanded,
    isOn,
    isKept,
    loading = false,
  }: { collapsedCount: number; expanded: boolean; isOn: (option: T) => boolean; isKept?: (option: T) => boolean; loading?: boolean },
): { folds: boolean; shown: readonly T[] } {
  const folds = !loading && options.length > collapsedCount + 2;
  return {
    folds,
    shown: folds && !expanded ? options.filter((option, i) => i < collapsedCount || isOn(option) || isKept?.(option)) : options,
  };
}

export type ShowAllButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children" | "onClick" | "type"> & {
  /** How many options the whole list holds: "Show all 24". */
  total: number;
  /** The whole list shows; the button then reads "Show fewer". */
  expanded: boolean;
  onToggle: () => void;
  /** Formats the number, e.g. "de-DE". Default "en-US". */
  locale?: string;
};

/**
 * The text button that opens a folded list, in the accent colour: "Show all N", then "Show fewer". A 1px line draws in
 * under the words from the start edge while it is hovered or focused. It carries aria-expanded.
 */
export function ShowAllButton({ total, expanded, onToggle, locale, className, ...props }: ShowAllButtonProps) {
  return (
    <button
      type="button"
      aria-expanded={expanded}
      onClick={onToggle}
      className={cn(
        "group/more relative inline-flex h-8 cursor-pointer items-center rounded-[6px] px-1 text-[14px] leading-5 font-medium text-[var(--fu-accent-soft,#8FAAFF)]",
        "transition-[color,scale] duration-200 hover:text-[var(--fu-accent-pale,#D1DDFF)] active:scale-[0.97] active:duration-75 motion-reduce:transition-none",
        "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
        className,
      )}
      {...props}
    >
      <span
        className={cn(
          "bg-[linear-gradient(currentColor,currentColor)] bg-[length:0%_1px] bg-[position:0_100%] rtl:bg-[position:100%_100%] bg-no-repeat pb-px",
          "transition-[background-size] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
          "[@media(hover:hover)]:group-hover/more:bg-[length:100%_1px] group-focus-visible/more:bg-[length:100%_1px]",
        )}
      >
        {expanded ? "Show fewer" : `Show all ${formatsFor(locale).number(total)}`}
      </span>
    </button>
  );
}
```

### components/filters-ui/ui/status-frame.tsx

```tsx
"use client";

import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type RefObject } from "react";
import { cn } from "../lib/cn";
import { SEARCH_ART } from "./art-search";
import { EmptyNote } from "./empty-note";
import { EmptyState } from "./empty-state";
import { ERROR_LINE, ERROR_TEXT, ErrorGlyph, RetryButton } from "./inline-error";
import { LoadingContext, useLoading } from "./skeleton";

/** Where the data stands: shown, on its way, or failed. */
export type Status = "ready" | "loading" | "error";

/**
 * The state props every item takes, with the same names and meanings everywhere, so a person who has learned one
 * filter knows them all. Spread them into an item's own props type.
 */
export type StateProps = {
  /** "loading" draws placeholders the size of the content; "error" shows errorText with a Retry. Default "ready". */
  status?: Status;
  /** Called by the Retry button. Without it the error line has no button. */
  onRetry?: () => void;
  /** The error line. Default "Couldn't load the options." */
  errorText?: string;
  /** The line shown in place of the options when there are none. Default "No options to show" */
  emptyText?: string;
  /** Dims the whole filter, blocks pointer and keyboard input and says so to screen readers. Default false. */
  disabled?: boolean;
};

export const DEFAULT_ERROR_TEXT = "Couldn't load the options.";
export const DEFAULT_EMPTY_TEXT = "No options to show";
export const DEFAULT_LOADING_TEXT = "Loading";

/** How long arriving content keeps its fade-in class: a little more than the 300ms fade. */
const ARRIVAL_MS = 400;

type Mode = "ready" | "loading" | "error" | "empty";

/** A frame around this one is loading and has said "Loading": this one then draws its placeholders without saying it again. */
const SaidLoading = createContext(false);

export type StatusFrameProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
  Omit<StateProps, "emptyText"> & {
    /** There are no options: emptyText shows in place of the content. */
    empty?: boolean;
    emptyText?: ReactNode;
    /** The picture above emptyText: an image address or a node. Default: the search picture. null draws the words alone as one quiet line, for a tight place. */
    emptyArt?: string | ReactNode | null;
    /** Words read once while loading. Default "Loading". */
    loadingText?: string;
    /** Reads loading and errors out. A block that holds several filters turns it off on each and says it once itself. Default true. */
    announce?: boolean;
    retryLabel?: string;
    children: ReactNode;
  };

/**
 * Wraps an item's content and gives it the shared states.
 * - loading: the content stays drawn, inert and busy, and its Skeleton, SkeletonText and CountPill pieces draw as
 *   placeholders of their real size, so nothing moves when the data arrives; the data then fades in once.
 * - error: one calm line and a Retry in place of the content. Loading and errors are read out through one polite
 *   status region that stays on the page.
 * - empty: a picture and one line in place of the content (or the line alone, with emptyArt null).
 * - disabled: dimmed, no pointer or keyboard input (a disabled fieldset turns off every native control inside), and
 *   read as unavailable. Custom focusable parts, such as a grid's cells, also need tabIndex -1 and aria-disabled.
 * When a state change takes away the control that had focus, the frame takes focus, so it is never lost.
 * A frame inside a loading frame draws its placeholders too, and does not say "Loading" again when that frame has said
 * it. So a block can load every filter in it with one quiet frame per card (announce false) and say it once in its head
 * with StatusLine; and a filter whose error must leave its title in place can take loading and disabled on a quiet outer
 * frame and let an inner frame around the part that fails speak.
 */
export function StatusFrame({
  status = "ready",
  onRetry,
  errorText = DEFAULT_ERROR_TEXT,
  empty = false,
  emptyText = DEFAULT_EMPTY_TEXT,
  emptyArt,
  disabled = false,
  loadingText = DEFAULT_LOADING_TEXT,
  announce = true,
  retryLabel,
  className,
  children,
  ...props
}: StatusFrameProps) {
  const frame = useRef<HTMLDivElement>(null);
  const outer = useLoading();
  const saidAbove = useContext(SaidLoading);
  const mode: Mode = status === "loading" ? "loading" : status === "error" ? "error" : empty ? "empty" : "ready";

  // The data arrives when loading turns to ready: its pieces fade in once, then go back to plain content.
  const [lastStatus, setLastStatus] = useState(status);
  const [arriving, setArriving] = useState(false);
  if (status !== lastStatus) {
    setLastStatus(status);
    setArriving(lastStatus === "loading" && status === "ready");
  }
  useEffect(() => {
    if (!arriving) return;
    const timer = setTimeout(() => setArriving(false), ARRIVAL_MS);
    return () => clearTimeout(timer);
  }, [arriving]);

  // Whether focus sat on a control inside, read just before a change of state is drawn.
  const key = `${mode}|${disabled}`;
  const drawnKey = useRef(key);
  const focusWasInside = useRef(false);
  if (key !== drawnKey.current && typeof document !== "undefined") {
    const active = document.activeElement;
    focusWasInside.current = !!frame.current && !!active && active !== frame.current && frame.current.contains(active);
  }
  useLayoutEffect(() => {
    if (drawnKey.current === key) return;
    drawnKey.current = key;
    if (!focusWasInside.current) return;
    focusWasInside.current = false;
    const node = frame.current;
    // The focused control was removed, made inert or disabled: the frame keeps focus instead of the page.
    if (node && (mode !== "ready" || disabled || !node.contains(document.activeElement))) node.focus({ preventScroll: true });
  });

  return (
    <div
      ref={frame}
      tabIndex={-1}
      data-status-frame=""
      data-status={mode}
      aria-busy={mode === "loading" || undefined}
      className={cn(
        "min-w-0 rounded-[12px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
        disabled && "pointer-events-none opacity-50 select-none",
        className,
      )}
      {...props}
    >
      <SaidLoading.Provider value={saidAbove || (mode === "loading" && announce)}>
        <LoadingContext.Provider value={{ loading: mode === "loading" || outer.loading, arriving: arriving || outer.arriving }}>
          {mode === "empty" ? (
            emptyArt === null ? (
              <EmptyNote>{emptyText}</EmptyNote>
            ) : (
              <EmptyState art={emptyArt ?? SEARCH_ART} title={emptyText} className="py-5" />
            )
          ) : mode === "error" ? null : (
            // display: contents, so the fieldset adds no box; while disabled it turns off every native control inside.
            <fieldset role="none" disabled={disabled} inert={mode === "loading"} className="contents">
              {children}
            </fieldset>
          )}
        </LoadingContext.Provider>
      </SaidLoading.Provider>
      <StatusLine
        status={mode === "loading" || mode === "error" ? mode : "ready"}
        onRetry={onRetry}
        errorText={errorText}
        loadingText={saidAbove ? "" : loadingText}
        announce={announce}
        retryLabel={retryLabel}
      />
    </div>
  );
}

export type StatusLineProps = {
  status?: Status;
  /** Called by Retry. Without it the error line has no button. */
  onRetry?: () => void;
  errorText?: string;
  loadingText?: string;
  /** Reads loading and errors out. Off, it leaves "Loading" out and still shows an error. Default true. */
  announce?: boolean;
  retryLabel?: string;
  /** Classes for the line while it shows an error, e.g. its margins. */
  className?: string;
};

/**
 * What a StatusFrame says, on its own: one polite region, on the page in every state so each change is read out.
 * Loading is read as "Loading" and not shown; an error shows as one calm line with Retry; ready says nothing and takes
 * no space. A block that keeps its cards in every state puts it in its head, to say the state once for all of them.
 * Retry hands focus to the nearest element marked data-status-frame (with tabIndex -1) around it.
 */
export function StatusLine({
  status = "ready",
  onRetry,
  errorText = DEFAULT_ERROR_TEXT,
  loadingText = DEFAULT_LOADING_TEXT,
  announce = true,
  retryLabel,
  className,
}: StatusLineProps) {
  const error = status === "error";
  const said = status === "loading" ? (announce ? loadingText : "") : error ? errorText : "";
  return (
    // The words take their own direction, so an English sentence keeps its full stop at its end on a right-to-left page.
    <div className={error ? cn(ERROR_LINE, className) : "contents"}>
      <p role={announce ? "status" : undefined} className={error ? ERROR_TEXT : "sr-only"}>
        {error && <ErrorGlyph />}
        {said && <span dir="auto">{said}</span>}
      </p>
      {error && onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
    </div>
  );
}

/**
 * For a block that leaves controls out by state, such as Clear all while it is disabled: when a change of `key` takes
 * away the control that had focus inside `scope`, `target` (default `scope`, with tabIndex -1) takes focus, so it is
 * never dropped to the page.
 */
export function useFocusKept(scope: RefObject<HTMLElement | null>, key: string, target: RefObject<HTMLElement | null> = scope) {
  const drawn = useRef(key);
  const had = useRef(false);
  if (key !== drawn.current && typeof document !== "undefined") {
    const active = document.activeElement;
    had.current = !!scope.current && !!active && scope.current.contains(active);
  }
  useLayoutEffect(() => {
    if (drawn.current === key) return;
    drawn.current = key;
    if (!had.current) return;
    had.current = false;
    const node = scope.current;
    if (node && !node.contains(document.activeElement)) target.current?.focus({ preventScroll: true });
  });
}
```

### components/filters-ui/ui/art-search.ts

```ts
/**
 * The picture for "nothing matches" and "nothing here": a glass magnifier on a clear background, drawn 56px.
 * It is a file, not code: the shadcn install saves it as public/filters-ui/search.svg. Copying by hand, save
 * https://filtersui.com/filters-ui/search.svg there, or point this at a picture of your own. With no file the empty
 * states show their words alone.
 */
export const SEARCH_ART = "/filters-ui/search.svg";
```

### components/filters-ui/ui/empty-note.tsx

```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";

export type EmptyNoteProps = HTMLAttributes<HTMLDivElement> & {
  /** A 16px glyph in currentColor before the words. */
  icon?: ReactNode;
  /** A button or link after the words, e.g. "Clear search". */
  action?: ReactNode;
};

/**
 * A quiet one-line note in place of a list that has nothing in it: dim 14px words, an optional glyph and an optional
 * action. No illustration and no box, so it sits in the space the options would take.
 */
export function EmptyNote({ icon, action, className, children, ...props }: EmptyNoteProps) {
  return (
    <div className={cn("flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2", className)} {...props}>
      <p className="flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-dim,#929292)]">
        {icon && (
          <span aria-hidden="true" className="mt-0.5 shrink-0 [&_svg]:size-4">
            {icon}
          </span>
        )}
        <span dir="auto">{children}</span>
      </p>
      {action}
    </div>
  );
}
```

### components/filters-ui/ui/empty-state.tsx

```tsx
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "../lib/cn";

export type EmptyStateProps = Omit<HTMLAttributes<HTMLDivElement>, "title"> & {
  /** The picture above the words: an image address, drawn 56px square, or any node of that size. */
  art?: string | ReactNode;
  /** The one line that says what is missing. */
  title: ReactNode;
  /** A link or button under the words, such as "Clear search". */
  action?: ReactNode;
  /** A second, quieter line under the title. */
  children?: ReactNode;
};

// Each part arrives once, a beat after the one above it: the picture comes into focus, the words rise into place.
const ENTER =
  "transition-[opacity,filter,translate,scale] duration-[480ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none starting:opacity-0";

/**
 * What a list shows in the room its options would take when it has none: a picture, one line and an action, stacked
 * in the middle. For a single quiet line with no picture, use EmptyNote.
 */
export function EmptyState({ art, title, action, className, children, ...props }: EmptyStateProps) {
  return (
    <div className={cn("flex min-w-0 max-w-full flex-col items-center text-center", className)} {...props}>
      {art && (
        <span aria-hidden="true" className={cn("mb-3 block size-14 shrink-0", ENTER, "starting:scale-[0.82] starting:blur-[6px]")}>
          {typeof art === "string" ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={art} alt="" width={56} height={56} loading="lazy" decoding="async" draggable={false} className="size-full object-contain select-none" />
          ) : (
            art
          )}
        </span>
      )}
      <p dir="auto" className={cn("max-w-full text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]", ENTER, "delay-[60ms] starting:translate-y-1.5 starting:blur-[2px]")}>
        {title}
      </p>
      {children && (
        <p dir="auto" className={cn("mt-1 max-w-full text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]", ENTER, "delay-[90ms] starting:translate-y-1.5 starting:blur-[2px]")}>
          {children}
        </p>
      )}
      {action && <div className={cn("mt-2 max-w-full", ENTER, "delay-[120ms] starting:translate-y-1.5")}>{action}</div>}
    </div>
  );
}
```

### components/filters-ui/ui/inline-error.tsx

```tsx
"use client";

import type { HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { buttonClasses } from "./button-classes";
import { CircleAlertIcon } from "./icons";

export const DEFAULT_RETRY_LABEL = "Retry";

/** The error line's layout: the words at the start, Retry at the end, wrapping under them when space runs out. */
export const ERROR_LINE = "flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-2";
/** The words: 14px, muted, with a 16px dim alert glyph before them. */
export const ERROR_TEXT = "flex min-w-0 items-start gap-2 text-[14px] leading-5 text-[var(--fu-mute,#BDBDBD)]";

/** The alert glyph that leads the words. Hidden from screen readers. */
export function ErrorGlyph() {
  return <CircleAlertIcon size={16} className="mt-0.5 shrink-0 text-[var(--fu-dim,#929292)]" />;
}

export type RetryButtonProps = {
  onRetry: () => void;
  label?: string;
  className?: string;
};

/**
 * A small grey button that is never shown disabled. Before it calls onRetry it hands focus to the StatusFrame around
 * it, which stays on the page while the content reloads, so focus is never lost with the button.
 */
export function RetryButton({ onRetry, label = DEFAULT_RETRY_LABEL, className }: RetryButtonProps) {
  return (
    <button
      type="button"
      onClick={(event) => {
        event.currentTarget.closest<HTMLElement>("[data-status-frame]")?.focus({ preventScroll: true });
        onRetry();
      }}
      className={buttonClasses({ variant: "secondary", size: "sm", className })}
    >
      {label}
    </button>
  );
}

export type InlineErrorProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
  /** One short line in plain words, e.g. "Couldn't load the options." */
  text: string;
  /** Shows Retry. Without it the line stands alone. */
  onRetry?: () => void;
  retryLabel?: string;
};

/**
 * A calm error in the component's own area: one muted line and a Retry button. The line is a polite status region, so
 * it is read out when it appears. Inside a StatusFrame use the frame's status="error" instead: it keeps one region on
 * the page for loading and errors alike.
 */
export function InlineError({ text, onRetry, retryLabel, className, ...props }: InlineErrorProps) {
  return (
    <div className={cn(ERROR_LINE, className)} {...props}>
      <p role="status" className={ERROR_TEXT}>
        <ErrorGlyph />
        <span dir="auto">{text}</span>
      </p>
      {onRetry && <RetryButton onRetry={onRetry} label={retryLabel} />}
    </div>
  );
}
```

### components/filters-ui/ui/button-classes.ts

```ts
import { cn } from "../lib/cn";

// The button looks as class names. Kept apart from button.tsx, a client module, so server pages can call them too.

export type ButtonVariant = "primary" | "secondary" | "ghost" | "quiet" | "quiet-accent";
export type ButtonSize = "sm" | "md" | "lg";

export const BUTTON_BASE = cn(
  "relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] font-[inherit] font-medium whitespace-nowrap no-underline select-none",
  "[-webkit-tap-highlight-color:transparent] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
  "active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100",
  "outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
  "aria-busy:cursor-progress aria-busy:active:scale-100",
);

const VARIANTS: Record<ButtonVariant, string> = {
  primary:
    "bg-[var(--fu-accent,#3B57E6)] text-[var(--fu-on-accent,#FFFFFF)] hover:bg-[var(--fu-accent-hover,#3450D4)] forced-colors:border forced-colors:border-[ButtonText]",
  secondary:
    "bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]",
  ghost: "bg-transparent text-[var(--fu-text,#F8F5F1)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))]",
  quiet: "bg-transparent text-[var(--fu-mute,#BDBDBD)] hover:text-[var(--fu-text,#F8F5F1)]",
  "quiet-accent":
    "bg-transparent text-[var(--fu-accent-soft,#8FAAFF)] decoration-1 underline-offset-[5px] hover:text-[var(--fu-accent-pale,#D1DDFF)] [@media(hover:hover)]:hover:underline",
};

// Below 44px a touch screen gets a taller invisible target through ::after.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:content-['']";

const SIZES: Record<ButtonSize, { box: string; before: string; after: string }> = {
  sm: { box: cn("h-8 gap-1.5 px-3 text-[13px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-1.5"), before: "ps-2.5", after: "pe-2.5" },
  md: { box: cn("h-10 gap-2 px-3.5 text-[15px] leading-5 [&_svg]:size-4", TAP, "pointer-coarse:after:-inset-y-0.5"), before: "ps-3", after: "pe-3" },
  lg: { box: "h-11 gap-2 px-4 text-[15px] leading-5 [&_svg]:size-[18px]", before: "ps-3.5", after: "pe-3.5" },
};

/** The classes of a button, for a link or a router link that should look like one. */
export function buttonClasses({
  variant = "primary",
  size = "md",
  before = false,
  after = false,
  className,
}: { variant?: ButtonVariant; size?: ButtonSize; before?: boolean; after?: boolean; className?: string } = {}) {
  return cn(BUTTON_BASE, VARIANTS[variant], SIZES[size].box, before && SIZES[size].before, after && SIZES[size].after, className);
}
```

### components/filters-ui/ui/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/demo/body-icons.tsx

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

// Side profiles, one per body style: the outline, then the x of each wheel centre.
export const PROFILES = {
  SUV: [
    "M16 100c0-13 4-22 18-26l46-10 26-30c4-5 9-7 15-7h104c8 0 14 2 19 8l26 34 26 6c6 2 8 6 8 13v24c0 4-3 6-7 6h-16a29 29 0 0 0-56 0H106a29 29 0 0 0-56 0H24c-5 0-8-4-8-12z",
    [78, 253],
  ],
  Sedan: [
    "M18 100c0-11 5-20 19-24l52-11c20-17 43-27 74-27 30 0 54 8 75 25l40 7c12 2 24 9 24 22v12c0 5-3 8-8 8h-20a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-12z",
    [76, 246],
  ],
  Truck: [
    "M14 102c0-14 5-23 19-27l44-9 26-28c4-5 9-7 15-7h62c7 0 11 4 12 10l2 25h104c5 0 8 3 8 8v30c0 5-3 8-8 8h-30a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H22c-5 0-8-4-8-10z",
    [76, 240],
  ],
  Hatchback: [
    "M26 100c0-11 5-20 19-24l44-11c20-18 41-28 72-29 28 0 50 7 66 26l32 16c8 5 13 12 13 22v8c0 4-3 6-7 6h-23a29 29 0 0 0-56 0H112a29 29 0 0 0-56 0H34c-5 0-8-4-8-14z",
    [84, 214],
  ],
  Coupe: [
    "M14 100c0-10 5-17 18-21l66-13c22-16 44-24 72-24 32 0 56 11 76 29l34 7c14 3 26 8 26 20v8c0 8-3 10-8 10h-22a29 29 0 0 0-56 0H106a29 29 0 0 0-56 0H22c-5 0-8-4-8-16z",
    [78, 248],
  ],
  Minivan: [
    "M18 102c0-13 5-22 18-26l40-10 36-32c5-5 11-7 18-7h124c9 0 14 3 19 9l18 31c4 6 6 12 6 20v21c0 4-3 6-7 6h-24a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-12z",
    [76, 238],
  ],
  Van: [
    "M18 102c0-14 4-23 16-27l34-10 22-36c3-5 8-8 14-8h186c8 0 14 6 14 14v75c0 4-3 6-7 6h-29a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-14z",
    [76, 240],
  ],
  Convertible: [
    "M18 100c0-11 5-19 18-23l58-10 18-22 8 1-14 21h116l42 8c11 2 22 8 22 21v10c0 7-3 10-8 10h-22a29 29 0 0 0-56 0H104a29 29 0 0 0-56 0H26c-5 0-8-4-8-16z",
    [76, 228],
  ],
} satisfies Record<string, [string, [number, number]]>;

export type BodyStyle = keyof typeof PROFILES;

/** A car's side profile in currentColor. The wheels are ringed in var(--tile-bg) so they read as cut out of the body. */
export function BodyIcon({ body, ...props }: SVGProps<SVGSVGElement> & { body: BodyStyle }) {
  const [outline, wheels] = PROFILES[body];
  return (
    <svg viewBox="0 0 320 140" height={28} aria-hidden="true" focusable="false" {...props}>
      <path d={outline} fill="currentColor" />
      {wheels.map((x) => (
        <circle key={x} cx={x} cy={112} r={19} fill="currentColor" stroke="var(--tile-bg,var(--fu-card,#1F1F1F))" strokeWidth={7} />
      ))}
    </svg>
  );
}
```

### components/filters-ui/ui/filter-card.tsx

```tsx
"use client";

import { useId, useRef, useState, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { ChevronDownIcon } from "./icons";

export type FilterCardProps = Omit<HTMLAttributes<HTMLElement>, "title" | "children"> & {
  title: string;
  /** The value in words ("Under $45k"). Shown on the closed card; null or empty means the filter is unset. */
  summary?: string | null;
  /** Clears this one filter. When given, a Clear button takes the summary's place while open or hovered. */
  onClear?: () => void;
  /** Controlled open state. Leave undefined to let the card manage it. */
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** Looks like a closed card but cannot be opened or focused, e.g. a filter whose body is not ready. */
  disabled?: boolean;
  /** Accessible name of the Clear button. Default "Clear {title}". */
  clearLabel?: string;
  /** Heading level wrapping the head button. Default 3. */
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  bodyClassName?: string;
  children?: ReactNode;
};

const SMOOTH = "ease-[cubic-bezier(0.22,1,0.36,1)]";

// The summary and Clear share one slot and trade places over 150ms through a 2px blur and 4px shift.
const SUMMARY_HIDDEN = "opacity-0 blur-[2px] -translate-y-1";
const SUMMARY_HIDES_WHEN = [
  "group-data-[state=open]/card:opacity-0 group-data-[state=open]/card:blur-[2px] group-data-[state=open]/card:-translate-y-1",
  "group-hover/slot:opacity-0 group-hover/slot:blur-[2px] group-hover/slot:-translate-y-1",
  "group-focus-within/slot:opacity-0 group-focus-within/slot:blur-[2px] group-focus-within/slot:-translate-y-1",
].join(" ");
// Hovering anywhere on a closed card offers Clear in the summary's place.
const SUMMARY_HIDES_ON_CARD_HOVER = "group-hover/card:opacity-0 group-hover/card:blur-[2px] group-hover/card:-translate-y-1";
const CLEAR_SHOWS_ON_CARD_HOVER = "group-hover/card:opacity-100 group-hover/card:blur-none group-hover/card:translate-y-0";
// A hidden Clear takes no taps: only a pointer that can hover reveals it before a click.
const CLEAR_HIDDEN = "pointer-events-none opacity-0 blur-[2px] translate-y-1 [@media(hover:hover)]:pointer-events-auto";
const CLEAR_SHOWS_WHEN = [
  "group-data-[state=open]/card:pointer-events-auto group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none group-data-[state=open]/card:translate-y-0",
  "group-hover/slot:opacity-100 group-hover/slot:blur-none group-hover/slot:translate-y-0",
  "group-focus-within/slot:opacity-100 group-focus-within/slot:blur-none group-focus-within/slot:translate-y-0",
].join(" ");

const FOCUS_RING =
  "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";

/**
 * One filter in a rounded card: a 52px head (title, value summary or Clear, chevron) that opens a body.
 * Opening animates the height over 480ms and reveals the content from a 6px blur, 6px lower.
 */
export function FilterCard({
  title,
  summary,
  onClear,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  disabled = false,
  clearLabel,
  headingLevel = 3,
  className,
  bodyClassName,
  children,
  ...props
}: FilterCardProps) {
  const id = useId();
  const headId = `${id}-head`;
  const bodyId = `${id}-body`;
  const head = useRef<HTMLButtonElement>(null);
  const [innerOpen, setInnerOpen] = useState(defaultOpen);
  const open = !disabled && (openProp ?? innerOpen);
  const set = Boolean(summary);

  // The last summary stays in place while it fades out after a clear.
  const [lastSummary, setLastSummary] = useState(summary ?? "");
  if (summary && summary !== lastSummary) setLastSummary(summary);

  const setOpen = (next: boolean) => {
    if (openProp === undefined) setInnerOpen(next);
    onOpenChange?.(next);
  };

  const Heading = `h${headingLevel}` as const;
  const swap = cn(
    "transition-[opacity,filter,translate] duration-150 ease-in-out motion-reduce:transition-none",
    "group-data-[state=open]/card:duration-[480ms] group-data-[state=open]/card:ease-[cubic-bezier(0.22,1,0.36,1)]",
  );

  return (
    <section
      data-state={open ? "open" : "closed"}
      data-set={set ? "true" : "false"}
      className={cn(
        "not-prose group/card relative overflow-hidden rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] text-[var(--fu-text,#F8F5F1)]",
        "transition-[background-color,border-color,opacity] duration-200 motion-reduce:transition-none",
        "[@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:border-[var(--fu-line,#404040)] [@media(hover:hover)]:data-[state=closed]:has-[[data-filter-card-head]:enabled:hover,[data-filter-card-slot]:hover]:bg-[var(--fu-card-hover,#262626)]",
        // The head button sits flush in a clipped card, so its focus ring is drawn around the card.
        "has-[[data-filter-card-head]:focus-visible]:outline-2 has-[[data-filter-card-head]:focus-visible]:outline-offset-2 has-[[data-filter-card-head]:focus-visible]:outline-solid has-[[data-filter-card-head]:focus-visible]:outline-[var(--fu-accent-soft,#8FAAFF)]",
        className,
      )}
      {...props}
    >
      <Heading className="m-0 -mb-0.5 text-[15px] font-semibold leading-5 text-[var(--fu-text,#F8F5F1)]">
        <button
          ref={head}
          type="button"
          id={headId}
          data-filter-card-head=""
          aria-expanded={open}
          aria-controls={bodyId}
          disabled={disabled}
          onClick={() => setOpen(!open)}
          className={cn(
            "flex h-[52px] w-full cursor-pointer items-center gap-3 rounded-[23px] px-4 text-start font-[inherit] text-inherit disabled:cursor-default",
            "outline-none",
          )}
        >
          <span className="min-w-0 truncate">{title}</span>
          {set && <span className="sr-only">, {summary}</span>}
          {set && (
            <span aria-hidden="true" className="invisible min-w-0 max-w-[calc((100%+32px)*0.55)] shrink-0 truncate text-[14px] font-normal">
              {summary}
            </span>
          )}
          <ChevronDownIcon
            size={20}
            className={cn(
              "ms-auto shrink-0 text-[var(--fu-mute,#BDBDBD)] group-has-[[data-filter-card-head]:disabled]/card:opacity-40 transition-[rotate] duration-[480ms] motion-reduce:transition-none",
              SMOOTH,
              "group-data-[state=open]/card:rotate-180",
            )}
          />
        </button>
      </Heading>

      {onClear && (
        <div
          inert={!set}
          data-filter-card-slot=""
          className="group/slot pointer-events-none absolute inset-e-[46px] top-4 grid h-5 max-w-[55%] justify-items-end text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]"
        >
          <span aria-hidden="true" className={cn("pointer-events-none max-w-full truncate font-normal [grid-area:1/1]", swap, set ? SUMMARY_HIDES_WHEN : SUMMARY_HIDDEN, set && !disabled && SUMMARY_HIDES_ON_CARD_HOVER)}>
            {summary || lastSummary}
          </span>
          <button
            type="button"
            tabIndex={set ? 0 : -1}
            aria-label={clearLabel ?? `Clear ${title.toLowerCase()}`}
            onClick={() => {
              onClear();
              head.current?.focus();
            }}
            className={cn(
              "relative -my-0.5 cursor-pointer rounded-[6px] py-0.5 font-medium [grid-area:1/1] before:absolute before:inset-x-0 before:-inset-y-2 before:content-['']",
              FOCUS_RING,
              "focus-visible:outline-offset-2",
              swap,
              CLEAR_HIDDEN,
              set && CLEAR_SHOWS_WHEN,
              set && !disabled && CLEAR_SHOWS_ON_CARD_HOVER,
            )}
          >
            Clear
          </button>
        </div>
      )}
      {!onClear && set && (
        <span
          aria-hidden="true"
          className={cn(
            "pointer-events-none absolute inset-e-[46px] top-4 max-w-[55%] truncate text-[14px] leading-5 text-[var(--fu-accent-soft,#8FAAFF)]",
            swap,
            "group-data-[state=open]/card:opacity-0",
          )}
        >
          {summary}
        </span>
      )}

      <div
        id={bodyId}
        role="region"
        aria-labelledby={headId}
        inert={!open}
        className={cn(
          "grid grid-rows-[0fr] transition-[grid-template-rows] duration-[480ms] motion-reduce:transition-none",
          SMOOTH,
          "group-data-[state=open]/card:grid-rows-[1fr]",
        )}
      >
        <div className="min-h-0 overflow-hidden">
          <div
            className={cn(
              // pt-0.5 makes up the head's -2px margin, so content starts right under the 52px head.
              "px-4 pt-0.5 pb-4",
              "translate-y-1.5 opacity-0 blur-[6px] transition-[opacity,filter,translate] duration-[480ms] motion-reduce:transition-none",
              SMOOTH,
              "group-data-[state=open]/card:translate-y-0 group-data-[state=open]/card:opacity-100 group-data-[state=open]/card:blur-none",
              "group-data-[state=open]/card:delay-[120ms] group-data-[state=open]/card:duration-[460ms] group-data-[state=open]/card:ease-[cubic-bezier(0.16,1,0.3,1)]",
              bodyClassName,
            )}
          >
            {children}
          </div>
        </div>
      </div>
    </section>
  );
}
```

## What it does

- Each tile toggles on or off; several can be on.
- The icon takes the accent colour on hover and when on.
- A tile with a count of 0 is dimmed and cannot be turned on.
- Icons are yours: any SVG 28px high, filled with currentColor.
- A long list shows its first 8 tiles and "Show all N"; a long name wraps inside its tile.

## Props and value

IconTiles (components/filters-ui/filters/icon-tiles.tsx) holds this value: V[], where V is a string: the values that are on. [] is no filter.

- options: readonly { value: V; label: string; icon: ReactNode; count: number }[] (required). The tiles. The icon is any SVG drawn in currentColor; var(--tile-bg) is the tile's own background, for cut-outs.
- value: readonly V[] (required). The values that are on.
- onChange: (value: V[]) => void (required). Called with the new list.
- label: string (required). Accessible name of the group.
- formatCount: (n: number) => string (default 1,234). Text in each count pill.
- countLabel: (n: number) => string (default "6 results"). Screen-reader words for a count, e.g. "6 cars".
- locale: string (default "en-US"). Formats the counts and their spoken numbers by default, e.g. "de-DE" prints 1.234. Words stay English.
- collapsedCount: number (default 8). How many tiles show before "Show all N". Tiles that are on always show. A list only folds when it hides three or more.
- 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 options."). The error line, in plain words.
- emptyText: string (default "No options to show"). The line shown under a small picture, in place of the options, when there are none.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.

It sits inside FilterCard (components/filters-ui/ui/filter-card.tsx), the card with the title, the value in words and a Clear button:

- title: string (required). The card's heading, e.g. "Price".
- summary: string | null (optional). The value in words, shown on the closed card. Null or empty means the filter is unset.
- onClear: () => void (optional). Clears this filter. When given, a Clear button takes the summary's place while open or hovered.
- open / defaultOpen / onOpenChange: boolean / boolean / (open: boolean) => void (default closed). Controlled or uncontrolled open state.
- headingLevel: 2 | 3 | 4 | 5 | 6 (default 3). Heading level around the head button.
- bodyClassName: string (optional). Classes for the body, e.g. to tune the space under the content.

## States

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

- Loading (status="loading"): placeholders the size of the real content pulse softly where the data goes, so nothing moves when it arrives. It takes no input. Each tile keeps its edge while its icon, name and count draw as placeholders; with no options yet it draws four placeholder tiles. It is aria-busy and says "Loading" once; when status turns back to "ready" the data fades in once. No spinner.
- Error (status="error", with onRetry and errorText): one calm line and a Retry button that calls onRetry, in the filter's own place. The line is read out politely, Retry is never shown disabled, and focus stays inside the component.
- Empty (no options given, with emptyText): a quiet line in place of the options.
- Zero results (every count is 0): every option stays where it is, dimmed, and cannot be turned on; one that is on can still be turned off.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable.
- Long labels (data, not a prop): A name longer than its tile wraps at its spaces, with the count beside the first line, and the tiles in a row keep one height; a single word too long for the tile ends in an ellipsis, and the tile's spoken name keeps it whole.
- Many options (data, not a prop): The first 8 tiles show (collapsedCount), with any that are on, and "Show all 24" opens the rest.

While it is disabled, leave FilterCard's onClear out, so the card offers no Clear.

## Usage

A working example with a few made-up cars. Imports assume @/ points at the project root; change @/components/filters-ui if this project uses another alias.

```tsx
"use client";

import { useState } from "react";
import { IconTiles } from "@/components/filters-ui/filters/icon-tiles";
import { BodyIcon, type BodyStyle } from "@/components/filters-ui/demo/body-icons";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";

type Car = { name: string; body: BodyStyle };

const CARS: Car[] = [
  { name: "Toyota RAV4", body: "SUV" },
  { name: "Honda CR-V", body: "SUV" },
  { name: "Kia Telluride", body: "SUV" },
  { name: "Toyota Camry", body: "Sedan" },
  { name: "Tesla Model 3", body: "Sedan" },
  { name: "Ford F-150", body: "Truck" },
  { name: "Toyota Tacoma", body: "Truck" },
  { name: "Volkswagen Golf GTI", body: "Hatchback" },
  { name: "Ford Mustang", body: "Coupe" },
  { name: "Toyota Sienna", body: "Minivan" },
  { name: "Ford Transit", body: "Van" },
  { name: "Mazda MX-5", body: "Convertible" },
];

const BODIES: BodyStyle[] = ["SUV", "Sedan", "Truck", "Hatchback", "Coupe", "Minivan", "Van", "Convertible"];

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

const options = BODIES.map((body) => ({
  value: body,
  label: body,
  icon: <BodyIcon body={body} />,
  count: CARS.filter((car) => car.body === body).length,
}));

const summaryOf = (picked: BodyStyle[]) =>
  picked.length === 0 ? null : picked.length <= 2 ? picked.join(", ") : `${picked.slice(0, 2).join(", ")} +${picked.length - 2}`;

export default function BodyStyleExample() {
  const [bodies, setBodies] = useState<BodyStyle[]>([]);
  const results = CARS.filter((car) => bodies.length === 0 || bodies.includes(car.body));

  return (
    <div className="w-full max-w-[320px]">
      <FilterCard
        title="Body style"
        summary={summaryOf(bodies)}
        onClear={() => setBodies([])}
        defaultOpen
      >
        <IconTiles label="Body style" options={options} value={bodies} onChange={setBodies} countLabel={carCount} />
      </FilterCard>
      <p aria-live="polite" className="mt-3 px-4 text-[14px] leading-5 tabular-nums">
        <span className="font-medium">{results.length}</span> <span className="text-[var(--fu-dim,#929292)]">of {CARS.length} cars</span>
      </p>
    </div>
  );
}
```

## Connect it to my data

Ask me which field it filters and where the list of items comes from. Counts are numbers I pass in: work them out from my items, and when there are other filters on the page, count each option with every other filter applied but this one left out, so a count says how many results picking it would give.

## Keep the look

It is dark by default and needs no setup. To change colours, set these CSS variables on :root or on a parent element. These are the dark defaults:

```css
:root {
  --fu-accent: #3B57E6;
  --fu-accent-hover: #3450D4;
  --fu-accent-pale: #D1DDFF;
  --fu-accent-soft: #8FAAFF;
  --fu-card: #1F1F1F;
  --fu-card-border: #2A2A2A;
  --fu-card-hover: #262626;
  --fu-control-border: #737373;
  --fu-control-hover: #A3A3A3;
  --fu-dim: #929292;
  --fu-hover: #333333;
  --fu-hover-wash: rgb(255 255 255/0.14);
  --fu-item-hover: #2A2A2A;
  --fu-line: #404040;
  --fu-mute: #BDBDBD;
  --fu-on-accent: #FFFFFF;
  --fu-pill: rgb(255 255 255/0.1);
  --fu-pill-square: #333333;
  --fu-pill-text: #C8C8C8;
  --fu-selected: #1F2747;
  --fu-skeleton: rgb(255 255 255/0.12);
  --fu-skeleton-on: rgb(143 170 255/0.3);
  --fu-surface-3: #2A2A2A;
  --fu-text: #F8F5F1;
}
```

To turn on the light theme, set these values under this project's own light selector (written as .light here). If it has none, put them on :root inside @media (prefers-color-scheme: light).

```css
.light {
  --fu-accent: #3B57E6;
  --fu-accent-hover: #2F4AD0;
  --fu-accent-pale: #253A9E;
  --fu-accent-soft: #3049D2;
  --fu-card: #FFFFFF;
  --fu-card-border: #E5E5E2;
  --fu-card-hover: #F8F8F6;
  --fu-control-border: #787874;
  --fu-control-hover: #5B5B57;
  --fu-dim: #555552;
  --fu-hover: rgb(29 27 24/0.11);
  --fu-hover-wash: rgb(29 27 24/0.07);
  --fu-item-hover: #F2F2F0;
  --fu-line: #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-selected: #E8EDFD;
  --fu-skeleton: rgb(29 27 24/0.09);
  --fu-skeleton-on: rgb(48 73 210/0.18);
  --fu-surface-3: rgb(29 27 24/0.07);
  --fu-text: #1B1B19;
}
```

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

- Tiles are toggle buttons with aria-pressed, inside a named group.
- Each tile is read as its name and count ("SUV, 3 cars"); the icon is hidden from screen readers.
- Loading, the group is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter.
- Disabled, the group is aria-disabled and every tile is a disabled button; "Show all N" has aria-expanded.
- Each tile is a button: Tab moves between them, Space or Enter toggles.
- "Show all N" is the last stop; while disabled no tile takes focus, and in an error Tab reaches Retry.

When done, run the app, tell me which page to open, and show me the value changing as I use the filter.

What it does

  • Each tile toggles on or off; several can be on.
  • The icon takes the accent colour on hover and when on.
  • A tile with a count of 0 is dimmed and cannot be turned on.
  • Icons are yours: any SVG 28px high, filled with currentColor.
  • A long list shows its first 8 tiles and "Show all N"; a long name wraps inside its tile.

Keyboard

  • Each tile is a button: Tab moves between them, Space or Enter toggles.
  • "Show all N" is the last stop; while disabled no tile takes focus, and in an error Tab reaches Retry.

Props

Value. V[], where V is a string: the values that are on. [] is no filter.

IconTiles props
PropDescription
options
Required

The tiles. The icon is any SVG drawn in currentColor; var(--tile-bg) is the tile's own background, for cut-outs.

readonly { value: V; label: string; icon: ReactNode; count: number }[]
value
Required

The values that are on.

readonly V[]
onChange
Required

Called with the new list.

(value: V[]) => void
label
Required

Accessible name of the group.

string
formatCount
Default 1,234

Text in each count pill.

(n: number) => string
countLabel
Default "6 results"

Screen-reader words for a count, e.g. "6 cars".

(n: number) => string
locale
Default "en-US"

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

string
collapsedCount
Default 8

How many tiles show before "Show all N". Tiles that are on always show. A list only folds when it hides three or more.

number
status
Default "ready"

"loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.

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

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

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

The error line, in plain words.

string
emptyText
Default "No options to show"

The line shown under a small picture, in place of the options, when there are none.

string
disabled
Default false

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

boolean

The card: FilterCard

FilterCard props
PropDescription
title
Required

The card's heading, e.g. "Price".

string
summary
Optional

The value in words, shown on the closed card. Null or empty means the filter is unset.

string | null
onClear
Optional

Clears this filter. When given, a Clear button takes the summary's place while open or hovered.

() => void
open / defaultOpen / onOpenChange
Default closed

Controlled or uncontrolled open state.

boolean / boolean / (open: boolean) => void
headingLevel
Default 3

Heading level around the head button.

2 | 3 | 4 | 5 | 6
bodyClassName
Optional

Classes for the body, e.g. to tune the space under the content.

string

More filters