FilamentHoverCard.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import { useState, useRef, useEffect, useLayoutEffect, type ReactNode } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { useNavigate } from 'react-router-dom';
  4. import { useTranslation } from 'react-i18next';
  5. import { Droplets, Copy, Check, Settings2, Package, Unlink } from 'lucide-react';
  6. import { isLightColor } from '../utils/colors';
  7. interface FilamentData {
  8. vendor: 'Bambu Lab' | 'Generic';
  9. profile: string;
  10. colorName: string;
  11. colorHex: string | null;
  12. kFactor: string;
  13. fillLevel: number | null; // null = unknown
  14. trayUuid?: string | null; // Bambu Lab spool UUID for Spoolman linking
  15. tagUid?: string | null; // Generic NFC tag UID fallback for linking
  16. fillSource?: 'ams' | 'spoolman' | 'inventory'; // Source of fill level data
  17. }
  18. interface SpoolmanConfig {
  19. enabled: boolean;
  20. onLinkSpool?: () => void;
  21. onUnlinkSpool?: () => void;
  22. linkedSpoolId?: number | null; // Spoolman spool ID if this tray is already linked
  23. spoolmanUrl?: string | null; // Base URL for Spoolman (for "Open in Spoolman" link)
  24. syncMode?: string | null; // If auto-sync is enabled, we may want to hide the unlink option for Bambu spools
  25. }
  26. interface InventoryConfig {
  27. onAssignSpool?: () => void;
  28. onUnassignSpool?: () => void;
  29. assignedSpool?: { id: number; material: string; brand: string | null; color_name: string | null; remainingWeightGrams?: number | null } | null;
  30. isAssigned?: boolean;
  31. }
  32. interface ConfigureSlotConfig {
  33. enabled: boolean;
  34. onConfigure?: () => void;
  35. }
  36. interface FilamentHoverCardProps {
  37. data: FilamentData;
  38. children: ReactNode;
  39. disabled?: boolean;
  40. className?: string;
  41. spoolman?: SpoolmanConfig;
  42. inventory?: InventoryConfig;
  43. configureSlot?: ConfigureSlotConfig;
  44. actions?: ReactNode;
  45. }
  46. /**
  47. * A hover card that displays filament details when hovering over AMS slots.
  48. * Replaces the basic browser tooltip with a styled popover.
  49. */
  50. export function FilamentHoverCard({ data, children, disabled, className = '', spoolman, inventory, configureSlot, actions }: FilamentHoverCardProps) {
  51. const { t } = useTranslation();
  52. const navigate = useNavigate();
  53. const [isVisible, setIsVisible] = useState(false);
  54. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  55. // Screen-space coordinates for the portaled card (#1336 follow-up). Using
  56. // a portal + position:fixed lets the popover escape sibling printer cards
  57. // that create their own stacking contexts on the dashboard — without this,
  58. // a card later in DOM order draws over the hover popover regardless of
  59. // z-index because z-index doesn't cross stacking-context boundaries.
  60. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  61. const [copied, setCopied] = useState(false);
  62. const [showUnlinkConfirm, setShowUnlinkConfirm] = useState(false);
  63. const triggerRef = useRef<HTMLDivElement>(null);
  64. const cardRef = useRef<HTMLDivElement>(null);
  65. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  66. const handleCopyUuid = () => {
  67. const uuid = data.trayUuid;
  68. if (!uuid) return;
  69. // Try modern clipboard API first, fallback to execCommand
  70. if (navigator.clipboard && window.isSecureContext) {
  71. navigator.clipboard.writeText(uuid).then(() => {
  72. setCopied(true);
  73. setTimeout(() => setCopied(false), 2000);
  74. }).catch(() => {
  75. // Fallback on error
  76. fallbackCopy(uuid);
  77. });
  78. } else {
  79. fallbackCopy(uuid);
  80. }
  81. };
  82. const fallbackCopy = (text: string) => {
  83. const textarea = document.createElement('textarea');
  84. textarea.value = text;
  85. textarea.style.position = 'fixed';
  86. textarea.style.opacity = '0';
  87. document.body.appendChild(textarea);
  88. textarea.select();
  89. try {
  90. document.execCommand('copy');
  91. setCopied(true);
  92. setTimeout(() => setCopied(false), 2000);
  93. } catch {
  94. console.error('Failed to copy to clipboard');
  95. }
  96. document.body.removeChild(textarea);
  97. };
  98. // Compute placement (top/bottom) + screen coordinates for the portaled
  99. // card. Runs on visibility change, scroll, and resize so the popover
  100. // tracks the trigger when the viewport moves. useLayoutEffect rather
  101. // than useEffect so the first paint already has the correct coords —
  102. // avoids a one-frame flicker at (0, 0).
  103. useLayoutEffect(() => {
  104. if (!isVisible) {
  105. setCoords(null);
  106. return;
  107. }
  108. const compute = () => {
  109. if (!triggerRef.current || !cardRef.current) return;
  110. const triggerRect = triggerRef.current.getBoundingClientRect();
  111. const cardHeight = cardRef.current.offsetHeight;
  112. const cardWidth = cardRef.current.offsetWidth;
  113. const headerHeight = 56;
  114. const spaceAbove = triggerRect.top - headerHeight;
  115. const spaceBelow = window.innerHeight - triggerRect.bottom;
  116. const placement: 'top' | 'bottom' =
  117. spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top';
  118. const centerX = triggerRect.left + triggerRect.width / 2;
  119. const left = Math.max(8, Math.min(centerX - cardWidth / 2, window.innerWidth - cardWidth - 8));
  120. const top = placement === 'top' ? triggerRect.top - cardHeight - 8 : triggerRect.bottom + 8;
  121. setPosition(placement);
  122. setCoords({ top, left });
  123. };
  124. // First compute is synchronous from the layout effect; a follow-up rAF
  125. // re-measures after the card actually has its rendered dimensions.
  126. compute();
  127. const rafId = requestAnimationFrame(compute);
  128. window.addEventListener('scroll', compute, true);
  129. window.addEventListener('resize', compute);
  130. return () => {
  131. cancelAnimationFrame(rafId);
  132. window.removeEventListener('scroll', compute, true);
  133. window.removeEventListener('resize', compute);
  134. };
  135. }, [isVisible]);
  136. const handleMouseEnter = () => {
  137. if (disabled) return;
  138. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  139. // Small delay to prevent flicker on quick mouse movements
  140. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  141. };
  142. const handleMouseLeave = () => {
  143. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  144. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  145. };
  146. // Dismiss the card immediately, for actions that open a dialog or navigate away.
  147. //
  148. // The card is portaled at z-[60] so it can escape sibling printer cards' stacking
  149. // contexts, which puts it ABOVE ConfigureAmsSlotModal and LinkSpoolModal at z-50 —
  150. // so a card left standing draws over the very dialog it just opened. Mouseleave is
  151. // the only thing that normally hides it, and a touch device never sends one after
  152. // the tap that opened the card, so on a tablet it stays up indefinitely (#2631).
  153. // Clearing the timeout is not optional: a pending show timer would re-open it.
  154. const dismiss = () => {
  155. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  156. setIsVisible(false);
  157. };
  158. // Cleanup timeout on unmount
  159. useEffect(() => {
  160. return () => {
  161. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  162. };
  163. }, []);
  164. // Get fill bar color based on percentage
  165. const getFillColor = (fill: number): string => {
  166. if (fill <= 15) return '#ef4444'; // red
  167. if (fill <= 30) return '#f97316'; // orange
  168. if (fill <= 50) return '#eab308'; // yellow
  169. return '#22c55e'; // green
  170. };
  171. const colorHex = data.colorHex ? `#${data.colorHex.replace('#', '')}` : null;
  172. const assignedRemainingWeight = inventory?.assignedSpool?.remainingWeightGrams ?? null;
  173. return (
  174. <div
  175. ref={triggerRef}
  176. data-testid="filament-slot"
  177. className={`relative ${className}`}
  178. onMouseEnter={handleMouseEnter}
  179. onMouseLeave={handleMouseLeave}
  180. >
  181. {children}
  182. {/* Portaled hover card — rendered into document.body so it escapes
  183. any ancestor stacking context. Sibling printer cards on the
  184. dashboard create their own stacking contexts; without the portal
  185. the popover gets covered by the next card even at z-[60]
  186. (#1336 follow-up). */}
  187. {isVisible && createPortal(
  188. <div
  189. ref={cardRef}
  190. className="fixed z-[60]"
  191. style={{
  192. top: coords?.top ?? -9999,
  193. left: coords?.left ?? -9999,
  194. maxWidth: 'calc(100vw - 24px)',
  195. // Hide until coords are computed to avoid a (-9999,-9999) flash.
  196. visibility: coords ? 'visible' : 'hidden',
  197. }}
  198. onMouseEnter={handleMouseEnter}
  199. onMouseLeave={handleMouseLeave}
  200. >
  201. {/* Card container */}
  202. <div className="
  203. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  204. rounded-lg shadow-xl overflow-hidden
  205. backdrop-blur-sm
  206. ">
  207. {/* Color swatch header - the hero element */}
  208. <div
  209. className="h-12 relative overflow-hidden"
  210. style={{
  211. backgroundColor: colorHex || '#3d3d3d',
  212. }}
  213. >
  214. {/* Subtle gradient overlay for depth */}
  215. <div className="absolute inset-0 bg-gradient-to-b from-white/10 to-transparent" />
  216. {/* Color name on swatch */}
  217. <div className={`
  218. absolute inset-0 flex items-center justify-center
  219. font-semibold text-sm tracking-wide
  220. ${isLightColor(colorHex) ? 'text-black/80' : 'text-white/90'}
  221. `}>
  222. {data.colorName}
  223. </div>
  224. {/* Vendor badge - solid background for visibility on any color */}
  225. <div className={`
  226. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  227. ${data.vendor === 'Bambu Lab'
  228. ? 'bg-black/60 text-white'
  229. : 'bg-black/50 text-white/90'}
  230. `}>
  231. {data.vendor === 'Bambu Lab' ? 'BBL' : 'GEN'}
  232. </div>
  233. </div>
  234. {/* Details section */}
  235. <div className="p-3 space-y-2.5">
  236. {/* Profile name */}
  237. <div className="flex items-center justify-between">
  238. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  239. {t('ams.profile')}
  240. </span>
  241. <span className="text-xs text-white font-semibold truncate max-w-[120px]">
  242. {data.profile}
  243. </span>
  244. </div>
  245. {/* K Factor */}
  246. <div className="flex items-center justify-between">
  247. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  248. {t('ams.kFactor')}
  249. </span>
  250. <span className="text-xs text-bambu-green font-mono font-bold">
  251. {data.kFactor}
  252. </span>
  253. </div>
  254. {/* Fill Level */}
  255. <div className="space-y-1">
  256. <div className="flex items-center justify-between">
  257. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1">
  258. <Droplets className="w-3 h-3" />
  259. {t('ams.fill')}
  260. </span>
  261. <span className="text-xs text-white font-semibold flex items-center gap-1">
  262. <span>{data.fillLevel !== null ? `${data.fillLevel}%` : '—'}</span>
  263. {assignedRemainingWeight !== null && data.fillLevel !== null && (
  264. <span className="text-[9px] text-bambu-gray font-normal">• {assignedRemainingWeight}g</span>
  265. )}
  266. </span>
  267. </div>
  268. {/* Fill bar */}
  269. <div className="h-1.5 bg-black/40 rounded-full overflow-hidden">
  270. {data.fillLevel !== null ? (
  271. <div
  272. className="h-full rounded-full transition-all duration-300"
  273. style={{
  274. width: `${data.fillLevel}%`,
  275. backgroundColor: getFillColor(data.fillLevel),
  276. }}
  277. />
  278. ) : (
  279. <div className="h-full w-full bg-bambu-gray/30 rounded-full" />
  280. )}
  281. </div>
  282. </div>
  283. {/* Spoolman section - only show if enabled */}
  284. {spoolman?.enabled && (
  285. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  286. {/* Tray UUID with copy button */}
  287. <div className="flex items-center justify-between">
  288. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  289. {t('spoolman.spoolId')}
  290. </span>
  291. {data.trayUuid ? (
  292. <button
  293. onClick={(e) => {
  294. e.stopPropagation();
  295. handleCopyUuid();
  296. }}
  297. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  298. title="Copy spool UUID"
  299. >
  300. <span className="font-mono text-[10px] truncate max-w-[80px]">
  301. {data.trayUuid.slice(0, 8)}...
  302. </span>
  303. {copied ? (
  304. <Check className="w-3 h-3 text-bambu-green" />
  305. ) : (
  306. <Copy className="w-3 h-3" />
  307. )}
  308. </button>
  309. ) : (
  310. <span className="text-[10px] text-bambu-gray">—</span>
  311. )}
  312. </div>
  313. {/* Open in inventory button (when already linked to a Spoolman spool) */}
  314. {spoolman.linkedSpoolId && (
  315. <>
  316. <button
  317. onClick={(e) => {
  318. e.stopPropagation();
  319. dismiss();
  320. navigate(`/inventory?spool=${spoolman.linkedSpoolId}`);
  321. }}
  322. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/40 text-bambu-green"
  323. title={t('inventory.openInInventory')}
  324. >
  325. <Package className="w-3.5 h-3.5" />
  326. {t('inventory.openInInventory')}
  327. </button>
  328. </>
  329. )}
  330. {/* Link/Unlink action buttons intentionally NOT rendered
  331. here. The inventory section below already provides
  332. Assign/Unassign for slot-binding (the primary user
  333. flow in Spoolman mode). Showing the spoolman tag-link
  334. buttons in addition surfaced two red Unlink-icon
  335. buttons for what users perceive as the same action,
  336. regardless of whether the labels said "Unlink Spool"
  337. vs "Unassign Spool". Tag-linking remains available
  338. via dedicated UI (LinkSpoolModal can be opened from
  339. Spoolman settings / inventory page). */}
  340. </div>
  341. )}
  342. {/* Inventory section — shown for every vendor including
  343. Bambu Lab (#1133). The earlier "non-Bambu only" gate
  344. prevented users from manually assigning a Bambu spool
  345. in inventory to an AMS slot when they didn't want to
  346. re-scan via SpoolBuddy NFC. */}
  347. {inventory && (
  348. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  349. {inventory.assignedSpool ? (
  350. <>
  351. <div className="flex items-center gap-1.5">
  352. <Package className="w-3 h-3 text-bambu-green" />
  353. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  354. {t('inventory.assigned')}
  355. </span>
  356. </div>
  357. <div className="flex items-baseline gap-1.5 min-w-0 mb-1">
  358. <p className="text-xs text-white truncate">
  359. {inventory.assignedSpool.brand ? `${inventory.assignedSpool.brand} ` : ''}
  360. {inventory.assignedSpool.material}
  361. {inventory.assignedSpool.color_name ? ` - ${inventory.assignedSpool.color_name}` : ''}
  362. </p>
  363. <span className="text-[10px] font-mono text-bambu-gray shrink-0">#{inventory.assignedSpool.id}</span>
  364. </div>
  365. {(!spoolman?.linkedSpoolId || inventory.assignedSpool!.id !== spoolman.linkedSpoolId) && (
  366. <button
  367. onClick={(e) => {
  368. e.stopPropagation();
  369. dismiss();
  370. navigate(`/inventory?spool=${inventory.assignedSpool!.id}`);
  371. }}
  372. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/40 text-bambu-green"
  373. title={t('inventory.openInInventory')}
  374. >
  375. <Package className="w-3.5 h-3.5" />
  376. {t('inventory.openInInventory')}
  377. </button>
  378. )}
  379. {inventory.onUnassignSpool && (
  380. <button
  381. onClick={(e) => {
  382. e.stopPropagation();
  383. dismiss();
  384. inventory.onUnassignSpool?.();
  385. }}
  386. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-red-100 dark:bg-red-500/20 hover:bg-red-200 dark:hover:bg-red-500/40 text-red-700 dark:text-red-400"
  387. >
  388. <Unlink className="w-3.5 h-3.5" />
  389. {t('inventory.unassignSpool')}
  390. </button>
  391. )}
  392. </>
  393. ) : inventory.onAssignSpool ? (
  394. <button
  395. onClick={inventory.isAssigned ? undefined : (e) => {
  396. e.stopPropagation();
  397. dismiss();
  398. inventory.onAssignSpool?.();
  399. }}
  400. disabled={!!inventory.isAssigned}
  401. className={`w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 text-bambu-blue ${
  402. inventory.isAssigned ? 'opacity-50 cursor-not-allowed' : 'hover:bg-bambu-blue/40'
  403. }`}
  404. >
  405. <Package className="w-3.5 h-3.5" />
  406. {t('inventory.assignSpool')}
  407. </button>
  408. ) : null}
  409. </div>
  410. )}
  411. {/* Configure slot section - always show if enabled */}
  412. {configureSlot?.enabled && (
  413. <div className={`${spoolman?.enabled && data.trayUuid ? '' : 'pt-2 mt-2 border-t border-bambu-dark-tertiary'}`}>
  414. <button
  415. onClick={(e) => {
  416. e.stopPropagation();
  417. dismiss();
  418. configureSlot.onConfigure?.();
  419. }}
  420. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/40 text-bambu-blue"
  421. title={t('ams.configureSlot')}
  422. >
  423. <Settings2 className="w-3.5 h-3.5" />
  424. {t('ams.configure')}
  425. </button>
  426. </div>
  427. )}
  428. {actions && (
  429. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-1">
  430. {actions}
  431. </div>
  432. )}
  433. </div>
  434. </div>
  435. {/* Arrow pointer */}
  436. <div
  437. className={`
  438. absolute left-1/2 -translate-x-1/2 w-0 h-0
  439. border-l-[6px] border-l-transparent
  440. border-r-[6px] border-r-transparent
  441. ${position === 'top'
  442. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  443. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  444. `}
  445. />
  446. </div>,
  447. document.body,
  448. )}
  449. {/* Unlink Confirmation Dialog */}
  450. {showUnlinkConfirm && (
  451. <div className="fixed inset-0 z-[100] flex items-center justify-center" onClick={() => setShowUnlinkConfirm(false)}>
  452. <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
  453. <div
  454. className="relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary"
  455. onClick={(e) => e.stopPropagation()}
  456. >
  457. <div className="p-4 space-y-4">
  458. <div className="space-y-2">
  459. <h3 className="text-base font-semibold text-white">
  460. {t('spoolman.unlinkConfirmTitle')}
  461. </h3>
  462. <p className="text-sm text-bambu-gray">
  463. {t('spoolman.unlinkConfirmMessage')}
  464. </p>
  465. </div>
  466. <div className="flex gap-2">
  467. <button
  468. onClick={() => setShowUnlinkConfirm(false)}
  469. className="flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white"
  470. >
  471. {t('common.cancel')}
  472. </button>
  473. <button
  474. onClick={() => {
  475. spoolman?.onUnlinkSpool?.();
  476. setShowUnlinkConfirm(false);
  477. }}
  478. className="flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-100 dark:bg-red-500/20 hover:bg-red-200 dark:hover:bg-red-500/40 text-red-700 dark:text-red-400"
  479. >
  480. {t('inventory.unassignSpool')}
  481. </button>
  482. </div>
  483. </div>
  484. </div>
  485. </div>
  486. )}
  487. </div>
  488. );
  489. }
  490. interface EmptySlotHoverCardProps {
  491. children: ReactNode;
  492. className?: string;
  493. configureSlot?: ConfigureSlotConfig;
  494. onAssignSpool?: () => void;
  495. actions?: ReactNode;
  496. // #1322 follow-up: distinguish firmware-confirmed empty (state 9/10) from
  497. // a user reset where the firmware still has a spool registered. "reset"
  498. // surfaces the user-cleared label; undefined / "physical" keeps the
  499. // historical "Empty slot" wording.
  500. kind?: 'physical' | 'reset';
  501. }
  502. export function EmptySlotHoverCard({ children, className = '', configureSlot, onAssignSpool, actions, kind }: EmptySlotHoverCardProps) {
  503. const { t } = useTranslation();
  504. const [isVisible, setIsVisible] = useState(false);
  505. // Screen-space coords for the portaled card — same pattern as
  506. // FilamentHoverCard, see comment there (#1336 follow-up).
  507. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  508. const triggerRef = useRef<HTMLDivElement>(null);
  509. const cardRef = useRef<HTMLDivElement>(null);
  510. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  511. const handleMouseEnter = () => {
  512. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  513. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  514. };
  515. const handleMouseLeave = () => {
  516. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  517. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  518. };
  519. // See FilamentHoverCard.dismiss — same z-[60]-over-a-z-50-dialog problem, and the
  520. // same missing mouseleave on touch (#2631).
  521. const dismiss = () => {
  522. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  523. setIsVisible(false);
  524. };
  525. useEffect(() => {
  526. return () => {
  527. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  528. };
  529. }, []);
  530. useLayoutEffect(() => {
  531. if (!isVisible) {
  532. setCoords(null);
  533. return;
  534. }
  535. const compute = () => {
  536. if (!triggerRef.current || !cardRef.current) return;
  537. const triggerRect = triggerRef.current.getBoundingClientRect();
  538. const cardHeight = cardRef.current.offsetHeight;
  539. const cardWidth = cardRef.current.offsetWidth;
  540. const centerX = triggerRect.left + triggerRect.width / 2;
  541. const left = Math.max(8, Math.min(centerX - cardWidth / 2, window.innerWidth - cardWidth - 8));
  542. const top = triggerRect.top - cardHeight - 8;
  543. setCoords({ top, left });
  544. };
  545. compute();
  546. const rafId = requestAnimationFrame(compute);
  547. window.addEventListener('scroll', compute, true);
  548. window.addEventListener('resize', compute);
  549. return () => {
  550. cancelAnimationFrame(rafId);
  551. window.removeEventListener('scroll', compute, true);
  552. window.removeEventListener('resize', compute);
  553. };
  554. }, [isVisible]);
  555. return (
  556. <div
  557. ref={triggerRef}
  558. className={`relative ${className}`}
  559. onMouseEnter={handleMouseEnter}
  560. onMouseLeave={handleMouseLeave}
  561. >
  562. {children}
  563. {isVisible && createPortal(
  564. <div
  565. ref={cardRef}
  566. className="fixed z-[60]"
  567. style={{
  568. top: coords?.top ?? -9999,
  569. left: coords?.left ?? -9999,
  570. visibility: coords ? 'visible' : 'hidden',
  571. }}
  572. onMouseEnter={handleMouseEnter}
  573. onMouseLeave={handleMouseLeave}
  574. >
  575. <div className="
  576. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  577. rounded-md shadow-lg overflow-hidden
  578. ">
  579. <div className="px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap">
  580. {kind === 'reset' ? t('ams.emptySlotReset') : t('ams.emptySlot')}
  581. </div>
  582. {/* Configure slot button */}
  583. {(configureSlot?.enabled || onAssignSpool || actions) && (
  584. <div className="px-2 pb-2 space-y-1">
  585. {/* Assign before Configure, matching the filled-slot card
  586. above (#2791). The two cards are separate render paths
  587. and had drifted into opposite orders, so the menu
  588. reshuffled itself depending on whether the slot happened
  589. to hold filament. */}
  590. {onAssignSpool && (
  591. <button
  592. onClick={(e) => { e.stopPropagation(); dismiss(); onAssignSpool(); }}
  593. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/40 text-bambu-blue"
  594. >
  595. <Package className="w-3.5 h-3.5" />
  596. {t('inventory.assignSpool')}
  597. </button>
  598. )}
  599. {configureSlot?.enabled && (
  600. <button
  601. onClick={(e) => {
  602. e.stopPropagation();
  603. dismiss();
  604. configureSlot.onConfigure?.();
  605. }}
  606. className="w-full flex items-center justify-start gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/40 text-bambu-blue"
  607. title={t('ams.configureSlot')}
  608. >
  609. <Settings2 className="w-3.5 h-3.5" />
  610. {t('ams.configure')}
  611. </button>
  612. )}
  613. {actions && (
  614. <div className="pt-1 mt-1 border-t border-bambu-dark-tertiary space-y-1">
  615. {actions}
  616. </div>
  617. )}
  618. </div>
  619. )}
  620. </div>
  621. <div className="
  622. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  623. border-l-[5px] border-l-transparent
  624. border-r-[5px] border-r-transparent
  625. border-t-[5px] border-t-bambu-dark-tertiary
  626. " />
  627. </div>,
  628. document.body,
  629. )}
  630. </div>
  631. );
  632. }