FilamentHoverCard.tsx 34 KB

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