FilamentHoverCard.tsx 33 KB

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