---
title: Context Menu
description: A right-click menu that pops open from the cursor.
category: Navigation
tier: free
url: https://ui.dimaac.com/components/context-menu
registry: https://ui.dimaac.com/r/context-menu.json
---

# Context Menu

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.

## Install

With the shadcn CLI:

```bash
npx shadcn@latest add https://ui.dimaac.com/r/context-menu.json
pnpm dlx shadcn@latest add https://ui.dimaac.com/r/context-menu.json
bunx --bun shadcn@latest add https://ui.dimaac.com/r/context-menu.json
```

With the `@dimaac` namespace in components.json: `npx shadcn@latest add @dimaac/context-menu`

Dependencies:

```bash
pnpm add gsap @gsap/react
npm install gsap @gsap/react
```

By hand:

1. Install the packages it uses: gsap, @gsap/react.
2. Copy the component file below into components/dimaac/context-menu.tsx.
3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
4. Import it with import { ContextMenu } from "@/components/dimaac/context-menu". Give its parent a size: it fills it.

## Usage

```tsx
import { ContextMenu } from "@/components/dimaac/context-menu";

<ContextMenu children={children} items={items} />
```

## 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. |

## Credits

- Photo: West Kast, Lummi (https://www.lummi.ai/photo/futuristic-gold-profile-jnio5), Lummi License
- Photo: Bernardo Lickfold, Lummi (https://www.lummi.ai/photo/portrait-through-orange-frame-kld5i), Lummi License
- Photo: Semihan Dosunmu, Lummi (https://www.lummi.ai/photo/avant-garde-fashion-portrait-rjvlr), Lummi License
- Photo: Semihan Dosunmu, Lummi (https://www.lummi.ai/photo/avant-garde-fashion-pose-1yqoo), Lummi License

## Source

### context-menu.tsx → `components/dimaac/context-menu.tsx`

```tsx
"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}
    </>
  );
}
```

### demo.tsx (the demo on the page, not installed)

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { ArrowDownUp, ClipboardPaste, Copy, Download, Eye, FolderPlus, Grid3x3, Heart, RefreshCw, Share2, Trash2 } from "lucide-react";
import { ContextMenu, type ContextMenuItem, type ContextMenuProps } from "@/components/dimaac/context-menu";

// A small photo board. Right-click a photo for its menu, right-click the
// board for the board's menu. Photos: Lummi (Lummi License).

type Look = { id: string; name: string; note: string; image: string; alt: string };

const looks: Look[] = [
  { id: "gold", name: "Gold visor", note: "No. 01", image: "https://ui.dimaac.com/media/fashion/gold-visor-4x5.jpg", alt: "Futuristic profile with a gold headpiece, amber sunglasses and red lips against a yellow background" },
  { id: "ring", name: "Orange ring", note: "No. 02", image: "https://ui.dimaac.com/media/fashion/orange-ring-4x5.jpg", alt: "A young man in a knit bucket hat framed through an orange circle" },
  { id: "corset", name: "Woven corset", note: "No. 03", image: "https://ui.dimaac.com/media/fashion/woven-corset-4x5.jpg", alt: "A model in a woven corset and pleated hat in natural tones" },
  { id: "knit", name: "Chunky knit", note: "No. 04", image: "https://ui.dimaac.com/media/fashion/chunky-knit-4x5.jpg", alt: "A model in a chunky knit sweater, ruffled pants and coral boots against a warm backdrop" },
];

export default function Demo(props: Partial<Omit<ContextMenuProps, "children" | "items">>) {
  const [favourites, setFavourites] = useState<string[]>(["ring"]);
  const [openId, setOpenId] = useState<string | null>(null);
  const [message, setMessage] = useState("");
  const timer = useRef<number | null>(null);

  const say = (text: string) => {
    setMessage(text);
    if (timer.current !== null) window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setMessage(""), 2200);
  };
  useEffect(
    () => () => {
      if (timer.current !== null) window.clearTimeout(timer.current);
    },
    [],
  );

  const itemsFor = (look: Look): ContextMenuItem[] => {
    const loved = favourites.includes(look.id);
    return [
      { id: "open", label: "Open look", icon: <Eye size={16} />, shortcut: "↵", onSelect: () => say(`Opened ${look.name}`) },
      {
        id: "favourite",
        label: loved ? "Remove from favourites" : "Add to favourites",
        icon: <Heart size={16} fill={loved ? "currentColor" : "none"} />,
        shortcut: "F",
        separator: true,
        onSelect: () => {
          setFavourites((list) => (loved ? list.filter((id) => id !== look.id) : [...list, look.id]));
          say(loved ? `${look.name} left your favourites` : `${look.name} saved to favourites`);
        },
      },
      { id: "duplicate", label: "Duplicate", icon: <Copy size={16} />, shortcut: "⌘ D", onSelect: () => say(`Duplicated ${look.name}`) },
      { id: "download", label: "Download image", icon: <Download size={16} />, shortcut: "⌘ S", onSelect: () => say(`Downloading ${look.name}…`) },
      { id: "share", label: "Share…", icon: <Share2 size={16} />, separator: true, onSelect: () => say(`Link to ${look.name} copied`) },
      { id: "archive", label: "Archive (soon)", icon: <FolderPlus size={16} />, disabled: true },
      { id: "remove", label: "Remove look", icon: <Trash2 size={16} />, shortcut: "⌫", danger: true, onSelect: () => say(`Removed ${look.name} (just kidding)`) },
    ];
  };

  const boardItems: ContextMenuItem[] = [
    { id: "new", label: "New board", icon: <FolderPlus size={16} />, shortcut: "⌘ N", onSelect: () => say("New board created") },
    { id: "paste", label: "Paste photo", icon: <ClipboardPaste size={16} />, shortcut: "⌘ V", separator: true, onSelect: () => say("Nothing on the clipboard") },
    { id: "sort", label: "Sort by date", icon: <ArrowDownUp size={16} />, onSelect: () => say("Sorted by date") },
    { id: "grid", label: "Show grid", icon: <Grid3x3 size={16} />, onSelect: () => say("Grid shown") },
    { id: "refresh", label: "Refresh", icon: <RefreshCw size={16} />, shortcut: "⌘ R", onSelect: () => say("Board refreshed") },
  ];

  return (
    <ContextMenu {...props} items={boardItems} className="relative h-full w-full overflow-hidden bg-[#f3f0eb] text-[#1c1917] dark:bg-[#0f0b0b] dark:text-[#e8ddd4]">
      <div className="flex h-full w-full flex-col px-5 py-6 sm:px-8 sm:py-8">
        <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-5 sm:gap-8">
          <h1 className="text-center text-[clamp(30px,5.4vw,72px)] leading-[0.95] font-medium tracking-[-0.04em] opacity-90">
            Pick a look,
            <br />
            then <span className="pointer-coarse:hidden">right-click it</span>
            <span className="hidden pointer-coarse:inline">hold it down</span>
          </h1>

          <div className="grid w-full max-w-[1020px] grid-cols-2 gap-3 sm:gap-5 md:grid-cols-4">
            {looks.map((look) => (
              <ContextMenu key={look.id} {...props} items={itemsFor(look)} onOpenChange={(open) => setOpenId((current) => (open ? look.id : current === look.id ? null : current))}>
                <div
                  tabIndex={0}
                  role="group"
                  aria-label={`${look.name}. Press the Menu key or Shift and F10 for actions.`}
                  className={`group relative aspect-[4/5] cursor-context-menu overflow-hidden rounded-2xl bg-black/10 shadow-[0_18px_40px_-20px_rgba(30,20,10,0.45)] outline-none transition-[box-shadow,transform] duration-300 focus-visible:ring-2 focus-visible:ring-teal-600 focus-visible:ring-offset-2 focus-visible:ring-offset-[#f3f0eb] motion-reduce:transition-none dark:focus-visible:ring-teal-300 dark:focus-visible:ring-offset-[#0f0b0b] ${
                    openId === look.id ? "-translate-y-1 ring-2 ring-teal-600 ring-offset-2 ring-offset-[#f3f0eb] dark:ring-teal-300 dark:ring-offset-[#0f0b0b]" : ""
                  }`}
                >
                  <img src={look.image} alt={look.alt} draggable={false} className="absolute inset-0 h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.04] motion-reduce:transition-none" />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent" />
                  {favourites.includes(look.id) ? (
                    <span className="absolute top-2.5 left-2.5 flex h-6 w-6 items-center justify-center rounded-full bg-white/90 text-red-500" aria-label="Favourite">
                      <Heart size={13} fill="currentColor" />
                    </span>
                  ) : null}
                  <div className="absolute inset-x-3 bottom-3 text-white">
                    <p className="text-[15px] font-medium tracking-[-0.01em] sm:text-[17px]">{look.name}</p>
                    <p className="font-mono text-[10px] tracking-wide uppercase opacity-70">{look.note}</p>
                  </div>
                </div>
              </ContextMenu>
            ))}
          </div>
        </div>

        <footer className="text-center font-mono text-[11px] tracking-wide uppercase opacity-60">
          <span className="pointer-coarse:hidden">The board has a menu too</span>
          <span className="hidden pointer-coarse:inline">The board has a menu too, hold it down</span>
        </footer>
      </div>

      <div
        role="status"
        aria-live="polite"
        className={`pointer-events-none absolute bottom-14 left-1/2 -translate-x-1/2 rounded-full bg-[#1c1917] px-4 py-2 text-[13px] whitespace-nowrap text-[#f3f0eb] shadow-lg transition-[opacity,transform] duration-300 motion-reduce:transition-none dark:bg-[#e8ddd4] dark:text-[#0f0b0b] ${
          message ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0"
        }`}
      >
        {message || " "}
      </div>
    </ContextMenu>
  );
}
```

## Agent prompt

```text
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.txt
```
