ContextMenu.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { useEffect, useRef, useState, useLayoutEffect } from 'react';
  2. import { ChevronRight } 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. title?: string;
  12. }
  13. interface ContextMenuProps {
  14. x: number;
  15. y: number;
  16. items: ContextMenuItem[];
  17. onClose: () => void;
  18. }
  19. export function ContextMenu({ x, y, items, onClose }: ContextMenuProps) {
  20. const menuRef = useRef<HTMLDivElement>(null);
  21. const [activeSubmenu, setActiveSubmenu] = useState<number | null>(null);
  22. const submenuTimeoutRef = useRef<number | null>(null);
  23. const [position, setPosition] = useState({ x, y, visible: false });
  24. const [openSubmenuLeft, setOpenSubmenuLeft] = useState(false);
  25. const [submenuPositions, setSubmenuPositions] = useState<Record<number, 'top' | 'bottom'>>({});
  26. useEffect(() => {
  27. const handleClickOutside = (e: MouseEvent) => {
  28. if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
  29. onClose();
  30. }
  31. };
  32. const handleEscape = (e: KeyboardEvent) => {
  33. if (e.key === 'Escape') {
  34. onClose();
  35. }
  36. };
  37. const handleScroll = () => {
  38. onClose();
  39. };
  40. document.addEventListener('mousedown', handleClickOutside);
  41. document.addEventListener('keydown', handleEscape);
  42. document.addEventListener('scroll', handleScroll, true);
  43. return () => {
  44. document.removeEventListener('mousedown', handleClickOutside);
  45. document.removeEventListener('keydown', handleEscape);
  46. document.removeEventListener('scroll', handleScroll, true);
  47. if (submenuTimeoutRef.current) {
  48. clearTimeout(submenuTimeoutRef.current);
  49. }
  50. };
  51. }, [onClose]);
  52. // Adjust position to keep menu in viewport - use useLayoutEffect for synchronous measurement
  53. useLayoutEffect(() => {
  54. if (menuRef.current) {
  55. // Force a reflow to get accurate measurements
  56. menuRef.current.style.visibility = 'hidden';
  57. menuRef.current.style.display = 'block';
  58. const rect = menuRef.current.getBoundingClientRect();
  59. const viewportWidth = window.innerWidth;
  60. const viewportHeight = window.innerHeight;
  61. const padding = 8;
  62. let adjustedX = x;
  63. let adjustedY = y;
  64. // Adjust horizontal position - if menu would overflow right, shift left
  65. if (x + rect.width > viewportWidth - padding) {
  66. adjustedX = Math.max(padding, viewportWidth - rect.width - padding);
  67. }
  68. // Also check if starting position is negative
  69. if (adjustedX < padding) {
  70. adjustedX = padding;
  71. }
  72. // Adjust vertical position - if menu would overflow bottom, shift up
  73. if (y + rect.height > viewportHeight - padding) {
  74. adjustedY = Math.max(padding, viewportHeight - rect.height - padding);
  75. }
  76. // Also check if starting position is negative
  77. if (adjustedY < padding) {
  78. adjustedY = padding;
  79. }
  80. // Check if submenus should open to the left (more space on left than right)
  81. const submenuWidth = 180;
  82. const spaceOnRight = viewportWidth - adjustedX - rect.width;
  83. const spaceOnLeft = adjustedX;
  84. // Only open left if there's not enough space on right AND there's enough space on left
  85. setOpenSubmenuLeft(spaceOnRight < submenuWidth && spaceOnLeft > submenuWidth);
  86. setPosition({ x: adjustedX, y: adjustedY, visible: true });
  87. }
  88. }, [x, y]);
  89. const handleMouseEnterSubmenu = (index: number, element: HTMLElement) => {
  90. if (submenuTimeoutRef.current) {
  91. clearTimeout(submenuTimeoutRef.current);
  92. submenuTimeoutRef.current = null;
  93. }
  94. // Calculate if submenu should open upward or downward
  95. const rect = element.getBoundingClientRect();
  96. const viewportHeight = window.innerHeight;
  97. const submenuMaxHeight = 300; // matches max-h-[300px]
  98. const padding = 8;
  99. // Check if there's enough space below for the submenu
  100. const spaceBelow = viewportHeight - rect.top - padding;
  101. const shouldOpenUpward = spaceBelow < submenuMaxHeight && rect.top > submenuMaxHeight;
  102. setSubmenuPositions(prev => ({ ...prev, [index]: shouldOpenUpward ? 'bottom' : 'top' }));
  103. setActiveSubmenu(index);
  104. };
  105. const handleMouseLeaveSubmenu = () => {
  106. submenuTimeoutRef.current = window.setTimeout(() => {
  107. setActiveSubmenu(null);
  108. }, 150);
  109. };
  110. return (
  111. <div
  112. ref={menuRef}
  113. 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"
  114. style={{
  115. left: position.x,
  116. top: position.y,
  117. visibility: position.visible ? 'visible' : 'hidden'
  118. }}
  119. >
  120. {items.map((item, index) => {
  121. if (item.divider) {
  122. return <div key={index} className="my-1 border-t border-bambu-dark-tertiary" />;
  123. }
  124. const hasSubmenu = item.submenu && item.submenu.length > 0;
  125. return (
  126. <div
  127. key={index}
  128. className="relative"
  129. onMouseEnter={(e) => hasSubmenu && handleMouseEnterSubmenu(index, e.currentTarget)}
  130. onMouseLeave={() => hasSubmenu && handleMouseLeaveSubmenu()}
  131. >
  132. <button
  133. onMouseEnter={(e) => hasSubmenu && handleMouseEnterSubmenu(index, e.currentTarget.parentElement!)}
  134. onClick={() => {
  135. if (hasSubmenu) {
  136. // Toggle submenu on click as well
  137. setActiveSubmenu(activeSubmenu === index ? null : index);
  138. } else if (!item.disabled) {
  139. item.onClick();
  140. onClose();
  141. }
  142. }}
  143. disabled={item.disabled}
  144. title={item.title}
  145. className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${
  146. item.disabled
  147. ? 'text-bambu-gray cursor-not-allowed'
  148. : item.danger
  149. ? 'text-red-400 hover:bg-red-400/10'
  150. : 'text-white hover:bg-bambu-dark-tertiary'
  151. } ${hasSubmenu && activeSubmenu === index ? 'bg-bambu-dark-tertiary' : ''}`}
  152. >
  153. {item.icon && <span className="w-4 h-4 flex-shrink-0 flex items-center justify-center">{item.icon}</span>}
  154. <span className="flex-1">{item.label}</span>
  155. {hasSubmenu && <ChevronRight className="w-4 h-4 text-bambu-gray" />}
  156. </button>
  157. {/* Submenu */}
  158. {hasSubmenu && activeSubmenu === index && (
  159. <div
  160. className={`absolute min-w-[160px] 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] ${
  161. openSubmenuLeft ? 'right-full mr-1' : 'left-full ml-1'
  162. } ${submenuPositions[index] === 'bottom' ? 'bottom-0' : 'top-0'}`}
  163. onMouseEnter={() => {
  164. if (submenuTimeoutRef.current) {
  165. clearTimeout(submenuTimeoutRef.current);
  166. submenuTimeoutRef.current = null;
  167. }
  168. }}
  169. onMouseLeave={() => handleMouseLeaveSubmenu()}
  170. >
  171. {item.submenu!.map((subItem, subIndex) => (
  172. <button
  173. key={subIndex}
  174. onClick={() => {
  175. if (!subItem.disabled) {
  176. subItem.onClick();
  177. onClose();
  178. }
  179. }}
  180. disabled={subItem.disabled}
  181. className={`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${
  182. subItem.disabled
  183. ? 'text-bambu-gray cursor-not-allowed'
  184. : subItem.danger
  185. ? 'text-red-400 hover:bg-red-400/10'
  186. : 'text-white hover:bg-bambu-dark-tertiary'
  187. }`}
  188. >
  189. {subItem.icon && <span className="w-4 h-4 flex-shrink-0 flex items-center justify-center">{subItem.icon}</span>}
  190. {subItem.label}
  191. </button>
  192. ))}
  193. </div>
  194. )}
  195. </div>
  196. );
  197. })}
  198. </div>
  199. );
  200. }