v1.3.5
Filters

Applied filters

The filters in use as a row of chips, each with its value and a cross, and Clear all at the end.

Live example

Add

  • Hyundai Tucson2022 · 46,256 km · Hybrid$21,695
  • Ford Escape2021 · 71,609 km · Hybrid$22,895
  • Honda CR-V2021 · 68,843 km · Hybrid$24,295
  • Honda CR-V2022 · 45,240 km · Hybrid$31,195

12 of 256 cars

Direction
Locale
State

Copy

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

Applied filters: The filters in use as a row of chips, each with its value and a cross, and Clear all at the end.

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/applied-filters.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/applied-filters.tsx

```tsx
"use client";

import { useCallback, useLayoutEffect, useRef, useState, type HTMLAttributes, type KeyboardEvent } from "react";
import { cn } from "../lib/cn";
import { isRtl, readingKey } from "../lib/direction";
import { EmptyNote } from "../ui/empty-note";
import { XIcon } from "../ui/icons";
import { StatusFrame, type StateProps } from "../ui/status-frame";
import { TextSwap } from "../ui/text-swap";

export type AppliedFilter = {
  /** Stable id, handed back to onRemove. */
  key: string;
  /** The filter's name, drawn dim: "Price". */
  label: string;
  /** Its value in words, drawn bright: "$15k to $45k". */
  value: string;
};

export type AppliedFiltersProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
  Pick<StateProps, "disabled"> & {
  /** The filters in use, in display order. */  filters: readonly AppliedFilter[];
  /** Called with a filter's key when its chip is pressed. */
  onRemove: (key: string) => void;
  /** When given, Clear all ends the row while two or more filters are in use. It is left out while disabled. */
  onClearAll?: () => void;
  clearAllLabel?: string;
  /** Accessible name of the list. Default "Applied filters". */
  label?: string;
  /** The quiet line shown in place of the chips while no filter is in use. Default "No filters applied" */
  emptyText?: string;
};

type Box = { x: number; y: number; w: number; h: number };

const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";
const CLEAR_KEY = "\u0000clear-all";
// A changed chip flashes these; when the page sets no --fu-* variables the fallbacks inside are used.
const TINT = "var(--fu-selected,#1F2747)";
const PALE = "var(--fu-accent-pale,#D1DDFF)";
const fallbackOf = (value: string) => value.slice(value.indexOf(",") + 1, -1);

const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

const FOCUS =
  "outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-[var(--fu-accent-soft,#8FAAFF)]";
// Below 44px a touch screen gets a taller invisible target.
const TAP = "pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1.5 pointer-coarse:after:content-['']";
const PRESS =
  "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";

/** How far a running move has carried an element, so a new move starts where it is seen. */
function translateOf(node: HTMLElement) {
  const transform = getComputedStyle(node).transform;
  if (!transform || transform === "none") return { x: 0, y: 0 };
  const matrix = new DOMMatrixReadOnly(transform);
  return { x: matrix.m41, y: matrix.m42 };
}

/**
 * The filters in use as a row of chips, "Price $15k to $45k" with a cross, and Clear all at the end. A removed chip
 * blurs away where it stood while the chips after it glide into the gap, across lines too, and the row's height
 * eases when a line empties. Clear all takes the chips away one after another from the end. With no filter in use a
 * quiet line takes the row's place, fading in once the last chip has gone. A value too long for the row is cut with
 * an ellipsis, and the chip then shows it whole on hover.
 */
export function AppliedFilters({
  filters,
  onRemove,
  onClearAll,
  clearAllLabel = "Clear all",
  label = "Applied filters",
  emptyText = "No filters applied",
  disabled = false,
  className,
  ...props
}: AppliedFiltersProps) {
  const root = useRef<HTMLDivElement>(null);
  const box = useRef<HTMLDivElement>(null);
  const list = useRef<HTMLUListElement>(null);
  const note = useRef<HTMLDivElement>(null);
  const noteWas = useRef<{ node: HTMLElement; box: Box } | null>(null);
  const ghosts = useRef<HTMLDivElement>(null);
  const boxes = useRef(new Map<string, Box>());
  const nodes = useRef(new Map<string, HTMLElement>());
  const values = useRef(new Map<string, string>());
  const last = useRef<{ width: number; height: number; rtl: boolean } | null>(null);
  const focusNext = useRef<{ index: number; from: string } | null>(null);
  const [said, setSaid] = useState("");
  // Clear all cannot run while disabled, so it is left out; focus on it moves to the row's frame.
  const showClear = Boolean(onClearAll) && filters.length > 1 && !disabled;
  const listKey = filters.map((f) => f.key).join("\n");

  // A chip, or Clear all, that goes away with focus on it because the filters changed elsewhere hands focus on as a
  // removal does: to the chip now in its place, or to the row.
  const drawnKey = useRef(listKey);
  if (drawnKey.current !== listKey) {
    const active = typeof document === "undefined" ? null : document.activeElement;
    const item = active instanceof HTMLElement && list.current?.contains(active) ? active.closest<HTMLElement>("[data-key]") : null;
    const was = drawnKey.current.split("\n");
    const stays = item?.dataset.key === CLEAR_KEY ? showClear : filters.some((f) => f.key === item?.dataset.key);
    if (item && !stays && !focusNext.current) {
      focusNext.current = { index: item.dataset.key === CLEAR_KEY ? was.length : was.indexOf(item.dataset.key ?? ""), from: drawnKey.current };
    }
    drawnKey.current = listKey;
  }

  // A chip that leaves is copied into a layer over the row at its old place and fades there; React has already
  // removed the real one, so the row's own layout is always the truth.
  const ghost = useCallback((node: HTMLElement, box: Box, delay: number) => {
    const layer = ghosts.current;
    if (!layer) return;
    const copy = node.cloneNode(true) as HTMLElement;
    copy.removeAttribute("data-key");
    copy.inert = true;
    Object.assign(copy.style, {
      position: "absolute",
      left: `${box.x}px`,
      top: `${box.y}px`,
      width: `${box.w}px`,
      height: `${box.h}px`,
      margin: "0",
      transform: "",
    });
    layer.append(copy);
    const fade = copy.animate(
      [
        { opacity: 1, transform: "scale(1)", filter: "blur(0)" },
        { opacity: 0, transform: "scale(0.86)", filter: "blur(2px)" },
      ],
      { duration: 200, delay, easing: "cubic-bezier(0.42, 0, 0.58, 1)", fill: "both" },
    );
    fade.onfinish = () => copy.remove();
    fade.oncancel = () => copy.remove();
  }, []);

  const observer = useRef<ResizeObserver | null>(null);

  const reflow = useCallback(() => {
    const wrap = root.current;
    const row = list.current;
    const content = box.current;
    if (!wrap || !row || !content) return;
    const width = row.offsetWidth;
    const rtl = isRtl(row);
    // A new width or a direction flip moves every chip at once; that is measured again, not played as a move.
    const animate = last.current !== null && last.current.width === width && last.current.rtl === rtl && !reducedMotion();
    const seen = new Set<string>();
    const entering: HTMLElement[] = [];
    const changed: HTMLElement[] = [];

    for (const node of Array.from(row.children) as HTMLElement[]) {
      const key = node.dataset.key;
      if (!key) continue;
      seen.add(key);
      const next = { x: node.offsetLeft, y: node.offsetTop, w: node.offsetWidth, h: node.offsetHeight };
      const prev = boxes.current.get(key);
      // Only a change of place moves a chip; a running move is picked up where it is seen, not restarted.
      if (animate && prev && (prev.x !== next.x || prev.y !== next.y)) {
        const now = translateOf(node);
        const dx = prev.x + now.x - next.x;
        const dy = prev.y + now.y - next.y;
        if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) {
          node.getAnimations().forEach((animation) => animation.id === "move" && animation.cancel());
          const move = node.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "translate(0, 0)" }], {
            duration: 420,
            easing: EASE,
          });
          move.id = "move";
        }
      } else if (animate && !prev) {
        entering.push(node);
      }
      const value = node.dataset.value;
      // A value cut short by the row shows whole on hover; one that fits needs no tooltip.
      const text = node.querySelector<HTMLElement>("[data-chip-value] > span");
      const chip = node.querySelector<HTMLElement>("button");
      if (text && chip && value !== undefined) {
        if (text.scrollWidth > text.clientWidth) chip.title = `${node.querySelector("[data-chip-label]")?.textContent ?? ""}: ${value}`;
        else chip.removeAttribute("title");
      }
      if (animate && value !== undefined && values.current.get(key) !== value) changed.push(node);
      if (value !== undefined) values.current.set(key, value);
      boxes.current.set(key, next);
      nodes.current.set(key, node);
    }

    // The last chip leaves first, so Clear all reads as the row folding back towards its start.
    const gone = [...boxes.current.entries()].filter(([key]) => !seen.has(key)).sort(([, a], [, b]) => b.y - a.y || b.x - a.x);
    gone.forEach(([key, box], i) => {
      const node = nodes.current.get(key);
      if (node) observer.current?.unobserve(node);
      if (animate && node) ghost(node, box, i * 40);
      boxes.current.delete(key);
      nodes.current.delete(key);
      values.current.delete(key);
    });

    entering.forEach((node, i) =>
      node.animate(
        [
          { opacity: 0, transform: "scale(0.9)", filter: "blur(2px)" },
          { opacity: 1, transform: "scale(1)", filter: "blur(0)" },
        ],
        { duration: 260, delay: 80 + i * 40, easing: EASE, fill: "backwards" },
      ),
    );

    // A chip that arrives or changes value starts in the selected blue and settles, so the eye finds what changed.
    for (const node of changed) {
      const chip = node.querySelector<HTMLElement>("button");
      if (!chip) continue;
      const style = getComputedStyle(chip);
      const tint = style.getPropertyValue("--fu-selected").trim() || fallbackOf(TINT);
      const pale = style.getPropertyValue("--fu-accent-pale").trim() || fallbackOf(PALE);
      chip.animate([{ backgroundColor: tint }], { duration: 1600, easing: EASE });
      chip.querySelector<HTMLElement>("[data-chip-value]")?.animate([{ color: pale }], { duration: 1600, easing: EASE });
    }

    // The empty line fades in once the leaving chips are gone, and blurs away like a chip when filters come back.
    const leaving = gone.length ? Math.min(gone.length - 1, 6) * 40 + 140 : 0;
    const shown = note.current;
    if (shown && !noteWas.current && animate) {
      shown.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, delay: leaving, easing: EASE, fill: "backwards" });
    }
    if (!shown && noteWas.current && animate) ghost(noteWas.current.node, noteWas.current.box, 0);
    noteWas.current = shown ? { node: shown, box: { x: shown.offsetLeft, y: shown.offsetTop, w: shown.offsetWidth, h: shown.offsetHeight } } : null;

    const height = content.offsetHeight;
    if (animate && last.current && last.current.height !== height) {
      const running = wrap.getAnimations().find((animation) => animation.id === "height");
      const from = running ? wrap.getBoundingClientRect().height : last.current.height;
      running?.cancel();
      // Shrinking waits for the leaving chips to fade, so what sits below never slides over them.
      const wait = height < from ? leaving : 0;
      const ease = wrap.animate([{ height: `${from}px` }, { height: `${height}px` }], { duration: 420, delay: wait, easing: EASE, fill: "backwards" });
      ease.id = "height";
    }
    last.current = { width, height, rtl };
  }, [ghost]);

  // A value that changes width (its text swaps over ~300ms) moves the chips after it too.
  useLayoutEffect(() => {
    if (typeof ResizeObserver === "undefined") return;
    observer.current = new ResizeObserver(() => reflow());
    return () => observer.current?.disconnect();
  }, [reflow]);

  useLayoutEffect(() => {
    reflow();
    const row = list.current;
    if (row && observer.current) {
      observer.current.observe(row);
      for (const node of Array.from(row.children)) observer.current.observe(node);
    }
    const pending = focusNext.current;
    if (pending && pending.from !== listKey) {
      focusNext.current = null;
      const buttons = row ? Array.from(row.querySelectorAll<HTMLButtonElement>("button")) : [];
      (pending.index < 0 ? root.current : (buttons[Math.min(pending.index, buttons.length - 1)] ?? root.current))?.focus();
    }
  });

  const remove = (filter: AppliedFilter, index: number) => {
    focusNext.current = { index, from: listKey };
    setSaid(`${filter.label} removed`);
    onRemove(filter.key);
  };

  const clearAll = () => {
    focusNext.current = { index: -1, from: listKey };
    setSaid("All filters removed");
    onClearAll?.();
  };

  // Left and Right step between chips, the way they sit on screen; Backspace or Delete removes the one in focus.
  const onKeyDown = (event: KeyboardEvent<HTMLUListElement>) => {
    const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>("button"));
    const at = buttons.indexOf(document.activeElement as HTMLButtonElement);
    if (at < 0) return;
    const key = readingKey(event.key, event.currentTarget);
    if (key === "ArrowRight" || key === "ArrowLeft") {
      event.preventDefault();
      buttons[Math.max(0, Math.min(buttons.length - 1, at + (key === "ArrowRight" ? 1 : -1)))].focus();
    } else if ((event.key === "Backspace" || event.key === "Delete") && at < filters.length) {
      event.preventDefault();
      remove(filters[at], at);
    }
  };

  return (
    <div ref={root} tabIndex={-1} className={cn("not-prose relative outline-none", className)} {...props}>
      {/* Under the row, so chips that glide into a gap pass over the one fading out. */}
      <div ref={ghosts} aria-hidden="true" className="pointer-events-none absolute inset-0" />
      <div ref={box}>
        <StatusFrame disabled={disabled} announce={false}>
          <ul ref={list} aria-label={label} onKeyDown={onKeyDown} className="relative m-0 flex list-none flex-wrap items-center gap-2 p-0">
            {filters.map((filter, index) => (
              <li key={filter.key} data-key={filter.key} data-value={filter.value} className="flex max-w-full">
                <button
                  type="button"
                  aria-label={`Remove ${filter.label}: ${filter.value}`}
                  onClick={() => remove(filter, index)}
                  className={cn(
                    "group/chip relative inline-flex h-8 max-w-full cursor-pointer items-center gap-1.5 rounded-[9px] pe-1.5 ps-3 font-[inherit] text-[14px] leading-5 whitespace-nowrap",
                    "bg-[var(--fu-surface-3,#2A2A2A)] [@media(hover:hover)]:hover:bg-[var(--fu-hover,#333333)]",
                    PRESS,
                    FOCUS,
                    TAP,
                  )}
                >
                  <span
                    aria-hidden="true"
                    data-chip-label=""
                    className="shrink-0 text-[var(--fu-dim,#929292)] transition-[color] duration-200 motion-reduce:transition-none [@media(hover:hover)]:group-hover/chip:text-[var(--fu-mute,#BDBDBD)]"
                  >
                    {filter.label}
                  </span>{" "}
                  <TextSwap
                    aria-hidden="true"
                    data-chip-value=""
                    className="min-w-0 grid-cols-[minmax(0,1fr)] font-medium text-[var(--fu-text,#F8F5F1)] [&>span]:truncate"
                  >
                    {filter.value}
                  </TextSwap>
                  <span
                    aria-hidden="true"
                    className={cn(
                      "ms-0.5 flex size-5 shrink-0 items-center justify-center rounded-[6px] text-[var(--fu-dim,#929292)] transition-[color,background-color] duration-200",
                      "group-hover/chip:bg-[var(--fu-line,#404040)] group-hover/chip:text-[var(--fu-text,#F8F5F1)] group-focus-visible/chip:text-[var(--fu-text,#F8F5F1)]",
                    )}
                  >
                    <XIcon size={14} strokeWidth={2.25} />
                  </span>
                </button>
              </li>
            ))}
            {showClear && (
              <li data-key={CLEAR_KEY} className="flex">
                <button
                  type="button"
                  onClick={clearAll}
                  className={cn(
                    "relative inline-flex h-8 cursor-pointer items-center rounded-[9px] px-2.5 font-[inherit] text-[14px] font-medium leading-5 whitespace-nowrap",
                    "text-[var(--fu-mute,#BDBDBD)] hover:bg-[var(--fu-hover-wash,rgb(255_255_255/0.14))] hover:text-[var(--fu-text,#F8F5F1)]",
                    PRESS,
                    FOCUS,
                    TAP,
                  )}
                >
                  {clearAllLabel}
                </button>
              </li>
            )}
          </ul>
        </StatusFrame>
        {filters.length === 0 && (
          <div ref={note}>
            <EmptyNote>{emptyText}</EmptyNote>
          </div>
        )}
      </div>
      <p className="sr-only" aria-live="polite">
        {said}
      </p>
    </div>
  );
}
```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```tsx
"use client";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```tsx
"use client";

import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react";
import { cn } from "../lib/cn";

export type TextSwapProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
  /** The text to show. A change animates: the old text leaves upward, the new one rises in. */
  children: string;
};

const EASE = "cubic-bezier(0.42, 0, 0.58, 1)";

const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/** Old text leaves over 150ms; new text enters over 170ms after 110ms; both move 4px through a 2px blur. */
export function TextSwap({ children, className, ...props }: TextSwapProps) {
  const [shown, setShown] = useState(children);
  const [leaving, setLeaving] = useState<{ text: string; key: number } | null>(null);
  const nowRef = useRef<HTMLSpanElement>(null);
  const oldRef = useRef<HTMLSpanElement>(null);

  if (children !== shown) {
    setLeaving(reducedMotion() ? null : { text: shown, key: (leaving?.key ?? 0) + 1 });
    setShown(children);
  }

  useLayoutEffect(() => {
    if (!leaving) return;
    const out = oldRef.current?.animate(
      [
        { opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
        { opacity: 0, transform: "translateY(-4px)", filter: "blur(2px)" },
      ],
      { duration: 150, easing: EASE, fill: "forwards" },
    );
    const into = nowRef.current?.animate(
      [
        { opacity: 0, transform: "translateY(4px)", filter: "blur(2px)" },
        { opacity: 1, transform: "translateY(0)", filter: "blur(0)" },
      ],
      { duration: 170, delay: 110, easing: EASE, fill: "backwards" },
    );
    const key = leaving.key;
    const done = () => setLeaving((current) => (current?.key === key ? null : current));
    if (into) into.onfinish = done;
    else done();
    return () => {
      out?.cancel();
      into?.cancel();
    };
  }, [leaving]);

  return (
    <span className={cn("inline-grid whitespace-nowrap", className)} {...props}>
      <span ref={nowRef} className="[grid-area:1/1]">
        {shown}
      </span>
      {leaving && (
        <span ref={oldRef} key={leaving.key} aria-hidden="true" className="pointer-events-none [grid-area:1/1]">
          {leaving.text}
        </span>
      )}
    </span>
  );
}
```

## What it does

- Each chip reads as the filter's name, dim, then its value, bright: "Price $15k to $45k".
- A removed chip blurs away in place while the chips after it glide into the gap, across lines too.
- The row's height eases when a line empties; Clear all takes the chips away one by one from the end.
- A value that changes swaps with a short blur, and the chips after it make room.
- Chips wrap onto as many lines as they need; on touch screens each is 44px tall to tap.

## Props and value

AppliedFilters (components/filters-ui/filters/applied-filters.tsx) holds this value: None of its own: it shows the { key, label, value } list you make from your filters and calls onRemove with a key.

- filters: readonly { key: string; label: string; value: string }[] (required). The filters in use, in display order: a name ("Price") and the value in words ("$15k to $45k").
- onRemove: (key: string) => void (required). Called with a filter's key when its chip is pressed. Clear that filter.
- onClearAll: () => void (optional). When given, Clear all ends the row while two or more filters are in use; it is left out while disabled.
- clearAllLabel: string (default "Clear all"). Text of the Clear all button.
- label: string (default "Applied filters"). Accessible name of the list.
- emptyText: string (default "No filters applied"). The quiet line shown in place of the chips while no filter is in use.
- disabled: boolean (default false). Dims the whole filter, blocks pointer and keyboard input and reads as unavailable.

## States

Keep each of these states as it is.

- Empty (no options given, with emptyText): No filter in use: a quiet line, "No filters applied", takes the row's place. After Clear all it fades in once the last chip has gone.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. Every chip and its cross are off, and Clear all is left out.
- Long labels (data, not a prop): A value too long for the row is cut with an ellipsis and shows whole on hover; the chip's name holds every word, and Clear all moves to the next line rather than being pushed out.
- Many options (data, not a prop): Chips wrap onto as many lines as they need, with Clear all at the end of the last.

## 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 { AppliedFilters, type AppliedFilter } from "@/components/filters-ui/filters/applied-filters";

type Car = { name: string; price: number; body: string; fuel: string; year: number };

const CARS: Car[] = [
  { name: "Toyota RAV4", price: 31900, body: "SUV", fuel: "Hybrid", year: 2021 },
  { name: "Honda CR-V", price: 33500, body: "SUV", fuel: "Hybrid", year: 2022 },
  { name: "Toyota Highlander", price: 44500, body: "SUV", fuel: "Hybrid", year: 2020 },
  { name: "Kia Sportage", price: 29400, body: "SUV", fuel: "Hybrid", year: 2019 },
  { name: "Lexus RX", price: 52900, body: "SUV", fuel: "Hybrid", year: 2022 },
  { name: "Mazda CX-5", price: 27400, body: "SUV", fuel: "Gas", year: 2021 },
  { name: "Ford Escape", price: 24800, body: "SUV", fuel: "Gas", year: 2020 },
  { name: "Tesla Model Y", price: 41900, body: "SUV", fuel: "Electric", year: 2023 },
  { name: "Toyota Camry", price: 26900, body: "Sedan", fuel: "Hybrid", year: 2021 },
  { name: "Honda Civic", price: 21900, body: "Sedan", fuel: "Gas", year: 2022 },
  { name: "Hyundai Elantra", price: 18900, body: "Sedan", fuel: "Hybrid", year: 2018 },
  { name: "Ford F-150", price: 38900, body: "Truck", fuel: "Gas", year: 2020 },
];

type Filters = { price: [number, number] | null; body: string | null; fuel: string | null };

const START: Filters = { price: [15000, 45000], body: "SUV", fuel: "Hybrid" };
const NONE: Filters = { price: null, body: null, fuel: null };

const short = (n: number) => `$${n / 1000}k`;
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });

// One chip per filter in use: its name, then its value in words.
function chipsOf(f: Filters): AppliedFilter[] {
  const chips: AppliedFilter[] = [];
  if (f.price) chips.push({ key: "price", label: "Price", value: `${short(f.price[0])} to ${short(f.price[1])}` });
  if (f.body) chips.push({ key: "body", label: "Body style", value: f.body });
  if (f.fuel) chips.push({ key: "fuel", label: "Fuel", value: f.fuel });
  return chips;
}

const matches = (car: Car, f: Filters) =>
  (!f.price || (car.price >= f.price[0] && car.price <= f.price[1])) &&
  (!f.body || car.body === f.body) &&
  (!f.fuel || car.fuel === f.fuel);

export default function AppliedFiltersExample() {
  const [filters, setFilters] = useState<Filters>(START);
  const results = CARS.filter((car) => matches(car, filters));

  return (
    <div className="w-full max-w-[400px]">
      <AppliedFilters
        filters={chipsOf(filters)}
        onRemove={(key) => setFilters((f) => ({ ...f, [key]: null }))}
        onClearAll={() => setFilters(NONE)}
      />
      <p aria-live="polite" className="mt-4 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>
      <ul className="mt-2 rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] p-2">
        {results.slice(0, 4).map((car) => (
          <li key={car.name} className="flex h-12 items-center justify-between gap-3 px-3 text-[15px] leading-5 tabular-nums">
            <span className="min-w-0 truncate">
              <span className="font-medium">{car.name}</span> <span className="text-[13px] text-[var(--fu-dim,#929292)]">{car.year}</span>
            </span>
            <span className="shrink-0 font-medium text-[var(--fu-accent-soft,#8FAAFF)]">{money.format(car.price)}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
```

## Connect it to my data

Ask me where my filters live. Build the chips from them: one { key, label, value } for each filter in use, the value in the same words as the filter's own summary, and nothing for a filter that is not set. In onRemove, clear the filter with that key; in onClearAll, clear them all. Put the row above the results, where it stays in view.

## Keep the look

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

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

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

```css
.light {
  --fu-accent: #3B57E6;
  --fu-accent-hover: #2F4AD0;
  --fu-accent-pale: #253A9E;
  --fu-accent-soft: #3049D2;
  --fu-card: #FFFFFF;
  --fu-card-border: #E5E5E2;
  --fu-dim: #555552;
  --fu-hover: rgb(29 27 24/0.11);
  --fu-hover-wash: rgb(29 27 24/0.07);
  --fu-line: #C4C4C0;
  --fu-mute: #444442;
  --fu-on-accent: #FFFFFF;
  --fu-selected: #E8EDFD;
  --fu-skeleton: rgb(29 27 24/0.09);
  --fu-skeleton-on: rgb(48 73 210/0.18);
  --fu-surface-3: rgb(29 27 24/0.07);
  --fu-text: #1B1B19;
}
```

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

## Direction and language

It lays out with start and end, so it works on a right-to-left page or inside any element with dir="rtl": arrows, bars, charts and the arrow keys follow. Keep the start and end classes; do not swap them for left and right.

## Keep the accessibility

- The chips are a named list, and each chip is named "Remove Price: $15k to $45k", with the whole value even when it is cut short.
- A removal is announced politely: "Price removed".
- Motion is skipped when reduced motion is asked for.
- Disabled, every chip is a disabled button and Clear all is left out; focus that sat on it moves to the row.
- Each chip is a button: Tab reaches it, Enter or Space removes it.
- Left and Right move between chips the way they sit on screen, so in right to left Left moves to the next one; Backspace or Delete removes the one in focus.
- After a removal focus moves to the next chip; after Clear all, to the row.
- While disabled no chip takes focus, and Clear all is left out.

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

What it does

  • Each chip reads as the filter's name, dim, then its value, bright: "Price $15k to $45k".
  • A removed chip blurs away in place while the chips after it glide into the gap, across lines too.
  • The row's height eases when a line empties; Clear all takes the chips away one by one from the end.
  • A value that changes swaps with a short blur, and the chips after it make room.
  • Chips wrap onto as many lines as they need; on touch screens each is 44px tall to tap.

Keyboard

  • Each chip is a button: Tab reaches it, Enter or Space removes it.
  • Left and Right move between chips the way they sit on screen, so in right to left Left moves to the next one; Backspace or Delete removes the one in focus.
  • After a removal focus moves to the next chip; after Clear all, to the row.
  • While disabled no chip takes focus, and Clear all is left out.

Props

Value. None of its own: it shows the { key, label, value } list you make from your filters and calls onRemove with a key.

AppliedFilters props
PropDescription
filters
Required

The filters in use, in display order: a name ("Price") and the value in words ("$15k to $45k").

readonly { key: string; label: string; value: string }[]
onRemove
Required

Called with a filter's key when its chip is pressed. Clear that filter.

(key: string) => void
onClearAll
Optional

When given, Clear all ends the row while two or more filters are in use; it is left out while disabled.

() => void
clearAllLabel
Default "Clear all"

Text of the Clear all button.

string
label
Default "Applied filters"

Accessible name of the list.

string
emptyText
Default "No filters applied"

The quiet line shown in place of the chips while no filter is in use.

string
disabled
Default false

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

boolean

More filters