FilamentHoverCard.tsx 30 KB

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