FilamentHoverCard.tsx 32 KB

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