Context Menu
A right-click menu that pops open from the cursor.
Customize
<ContextMenu children={children} items={items} />Changes show live and stay in the address, so a link keeps them.
Code
"use client";
import { useEffect, useRef, useState, type RefObject, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";
// A right-click menu that opens where the cursor is. Wrap anything in it and give it a list of items.
// It opens with a quick pop from the cursor and a stagger on the rows, one soft highlight glides
// between the rows, and it is a real menu for keyboards and screen readers (arrow keys, Home and End,
// type a letter to jump, Enter to choose, Escape to close and give focus back). On touch screens a
// long press opens it. The document listeners exist only while the menu is open.
export type ContextMenuItem = {
/** A unique id for the row. */
id: string;
/** The text of the row. */
label: string;
/** An icon shown before the label, e.g. a lucide-react icon: <Heart size={16} />. */
icon?: ReactNode;
/** A shortcut hint shown on the right, e.g. "⌘ D". It is only a label: the shortcut itself is yours to handle. */
shortcut?: string;
/** Called when the row is chosen. */
onSelect?: (item: ContextMenuItem) => void;
/** Draw a divider line after this row. */
separator?: boolean;
/** Show the row greyed out and skip it. */
disabled?: boolean;
/** Colour the row red, for things like Delete. */
danger?: boolean;
};
export type ContextMenuProps = {
/** What the menu opens on. Right-click (or long-press on touch) anywhere inside it. */
children: ReactNode;
/** The rows of the menu. */
items: ContextMenuItem[];
/** Called with the row that was chosen (after the row's own onSelect). */
onItemSelect?: (item: ContextMenuItem) => void;
/** Called when the menu opens (true) and starts closing (false). */
onOpenChange?: (open: boolean) => void;
/** Width of the menu, in pixels. */
width?: number;
/** How long the menu takes to pop open, in seconds. */
openDuration?: number;
/** Delay between one row appearing and the next, in seconds. */
stagger?: number;
/** How small the menu starts, from 0.5 to 1. It grows from the cursor. */
startScale?: number;
/** The GSAP ease of the pop, e.g. "power3.out" or "back.out(1.7)". */
ease?: string;
/** The colour of the highlight and the focus. */
accent?: string;
/** A frosted-glass menu (blurred, see-through) instead of a solid one. */
glass?: boolean;
/** Turn the custom menu off, so the browser's own menu shows. */
disabled?: boolean;
/** How long a finger must stay down on touch screens to open the menu, in milliseconds. */
longPress?: number;
/** Extra classes for the box around the children. */
className?: string;
/** Extra classes for the menu itself, e.g. a different radius. */
menuClassName?: string;
};
type Opening = { x: number; y: number; key: number; keyboard: boolean };
type MenuSettings = Required<Pick<ContextMenuProps, "width" | "openDuration" | "stagger" | "startScale" | "ease" | "accent" | "glass" | "menuClassName">>;
// Menus can sit inside each other (a card inside a board). The innermost one opens, and marks the
// event here so the ones around it leave it alone.
const claimed = new WeakSet<Event>();
export function ContextMenu({
children,
items,
onItemSelect,
onOpenChange,
width = 232,
openDuration = 0.26,
stagger = 0.022,
startScale = 0.9,
ease = "power3.out",
accent = "#0f766e",
glass = true,
disabled = false,
longPress = 480,
className = "",
menuClassName = "",
}: ContextMenuProps) {
const boxRef = useRef<HTMLDivElement>(null);
const [opening, setOpening] = useState<Opening | null>(null);
const [closing, setClosing] = useState(false);
const counter = useRef(0);
const lastOpenAt = useRef(0);
const lastLongPressAt = useRef(0);
const pressTimer = useRef<number | null>(null);
const pressStart = useRef({ x: 0, y: 0 });
// The callback can change on every render: keep the newest one without re-running effects
const onOpenChangeRef = useRef(onOpenChange);
onOpenChangeRef.current = onOpenChange;
const reported = useRef(false);
const open = opening !== null && !closing;
useEffect(() => {
if (reported.current === open) return;
reported.current = open;
onOpenChangeRef.current?.(open);
}, [open]);
const openAt = (x: number, y: number, keyboard: boolean) => {
counter.current += 1;
lastOpenAt.current = performance.now();
setClosing(false);
// A new key builds a fresh menu, so opening it somewhere else plays the pop again
setOpening({ x, y, key: counter.current, keyboard });
};
const clearPress = () => {
if (pressTimer.current !== null) window.clearTimeout(pressTimer.current);
pressTimer.current = null;
};
useEffect(() => clearPress, []);
const onContextMenu = (event: ReactMouseEvent) => {
if (disabled || items.length === 0 || claimed.has(event.nativeEvent)) return;
claimed.add(event.nativeEvent);
event.preventDefault();
// A long press on Android fires this a moment after our own timer already opened the menu
if (performance.now() - lastOpenAt.current < 900) return;
openAt(event.clientX, event.clientY, false);
};
// Touch screens: a long press opens the menu (iOS never sends a contextmenu event)
const onPointerDown = (event: ReactPointerEvent) => {
if (disabled || items.length === 0 || event.pointerType !== "touch" || !event.isPrimary || claimed.has(event.nativeEvent)) return;
claimed.add(event.nativeEvent);
clearPress();
const { clientX, clientY } = event;
pressStart.current = { x: clientX, y: clientY };
pressTimer.current = window.setTimeout(() => {
pressTimer.current = null;
lastLongPressAt.current = performance.now();
openAt(clientX, clientY, false);
}, longPress);
};
const onPointerMove = (event: ReactPointerEvent) => {
// A finger that moves is scrolling or dragging, not pressing
const start = pressStart.current;
if (pressTimer.current !== null && Math.hypot(event.clientX - start.x, event.clientY - start.y) > 10) clearPress();
};
// The tap that ends a long press shouldn't also click what is under the finger
const swallowClick = (event: ReactMouseEvent) => {
if (performance.now() - lastLongPressAt.current < 600) {
event.preventDefault();
event.stopPropagation();
}
};
// The keyboard way in: the Menu key, or Shift + F10, opens it beside the focused element
const onKeyDown = (event: ReactKeyboardEvent) => {
if (disabled || items.length === 0 || claimed.has(event.nativeEvent)) return;
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
claimed.add(event.nativeEvent);
event.preventDefault();
const box = boxRef.current;
const focused = document.activeElement;
const target = focused instanceof HTMLElement && box?.contains(focused) ? focused : box;
if (!target) return;
const rect = target.getBoundingClientRect();
openAt(rect.left + Math.min(rect.width / 2, 48), rect.top + Math.min(rect.height / 2, 32), true);
};
return (
<div
ref={boxRef}
className={className}
onContextMenu={onContextMenu}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={clearPress}
onPointerCancel={clearPress}
onClickCapture={swallowClick}
onKeyDown={onKeyDown}
style={{ WebkitTouchCallout: "none" }}
>
{children}
{opening && !disabled
? createPortal(
<Menu
key={opening.key}
opening={opening}
items={items}
settings={{ width, openDuration, stagger, startScale, ease, accent, glass, menuClassName }}
onItemSelect={onItemSelect}
onClosing={() => setClosing(true)}
onDone={() => setOpening((current) => (current && current.key === opening.key ? null : current))}
fallbackFocus={boxRef}
/>,
document.body,
)
: null}
</div>
);
}
type MenuProps = {
opening: Opening;
items: ContextMenuItem[];
settings: MenuSettings;
onItemSelect?: (item: ContextMenuItem) => void;
onClosing: () => void;
onDone: () => void;
fallbackFocus: RefObject<HTMLElement | null>;
};
// The menu itself exists only while it is open, so everything it listens to goes away with it.
function Menu({ opening, items, settings, onItemSelect, onClosing, onDone, fallbackFocus }: MenuProps) {
const menuRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const pillRef = useRef<HTMLDivElement>(null);
const [leaving, setLeaving] = useState(false);
const leavingRef = useRef(false);
const exitRef = useRef<() => void>(() => undefined);
const previousFocus = useRef<Element | null>(null);
const typed = useRef({ text: "", timer: 0 });
// Read when the menu opens or closes, so a changing control never rebuilds an open menu
const settingsRef = useRef(settings);
settingsRef.current = settings;
const onDoneRef = useRef(onDone);
onDoneRef.current = onDone;
// Where the menu goes, how it pops open, and the highlight that glides between rows
useGSAP(
(_context, contextSafe) => {
const menu = menuRef.current;
const list = listRef.current;
const pill = pillRef.current;
if (!menu || !list || !pill || !contextSafe) return;
// Remember where focus was, once (React StrictMode runs this twice, and by then the menu has focus)
if (previousFocus.current === null) previousFocus.current = document.activeElement;
// Put the menu at the cursor, flipped or pushed in when it would leave the screen
const margin = 8;
const w = menu.offsetWidth;
const h = menu.offsetHeight;
const maxLeft = Math.max(margin, window.innerWidth - w - margin);
const maxTop = Math.max(margin, window.innerHeight - h - margin);
const left = Math.min(Math.max(opening.x + w > window.innerWidth - margin ? opening.x - w : opening.x, margin), maxLeft);
const top = Math.min(Math.max(opening.y + h > window.innerHeight - margin ? opening.y - h : opening.y, margin), maxTop);
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
// The pop grows from the cursor, wherever the menu ended up
const originX = Math.min(Math.max(opening.x - left, 0), w);
const originY = Math.min(Math.max(opening.y - top, 0), h);
gsap.set(menu, { transformOrigin: `${originX}px ${originY}px` });
const rows = Array.from(list.querySelectorAll<HTMLElement>('[role="menuitem"]'));
const dividers = Array.from(list.querySelectorAll<HTMLElement>('[role="separator"]'));
const mm = gsap.matchMedia();
let glideY: ((value: number) => gsap.core.Tween) | null = null;
let glideH: ((value: number) => gsap.core.Tween) | null = null;
let animated = true;
mm.add(
{ reduce: "(prefers-reduced-motion: reduce)", motion: "(prefers-reduced-motion: no-preference)" },
(context) => {
animated = !context.conditions?.reduce;
const { openDuration, stagger, startScale, ease } = settingsRef.current;
if (!animated) {
// No movement: the menu is simply there
gsap.set([menu, ...rows, ...dividers], { opacity: 1, clearProps: "transform" });
return;
}
gsap.set(pill, { opacity: 0 });
glideY = gsap.quickTo(pill, "y", { duration: 0.22, ease: "power3.out" });
glideH = gsap.quickTo(pill, "height", { duration: 0.22, ease: "power3.out" });
gsap
.timeline({ defaults: { overwrite: "auto" } })
.fromTo(menu, { opacity: 0, scale: startScale, y: -6 }, { opacity: 1, scale: 1, y: 0, duration: openDuration, ease, clearProps: "transform" }, 0)
.fromTo([...rows, ...dividers], { opacity: 0, y: 6 }, { opacity: 1, y: 0, duration: openDuration * 0.9, ease: "power2.out", stagger, clearProps: "transform" }, 0.04);
},
);
// The highlight follows whichever row has focus (the mouse moves focus too)
let lit = false;
const moveHighlight = contextSafe((row: HTMLElement) => {
if (animated && glideY && glideH) {
if (!lit) gsap.set(pill, { y: row.offsetTop, height: row.offsetHeight });
else {
glideY(row.offsetTop);
glideH(row.offsetHeight);
}
gsap.to(pill, { opacity: 1, duration: 0.15, overwrite: "auto" });
} else {
gsap.set(pill, { y: row.offsetTop, height: row.offsetHeight, opacity: 1 });
}
lit = true;
});
const onFocusIn = (event: FocusEvent) => {
const row = (event.target as HTMLElement).closest<HTMLElement>('[role="menuitem"]');
if (row) moveHighlight(row);
};
const onFocusOut = contextSafe((event: FocusEvent) => {
if ((event.relatedTarget as HTMLElement | null)?.closest?.('[role="menuitem"]')) return;
lit = false;
gsap.to(pill, { opacity: 0, duration: 0.15, overwrite: "auto" });
});
list.addEventListener("focusin", onFocusIn);
list.addEventListener("focusout", onFocusOut);
// Closing plays a short fade, then the parent removes the menu
exitRef.current = contextSafe(() => {
list.removeEventListener("focusin", onFocusIn);
list.removeEventListener("focusout", onFocusOut);
if (!animated) {
onDoneRef.current();
return;
}
gsap.to(menu, { opacity: 0, scale: 0.96, duration: 0.14, ease: "power2.in", overwrite: true, onComplete: () => onDoneRef.current() });
});
// Keyboard-opened menus start on the first row, mouse-opened ones on the menu itself
const first = rows.find((row) => row.getAttribute("aria-disabled") !== "true");
(opening.keyboard && first ? first : menu).focus({ preventScroll: true });
return () => {
list.removeEventListener("focusin", onFocusIn);
list.removeEventListener("focusout", onFocusOut);
mm.revert();
};
},
{ scope: menuRef, dependencies: [] },
);
// Start closing. Keyboard and row choices give focus back to where it was.
const close = (restoreFocus: boolean) => {
if (leavingRef.current) return;
leavingRef.current = true;
setLeaving(true);
onClosing();
if (restoreFocus) {
const back = previousFocus.current;
const hadFocus = back instanceof HTMLElement && back !== document.body && back.isConnected;
// Opened with the keyboard from something unfocusable: land on the box around it
const target = hadFocus ? back : opening.keyboard ? fallbackFocus.current : null;
if (target) {
if (!target.hasAttribute("tabindex") && !(target instanceof HTMLButtonElement || target instanceof HTMLAnchorElement || target instanceof HTMLInputElement)) target.tabIndex = -1;
target.focus({ preventScroll: true });
}
}
exitRef.current();
};
// Listeners that exist only while the menu is open: a press elsewhere, scrolling, a resized window
useEffect(() => {
if (leaving) return;
const menu = menuRef.current;
const onPressOutside = (event: PointerEvent) => {
if (menu && event.target instanceof Node && menu.contains(event.target)) return;
close(false);
};
const onAnyChange = () => close(false);
document.addEventListener("pointerdown", onPressOutside, true);
window.addEventListener("scroll", onAnyChange, { capture: true, passive: true });
window.addEventListener("resize", onAnyChange);
window.addEventListener("blur", onAnyChange);
return () => {
document.removeEventListener("pointerdown", onPressOutside, true);
window.removeEventListener("scroll", onAnyChange, { capture: true });
window.removeEventListener("resize", onAnyChange);
window.removeEventListener("blur", onAnyChange);
};
// close only reads refs and stable callbacks
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [leaving]);
useEffect(() => () => window.clearTimeout(typed.current.timer), []);
const choose = (item: ContextMenuItem) => {
if (item.disabled || leavingRef.current) return;
close(true);
item.onSelect?.(item);
onItemSelect?.(item);
};
const rowElements = () => Array.from(listRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]:not([aria-disabled="true"])') ?? []);
const onMenuKeyDown = (event: ReactKeyboardEvent) => {
const rows = rowElements();
const index = rows.indexOf(document.activeElement as HTMLElement);
const go = (next: number) => {
event.preventDefault();
rows[(next + rows.length) % rows.length]?.focus({ preventScroll: true });
};
if (event.key === "ArrowDown") go(index + 1);
else if (event.key === "ArrowUp") go(index < 0 ? rows.length - 1 : index - 1);
else if (event.key === "Home") go(0);
else if (event.key === "End") go(rows.length - 1);
else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close(true);
} else if (event.key === "Tab") {
event.preventDefault();
close(true);
} else if (event.key.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey && event.key !== " ") {
// Type a letter (or a few quickly) to jump to the row that starts with it
window.clearTimeout(typed.current.timer);
typed.current.text += event.key.toLowerCase();
typed.current.timer = window.setTimeout(() => (typed.current.text = ""), 600);
const ordered = [...rows.slice(index + 1), ...rows.slice(0, index + 1)];
const match = ordered.find((row) => (row.textContent ?? "").trim().toLowerCase().startsWith(typed.current.text));
if (match) {
event.preventDefault();
match.focus({ preventScroll: true });
}
}
};
const { width, accent, glass, menuClassName } = settings;
return (
<div
ref={menuRef}
role="menu"
aria-orientation="vertical"
tabIndex={-1}
onKeyDown={onMenuKeyDown}
onContextMenu={(event) => event.preventDefault()}
className={`fixed z-[2147483000] max-w-[calc(100vw-16px)] rounded-2xl border p-1.5 text-[13.5px] leading-none outline-none select-none ${
glass
? "border-black/10 bg-white/82 text-stone-900 shadow-[0_24px_60px_-18px_rgba(30,20,10,0.35),0_2px_6px_rgba(30,20,10,0.08)] backdrop-blur-2xl backdrop-saturate-150 dark:border-white/12 dark:bg-stone-900/80 dark:text-stone-100 dark:shadow-[0_28px_70px_-16px_rgba(0,0,0,0.75),0_2px_8px_rgba(0,0,0,0.4)]"
: "border-stone-200 bg-white text-stone-900 shadow-[0_24px_60px_-18px_rgba(30,20,10,0.35),0_2px_6px_rgba(30,20,10,0.08)] dark:border-stone-700 dark:bg-stone-900 dark:text-stone-100 dark:shadow-[0_28px_70px_-16px_rgba(0,0,0,0.75)]"
} ${menuClassName}`}
style={{ left: 0, top: 0, width, willChange: "transform, opacity", ["--menu-accent" as string]: accent }}
>
<div ref={listRef} className="relative flex flex-col">
{/* The one highlight that glides between rows */}
<div
ref={pillRef}
aria-hidden="true"
className="pointer-events-none absolute inset-x-0 top-0 rounded-[10px] opacity-0"
style={{ background: "color-mix(in oklab, var(--menu-accent) 16%, transparent)", boxShadow: "inset 0 0 0 1px color-mix(in oklab, var(--menu-accent) 28%, transparent)" }}
/>
{items.map((item) => (
<MenuRow key={item.id} item={item} onChoose={choose} />
))}
</div>
</div>
);
}
function MenuRow({ item, onChoose }: { item: ContextMenuItem; onChoose: (item: ContextMenuItem) => void }) {
return (
<>
<button
type="button"
role="menuitem"
tabIndex={-1}
aria-disabled={item.disabled ? "true" : undefined}
onClick={() => onChoose(item)}
onPointerEnter={(event) => {
if (event.pointerType !== "touch" && !item.disabled) event.currentTarget.focus({ preventScroll: true });
}}
onPointerLeave={(event) => {
// Moving off the rows lets the highlight fade: focus goes back to the menu
if (event.pointerType !== "touch" && document.activeElement === event.currentTarget) (event.currentTarget.closest('[role="menu"]') as HTMLElement | null)?.focus({ preventScroll: true });
}}
className={`relative flex w-full items-center gap-2.5 rounded-[10px] px-2.5 py-2 text-left text-[13.5px] leading-5 outline-none pointer-coarse:py-2.5 ${
item.disabled ? "cursor-not-allowed opacity-40" : item.danger ? "cursor-pointer text-red-600 dark:text-red-400" : "cursor-pointer"
}`}
>
{item.icon ? (
<span aria-hidden="true" className="flex h-4 w-4 shrink-0 items-center justify-center opacity-70">
{item.icon}
</span>
) : null}
<span className="flex-1 truncate">{item.label}</span>
{item.shortcut ? <span className="ml-3 shrink-0 font-mono text-[11px] tracking-wide opacity-45">{item.shortcut}</span> : null}
</button>
{item.separator ? <div role="separator" className="mx-2 my-1 h-px bg-black/10 dark:bg-white/12" /> : null}
</>
);
}
The component. Installs to components/dimaac/context-menu.tsx.
Install
With the shadcn CLI
npx shadcn@latest add https://ui.dimaac.com/r/context-menu.jsonIt adds components/dimaac/context-menu.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/context-menu.
By hand
npm install gsap @gsap/react- Install the packages it uses: gsap, @gsap/react.
- Copy the component file below into components/dimaac/context-menu.tsx.
- It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
- Import it with import { ContextMenu } from "@/components/dimaac/context-menu". Give its parent a size: it fills it.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
children (required) | ReactNode | - | What the menu opens on. Right-click (or long-press on touch) anywhere inside it. |
items (required) | ContextMenuItem[] | - | The rows of the menu. |
onItemSelect | (item: ContextMenuItem) => void | - | Called with the row that was chosen (after the row's own onSelect). |
onOpenChange | (open: boolean) => void | - | Called when the menu opens (true) and starts closing (false). |
width | number | 232 | Width of the menu, in pixels. |
openDuration | number | 0.26 | How long the menu takes to pop open, in seconds. |
stagger | number | 0.022 | Delay between one row appearing and the next, in seconds. |
startScale | number | 0.9 | How small the menu starts, from 0.5 to 1. It grows from the cursor. |
ease | string | "power3.out" | The GSAP ease of the pop, e.g. "power3.out" or "back.out(1.7)". |
accent | string | "#0f766e" | The colour of the highlight and the focus. |
glass | boolean | true | A frosted-glass menu (blurred, see-through) instead of a solid one. |
disabled | boolean | false | Turn the custom menu off, so the browser's own menu shows. |
longPress | number | 480 | How long a finger must stay down on touch screens to open the menu, in milliseconds. |
className | string | "" | Extra classes for the box around the children. |
menuClassName | string | "" | Extra classes for the menu itself, e.g. a different radius. |
Use with AI
Agent prompt
Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.
Add the Context Menu component (<ContextMenu />) from DiMaac UI to this project.
Docs: https://ui.dimaac.com/components/context-menu
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/context-menu.json
Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/context-menu.json
Then use it like this:
import { ContextMenu } from "@/components/dimaac/context-menu";
<ContextMenu children={children} items={items} />
If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/context-menu.tsx and install gsap, @gsap/react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size: it fills it. Keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txtFiles agents read
- llms.txt
- Every component and how to install it
- context-menu.md
- This page as Markdown: install, props and the full source
- context-menu.json
- The shadcn registry item
About
Wrap anything in it, hand it a list of items, and right-click: a menu pops open from the cursor with a quick scale and a stagger on the rows, flips or slides in so it never leaves the screen, and one soft highlight glides between the rows. It is a real menu for keyboards and screen readers (role=menu and menuitem, arrow keys, Home and End, type a letter to jump, Enter to choose, Escape to close with focus returned, and the Menu key or Shift + F10 to open it), a long press opens it on touch screens, menus can be nested (the innermost one opens), and it listens to the document only while it is open. It follows prefers-reduced-motion by appearing without movement. Ported from the first DiMaac UI and rebuilt: the always-on scroll listeners and the missing keyboard support are gone.
- Installs to
components/dimaac/context-menu.tsx- Uses
- gsap, @gsap/react
- Tags
- menu, right-click, gsap, keyboard, a11y
Photo by West Kast, Bernardo Lickfold, Semihan Dosunmu and Semihan Dosunmu on Lummi (Lummi License).