{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "context-menu",
  "title": "Context Menu",
  "description": "A right-click context menu with checkbox and radio items, nested submenus, viewport edge clamping and full keyboard navigation.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/context-menu/context-menu.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\n// useLayoutEffect logs a warning when it runs server-side (no DOM to\n// measure before paint there); fall back to useEffect there and only\n// take the synchronous-before-paint measurement in the browser.\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? React.useLayoutEffect : React.useEffect;\n\nexport type ContextMenuItemKind = \"item\" | \"checkbox\" | \"radio\" | \"separator\" | \"label\" | \"submenu\";\nexport type ContextMenuSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface ContextMenuItem {\n  id: string;\n  kind: ContextMenuItemKind;\n  label?: string;\n  shortcut?: string;\n  checked?: boolean;\n  disabled?: boolean;\n  danger?: boolean;\n  items?: ContextMenuItem[];\n}\n\nexport interface ContextMenuProps {\n  items: ContextMenuItem[];\n  children: React.ReactNode;\n  onSelect?: (item: ContextMenuItem) => void;\n  disabled?: boolean;\n  size?: ContextMenuSize;\n  width?: number;\n  theme?: \"dark\" | \"light\";\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", faint: \"rgba(245,244,241,0.28)\", panelBg: \"#0E0E0E\", panelBorder: \"rgba(255,255,255,0.1)\", hover: \"rgba(255,255,255,0.08)\", separator: \"rgba(255,255,255,0.08)\", kbdBg: \"rgba(255,255,255,0.06)\", kbdBorder: \"rgba(255,255,255,0.1)\", danger: \"#FF7A6B\", check: \"#F5F4F1\", checkFg: \"#0A0A0A\", shadow: \"0 24px 60px rgba(0,0,0,0.55)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", faint: \"rgba(10,10,10,0.28)\", panelBg: \"#FFFFFF\", panelBorder: \"rgba(10,10,10,0.12)\", hover: \"rgba(10,10,10,0.06)\", separator: \"rgba(10,10,10,0.08)\", kbdBg: \"rgba(10,10,10,0.04)\", kbdBorder: \"rgba(10,10,10,0.1)\", danger: \"#E5484D\", check: \"#0A0A0A\", checkFg: \"#FFFFFF\", shadow: \"0 20px 50px rgba(0,0,0,0.18)\" },\n};\n\nconst SIZES: Record<ContextMenuSize, { font: number; rowH: number; radius: number }> = {\n  sm: { font: 13, rowH: 30, radius: 9 },\n  md: { font: 14, rowH: 33, radius: 10 },\n  lg: { font: 15, rowH: 36, radius: 11 },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\ntype Size = (typeof SIZES)[\"md\"];\n\nfunction isFocusable(item: ContextMenuItem) {\n  return item.kind !== \"separator\" && item.kind !== \"label\" && !item.disabled;\n}\n\nfunction Kbd({ children, p }: { children: string; p: Palette }) {\n  return (\n    <span className=\"inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md font-medium\" style={{ height: 18, padding: \"0 5px\", background: p.kbdBg, border: `1px solid ${p.kbdBorder}`, color: p.muted, fontSize: 10.5 }}>\n      {children}\n    </span>\n  );\n}\n\nfunction CheckGlyph({ p }: { p: Palette }) {\n  return (\n    <svg width=\"9\" height=\"9\" viewBox=\"0 0 12 12\" fill=\"none\" aria-hidden=\"true\">\n      <path d=\"M2.5 6.3L4.8 8.6L9.5 3.5\" stroke={p.checkFg} strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\ninterface RowProps {\n  id: string;\n  item: ContextMenuItem;\n  s: Size;\n  p: Palette;\n  focused: boolean;\n  submenuOpen: boolean;\n  onHover: () => void;\n  onActivate: () => void;\n  setRef: (el: HTMLDivElement | null) => void;\n}\n\nfunction Row({ id, item, s, p, focused, submenuOpen, onHover, onActivate, setRef }: RowProps) {\n  if (item.kind === \"separator\") return <div role=\"separator\" style={{ margin: \"5px 8px\", height: 1, background: p.separator }} />;\n  if (item.kind === \"label\")\n    return (\n      <div className=\"font-semibold uppercase\" style={{ padding: \"7px 12px 4px\", color: p.faint, fontSize: 10.5, letterSpacing: \"0.07em\" }}>\n        {item.label}\n      </div>\n    );\n\n  const isCheck = item.kind === \"checkbox\" || item.kind === \"radio\";\n  return (\n    <div\n      ref={setRef}\n      id={id}\n      role={item.kind === \"checkbox\" ? \"menuitemcheckbox\" : item.kind === \"radio\" ? \"menuitemradio\" : \"menuitem\"}\n      aria-checked={isCheck ? Boolean(item.checked) : undefined}\n      aria-haspopup={item.kind === \"submenu\" ? \"menu\" : undefined}\n      aria-expanded={item.kind === \"submenu\" ? submenuOpen : undefined}\n      aria-disabled={item.disabled || undefined}\n      tabIndex={-1}\n      onMouseEnter={item.disabled ? undefined : onHover}\n      onClick={item.disabled ? undefined : onActivate}\n      className=\"mx-1.5 flex cursor-pointer items-center outline-none select-none\"\n      style={{ gap: 9, height: s.rowH, padding: \"0 10px\", borderRadius: s.radius - 2, background: focused || submenuOpen ? p.hover : \"transparent\", color: item.disabled ? p.faint : item.danger ? p.danger : p.text, fontSize: s.font - 0.5, fontWeight: 500, cursor: item.disabled ? \"default\" : \"pointer\" }}\n    >\n      {item.kind === \"checkbox\" && (\n        <span className=\"flex shrink-0 items-center justify-center rounded\" style={{ width: 14, height: 14, border: `1.5px solid ${item.checked ? p.check : p.panelBorder}`, background: item.checked ? p.check : \"transparent\" }}>\n          {item.checked && <CheckGlyph p={p} />}\n        </span>\n      )}\n      {item.kind === \"radio\" && (\n        <span className=\"flex shrink-0 items-center justify-center rounded-full\" style={{ width: 14, height: 14, border: `1.5px solid ${item.checked ? p.check : p.panelBorder}` }}>\n          {item.checked && <span style={{ width: 6, height: 6, borderRadius: 999, background: p.check }} />}\n        </span>\n      )}\n      <span className=\"min-w-0 flex-1 truncate\">{item.label}</span>\n      {item.shortcut && <Kbd p={p}>{item.shortcut}</Kbd>}\n      {item.kind === \"submenu\" && (\n        <svg width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke={p.muted} strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n          <path d=\"M6 3.5L10.5 8L6 12.5\" />\n        </svg>\n      )}\n    </div>\n  );\n}\n\ninterface MenuListProps {\n  items: ContextMenuItem[];\n  s: Size;\n  p: Palette;\n  width: number;\n  /** \"point\": fixed at a raw {x,y}, clamped to the viewport (the root menu). \"right\": a flyout portaled next to its trigger row. */\n  placement: \"point\" | \"right\";\n  point?: { x: number; y: number };\n  anchorRect?: DOMRect | null;\n  onActivate: (item: ContextMenuItem) => void;\n  onClose: () => void;\n  onCloseAll: () => void;\n}\n\nfunction MenuList({ items, s, p, width, placement, point, anchorRect, onActivate, onClose, onCloseAll }: MenuListProps) {\n  const uid = React.useId();\n  const focusableIds = items.filter(isFocusable).map((n) => n.id);\n  const [focusedId, setFocusedId] = React.useState<string | null>(focusableIds[0] ?? null);\n  const [openSubmenu, setOpenSubmenu] = React.useState<string | null>(null);\n  const [submenuAnchor, setSubmenuAnchor] = React.useState<DOMRect | null>(null);\n  const [pos, setPos] = React.useState<{ left: number; top: number } | null>(null);\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const rowRefs = React.useRef<Record<string, HTMLDivElement | null>>({});\n\n  useIsomorphicLayoutEffect(() => {\n    setSubmenuAnchor(openSubmenu ? (rowRefs.current[openSubmenu]?.getBoundingClientRect() ?? null) : null);\n  }, [openSubmenu]);\n\n  // Clamp the root menu to the viewport: it renders once at the raw click\n  // point, gets measured before paint, then is nudged left/up if it would\n  // overflow the right or bottom edge.\n  useIsomorphicLayoutEffect(() => {\n    if (placement !== \"point\" || !point) return;\n    const el = rootRef.current;\n    if (!el) return;\n    const r = el.getBoundingClientRect();\n    const pad = 8;\n    let left = point.x;\n    let top = point.y;\n    if (left + r.width > window.innerWidth - pad) left = Math.max(pad, window.innerWidth - pad - r.width);\n    if (top + r.height > window.innerHeight - pad) top = Math.max(pad, window.innerHeight - pad - r.height);\n    setPos({ left, top });\n  }, [placement, point]);\n\n  useIsomorphicLayoutEffect(() => {\n    // For a \"right\" flyout, the panel renders nothing (see the early return\n    // below) until anchorRect is measured, so rootRef.current is still null\n    // on this effect's first pass; re-running once anchorRect lands makes\n    // sure focus actually reaches the now-real DOM node. preventScroll stops\n    // the browser from auto-scrolling an ancestor to reveal it (which would\n    // otherwise shift unrelated content — the same issue a plain scrollable\n    // menu panel runs into with a flyout escaping its bounds).\n    rootRef.current?.focus({ preventScroll: true });\n  }, [anchorRect]);\n\n  const move = (dir: 1 | -1) => {\n    if (focusableIds.length === 0) return;\n    const i = focusedId ? focusableIds.indexOf(focusedId) : -1;\n    const next = (i + dir + focusableIds.length) % focusableIds.length;\n    setFocusedId(focusableIds[next]);\n  };\n\n  const activate = (item: ContextMenuItem) => {\n    if (item.disabled) return;\n    if (item.kind === \"submenu\") {\n      setOpenSubmenu(item.id);\n      return;\n    }\n    onActivate(item);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (openSubmenu !== null) {\n      if (e.key === \"Escape\") {\n        e.preventDefault();\n        setOpenSubmenu(null);\n      }\n      return;\n    }\n    const focusedItem = items.find((n) => n.id === focusedId);\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      move(1);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      move(-1);\n    } else if (e.key === \"ArrowRight\") {\n      if (focusedItem?.kind === \"submenu\") {\n        e.preventDefault();\n        setOpenSubmenu(focusedItem.id);\n      }\n    } else if (e.key === \"ArrowLeft\") {\n      if (placement === \"right\") {\n        e.preventDefault();\n        onClose();\n      }\n    } else if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      if (focusedItem) activate(focusedItem);\n    } else if (e.key === \"Escape\") {\n      e.preventDefault();\n      onCloseAll();\n    } else if (e.key === \"Home\") {\n      e.preventDefault();\n      if (focusableIds.length) setFocusedId(focusableIds[0]);\n    } else if (e.key === \"End\") {\n      e.preventDefault();\n      if (focusableIds.length) setFocusedId(focusableIds[focusableIds.length - 1]);\n    }\n  };\n\n  if (placement === \"right\" && !anchorRect) return null;\n\n  const style: React.CSSProperties =\n    placement === \"point\"\n      ? { left: pos?.left ?? point?.x ?? 0, top: pos?.top ?? point?.y ?? 0 }\n      : { left: (anchorRect?.right ?? 0) + 4, top: (anchorRect?.top ?? 0) - 8 };\n\n  const node = (\n    <motion.div\n      ref={rootRef}\n      role=\"menu\"\n      tabIndex={-1}\n      aria-activedescendant={focusedId ? `${uid}-${focusedId}` : undefined}\n      onKeyDown={onKeyDown}\n      className=\"fixed z-[9999] overflow-y-auto overflow-x-hidden outline-none\"\n      style={{ ...style, width, maxHeight: 360, padding: 6, borderRadius: s.radius + 4, background: p.panelBg, border: `1px solid ${p.panelBorder}`, boxShadow: p.shadow }}\n      initial={{ opacity: 0, scale: 0.96 }}\n      animate={{ opacity: 1, scale: 1 }}\n      exit={{ opacity: 0, scale: 0.97 }}\n      transition={{ duration: 0.14, ease: [0.16, 1, 0.3, 1] }}\n    >\n      {items.map((item) => (\n        <div key={item.id} className=\"relative\">\n          <Row\n            id={`${uid}-${item.id}`}\n            item={item}\n            s={s}\n            p={p}\n            focused={item.id === focusedId}\n            submenuOpen={item.id === openSubmenu}\n            onHover={() => {\n              setFocusedId(item.id);\n              setOpenSubmenu(item.kind === \"submenu\" ? item.id : null);\n            }}\n            onActivate={() => activate(item)}\n            setRef={(el) => {\n              rowRefs.current[item.id] = el;\n            }}\n          />\n          <AnimatePresence>\n            {item.id === openSubmenu && item.items && (\n              <MenuList\n                items={item.items}\n                s={s}\n                p={p}\n                width={width}\n                placement=\"right\"\n                anchorRect={submenuAnchor}\n                onActivate={onActivate}\n                onClose={() => {\n                  setOpenSubmenu(null);\n                  rootRef.current?.focus({ preventScroll: true });\n                }}\n                onCloseAll={onCloseAll}\n              />\n            )}\n          </AnimatePresence>\n        </div>\n      ))}\n    </motion.div>\n  );\n\n  return createPortal(node, document.body);\n}\n\nexport function ContextMenu({ items, children, onSelect, disabled = false, size = \"md\", width = 220, theme = \"dark\", className }: ContextMenuProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const [point, setPoint] = React.useState<{ x: number; y: number } | null>(null);\n  const triggerRef = React.useRef<HTMLDivElement>(null);\n  const open = point !== null;\n\n  const close = React.useCallback(() => setPoint(null), []);\n\n  const onContextMenu = (e: React.MouseEvent) => {\n    if (disabled) return;\n    e.preventDefault();\n    setPoint({ x: e.clientX, y: e.clientY });\n  };\n\n  React.useEffect(() => {\n    if (!open) return;\n    const onDown = () => close();\n    const onScroll = () => close();\n    // The mousedown that opens a NEW context menu (right-click) shouldn't\n    // also immediately close it via this same listener, so it's attached a\n    // tick later.\n    const id = setTimeout(() => {\n      document.addEventListener(\"mousedown\", onDown);\n      document.addEventListener(\"contextmenu\", onDown);\n    }, 0);\n    window.addEventListener(\"scroll\", onScroll, true);\n    window.addEventListener(\"resize\", onScroll);\n    return () => {\n      clearTimeout(id);\n      document.removeEventListener(\"mousedown\", onDown);\n      document.removeEventListener(\"contextmenu\", onDown);\n      window.removeEventListener(\"scroll\", onScroll, true);\n      window.removeEventListener(\"resize\", onScroll);\n    };\n  }, [open, close]);\n\n  const handleActivate = (item: ContextMenuItem) => {\n    onSelect?.(item);\n    close();\n  };\n\n  return (\n    <>\n      <div ref={triggerRef} onContextMenu={onContextMenu} className={cn(\"contents\", className)}>\n        {children}\n      </div>\n      <AnimatePresence>\n        {open && point && (\n          <MenuList items={items} s={s} p={p} width={width} placement=\"point\" point={point} onActivate={handleActivate} onClose={close} onCloseAll={close} />\n        )}\n      </AnimatePresence>\n    </>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}