Dropdown menu
Scales out of its trigger, one highlight slides between items, and a submenu stays open while your pointer cuts the corner toward it.
npx shadcn@latest add https://captain-ui.vercel.app/r/dropdown-menu.jsonFix invoice rounding
Run 1187 in billing-service, 4m 12s, $0.84
"use client";
// Captain UI · Dropdown menu, MIT. Scales out of its trigger, one highlight slides between items, submenus forgive a diagonal pointer.
import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from "motion/react";
import {
createContext,
useCallback,
useContext,
useEffect,
useId,
useRef,
useState,
type KeyboardEvent,
type MutableRefObject,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { EASE, SPRING_LAYOUT, clamp, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
type Pt = { x: number; y: number };
type OpenedBy = "pointer" | "keyboard";
type RootCtx = {
open: boolean;
openedBy: OpenedBy;
setOpen: (open: boolean, by?: OpenedBy) => void;
trigger: MutableRefObject<HTMLButtonElement | null>;
contentId: string;
};
type LevelCtx = {
content: MutableRefObject<HTMLDivElement | null>;
sub: string | null;
setSub: (id: string | null, by?: OpenedBy) => void;
subBy: OpenedBy;
/** The safe triangle toward an open submenu. Items under it ignore the pointer. */
grace: MutableRefObject<{ poly: Pt[]; until: number } | null>;
close: (focusBack?: boolean) => void;
};
type SubCtx = { id: string; open: boolean; trigger: MutableRefObject<HTMLDivElement | null> };
const Root = createContext<RootCtx | null>(null);
const Level = createContext<LevelCtx | null>(null);
const Sub = createContext<SubCtx | null>(null);
const use = <T,>(c: React.Context<T | null>, n: string) => {
const v = useContext(c);
if (!v) throw new Error(`${n} must be used inside <DropdownMenu>`);
return v;
};
const ITEM = '[data-cu-item]:not([aria-disabled="true"])';
const items = (el: HTMLElement | null) => (el ? Array.from(el.querySelectorAll<HTMLElement>(ITEM)).filter((n) => n.closest("[data-cu-menu]") === el) : []);
function inPoly(p: Pt, poly: Pt[]) {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i]!;
const b = poly[j]!;
if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
}
return inside;
}
export function DropdownMenu({ open: controlled, defaultOpen = false, onOpenChange, children }: { open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; children: ReactNode }) {
const [inner, setInner] = useState(defaultOpen);
const [openedBy, setBy] = useState<OpenedBy>("pointer");
const open = controlled ?? inner;
const trigger = useRef<HTMLButtonElement | null>(null);
const contentId = useId();
const setOpen = useCallback(
(next: boolean, by: OpenedBy = "pointer") => {
setBy(by);
if (controlled === undefined) setInner(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
return <Root.Provider value={{ open, openedBy, setOpen, trigger, contentId }}>{children}</Root.Provider>;
}
export function DropdownMenuTrigger({ children, className, "aria-label": label }: { children: ReactNode; className?: string; "aria-label"?: string }) {
const r = use(Root, "DropdownMenuTrigger");
const mouse = useRef(false);
return (
<button
ref={r.trigger}
type="button"
aria-label={label}
aria-haspopup="menu"
aria-expanded={r.open}
aria-controls={r.open ? r.contentId : undefined}
data-state={r.open ? "open" : "closed"}
onPointerDown={(e) => {
if (e.button !== 0 || e.pointerType !== "mouse") return;
mouse.current = true;
// Keep focus off the trigger so the menu can take it.
if (!r.open) e.preventDefault();
r.setOpen(!r.open, "pointer");
}}
onClick={(e) => {
// Touch and keyboard-clicks land here; mouse already toggled on pointerdown.
if (mouse.current) {
mouse.current = false;
return;
}
r.setOpen(!r.open, e.detail === 0 ? "keyboard" : "pointer");
}}
onKeyDown={(e) => {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
r.setOpen(true, "keyboard");
}
}}
className={cx(
"pressable inline-flex h-9 items-center gap-1.5 rounded-inner px-3 text-[14px] font-medium text-ink transition-colors duration-150 hover:bg-hover focus-visible:bg-hover data-[state=open]:bg-press",
className,
)}
>
{children}
</button>
);
}
type Placement = { x: number; y: number; ox: number; oy: number };
function useMenu(close: (focusBack?: boolean) => void) {
const content = useRef<HTMLDivElement | null>(null);
const [sub, setSubState] = useState<string | null>(null);
const [subBy, setSubBy] = useState<OpenedBy>("pointer");
const grace = useRef<{ poly: Pt[]; until: number } | null>(null);
const setSub = useCallback((id: string | null, by: OpenedBy = "pointer") => {
setSubBy(by);
setSubState(id);
}, []);
return { content, sub, setSub, subBy, grace, close } satisfies LevelCtx;
}
type PanelProps = {
level: LevelCtx;
id?: string;
labelledBy?: string;
place: (w: number, h: number) => Placement | null;
focusFirst: boolean;
onEscape: () => void;
onLeft?: () => void;
subId?: string;
className?: string;
children: ReactNode;
};
/** One floating list: positioning, roving focus, the sliding highlight and typeahead. Shared by the menu and its submenus. */
function Panel({ level, id, labelledBy, place, focusFirst, onEscape, onLeft, subId, className, children }: PanelProps) {
const reduce = useReducedMotion();
const [pos, setPos] = useState<Placement | null>(null);
const hy = useMotionValue(0);
const hh = useMotionValue(0);
const ho = useMotionValue(0);
const shown = useRef(false);
const typed = useRef({ text: "", t: 0 });
useIsoLayoutEffect(() => {
const el = level.content.current;
if (!el) return;
const run = () => setPos(place(el.offsetWidth, el.offsetHeight));
run();
window.addEventListener("resize", run);
window.addEventListener("scroll", run, true);
return () => {
window.removeEventListener("resize", run);
window.removeEventListener("scroll", run, true);
};
}, []);
useEffect(() => {
const el = level.content.current;
if (!el) return;
if (focusFirst) items(el)[0]?.focus({ preventScroll: true });
else el.focus({ preventScroll: true });
}, []);
// The highlight follows focus. Hover moves focus, so pointer and keyboard share one highlight.
const follow = (target: HTMLElement | null) => {
const el = level.content.current;
// Focus inside a submenu bubbles here through the portal: keep the highlight on its trigger.
if (!el || !target || target.closest("[data-cu-menu]") !== el) return;
if (target === el) {
animate(ho, 0, { duration: 0.12, ease: EASE });
shown.current = false;
return;
}
const y = target.offsetTop;
const h = target.offsetHeight;
if (!shown.current || reduce) {
hy.jump(y);
hh.jump(h);
animate(ho, 1, { duration: shown.current ? 0 : 0.08, ease: EASE });
} else {
animate(hy, y, SPRING_LAYOUT);
animate(hh, h, SPRING_LAYOUT);
}
shown.current = true;
};
useEffect(() => {
const el = level.content.current;
if (!el) return;
const leave = (e: PointerEvent) => {
if (e.pointerType !== "mouse" || level.sub) return;
const to = e.relatedTarget as Node | null;
if (to && el.contains(to)) return;
el.focus({ preventScroll: true });
};
el.addEventListener("pointerleave", leave);
return () => el.removeEventListener("pointerleave", leave);
}, [level.sub]);
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const el = level.content.current;
if (!el || !el.contains(e.target as Node)) return;
const list = items(el);
const i = list.indexOf(document.activeElement as HTMLElement);
const go = (n: number) => list[(n + list.length) % list.length]?.focus({ preventScroll: true });
switch (e.key) {
case "ArrowDown":
e.preventDefault();
go(i < 0 ? 0 : i + 1);
return;
case "ArrowUp":
e.preventDefault();
go(i < 0 ? list.length - 1 : i - 1);
return;
case "Home":
case "PageUp":
e.preventDefault();
go(0);
return;
case "End":
case "PageDown":
e.preventDefault();
go(list.length - 1);
return;
case "Escape":
e.preventDefault();
e.stopPropagation();
onEscape();
return;
case "ArrowLeft":
if (onLeft) {
e.preventDefault();
onLeft();
}
return;
case "Tab":
e.preventDefault();
level.close(true);
return;
case "Enter":
case " ":
if (i >= 0 && !typed.current.text) {
e.preventDefault();
list[i]!.click();
}
return;
}
// Typeahead: letters within 500ms add up; a repeated letter cycles through matches.
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
const now = performance.now();
const t = typed.current;
t.text = now - t.t > 500 ? e.key.toLowerCase() : t.text + e.key.toLowerCase();
t.t = now;
setTimeout(() => {
if (performance.now() - typed.current.t >= 500) typed.current.text = "";
}, 520);
const same = t.text.split("").every((c) => c === t.text[0]);
const q = same ? t.text[0]! : t.text;
const label = (n: HTMLElement) => (n.dataset.text ?? n.textContent ?? "").trim().toLowerCase();
const order = [...list.slice(i + 1), ...list.slice(0, i + 1)];
const pool = same || i < 0 ? order : [list[i]!, ...order];
pool.find((n) => label(n).startsWith(q))?.focus({ preventScroll: true });
}
};
return (
<motion.div
ref={level.content}
id={id}
role="menu"
aria-orientation="vertical"
aria-labelledby={labelledBy}
tabIndex={-1}
data-cu-menu=""
data-cu-sub={subId}
onKeyDown={onKey}
onFocus={(e) => follow(e.target as HTMLElement)}
initial={{ opacity: 0, scale: reduce ? 1 : 0.96 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.96, transition: { duration: 0.12, ease: EASE } }}
transition={{ duration: 0.16, ease: EASE }}
className={cx("glass fixed left-0 top-0 z-[90] min-w-[224px] rounded-shell p-1 outline-none", className)}
style={{
left: pos?.x ?? -9999,
top: pos?.y ?? -9999,
// No visibility:hidden before placement: focus() on a hidden element silently fails, and the first item is focused in an effect.
transformOrigin: pos ? `${pos.ox}px ${pos.oy}px` : undefined,
}}
>
<motion.div aria-hidden="true" className="pointer-events-none absolute inset-x-1 top-0 rounded-inner bg-press" style={{ y: hy, height: hh, opacity: ho }} />
{children}
</motion.div>
);
}
export function DropdownMenuContent({ children, align = "start", sideOffset = 6, className }: { children: ReactNode; align?: "start" | "end"; sideOffset?: number; className?: string }) {
const r = use(Root, "DropdownMenuContent");
const close = useCallback(
(focusBack = true) => {
r.setOpen(false);
if (focusBack) r.trigger.current?.focus({ preventScroll: true });
},
[r],
);
const level = useMenu(close);
useEffect(() => {
if (!r.open) return;
const away = (e: PointerEvent) => {
const t = e.target as Node;
if (r.trigger.current?.contains(t)) return;
if (t instanceof Element && t.closest("[data-cu-menu]")) return;
close(false);
};
document.addEventListener("pointerdown", away, true);
return () => document.removeEventListener("pointerdown", away, true);
}, [r.open, close, r.trigger]);
const place = (w: number, h: number): Placement | null => {
const t = r.trigger.current?.getBoundingClientRect();
if (!t) return null;
const vw = window.innerWidth;
const vh = window.innerHeight;
const below = vh - t.bottom - sideOffset - 8 >= h || t.top < vh - t.bottom;
const x = clamp(align === "start" ? t.left : t.right - w, 8, vw - w - 8);
const y = below ? t.bottom + sideOffset : t.top - sideOffset - h;
return { x, y, ox: clamp(t.left + t.width / 2 - x, 0, w), oy: below ? 0 : h };
};
return typeof document === "undefined"
? null
: createPortal(
<AnimatePresence>
{r.open ? (
<Level.Provider value={level}>
<Panel level={level} id={r.contentId} place={place} focusFirst={r.openedBy === "keyboard"} onEscape={() => close(true)} className={className}>
{children}
</Panel>
</Level.Provider>
) : null}
</AnimatePresence>,
document.body,
);
}
type ItemProps = {
children: ReactNode;
onSelect?: () => void;
disabled?: boolean;
/** Keyboard shortcut shown at the right, e.g. "⌘R". */
shortcut?: string;
tone?: "default" | "danger";
/** Text used for typeahead when children are not plain text. */
textValue?: string;
/** Keep the menu open after selecting. */
keepOpen?: boolean;
className?: string;
};
function useItemPointer() {
const lvl = use(Level, "DropdownMenuItem");
return (e: React.PointerEvent<HTMLElement>) => {
if (e.pointerType !== "mouse") return;
const g = lvl.grace.current;
if (g && performance.now() < g.until && inPoly({ x: e.clientX, y: e.clientY }, g.poly)) return;
lvl.grace.current = null;
if (document.activeElement !== e.currentTarget) e.currentTarget.focus({ preventScroll: true });
};
}
const ROW =
"relative flex h-8 cursor-default select-none items-center gap-2.5 rounded-inner pl-2 pr-2.5 text-[14px] text-ink outline-none aria-disabled:opacity-45 before:absolute before:inset-x-0 before:-inset-y-0.5 before:content-['']";
function Slot({ children }: { children?: ReactNode }) {
return <span className="grid size-4 shrink-0 place-items-center text-ink-2">{children}</span>;
}
function Shortcut({ keys }: { keys?: string }) {
return keys ? <span className="tnum ml-auto pl-6 text-[12.5px] text-ink-3">{keys}</span> : null;
}
export function DropdownMenuItem({ children, onSelect, disabled, shortcut, tone = "default", textValue, keepOpen, className }: ItemProps) {
const lvl = use(Level, "DropdownMenuItem");
const r = use(Root, "DropdownMenuItem");
const hover = useItemPointer();
return (
<div
role="menuitem"
tabIndex={-1}
data-cu-item=""
data-text={textValue}
aria-disabled={disabled || undefined}
onPointerMove={hover}
onFocus={() => lvl.setSub(null)}
onClick={() => {
if (disabled) return;
onSelect?.();
if (!keepOpen) {
r.setOpen(false);
r.trigger.current?.focus({ preventScroll: true });
}
}}
className={cx(ROW, tone === "danger" && "text-danger", className)}
>
<Slot />
<span className="truncate">{children}</span>
<Shortcut keys={shortcut} />
</div>
);
}
export function DropdownMenuCheckboxItem({
checked,
onCheckedChange,
children,
disabled,
shortcut,
textValue,
}: Omit<ItemProps, "onSelect" | "tone" | "keepOpen"> & { checked: boolean; onCheckedChange: (checked: boolean) => void }) {
const lvl = use(Level, "DropdownMenuCheckboxItem");
const hover = useItemPointer();
const reduce = useReducedMotion();
return (
<div
role="menuitemcheckbox"
aria-checked={checked}
tabIndex={-1}
data-cu-item=""
data-text={textValue}
aria-disabled={disabled || undefined}
onPointerMove={hover}
onFocus={() => lvl.setSub(null)}
onClick={() => !disabled && onCheckedChange(!checked)}
className={ROW}
>
<Slot>
<svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" className="text-ink">
<motion.path
d="M5.5 12.75 9.75 17 18.5 7.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
initial={false}
animate={{ pathLength: checked ? 1 : 0, opacity: checked ? 1 : 0 }}
transition={reduce ? { duration: 0 } : { duration: 0.18, ease: EASE }}
/>
</svg>
</Slot>
<span className="truncate">{children}</span>
<Shortcut keys={shortcut} />
</div>
);
}
/** A quiet break between groups: space, not a rule. */
export function DropdownMenuSeparator() {
return <div role="separator" aria-orientation="horizontal" className="h-2" />;
}
export function DropdownMenuSub({ children }: { children: ReactNode }) {
const lvl = use(Level, "DropdownMenuSub");
const id = useId();
const trigger = useRef<HTMLDivElement | null>(null);
return <Sub.Provider value={{ id, open: lvl.sub === id, trigger }}>{children}</Sub.Provider>;
}
export function DropdownMenuSubTrigger({ children, disabled, textValue }: { children: ReactNode; disabled?: boolean; textValue?: string }) {
const lvl = use(Level, "DropdownMenuSubTrigger");
const s = use(Sub, "DropdownMenuSubTrigger");
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const hover = useItemPointer();
useEffect(() => () => {
if (timer.current) clearTimeout(timer.current);
}, []);
return (
<div
ref={s.trigger}
role="menuitem"
aria-haspopup="menu"
aria-expanded={s.open}
tabIndex={-1}
data-cu-item=""
data-text={textValue}
data-state={s.open ? "open" : "closed"}
aria-disabled={disabled || undefined}
onPointerMove={(e) => {
hover(e);
if (e.pointerType !== "mouse" || disabled || s.open || timer.current) return;
timer.current = setTimeout(() => {
timer.current = null;
lvl.setSub(s.id, "pointer");
}, 90);
}}
onPointerLeave={(e) => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
if (e.pointerType !== "mouse") return;
const menu = document.querySelector<HTMLElement>(`[data-cu-sub="${CSS.escape(s.id)}"]`);
if (!menu) return;
const m = menu.getBoundingClientRect();
const right = m.left >= e.clientX;
const edge = right ? m.left : m.right;
const nudge = right ? -4 : 4;
// Safe triangle: from the pointer to the near corners of the submenu.
lvl.grace.current = {
poly: [
{ x: e.clientX + nudge, y: e.clientY },
{ x: edge, y: m.top - 6 },
{ x: edge, y: m.bottom + 6 },
],
until: performance.now() + 400,
};
}}
onFocus={() => {
if (lvl.sub && lvl.sub !== s.id) lvl.setSub(null);
}}
onClick={() => !disabled && lvl.setSub(s.id, "pointer")}
onKeyDown={(e) => {
if (disabled) return;
if (e.key === "ArrowRight" || e.key === "Enter" || e.key === " ") {
e.preventDefault();
e.stopPropagation();
lvl.setSub(s.id, "keyboard");
}
}}
className={cx(ROW, "data-[state=open]:bg-hover")}
>
<Slot />
<span className="truncate">{children}</span>
<span className="ml-auto pl-6 text-ink-3">
<Icon name="chevronRight" size={14} />
</span>
</div>
);
}
export function DropdownMenuSubContent({ children, className }: { children: ReactNode; className?: string }) {
const parent = use(Level, "DropdownMenuSubContent");
const r = use(Root, "DropdownMenuSubContent");
const s = use(Sub, "DropdownMenuSubContent");
const back = () => {
parent.setSub(null);
s.trigger.current?.focus({ preventScroll: true });
};
const level = useMenu(parent.close);
const place = (w: number, h: number): Placement | null => {
const t = s.trigger.current?.getBoundingClientRect();
if (!t) return null;
const vw = window.innerWidth;
const vh = window.innerHeight;
const right = t.right + 4 + w <= vw - 8 || t.left < vw - t.right;
const x = right ? t.right + 4 : t.left - 4 - w;
const y = clamp(t.top - 4, 8, vh - h - 8);
return { x, y, ox: right ? 0 : w, oy: clamp(t.top + t.height / 2 - y, 0, h) };
};
return typeof document === "undefined"
? null
: createPortal(
<AnimatePresence>
{s.open && r.open ? (
<Level.Provider value={level}>
<Panel level={level} subId={s.id} place={place} focusFirst={parent.subBy === "keyboard"} onEscape={back} onLeft={back} className={className}>
{children}
</Panel>
</Level.Provider>
) : null}
</AnimatePresence>,
document.body,
);
}
export function DropdownMenuLabel({ children }: { children: ReactNode }) {
return <div className="px-2 pb-1 pt-1.5 text-[12.5px] text-ink-3">{children}</div>;
}Usage
import {
DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem,
DropdownMenuCheckboxItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,
} from "@/components/ui/dropdown-menu"
<DropdownMenu>
<DropdownMenuTrigger>Options</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem shortcut="⌘R" onSelect={rerun}>Rerun</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Move to project</DropdownMenuSubTrigger>
<DropdownMenuSubContent>…</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuCheckboxItem checked={notify} onCheckedChange={setNotify}>Notify me</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| DropdownMenu open | boolean | Controlled open state. Pair with onOpenChange. | |
| DropdownMenuContent align | "start" | "end" | "start" | Which edge of the trigger the menu lines up with. Flips above when there is no room below. |
| DropdownMenuItem onSelect | () => void | Runs on click, Enter or Space, then the menu closes. | |
| DropdownMenuItem shortcut | string | Shown at the right in tabular figures. | |
| DropdownMenuItem tone | "default" | "danger" | "default" | Danger for destructive actions. |
| DropdownMenuItem textValue | string | Typeahead text when children are not plain text. | |
| DropdownMenuCheckboxItem checked | boolean | Toggles without closing the menu. | |
| DropdownMenuSub | component | Wraps a SubTrigger and SubContent. Opens on hover, Enter or the right arrow. |
Keyboard
- ↑ ↓
- Move
- Home / End
- First or last item
- Enter / Space
- Select
- → / ←
- Open or close a submenu
- A to Z
- Jump to the item that starts with what you type
- Esc
- Close and return focus
Accessibility
- role=menu with menuitem and menuitemcheckbox, aria-checked and aria-expanded on submenu triggers.
- Roving focus: hovering an item focuses it, so pointer and keyboard share one highlight.
- Opening from the keyboard focuses the first item; closing returns focus to the trigger.
- Tab closes the menu instead of trapping focus.