v1.3.5
Basics

Dropdown

A menu behind a small pill, such as "Sort by Newest", with one choice, several, or plain actions.

Live example

5 cars

  • Toyota RAV42022 · 28,000 km$31,400Today
  • Honda Civic2019 · 64,000 km$17,900Yesterday
  • Kia EV62024 · 9,000 km$38,9003 days ago
  • Ford Escape2020 · 47,000 km$21,5005 days ago
  • Mazda CX-52021 · 35,000 km$26,2008 days ago
Direction
Locale
State

Copy

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

Dropdown: A menu behind a small pill, such as "Sort by Newest", with one choice, several, or plain actions.

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/dropdown.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/ui/dropdown-menu.tsx

```tsx
"use client";

import { Fragment, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { cn } from "../lib/cn";
import { CheckIcon, ChevronDownIcon } from "./icons";
import { typesCharacter, keepRowInView, LIST_PANEL, ListCheck, PopoverPanel, RowHighlight, useTypeAhead, type PopoverCloseReason } from "./popover";
import { ARRIVING, SkeletonText, useLoading } from "./skeleton";
import { TextSwap } from "./text-swap";

export type MenuOption<V extends string = string> = {
  value: V;
  label: string;
  disabled?: boolean;
  /** Muted words after the label, e.g. what comes first in this order. */
  hint?: string;
  /** A 16px glyph before the label, drawn in currentColor. It takes the accent when chosen. */
  icon?: ReactNode;
};
export type MenuGroup<V extends string = string> = { label?: string; options: readonly MenuOption<V>[] };
export type MenuAction = { label: string; onSelect: () => void; disabled?: boolean; hint?: string };

type SharedProps<V extends string> = {  /** Accessible name of the menu, e.g. "Sort by". Read before the value when there is no prefix. */
  label: string;
  /** Muted words before the value on the trigger, e.g. "Sort by". */
  prefix?: string;
  /** The choices, plain or in labelled groups. A separator falls between groups. */
  options: readonly (MenuOption<V> | MenuGroup<V>)[];
  /** Commands under the choices, after a separator, e.g. "Reset". */
  actions?: readonly MenuAction[];
  /** "filled": a --fu-surface-3 pill. "quiet": no fill until hovered, for a toolbar or next to a result count. Default "filled". */
  variant?: "filled" | "quiet";
  /** Which edge the menu lines up with. Default "start". */
  align?: "start" | "end";
  /** Text on the trigger instead of the chosen labels. */
  valueLabel?: string;
  /** The quiet line in the open menu when there are no options and no actions. Default "No choices". */
  emptyText?: string;
  disabled?: boolean;
  /** Draws the menu open in place, for a still picture. Nothing responds. */
  still?: boolean;
  className?: string;
};

export type DropdownMenuProps<V extends string = string> = SharedProps<V> &
  (
    | { multiple?: false; value: V; onChange: (value: V) => void }
    | {
        multiple: true;
        value: readonly V[];
        onChange: (value: V[]) => void;
        /** Trigger text while nothing is ticked. Default "Any". */
        emptyLabel?: string;
      }
  );

type Entry<V extends string> = { label: string; hint?: string; icon?: ReactNode; disabled: boolean; group: number } & (
  | { kind: "radio" | "check"; value: V }
  | { kind: "action"; action: MenuAction }
);

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

/**
 * A trigger pill ("Sort by Newest") that opens a menu, grown out of the pill, of single-choice options (the chosen one
 * tinted, with a check that draws in), multi-choice options with a box, and plain actions. One highlight marks
 * the active row; an option may carry a glyph and a hint. Focus moves into the menu: arrows (wrapping), Home, End and first
 * letters move it, Enter or Space picks, Escape closes back to the trigger. A single choice closes the menu; ticking a
 * box keeps it open.
 */
export function DropdownMenu<V extends string = string>(props: DropdownMenuProps<V>) {
  const { label, prefix, options, actions = [], variant = "filled", align = "start", valueLabel, emptyText = "No choices", disabled = false, still = false, className } = props;
  // Inside a loading StatusFrame the trigger keeps its box and a bar stands in for the chosen labels.
  const { loading, arriving } = useLoading();
  const id = useId();
  const menuId = `${id}-menu`;
  const itemId = (index: number) => `${id}-item-${index}`;
  const trigger = useRef<HTMLButtonElement>(null);
  const panel = useRef<HTMLDivElement>(null);
  const items = useRef<(HTMLDivElement | null)[]>([]);
  const nothing = useRef<HTMLDivElement>(null);
  const [isOpen, setOpen] = useState(false);
  // A menu open when its data starts loading closes: its choices are on their way.
  if (isOpen && loading) setOpen(false);
  const open = still || isOpen;
  const [active, setActive] = useState<number | null>(null);
  const [pressed, setPressed] = useState(false);
  const opening = useRef<"menu" | "first" | "last">("menu");
  const skipClick = useRef(false);
  const typeAhead = useTypeAhead();

  const chosen: readonly V[] = props.multiple ? props.value : [props.value];
  const groups: { label?: string; options: MenuOption<V>[] }[] = [];
  let loose = false;
  for (const option of options) {
    if ("options" in option) groups.push({ label: option.label, options: [...option.options] });
    else if (loose) groups[groups.length - 1].options.push(option);
    else groups.push({ options: [option] });
    loose = !("options" in option);
  }
  const entries: Entry<V>[] = [
    ...groups.flatMap((group, at) =>
      group.options.map((option): Entry<V> => ({
        kind: props.multiple ? "check" : "radio",
        value: option.value,
        label: option.label,
        hint: option.hint,
        icon: option.icon,
        disabled: Boolean(option.disabled),
        group: at,
      })),
    ),
    ...actions.map((action): Entry<V> => ({ kind: "action", action, label: action.label, hint: action.hint, disabled: Boolean(action.disabled), group: groups.length })),
  ];
  const usable = entries.flatMap((entry, index) => (entry.disabled ? [] : [index]));
  const isChecked = (entry: Entry<V>) => entry.kind !== "action" && chosen.includes(entry.value);

  const labels = entries.filter((entry) => isChecked(entry)).map((entry) => entry.label);
  // A still picture shows the highlight on the chosen item, as if opened from the keyboard.
  const current = still ? (usable.find((index) => isChecked(entries[index])) ?? null) : active;
  const shown = valueLabel ?? (props.multiple ? (labels.length ? labels.join(", ") : (props.emptyLabel ?? "Any")) : (labels[0] ?? ""));

  // preventScroll keeps the page still, so the menu's own scroll follows the focused item by hand.
  const focusAt = (index: number | undefined) => {
    const item = index === undefined ? null : items.current[index];
    if (!item) return;
    item.focus({ preventScroll: true });
    if (panel.current) keepRowInView(panel.current, item);
  };

  useLayoutEffect(() => {
    if (!isOpen) return;
    const checked = usable.find((index) => isChecked(entries[index]));
    const target = opening.current === "menu" ? undefined : opening.current === "last" ? usable.at(-1) : (checked ?? usable[0]);
    // With nothing to choose, focus lands on the line that says so.
    if (target === undefined) (nothing.current ?? panel.current)?.focus({ preventScroll: true });
    else focusAt(target);
    // Runs once per open; the entries are read as they are then.
  }, [isOpen]);

  // A new value eases the trigger to its new width over 150ms. The leaving text is left out of the measure, and the
  // width stays pinned until it has gone (TextSwap takes 280ms), so it never snaps back to fit the old words.
  const width = useRef<number | null>(null);
  useLayoutEffect(() => {
    const node = trigger.current;
    if (!node || still) return;
    const leaving = node.querySelector<HTMLElement>("[data-swap] > [aria-hidden]");
    if (leaving) leaving.style.display = "none";
    const to = node.offsetWidth;
    if (leaving) leaving.style.display = "";
    const from = width.current;
    width.current = to;
    if (from === null || from === to || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    node.style.width = `${to}px`;
    const glide = node.animate([{ width: `${from}px` }, { width: `${to}px` }], { duration: 150, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
    const timer = setTimeout(() => {
      node.style.width = "";
    }, 300);
    return () => {
      glide.cancel();
      clearTimeout(timer);
      node.style.width = "";
    };
  }, [shown, still]);

  const show = (from: "menu" | "first" | "last") => {
    opening.current = from;
    setActive(null);
    setOpen(true);
  };

  const shut = (reason: PopoverCloseReason | "pick" | "tab") => {
    const inside = panel.current?.contains(document.activeElement);
    if (inside && reason !== "blur" && reason !== "outside") trigger.current?.focus({ preventScroll: true });
    setOpen(false);
    setPressed(false);
  };

  const pick = (index: number) => {
    const entry = entries[index];
    if (!entry || entry.disabled) return;
    if (entry.kind === "check") {
      if (!props.multiple) return;
      const on = props.value.includes(entry.value);
      // Kept in the order of the options, whatever order they were ticked in.
      props.onChange(entries.flatMap((e) => (e.kind === "check" && (e === entry ? !on : props.value.includes(e.value)) ? [e.value] : [])));
      return;
    }
    shut("pick");
    if (entry.kind === "action") entry.action.onSelect();
    else if (!props.multiple && entry.value !== props.value) props.onChange(entry.value);
  };

  const onMenuKey = (event: KeyboardEvent<HTMLDivElement>) => {
    const { key } = event;
    // Tab leaves either way. Shift+Tab lands on the trigger, which does not count as leaving, so it closes here.
    if (key === "Tab") {
      if (event.shiftKey) {
        event.preventDefault();
        shut("tab");
      } else setTimeout(() => shut("blur"));
      return;
    }
    if (event.nativeEvent.isComposing || !usable.length) return;
    const at = active === null ? -1 : usable.indexOf(active);
    if (key === "ArrowDown") {
      event.preventDefault();
      focusAt(usable[(at + 1) % usable.length]);
    } else if (key === "ArrowUp") {
      event.preventDefault();
      focusAt(usable[at <= 0 ? usable.length - 1 : at - 1]);
    } else if (key === "Home" || key === "End") {
      event.preventDefault();
      focusAt(key === "Home" ? usable[0] : usable.at(-1));
    } else if (key === " " && typeAhead.running()) {
      event.preventDefault();
      focusAt(usable[typeAhead.find(key, usable.map((index) => entries[index]), at)]);
    } else if ((key === "Enter" || key === " ") && active !== null) {
      event.preventDefault();
      pick(active);
    } else if (typesCharacter(event)) {
      event.preventDefault();
      focusAt(usable[typeAhead.find(key, usable.map((index) => entries[index]), at)]);
    }
  };

  const rows = entries.map((entry, index) => {
    const checked = isChecked(entry);
    const role = entry.kind === "radio" ? "menuitemradio" : entry.kind === "check" ? "menuitemcheckbox" : "menuitem";
    return (
      <div
        key={entry.kind === "action" ? `action-${index}` : `option-${entry.value}`}
        ref={(node) => {
          items.current[index] = node;
        }}
        id={itemId(index)}
        role={role}
        tabIndex={-1}
        aria-checked={entry.kind === "action" ? undefined : checked}
        aria-disabled={entry.disabled || undefined}
        data-state={checked ? "on" : "off"}
        data-active={current === index || undefined}
        onFocus={() => setActive(index)}
        onPointerMove={(event) => {
          if (event.pointerType !== "mouse" || document.activeElement === event.currentTarget) return;
          if (entry.disabled) panel.current?.focus({ preventScroll: true });
          else event.currentTarget.focus({ preventScroll: true });
        }}
        onPointerDown={() => !entry.disabled && setPressed(true)}
        onPointerUp={() => setPressed(false)}
        onPointerLeave={() => setPressed(false)}
        onClick={() => pick(index)}
        className={cn(
          "group/item relative flex min-h-10 cursor-pointer items-center gap-2.5 rounded-[9px] py-2 pe-2 ps-2.5 text-[14px] leading-5 outline-none select-none pointer-coarse:min-h-11",
          "transition-[background-color,color] duration-200 motion-reduce:transition-none",
          entry.kind === "radio" && checked && "bg-[var(--fu-selected,#1F2747)] font-medium text-[var(--fu-accent-pale,#D1DDFF)]",
          entry.disabled && "cursor-default opacity-40",
          "forced-colors:data-[active]:bg-[Highlight] forced-colors:data-[active]:text-[HighlightText]",
        )}
      >
        {entry.kind === "check" && (
          <span
            aria-hidden="true"
            className={cn(
              "grid size-[18px] shrink-0 place-items-center rounded-[5px] border border-[var(--fu-control-border,#737373)] text-[var(--fu-accent-soft,#8FAAFF)]",
              "transition-[background-color,border-color] duration-200 motion-reduce:transition-none",
              SMOOTH,
              "group-data-[active]/item:border-[var(--fu-control-hover,#A3A3A3)]",
              "group-data-[state=on]/item:border-[var(--fu-accent-soft,#8FAAFF)] group-data-[state=on]/item:bg-[var(--fu-selected,#1F2747)]",
            )}
          >
            <CheckIcon
              size={14}
              strokeWidth={3}
              className={cn(
                // The path is about 23 units long; a negative offset draws it from the short leg up.
                "[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:-23] [&_path]:transition-[stroke-dashoffset] [&_path]:duration-200 motion-reduce:[&_path]:transition-none",
                "[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] group-data-[state=on]/item:[&_path]:[stroke-dashoffset:0]",
              )}
            />
          </span>
        )}
        {entry.icon && (
          <span
            aria-hidden="true"
            className={cn(
              "-my-0.5 grid size-6 shrink-0 place-items-center rounded-[7px] transition-[color,background-color] duration-200 motion-reduce:transition-none",
              entry.kind !== "action" && checked
                ? "bg-[var(--fu-accent,#3B57E6)]/45 text-[var(--fu-accent-pale,#D1DDFF)]"
                : "bg-[var(--fu-surface-3,#2A2A2A)] text-[var(--fu-mute,#BDBDBD)] group-data-[active]/item:text-[var(--fu-text,#F8F5F1)]",
            )}
          >
            {entry.icon}
          </span>
        )}
        <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{entry.label}</span>
        {entry.hint && (
          <span
            className={cn(
              "shrink-0 ps-2 text-[13px] leading-5 font-normal tabular-nums",
              entry.kind !== "action" && checked ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)]",
            )}
          >
            {entry.hint}
          </span>
        )}
        {entry.kind === "radio" && <ListCheck on={checked} />}
      </div>
    );
  });

  const sections = [...groups.map((group, at) => ({ label: group.label, at })), ...(actions.length ? [{ label: undefined, at: groups.length }] : [])];

  return (
    <div className={cn("relative inline-flex max-w-full", disabled && "pointer-events-none opacity-50", className)}>
      <button
        ref={trigger}
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={open ? menuId : undefined}
        disabled={disabled}
        tabIndex={still ? -1 : undefined}
        onKeyDown={(event) => {
          const { key } = event;
          if (key === "ArrowDown" || key === "ArrowUp" || key === "Enter" || key === " ") {
            event.preventDefault();
            if (key === "Enter" || key === " ") skipClick.current = true;
            show(key === "ArrowUp" ? "last" : "first");
          }
        }}
        onKeyUp={() => {
          setTimeout(() => {
            skipClick.current = false;
          });
        }}
        // The key that opened the menu had its keyup land in it, so a press on the closed trigger clears the skip. While
        // open the skip stays: Safari does not focus a pressed button, so the menu closes on blur before this click.
        onPointerDown={() => {
          if (!isOpen) skipClick.current = false;
        }}
        onClick={() => {
          if (skipClick.current) {
            skipClick.current = false;
            return;
          }
          if (isOpen) shut("pick");
          else show("menu");
        }}
        className={cn(
          "relative inline-flex h-9 max-w-full min-w-0 cursor-pointer items-center gap-1 rounded-[10px] pe-2.5 ps-3 font-[inherit] text-[14px] leading-5 whitespace-nowrap",
          "[-webkit-tap-highlight-color:transparent] pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-1 pointer-coarse:after:content-['']",
          "transition-[background-color,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] active:scale-[0.97] active:duration-75 aria-expanded:active:scale-100 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)]",
          variant === "filled"
            ? "bg-[var(--fu-surface-3,#2A2A2A)] hover:bg-[var(--fu-hover,#333333)] aria-expanded:bg-[var(--fu-hover,#333333)] forced-colors:border forced-colors:border-[ButtonText]"
            : "bg-transparent hover:bg-[var(--fu-wash,rgb(255_255_255/0.08))] aria-expanded:bg-[var(--fu-wash,rgb(255_255_255/0.08))]",
        )}
      >
        {prefix ? <span className="shrink-0 text-[var(--fu-mute,#BDBDBD)]">{prefix}</span> : <span className="sr-only">{label}: </span>}
        {loading && valueLabel === undefined ? (
          <span className="min-w-0 truncate font-medium">
            <SkeletonText>{shown}</SkeletonText>
          </span>
        ) : (
          <TextSwap data-swap="" className={cn("min-w-0 grid-cols-[minmax(0,1fr)] font-medium text-[var(--fu-text,#F8F5F1)] [&>span]:truncate", arriving && ARRIVING)}>
            {shown}
          </TextSwap>
        )}
        <ChevronDownIcon
          size={16}
          className={cn("ms-0.5 shrink-0 text-[var(--fu-mute,#BDBDBD)] transition-[rotate,color] duration-[480ms] motion-reduce:transition-none", SMOOTH, open && "rotate-180 text-[var(--fu-accent-soft,#8FAAFF)]")}
        />
      </button>

      <PopoverPanel
        ref={panel}
        id={menuId}
        role="menu"
        aria-label={label}
        tabIndex={-1}
        open={open}
        still={still}
        anchor={trigger}
        align={align}
        onClose={shut}
        onKeyDown={onMenuKey}
        onFocus={(event) => {
          if (event.target === event.currentTarget) setActive(null);
        }}
        onPointerLeave={(event) => {
          if (event.pointerType === "mouse" && panel.current?.contains(document.activeElement) && document.activeElement !== panel.current) {
            panel.current?.focus({ preventScroll: true });
          }
        }}
        className={cn(LIST_PANEL, "min-w-[220px] outline-none")}
      >
        <RowHighlight activeId={open && current !== null ? itemId(current) : null} open={open} pressed={pressed} />
        {entries.length === 0 && (
          // An item that cannot be picked, so the menu still holds one and a screen reader says why it is empty.
          <div
            ref={nothing}
            role="menuitem"
            aria-disabled="true"
            tabIndex={-1}
            className="flex min-h-10 items-center rounded-[9px] px-2.5 text-[14px] leading-5 text-[var(--fu-dim,#929292)] outline-none focus-visible:bg-[var(--fu-row-active,rgb(255_255_255/0.07))]"
          >
            {emptyText}
          </div>
        )}
        {sections.map(({ label: title, at }, n) => {
          const titleId = `${id}-group-${at}`;
          const own = rows.filter((_, index) => entries[index].group === at);
          return (
            <Fragment key={at}>
              {n > 0 && <div role="separator" className="mx-2.5 my-1.5 h-px bg-[var(--fu-card-border,#2A2A2A)]" />}
              {at < groups.length ? (
                <div role="group" aria-labelledby={title ? titleId : undefined}>
                  {title && (
                    <div id={titleId} className="px-2.5 pt-1.5 pb-2 text-[12px] leading-4 font-medium text-[var(--fu-dim,#929292)]">
                      {title}
                    </div>
                  )}
                  {own}
                </div>
              ) : (
                own
              )}
            </Fragment>
          );
        })}
      </PopoverPanel>
    </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/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/popover.tsx

```tsx
"use client";

import { useEffect, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type Ref, type RefObject } from "react";
import { cn } from "../lib/cn";
import { isRtl } from "../lib/direction";
import { formatsFor } from "../lib/format";
import { SCROLL } from "../lib/scroll";
import { CheckIcon } from "./icons";

export type PopoverCloseReason = "escape" | "outside" | "blur" | "away";

export type PopoverPanelProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
  ref?: Ref<HTMLDivElement>;
  open: boolean;
  /** The trigger the panel opens against. */
  anchor: RefObject<HTMLElement | null>;
  /**
   * Asks the owner to close: "escape", "outside" (a press outside the trigger and the panel), "blur" (focus moved
   * outside both) or "away" (the trigger scrolled out of view). The owner sets open to false and moves focus if needed.
   */
  onClose: (reason: PopoverCloseReason) => void;
  /** Lines up the start edges, or the end edges with "end": the left edges in left-to-right, the right ones in RTL. Default "start". */
  align?: "start" | "end";
  /** At least as wide as the trigger. */
  matchWidth?: boolean;
  /** Widest the panel grows, in px; never wider than the screen less its margins. Default 320. */
  maxWidth?: number;
  /** Tallest the panel grows before it scrolls, in px; also capped by the room on its side. Default 320. */
  maxHeight?: number;
  /** Draws the panel open in place under the trigger, for a still picture. Nothing moves or listens. The owner needs position: relative. */
  still?: boolean;
  children: ReactNode;
};

const GAP = 6;
const EDGE_Y = 8;
const MIN_HEIGHT = 160;
const edgeX = (width: number) => (width < 640 ? 16 : 8);

/** Open panels, newest last: Escape closes only the newest. */
const layers: symbol[] = [];

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

// Browsers without popover support (before Chrome 114, Safari 17, Firefox 125) get a fixed panel in place instead.
function show(node: HTMLElement) {
  if (typeof node.showPopover !== "function") {
    node.style.display = "block";
    return;
  }
  try {
    if (!node.matches(":popover-open")) node.showPopover();
  } catch {}
}

function hide(node: HTMLElement) {
  if (typeof node.hidePopover !== "function") {
    node.style.display = "none";
    return;
  }
  try {
    node.hidePopover();
  } catch {}
}

/** The surface of a menu or list panel: 14px radius, the card colour, a --fu-line hairline, 6px inside, a deep soft shadow. */
export const LIST_PANEL =
  "w-max rounded-[14px] border border-[var(--fu-line,#404040)] bg-[var(--fu-card,#1F1F1F)] p-1.5 shadow-[inset_0_1px_0_var(--fu-rim,rgb(255_255_255/0.04)),0_24px_48px_-12px_var(--fu-shadow-deep,rgb(0_0_0/0.8)),0_10px_20px_-8px_var(--fu-shadow,rgb(0_0_0/0.5))]";

/**
 * A floating panel for menus and lists. It stays where it is in the DOM, so it inherits fonts and --fu-* variables and
 * Tab reaches it right after its trigger, and opens on the browser's top layer (popover="manual"), so no overflow,
 * transform or z-index around the trigger can clip or bury it. It opens below the trigger, or above when only that fits,
 * keeps 8px from the screen edges (16px at the sides on phones) and follows the trigger while the page scrolls.
 * It grows out of the trigger over 480ms (scale 0.98 to 1 from the trigger's side, through a 6px blur) and leaves
 * over 160ms; it is inert while it leaves. Children can follow it through group/popover's data-state: closed, open,
 * closing.
 */
export function PopoverPanel({
  ref,
  open,
  anchor,
  onClose,
  align = "start",
  matchWidth = false,
  maxWidth = 320,
  maxHeight = 320,
  still = false,
  className,
  style,
  children,
  ...props
}: PopoverPanelProps) {
  const panel = useRef<HTMLDivElement | null>(null);
  const [phase, setPhase] = useState<"hidden" | "open" | "closing">("hidden");
  // Counts grow in only the first time the panel opens; after that they are already in place.
  const [seen, setSeen] = useState(false);
  // Which edges have rows scrolled out of view, so a soft fade there says the list goes on.
  const [more, setMore] = useState({ top: false, bottom: false });
  const side = useRef<"bottom" | "top">("bottom");
  const close = useRef(onClose);
  useLayoutEffect(() => {
    close.current = onClose;
  });

  const setRef = (node: HTMLDivElement | null) => {
    panel.current = node;
    if (typeof ref === "function") ref(node);
    else if (ref) ref.current = node;
  };

  // Measures the trigger without its press scale (offset sizes around the rect's centre), then picks a side and a spot.
  const place = (first: boolean) => {
    const node = panel.current;
    const trigger = anchor.current;
    if (!node || !trigger) return;
    const vw = document.documentElement.clientWidth;
    const vh = document.documentElement.clientHeight;
    const rect = trigger.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const left = cx - trigger.offsetWidth / 2;
    const right = cx + trigger.offsetWidth / 2;
    const top = cy - trigger.offsetHeight / 2;
    const bottom = cy + trigger.offsetHeight / 2;
    if (!first && (bottom < 0 || top > vh || right < 0 || left > vw)) {
      close.current("away");
      return;
    }

    const mx = edgeX(vw);
    const widest = Math.min(maxWidth, vw - 2 * mx);
    node.style.maxWidth = `${widest}px`;
    if (matchWidth) node.style.minWidth = `${Math.min(trigger.offsetWidth, widest)}px`;
    node.style.maxHeight = `${maxHeight}px`;
    const natural = node.offsetHeight;
    const below = vh - EDGE_Y - bottom - GAP;
    const above = top - GAP - EDGE_Y;
    const roomOf = (s: "bottom" | "top") => (s === "bottom" ? below : above);
    let next: "bottom" | "top";
    if (!first && natural <= roomOf(side.current)) next = side.current;
    else if (natural <= below) next = "bottom";
    else if (natural <= above) next = "top";
    else next = below >= above ? "bottom" : "top";
    side.current = next;

    node.style.maxHeight = `${Math.min(maxHeight, Math.max(MIN_HEIGHT, roomOf(next)))}px`;
    const width = node.offsetWidth;
    const height = node.offsetHeight;
    const toRight = (align === "end") !== isRtl(trigger);
    const x = Math.min(Math.max(mx, toRight ? right - width : left), vw - mx - width);
    const y = next === "bottom" ? bottom + GAP : top - GAP - height;
    node.style.left = `${Math.round(x)}px`;
    node.style.top = `${Math.round(y)}px`;
    node.style.transformOrigin = `${Math.round(cx - x)}px ${next === "bottom" ? "0" : "100%"}`;
    node.dataset.side = next;
  };

  useLayoutEffect(() => {
    const node = panel.current;
    if (still || !node) return;
    if (open) {
      if (phase === "hidden") {
        // Shown and placed in its closed look with no transition, then opened, so it enters from the trigger's side.
        node.style.transition = "none";
        show(node);
        place(true);
        void getComputedStyle(node).opacity;
        node.style.transition = "";
      }
      setPhase("open");
      setSeen(true);
    } else if (phase === "open") {
      setPhase(reducedMotion() ? "hidden" : "closing");
    }
    // place reads the latest props; phase is read as committed.
  }, [open, still]);

  useLayoutEffect(() => {
    if (phase === "hidden" && !still && panel.current) hide(panel.current);
  }, [phase, still]);

  useEffect(() => {
    const node = panel.current;
    if (!node || (!still && phase !== "open")) return;
    const measure = () => {
      const top = node.scrollTop > 1;
      const bottom = node.scrollTop + node.clientHeight < node.scrollHeight - 1;
      setMore((now) => (now.top === top && now.bottom === bottom ? now : { top, bottom }));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(node);
    node.addEventListener("scroll", measure, { passive: true });
    return () => {
      observer.disconnect();
      node.removeEventListener("scroll", measure);
    };
  }, [phase, still]);

  useEffect(() => {
    const node = panel.current;
    if (phase !== "closing" || !node) return;
    const done = () => setPhase((now) => (now === "closing" ? "hidden" : now));
    const timer = setTimeout(done, 190);
    const onEnd = (event: TransitionEvent) => {
      if (event.target === node && event.propertyName === "opacity") done();
    };
    node.addEventListener("transitionend", onEnd);
    return () => {
      clearTimeout(timer);
      node.removeEventListener("transitionend", onEnd);
    };
  }, [phase]);

  useEffect(() => {
    const node = panel.current;
    const trigger = anchor.current;
    if (still || phase !== "open" || !node || !trigger) return;
    const token = Symbol("layer");
    layers.push(token);

    let frame = 0;
    const follow = (event?: Event) => {
      if (event?.type === "scroll" && event.target instanceof Node && node.contains(event.target)) return;
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => place(false));
    };
    const observer = new ResizeObserver(() => follow());
    observer.observe(trigger);
    observer.observe(node);
    window.addEventListener("scroll", follow, { capture: true, passive: true });
    window.addEventListener("resize", follow);
    window.visualViewport?.addEventListener("resize", follow);

    const inside = (target: EventTarget | null) => target instanceof Node && (node.contains(target) || trigger.contains(target));
    // A mouse closes on press; a finger or pen on a tap that did not move, so starting a scroll keeps the panel open.
    // The press is never cancelled, so one click on another control both closes this and works there.
    let touch: { id: number; x: number; y: number } | null = null;
    const onDown = (event: PointerEvent) => {
      if (inside(event.target)) return;
      if (event.pointerType === "mouse") close.current("outside");
      else touch = { id: event.pointerId, x: event.clientX, y: event.clientY };
    };
    const onUp = (event: PointerEvent) => {
      if (touch && touch.id === event.pointerId && Math.hypot(event.clientX - touch.x, event.clientY - touch.y) < 10) close.current("outside");
      touch = null;
    };
    const onCancel = () => {
      touch = null;
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== "Escape" || event.isComposing || layers.at(-1) !== token) return;
      event.stopPropagation();
      event.preventDefault();
      close.current("escape");
    };
    const onFocusOut = (event: FocusEvent) => {
      if (event.relatedTarget && !inside(event.relatedTarget)) close.current("blur");
    };
    document.addEventListener("pointerdown", onDown, true);
    document.addEventListener("pointerup", onUp, true);
    document.addEventListener("pointercancel", onCancel, true);
    window.addEventListener("keydown", onKey, true);
    node.addEventListener("focusout", onFocusOut);
    trigger.addEventListener("focusout", onFocusOut);

    return () => {
      layers.splice(layers.indexOf(token), 1);
      cancelAnimationFrame(frame);
      observer.disconnect();
      window.removeEventListener("scroll", follow, { capture: true });
      window.removeEventListener("resize", follow);
      window.visualViewport?.removeEventListener("resize", follow);
      document.removeEventListener("pointerdown", onDown, true);
      document.removeEventListener("pointerup", onUp, true);
      document.removeEventListener("pointercancel", onCancel, true);
      window.removeEventListener("keydown", onKey, true);
      node.removeEventListener("focusout", onFocusOut);
      trigger.removeEventListener("focusout", onFocusOut);
    };
    // place and the trigger are read live.
  }, [phase, still]);

  const state = still ? (open ? "open" : "closed") : phase === "hidden" ? "closed" : phase;

  return (
    <div
      ref={setRef}
      popover={still ? undefined : "manual"}
      data-state={state}
      data-unseen={!seen && !still && state === "closed" ? "" : undefined}
      // Not while it is opening again before it finished leaving, so focus can move in.
      inert={state === "closing" && !open}
      style={still ? { maxWidth, maxHeight, ...style } : style}
      className={cn(
        // The browser's own popover look is reset: no inset, margin or padding, and these colours, not Canvas.
        "group/popover m-0 box-border overflow-x-hidden overflow-y-auto overscroll-contain text-[var(--fu-text,#F8F5F1)] [-webkit-tap-highlight-color:transparent]",
        SCROLL,
        still
          ? cn("absolute top-full z-10 mt-1.5", align === "end" ? "inset-e-0" : "inset-s-0", matchWidth && "min-w-full", !open && "hidden")
          : "fixed inset-auto z-50",
        "transition-[opacity,translate,scale,filter] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
        "data-[state=open]:duration-[480ms] data-[state=closing]:duration-[160ms]",
        "data-[state=closed]:pointer-events-none data-[state=closed]:scale-[0.98] data-[state=closed]:opacity-0 data-[state=closed]:blur-[6px]",
        "data-[state=closing]:pointer-events-none data-[state=closing]:scale-[0.98] data-[state=closing]:opacity-0 data-[state=closing]:blur-[2px]",
        "data-[side=bottom]:data-[state=closed]:-translate-y-1 data-[side=top]:data-[state=closed]:translate-y-1",
        className,
      )}
      {...props}
    >
      <span aria-hidden="true" className={cn(FADE, "-top-1.5 -mt-1.5 mb-[-26px] bg-linear-to-b", more.top && "opacity-100")} />
      {children}
      <span aria-hidden="true" className={cn(FADE, "-bottom-1.5 mt-[-26px] -mb-1.5 bg-linear-to-t", more.bottom && "opacity-100")} />
    </div>
  );
}

// Pinned to the panel edge as it scrolls, over the rows and the highlight; it takes no room in the list. Sized for LIST_PANEL.
const FADE =
  "pointer-events-none sticky z-[2] -mx-1.5 block h-8 from-[var(--fu-card,#1F1F1F)] to-transparent opacity-0 transition-opacity duration-150 motion-reduce:transition-none forced-colors:hidden";

/** Scrolls a list panel just enough that `row` shows whole, with the panel's 4px inset around it. */
export function keepRowInView(panel: HTMLElement, row: HTMLElement) {
  const top = row.offsetTop - 4;
  const bottom = row.offsetTop + row.offsetHeight + 4;
  if (top < panel.scrollTop) panel.scrollTop = top;
  else if (bottom > panel.scrollTop + panel.clientHeight) panel.scrollTop = bottom - panel.clientHeight;
}

type Mark = { top: number; height: number; shown: boolean };

/**
 * The one fill that marks a list's active row, moving straight to it. It lies over the rows, a
 * light veil, so it shows on the chosen row's tint too. It fades in where it lands when the list opens, and stays put
 * while the list fades out. Place it first inside the panel.
 */
export function RowHighlight({ activeId, open, pressed = false }: { activeId: string | null; open: boolean; pressed?: boolean }) {
  const [mark, setMark] = useState<Mark | null>(null);
  const [, remeasure] = useState(0);
  const tries = useRef(0);

  useLayoutEffect(() => {
    if (!open) {
      tries.current = 0;
      return;
    }
    const node = activeId ? document.getElementById(activeId) : null;
    // The panel may still be hidden on this pass (it is shown after its children's effects); measure again next frame,
    // a few times at most, in case something else keeps it hidden.
    if (node && !node.getClientRects().length) {
      if (tries.current >= 3) return;
      tries.current += 1;
      const frame = requestAnimationFrame(() => remeasure((n) => n + 1));
      return () => cancelAnimationFrame(frame);
    }
    tries.current = 0;
    const next: Mark | null = node
      ? { top: node.offsetTop, height: node.offsetHeight, shown: true }
      : mark && { ...mark, shown: false };
    if (next?.top !== mark?.top || next?.height !== mark?.height || next?.shown !== mark?.shown) setMark(next);
  });

  return (
    <div
      aria-hidden="true"
      className={cn(
        "pointer-events-none absolute inset-x-1.5 top-0 z-[1] rounded-[9px] transition-[opacity,background-color] duration-150 motion-reduce:transition-none forced-colors:hidden",
        "ease-[cubic-bezier(0.22,1,0.36,1)]",
        pressed ? "bg-[var(--fu-row-press,rgb(255_255_255/0.12))]" : "bg-[var(--fu-row-active,rgb(255_255_255/0.07))]",
        !mark?.shown && "opacity-0",
      )}
      style={mark ? { translate: `0 ${mark.top}px`, height: mark.height } : undefined}
    />
  );
}

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

/**
 * The check on a chosen row. It draws itself in, from the short leg up, 140ms after its panel first opens; after that
 * it is already in place. Takes its 16px place even when off, so rows line up.
 */
export function ListCheck({ on }: { on: boolean }) {
  return (
    <CheckIcon
      size={16}
      strokeWidth={2.5}
      className={cn(
        "shrink-0 text-[var(--fu-accent-soft,#8FAAFF)]",
        on
          ? cn(
              // The path is about 23 units long; a negative offset draws it from the short leg up.
              "[&_path]:[stroke-dasharray:23] [&_path]:[stroke-dashoffset:0] [&_path]:transition-[stroke-dashoffset] [&_path]:delay-[140ms] [&_path]:duration-[420ms]",
              "[&_path]:ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:[&_path]:transition-none",
              "group-data-[unseen]/popover:[&_path]:[stroke-dashoffset:-23] group-data-[unseen]/popover:[&_path]:transition-none",
            )
          : "invisible",
      )}
    />
  );
}

/**
 * A row's count as a short bar and a number. The bar is the count's share of `max`; bars grow in from the start edge as
 * their panel first opens, one row after another (`order`), and ease to a new width when the count changes. With bar false
 * only the number shows, in the same place, e.g. for "Any".
 */
export function ListCount({
  count,
  max,
  order = 0,
  on = false,
  bar = true,
  format,
  locale,
}: {
  count: number;
  max: number;
  order?: number;
  on?: boolean;
  bar?: boolean;
  format?: (n: number) => string;
  /** Formats the count when no format is given. */
  locale?: string;
}) {
  const share = max > 0 ? Math.min(1, count / max) : 0;
  return (
    <span aria-hidden="true" className="flex shrink-0 items-center gap-2.5">
      <span className={cn("flex h-1 w-12 items-center rounded-full bg-[var(--fu-track,rgb(255_255_255/0.06))]", !bar && "invisible")}>
        <span
          className={cn(
            "h-1 origin-left rtl:origin-right rounded-full transition-[scale,width,background-color] duration-[480ms] motion-reduce:transition-none",
            SMOOTH,
            "group-data-[unseen]/popover:scale-x-0 group-data-[unseen]/popover:transition-none",
            on
              ? "bg-[var(--fu-accent-soft,#8FAAFF)]"
              : "bg-[var(--fu-rail,#4A4A4A)] group-data-[active]/row:bg-[var(--fu-control-border,#737373)]",
          )}
          // A count above 0 always shows a sliver, so only an empty option has no bar.
          style={{ width: `${count > 0 ? Math.max(share * 100, 6) : 0}%`, transitionDelay: `${90 + Math.min(order, 10) * 22}ms, 0ms, 0ms` }}
        />
      </span>
      <span
        className={cn(
          "min-w-[3ch] text-end text-[13px] leading-5 tabular-nums transition-[color] duration-200",
          on ? "text-[var(--fu-accent-soft,#8FAAFF)]" : "text-[var(--fu-dim,#929292)] group-data-[active]/row:text-[var(--fu-mute,#BDBDBD)]",
        )}
      >
        {(format ?? formatsFor(locale).number)(count)}
      </span>
    </span>
  );
}

/**
 * Finds a row by the letters typed in the last 500ms. One letter, or the same letter again and again, steps to the
 * next row starting with it; a word keeps the current row while it still matches.
 */
export function useTypeAhead() {
  const word = useRef("");
  const lastKey = useRef(0);
  const running = () => word.current !== "" && Date.now() - lastKey.current <= 500;

  const find = <T extends { label: string }>(char: string, items: readonly T[], current: number): number => {
    word.current = (running() ? word.current : "") + char.toLowerCase();
    lastKey.current = Date.now();
    const stepping = /^(.)\1*$/u.test(word.current);
    const wanted = stepping ? [...word.current][0] : word.current;
    // The rows in search order: from the next row (or the current one, for a word) round to the one before it.
    const start = stepping ? current + 1 : Math.max(current, 0);
    const order = items.map((_, index) => index);
    const hit = [...order.slice(start), ...order.slice(0, start)].find((index) => items[index].label.toLowerCase().startsWith(wanted));
    return hit ?? -1;
  };

  return { find, running };
}

/** True for a key press that types one character, not a shortcut. */
export const typesCharacter = (event: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }) =>
  /^.$/u.test(event.key) && !(event.ctrlKey || event.metaKey || event.altKey);
```

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

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

export const DEFAULT_LOCALE = "en-US";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### components/filters-ui/ui/sort-glyphs.tsx

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

export type GlyphProps = Omit<SVGProps<SVGSVGElement>, "children">;

// 16px glyphs for sort orders, drawn in currentColor with 1.5px strokes.
function Glyph({ children, ...props }: GlyphProps & { children: ReactNode }) {
  return (
    <svg
      width={16}
      height={16}
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.5}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
      {...props}
    >
      {children}
    </svg>
  );
}

/** Bars rising in reading order, left to right or right to left in RTL: lowest first. */
export function AscendingGlyph(props: GlyphProps) {
  return (
    <Glyph strokeWidth={2} {...props} className={`rtl:-scale-x-100 ${props.className ?? ""}`}>
      <path d="M3.5 13V9.5M8 13V6.5M12.5 13V3" />
    </Glyph>
  );
}

/** Bars falling in reading order: highest first. */
export function DescendingGlyph(props: GlyphProps) {
  return (
    <Glyph strokeWidth={2} {...props} className={`rtl:-scale-x-100 ${props.className ?? ""}`}>
      <path d="M3.5 13V3M8 13V6.5M12.5 13V9.5" />
    </Glyph>
  );
}

/** A clock: newest first. */
export function ClockGlyph(props: GlyphProps) {
  return (
    <Glyph {...props}>
      <circle cx="8" cy="8" r="6" />
      <path d="M8 4.75V8l2.25 1.5" />
    </Glyph>
  );
}

/** A gauge with its needle low: least driven first. */
export function GaugeGlyph(props: GlyphProps) {
  return (
    <Glyph {...props}>
      <path d="M2.25 12.25a5.75 5.75 0 1 1 11.5 0" />
      <path d="M8 12.25 5.5 9.5" />
      <circle cx="8" cy="12.25" r="1.25" fill="currentColor" stroke="none" />
    </Glyph>
  );
}

/** A calendar page: newest year first. */
export function CalendarGlyph(props: GlyphProps) {
  return (
    <Glyph {...props}>
      <rect x="2.5" y="3.25" width="11" height="10.25" rx="2" />
      <path d="M2.5 6.75h11M5.5 1.75v2.5M10.5 1.75v2.5" />
    </Glyph>
  );
}
```

## What it does

- The trigger reads as a phrase, "Sort by Newest", and its value swaps with a short blur as the choice changes.
- The menu grows out of the trigger on the page's top layer, so no card clips it, and flips above when there is no room below.
- One highlight follows the pointer and the keys; each option can carry a glyph in a small tile and a hint, such as what comes first.
- One choice tints its row and draws a check, then closes the menu; several choices show tick boxes and keep it open.
- A press outside closes it without moving focus; a finger has to tap, so starting a scroll keeps it open.

## Props and value

DropdownMenu (components/filters-ui/ui/dropdown-menu.tsx) holds this value: V for one choice, or V[] with multiple, where V is a string: the chosen option values.

- label: string (required). Accessible name of the menu, e.g. "Sort by".
- options: readonly (MenuOption<V> | { label?: string; options: MenuOption<V>[] })[] (required). The choices: { value, label, disabled?, hint?, icon? }, plain or in labelled groups. hint is muted words on the right, such as what comes first; icon is a 16px glyph in currentColor. A separator falls between groups.
- value: V, or readonly V[] with multiple (required). The chosen value, or the ticked values.
- onChange: (value: V) => void, or (value: V[]) => void with multiple (required). Called with the new choice. Ticked values come back in the order of the options.
- multiple: boolean (default false). Tick boxes instead of one check; the menu stays open while ticking.
- prefix: string (optional). Muted words before the value on the trigger, e.g. "Sort by".
- actions: readonly { label: string; onSelect: () => void; disabled?: boolean; hint?: string }[] (optional). Commands under the choices, after a separator.
- variant: "filled" | "quiet" (default "filled"). "quiet" has no fill until hovered, for a toolbar or beside a result count.
- align: "start" | "end" (default "start"). Which edge of the trigger the menu lines up with.
- valueLabel / emptyLabel: string / string (default the chosen labels / "Any"). Trigger text instead of the chosen labels, and the text while nothing is ticked.
- emptyText: string (default "No choices"). The quiet line in the open menu when there are no options and no actions.
- disabled: boolean (default false). Dims the trigger and blocks input.

## States

Keep each of these states as it is.

- Empty (no options given, with emptyText): No options and no actions: the open menu holds one quiet line, "No choices" by default, and the trigger shows only its prefix.
- Disabled (disabled): dimmed, no pointer or keyboard input, and read as unavailable. The trigger is dimmed and does not open.
- Long labels (data, not a prop): The trigger ends a long value in an ellipsis at its width; in the menu a long label wraps onto more lines, its hint and check staying at the end.
- Many options (data, not a prop): The menu caps its height to the room in the window and scrolls; arrows, Home, End and typed letters keep the focused item in view.

## 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 { useLayoutEffect, useRef, useState } from "react";
import { formatsFor, type Formats } from "@/components/filters-ui/lib/format";
import { DropdownMenu } from "@/components/filters-ui/ui/dropdown-menu";
import { AscendingGlyph, CalendarGlyph, ClockGlyph, DescendingGlyph, GaugeGlyph } from "@/components/filters-ui/ui/sort-glyphs";

// days: how long ago it was listed.
type Car = { id: string; name: string; year: number; price: number; km: number; days: number };

const CARS: Car[] = [
  { id: "rav4", name: "Toyota RAV4", year: 2022, price: 31400, km: 28000, days: 0 },
  { id: "civic", name: "Honda Civic", year: 2019, price: 17900, km: 64000, days: 1 },
  { id: "ev6", name: "Kia EV6", year: 2024, price: 38900, km: 9000, days: 3 },
  { id: "escape", name: "Ford Escape", year: 2020, price: 21500, km: 47000, days: 5 },
  { id: "cx5", name: "Mazda CX-5", year: 2021, price: 26200, km: 35000, days: 8 },
];


type Field = "days" | "price" | "km" | "year";

const SORTS = [
  { value: "newest", label: "Newest listings", field: "days", by: (a: Car, b: Car) => a.days - b.days, icon: <ClockGlyph /> },
  { value: "price-low", label: "Price low to high", field: "price", by: (a: Car, b: Car) => a.price - b.price, icon: <AscendingGlyph /> },
  { value: "price-high", label: "Price high to low", field: "price", by: (a: Car, b: Car) => b.price - a.price, icon: <DescendingGlyph /> },
  { value: "km-low", label: "Lowest kilometres", field: "km", by: (a: Car, b: Car) => a.km - b.km, icon: <GaugeGlyph /> },
  { value: "year-new", label: "Newest model year", field: "year", by: (a: Car, b: Car) => b.year - a.year, icon: <CalendarGlyph /> },
] as const;

type Sort = (typeof SORTS)[number]["value"];

// Each field in words, with the locale's numbers: "$31,400", "28,000 km", "3 days ago".
const showIn = (f: Formats): Record<Field, (car: Car) => string> => ({
  days: (car) => (car.days === 0 ? "Today" : car.days === 1 ? "Yesterday" : `${f.number(car.days)} days ago`),
  price: (car) => f.price(car.price),
  km: (car) => f.distance(car.km),
  year: (car) => f.plain(car.year),
});

export default function SortExample({ locale = "en-US" }: { locale?: string }) {
  const f = formatsFor(locale);
  const show = showIn(f);
  // Each order's hint is what would come first.
  const options = SORTS.map(({ value, label, icon, field, by }) => ({ value, label, icon, hint: show[field]([...CARS].sort(by)[0]) }));
  const [sort, setSort] = useState<Sort>("newest");
  const order = SORTS.find((s) => s.value === sort)!;
  const cars = [...CARS].sort(order.by);

  // Each row glides from where it is on screen to its new place; the rank numbers stay. A glide still running when the
  // order changes again is taken over from its current offset, so a quick second pick does not snap rows back.
  const rows = useRef(new Map<string, HTMLLIElement>());
  const tops = useRef(new Map<string, number>());
  useLayoutEffect(() => {
    const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    for (const [id, row] of rows.current) {
      const shift = Number.parseFloat(getComputedStyle(row).translate.split(" ")[1] ?? "0") || 0;
      for (const glide of row.getAnimations()) glide.cancel();
      const top = row.offsetTop;
      const was = tops.current.get(id);
      tops.current.set(id, top);
      if (still || was === undefined) continue;
      const from = was + shift - top;
      if (Math.abs(from) < 0.5) continue;
      row.animate([{ translate: `0 ${from}px` }, { translate: "0 0" }], { duration: 560, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
    }
  }, [sort]);

  // The field the list is sorted by takes the accent.
  const lit = (field: Field, rest = "") =>
    `transition-[color] duration-300 ${order.field === field ? "text-[var(--fu-accent-soft,#8FAAFF)]" : rest}`;

  return (
    <div className="w-full max-w-[400px]">
      <div className="flex items-center justify-between gap-3 pe-[7px] ps-[21px]">
        <p className="text-[14px] leading-5 text-[var(--fu-dim,#929292)]">{f.number(CARS.length)} cars</p>
        <DropdownMenu label="Sort by" prefix="Sort by" variant="quiet" align="end" value={sort} onChange={setSort} options={options} />
      </div>
      <div className="relative mt-2 flex rounded-[24px] border border-[var(--fu-card-border,#2A2A2A)] bg-[var(--fu-card,#1F1F1F)] p-2">
        <ol aria-hidden="true" className="w-6 shrink-0 ps-2">
          {cars.map((_car, i) => (
            <li key={i} className="flex h-14 items-center text-[13px] leading-5 tabular-nums text-[var(--fu-dim,#929292)]">
              {f.plain(i + 1)}
            </li>
          ))}
        </ol>
        <ul className="min-w-0 flex-1">
          {cars.map((car) => (
            <li
              key={car.id}
              ref={(node) => {
                if (node) rows.current.set(car.id, node);
                else rows.current.delete(car.id);
              }}
              className="flex h-14 items-center gap-3 rounded-[16px] px-3 tabular-nums"
            >
              <span className="min-w-0 flex-1">
                <span className="block truncate text-[15px] leading-5 font-medium text-[var(--fu-text,#F8F5F1)]">{car.name}</span>
                <span className="block text-[13px] leading-5 text-[var(--fu-mute,#BDBDBD)]">
                  <span className={lit("year")}>{show.year(car)}</span>
                  {" · "}
                  <span className={lit("km")}>{show.km(car)}</span>
                </span>
              </span>
              <span className="shrink-0 text-end">
                <span className={`block text-[15px] leading-5 font-medium ${lit("price", "text-[var(--fu-text,#F8F5F1)]")}`}>{show.price(car)}</span>
                <span className={`block text-[13px] leading-5 ${lit("days", "text-[var(--fu-dim,#929292)]")}`}>{show.days(car)}</span>
              </span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
```

## Connect it to my data

Ask me what the menu should change: a sort order, a view, or a set of columns. Keep the value in my own state and pass it with onChange, as the example does; for a sort, sort my items with it. Use multiple for several choices at once, and actions for commands such as Reset. Keep components/filters-ui/ui/popover.tsx as it is: it places the menu on the page's top layer (the popover API: Chrome 114, Safari 17, Firefox 125 or newer), so it is never clipped by a card or a scroll area.

## 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-pale: #D1DDFF;
  --fu-accent-soft: #8FAAFF;
  --fu-card: #1F1F1F;
  --fu-card-border: #2A2A2A;
  --fu-control-border: #737373;
  --fu-control-hover: #A3A3A3;
  --fu-dim: #929292;
  --fu-hover: #333333;
  --fu-line: #404040;
  --fu-mute: #BDBDBD;
  --fu-rail: #4A4A4A;
  --fu-rim: rgb(255 255 255/0.04);
  --fu-row-active: rgb(255 255 255/0.07);
  --fu-row-press: rgb(255 255 255/0.12);
  --fu-selected: #1F2747;
  --fu-shadow: rgb(0 0 0/0.5);
  --fu-shadow-deep: rgb(0 0 0/0.8);
  --fu-skeleton: rgb(255 255 255/0.12);
  --fu-skeleton-on: rgb(143 170 255/0.3);
  --fu-surface-3: #2A2A2A;
  --fu-text: #F8F5F1;
  --fu-track: rgb(255 255 255/0.06);
  --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-pale: #253A9E;
  --fu-accent-soft: #3049D2;
  --fu-card: #FFFFFF;
  --fu-card-border: #E5E5E2;
  --fu-control-border: #787874;
  --fu-control-hover: #5B5B57;
  --fu-dim: #555552;
  --fu-hover: rgb(29 27 24/0.11);
  --fu-line: #C4C4C0;
  --fu-mute: #444442;
  --fu-rail: #D6D6D2;
  --fu-rim: rgb(255 255 255/0.7);
  --fu-row-active: rgb(29 27 24/0.05);
  --fu-row-press: rgb(29 27 24/0.09);
  --fu-selected: #E8EDFD;
  --fu-shadow: rgb(36 36 33/0.12);
  --fu-shadow-deep: rgb(36 36 33/0.16);
  --fu-skeleton: rgb(29 27 24/0.09);
  --fu-skeleton-on: rgb(48 73 210/0.18);
  --fu-surface-3: rgb(29 27 24/0.07);
  --fu-text: #1B1B19;
  --fu-track: rgb(29 27 24/0.07);
  --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.

## Keep the accessibility

- The trigger has aria-haspopup="menu" and aria-expanded; the menu is role="menu" with a name.
- Items are menuitemradio or menuitemcheckbox with aria-checked, or menuitem for actions; focus moves to each item itself.
- The highlight and the check are separate signals, and the highlight turns to the system colour in forced colours mode.
- Disabled, the trigger is a disabled button. Inside a loading StatusFrame it keeps its box and draws a placeholder for its value.
- Enter, Space or Down opens the menu on the chosen item; Up opens it on the last.
- Up and Down move and wrap; Home and End jump; typing a letter finds an item.
- Enter or Space picks; Escape closes and returns to the trigger; Tab closes and moves on.
- While disabled Tab skips the trigger.

When done, run the app, tell me which page to open, and show me it working.

What it does

  • The trigger reads as a phrase, "Sort by Newest", and its value swaps with a short blur as the choice changes.
  • The menu grows out of the trigger on the page's top layer, so no card clips it, and flips above when there is no room below.
  • One highlight follows the pointer and the keys; each option can carry a glyph in a small tile and a hint, such as what comes first.
  • One choice tints its row and draws a check, then closes the menu; several choices show tick boxes and keep it open.
  • A press outside closes it without moving focus; a finger has to tap, so starting a scroll keeps it open.

Keyboard

  • Enter, Space or Down opens the menu on the chosen item; Up opens it on the last.
  • Up and Down move and wrap; Home and End jump; typing a letter finds an item.
  • Enter or Space picks; Escape closes and returns to the trigger; Tab closes and moves on.
  • While disabled Tab skips the trigger.

Props

Value. V for one choice, or V[] with multiple, where V is a string: the chosen option values.

DropdownMenu props
PropDescription
label
Required

Accessible name of the menu, e.g. "Sort by".

string
options
Required

The choices: { value, label, disabled?, hint?, icon? }, plain or in labelled groups. hint is muted words on the right, such as what comes first; icon is a 16px glyph in currentColor. A separator falls between groups.

readonly (MenuOption<V> | { label?: string; options: MenuOption<V>[] })[]
value
Required

The chosen value, or the ticked values.

V, or readonly V[] with multiple
onChange
Required

Called with the new choice. Ticked values come back in the order of the options.

(value: V) => void, or (value: V[]) => void with multiple
multiple
Default false

Tick boxes instead of one check; the menu stays open while ticking.

boolean
prefix
Optional

Muted words before the value on the trigger, e.g. "Sort by".

string
actions
Optional

Commands under the choices, after a separator.

readonly { label: string; onSelect: () => void; disabled?: boolean; hint?: string }[]
variant
Default "filled"

"quiet" has no fill until hovered, for a toolbar or beside a result count.

"filled" | "quiet"
align
Default "start"

Which edge of the trigger the menu lines up with.

"start" | "end"
valueLabel / emptyLabel
Default the chosen labels / "Any"

Trigger text instead of the chosen labels, and the text while nothing is ticked.

string / string
emptyText
Default "No choices"

The quiet line in the open menu when there are no options and no actions.

string
disabled
Default false

Dims the trigger and blocks input.

boolean

Related