Dropdown menu
FreeThe base for every menu, select and picker: it grows out of its trigger, a highlight glides between rows, and rows can be actions, choices that say what they cost, checkboxes, switches or submenus.
npx shadcn@latest add https://pixilui.com/r/dropdown-menu.jsonPreview
A highlight glides between rows, and each row's icon plays as it lands.
Menu
import { IconAdd } from "@/components/pixilui/icons/add";
import { IconCode } from "@/components/pixilui/icons/code";
import { IconCopyCheck } from "@/components/pixilui/icons/copy-check";
import { IconDisclosure } from "@/components/pixilui/icons/disclosure";
import { IconHandoff } from "@/components/pixilui/icons/handoff";
import { IconMore } from "@/components/pixilui/icons/more";
import { IconQueue } from "@/components/pixilui/icons/queue";
import { IconRegenerate } from "@/components/pixilui/icons/regenerate";
import { IconSearch } from "@/components/pixilui/icons/search";
import { IconSettings } from "@/components/pixilui/icons/settings";
import { IconStopRun } from "@/components/pixilui/icons/stop-run";
import { Button } from "@/components/pixilui/button";
import { DropdownMenu } from "@/components/pixilui/dropdown-menu";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
menu: ["actions", "model", "workspaces", "filter", "tools"],
} as const;
/** One of the locked menus: a run's actions with a submenu, a model select with search, workspaces, a status filter and tool switches. */
export default function DropdownMenuDemo({ menu = "actions" }: KnobValues<typeof knobs>) {
return (
// on a phone the trigger sits at the start, so the open menu has the width it needs
<div className="flex h-96 w-full max-w-md items-start justify-start pt-4 sm:justify-center">
{menu === "actions" ? (
<DropdownMenu
defaultOpen
key="actions"
aria-label="Run options"
trigger={<Button variant="secondary-2" size="sm" aria-label="Run options" icon={<IconMore />} />}
groups={[
{
rows: [
{ id: "rerun", label: "Rerun failed runs", icon: <IconRegenerate /> },
{ id: "pause", label: "Pause the queue", icon: <IconQueue /> },
{
id: "assign",
label: "Assign to",
icon: <IconHandoff />,
submenu: {
"aria-label": "Assign to",
select: "single",
groups: [
{
rows: [
{ id: "support", label: "Support agent", meta: "4 runs", checked: true },
{ id: "research", label: "Research agent", meta: "2 runs" },
{ id: "billing", label: "Billing agent", meta: "Idle" },
],
},
{ rows: [{ id: "none", label: "Unassigned" }] },
],
},
},
{ id: "copy", label: "Copy run ID", icon: <IconCopyCheck />, shortcut: "⌘C" },
],
},
{ rows: [{ id: "stop", label: "Stop all runs", icon: <IconStopRun />, tone: "danger" }] },
]}
/>
) : menu === "model" ? (
<DropdownMenu
defaultOpen
key="model"
aria-label="Model"
select="single"
width="300px"
trigger={({ picked }) => (
<Button variant="secondary" size="sm" iconEnd={<IconDisclosure />}>
{picked?.label ?? "Model"}
</Button>
)}
search={{ placeholder: "Search models", "aria-label": "Search models", empty: "No model matches", icon: <IconSearch /> }}
groups={[
{
label: "Current",
rows: [
{ id: "haiku", label: "Haiku 5.5", description: "Fastest · about $0.25 a run" },
{ id: "sonnet", label: "Sonnet 5.5", description: "Balanced · about $1.10 a run" },
{ id: "opus", label: "Opus 5.5", description: "Best for hard tasks · about $4.80 a run", checked: true },
{ id: "fable", label: "Fable 5.2", description: "Uses your weekly limit 3x faster", risk: true },
],
},
{
label: "Older",
rows: [
{ id: "opus5", label: "Opus 5", description: "Retires Feb 12 · moves to Opus 5.5" },
{ id: "sonnet5", label: "Sonnet 5", description: "Retires Feb 12 · moves to Sonnet 5.5" },
],
},
]}
/>
) : menu === "workspaces" ? (
<DropdownMenu
defaultOpen
key="ws"
aria-label="Workspaces"
select="single"
ring
trigger={({ picked }) => (
<Button variant="secondary" size="sm" iconEnd={<IconDisclosure />}>
{picked?.label ?? "Workspace"}
</Button>
)}
groups={[
{
label: "Workspaces",
rows: [
{ id: "support", label: "Acme Support", dot: "var(--pixilui-st-done-h)", checked: true },
{ id: "research", label: "Acme Research", dot: "var(--pixilui-h-read)" },
{ id: "personal", label: "Personal", dot: "var(--pixilui-st-warn-h)" },
],
},
{
rows: [
{ id: "new", label: "New workspace", icon: <IconAdd />, kind: "action" },
{ id: "settings", label: "Workspace settings", icon: <IconSettings />, kind: "action" },
],
},
]}
/>
) : menu === "filter" ? (
<DropdownMenu
defaultOpen
key="filter"
aria-label="Filter by status"
select="multi"
width="240px"
trigger={({ count }) => (
<Button variant="secondary" size="sm" iconEnd={<IconDisclosure />} badge={count || undefined}>
Status
</Button>
)}
groups={[
{
label: "Filter by status",
clearLabel: "Clear",
rows: [
{ id: "running", label: "Running", dot: "var(--pixilui-st-run-h)", meta: "12", checked: true },
{ id: "waiting", label: "Waiting", dot: "var(--pixilui-st-wait-h)", meta: "3", checked: true },
{ id: "done", label: "Done", dot: "var(--pixilui-st-done-h)", meta: "38" },
{ id: "failed", label: "Failed", dot: "var(--pixilui-st-fail-h)", meta: "2" },
{ id: "stopped", label: "Stopped", dot: "var(--pixilui-st-stop-h)", meta: "0" },
],
},
]}
/>
) : (
<DropdownMenu
defaultOpen
key="tools"
aria-label="Tools"
width="240px"
trigger={
<Button variant="secondary" size="sm" iconEnd={<IconDisclosure />}>
Tools
</Button>
}
groups={[
{
label: "Tools",
rows: [
{ id: "web", label: "Web search", icon: <IconSearch />, kind: "switch", checked: true },
{ id: "code", label: "Run code", icon: <IconCode />, kind: "switch" },
],
},
{ rows: [{ id: "settings", label: "Tool settings", icon: <IconSettings /> }] },
]}
/>
)}
</div>
);
}When to use
Use it when
- A run's actions behind a ••• button, with a submenu for assigning.
- Picking a model, where each option says what it costs, with search.
- Switching workspaces, filtering by several statuses, or tools that switch on and off in place.
Use something else when
- Two or three options always visible: use a segmented control or radios.
- A form's field among many options: use a select.
- A command palette across the app: use the command menu.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/dropdown-menu.jsonAdds dropdown-menu.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
components/pixilui/dropdown-menu.tsx
"use client";
/*
The dropdown menu, locked 27 Nov 2026 (design/explorations/components/locked/dropdown-menu; the 28 Nov row corner
and the 29 Nov switch row). Its look and motion are foundation.css section 8 (.pixilui-dropdown-*); this file
writes the locked markup from plain data and wires the locked behavior (dropdown-menu.js) onto it:
Open the menu grows from .96 and fades in (200ms) while its rows rise 3px, 25ms apart; it closes faster
the same way back (120ms). The trigger's chevron turns (aria-expanded).
Highlight one grey fill glides to the row under the pointer or the keys (150ms); the row's animated icon
plays as it lands (data-pxi-play). Keys win until the pointer really moves.
Rows actions, single choice (a check or a ring), multi choice (the locked checkbox; the menu stays open,
Clear empties it), switch rows (the locked switch at menu size; the menu stays open), submenus that
open beside their row after an 80ms intent, kept open by a safe triangle while the pointer heads there.
Search the first row filters the rest, dims the letters that don't match and hides empty groups.
Keys Down, Enter or Space opens and focuses; Up and Down move and wrap; Home and End; Enter picks; Right
opens a submenu, Left or Escape steps back; Escape closes and returns focus; Tab closes.
Reduced instant.
*/
import {
Fragment,
cloneElement,
forwardRef,
isValidElement,
useEffect,
useId,
useMemo,
useRef,
useState,
type ComponentPropsWithoutRef,
type CSSProperties,
type ReactElement,
type ReactNode,
} from "react";
import { cn } from "./lib/utils";
/** A missing list prop (plain JavaScript, a guessing agent): one stable empty list, so nothing throws or re-renders. */
const NONE: never[] = [];
export type DropdownMenuRow = {
/** Stable id: what the menu reports for this row. */
id: string;
/** The row's words. */
label: string;
/** A second line under the label, such as what an option costs. */
description?: string;
/** Sets the second line in the warning color. */
risk?: boolean;
/** A leading icon (an animated icon plays when its row is highlighted). */
icon?: ReactNode;
/** A leading color dot (any CSS color): a status or a workspace. */
dot?: string;
/** Grey text at the end: a count, "4 runs". */
meta?: ReactNode;
/** A shortcut at the end, as plain text (menus keep plain-text shortcuts). */
shortcut?: string;
/** danger: red words and icon. */
tone?: "danger";
/** On in a single or multi choice list, or a switch row. */
checked?: boolean;
/** switch: a setting that flips in place, the menu staying open. action: in a choice list, a row that acts instead of picking ("New workspace"). */
kind?: "switch" | "action";
/** A submenu that opens beside the row. */
submenu?: DropdownMenuList;
/** Runs when the row is picked (an action, or a choice). */
onSelect?: () => void;
/** Runs when a multi choice or switch row flips. */
onCheckedChange?: (checked: boolean) => void;
/** The row acts in place: picking it runs onSelect and the menu stays open (a connector that reconnects). */
keepOpen?: boolean;
};
export type DropdownMenuGroup = {
/** A label over the group. Without one, a gap separates it from the group before. */
label?: string;
/** In a multi choice list, the label's Clear button (shown while any row is on). */
clearLabel?: string;
/** The group's rows, in order. */
rows: DropdownMenuRow[];
};
export type DropdownMenuList = {
/** The menu's accessible name. */
"aria-label": string;
/** single: picking checks the row (a check, or a ring with dots). multi: rows toggle and the menu stays open. */
select?: "single" | "multi";
/** single choice: show a ring instead of a check (workspaces). */
ring?: boolean;
/** The menu's width (232px by default; submenus 212px). */
width?: string;
/** The rows, in groups: each with an optional label, separated by a gap when it has none. */
groups: DropdownMenuGroup[];
/** A search row first: it filters the rows and says when nothing matches. */
search?: { placeholder: string; "aria-label": string; empty: string; icon?: ReactNode };
/** Content after the rows, inside the menu (the composer's effort ramp under its models). */
after?: ReactNode;
/** A class on the menu itself (the composer's folder and branch menus set their names in mono). */
menuClassName?: string;
};
export type DropdownMenuTriggerState = {
/** Whether the menu is open. */
open: boolean;
/** The picked row of a single choice menu. */
picked?: DropdownMenuRow;
/** How many rows are on in a multi choice menu. */
count: number;
};
export type DropdownMenuProps = Omit<ComponentPropsWithoutRef<"div">, "children"> &
DropdownMenuList & {
/** The trigger, a locked Button; or a function of the menu's state, to show the picked value or the count. */
trigger: ReactElement | ((state: DropdownMenuTriggerState) => ReactElement);
/** end: the menu lines up with the trigger's right edge. */
align?: "end";
/** Runs with the root menu's picked ids (single: one id; multi: every row that is on). */
onValueChange?: (ids: string[]) => void;
/** Open on mount, without taking focus (a preview, a tour). */
defaultOpen?: boolean;
};
/* ------------------------------------------------------------------ the marks (static free Hugeicons, MIT) */
const Check = () => (
<svg className="pixilui-dropdown-check" viewBox="0 0 24 24" aria-hidden="true">
<path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="m5 14l3.5 3.5L19 6.5" />
</svg>
);
const Chevron = () => (
<svg className="pixilui-dropdown-chev" viewBox="0 0 24 24" aria-hidden="true">
<path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M9 6s6 4.419 6 6s-6 6-6 6" />
</svg>
);
const Ring = () => (
<span className="pixilui-dropdown-ring">
<svg className="pixilui-i" viewBox="0 0 24 24" aria-hidden="true">
<path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="m5 14l3.5 3.5L19 6.5" />
</svg>
</span>
);
function withIconClass(node: ReactNode) {
if (!isValidElement(node)) return node;
const el = node as ReactElement<{ className?: string }>;
return cloneElement(el, { className: cn("pixilui-i", el.props.className) });
}
/* ------------------------------------------------------------------ the markup */
/** Every row by its element id, for the menu whose id is given (the ids Menu writes). */
function collect(list: DropdownMenuList, id: string, into = new Map<string, DropdownMenuRow>()) {
list.groups.forEach((g, gi) =>
g.rows.forEach((row, ri) => {
const rowId = `${id}-${gi}-${ri}`;
into.set(rowId, row);
if (row.submenu) collect(row.submenu, `${rowId}-sub`, into);
}),
);
return into;
}
function Menu({ list, id, sub, hidden }: { list: DropdownMenuList; id: string; sub?: boolean; hidden?: boolean }) {
const parts: ReactNode[] = [<span key="hl" className="pixilui-dropdown-highlight" aria-hidden="true" />];
if (list.search)
parts.push(
<div key="search" className="pixilui-dropdown-search" data-pxi="">
{withIconClass(list.search.icon)}
<input type="text" placeholder={list.search.placeholder} aria-label={list.search["aria-label"]} autoComplete="off" spellCheck={false} />
</div>,
);
list.groups.forEach((g, gi) => {
if (g.label != null)
parts.push(
<div key={`l${gi}`} className="pixilui-dropdown-label">
{g.clearLabel ? (
<>
<span>{g.label}</span>
<button className="pixilui-dropdown-clear" type="button" hidden={!g.rows.some((r) => r.checked)}>
{g.clearLabel}
</button>
</>
) : (
g.label
)}
</div>,
);
else if (gi > 0) parts.push(<div key={`s${gi}`} className="pixilui-dropdown-sep" />);
g.rows.forEach((row, ri) => {
const rowId = `${id}-${gi}-${ri}`;
const subId = row.submenu ? `${rowId}-sub` : undefined;
const sw = row.kind === "switch";
const act = row.kind === "action" || !list.select;
const role = sw || (list.select === "multi" && !act) ? "menuitemcheckbox" : act ? "menuitem" : "menuitemradio";
const checked = sw || (list.select === "multi" && !act) ? (row.checked ? "true" : "false") : row.checked && !act ? "true" : undefined;
parts.push(
<div
key={rowId}
id={rowId}
className="pixilui-dropdown-item"
role={role}
aria-checked={checked}
data-tone={row.tone}
data-sub={subId}
data-switch={sw ? "" : undefined}
data-keep-open={row.keepOpen ? "" : undefined}
>
{list.select === "multi" && !sw && !act ? (
<span className="pixilui-checkbox">
<svg viewBox="0 0 14 14" aria-hidden="true">
<path className="pixilui-checkbox-tick" pathLength={1} d="M3.7 7.35l2.2 2.2 4.4-4.9" />
<path className="pixilui-checkbox-dash" pathLength={1} d="M4.4 7h5.2" />
</svg>
</span>
) : null}
{withIconClass(row.icon)}
{row.dot ? <span className="pixilui-dropdown-dot" style={{ "--pixilui-dot": row.dot } as CSSProperties} /> : null}
<span className="pixilui-dropdown-text">
{row.description ? (
<>
<b>{row.label}</b>
<small data-tone={row.risk ? "risk" : undefined}>{row.description}</small>
</>
) : row.dot && list.select === "single" ? (
<b>{row.label}</b>
) : (
row.label
)}
</span>
{row.meta != null ? <span className="pixilui-dropdown-meta">{row.meta}</span> : null}
{row.shortcut ? <kbd>{row.shortcut}</kbd> : null}
{row.submenu ? <Chevron /> : null}
{list.select === "single" && !sw && !act ? list.ring ? <Ring /> : <Check /> : null}
{sw ? (
<span className="pixilui-switch" aria-hidden="true" aria-checked={row.checked ? "true" : "false"}>
<span className="pixilui-switch-knob" aria-hidden="true" />
</span>
) : null}
</div>,
);
if (row.submenu && subId) parts.push(<Menu key={subId} list={row.submenu} id={subId} sub hidden />);
});
});
if (list.search)
parts.push(
<div key="empty" className="pixilui-dropdown-empty" data-text={list.search.empty} hidden>
{null}
</div>,
);
if (list.after != null) parts.push(<div key="after-sep" className="pixilui-dropdown-sep" />, <Fragment key="after">{list.after}</Fragment>);
return (
<div
className={cn("pixilui-dropdown-menu", sub && "pixilui-dropdown-sub", list.menuClassName)}
id={id}
role="menu"
aria-label={list["aria-label"]}
data-single={list.select === "single" ? "" : undefined}
data-multi={list.select === "multi" ? "" : undefined}
style={list.width ? ({ "--pixilui-dropdown-w": list.width } as CSSProperties) : undefined}
hidden={hidden}
>
{parts}
</div>
);
}
/* ------------------------------------------------------------------ the behavior (dropdown-menu.js) */
type Events = {
pick: (row: Element, menu: Element) => void;
flip: (row: Element, checked: boolean) => void;
clear: (menu: Element) => void;
openChange: (open: boolean) => void;
};
type MenuEl = HTMLElement & { _t?: ReturnType<typeof setTimeout>; _hover?: ReturnType<typeof setTimeout> | 0; _over?: HTMLElement; _anchor?: { x: number; y: number } | null };
/** Wires one dropdown (its root element holds the trigger and the menu). Returns the cleanup. */
function wire(dd: HTMLElement, on: Events) {
const off: (() => void)[] = [];
const listen = <K extends keyof HTMLElementEventMap>(el: EventTarget, type: K | string, fn: (e: never) => void, opts?: AddEventListenerOptions | boolean) => {
el.addEventListener(type, fn as EventListener, opts);
off.push(() => el.removeEventListener(type, fn as EventListener, opts));
};
const names = new WeakMap<Element, string>();
const rows = (menu: Element) => [...menu.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item:not([hidden])")];
const subOf = (item: Element | null) => (item instanceof HTMLElement && item.dataset.sub ? (document.getElementById(item.dataset.sub) as MenuEl | null) : null);
const active = (menu: Element) => (document.getElementById(menu.getAttribute("aria-activedescendant") || "") as HTMLElement | null) || null;
const reduce = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
const syncSwitch = (it: Element) => it.querySelector(":scope > .pixilui-switch")?.setAttribute("aria-checked", String(it.getAttribute("aria-checked") === "true"));
const trigger = () => dd.querySelector<HTMLElement>(":scope > .pixilui-dropdown-trigger")!;
const root = () => dd.querySelector<MenuEl>(":scope > .pixilui-dropdown-menu")!;
// keys win until the pointer really moves
let keys = false;
listen(window, "keydown", () => (keys = true), true);
listen(window, "mousemove", (e: MouseEvent) => {
if (e.movementX || e.movementY) keys = false;
}, true);
function unplay(menu: Element, keep?: Element) {
menu.querySelectorAll(":scope > .pixilui-dropdown-item[data-pxi-play]").forEach((x) => x !== keep && x.removeAttribute("data-pxi-play"));
}
function glide(menu: MenuEl, item: HTMLElement | null | undefined, jump?: boolean) {
const hl = menu.querySelector<HTMLElement>(":scope > .pixilui-dropdown-highlight");
if (!hl || !item) return;
menu.toggleAttribute("data-jump", !!jump || !menu.hasAttribute("data-hl"));
menu.style.setProperty("--pixilui-dropdown-y", `${item.offsetTop}px`);
hl.style.height = `${item.offsetHeight}px`;
menu.toggleAttribute("data-hl", true);
menu.setAttribute("aria-activedescendant", item.id);
unplay(menu, item);
item.setAttribute("data-pxi-play", "");
requestAnimationFrame(() => menu.removeAttribute("data-jump"));
}
function rest(menu: MenuEl) {
const keep =
menu.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-expanded="true"]') ||
(!menu.hasAttribute("data-multi") && menu.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-checked="true"]:not([hidden]):not([data-switch])'));
if (keep) glide(menu, keep);
else {
menu.removeAttribute("data-hl");
menu.removeAttribute("aria-activedescendant");
unplay(menu);
}
}
function show(menu: MenuEl) {
clearTimeout(menu._t);
menu.removeAttribute("data-out");
menu.removeAttribute("data-hl");
unplay(menu);
menu.hidden = false;
const seq = [...menu.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item, :scope > .pixilui-dropdown-label, :scope > .pixilui-dropdown-search")];
seq.forEach((el, i) => el.style.setProperty("--pixilui-dropdown-i", String(i)));
menu.removeAttribute("data-in");
void menu.offsetWidth;
menu.toggleAttribute("data-in", true);
}
function hide(menu: MenuEl, instant?: boolean) {
if (menu.hidden) return;
menu.querySelectorAll(':scope > .pixilui-dropdown-item[aria-expanded="true"]').forEach((it) => closeSub(it as HTMLElement, true));
if (instant || reduce()) {
clearTimeout(menu._t);
menu.hidden = true;
menu.removeAttribute("data-in");
menu.removeAttribute("data-out");
return;
}
menu.removeAttribute("data-in");
menu.toggleAttribute("data-out", true);
const finish = () => {
clearTimeout(menu._t);
menu.removeEventListener("animationend", done);
if (menu.hasAttribute("data-out")) {
menu.hidden = true;
menu.removeAttribute("data-out");
}
};
function done(e: Event) {
if (e.target === menu) finish();
}
menu.addEventListener("animationend", done);
menu._t = setTimeout(finish, (parseFloat(getComputedStyle(menu).animationDuration) || 0) * 1000 + 60); // if animationend never comes
}
function filter(menu: MenuEl, query: string) {
const q = query.trim().toLowerCase();
let first: HTMLElement | null = null;
menu.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item").forEach((it) => {
const b = it.querySelector<HTMLElement>(".pixilui-dropdown-text b") || it.querySelector<HTMLElement>(".pixilui-dropdown-text")!;
if (!names.has(b)) names.set(b, b.textContent ?? "");
const name = it.dataset.value || names.get(b)!;
const at = name.toLowerCase().indexOf(q);
const ok = !q || at >= 0;
it.hidden = !ok;
b.replaceChildren();
if (!q || at < 0) b.append(name);
else {
const dim = (t: string) => {
const span = document.createElement("span");
span.setAttribute("data-dim", "");
span.textContent = t;
return span;
};
b.append(dim(name.slice(0, at)), name.slice(at, at + q.length), dim(name.slice(at + q.length)));
}
if (ok && !first) first = it;
});
let label: HTMLElement | null = null;
let seen = false;
const settle = () => {
if (label) label.hidden = !seen;
};
[...menu.children].forEach((el) => {
if (!(el instanceof HTMLElement)) return;
if (el.classList.contains("pixilui-dropdown-label")) {
settle();
label = el;
seen = false;
} else if (el.classList.contains("pixilui-dropdown-item") && !el.hidden) seen = true;
else if (el.classList.contains("pixilui-dropdown-sep")) el.hidden = !!q;
});
settle();
const empty = menu.querySelector<HTMLElement>(":scope > .pixilui-dropdown-empty");
if (empty) {
empty.hidden = !!first;
if (!first) empty.textContent = `${empty.dataset.text || ""} “${q}”`;
}
if (q) {
if (first) glide(menu, first, true);
else {
menu.removeAttribute("data-hl");
menu.removeAttribute("aria-activedescendant");
unplay(menu);
}
}
}
function open(focus?: boolean) {
const menu = root();
if (!menu.hidden && !menu.hasAttribute("data-out")) return;
const search = menu.querySelector<HTMLInputElement>(":scope > .pixilui-dropdown-search input");
if (search) {
search.value = "";
filter(menu, "");
}
show(menu);
trigger().setAttribute("aria-expanded", "true");
on.openChange(true);
const cur = !menu.hasAttribute("data-multi") && menu.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-checked="true"]:not([data-switch])');
if (cur) glide(menu, cur, true);
if (focus) {
(search || menu).focus({ preventScroll: true });
if (!cur && !search) glide(menu, rows(menu)[0], true);
}
}
function close() {
const menu = root();
if (menu.hidden) return;
trigger().setAttribute("aria-expanded", "false");
hide(menu);
on.openChange(false);
}
function openSub(item: HTMLElement, focus?: boolean) {
const sub = subOf(item);
if (!sub) return;
const menu = item.parentElement as MenuEl;
clearTimeout(menu._hover || undefined);
menu.querySelectorAll<HTMLElement>(':scope > .pixilui-dropdown-item[aria-expanded="true"]').forEach((o) => o !== item && closeSub(o));
if (item.getAttribute("aria-expanded") !== "true" || sub.hidden || sub.hasAttribute("data-out")) {
sub.style.top = `${item.offsetTop - parseFloat(getComputedStyle(menu).paddingTop)}px`;
item.setAttribute("aria-expanded", "true");
show(sub);
}
glide(menu, item);
const cur = sub.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-checked="true"]:not([data-switch])');
if (focus) {
glide(sub, cur || rows(sub)[0], true);
sub.focus({ preventScroll: true });
} else if (cur) glide(sub, cur, true);
}
function closeSub(item: HTMLElement, instant?: boolean) {
const sub = subOf(item);
if (!sub) return;
item.setAttribute("aria-expanded", "false");
hide(sub, instant);
}
function count(menu: Element) {
const n = menu.querySelectorAll(':scope > .pixilui-dropdown-item[aria-checked="true"]').length;
const c = menu.querySelector<HTMLElement>(".pixilui-dropdown-clear");
if (c) c.hidden = !n;
}
function pick(item: HTMLElement) {
const menu = item.parentElement as MenuEl;
if (item.dataset.sub) return openSub(item, true);
const acts = item.getAttribute("role") === "menuitem";
if (item.hasAttribute("data-switch") || (menu.hasAttribute("data-multi") && !acts)) {
const next = item.getAttribute("aria-checked") !== "true";
item.setAttribute("aria-checked", String(next));
syncSwitch(item);
if (menu.hasAttribute("data-multi")) count(menu);
glide(menu, item);
on.flip(item, next);
return;
}
if (item.hasAttribute("data-keep-open")) {
on.pick(item, menu);
glide(menu, item);
return;
}
if (menu.hasAttribute("data-single") && !acts) {
menu.querySelectorAll(":scope > .pixilui-dropdown-item").forEach((i) => i.removeAttribute("aria-checked"));
item.setAttribute("aria-checked", "true");
}
on.pick(item, menu);
close();
trigger().focus();
}
// is the pointer travelling from the open row toward its submenu (inside the "safe triangle")?
function heading(menu: MenuEl, x: number, y: number) {
const it = menu.querySelector(':scope > .pixilui-dropdown-item[aria-expanded="true"]');
const sub = subOf(it);
const a = menu._anchor;
if (!sub || !a) return false;
const r = sub.getBoundingClientRect();
const A = [a.x, a.y];
const B = [r.left, r.top - 8];
const C = [r.left, r.bottom + 8];
const P = [x, y];
const side = (u: number[], v: number[], w: number[]) => (u[0]! - w[0]!) * (v[1]! - w[1]!) - (v[0]! - w[0]!) * (u[1]! - w[1]!);
const s1 = side(P, A, B) < 0;
const s2 = side(P, B, C) < 0;
const s3 = side(P, C, A) < 0;
return s1 === s2 && s2 === s3;
}
function hoverTo(menu: MenuEl, it: HTMLElement | undefined) {
clearTimeout(menu._hover || undefined);
if (!it || it.hidden) return;
glide(menu, it);
const openIt = menu.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-expanded="true"]');
if (openIt && openIt !== it) closeSub(openIt);
if (it.dataset.sub && it.getAttribute("aria-expanded") !== "true")
menu._hover = setTimeout(() => {
menu._hover = 0;
openSub(it);
}, 80); // hover intent
}
function wireMenu(menu: MenuEl, parentItem: HTMLElement | null) {
menu.tabIndex = -1;
menu.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item").forEach((it) => {
const sub = subOf(it);
if (sub) {
it.setAttribute("aria-haspopup", "menu");
it.setAttribute("aria-expanded", "false");
it.setAttribute("aria-controls", sub.id);
wireMenu(sub, it);
}
if (it.hasAttribute("data-switch")) syncSwitch(it);
});
listen(menu, "mousemove", (e: MouseEvent) => {
const target = e.target as Element;
if (keys || target.closest(".pixilui-dropdown-menu") !== menu) return;
const it = target.closest<HTMLElement>(".pixilui-dropdown-item");
if (!it || it.parentElement !== menu) return;
menu._over = it;
const openIt = menu.querySelector<HTMLElement>(':scope > .pixilui-dropdown-item[aria-expanded="true"]');
if (it === openIt) {
menu._anchor = { x: e.clientX, y: e.clientY };
clearTimeout(menu._hover || undefined);
if (active(menu) !== it) glide(menu, it);
return;
}
if (openIt && heading(menu, e.clientX, e.clientY)) {
clearTimeout(menu._hover || undefined);
menu._hover = setTimeout(() => {
menu._hover = 0;
hoverTo(menu, menu._over);
}, 260);
return;
}
menu._anchor = null;
if (active(menu) !== it || (it.dataset.sub && it.getAttribute("aria-expanded") !== "true" && !menu._hover)) hoverTo(menu, it);
});
listen(menu, "mouseleave", (e: MouseEvent) => {
if (keys || (e.relatedTarget && menu.contains(e.relatedTarget as Node))) return;
clearTimeout(menu._hover || undefined);
menu._hover = 0;
rest(menu);
});
if (parentItem)
listen(menu, "mouseenter", () => {
if (keys) return;
const pm = parentItem.parentElement as MenuEl;
clearTimeout(pm._hover || undefined);
pm._hover = 0;
glide(pm, parentItem);
});
listen(menu, "click", (e: MouseEvent) => {
const target = e.target as Element;
if (target.closest(".pixilui-dropdown-menu") !== menu) return;
e.stopPropagation();
if (target.closest(".pixilui-dropdown-clear")) {
menu.querySelectorAll(":scope > .pixilui-dropdown-item").forEach((i) => i.setAttribute("aria-checked", "false"));
count(menu);
on.clear(menu);
return;
}
const it = target.closest<HTMLElement>(".pixilui-dropdown-item");
if (it && it.parentElement === menu) pick(it);
});
const search = menu.querySelector<HTMLInputElement>(":scope > .pixilui-dropdown-search input");
if (search) listen(search, "input", () => filter(menu, search.value));
listen(menu, "keydown", (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
if (target.closest(".pixilui-dropdown-menu") !== menu || e.isComposing) return;
const typing = target.tagName === "INPUT";
const list = rows(menu);
const cur = active(menu);
const i = cur ? list.indexOf(cur) : -1;
const step = (d: number) => {
if (!list.length) return;
const n = i < 0 ? (d > 0 ? 0 : list.length - 1) : (i + d + list.length) % list.length;
glide(menu, list[n]);
};
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
step(e.key === "ArrowDown" ? 1 : -1);
} else if (!typing && (e.key === "Home" || e.key === "End")) {
e.preventDefault();
glide(menu, list[e.key === "Home" ? 0 : list.length - 1]);
} else if (e.key === "Enter" || (!typing && e.key === " ")) {
e.preventDefault();
if (cur && !cur.hidden) pick(cur);
} else if (!typing && e.key === "ArrowRight" && cur?.dataset.sub) {
e.preventDefault();
openSub(cur, true);
} else if ((e.key === "ArrowLeft" && !typing) || e.key === "Escape") {
e.preventDefault();
if (parentItem) {
closeSub(parentItem);
glide(parentItem.parentElement as MenuEl, parentItem);
(parentItem.parentElement as HTMLElement).focus({ preventScroll: true });
} else if (e.key === "Escape") {
close();
trigger().focus();
}
} else if (e.key === "Tab") close();
});
}
wireMenu(root(), null);
const t = trigger();
listen(t, "click", (e: MouseEvent) => {
e.stopPropagation();
const menu = root();
if (menu.hidden || menu.hasAttribute("data-out")) {
document.dispatchEvent(new CustomEvent("pixilui-dropdown:open", { detail: dd }));
open(true);
} else close();
});
listen(t, "keydown", (e: KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
document.dispatchEvent(new CustomEvent("pixilui-dropdown:open", { detail: dd }));
open(true);
}
});
// one menu open at a time, and an outside click closes it
listen(document, "pixilui-dropdown:open", (e: CustomEvent<HTMLElement>) => e.detail !== dd && close());
listen(window, "click", () => close());
return {
open,
close,
openSub,
cleanup: () => {
off.forEach((f) => f());
clearTimeout(root()._t);
},
};
}
/* ------------------------------------------------------------------ the part */
/** A menu that grows from its trigger, with a highlight that glides between rows: actions, choices, switches, submenus and search. */
export const DropdownMenu = forwardRef<HTMLDivElement, DropdownMenuProps>(function DropdownMenu(
{ trigger, align, onValueChange, defaultOpen, select, ring, width, groups = NONE, search, after, menuClassName, "aria-label": label, className, ...props },
forwarded,
) {
const uid = useId().replace(/[^\w-]/g, "");
const list: DropdownMenuList = { "aria-label": label, select, ring, width, groups, search, after, menuClassName };
const rowsById = useMemo(() => collect({ "aria-label": label, select, ring, width, groups, search }, `${uid}-menu`), [label, select, ring, width, groups, search, uid]);
const all = groups.flatMap((g) => g.rows);
const [picked, setPicked] = useState<string | undefined>(() => (select === "single" ? all.find((r) => r.checked)?.id : undefined));
const [count, setCount] = useState(() => (select === "multi" ? all.filter((r) => r.checked).length : 0));
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement | null>(null);
// the first render's wish only
const defaultOpenRef = useRef(defaultOpen);
const latest = useRef({ onValueChange, rowsById });
useEffect(() => {
latest.current = { onValueChange, rowsById };
});
useEffect(() => {
const dd = ref.current;
// no trigger (a missing prop): nothing to open, so nothing to wire
if (!dd || !dd.querySelector(":scope > .pixilui-dropdown-trigger")) return;
const rootId = `${uid}-menu`;
const rowOf = (el: Element) => latest.current.rowsById.get(el.id);
const checkedIds = (menu: Element) => [...menu.querySelectorAll(':scope > .pixilui-dropdown-item[aria-checked="true"]')].map((el) => rowOf(el)?.id).filter((x): x is string => !!x);
const wired = wire(dd, {
pick: (el, menu) => {
const row = rowOf(el);
row?.onSelect?.();
if (menu.id === rootId && menu.hasAttribute("data-single") && row && el.getAttribute("role") === "menuitemradio") {
setPicked(row.id);
latest.current.onValueChange?.([row.id]);
}
},
flip: (el, checked) => {
const row = rowOf(el);
row?.onCheckedChange?.(checked);
const menu = el.parentElement!;
if (menu.id === rootId && menu.hasAttribute("data-multi")) {
const ids = checkedIds(menu);
setCount(ids.length);
latest.current.onValueChange?.(ids);
}
},
clear: (menu) => {
menu.querySelectorAll(":scope > .pixilui-dropdown-item").forEach((el) => rowOf(el)?.onCheckedChange?.(false));
if (menu.id === rootId) {
setCount(0);
latest.current.onValueChange?.([]);
}
},
openChange: setOpen,
});
if (defaultOpenRef.current) wired.open(false);
return wired.cleanup;
}, [uid]);
const pickedRow = picked ? all.find((r) => r.id === picked) : undefined;
const t = typeof trigger === "function" ? trigger({ open, picked: pickedRow, count }) : trigger;
const triggerEl = isValidElement(t)
? cloneElement(t as ReactElement<{ className?: string }>, {
className: cn((t as ReactElement<{ className?: string }>).props.className, "pixilui-dropdown-trigger"),
"aria-haspopup": "menu",
"aria-expanded": open ? "true" : "false",
} as Record<string, unknown>)
: t;
return (
<div
ref={(el) => {
ref.current = el;
if (typeof forwarded === "function") forwarded(el);
else if (forwarded) forwarded.current = el;
}}
className={cn("pixilui-dropdown font-body", className)}
data-align={align}
{...props}
>
{triggerEl}
<Menu list={list} id={`${uid}-menu`} hidden />
</div>
);
});
/* ------------------------------------------------------------------ the moves, for a menu driven from elsewhere */
/**
* The menu's own moves for a menu another part drives (the composer's typed / and @ menus, which open at the caret and have no
* trigger of their own): showMenu grows it in, hideMenu plays its close and hides it, glideMenu moves the highlight (jump: no
* glide, as on the first row).
*/
export function showMenu(menu: HTMLElement) {
clearTimeout((menu as MenuEl)._t);
menu.removeAttribute("data-out");
menu.removeAttribute("data-hl");
menu.hidden = false;
[...menu.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item, :scope > .pixilui-dropdown-label, :scope > .pixilui-dropdown-search")].forEach((el, i) => el.style.setProperty("--pixilui-dropdown-i", String(i)));
menu.removeAttribute("data-in");
void menu.offsetWidth;
menu.toggleAttribute("data-in", true);
}
export function hideMenu(menu: HTMLElement) {
const m = menu as MenuEl;
if (menu.hidden) return;
if (matchMedia("(prefers-reduced-motion: reduce)").matches) {
menu.hidden = true;
menu.removeAttribute("data-in");
return;
}
menu.removeAttribute("data-in");
menu.toggleAttribute("data-out", true);
const finish = () => {
clearTimeout(m._t);
if (menu.hasAttribute("data-out")) {
menu.hidden = true;
menu.removeAttribute("data-out");
}
};
menu.addEventListener("animationend", (e) => e.target === menu && finish(), { once: true });
m._t = setTimeout(finish, (parseFloat(getComputedStyle(menu).animationDuration) || 0) * 1000 + 60);
}
export function glideMenu(menu: HTMLElement, item: HTMLElement | null | undefined, jump?: boolean) {
const hl = menu.querySelector<HTMLElement>(":scope > .pixilui-dropdown-highlight");
if (!hl || !item) return;
menu.toggleAttribute("data-jump", !!jump || !menu.hasAttribute("data-hl"));
menu.style.setProperty("--pixilui-dropdown-y", `${item.offsetTop}px`);
hl.style.height = `${item.offsetHeight}px`;
menu.toggleAttribute("data-hl", true);
menu.setAttribute("aria-activedescendant", item.id);
menu.querySelectorAll(":scope > .pixilui-dropdown-item[data-pxi-play]").forEach((x) => x !== item && x.removeAttribute("data-pxi-play"));
item.setAttribute("data-pxi-play", "");
requestAnimationFrame(() => menu.removeAttribute("data-jump"));
}
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { DropdownMenu } from "@/components/pixilui/dropdown-menu";
<DropdownMenu
aria-label={aria-label}
groups={groups}
trigger={trigger}
onValueChange={onValueChange}
/>The menu is 232px by default (width sets it); align="end" lines it up with the trigger's right edge.
API reference
PropTypeDefault
aria-labelRequiredstring–The menu's accessible name.groupsRequiredDropdownMenuGroup[]NONEThe rows, in groups: each with an optional label, separated by a gap when it has none.triggerRequiredReactElement | ((state: DropdownMenuTriggerState) => ReactElement)–The trigger, a locked Button; or a function of the menu's state, to show the picked value or the count.select"single" | "multi"–single: picking checks the row (a check, or a ring with dots). multi: rows toggle and the menu stays open.ringboolean–single choice: show a ring instead of a check (workspaces).widthstring–The menu's width (232px by default; submenus 212px).search{ placeholder: string; "aria-label": string; empty: string; icon?: ReactNode }–A search row first: it filters the rows and says when nothing matches.afterReactNode–Content after the rows, inside the menu (the composer's effort ramp under its models).menuClassNamestring–A class on the menu itself (the composer's folder and branch menus set their names in mono).align"end"–end: the menu lines up with the trigger's right edge.onValueChange(ids: string[]) => void–Runs with the root menu's picked ids (single: one id; multi: every row that is on).defaultOpenboolean–Open on mount, without taking focus (a preview, a tour).Also takes every native <div> attribute, and a ref.
Keyboard
↓ Enter SpaceOn the trigger, opens the menu and moves focus into it (or its search).
↑ ↓Moves the highlight, wrapping at the ends; Home and End jump to them.
EnterPicks the highlighted row; a switch or multi choice row flips and the menu stays open.
→ ←Opens a submenu and moves into it; steps back to its row.
EscCloses the menu (or steps out of a submenu) and returns focus to the trigger.
TabCloses the menu.
Accessibility
- The trigger has aria-haspopup="menu" and aria-expanded; the menu follows the highlight with aria-activedescendant.
- Rows are menuitem, menuitemradio or menuitemcheckbox with aria-checked; a switch row's switch is aria-hidden and the row carries the state.
- Only one menu is open at a time; an outside click closes it.
- Keys win until the pointer really moves, so a menu closing under a resting pointer never steals the keyboard's highlight.
Motion
- Opens from .96 and fades in over 200ms while its rows rise 3px, 25ms apart; closes in 120ms the same way back.
- The highlight glides to its row in 150ms, and the row's animated icon plays as it lands.
- A submenu opens after an 80ms hover intent; a safe triangle keeps it open while the pointer heads to it.
- Reduced motion: instant.