FilamentHoverCard.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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. // Cleanup timeout on unmount
  147. useEffect(() => {
  148. return () => {
  149. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  150. };
  151. }, []);
  152. // Get fill bar color based on percentage
  153. const getFillColor = (fill: number): string => {
  154. if (fill <= 15) return '#ef4444'; // red
  155. if (fill <= 30) return '#f97316'; // orange
  156. if (fill <= 50) return '#eab308'; // yellow
  157. return '#22c55e'; // green
  158. };
  159. const colorHex = data.colorHex ? `#${data.colorHex.replace('#', '')}` : null;
  160. const assignedRemainingWeight = inventory?.assignedSpool?.remainingWeightGrams ?? null;
  161. return (
  162. <div
  163. ref={triggerRef}
  164. data-testid="filament-slot"
  165. className={`relative ${className}`}
  166. onMouseEnter={handleMouseEnter}
  167. onMouseLeave={handleMouseLeave}
  168. >
  169. {children}
  170. {/* Portaled hover card — rendered into document.body so it escapes
  171. any ancestor stacking context. Sibling printer cards on the
  172. dashboard create their own stacking contexts; without the portal
  173. the popover gets covered by the next card even at z-[60]
  174. (#1336 follow-up). */}
  175. {isVisible && createPortal(
  176. <div
  177. ref={cardRef}
  178. className="fixed z-[60]"
  179. style={{
  180. top: coords?.top ?? -9999,
  181. left: coords?.left ?? -9999,
  182. maxWidth: 'calc(100vw - 24px)',
  183. // Hide until coords are computed to avoid a (-9999,-9999) flash.
  184. visibility: coords ? 'visible' : 'hidden',
  185. }}
  186. onMouseEnter={handleMouseEnter}
  187. onMouseLeave={handleMouseLeave}
  188. >
  189. {/* Card container */}
  190. <div className="
  191. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  192. rounded-lg shadow-xl overflow-hidden
  193. backdrop-blur-sm
  194. ">
  195. {/* Color swatch header - the hero element */}
  196. <div
  197. className="h-12 relative overflow-hidden"
  198. style={{
  199. backgroundColor: colorHex || '#3d3d3d',
  200. }}
  201. >
  202. {/* Subtle gradient overlay for depth */}
  203. <div className="absolute inset-0 bg-gradient-to-b from-white/10 to-transparent" />
  204. {/* Color name on swatch */}
  205. <div className={`
  206. absolute inset-0 flex items-center justify-center
  207. font-semibold text-sm tracking-wide
  208. ${isLightColor(colorHex) ? 'text-black/80' : 'text-white/90'}
  209. `}>
  210. {data.colorName}
  211. </div>
  212. {/* Vendor badge - solid background for visibility on any color */}
  213. <div className={`
  214. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  215. ${data.vendor === 'Bambu Lab'
  216. ? 'bg-black/60 text-white'
  217. : 'bg-black/50 text-white/90'}
  218. `}>
  219. {data.vendor === 'Bambu Lab' ? 'BBL' : 'GEN'}
  220. </div>
  221. </div>
  222. {/* Details section */}
  223. <div className="p-3 space-y-2.5">
  224. {/* Profile name */}
  225. <div className="flex items-center justify-between">
  226. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  227. {t('ams.profile')}
  228. </span>
  229. <span className="text-xs text-white font-semibold truncate max-w-[120px]">
  230. {data.profile}
  231. </span>
  232. </div>
  233. {/* K Factor */}
  234. <div className="flex items-center justify-between">
  235. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  236. {t('ams.kFactor')}
  237. </span>
  238. <span className="text-xs text-bambu-green font-mono font-bold">
  239. {data.kFactor}
  240. </span>
  241. </div>
  242. {/* Fill Level */}
  243. <div className="space-y-1">
  244. <div className="flex items-center justify-between">
  245. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1">
  246. <Droplets className="w-3 h-3" />
  247. {t('ams.fill')}
  248. </span>
  249. <span className="text-xs text-white font-semibold flex items-center gap-1">
  250. <span>{data.fillLevel !== null ? `${data.fillLevel}%` : '—'}</span>
  251. {assignedRemainingWeight !== null && data.fillLevel !== null && (
  252. <span className="text-[9px] text-bambu-gray font-normal">• {assignedRemainingWeight}g</span>
  253. )}
  254. </span>
  255. </div>
  256. {/* Fill bar */}
  257. <div className="h-1.5 bg-black/40 rounded-full overflow-hidden">
  258. {data.fillLevel !== null ? (
  259. <div
  260. className="h-full rounded-full transition-all duration-300"
  261. style={{
  262. width: `${data.fillLevel}%`,
  263. backgroundColor: getFillColor(data.fillLevel),
  264. }}
  265. />
  266. ) : (
  267. <div className="h-full w-full bg-bambu-gray/30 rounded-full" />
  268. )}
  269. </div>
  270. </div>
  271. {/* Spoolman section - only show if enabled */}
  272. {spoolman?.enabled && (
  273. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  274. {/* Tray UUID with copy button */}
  275. <div className="flex items-center justify-between">
  276. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  277. {t('spoolman.spoolId')}
  278. </span>
  279. {data.trayUuid ? (
  280. <button
  281. onClick={(e) => {
  282. e.stopPropagation();
  283. handleCopyUuid();
  284. }}
  285. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  286. title="Copy spool UUID"
  287. >
  288. <span className="font-mono text-[10px] truncate max-w-[80px]">
  289. {data.trayUuid.slice(0, 8)}...
  290. </span>
  291. {copied ? (
  292. <Check className="w-3 h-3 text-bambu-green" />
  293. ) : (
  294. <Copy className="w-3 h-3" />
  295. )}
  296. </button>
  297. ) : (
  298. <span className="text-[10px] text-bambu-gray">—</span>
  299. )}
  300. </div>
  301. {/* Open in inventory button (when already linked to a Spoolman spool) */}
  302. {spoolman.linkedSpoolId && (
  303. <>
  304. <button
  305. onClick={(e) => {
  306. e.stopPropagation();
  307. navigate(`/inventory?spool=${spoolman.linkedSpoolId}`);
  308. }}
  309. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green"
  310. title={t('inventory.openInInventory')}
  311. >
  312. <Package className="w-3.5 h-3.5" />
  313. {t('inventory.openInInventory')}
  314. </button>
  315. </>
  316. )}
  317. {/* Link/Unlink action buttons intentionally NOT rendered
  318. here. The inventory section below already provides
  319. Assign/Unassign for slot-binding (the primary user
  320. flow in Spoolman mode). Showing the spoolman tag-link
  321. buttons in addition surfaced two red Unlink-icon
  322. buttons for what users perceive as the same action,
  323. regardless of whether the labels said "Unlink Spool"
  324. vs "Unassign Spool". Tag-linking remains available
  325. via dedicated UI (LinkSpoolModal can be opened from
  326. Spoolman settings / inventory page). */}
  327. </div>
  328. )}
  329. {/* Inventory section — shown for every vendor including
  330. Bambu Lab (#1133). The earlier "non-Bambu only" gate
  331. prevented users from manually assigning a Bambu spool
  332. in inventory to an AMS slot when they didn't want to
  333. re-scan via SpoolBuddy NFC. */}
  334. {inventory && (
  335. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  336. {inventory.assignedSpool ? (
  337. <>
  338. <div className="flex items-center gap-1.5">
  339. <Package className="w-3 h-3 text-bambu-green" />
  340. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  341. {t('inventory.assigned')}
  342. </span>
  343. </div>
  344. <div className="flex items-baseline gap-1.5 min-w-0 mb-1">
  345. <p className="text-xs text-white truncate">
  346. {inventory.assignedSpool.brand ? `${inventory.assignedSpool.brand} ` : ''}
  347. {inventory.assignedSpool.material}
  348. {inventory.assignedSpool.color_name ? ` - ${inventory.assignedSpool.color_name}` : ''}
  349. </p>
  350. <span className="text-[10px] font-mono text-bambu-gray shrink-0">#{inventory.assignedSpool.id}</span>
  351. </div>
  352. {(!spoolman?.linkedSpoolId || inventory.assignedSpool!.id !== spoolman.linkedSpoolId) && (
  353. <button
  354. onClick={(e) => {
  355. e.stopPropagation();
  356. navigate(`/inventory?spool=${inventory.assignedSpool!.id}`);
  357. }}
  358. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green"
  359. title={t('inventory.openInInventory')}
  360. >
  361. <Package className="w-3.5 h-3.5" />
  362. {t('inventory.openInInventory')}
  363. </button>
  364. )}
  365. {inventory.onUnassignSpool && (
  366. <button
  367. onClick={(e) => {
  368. e.stopPropagation();
  369. inventory.onUnassignSpool?.();
  370. }}
  371. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400"
  372. >
  373. <Unlink className="w-3.5 h-3.5" />
  374. {t('inventory.unassignSpool')}
  375. </button>
  376. )}
  377. </>
  378. ) : inventory.onAssignSpool ? (
  379. <button
  380. onClick={inventory.isAssigned ? undefined : (e) => {
  381. e.stopPropagation();
  382. inventory.onAssignSpool?.();
  383. }}
  384. disabled={!!inventory.isAssigned}
  385. className={`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 text-bambu-blue ${
  386. inventory.isAssigned ? 'opacity-50 cursor-not-allowed' : 'hover:bg-bambu-blue/30'
  387. }`}
  388. >
  389. <Package className="w-3.5 h-3.5" />
  390. {t('inventory.assignSpool')}
  391. </button>
  392. ) : null}
  393. </div>
  394. )}
  395. {/* Configure slot section - always show if enabled */}
  396. {configureSlot?.enabled && (
  397. <div className={`${spoolman?.enabled && data.trayUuid ? '' : 'pt-2 mt-2 border-t border-bambu-dark-tertiary'}`}>
  398. <button
  399. onClick={(e) => {
  400. e.stopPropagation();
  401. configureSlot.onConfigure?.();
  402. }}
  403. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue"
  404. title={t('ams.configureSlot')}
  405. >
  406. <Settings2 className="w-3.5 h-3.5" />
  407. {t('ams.configure')}
  408. </button>
  409. </div>
  410. )}
  411. {actions && (
  412. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-1">
  413. {actions}
  414. </div>
  415. )}
  416. </div>
  417. </div>
  418. {/* Arrow pointer */}
  419. <div
  420. className={`
  421. absolute left-1/2 -translate-x-1/2 w-0 h-0
  422. border-l-[6px] border-l-transparent
  423. border-r-[6px] border-r-transparent
  424. ${position === 'top'
  425. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  426. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  427. `}
  428. />
  429. </div>,
  430. document.body,
  431. )}
  432. {/* Unlink Confirmation Dialog */}
  433. {showUnlinkConfirm && (
  434. <div className="fixed inset-0 z-[100] flex items-center justify-center" onClick={() => setShowUnlinkConfirm(false)}>
  435. <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
  436. <div
  437. className="relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary"
  438. onClick={(e) => e.stopPropagation()}
  439. >
  440. <div className="p-4 space-y-4">
  441. <div className="space-y-2">
  442. <h3 className="text-base font-semibold text-white">
  443. {t('spoolman.unlinkConfirmTitle')}
  444. </h3>
  445. <p className="text-sm text-bambu-gray">
  446. {t('spoolman.unlinkConfirmMessage')}
  447. </p>
  448. </div>
  449. <div className="flex gap-2">
  450. <button
  451. onClick={() => setShowUnlinkConfirm(false)}
  452. className="flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white"
  453. >
  454. {t('common.cancel')}
  455. </button>
  456. <button
  457. onClick={() => {
  458. spoolman?.onUnlinkSpool?.();
  459. setShowUnlinkConfirm(false);
  460. }}
  461. className="flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400"
  462. >
  463. {t('inventory.unassignSpool')}
  464. </button>
  465. </div>
  466. </div>
  467. </div>
  468. </div>
  469. )}
  470. </div>
  471. );
  472. }
  473. interface EmptySlotHoverCardProps {
  474. children: ReactNode;
  475. className?: string;
  476. configureSlot?: ConfigureSlotConfig;
  477. onAssignSpool?: () => void;
  478. actions?: ReactNode;
  479. // #1322 follow-up: distinguish firmware-confirmed empty (state 9/10) from
  480. // a user reset where the firmware still has a spool registered. "reset"
  481. // surfaces the user-cleared label; undefined / "physical" keeps the
  482. // historical "Empty slot" wording.
  483. kind?: 'physical' | 'reset';
  484. }
  485. export function EmptySlotHoverCard({ children, className = '', configureSlot, onAssignSpool, actions, kind }: EmptySlotHoverCardProps) {
  486. const { t } = useTranslation();
  487. const [isVisible, setIsVisible] = useState(false);
  488. // Screen-space coords for the portaled card — same pattern as
  489. // FilamentHoverCard, see comment there (#1336 follow-up).
  490. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  491. const triggerRef = useRef<HTMLDivElement>(null);
  492. const cardRef = useRef<HTMLDivElement>(null);
  493. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  494. const handleMouseEnter = () => {
  495. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  496. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  497. };
  498. const handleMouseLeave = () => {
  499. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  500. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  501. };
  502. useEffect(() => {
  503. return () => {
  504. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  505. };
  506. }, []);
  507. useLayoutEffect(() => {
  508. if (!isVisible) {
  509. setCoords(null);
  510. return;
  511. }
  512. const compute = () => {
  513. if (!triggerRef.current || !cardRef.current) return;
  514. const triggerRect = triggerRef.current.getBoundingClientRect();
  515. const cardHeight = cardRef.current.offsetHeight;
  516. const cardWidth = cardRef.current.offsetWidth;
  517. const centerX = triggerRect.left + triggerRect.width / 2;
  518. const left = Math.max(8, Math.min(centerX - cardWidth / 2, window.innerWidth - cardWidth - 8));
  519. const top = triggerRect.top - cardHeight - 8;
  520. setCoords({ top, left });
  521. };
  522. compute();
  523. const rafId = requestAnimationFrame(compute);
  524. window.addEventListener('scroll', compute, true);
  525. window.addEventListener('resize', compute);
  526. return () => {
  527. cancelAnimationFrame(rafId);
  528. window.removeEventListener('scroll', compute, true);
  529. window.removeEventListener('resize', compute);
  530. };
  531. }, [isVisible]);
  532. return (
  533. <div
  534. ref={triggerRef}
  535. className={`relative ${className}`}
  536. onMouseEnter={handleMouseEnter}
  537. onMouseLeave={handleMouseLeave}
  538. >
  539. {children}
  540. {isVisible && createPortal(
  541. <div
  542. ref={cardRef}
  543. className="fixed z-[60]"
  544. style={{
  545. top: coords?.top ?? -9999,
  546. left: coords?.left ?? -9999,
  547. visibility: coords ? 'visible' : 'hidden',
  548. }}
  549. onMouseEnter={handleMouseEnter}
  550. onMouseLeave={handleMouseLeave}
  551. >
  552. <div className="
  553. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  554. rounded-md shadow-lg overflow-hidden
  555. ">
  556. <div className="px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap">
  557. {kind === 'reset' ? t('ams.emptySlotReset') : t('ams.emptySlot')}
  558. </div>
  559. {/* Configure slot button */}
  560. {(configureSlot?.enabled || onAssignSpool || actions) && (
  561. <div className="px-2 pb-2 space-y-1">
  562. {configureSlot?.enabled && (
  563. <button
  564. onClick={(e) => {
  565. e.stopPropagation();
  566. configureSlot.onConfigure?.();
  567. }}
  568. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue"
  569. title={t('ams.configureSlot')}
  570. >
  571. <Settings2 className="w-3.5 h-3.5" />
  572. {t('ams.configure')}
  573. </button>
  574. )}
  575. {onAssignSpool && (
  576. <button
  577. onClick={(e) => { e.stopPropagation(); onAssignSpool(); }}
  578. className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue"
  579. >
  580. <Package className="w-3.5 h-3.5" />
  581. {t('inventory.assignSpool')}
  582. </button>
  583. )}
  584. {actions && (
  585. <div className="pt-1 mt-1 border-t border-bambu-dark-tertiary space-y-1">
  586. {actions}
  587. </div>
  588. )}
  589. </div>
  590. )}
  591. </div>
  592. <div className="
  593. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  594. border-l-[5px] border-l-transparent
  595. border-r-[5px] border-r-transparent
  596. border-t-[5px] border-t-bambu-dark-tertiary
  597. " />
  598. </div>,
  599. document.body,
  600. )}
  601. </div>
  602. );
  603. }