v1.3.5
Filters

Price range

Pick a price range on a bar chart, with two handles and typed fields.

Live example

165 of 256 cars

Direction
Locale
State

Copy

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

Price range: Pick a price range on a bar chart, with two handles and typed fields.

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/range-histogram.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/range-histogram.tsx

```tsx
"use client";

import { useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";
import { formatsFor } from "../lib/format";
import type { NumberDrag } from "../ui/drag-handle";
import { RangeChart, type RangeValue } from "../ui/range-chart";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextField } from "../ui/text-field";

export type RangeHistogramProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> &
  StateProps & {
  min: number;
  max: number;
  step: number;
  value: RangeValue;
  onChange: (value: RangeValue) => void;
  /** Item count per bar, spread evenly from min to max. */
  buckets?: readonly number[];
  /** Field, tooltip and screen-reader text for a value, e.g. "$45,000". Default: the number in the locale. */
  format?: (value: number) => string;
  /**   * Reads a typed value. Default: the first number in the text, read with the locale's marks ("45.000" is 45000 in
   * de-DE), with an optional k or m suffix, or null when there is none.
   */
  parse?: (text: string) => number | null;
  /** Formats and reads numbers by default, e.g. "de-DE". Default "en-US". */
  locale?: string;
  /** Tooltip text while the high end is open. Default: the top value and a plus. */
  openLabel?: string;
  /** One handle and one field, for an upper limit only. */
  single?: boolean;
  /** Field placeholders. Default "Minimum" and "Maximum". */
  placeholders?: { low?: string; high?: string };
  /** Accessible names of the handles and fields, e.g. "Lowest price". Default: the placeholders. */
  labels?: { low?: string; high?: string };
  /** Bar width as a share of its slot, so a chart with few bars can keep the rhythm of a denser one. Default 1. */
  barScale?: number;
  /** Says loading and errors out loud. Off when the chart sits inside another filter that says them once, as in Budget. Default true. */
  announce?: boolean;
};

/** A range chart with typed Minimum and Maximum fields under it, kept in step both ways. */
export function RangeHistogram({
  min,
  max,
  step,
  value,
  onChange,
  buckets,
  format: formatProp,
  parse: parseProp,
  locale,
  openLabel,
  single = false,
  placeholders,
  labels,
  barScale,
  status = "ready",
  onRetry,
  errorText = "Couldn't load the counts.",
  emptyText = "No items to show",
  disabled = false,
  announce = true,
  className,
  ...props
}: RangeHistogramProps) {
  const formats = formatsFor(locale);
  const format = formatProp ?? formats.number;
  const parse = parseProp ?? formats.readNumber;
  const lowPlaceholder = placeholders?.low ?? "Minimum";
  const highPlaceholder = placeholders?.high ?? "Maximum";
  const lowLabel = labels?.low ?? lowPlaceholder;
  const highLabel = labels?.high ?? highPlaceholder;
  // The handle a field is dragging, and where: the chart moves it and raises its bars as in a drag of its own.
  const [held, setHeld] = useState<{ handle: "low" | "high"; value: number } | null>(null);
  const holding = (handle: "low" | "high") => (at: number | null) => setHeld(at === null ? null : { handle, value: at });

  // A typed number snaps outwards to the step, so nothing typed is left out, and stays inside the range, one step clear of the other end.
  // An empty field, or a value at the very end, leaves that end open.
  const commit = (end: 0 | 1, typed: number | null) => {
    const next: RangeValue = [single ? null : value[0], value[1]];
    if (typed === null) next[end] = null;
    else {
      const round = end === 0 ? Math.floor : Math.ceil;
      const snapped = Math.min(max, Math.max(min, min + round((typed - min) / step) * step));
      if (end === 0) {
        const ceiling = (value[1] ?? max) - step;
        next[0] = snapped <= min ? null : Math.min(snapped, ceiling);
      } else {
        const floor = (single ? min : (value[0] ?? min)) + step;
        next[1] = snapped >= max ? null : Math.max(snapped, floor);
      }
    }
    if (next[0] !== value[0] || next[1] !== value[1]) onChange(next);
  };

  // The frame dims and blocks everything while disabled, so the chart and fields are not dimmed a second time.
  return (
    <div className={cn("pt-1", className)} {...props}>
      <StatusFrame status={status} onRetry={onRetry} errorText={errorText} disabled={disabled} announce={announce}>
        <RangeChart
          min={min}
          max={max}
          step={step}
          value={value}
          onChange={onChange}
          buckets={buckets}
          format={format}
          openLabel={openLabel}
          single={single}
          labels={{ low: lowLabel, high: highLabel }}
          barScale={barScale}
          held={held}
          locale={locale}
          emptyText={emptyText}
        />
        <div className={cn("mt-3 grid gap-2", single ? "grid-cols-1" : "grid-cols-[repeat(auto-fit,minmax(min(100%,7rem),1fr))]")}>
          {!single && (
            <RangeField
              value={value[0]}
              format={format}
              parse={parse}
              label={lowLabel}
              placeholder={lowPlaceholder}
              onCommit={(typed) => commit(0, typed)}
              scale={{ min, max, step, emptyAt: "min", ceiling: (value[1] ?? max) - step, onHold: holding("low") }}
            />
          )}
          <RangeField
            value={value[1]}
            format={format}
            parse={parse}
            label={highLabel}
            placeholder={highPlaceholder}
            onCommit={(typed) => commit(1, typed)}
            scale={{ min, max, step, emptyAt: "max", floor: (single ? min : (value[0] ?? min)) + step, onHold: holding("high") }}
          />
        </div>
      </StatusFrame>
    </div>
  );
}

type RangeFieldProps = {
  value: number | null;
  format: (value: number) => string;
  parse: (text: string) => number | null;
  label: string;
  placeholder: string;
  onCommit: (value: number | null) => void;
  /** The scale the field's drag handle moves along. */
  scale: Omit<NumberDrag, "value" | "onChange">;
};

// Shows the formatted value; while focused it holds what the person types, and commits on Enter or blur. Dragging its
// handle commits each step.
function RangeField({ value, format, parse, label, placeholder, onCommit, scale }: RangeFieldProps) {
  const [draft, setDraft] = useState<string | null>(null);
  const shown = value === null ? "" : format(value);

  const commit = () => {
    if (draft === null) return;
    setDraft(null);
    const typed = draft.trim() ? parse(draft) : null;
    // Text that reads as no number puts the field back rather than dropping the limit.
    if (draft.trim() && (typed === null || !Number.isFinite(typed))) return;
    onCommit(typed);
  };

  return (
    <TextField
      label={label}
      placeholder={placeholder}
      inputMode="numeric"
      autoComplete="off"
      enterKeyHint="done"
      value={draft ?? shown}
      onChange={setDraft}
      onClear={() => {
        setDraft(null);
        onCommit(null);
      }}
      onBlur={commit}
      drag={{
        ...scale,
        value,
        onChange: (dragged) => {
          setDraft(null);
          onCommit(dragged);
        },
      }}
      onKeyDown={(event) => {
        if (event.key === "Enter") {
          event.preventDefault();
          commit();
        } else if (event.key === "Escape" && draft !== null) {
          event.stopPropagation();
          setDraft(null);
        }
      }}
      inputClassName="tabular-nums"
    />
  );
}
```

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

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

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

### components/filters-ui/lib/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/drag-handle.tsx

```tsx
"use client";

import { useEffect, useRef, useState, type CSSProperties, type PointerEvent, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";

export type NumberDrag = {
  /** The number the field holds; null while it is empty. */
  value: number | null;
  /** The scale the field's width stands for. */
  min: number;
  max: number;
  /** Dragged values snap to this. */
  step: number;
  onChange: (value: number) => void;
  /** Where the handle stands while the field is empty. Default "min". */
  emptyAt?: "min" | "max";
  /** The lowest and highest value a drag may reach, inside min and max: the other end of a range, say. */
  floor?: number;
  ceiling?: number;
  /**
   * Called on each move of a drag with the value under the pointer, before it snaps to a step, and with null when the
   * handle is let go: for a chart that should move with the handle.
   */
  onHold?: (value: number | null) => void;
};

type Press = { start: number; width: number; rtl: boolean; grab: number; x: number; last: number | null; moved: boolean; settled: boolean };

/**
 * Turns a number field into a slider as well. With a mouse over the field a thin handle shows where the value stands
 * along the field's width; dragging it fills the field up to the handle and moves the value in steps. A press that does
 * not move puts the caret in the field instead, with its text picked. The field needs the classes "group/field relative
 * isolate": the fill and the handle are drawn behind its text, and only a strip over the handle takes the pointer.
 * While a drag runs the layer carries data-dragging, which a field that grows with its text can use to hold its width.
 * With the pointer on the handle itself it grows and takes the accent colour, as it does while dragged, so it reads as
 * the thing to grab. The accent keeps the digits it crosses readable, which a light handle would not.
 */
export function DragHandle({ drag, input, pad = 12 }: { drag: NumberDrag; input: RefObject<HTMLInputElement | null>; pad?: number }) {
  const { value, min, max, step, onChange, emptyAt = "min" } = drag;
  const strip = useRef<HTMLSpanElement>(null);
  const press = useRef<Press | null>(null);
  const [dragging, setDragging] = useState(false);
  const [near, setNear] = useState(false);
  const hold = useRef(drag.onHold);
  hold.current = drag.onHold;

  const span = max - min || 1;
  const share = (n: number) => Math.min(1, Math.max(0, (n - min) / span));
  const at = share(value ?? (emptyAt === "max" ? max : min));
  // A CSS variable set on the field while dragging takes over from the value, so the handle follows the pointer between steps.
  const place = `calc(${pad}px + var(--drag-at, ${at}) * (100% - ${pad * 2}px))`;

  const pointerShare = (x: number, p: Press) => {
    const f = (x - p.start) / p.width;
    return p.rtl ? 1 - f : f;
  };
  /** Takes the field's box as it is now and keeps the handle where the pointer holds it. */
  const measure = (p: Press, x: number, held: number) => {
    const box = strip.current?.parentElement?.getBoundingClientRect();
    if (!box) return;
    p.start = box.left + pad;
    p.width = Math.max(1, box.width - pad * 2);
    p.grab = pointerShare(x, p) - held;
  };

  // A drag cut short by the field going away (loading, disabled) must not leave its place on the field.
  useEffect(() => {
    const field = strip.current?.parentElement;
    return () => {
      field?.style.removeProperty("--drag-at");
      if (press.current?.moved) hold.current?.(null);
    };
  }, []);

  const down = (event: PointerEvent<HTMLSpanElement>) => {
    // A frame turns its filter off with a disabled fieldset; the strip is no control, so it asks the field.
    if (event.button !== 0 || !strip.current || input.current?.matches(":disabled")) return;
    // Keeps the press from starting a text selection or moving focus; a press that never moves focuses the field on release.
    event.preventDefault();
    const p: Press = { start: 0, width: 1, rtl: isRtl(strip.current), grab: 0, x: event.clientX, last: value, moved: false, settled: false };
    measure(p, event.clientX, at);
    press.current = p;
    event.currentTarget.setPointerCapture(event.pointerId);
  };

  const move = (event: PointerEvent<HTMLSpanElement>) => {
    const p = press.current;
    if (!p) return;
    if (!p.moved) {
      if (Math.abs(event.clientX - p.x) < 3) return;
      // A field that grows with its text takes its widest size for the drag (see data-dragging); the next move
      // measures it at that size, so the handle stays under the pointer from then on.
      p.moved = true;
      setDragging(true);
      return;
    }
    if (!p.settled) {
      p.settled = true;
      measure(p, event.clientX, share(p.last ?? (emptyAt === "max" ? max : min)));
    }
    const floor = drag.floor ?? min;
    const ceiling = drag.ceiling ?? max;
    const to = Math.min(share(ceiling), Math.max(share(floor), pointerShare(event.clientX, p) - p.grab));
    strip.current?.parentElement?.style.setProperty("--drag-at", String(to));
    drag.onHold?.(min + to * span);
    // Snapped to the step, kept between the floor and the ceiling (a typed floor may sit off the steps), and written
    // with the step's own decimals, so 0.1 steps do not come out as 0.30000000000000004.
    const snapped = Math.min(ceiling, Math.max(floor, min + Math.round((to * span) / step) * step));
    const next = Number(snapped.toFixed((String(step).split(".")[1] ?? "").length));
    if (next !== p.last) {
      p.last = next;
      onChange(next);
    }
  };

  const up = (event: PointerEvent<HTMLSpanElement>, cancelled = false) => {
    const p = press.current;
    if (!p) return;
    press.current = null;
    strip.current?.parentElement?.style.removeProperty("--drag-at");
    if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
    setDragging(false);
    if (p.moved) drag.onHold?.(null);
    if (!p.moved && !cancelled) {
      input.current?.focus();
      input.current?.select();
    }
  };

  return (
    <>
      <span
        aria-hidden="true"
        data-dragging={dragging || undefined}
        data-near={near || dragging || undefined}
        className="group/drag pointer-events-none absolute inset-0 -z-10 overflow-hidden rounded-[inherit]"
      >
        <span
          className="absolute inset-y-0 inset-s-0 bg-[var(--fu-wash,rgb(255_255_255/0.08))] opacity-0 transition-opacity duration-200 motion-reduce:transition-none group-data-[dragging]/drag:opacity-100"
          style={{ width: place }}
        />
        <span
          // Centred on its place with a start margin, which follows the field's own direction: a left-to-right
          // number pill keeps it right inside a right-to-left page, where a mirrored translate would not.
          className={cn(
            "absolute top-1/2 -ms-[1.5px] h-5 w-[3px] -translate-y-1/2 rounded-full bg-[var(--fu-control-border,#737373)] opacity-0 in-[fieldset:disabled]:hidden",
            "transition-[opacity,background-color,scale] duration-150 motion-reduce:transition-none forced-colors:bg-[CanvasText]",
            "pointer-fine:group-hover/field:opacity-100 group-data-[near]/drag:bg-[var(--fu-accent,#3B57E6)] group-data-[near]/drag:opacity-100",
            "group-data-[near]/drag:scale-x-150 group-data-[near]/drag:scale-y-125",
          )}
          style={{ insetInlineStart: place } as CSSProperties}
        />
      </span>
      <span
        ref={strip}
        aria-hidden="true"
        onPointerDown={down}
        onPointerMove={move}
        onPointerUp={(event) => up(event)}
        onPointerCancel={(event) => up(event, true)}
        onPointerEnter={() => setNear(true)}
        onPointerLeave={() => setNear(false)}
        // Inside a <label> a click would hand focus to the field after a drag; focus is given on release instead.
        onClick={(event) => event.preventDefault()}
        className="pointer-events-none absolute inset-y-0 -ms-2 w-4 cursor-ew-resize touch-none in-[fieldset:disabled]:hidden pointer-fine:pointer-events-auto"
        style={{ insetInlineStart: place } as CSSProperties}
      />
    </>
  );
}
```

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

```ts
// Right-to-left helpers for positions and keys worked out in script. Each reads the direction from the element
// itself, so it is right when only a parent sets dir="rtl".

/** True when the element lays out right to left. */
export const isRtl = (node: Element | null | undefined) => !!node && getComputedStyle(node).direction === "rtl";

/**
 * The arrow key as a step in reading order: in right-to-left, ArrowLeft moves forward and ArrowRight back, as the
 * ARIA patterns ask for horizontal widgets. Every other key comes back as it is.
 */
export function readingKey(key: string, node: Element | null | undefined): string {
  if ((key !== "ArrowLeft" && key !== "ArrowRight") || !isRtl(node)) return key;
  return key === "ArrowLeft" ? "ArrowRight" : "ArrowLeft";
}

/** A child's offset from its offset parent's start edge: its offsetLeft, or the distance from the right in RTL. */
export function startOffset(node: HTMLElement): number {
  if (!isRtl(node)) return node.offsetLeft;
  const parent = node.offsetParent as HTMLElement | null;
  return (parent?.clientWidth ?? 0) - node.offsetLeft - node.offsetWidth;
}

/** Calls back whenever a dir attribute on the page changes, so a position measured in script can be taken again. */
export function onDirChange(callback: () => void): () => void {
  if (typeof MutationObserver === "undefined") return () => {};
  const observer = new MutationObserver(callback);
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ["dir"], subtree: true });
  return () => observer.disconnect();
}
```

### components/filters-ui/ui/range-chart.tsx

```tsx
"use client";

import { useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type PointerEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { isRtl, readingKey } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { EmptyNote } from "./empty-note";
import { SKELETON_FILL, useLoading } from "./skeleton";

/** [low, high]. null is an open end: no lower or no upper limit. */
export type RangeValue = [number | null, number | null];

type Handle = "low" | "high";

export type RangeChartProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> & {
  min: number;
  max: number;
  step: number;
  value: RangeValue;
  onChange: (value: RangeValue) => void;
  /** Item count per bar, spread evenly from min to max. Leave out for a plain slider. */
  buckets?: readonly number[];
  /** Tooltip and screen-reader text for a value. Gets the handle too, for scales where the high handle reads one step back. */
  format?: (value: number, handle: "low" | "high") => string;
  /** Tooltip text while the high end is open. Default: the top value and a plus ("$100,000+"). */
  openLabel?: string;
  /** One handle, for an upper limit only. The low end of `value` is ignored; the handle stops one step above min. */
  single?: boolean;
  /** Accessible names of the handles. */
  labels?: { low?: string; high?: string };
  /** Bar width as a share of its slot, so a chart with few bars can keep the rhythm of a denser one. Default 1. */
  barScale?: number;
  /**
   * A handle that something outside the chart is dragging, a field of its own say, with the value under its pointer.
   * The chart draws that handle there and raises the bars it passes, as in a drag of its own, without the tooltip.
   */
  held?: { handle: "low" | "high"; value: number } | null;
  /** Formats values when no format is given, e.g. "de-DE". */
  locale?: string;
  disabled?: boolean;
  /**
   * Draws pulsing columns in a calm hill and a pulsing rail, with no handles, in the space the chart takes.
   * Default: the nearest StatusFrame's loading state.
   */
  loading?: boolean;
  /** Shown, quiet, in the bars' place when buckets is an empty list. Default "No items to show" */
  emptyText?: ReactNode;
};

const HANDLE = 20;
/** Columns a loading chart draws when it has no buckets yet. */
const PLACEHOLDER_BARS = 20;

/** A loading column's height in percent: a soft hill, highest a third of the way along, as many prices are. */
export const hillAt = (i: number, n: number) => {
  const x = (i + 0.5) / n;
  return Math.round(18 + 64 * Math.exp(-(((x - 0.38) / 0.24) ** 2)));
};
// A press on a handle becomes a drag only after it travels this far, so a click does not show the tooltip.
const DRAG_FROM = 3;

const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));

// A handle stops at the end of the track, so the bars, the fill and the tooltip share the handle's travel.
const along = (fraction: number) => `calc(${HANDLE / 2}px + (100% - ${HANDLE}px) * ${fraction})`;

type Drag = { handle: Handle; fraction: number; moving: boolean };

/**
 * A bar chart of how many items sit along a range, with one or two handles on a track under it.
 * Each handle is backed by a visually hidden native range input for keyboards and screen readers. Right to left, the
 * scale runs from the right: the minimum sits at the right end and the Left arrow raises a value.
 */
export function RangeChart({
  min,
  max,
  step,
  value,
  onChange,
  buckets,
  format: formatProp,
  openLabel,
  single = false,
  labels,
  barScale = 1,
  held,
  locale,
  disabled = false,
  loading: loadingProp,
  emptyText = "No items to show",
  className,
  ...props
}: RangeChartProps) {
  const status = useLoading();
  const loading = loadingProp ?? status.loading;
  const format: (value: number, handle: Handle) => string = formatProp ?? formatsFor(locale).number;
  const root = useRef<HTMLDivElement>(null);
  const tip = useRef<HTMLSpanElement>(null);
  const grip = useRef<{ x: number; shift: number; handle: Handle; stacked: boolean; box: DOMRect } | null>(null);
  const pressed = useRef(false);
  const [drag, setDrag] = useState<Drag | null>(null);
  const [lastHeld, setLastHeld] = useState<Handle>("high");
  const [tipHalf, setTipHalf] = useState(0);

  const span = max - min || 1;
  const snap = (v: number) => clamp(min + Math.round((v - min) / step) * step, min, max);
  const low = single ? min : clamp(value[0] ?? min, min, max);
  const high = clamp(value[1] ?? max, Math.min(low + step, max), max);
  const values = { low, high };
  const fractionOf = (v: number) => (v - min) / span;
  const stepFraction = step / span;

  const emit = (nextLow: number, nextHigh: number) => {
    const next: RangeValue = [single || nextLow <= min ? null : nextLow, nextHigh >= max ? null : nextHigh];
    if (next[0] !== value[0] || next[1] !== value[1]) onChange(next);
  };

  // Handles never cross: each stops one step short of the other. Returns where the handle landed.
  const moveTo = (handle: Handle, v: number) => {
    if (handle === "low") {
      const next = Math.min(snap(v), high - step);
      emit(next, high);
      return next;
    }
    const next = Math.max(snap(v), low + step);
    emit(low, next);
    return next;
  };

  // A drag passes the box it measured at press, so moves do not force a layout read each event.
  const fractionAt = (clientX: number, box = root.current?.getBoundingClientRect()) => {
    if (!box) return 0;
    const fromStart = isRtl(root.current) ? box.right - clientX : clientX - box.left;
    return clamp((fromStart - HANDLE / 2) / (box.width - HANDLE), 0, 1);
  };

  // Where each handle is drawn: a dragged one sits under the pointer, the other at its value. A handle held from
  // outside is drawn the same way.
  const pulled = !drag && held ? { handle: held.handle, fraction: clamp(fractionOf(held.value), 0, 1) } : null;
  const shown = { low: fractionOf(low), high: fractionOf(high) };
  if (drag) shown[drag.handle] = drag.fraction;
  else if (pulled) shown[pulled.handle] = pulled.fraction;

  const nearest = (v: number): Handle => {
    if (single || v > high) return "high";
    if (v < low) return "low";
    return v - low < high - v ? "low" : "high";
  };

  // A press on a bar gives the nearest handle that bar's outer edge, so the bar stays in the range.
  // A press on the rail moves the nearest handle to the step under the pointer.
  const land = (clientX: number, onBar: boolean) => {
    const at = min + fractionAt(clientX) * span;
    if (onBar && buckets?.length) {
      const size = span / buckets.length;
      const bar = clamp(Math.floor((at - min) / size), 0, buckets.length - 1);
      const handle = nearest(min + (bar + 0.5) * size);
      return { handle, value: moveTo(handle, min + (handle === "low" ? bar : bar + 1) * size) };
    }
    const handle = nearest(at);
    return { handle, value: moveTo(handle, at) };
  };

  const press = (event: PointerEvent<HTMLDivElement>) => {
    pressed.current = false;
    if (disabled || event.button !== 0) return;
    const target = event.target as HTMLElement;
    const handle = target.closest<HTMLElement>("[data-handle]")?.dataset.handle as Handle | undefined;
    // A finger landing off a handle may be starting a scroll, so a tap waits for its click.
    if (!handle && event.pointerType === "touch") return;
    event.preventDefault();
    pressed.current = true;
    try {
      event.currentTarget.setPointerCapture(event.pointerId);
    } catch {}
    const box = event.currentTarget.getBoundingClientRect();
    const landed = handle ? null : land(event.clientX, !!target.closest("[data-bars]"));
    const held = handle ?? landed!.handle;
    const startFraction = fractionOf(handle ? values[handle] : landed!.value);
    // Handles one step apart overlap, so the first move picks which one is pulled out of the stack.
    const stacked = !!handle && !single && high - low <= step;
    grip.current = { x: event.clientX, shift: startFraction - fractionAt(event.clientX, box), handle: held, stacked, box };
    setLastHeld(held);
    setDrag({ handle: held, fraction: startFraction, moving: false });
    (root.current?.querySelector(`input[data-for="${held}"]`) as HTMLInputElement | null)?.focus({ preventScroll: true });
  };

  const follow = (event: PointerEvent<HTMLDivElement>) => {
    const g = grip.current;
    if (!g || !drag) return;
    if (!drag.moving && Math.abs(event.clientX - g.x) < DRAG_FROM) return;
    if (g.stacked) {
      const pulled: Handle = event.clientX < g.x !== isRtl(root.current) ? "low" : "high";
      g.stacked = false;
      if (pulled !== g.handle) {
        g.shift += fractionOf(values[pulled]) - fractionOf(values[g.handle]);
        g.handle = pulled;
        setLastHeld(pulled);
        (root.current?.querySelector(`input[data-for="${pulled}"]`) as HTMLInputElement | null)?.focus({ preventScroll: true });
      }
    }
    const [floor, ceiling] =
      g.handle === "low" ? [0, fractionOf(high) - stepFraction] : [fractionOf(low) + stepFraction, 1];
    const fraction = clamp(fractionAt(event.clientX, g.box) + g.shift, floor, ceiling);
    setDrag({ handle: g.handle, fraction, moving: true });
    moveTo(g.handle, min + fraction * span);
  };

  const release = () => {
    grip.current = null;
    setDrag(null);
  };

  const dragging = !!drag?.moving;
  const tipHandle = drag?.handle ?? lastHeld;
  // An open end is no limit, so it does not read as the end value.
  const textOf = (handle: Handle) =>
    handle === "high" && value[1] === null ? (openLabel ?? `${format(max, "high")}+`) : format(values[handle], handle);
  const tipText = textOf(tipHandle);

  useLayoutEffect(() => {
    if (tip.current) setTipHalf(tip.current.offsetWidth / 2);
  }, [tipText]);

  const tallest = Math.max(1, ...(buckets ?? []));
  // While a handle is dragged, the bars it passes rise a little, in a soft wave centred on the handle.
  const wave = dragging && drag ? drag.fraction : pulled ? pulled.fraction : null;
  const bumpAt = wave !== null && buckets?.length ? wave * buckets.length - 0.5 : null;
  const bumpOf = (i: number) => {
    if (bumpAt === null) return 0;
    const near = Math.max(0, 1 - Math.abs(i - bumpAt) / 2.4);
    return near * near;
  };
  // The rise is a few fixed pixels plus a small share of the bar, so a short bar shows it as clearly as a tall one.
  // It grows the height rather than scaling the bar, and stops at the top of the bar area: a card around the chart
  // clips anything above it, which would cut the rounded top flat.
  const heightOf = (share: number, bump: number) =>
    bump ? `min(100%, calc(${share}% + ${bump} * var(--lift, 1) * (5px + ${0.13 * share}%)))` : `${share}%`;
  const lowShown = single ? 0 : shown.low;
  const handles: Handle[] = single ? ["high"] : ["low", "high"];
  const columns = buckets?.length || PLACEHOLDER_BARS;

  return (
    <div
      ref={root}
      data-dragging={dragging || !!pulled || undefined}
      data-disabled={disabled || undefined}
      className={cn(
        "group/range relative cursor-pointer touch-pan-y select-none [-webkit-tap-highlight-color:transparent]",
        "data-[dragging]:cursor-grabbing data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
        className,
      )}
      onPointerDown={press}
      onPointerMove={follow}
      onPointerUp={release}
      onPointerCancel={release}
      onLostPointerCapture={release}
      onClick={(event) => {
        if (!pressed.current && !disabled) land(event.clientX, !!(event.target as HTMLElement).closest("[data-bars]"));
        pressed.current = false;
      }}
      {...props}
    >
      {buckets && buckets.length === 0 && !loading && (
        <EmptyNote className="mx-[10px] h-14 justify-center">{emptyText}</EmptyNote>
      )}
      {buckets && (buckets.length > 0 || loading) && (
        <div
          data-bars
          aria-hidden
          className="mx-[10px] flex h-14 items-end gap-[2px] motion-reduce:[--lift:0]"
          // Many bars close their gaps up, a 2px gap at most and a quarter of a bar's slot at least, so bars never vanish.
          style={columns > 40 ? { gap: `min(2px, calc(100% / ${columns * 4}))` } : undefined}
        >
          {loading
            ? Array.from({ length: columns }, (_, i) => (
                <span
                  key={i}
                  className={cn(
                    "min-w-0 flex-1 rounded-t-[3px]",
                    SKELETON_FILL,
                    "transition-[height,background-color] duration-[420ms,200ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                  )}
                  style={{ height: `${hillAt(i, columns)}%` }}
                />
              ))
            : buckets.map((count, i) => {
                const start = i / buckets.length;
                const end = (i + 1) / buckets.length;
                const cover = clamp((Math.min(end, shown.high) - Math.max(start, lowShown)) / (end - start), 0, 1);
                const lit = cover > 0 ? Math.round((0.35 + 0.65 * cover) * 100) : 0;
                const narrow = barScale !== 1;
                const bar = (
                  <span
                    key={i}
                    className={cn(
                      "min-w-0 rounded-t-[3px]",
                      narrow ? "flex-none" : "flex-1",
                      "transition-[height,background-color] duration-[420ms,200ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                      // While dragging, the wave follows the handle exactly; it eases back when the handle is let go.
                      "group-data-[dragging]/range:transition-none",
                      // Forced colours would drop the inline fill, and the chart with it.
                      "forced-colors:[forced-color-adjust:none]",
                    )}
                    style={{
                      height: heightOf(Math.max(count ? 8 : 3, (count / tallest) * 100), bumpOf(i)),
                      backgroundColor: `color-mix(in srgb, var(--fu-accent-soft,#8FAAFF) ${lit}%, var(--fu-bar-out,#4A4A4A))`,
                      // The bar a denser chart would draw: its slot plus one 2px gap, scaled, less the gap.
                      width: narrow ? `calc((100% + 2px) * ${barScale} - 2px)` : undefined,
                    } as CSSProperties}
                  />
                );
                return narrow ? (
                  <span key={i} className="flex h-full min-w-0 flex-1 items-end justify-center">
                    {bar}
                  </span>
                ) : (
                  bar
                );
              })}
        </div>
      )}

      <div className="relative h-6">
        <span
          aria-hidden
          className={cn(
            "absolute inset-x-0 top-[10px] h-1 rounded-[2px] transition-[background-color] duration-200 motion-reduce:transition-none",
            loading ? SKELETON_FILL : "bg-[var(--fu-rail,#4A4A4A)] forced-colors:bg-[GrayText] forced-colors:[forced-color-adjust:none]",
          )}
        />
        <span
          aria-hidden
          className={cn(
            "absolute top-[10px] h-1 rounded-[2px] bg-[var(--fu-accent-soft,#8FAAFF)] forced-colors:bg-[Highlight] forced-colors:[forced-color-adjust:none]",
            // While loading the fill and handles are hidden; they fade in with the data.
            loading && "opacity-0",
            "transition-[left,right,opacity] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
            "group-data-[dragging]/range:transition-none",
          )}
          style={{ insetInlineStart: single ? 0 : along(lowShown), insetInlineEnd: along(1 - shown.high) }}
        />
        {handles.map((handle) => {
          const grabbed = (drag ?? pulled)?.handle === handle;
          const label = labels?.[handle] ?? (handle === "low" ? "Minimum" : "Maximum");
          return (
            <span key={handle} className="contents">
              <input
                type="range"
                data-for={handle}
                aria-label={label}
                aria-valuetext={
                  handle === "high" && value[1] === null ? "No maximum" : handle === "low" && value[0] === null ? "No minimum" : format(values[handle], handle)
                }
                min={single ? min + step : min}
                max={max}
                step={step}
                value={values[handle]}
                disabled={disabled}
                onChange={(event) => moveTo(handle, Number(event.target.value))}
                // Left and Right follow the screen in RTL too, the same in every browser.
                onKeyDown={(event) => {
                  const key = readingKey(event.key, event.currentTarget);
                  if (key === event.key) return;
                  event.preventDefault();
                  moveTo(handle, values[handle] + (key === "ArrowRight" ? step : -step));
                }}
                className="peer pointer-events-none absolute inset-0 m-0 h-full w-full opacity-0"
              />
              <span
                data-handle={handle}
                data-grabbed={grabbed || undefined}
                className={cn(
                  loading && "opacity-0",
                  "absolute top-[2px] -ms-[10px] size-5 cursor-grab touch-none rounded-full bg-[var(--fu-handle,#F8F5F1)]",
                  "shadow-[0_0_0_0_color-mix(in_srgb,var(--fu-accent-soft,#8FAAFF)_28%,transparent),0_0_0_1px_var(--fu-handle-edge,rgb(0_0_0/0.25)),0_2px_6px_var(--fu-shadow,rgb(0_0_0/0.5))]",
                  "transition-[left,scale,box-shadow,opacity] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                  "before:absolute before:-inset-[10px] before:rounded-full before:content-['']",
                  "hover:scale-[1.15]",
                  "peer-focus-visible:z-[1] data-[grabbed]:z-[1] data-[grabbed]:scale-[1.15] data-[grabbed]:cursor-grabbing",
                  "data-[grabbed]:shadow-[0_0_0_6px_color-mix(in_srgb,var(--fu-accent-soft,#8FAAFF)_28%,transparent),0_0_0_1px_var(--fu-handle-edge,rgb(0_0_0/0.25)),0_2px_6px_var(--fu-shadow,rgb(0_0_0/0.5))]",
                  "group-data-[dragging]/range:data-[grabbed]:transition-[scale,box-shadow]",
                  "peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-solid peer-focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
                  "forced-colors:bg-[CanvasText] forced-colors:[forced-color-adjust:none] forced-colors:peer-focus-visible:outline-[Highlight]",
                )}
                style={{ insetInlineStart: along(shown[handle]) }}
              />
            </span>
          );
        })}
      </div>

      <span
        ref={tip}
        aria-hidden
        data-state={dragging ? "open" : "closed"}
        className={cn(
          "pointer-events-none absolute bottom-10 z-[2] -translate-x-1/2 rtl:translate-x-1/2 rounded-[8px] px-2 py-1 whitespace-nowrap",
          "bg-[var(--fu-text,#F8F5F1)] text-[13px] leading-[18px] font-medium text-[var(--fu-surface-1,#171717)] tabular-nums",
          "transition-[opacity,translate] duration-150 ease-in-out motion-reduce:transition-none",
          "data-[state=closed]:translate-y-1 data-[state=closed]:opacity-0",
        )}
        style={
          {
            insetInlineStart: `clamp(${tipHalf}px, ${along(shown[tipHandle])}, calc(100% - ${tipHalf}px))`,
          } as CSSProperties
        }
      >
        {tipText}
      </span>
    </div>
  );
}
```

### 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/skeleton.tsx

```tsx
"use client";

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

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

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

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

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

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

export type SkeletonProps = HTMLAttributes<HTMLSpanElement>;

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

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

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

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

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

```tsx
"use client";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### components/filters-ui/ui/empty-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/ui/text-field.tsx

```tsx
"use client";

import { useRef, type InputHTMLAttributes, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { DragHandle, type NumberDrag } from "./drag-handle";
import { XIcon } from "./icons";
import { ARRIVING, Skeleton, useLoading } from "./skeleton";

export type TextFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "onChange" | "prefix" | "size"> & {
  value: string;
  onChange: (value: string) => void;
  /** Accessible name. Shown only to screen readers; the placeholder is the visible label. */
  label: string;
  /** Text or an icon before the value, e.g. "$". */
  prefix?: ReactNode;
  /** Shows a 16px clear button while the field has a value. Defaults to emptying the value. */
  onClear?: () => void;
  clearLabel?: string;
  /** For a field that holds a number: a handle to drag it along a scale, as on a slider. See DragHandle. */
  drag?: NumberDrag;
  className?: string;
  inputClassName?: string;
};

/** 44px field, 12px radius, 1px --fu-field-border border, 15px text, optional prefix and clear X. */
export function TextField({
  value,
  onChange,
  label,
  prefix,
  onClear,
  clearLabel,
  drag,
  className,
  inputClassName,
  disabled,
  ...props
}: TextFieldProps) {
  const input = useRef<HTMLInputElement>(null);
  const filled = value.length > 0;
  // Inside a loading StatusFrame the box stays and a bar stands in for the words, which fade in once when they arrive.
  const { loading, arriving } = useLoading();

  return (
    <div
      className={cn(
        "flex h-11 min-w-0 items-center gap-1.5 rounded-[12px] border border-[var(--fu-field-border,#737373)] bg-[var(--fu-input,rgb(0_0_0/0))] px-3",
        "text-[15px] leading-5 text-[var(--fu-text,#F8F5F1)] transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none",
        "hover:border-[var(--fu-control-hover,#A3A3A3)] focus-within:border-[var(--fu-accent-soft,#8FAAFF)] focus-within:hover:border-[var(--fu-accent-soft,#8FAAFF)]",
        "focus-within:shadow-[inset_0_0_0_1px_var(--fu-accent-soft,#8FAAFF)]",
        disabled && "pointer-events-none opacity-50",
        drag && "group/field relative isolate",
        className,
      )}
      onPointerDown={(event) => {
        if (event.target === event.currentTarget) {
          event.preventDefault();
          input.current?.focus();
        }
      }}
    >
      {prefix != null && <span className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">{prefix}</span>}
      {loading && <Skeleton className="h-3 w-[45%] max-w-28 rounded-[4px]" />}
      <input
        key={loading ? "loading" : "ready"}
        ref={input}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        aria-label={label}
        disabled={disabled}
        className={cn(
          "h-full min-w-0 flex-1 bg-transparent text-ellipsis text-inherit tabular-nums outline-none",
          "placeholder:text-[var(--fu-mute,#BDBDBD)]",
          inputClassName,
          loading && "sr-only",
          arriving && ARRIVING,
        )}
        {...props}
      />
      {filled && !loading && (
        <button
          type="button"
          aria-label={clearLabel ?? `Clear ${label.toLowerCase()}`}
          onClick={() => {
            if (onClear) onClear();
            else onChange("");
            input.current?.focus();
          }}
          className={cn(
            // Above the drag handle's layer, so the cross can always be pressed.
            "relative z-[1] -me-1 grid size-6 shrink-0 cursor-pointer place-items-center rounded-[6px] text-[var(--fu-mute,#BDBDBD)]",
            "transition-colors duration-150 hover:text-[var(--fu-text,#F8F5F1)]",
            "focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]",
          )}
        >
          <XIcon size={16} />
        </button>
      )}
      {drag && !loading && !disabled && <DragHandle drag={drag} input={input} />}
    </div>
  );
}
```

### components/filters-ui/ui/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

- Bars show how many items sit along the range; bars inside the range light up.
- Drag a handle, press a bar or the rail, or type a number: the chart and fields stay in step. Under a mouse each field shows a thin handle of its own: drag it and the field fills like a slider, while the chart's handle and bars move with it.
- Typed values accept "45000", "45,000", "$45k" or "1.2m" and snap outwards to the step.
- A handle at either end, or an empty field, leaves that end open.
- Handles never cross: each stops one step short of the other.

## Props and value

RangeHistogram (components/filters-ui/filters/range-histogram.tsx) holds this value: [number | null, number | null]: [low, high]. null is an open end, so [null, null] is no limit.

- min: number (required). Bottom of the scale.
- max: number (required). Top of the scale. A high end here reads as no upper limit.
- step: number (required). Handles and typed values snap to this.
- value: [number | null, number | null] (required). The range. null is an open end.
- onChange: (value: [number | null, number | null]) => void (required). Called with the new range.
- buckets: readonly number[] (optional). Item count per bar, spread evenly from min to max. Leave out for a plain slider.
- format: (value: number) => string (default 1,234). Text for a value in the field, the tooltip and screen readers, e.g. "$45,000".
- parse: (text: string) => number | null (default reads "45k" and "1.2m"). Reads a typed value, with the locale's marks. Return null when the text holds no number.
- locale: string (default "en-US"). Formats values by default and reads typed numbers the locale's way: "45.000" is forty-five thousand in de-DE. Words stay English.
- openLabel: string (default max and "+"). Tooltip text while the high end is open, e.g. "$100,000+".
- single: boolean (default false). One handle and one field, for an upper limit only.
- placeholders: { low?: string; high?: string } (default Minimum, Maximum). Field placeholders.
- labels: { low?: string; high?: string } (default the placeholders). Accessible names of the handles and fields, e.g. "Lowest price".
- barScale: number (default 1). Bar width as a share of its slot, so a chart with few bars keeps the rhythm of a denser one.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.
- status: "ready" | "loading" | "error" (default "ready"). "loading" draws placeholders the size of the real content, so nothing moves when the data arrives; "error" shows errorText and a Retry button in its place.
- onRetry: () => void (optional). Called by Retry in the error state. Without it the error line has no button.
- errorText: string (default "Couldn't load the counts."). The error line, in plain words.
- emptyText: string (default "No items to show"). The quiet line shown where the bars go when buckets is an empty list.
- announce: boolean (default true). Says loading and errors out loud. Turn it off when the chart sits inside another filter that says them once, as in Budget.

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. The bars draw as pulsing columns in a soft hill and the rail pulses; the handles hide and each field shows a placeholder bar. 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): buckets is an empty list: emptyText sits quietly where the bars go, and the handles and fields still work.
- Zero results (every count is 0): Every bucket is 0: the bars lie flat along the rail, and the range can still be set.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable.
- Many options (data, not a prop): Many buckets: from 40 bars the gaps narrow, to a quarter of a bar's slot, so no bar vanishes.

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 { RangeHistogram } from "@/components/filters-ui/filters/range-histogram";
import type { RangeValue } from "@/components/filters-ui/ui/range-chart";
import { FilterCard } from "@/components/filters-ui/ui/filter-card";

type Car = { name: string; price: number };

const CARS: Car[] = [
  { name: "Toyota Corolla", price: 21900 },
  { name: "Honda Civic", price: 24500 },
  { name: "Mazda CX-5", price: 27400 },
  { name: "Toyota RAV4", price: 29900 },
  { name: "Hyundai Tucson", price: 31200 },
  { name: "Subaru Outback", price: 33800 },
  { name: "Tesla Model 3", price: 38700 },
  { name: "Ford Mustang", price: 41500 },
  { name: "Kia Telluride", price: 46500 },
  { name: "Ford F-150", price: 52900 },
  { name: "BMW X3", price: 54800 },
  { name: "Chevrolet Corvette", price: 89900 },
];

const MIN = 0;
const MAX = 100000;
const STEP = 2500;
const BARS = 20;

const whole = new Intl.NumberFormat("en-US");
const tenths = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 });
const money = (value: number) => `$${whole.format(value)}`;
const short = (value: number) => (value >= 1000 ? `$${tenths.format(value / 1000)}k` : money(value));

// How many cars fall in each bar; a dearer car counts in the last one.
const buckets = Array.from({ length: BARS }, () => 0);
for (const { price } of CARS) {
  buckets[Math.min(BARS - 1, Math.floor(((price - MIN) / (MAX - MIN)) * BARS))] += 1;
}

function summaryOf([low, high]: RangeValue) {
  if (low !== null && high !== null) return `${short(low)} to ${short(high)}`;
  if (high !== null) return `Under ${short(high)}`;
  if (low !== null) return `Over ${short(low)}`;
  return null;
}

export default function PriceExample() {
  const [price, setPrice] = useState<RangeValue>([null, null]);
  const [low, high] = price;
  const results = CARS.filter((car) => (low === null || car.price >= low) && (high === null || car.price <= high));

  return (
    <div className="w-full max-w-[320px]">
      <FilterCard
        title="Price"
        summary={summaryOf(price)}
        onClear={() => setPrice([null, null])}
        defaultOpen
      >
        <RangeHistogram
          min={MIN}
          max={MAX}
          step={STEP}
          value={price}
          onChange={setPrice}
          buckets={buckets}
          format={money}
          labels={{ low: "Lowest price", high: "Highest price" }}
        />
      </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-bar-out: #4A4A4A;
  --fu-card: #1F1F1F;
  --fu-card-border: #2A2A2A;
  --fu-card-hover: #262626;
  --fu-control-border: #737373;
  --fu-control-hover: #A3A3A3;
  --fu-dim: #929292;
  --fu-field-border: #737373;
  --fu-handle: #F8F5F1;
  --fu-handle-edge: rgb(0 0 0/0.25);
  --fu-hover: #333333;
  --fu-hover-wash: rgb(255 255 255/0.14);
  --fu-input: rgb(0 0 0/0);
  --fu-line: #404040;
  --fu-mute: #BDBDBD;
  --fu-on-accent: #FFFFFF;
  --fu-rail: #4A4A4A;
  --fu-shadow: rgb(0 0 0/0.5);
  --fu-skeleton: rgb(255 255 255/0.12);
  --fu-skeleton-on: rgb(143 170 255/0.3);
  --fu-surface-1: #171717;
  --fu-surface-3: #2A2A2A;
  --fu-text: #F8F5F1;
  --fu-wash: rgb(255 255 255/0.08);
}
```

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

```css
.light {
  --fu-accent: #3B57E6;
  --fu-accent-hover: #2F4AD0;
  --fu-accent-pale: #253A9E;
  --fu-accent-soft: #3049D2;
  --fu-bar-out: #D6D6D2;
  --fu-card: #FFFFFF;
  --fu-card-border: #E5E5E2;
  --fu-card-hover: #F8F8F6;
  --fu-control-border: #787874;
  --fu-control-hover: #5B5B57;
  --fu-dim: #555552;
  --fu-field-border: #949490;
  --fu-handle: #FFFFFF;
  --fu-handle-edge: rgb(29 27 24/0.55);
  --fu-hover: rgb(29 27 24/0.11);
  --fu-hover-wash: rgb(29 27 24/0.07);
  --fu-input: #FFFFFF;
  --fu-line: #C4C4C0;
  --fu-mute: #444442;
  --fu-on-accent: #FFFFFF;
  --fu-rail: #D6D6D2;
  --fu-shadow: rgb(36 36 33/0.12);
  --fu-skeleton: rgb(29 27 24/0.09);
  --fu-skeleton-on: rgb(48 73 210/0.18);
  --fu-surface-1: #FFFFFF;
  --fu-surface-3: rgb(29 27 24/0.07);
  --fu-text: #1B1B19;
  --fu-wash: rgb(29 27 24/0.05);
}
```

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

## Direction and language

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

## Keep the accessibility

- Each handle is a native range input with its own name ("Lowest price") and a spoken value; an open end reads "No minimum" or "No maximum".
- The fields carry names even though only placeholders show.
- The tooltip and bars are hidden from screen readers; the inputs carry the meaning.
- Loading, it is aria-busy and says "Loading" once; an error is read out politely, and Retry keeps focus in the filter. Disabled, the handles and fields are disabled inputs.
- Tab reaches each handle, then each field.
- Arrow keys move the focused handle by one step; Home and End jump to the ends. Right to left, Left raises the value and Right lowers it.
- Enter or leaving a field applies what was typed; Escape puts the field back.
- While disabled the handles and fields leave the tab order; 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

  • Bars show how many items sit along the range; bars inside the range light up.
  • Drag a handle, press a bar or the rail, or type a number: the chart and fields stay in step. Under a mouse each field shows a thin handle of its own: drag it and the field fills like a slider, while the chart's handle and bars move with it.
  • Typed values accept "45000", "45,000", "$45k" or "1.2m" and snap outwards to the step.
  • A handle at either end, or an empty field, leaves that end open.
  • Handles never cross: each stops one step short of the other.

Keyboard

  • Tab reaches each handle, then each field.
  • Arrow keys move the focused handle by one step; Home and End jump to the ends. Right to left, Left raises the value and Right lowers it.
  • Enter or leaving a field applies what was typed; Escape puts the field back.
  • While disabled the handles and fields leave the tab order; in an error Tab reaches Retry.

Props

Value. [number | null, number | null]: [low, high]. null is an open end, so [null, null] is no limit.

RangeHistogram props
PropDescription
min
Required

Bottom of the scale.

number
max
Required

Top of the scale. A high end here reads as no upper limit.

number
step
Required

Handles and typed values snap to this.

number
value
Required

The range. null is an open end.

[number | null, number | null]
onChange
Required

Called with the new range.

(value: [number | null, number | null]) => void
buckets
Optional

Item count per bar, spread evenly from min to max. Leave out for a plain slider.

readonly number[]
format
Default 1,234

Text for a value in the field, the tooltip and screen readers, e.g. "$45,000".

(value: number) => string
parse
Default reads "45k" and "1.2m"

Reads a typed value, with the locale's marks. Return null when the text holds no number.

(text: string) => number | null
locale
Default "en-US"

Formats values by default and reads typed numbers the locale's way: "45.000" is forty-five thousand in de-DE. Words stay English.

string
openLabel
Default max and "+"

Tooltip text while the high end is open, e.g. "$100,000+".

string
single
Default false

One handle and one field, for an upper limit only.

boolean
placeholders
Default Minimum, Maximum

Field placeholders.

{ low?: string; high?: string }
labels
Default the placeholders

Accessible names of the handles and fields, e.g. "Lowest price".

{ low?: string; high?: string }
barScale
Default 1

Bar width as a share of its slot, so a chart with few bars keeps the rhythm of a denser one.

number
disabled
Default false

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

boolean
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 counts."

The error line, in plain words.

string
emptyText
Default "No items to show"

The quiet line shown where the bars go when buckets is an empty list.

string
announce
Default true

Says loading and errors out loud. Turn it off when the chart sits inside another filter that says them once, as in Budget.

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