ContextMenu.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import { useEffect, useRef, useState, useLayoutEffect } from 'react';
  2. import { ChevronRight, Search } from 'lucide-react';
  3. export interface ContextMenuItem {
  4. label: string;
  5. icon?: React.ReactNode;
  6. onClick: () => void;
  7. danger?: boolean;
  8. disabled?: boolean;
  9. divider?: boolean;
  10. submenu?: ContextMenuItem[];
  11. // When set on an item with a submenu, render a search input above the
  12. // submenu items that filters by label (case-insensitive).
  13. submenuSearchPlaceholder?: string;
  14. title?: string;
  15. }
  16. interface ContextMenuProps {
  17. x: number;
  18. y: number;
  19. items: ContextMenuItem[];
  20. onClose: () => void;
  21. // The element that opened the menu. A mousedown on it is not "outside":
  22. // without this the anchor's click handler runs after the menu has already
  23. // been dismissed and cannot act as a close toggle.
  24. anchorRef?: React.RefObject<HTMLElement | null>;
  25. }
  26. interface SubmenuPanelProps {
  27. items: ContextMenuItem[];
  28. searchPlaceholder?: string;
  29. onClose: () => void;
  30. className: string;
  31. onMouseEnter: () => void;
  32. onMouseLeave: () => void;
  33. }
  34. function SubmenuPanel({
  35. items,
  36. searchPlaceholder,
  37. onClose,
  38. className,
  39. onMouseEnter,
  40. onMouseLeave,
  41. }: SubmenuPanelProps) {
  42. const [query, setQuery] = useState('');
  43. const inputRef = useRef<HTMLInputElement>(null);
  44. useEffect(() => {
  45. if (searchPlaceholder) {
  46. // Defer focus so it survives the mouse event that opened the submenu.
  47. const id = window.setTimeout(() => inputRef.current?.focus(), 0);
  48. return () => window.clearTimeout(id);
  49. }
  50. }, [searchPlaceholder]);
  51. const trimmed = query.trim().toLowerCase();
  52. const filteredItems = searchPlaceholder && trimmed
  53. ? items.filter((i) => i.label.toLowerCase().includes(trimmed))
  54. : items;
  55. return (
  56. <div
  57. className={className}
  58. onMouseEnter={onMouseEnter}
  59. onMouseLeave={onMouseLeave}
  60. >
  61. {searchPlaceholder && (
  62. <div className="sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary">
  63. <div className="relative">
  64. <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none" />
  65. <input
  66. ref={inputRef}
  67. type="text"
  68. value={query}
  69. onChange={(e) => setQuery(e.target.value)}
  70. onKeyDown={(e) => {
  71. if (e.key === 'Enter') {
  72. const first = filteredItems.find((i) => !i.disabled);
  73. if (first) {
  74. first.onClick();
  75. onClose();
  76. }
  77. }
  78. }}
  79. placeholder={searchPlaceholder}
  80. className="w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"
  81. />
  82. </div>
  83. </div>
  84. )}
  85. {filteredItems.map((subItem, subIndex) => (
  86. <button
  87. key={subIndex}
  88. onClick={() => {
  89. if (!subItem.disabled) {
  90. subItem.onClick();
  91. onClose();
  92. }
  93. }}
  94. disabled={subItem.disabled}
  95. className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${
  96. subItem.disabled
  97. ? 'text-bambu-gray cursor-not-allowed'
  98. : subItem.danger
  99. ? 'text-red-700 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-400/10'
  100. : 'text-white hover:bg-bambu-dark-tertiary'
  101. }`}
  102. >
  103. {subItem.icon && <span className="w-4 h-4 flex-shrink-0 flex items-center justify-center">{subItem.icon}</span>}
  104. <span className="flex-1 truncate">{subItem.label}</span>
  105. </button>
  106. ))}
  107. {searchPlaceholder && filteredItems.length === 0 && (
  108. <div className="px-3 py-2 text-sm text-bambu-gray text-center italic">—</div>
  109. )}
  110. </div>
  111. );
  112. }
  113. export function ContextMenu({ x, y, items, onClose, anchorRef }: ContextMenuProps) {
  114. const menuRef = useRef<HTMLDivElement>(null);
  115. const [activeSubmenu, setActiveSubmenu] = useState<number | null>(null);
  116. const submenuTimeoutRef = useRef<number | null>(null);
  117. const [position, setPosition] = useState({ x, y, visible: false });
  118. const [openSubmenuLeft, setOpenSubmenuLeft] = useState(false);
  119. const [submenuPositions, setSubmenuPositions] = useState<Record<number, 'top' | 'bottom'>>({});
  120. useEffect(() => {
  121. const handleClickOutside = (e: MouseEvent) => {
  122. const target = e.target as Node;
  123. if (menuRef.current?.contains(target) || anchorRef?.current?.contains(target)) return;
  124. onClose();
  125. };
  126. const handleEscape = (e: KeyboardEvent) => {
  127. if (e.key === 'Escape') {
  128. onClose();
  129. }
  130. };
  131. const handleScroll = (e: Event) => {
  132. // Internal submenu scroll (overflow-y-auto on the submenu panel) must
  133. // not dismiss the menu — only close on scroll outside our own subtree.
  134. if (menuRef.current && menuRef.current.contains(e.target as Node)) {
  135. return;
  136. }
  137. onClose();
  138. };
  139. document.addEventListener('mousedown', handleClickOutside);
  140. document.addEventListener('keydown', handleEscape);
  141. document.addEventListener('scroll', handleScroll, true);
  142. return () => {
  143. document.removeEventListener('mousedown', handleClickOutside);
  144. document.removeEventListener('keydown', handleEscape);
  145. document.removeEventListener('scroll', handleScroll, true);
  146. if (submenuTimeoutRef.current) {
  147. clearTimeout(submenuTimeoutRef.current);
  148. }
  149. };
  150. }, [onClose, anchorRef]);
  151. // Adjust position to keep menu in viewport - use useLayoutEffect for synchronous measurement
  152. useLayoutEffect(() => {
  153. if (menuRef.current) {
  154. // Force a reflow to get accurate measurements
  155. menuRef.current.style.visibility = 'hidden';
  156. menuRef.current.style.display = 'block';
  157. const rect = menuRef.current.getBoundingClientRect();
  158. const viewportWidth = window.innerWidth;
  159. const viewportHeight = window.innerHeight;
  160. const padding = 8;
  161. let adjustedX = x;
  162. let adjustedY = y;
  163. // Adjust horizontal position - if menu would overflow right, shift left
  164. if (x + rect.width > viewportWidth - padding) {
  165. adjustedX = Math.max(padding, viewportWidth - rect.width - padding);
  166. }
  167. // Also check if starting position is negative
  168. if (adjustedX < padding) {
  169. adjustedX = padding;
  170. }
  171. // Adjust vertical position - if menu would overflow bottom, shift up
  172. if (y + rect.height > viewportHeight - padding) {
  173. adjustedY = Math.max(padding, viewportHeight - rect.height - padding);
  174. }
  175. // Also check if starting position is negative
  176. if (adjustedY < padding) {
  177. adjustedY = padding;
  178. }
  179. // Check if submenus should open to the left (more space on left than right)
  180. const submenuWidth = 180;
  181. const spaceOnRight = viewportWidth - adjustedX - rect.width;
  182. const spaceOnLeft = adjustedX;
  183. // Only open left if there's not enough space on right AND there's enough space on left
  184. setOpenSubmenuLeft(spaceOnRight < submenuWidth && spaceOnLeft > submenuWidth);
  185. setPosition({ x: adjustedX, y: adjustedY, visible: true });
  186. }
  187. }, [x, y]);
  188. const handleMouseEnterSubmenu = (index: number, element: HTMLElement) => {
  189. if (submenuTimeoutRef.current) {
  190. clearTimeout(submenuTimeoutRef.current);
  191. submenuTimeoutRef.current = null;
  192. }
  193. // Calculate if submenu should open upward or downward
  194. const rect = element.getBoundingClientRect();
  195. const viewportHeight = window.innerHeight;
  196. const submenuMaxHeight = 300; // matches max-h-[300px]
  197. const padding = 8;
  198. // Check if there's enough space below for the submenu
  199. const spaceBelow = viewportHeight - rect.top - padding;
  200. const shouldOpenUpward = spaceBelow < submenuMaxHeight && rect.top > submenuMaxHeight;
  201. setSubmenuPositions(prev => ({ ...prev, [index]: shouldOpenUpward ? 'bottom' : 'top' }));
  202. setActiveSubmenu(index);
  203. };
  204. const handleMouseLeaveSubmenu = () => {
  205. submenuTimeoutRef.current = window.setTimeout(() => {
  206. setActiveSubmenu(null);
  207. }, 150);
  208. };
  209. return (
  210. <div
  211. ref={menuRef}
  212. className="fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1"
  213. style={{
  214. left: position.x,
  215. top: position.y,
  216. visibility: position.visible ? 'visible' : 'hidden'
  217. }}
  218. >
  219. {items.map((item, index) => {
  220. if (item.divider) {
  221. return <div key={index} className="my-1 border-t border-bambu-dark-tertiary" />;
  222. }
  223. const hasSubmenu = item.submenu && item.submenu.length > 0;
  224. return (
  225. <div
  226. key={index}
  227. className="relative"
  228. onMouseEnter={(e) => hasSubmenu && handleMouseEnterSubmenu(index, e.currentTarget)}
  229. onMouseLeave={() => hasSubmenu && handleMouseLeaveSubmenu()}
  230. >
  231. <button
  232. onMouseEnter={(e) => hasSubmenu && handleMouseEnterSubmenu(index, e.currentTarget.parentElement!)}
  233. onClick={() => {
  234. if (hasSubmenu) {
  235. // Toggle submenu on click as well
  236. setActiveSubmenu(activeSubmenu === index ? null : index);
  237. } else if (!item.disabled) {
  238. item.onClick();
  239. onClose();
  240. }
  241. }}
  242. disabled={item.disabled}
  243. title={item.title}
  244. className={`group w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${
  245. item.disabled
  246. ? 'text-bambu-gray cursor-not-allowed'
  247. : item.danger
  248. ? 'text-red-700 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-400/10'
  249. : 'text-white hover:bg-bambu-dark-tertiary'
  250. } ${hasSubmenu && activeSubmenu === index ? 'bg-bambu-dark-tertiary' : ''}`}
  251. >
  252. {item.icon && <span className="w-4 h-4 flex-shrink-0 flex items-center justify-center">{item.icon}</span>}
  253. <span className="flex-1">{item.label}</span>
  254. {hasSubmenu && <ChevronRight className="w-4 h-4 text-bambu-gray" />}
  255. </button>
  256. {/* Submenu */}
  257. {hasSubmenu && activeSubmenu === index && (
  258. <SubmenuPanel
  259. items={item.submenu!}
  260. searchPlaceholder={item.submenuSearchPlaceholder}
  261. onClose={onClose}
  262. className={`absolute min-w-[200px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${
  263. openSubmenuLeft ? 'right-full mr-1' : 'left-full ml-1'
  264. } ${submenuPositions[index] === 'bottom' ? 'bottom-0' : 'top-0'}`}
  265. onMouseEnter={() => {
  266. if (submenuTimeoutRef.current) {
  267. clearTimeout(submenuTimeoutRef.current);
  268. submenuTimeoutRef.current = null;
  269. }
  270. }}
  271. onMouseLeave={() => handleMouseLeaveSubmenu()}
  272. />
  273. )}
  274. </div>
  275. );
  276. })}
  277. </div>
  278. );
  279. }