FilamentHoverCard.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { useState, useRef, useEffect, type ReactNode } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { Droplets, Link2, Copy, Check, Settings2, ExternalLink } from 'lucide-react';
  4. interface FilamentData {
  5. vendor: 'Bambu Lab' | 'Generic';
  6. profile: string;
  7. colorName: string;
  8. colorHex: string | null;
  9. kFactor: string;
  10. fillLevel: number | null; // null = unknown
  11. trayUuid?: string | null; // Bambu Lab spool UUID for Spoolman linking
  12. }
  13. interface SpoolmanConfig {
  14. enabled: boolean;
  15. onLinkSpool?: (trayUuid: string) => void;
  16. hasUnlinkedSpools?: boolean; // Whether there are spools available to link
  17. linkedSpoolId?: number | null; // Spoolman spool ID if this tray is already linked
  18. spoolmanUrl?: string | null; // Base URL for Spoolman (for "Open in Spoolman" link)
  19. }
  20. interface ConfigureSlotConfig {
  21. enabled: boolean;
  22. onConfigure?: () => void;
  23. }
  24. interface FilamentHoverCardProps {
  25. data: FilamentData;
  26. children: ReactNode;
  27. disabled?: boolean;
  28. className?: string;
  29. spoolman?: SpoolmanConfig;
  30. configureSlot?: ConfigureSlotConfig;
  31. }
  32. /**
  33. * A hover card that displays filament details when hovering over AMS slots.
  34. * Replaces the basic browser tooltip with a styled popover.
  35. */
  36. export function FilamentHoverCard({ data, children, disabled, className = '', spoolman, configureSlot }: FilamentHoverCardProps) {
  37. const { t } = useTranslation();
  38. const [isVisible, setIsVisible] = useState(false);
  39. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  40. const [copied, setCopied] = useState(false);
  41. const triggerRef = useRef<HTMLDivElement>(null);
  42. const cardRef = useRef<HTMLDivElement>(null);
  43. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  44. const handleCopyUuid = () => {
  45. const uuid = data.trayUuid;
  46. if (!uuid) return;
  47. // Try modern clipboard API first, fallback to execCommand
  48. if (navigator.clipboard && window.isSecureContext) {
  49. navigator.clipboard.writeText(uuid).then(() => {
  50. setCopied(true);
  51. setTimeout(() => setCopied(false), 2000);
  52. }).catch(() => {
  53. // Fallback on error
  54. fallbackCopy(uuid);
  55. });
  56. } else {
  57. fallbackCopy(uuid);
  58. }
  59. };
  60. const fallbackCopy = (text: string) => {
  61. const textarea = document.createElement('textarea');
  62. textarea.value = text;
  63. textarea.style.position = 'fixed';
  64. textarea.style.opacity = '0';
  65. document.body.appendChild(textarea);
  66. textarea.select();
  67. try {
  68. document.execCommand('copy');
  69. setCopied(true);
  70. setTimeout(() => setCopied(false), 2000);
  71. } catch {
  72. console.error('Failed to copy to clipboard');
  73. }
  74. document.body.removeChild(textarea);
  75. };
  76. // Calculate position when showing
  77. useEffect(() => {
  78. if (isVisible && triggerRef.current && cardRef.current) {
  79. const triggerRect = triggerRef.current.getBoundingClientRect();
  80. const cardHeight = cardRef.current.offsetHeight;
  81. // Account for fixed header (56px) - space above should exclude header area
  82. const headerHeight = 56;
  83. const spaceAbove = triggerRect.top - headerHeight;
  84. const spaceBelow = window.innerHeight - triggerRect.bottom;
  85. // Prefer top, but flip to bottom if not enough space (accounting for header)
  86. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  87. setPosition('bottom');
  88. } else {
  89. setPosition('top');
  90. }
  91. }
  92. }, [isVisible]);
  93. const handleMouseEnter = () => {
  94. if (disabled) return;
  95. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  96. // Small delay to prevent flicker on quick mouse movements
  97. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  98. };
  99. const handleMouseLeave = () => {
  100. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  101. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  102. };
  103. // Cleanup timeout on unmount
  104. useEffect(() => {
  105. return () => {
  106. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  107. };
  108. }, []);
  109. // Get fill bar color based on percentage
  110. const getFillColor = (fill: number): string => {
  111. if (fill <= 15) return '#ef4444'; // red
  112. if (fill <= 30) return '#f97316'; // orange
  113. if (fill <= 50) return '#eab308'; // yellow
  114. return '#22c55e'; // green
  115. };
  116. // Determine if color is light (for text contrast on swatch)
  117. const isLightColor = (hex: string | null): boolean => {
  118. if (!hex) return false;
  119. const cleanHex = hex.replace('#', '');
  120. const r = parseInt(cleanHex.slice(0, 2), 16);
  121. const g = parseInt(cleanHex.slice(2, 4), 16);
  122. const b = parseInt(cleanHex.slice(4, 6), 16);
  123. const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  124. return luminance > 0.6;
  125. };
  126. const colorHex = data.colorHex ? `#${data.colorHex.replace('#', '')}` : null;
  127. return (
  128. <div
  129. ref={triggerRef}
  130. className={`relative ${className}`}
  131. onMouseEnter={handleMouseEnter}
  132. onMouseLeave={handleMouseLeave}
  133. >
  134. {children}
  135. {/* Hover Card */}
  136. {isVisible && (
  137. <div
  138. ref={cardRef}
  139. className={`
  140. absolute left-1/2 -translate-x-1/2 z-50
  141. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  142. animate-in fade-in-0 zoom-in-95 duration-150
  143. `}
  144. style={{
  145. // Ensure card doesn't go off-screen horizontally
  146. maxWidth: 'calc(100vw - 24px)',
  147. }}
  148. >
  149. {/* Card container */}
  150. <div className="
  151. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  152. rounded-lg shadow-xl overflow-hidden
  153. backdrop-blur-sm
  154. ">
  155. {/* Color swatch header - the hero element */}
  156. <div
  157. className="h-12 relative overflow-hidden"
  158. style={{
  159. backgroundColor: colorHex || '#3d3d3d',
  160. }}
  161. >
  162. {/* Subtle gradient overlay for depth */}
  163. <div className="absolute inset-0 bg-gradient-to-b from-white/10 to-transparent" />
  164. {/* Color name on swatch */}
  165. <div className={`
  166. absolute inset-0 flex items-center justify-center
  167. font-semibold text-sm tracking-wide
  168. ${isLightColor(colorHex) ? 'text-black/80' : 'text-white/90'}
  169. `}>
  170. {data.colorName}
  171. </div>
  172. {/* Vendor badge - solid background for visibility on any color */}
  173. <div className={`
  174. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  175. ${data.vendor === 'Bambu Lab'
  176. ? 'bg-black/60 text-white'
  177. : 'bg-black/50 text-white/90'}
  178. `}>
  179. {data.vendor === 'Bambu Lab' ? 'BBL' : 'GEN'}
  180. </div>
  181. </div>
  182. {/* Details section */}
  183. <div className="p-3 space-y-2.5">
  184. {/* Profile name */}
  185. <div className="flex items-center justify-between">
  186. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  187. {t('ams.profile')}
  188. </span>
  189. <span className="text-xs text-white font-semibold truncate max-w-[120px]">
  190. {data.profile}
  191. </span>
  192. </div>
  193. {/* K Factor */}
  194. <div className="flex items-center justify-between">
  195. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  196. {t('ams.kFactor')}
  197. </span>
  198. <span className="text-xs text-bambu-green font-mono font-bold">
  199. {data.kFactor}
  200. </span>
  201. </div>
  202. {/* Fill Level */}
  203. <div className="space-y-1">
  204. <div className="flex items-center justify-between">
  205. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1">
  206. <Droplets className="w-3 h-3" />
  207. {t('ams.fill')}
  208. </span>
  209. <span className="text-xs text-white font-semibold">
  210. {data.fillLevel !== null ? `${data.fillLevel}%` : '—'}
  211. </span>
  212. </div>
  213. {/* Fill bar */}
  214. <div className="h-1.5 bg-black/40 rounded-full overflow-hidden">
  215. {data.fillLevel !== null ? (
  216. <div
  217. className="h-full rounded-full transition-all duration-300"
  218. style={{
  219. width: `${data.fillLevel}%`,
  220. backgroundColor: getFillColor(data.fillLevel),
  221. }}
  222. />
  223. ) : (
  224. <div className="h-full w-full bg-bambu-gray/30 rounded-full" />
  225. )}
  226. </div>
  227. </div>
  228. {/* Spoolman section - only show if enabled */}
  229. {spoolman?.enabled && data.trayUuid && (
  230. <div className="pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2">
  231. {/* Tray UUID with copy button */}
  232. <div className="flex items-center justify-between">
  233. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  234. {t('spoolman.spoolId')}
  235. </span>
  236. <button
  237. onClick={(e) => {
  238. e.stopPropagation();
  239. handleCopyUuid();
  240. }}
  241. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  242. title="Copy spool UUID"
  243. >
  244. <span className="font-mono text-[10px] truncate max-w-[80px]">
  245. {data.trayUuid.slice(0, 8)}...
  246. </span>
  247. {copied ? (
  248. <Check className="w-3 h-3 text-bambu-green" />
  249. ) : (
  250. <Copy className="w-3 h-3" />
  251. )}
  252. </button>
  253. </div>
  254. {/* Open in Spoolman button (when already linked) */}
  255. {spoolman.linkedSpoolId && spoolman.spoolmanUrl && (
  256. <a
  257. href={`${spoolman.spoolmanUrl.replace(/\/$/, '')}/spool/show/${spoolman.linkedSpoolId}`}
  258. target="_blank"
  259. rel="noopener noreferrer"
  260. onClick={(e) => e.stopPropagation()}
  261. 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"
  262. title={t('spoolman.openInSpoolman')}
  263. >
  264. <ExternalLink className="w-3.5 h-3.5" />
  265. {t('spoolman.openInSpoolman')}
  266. </a>
  267. )}
  268. {/* Link Spool button (when not linked) */}
  269. {!spoolman.linkedSpoolId && spoolman.onLinkSpool && (
  270. <button
  271. onClick={(e) => {
  272. e.stopPropagation();
  273. if (spoolman.hasUnlinkedSpools !== false) {
  274. spoolman.onLinkSpool?.(data.trayUuid!);
  275. }
  276. }}
  277. disabled={spoolman.hasUnlinkedSpools === false}
  278. className={`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors ${
  279. spoolman.hasUnlinkedSpools === false
  280. ? 'bg-bambu-gray/10 text-bambu-gray cursor-not-allowed'
  281. : 'bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green'
  282. }`}
  283. title={spoolman.hasUnlinkedSpools === false ? t('spoolman.noUnlinkedSpools') : t('spoolman.linkToSpoolman')}
  284. >
  285. <Link2 className="w-3.5 h-3.5" />
  286. {t('spoolman.linkToSpoolman')}
  287. </button>
  288. )}
  289. </div>
  290. )}
  291. {/* Configure slot section - always show if enabled */}
  292. {configureSlot?.enabled && (
  293. <div className={`${spoolman?.enabled && data.trayUuid ? '' : 'pt-2 mt-2 border-t border-bambu-dark-tertiary'}`}>
  294. <button
  295. onClick={(e) => {
  296. e.stopPropagation();
  297. configureSlot.onConfigure?.();
  298. }}
  299. 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"
  300. title={t('ams.configureSlot')}
  301. >
  302. <Settings2 className="w-3.5 h-3.5" />
  303. {t('ams.configure')}
  304. </button>
  305. </div>
  306. )}
  307. </div>
  308. </div>
  309. {/* Arrow pointer */}
  310. <div
  311. className={`
  312. absolute left-1/2 -translate-x-1/2 w-0 h-0
  313. border-l-[6px] border-l-transparent
  314. border-r-[6px] border-r-transparent
  315. ${position === 'top'
  316. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  317. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  318. `}
  319. />
  320. </div>
  321. )}
  322. </div>
  323. );
  324. }
  325. interface EmptySlotHoverCardProps {
  326. children: ReactNode;
  327. className?: string;
  328. configureSlot?: ConfigureSlotConfig;
  329. }
  330. /**
  331. * Wrapper for empty slots - shows "Empty" on hover with optional configure button
  332. */
  333. export function EmptySlotHoverCard({ children, className = '', configureSlot }: EmptySlotHoverCardProps) {
  334. const { t } = useTranslation();
  335. const [isVisible, setIsVisible] = useState(false);
  336. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  337. const handleMouseEnter = () => {
  338. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  339. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  340. };
  341. const handleMouseLeave = () => {
  342. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  343. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  344. };
  345. useEffect(() => {
  346. return () => {
  347. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  348. };
  349. }, []);
  350. return (
  351. <div
  352. className={`relative ${className}`}
  353. onMouseEnter={handleMouseEnter}
  354. onMouseLeave={handleMouseLeave}
  355. >
  356. {children}
  357. {isVisible && (
  358. <div className="
  359. absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50
  360. animate-in fade-in-0 zoom-in-95 duration-150
  361. ">
  362. <div className="
  363. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  364. rounded-md shadow-lg overflow-hidden
  365. ">
  366. <div className="px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap">
  367. {t('ams.emptySlot')}
  368. </div>
  369. {/* Configure slot button */}
  370. {configureSlot?.enabled && (
  371. <div className="px-2 pb-2">
  372. <button
  373. onClick={(e) => {
  374. e.stopPropagation();
  375. configureSlot.onConfigure?.();
  376. }}
  377. 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"
  378. title={t('ams.configureSlot')}
  379. >
  380. <Settings2 className="w-3.5 h-3.5" />
  381. {t('ams.configure')}
  382. </button>
  383. </div>
  384. )}
  385. </div>
  386. <div className="
  387. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  388. border-l-[5px] border-l-transparent
  389. border-r-[5px] border-r-transparent
  390. border-t-[5px] border-t-bambu-dark-tertiary
  391. " />
  392. </div>
  393. )}
  394. </div>
  395. );
  396. }