FilamentHoverCard.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import { useState, useRef, useEffect, type ReactNode } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { Droplets, Link2, Copy, Check, Settings2, ExternalLink, Package, Unlink } from 'lucide-react';
  4. import { isLightColor } from '../utils/colors';
  5. interface FilamentData {
  6. vendor: 'Bambu Lab' | 'Generic';
  7. profile: string;
  8. colorName: string;
  9. colorHex: string | null;
  10. kFactor: string;
  11. fillLevel: number | null; // null = unknown
  12. trayUuid?: string | null; // Bambu Lab spool UUID for Spoolman linking
  13. tagUid?: string | null; // Generic NFC tag UID fallback for linking
  14. fillSource?: 'ams' | 'spoolman' | 'inventory'; // Source of fill level data
  15. }
  16. interface SpoolmanConfig {
  17. enabled: boolean;
  18. onLinkSpool?: () => void;
  19. onUnlinkSpool?: () => void;
  20. linkedSpoolId?: number | null; // Spoolman spool ID if this tray is already linked
  21. spoolmanUrl?: string | null; // Base URL for Spoolman (for "Open in Spoolman" link)
  22. syncMode?: string | null; // If auto-sync is enabled, we may want to hide the unlink option for Bambu spools
  23. }
  24. interface InventoryConfig {
  25. onAssignSpool?: () => void;
  26. onUnassignSpool?: () => void;
  27. assignedSpool?: { id: number; material: string; brand: string | null; color_name: string | null; remainingWeightGrams?: number | null } | null;
  28. }
  29. interface ConfigureSlotConfig {
  30. enabled: boolean;
  31. onConfigure?: () => void;
  32. }
  33. interface FilamentHoverCardProps {
  34. data: FilamentData;
  35. children: ReactNode;
  36. disabled?: boolean;
  37. className?: string;
  38. spoolman?: SpoolmanConfig;
  39. inventory?: InventoryConfig;
  40. configureSlot?: ConfigureSlotConfig;
  41. }
  42. /**
  43. * A hover card that displays filament details when hovering over AMS slots.
  44. * Replaces the basic browser tooltip with a styled popover.
  45. */
  46. export function FilamentHoverCard({ data, children, disabled, className = '', spoolman, inventory, configureSlot }: FilamentHoverCardProps) {
  47. const { t } = useTranslation();
  48. const [isVisible, setIsVisible] = useState(false);
  49. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  50. const [copied, setCopied] = useState(false);
  51. const [showUnlinkConfirm, setShowUnlinkConfirm] = useState(false);
  52. const triggerRef = useRef<HTMLDivElement>(null);
  53. const cardRef = useRef<HTMLDivElement>(null);
  54. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  55. const handleCopyUuid = () => {
  56. const uuid = data.trayUuid;
  57. if (!uuid) return;
  58. // Try modern clipboard API first, fallback to execCommand
  59. if (navigator.clipboard && window.isSecureContext) {
  60. navigator.clipboard.writeText(uuid).then(() => {
  61. setCopied(true);
  62. setTimeout(() => setCopied(false), 2000);
  63. }).catch(() => {
  64. // Fallback on error
  65. fallbackCopy(uuid);
  66. });
  67. } else {
  68. fallbackCopy(uuid);
  69. }
  70. };
  71. const fallbackCopy = (text: string) => {
  72. const textarea = document.createElement('textarea');
  73. textarea.value = text;
  74. textarea.style.position = 'fixed';
  75. textarea.style.opacity = '0';
  76. document.body.appendChild(textarea);
  77. textarea.select();
  78. try {
  79. document.execCommand('copy');
  80. setCopied(true);
  81. setTimeout(() => setCopied(false), 2000);
  82. } catch {
  83. console.error('Failed to copy to clipboard');
  84. }
  85. document.body.removeChild(textarea);
  86. };
  87. // Calculate position when showing
  88. useEffect(() => {
  89. if (isVisible && triggerRef.current && cardRef.current) {
  90. const triggerRect = triggerRef.current.getBoundingClientRect();
  91. const cardHeight = cardRef.current.offsetHeight;
  92. // Account for fixed header (56px) - space above should exclude header area
  93. const headerHeight = 56;
  94. const spaceAbove = triggerRect.top - headerHeight;
  95. const spaceBelow = window.innerHeight - triggerRect.bottom;
  96. // Prefer top, but flip to bottom if not enough space (accounting for header)
  97. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  98. setPosition('bottom');
  99. } else {
  100. setPosition('top');
  101. }
  102. }
  103. }, [isVisible]);
  104. const handleMouseEnter = () => {
  105. if (disabled) return;
  106. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  107. // Small delay to prevent flicker on quick mouse movements
  108. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  109. };
  110. const handleMouseLeave = () => {
  111. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  112. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  113. };
  114. // Cleanup timeout on unmount
  115. useEffect(() => {
  116. return () => {
  117. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  118. };
  119. }, []);
  120. // Get fill bar color based on percentage
  121. const getFillColor = (fill: number): string => {
  122. if (fill <= 15) return '#ef4444'; // red
  123. if (fill <= 30) return '#f97316'; // orange
  124. if (fill <= 50) return '#eab308'; // yellow
  125. return '#22c55e'; // green
  126. };
  127. const colorHex = data.colorHex ? `#${data.colorHex.replace('#', '')}` : null;
  128. const assignedRemainingWeight = inventory?.assignedSpool?.remainingWeightGrams ?? null;
  129. return (
  130. <div
  131. ref={triggerRef}
  132. className={`relative ${className}`}
  133. onMouseEnter={handleMouseEnter}
  134. onMouseLeave={handleMouseLeave}
  135. >
  136. {children}
  137. {/* Hover Card */}
  138. {isVisible && (
  139. <div
  140. ref={cardRef}
  141. className={`
  142. absolute left-1/2 -translate-x-1/2 z-[60]
  143. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  144. animate-in fade-in-0 zoom-in-95 duration-150
  145. `}
  146. style={{
  147. // Ensure card doesn't go off-screen horizontally
  148. maxWidth: 'calc(100vw - 24px)',
  149. }}
  150. >
  151. {/* Card container */}
  152. <div className="
  153. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  154. rounded-lg shadow-xl overflow-hidden
  155. backdrop-blur-sm
  156. ">
  157. {/* Color swatch header - the hero element */}
  158. <div
  159. className="h-12 relative overflow-hidden"
  160. style={{
  161. backgroundColor: colorHex || '#3d3d3d',
  162. }}
  163. >
  164. {/* Subtle gradient overlay for depth */}
  165. <div className="absolute inset-0 bg-gradient-to-b from-white/10 to-transparent" />
  166. {/* Color name on swatch */}
  167. <div className={`
  168. absolute inset-0 flex items-center justify-center
  169. font-semibold text-sm tracking-wide
  170. ${isLightColor(colorHex) ? 'text-black/80' : 'text-white/90'}
  171. `}>
  172. {data.colorName}
  173. </div>
  174. {/* Vendor badge - solid background for visibility on any color */}
  175. <div className={`
  176. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  177. ${data.vendor === 'Bambu Lab'
  178. ? 'bg-black/60 text-white'
  179. : 'bg-black/50 text-white/90'}
  180. `}>
  181. {data.vendor === 'Bambu Lab' ? 'BBL' : 'GEN'}
  182. </div>
  183. </div>
  184. {/* Details section */}
  185. <div className="p-3 space-y-2.5">
  186. {/* Profile name */}
  187. <div className="flex items-center justify-between">
  188. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  189. {t('ams.profile')}
  190. </span>
  191. <span className="text-xs text-white font-semibold truncate max-w-[120px]">
  192. {data.profile}
  193. </span>
  194. </div>
  195. {/* K Factor */}
  196. <div className="flex items-center justify-between">
  197. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  198. {t('ams.kFactor')}
  199. </span>
  200. <span className="text-xs text-bambu-green font-mono font-bold">
  201. {data.kFactor}
  202. </span>
  203. </div>
  204. {/* Fill Level */}
  205. <div className="space-y-1">
  206. <div className="flex items-center justify-between">
  207. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1">
  208. <Droplets className="w-3 h-3" />
  209. {t('ams.fill')}
  210. </span>
  211. <span className="text-xs text-white font-semibold flex items-center gap-1">
  212. <span>{data.fillLevel !== null ? `${data.fillLevel}%` : '—'}</span>
  213. {assignedRemainingWeight !== null && data.fillLevel !== null && (
  214. <span className="text-[9px] text-bambu-gray font-normal">• {assignedRemainingWeight}g</span>
  215. )}
  216. {data.fillSource === 'spoolman' && data.fillLevel !== null && (
  217. <span className="text-[9px] text-bambu-gray font-normal">{t('spoolman.fillSourceLabel')}</span>
  218. )}
  219. {data.fillSource === 'inventory' && data.fillLevel !== null && (
  220. <span className="text-[9px] text-bambu-gray font-normal">{t('inventory.fillSourceLabel')}</span>
  221. )}
  222. </span>
  223. </div>
  224. {/* Fill bar */}
  225. <div className="h-1.5 bg-black/40 rounded-full overflow-hidden">
  226. {data.fillLevel !== null ? (
  227. <div
  228. className="h-full rounded-full transition-all duration-300"
  229. style={{
  230. width: `${data.fillLevel}%`,
  231. backgroundColor: getFillColor(data.fillLevel),
  232. }}
  233. />
  234. ) : (
  235. <div className="h-full w-full bg-bambu-gray/30 rounded-full" />
  236. )}
  237. </div>
  238. </div>
  239. {/* Spoolman section - only show if enabled */}
  240. {spoolman?.enabled && (
  241. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  242. {/* Tray UUID with copy button */}
  243. <div className="flex items-center justify-between">
  244. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  245. {t('spoolman.spoolId')}
  246. </span>
  247. {data.trayUuid ? (
  248. <button
  249. onClick={(e) => {
  250. e.stopPropagation();
  251. handleCopyUuid();
  252. }}
  253. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  254. title="Copy spool UUID"
  255. >
  256. <span className="font-mono text-[10px] truncate max-w-[80px]">
  257. {data.trayUuid.slice(0, 8)}...
  258. </span>
  259. {copied ? (
  260. <Check className="w-3 h-3 text-bambu-green" />
  261. ) : (
  262. <Copy className="w-3 h-3" />
  263. )}
  264. </button>
  265. ) : (
  266. <span className="text-[10px] text-bambu-gray">—</span>
  267. )}
  268. </div>
  269. {/* Open in Spoolman button (when already linked) */}
  270. {spoolman.linkedSpoolId && spoolman.spoolmanUrl && (
  271. <>
  272. <a
  273. href={`${spoolman.spoolmanUrl.replace(/\/$/, '')}/spool/show/${spoolman.linkedSpoolId}`}
  274. target="_blank"
  275. rel="noopener noreferrer"
  276. onClick={(e) => e.stopPropagation()}
  277. 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"
  278. title={t('spoolman.openInSpoolman')}
  279. >
  280. <ExternalLink className="w-3.5 h-3.5" />
  281. {t('spoolman.openInSpoolman')}
  282. </a>
  283. {spoolman.onUnlinkSpool && (data.vendor !== 'Bambu Lab' || spoolman.syncMode === 'manual') && (
  284. <button
  285. onClick={(e) => {
  286. e.stopPropagation();
  287. setShowUnlinkConfirm(true);
  288. }}
  289. 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"
  290. title={t('spoolman.unlinkSpool')}
  291. >
  292. <Unlink className="w-3.5 h-3.5" />
  293. {t('spoolman.unlinkSpool')}
  294. </button>
  295. )}
  296. </>
  297. )}
  298. {/* Link Spool button (when not linked) */}
  299. {!spoolman.linkedSpoolId && (
  300. <button
  301. onClick={(e) => {
  302. e.stopPropagation();
  303. if (spoolman.onLinkSpool) {
  304. spoolman.onLinkSpool?.();
  305. }
  306. }}
  307. disabled={!spoolman.onLinkSpool}
  308. className={`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors ${
  309. !spoolman.onLinkSpool
  310. ? 'bg-bambu-gray/10 text-bambu-gray cursor-not-allowed'
  311. : 'bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green'
  312. }`}
  313. >
  314. <Link2 className="w-3.5 h-3.5" />
  315. {t('spoolman.linkToSpoolman')}
  316. </button>
  317. )}
  318. </div>
  319. )}
  320. {/* Inventory section — shown for every vendor including
  321. Bambu Lab (#1133). The earlier "non-Bambu only" gate
  322. prevented users from manually assigning a Bambu spool
  323. in inventory to an AMS slot when they didn't want to
  324. re-scan via SpoolBuddy NFC. */}
  325. {inventory && (
  326. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  327. {inventory.assignedSpool ? (
  328. <>
  329. <div className="flex items-center gap-1.5">
  330. <Package className="w-3 h-3 text-bambu-green" />
  331. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  332. {t('inventory.assigned')}
  333. </span>
  334. </div>
  335. <p className="text-xs text-white truncate">
  336. {inventory.assignedSpool.brand ? `${inventory.assignedSpool.brand} ` : ''}
  337. {inventory.assignedSpool.material}
  338. {inventory.assignedSpool.color_name ? ` - ${inventory.assignedSpool.color_name}` : ''}
  339. </p>
  340. {inventory.onUnassignSpool && (
  341. <button
  342. onClick={(e) => {
  343. e.stopPropagation();
  344. inventory.onUnassignSpool?.();
  345. }}
  346. 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"
  347. >
  348. <Unlink className="w-3.5 h-3.5" />
  349. {t('inventory.unassignSpool')}
  350. </button>
  351. )}
  352. </>
  353. ) : inventory.onAssignSpool ? (
  354. <button
  355. onClick={(e) => {
  356. e.stopPropagation();
  357. inventory.onAssignSpool?.();
  358. }}
  359. 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"
  360. >
  361. <Package className="w-3.5 h-3.5" />
  362. {t('inventory.assignSpool')}
  363. </button>
  364. ) : null}
  365. </div>
  366. )}
  367. {/* Configure slot section - always show if enabled */}
  368. {configureSlot?.enabled && (
  369. <div className={`${spoolman?.enabled && data.trayUuid ? '' : 'pt-2 mt-2 border-t border-bambu-dark-tertiary'}`}>
  370. <button
  371. onClick={(e) => {
  372. e.stopPropagation();
  373. configureSlot.onConfigure?.();
  374. }}
  375. 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"
  376. title={t('ams.configureSlot')}
  377. >
  378. <Settings2 className="w-3.5 h-3.5" />
  379. {t('ams.configure')}
  380. </button>
  381. </div>
  382. )}
  383. </div>
  384. </div>
  385. {/* Arrow pointer */}
  386. <div
  387. className={`
  388. absolute left-1/2 -translate-x-1/2 w-0 h-0
  389. border-l-[6px] border-l-transparent
  390. border-r-[6px] border-r-transparent
  391. ${position === 'top'
  392. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  393. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  394. `}
  395. />
  396. </div>
  397. )}
  398. {/* Unlink Confirmation Dialog */}
  399. {showUnlinkConfirm && (
  400. <div className="fixed inset-0 z-[100] flex items-center justify-center" onClick={() => setShowUnlinkConfirm(false)}>
  401. <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
  402. <div
  403. className="relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary"
  404. onClick={(e) => e.stopPropagation()}
  405. >
  406. <div className="p-4 space-y-4">
  407. <div className="space-y-2">
  408. <h3 className="text-base font-semibold text-white">
  409. {t('spoolman.unlinkConfirmTitle')}
  410. </h3>
  411. <p className="text-sm text-bambu-gray">
  412. {t('spoolman.unlinkConfirmMessage')}
  413. </p>
  414. </div>
  415. <div className="flex gap-2">
  416. <button
  417. onClick={() => setShowUnlinkConfirm(false)}
  418. className="flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white"
  419. >
  420. {t('common.cancel')}
  421. </button>
  422. <button
  423. onClick={() => {
  424. spoolman?.onUnlinkSpool?.();
  425. setShowUnlinkConfirm(false);
  426. }}
  427. 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"
  428. >
  429. {t('spoolman.unlinkSpool')}
  430. </button>
  431. </div>
  432. </div>
  433. </div>
  434. </div>
  435. )}
  436. </div>
  437. );
  438. }
  439. interface EmptySlotHoverCardProps {
  440. children: ReactNode;
  441. className?: string;
  442. configureSlot?: ConfigureSlotConfig;
  443. }
  444. /**
  445. * Wrapper for empty slots - shows "Empty" on hover with optional configure button.
  446. *
  447. * The "Assign spool" affordance was removed from empty slots in #1133: a
  448. * physically empty slot has no spool to attach to, and offering the
  449. * action there only led to users assigning the wrong spool to a slot
  450. * the printer hadn't actually loaded yet. Assignment now requires a
  451. * loaded slot (which renders FilamentHoverCard, where the button lives).
  452. */
  453. export function EmptySlotHoverCard({ children, className = '', configureSlot }: EmptySlotHoverCardProps) {
  454. const { t } = useTranslation();
  455. const [isVisible, setIsVisible] = useState(false);
  456. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  457. const handleMouseEnter = () => {
  458. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  459. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  460. };
  461. const handleMouseLeave = () => {
  462. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  463. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  464. };
  465. useEffect(() => {
  466. return () => {
  467. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  468. };
  469. }, []);
  470. return (
  471. <div
  472. className={`relative ${className}`}
  473. onMouseEnter={handleMouseEnter}
  474. onMouseLeave={handleMouseLeave}
  475. >
  476. {children}
  477. {isVisible && (
  478. <div className="
  479. absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50
  480. animate-in fade-in-0 zoom-in-95 duration-150
  481. ">
  482. <div className="
  483. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  484. rounded-md shadow-lg overflow-hidden
  485. ">
  486. <div className="px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap">
  487. {t('ams.emptySlot')}
  488. </div>
  489. {/* Configure slot button */}
  490. {configureSlot?.enabled && (
  491. <div className="px-2 pb-2">
  492. <button
  493. onClick={(e) => {
  494. e.stopPropagation();
  495. configureSlot.onConfigure?.();
  496. }}
  497. 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"
  498. title={t('ams.configureSlot')}
  499. >
  500. <Settings2 className="w-3.5 h-3.5" />
  501. {t('ams.configure')}
  502. </button>
  503. </div>
  504. )}
  505. </div>
  506. <div className="
  507. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  508. border-l-[5px] border-l-transparent
  509. border-r-[5px] border-r-transparent
  510. border-t-[5px] border-t-bambu-dark-tertiary
  511. " />
  512. </div>
  513. )}
  514. </div>
  515. );
  516. }