FilamentHoverCard.tsx 36 KB

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