ModelViewerModal.tsx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. import { useState, useEffect, useRef, useMemo, type ReactNode } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery } from '@tanstack/react-query';
  4. import { X, ExternalLink, Box, Cog, Loader2, Layers, Check, Maximize2, Minimize2, ChevronDown } from 'lucide-react';
  5. import { ModelViewer } from './ModelViewer';
  6. import { Button } from './Button';
  7. import { api, withMediaToken } from '../api/client';
  8. import { useToast } from '../contexts/ToastContext';
  9. import { isApiSliceableFileType, isSliceableFileType, openInSlicer, resolveDesktopSlicer, type SlicerType } from '../utils/slicer';
  10. import type { ArchivePlatesResponse, LibraryFilePlatesResponse, PlateMetadata } from '../types/plates';
  11. // The modal shows the model only; G-code has its own full-page viewer.
  12. type ViewTab = '3d';
  13. interface ModelViewerModalProps {
  14. archiveId?: number;
  15. libraryFileId?: number;
  16. title: string;
  17. fileType?: string;
  18. onClose: () => void;
  19. // When set and `settings.use_slicer_api` is on, the header's slicer button
  20. // becomes "Slice" and calls this instead of opening BambuStudio / Orca
  21. // externally — so the preview modal's slice action matches the file row's
  22. // Cog (in-app Bambuddy SliceModal) when the slicer API is enabled.
  23. onSliceWithBambuddy?: () => void;
  24. }
  25. interface Capabilities {
  26. has_model: boolean;
  27. has_source: boolean;
  28. build_volume: { x: number; y: number; z: number };
  29. filament_colors: string[];
  30. }
  31. interface SlicerSplitButtonProps {
  32. icon: ReactNode;
  33. label: string;
  34. dropdownLabel: string;
  35. onPrimary: () => void;
  36. items: Array<{ key: string; label: string; onClick: () => void }>;
  37. }
  38. // Split button: the primary part runs the default slicer action, the chevron
  39. // opens a dropdown with the other slicer options. Outside click or Escape
  40. // (non-propagating) closes the dropdown. The split only renders when the
  41. // action is already possible, so there is no disabled state to express.
  42. //
  43. // With nothing to put in the dropdown it collapses to a plain button rather
  44. // than offering a chevron onto an empty menu. That is reachable since #3029:
  45. // an STL has exactly one slicer that will take it, so there is no alternative
  46. // to offer once that one is the primary action.
  47. function SlicerSplitButton({ icon, label, dropdownLabel, onPrimary, items }: SlicerSplitButtonProps) {
  48. const [open, setOpen] = useState(false);
  49. const containerRef = useRef<HTMLDivElement>(null);
  50. useEffect(() => {
  51. if (!open) return;
  52. const handlePointerDown = (e: MouseEvent) => {
  53. if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
  54. setOpen(false);
  55. }
  56. };
  57. const handleKeyDown = (e: KeyboardEvent) => {
  58. if (e.key === 'Escape') {
  59. e.stopPropagation();
  60. setOpen(false);
  61. }
  62. };
  63. document.addEventListener('mousedown', handlePointerDown);
  64. document.addEventListener('keydown', handleKeyDown);
  65. return () => {
  66. document.removeEventListener('mousedown', handlePointerDown);
  67. document.removeEventListener('keydown', handleKeyDown);
  68. };
  69. }, [open]);
  70. if (items.length === 0) {
  71. return (
  72. <Button variant="secondary" size="sm" onClick={onPrimary}>
  73. {icon}
  74. {label}
  75. </Button>
  76. );
  77. }
  78. return (
  79. <div className="relative inline-flex" ref={containerRef}>
  80. <div className="flex relative z-50">
  81. <Button
  82. variant="secondary"
  83. size="sm"
  84. onClick={() => {
  85. setOpen(false);
  86. onPrimary();
  87. }}
  88. className="rounded-r-none"
  89. >
  90. {icon}
  91. {label}
  92. </Button>
  93. <Button
  94. variant="secondary"
  95. size="sm"
  96. onClick={() => setOpen((prev) => !prev)}
  97. aria-label={dropdownLabel}
  98. aria-haspopup="menu"
  99. aria-expanded={open}
  100. className="rounded-l-none border-l border-bambu-dark px-2"
  101. >
  102. <ChevronDown className={`w-4 h-4 transition-transform ${open ? 'rotate-180' : ''}`} />
  103. </Button>
  104. </div>
  105. {open && (
  106. <div
  107. role="menu"
  108. className="absolute right-0 top-full mt-1 w-56 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-50 py-1"
  109. >
  110. {items.map((item) => (
  111. <button
  112. key={item.key}
  113. type="button"
  114. role="menuitem"
  115. onClick={() => {
  116. setOpen(false);
  117. item.onClick();
  118. }}
  119. className="w-full text-left px-3 py-2 text-sm text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white transition-colors flex items-center gap-2"
  120. >
  121. <ExternalLink className="w-4 h-4 flex-shrink-0" />
  122. {item.label}
  123. </button>
  124. ))}
  125. </div>
  126. )}
  127. </div>
  128. );
  129. }
  130. export function ModelViewerModal({ archiveId, libraryFileId, title, fileType, onClose, onSliceWithBambuddy }: ModelViewerModalProps) {
  131. const { t } = useTranslation();
  132. const { showToast } = useToast();
  133. const { data: settings } = useQuery({ queryKey: ['settings'], queryFn: api.getSettings });
  134. // Desktop "Open in Slicer" target — falls back to preferred_slicer when the
  135. // user hasn't explicitly chosen a different desktop slicer (#1329). This
  136. // variable is only used for URI-handoff; sidecar slicing keeps using
  137. // preferred_slicer directly.
  138. const preferredSlicer: SlicerType = resolveDesktopSlicer(settings?.open_in_slicer, settings?.preferred_slicer);
  139. const isLibrary = libraryFileId != null;
  140. const [activeTab, setActiveTab] = useState<ViewTab | null>(null);
  141. const [capabilities, setCapabilities] = useState<Capabilities | null>(null);
  142. const [loading, setLoading] = useState(true);
  143. const [platesData, setPlatesData] = useState<ArchivePlatesResponse | LibraryFilePlatesResponse | null>(null);
  144. const [platesLoading, setPlatesLoading] = useState(false);
  145. const [selectedPlateId, setSelectedPlateId] = useState<number | null>(null);
  146. const [platePage, setPlatePage] = useState(0);
  147. const [isFullscreen, setIsFullscreen] = useState(false);
  148. const [platePanelHeight, setPlatePanelHeight] = useState<number | null>(null);
  149. const [isDraggingDivider, setIsDraggingDivider] = useState(false);
  150. const [hasCustomSplit, setHasCustomSplit] = useState(false);
  151. const splitContainerRef = useRef<HTMLDivElement>(null);
  152. const platesPanelRef = useRef<HTMLDivElement>(null);
  153. const dividerHeight = 10;
  154. const minPlateHeight = 160;
  155. const minViewerPx = 240;
  156. const minViewerRatio = 0.35;
  157. // Close on Escape key
  158. useEffect(() => {
  159. const handleKeyDown = (e: KeyboardEvent) => {
  160. if (e.key === 'Escape') onClose();
  161. };
  162. window.addEventListener('keydown', handleKeyDown);
  163. return () => window.removeEventListener('keydown', handleKeyDown);
  164. }, [onClose]);
  165. useEffect(() => {
  166. setLoading(true);
  167. if (isLibrary) {
  168. const normalizedType = (fileType || '').toLowerCase();
  169. // A `.gcode.3mf` file is the slicer's sliced output — it carries
  170. // both the per-plate model (in `3D/3dmodel.model`) and the g-code
  171. // for the active plate (in `Metadata/plate_*.gcode`). The backend
  172. // library scan path (library.py) tags it `gcode.3mf` while the
  173. // upload path tags it `3mf`, so we accept both shapes here for
  174. // the 3D-tab + g-code-tab gating (#1543).
  175. const isThreeMfFamily = normalizedType === '3mf' || normalizedType === 'gcode.3mf';
  176. const hasModel = isThreeMfFamily || normalizedType === 'stl';
  177. setCapabilities({
  178. has_model: hasModel,
  179. has_source: false,
  180. build_volume: { x: 256, y: 256, z: 256 },
  181. filament_colors: [],
  182. });
  183. setActiveTab(hasModel ? '3d' : null);
  184. setLoading(false);
  185. return;
  186. }
  187. if (!archiveId) {
  188. setCapabilities(null);
  189. setActiveTab(null);
  190. setLoading(false);
  191. return;
  192. }
  193. api.getArchiveCapabilities(archiveId)
  194. .then(caps => {
  195. setCapabilities(caps);
  196. // Auto-select the first available tab
  197. if (caps.has_model) {
  198. setActiveTab('3d');
  199. }
  200. setLoading(false);
  201. })
  202. .catch(() => {
  203. // Fallback to 3D model tab if capabilities check fails
  204. setCapabilities({ has_model: true, has_source: false, build_volume: { x: 256, y: 256, z: 256 }, filament_colors: [] });
  205. setActiveTab('3d');
  206. setLoading(false);
  207. });
  208. }, [archiveId, fileType, isLibrary]);
  209. useEffect(() => {
  210. setPlatesLoading(true);
  211. setSelectedPlateId(null);
  212. setPlatePage(0);
  213. if (isLibrary) {
  214. const normalizedType = (fileType || '').toLowerCase();
  215. // Same 3mf-family gate as the capabilities branch above — sliced
  216. // `.gcode.3mf` files have plate metadata too (#1543).
  217. const isThreeMfFamily = normalizedType === '3mf' || normalizedType === 'gcode.3mf';
  218. if (!libraryFileId || !isThreeMfFamily) {
  219. setPlatesData(null);
  220. setPlatesLoading(false);
  221. return;
  222. }
  223. api.getLibraryFilePlates(libraryFileId)
  224. .then((data) => setPlatesData(data))
  225. .catch(() => setPlatesData(null))
  226. .finally(() => setPlatesLoading(false));
  227. return;
  228. }
  229. if (!archiveId) {
  230. setPlatesData(null);
  231. setPlatesLoading(false);
  232. return;
  233. }
  234. api.getArchivePlates(archiveId)
  235. .then((data) => setPlatesData(data))
  236. .catch(() => setPlatesData(null))
  237. .finally(() => setPlatesLoading(false));
  238. }, [archiveId, fileType, isLibrary, libraryFileId]);
  239. const plates = useMemo(() => platesData?.plates ?? [], [platesData]);
  240. const hasMultiplePlates = (platesData?.is_multi_plate ?? false) && plates.length > 1;
  241. const splitFullscreen = isFullscreen && hasMultiplePlates;
  242. const selectedPlate: PlateMetadata | null = selectedPlateId == null
  243. ? null
  244. : plates.find((plate) => plate.index === selectedPlateId) ?? null;
  245. const getPlateObjectCount = (plate: PlateMetadata): number => plate.object_count ?? plate.objects?.length ?? 0;
  246. const totalObjectCount = plates.reduce((sum, plate) => sum + getPlateObjectCount(plate), 0);
  247. const selectedObjectCount = selectedPlate ? getPlateObjectCount(selectedPlate) : totalObjectCount;
  248. const objectCountLabel = selectedPlate ? t('modelViewer.plateNumber', { number: selectedPlate.index }) : t('modelViewer.allPlates');
  249. const hasObjectCount = plates.length > 0;
  250. const platesGridRef = useRef<HTMLDivElement>(null);
  251. const platesViewportRef = useRef<HTMLDivElement>(null);
  252. const [platesPerPage, setPlatesPerPage] = useState(10);
  253. const [plateColumns, setPlateColumns] = useState(3);
  254. const shouldPaginatePlates = plates.length > platesPerPage;
  255. const totalPlatePages = Math.max(1, Math.ceil(plates.length / platesPerPage));
  256. const pagedPlates = shouldPaginatePlates
  257. ? plates.slice(platePage * platesPerPage, (platePage + 1) * platesPerPage)
  258. : plates;
  259. useEffect(() => {
  260. if (!splitFullscreen) {
  261. setPlatesPerPage(10);
  262. setPlateColumns(3);
  263. return;
  264. }
  265. const grid = platesGridRef.current;
  266. const viewport = platesViewportRef.current;
  267. if (!grid || !viewport) return;
  268. let rafId = 0;
  269. const updateLayout = () => {
  270. const availableWidth = viewport.clientWidth;
  271. const minButtonWidth = 210;
  272. const computedCols = Math.floor(availableWidth / minButtonWidth);
  273. const nextCols = Math.max(3, Math.min(5, computedCols || 3));
  274. setPlateColumns((prev) => (prev === nextCols ? prev : nextCols));
  275. const computed = window.getComputedStyle(grid);
  276. const rowGap = Number.parseFloat(computed.rowGap || '0');
  277. const firstItem = grid.querySelector<HTMLElement>('button');
  278. const rowHeight = firstItem?.getBoundingClientRect().height ?? 44;
  279. const availableHeight = viewport.clientHeight;
  280. const rows = Math.max(1, Math.floor((availableHeight + rowGap) / (rowHeight + rowGap)));
  281. const maxSlots = rows * nextCols;
  282. const nextPerPage = Math.max(1, maxSlots - 1);
  283. setPlatesPerPage((prev) => (prev === nextPerPage ? prev : nextPerPage));
  284. };
  285. const scheduleUpdate = () => {
  286. if (rafId) cancelAnimationFrame(rafId);
  287. rafId = requestAnimationFrame(updateLayout);
  288. };
  289. scheduleUpdate();
  290. const resizeObserver = new ResizeObserver(scheduleUpdate);
  291. resizeObserver.observe(viewport);
  292. resizeObserver.observe(grid);
  293. return () => {
  294. if (rafId) cancelAnimationFrame(rafId);
  295. resizeObserver.disconnect();
  296. };
  297. }, [splitFullscreen, plates.length]);
  298. useEffect(() => {
  299. if (!shouldPaginatePlates) {
  300. setPlatePage(0);
  301. return;
  302. }
  303. setPlatePage((prev) => Math.min(prev, totalPlatePages - 1));
  304. }, [plates.length, shouldPaginatePlates, totalPlatePages]);
  305. useEffect(() => {
  306. if (!shouldPaginatePlates || selectedPlateId == null) return;
  307. const selectedIndex = plates.findIndex((plate) => plate.index === selectedPlateId);
  308. if (selectedIndex < 0) return;
  309. const nextPage = Math.floor(selectedIndex / platesPerPage);
  310. setPlatePage((prev) => (prev === nextPage ? prev : nextPage));
  311. }, [plates, platesPerPage, selectedPlateId, shouldPaginatePlates]);
  312. useEffect(() => {
  313. if (!splitFullscreen) {
  314. setPlatePanelHeight(null);
  315. setHasCustomSplit(false);
  316. return;
  317. }
  318. if (hasCustomSplit) return;
  319. const container = splitContainerRef.current;
  320. const panel = platesPanelRef.current;
  321. if (!container || !panel) return;
  322. const containerHeight = container.clientHeight;
  323. if (!containerHeight) return;
  324. const minViewerHeight = Math.max(minViewerPx, containerHeight * minViewerRatio);
  325. const maxPlateHeight = Math.max(minPlateHeight, containerHeight - dividerHeight - minViewerHeight);
  326. const desiredHeight = Math.min(panel.scrollHeight, maxPlateHeight);
  327. setPlatePanelHeight(Math.max(minPlateHeight, desiredHeight));
  328. }, [splitFullscreen, hasCustomSplit, plates.length, platePage, dividerHeight, minPlateHeight, minViewerPx, minViewerRatio]);
  329. useEffect(() => {
  330. if (!isDraggingDivider) return;
  331. const handleMouseMove = (event: MouseEvent) => {
  332. const container = splitContainerRef.current;
  333. if (!container) return;
  334. const rect = container.getBoundingClientRect();
  335. const containerHeight = rect.height;
  336. if (!containerHeight) return;
  337. const minViewerHeight = Math.max(minViewerPx, containerHeight * minViewerRatio);
  338. const maxPlateHeight = Math.max(minPlateHeight, containerHeight - dividerHeight - minViewerHeight);
  339. const nextHeight = Math.min(maxPlateHeight, Math.max(minPlateHeight, event.clientY - rect.top));
  340. setPlatePanelHeight(nextHeight);
  341. };
  342. const handleMouseUp = () => {
  343. setIsDraggingDivider(false);
  344. setHasCustomSplit(true);
  345. };
  346. document.addEventListener('mousemove', handleMouseMove);
  347. document.addEventListener('mouseup', handleMouseUp);
  348. document.body.style.cursor = 'row-resize';
  349. document.body.style.userSelect = 'none';
  350. return () => {
  351. document.removeEventListener('mousemove', handleMouseMove);
  352. document.removeEventListener('mouseup', handleMouseUp);
  353. document.body.style.cursor = '';
  354. document.body.style.userSelect = '';
  355. };
  356. }, [isDraggingDivider, dividerHeight, minPlateHeight, minViewerPx, minViewerRatio]);
  357. // Which desktop slicers this file can actually be handed to, configured one
  358. // first. Shares its lists with `isSliceableFilename()`, which the File
  359. // Manager's card menu and list row use, so a file's "Slice" action and its
  360. // 3D-preview slicer button can no longer disagree about the same file.
  361. //
  362. // Per-slicer rather than one list, because Bambu Studio's protocol handler
  363. // takes 3MF only while OrcaSlicer's takes STL and STEP too (#3029). Archive
  364. // previews always hand over a 3MF, which both accept.
  365. const desktopSlicerOrder: SlicerType[] =
  366. preferredSlicer === 'orcaslicer' ? ['orcaslicer', 'bambu_studio'] : ['bambu_studio', 'orcaslicer'];
  367. const usableSlicers = isLibrary
  368. ? desktopSlicerOrder.filter((slicer) => isSliceableFileType(fileType, slicer))
  369. : desktopSlicerOrder;
  370. const canOpenInSlicer = usableSlicers.length > 0;
  371. // The sidecar's list is narrower: its CLI cannot load STEP even though the
  372. // desktop GUI opens one fine, so in-app slicing is gated separately.
  373. const apiSlicerReadyType = isApiSliceableFileType(fileType);
  374. // When the user has the in-app Slicer API enabled (Settings → Workflow →
  375. // Slicer → Use Slicer API), library-mode previews route the header's slicer
  376. // button into Bambuddy's own SliceModal — same behaviour as the Cog button
  377. // in the file-row actions. Falls back to the external-slicer launcher when
  378. // the API is off, when no in-app handler is wired (e.g. archive preview),
  379. // or when the file type can't be sliced (.gcode / .gcode.3mf, etc.).
  380. const useBambuddySlicer = Boolean(
  381. isLibrary && settings?.use_slicer_api && onSliceWithBambuddy && apiSlicerReadyType,
  382. );
  383. const handleOpenInSlicer = async (slicer: SlicerType) => {
  384. if (!canOpenInSlicer) return;
  385. const filename = title || 'model';
  386. try {
  387. if (isLibrary) {
  388. const { token } = await api.createLibrarySlicerToken(libraryFileId!);
  389. const path = api.getLibrarySlicerDownloadUrl(libraryFileId!, token, filename);
  390. openInSlicer(`${window.location.origin}${path}`, slicer);
  391. } else {
  392. const { token } = await api.createArchiveSlicerToken(archiveId!);
  393. const path = api.getArchiveSlicerDownloadUrl(archiveId!, token, filename);
  394. openInSlicer(`${window.location.origin}${path}`, slicer);
  395. }
  396. } catch {
  397. // Fallback to direct URL (works when auth is disabled). With auth on the
  398. // slicer may then hit a 401, so surface the failure instead of making a
  399. // permission denial look identical to "no slicer installed".
  400. showToast(t('modelViewer.openInSlicerFailed'), 'error');
  401. if (isLibrary) {
  402. const downloadUrl = `${window.location.origin}${api.getLibraryFileDownloadUrl(libraryFileId!)}`;
  403. openInSlicer(downloadUrl, slicer);
  404. } else {
  405. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archiveId!, filename)}`;
  406. openInSlicer(downloadUrl, slicer);
  407. }
  408. }
  409. };
  410. // With the sidecar as the primary action every usable slicer is an
  411. // alternative; without it the first one is the primary, so the dropdown holds
  412. // the rest.
  413. const slicerDropdownTypes: SlicerType[] = useBambuddySlicer ? usableSlicers : usableSlicers.slice(1);
  414. const slicerName = (slicer: SlicerType) =>
  415. slicer === 'orcaslicer' ? t('settings.slicerOrcaSlicer') : t('settings.slicerBambuStudio');
  416. const slicerDropdownItems = slicerDropdownTypes.map((slicer) => ({
  417. key: slicer,
  418. label: t('modelViewer.openInSlicerWith', { slicer: slicerName(slicer) }),
  419. onClick: () => handleOpenInSlicer(slicer),
  420. }));
  421. return (
  422. <div
  423. className={`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${isFullscreen ? 'p-0' : 'p-8'}`}
  424. onClick={onClose}
  425. >
  426. <div
  427. className={`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${
  428. isFullscreen ? 'h-full max-w-none rounded-none' : 'h-[80vh] max-w-4xl rounded-xl'
  429. }`}
  430. onClick={(e) => e.stopPropagation()}
  431. >
  432. {/* Header */}
  433. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  434. <div className="flex items-center gap-3 min-w-0 flex-1 mr-4">
  435. <h2 className="text-lg font-semibold text-white truncate">{title}</h2>
  436. {hasObjectCount && (
  437. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap">
  438. {objectCountLabel}: {t('modelViewer.objectCount', { count: selectedObjectCount })}
  439. </span>
  440. )}
  441. </div>
  442. <div className="flex items-center gap-2">
  443. {useBambuddySlicer ? (
  444. <SlicerSplitButton
  445. icon={<Cog className="w-4 h-4" />}
  446. label={t('slice.action')}
  447. dropdownLabel={t('modelViewer.moreSlicerOptions')}
  448. onPrimary={() => onSliceWithBambuddy?.()}
  449. items={slicerDropdownItems}
  450. />
  451. ) : canOpenInSlicer ? (
  452. <SlicerSplitButton
  453. icon={<ExternalLink className="w-4 h-4" />}
  454. // Name the slicer when it is not the configured one. That happens
  455. // when the configured slicer cannot take this format — an STL with
  456. // Bambu Studio selected — and silently handing the file to the
  457. // other one without saying so would be worse than the failure it
  458. // replaces.
  459. label={
  460. usableSlicers[0] === preferredSlicer
  461. ? t('modelViewer.openInSlicer')
  462. : t('modelViewer.openInSlicerWith', { slicer: slicerName(usableSlicers[0]) })
  463. }
  464. dropdownLabel={t('modelViewer.moreSlicerOptions')}
  465. onPrimary={() => handleOpenInSlicer(usableSlicers[0])}
  466. items={slicerDropdownItems}
  467. />
  468. ) : (
  469. <Button variant="secondary" size="sm" disabled>
  470. <ExternalLink className="w-4 h-4" />
  471. {t('modelViewer.openInSlicer')}
  472. </Button>
  473. )}
  474. <Button
  475. variant="secondary"
  476. size="sm"
  477. onClick={() => setIsFullscreen((prev) => !prev)}
  478. title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
  479. >
  480. {isFullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
  481. </Button>
  482. <Button variant="ghost" size="sm" onClick={onClose}>
  483. <X className="w-5 h-5" />
  484. </Button>
  485. </div>
  486. </div>
  487. {/* Tabs - only show if we have capabilities */}
  488. {capabilities && (
  489. <div className="flex border-b border-bambu-dark-tertiary">
  490. <button
  491. onClick={() => capabilities.has_model && setActiveTab('3d')}
  492. disabled={!capabilities.has_model}
  493. className={`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${
  494. activeTab === '3d'
  495. ? 'text-bambu-green border-b-2 border-bambu-green'
  496. : capabilities.has_model
  497. ? 'text-bambu-gray hover:text-white'
  498. : 'text-bambu-gray/30 cursor-not-allowed'
  499. }`}
  500. >
  501. <Box className="w-4 h-4" />
  502. {t('modelViewer.tabs.model')}
  503. {!capabilities.has_model && <span className="text-xs">({t('modelViewer.notAvailable')})</span>}
  504. </button>
  505. </div>
  506. )}
  507. {/* Viewer */}
  508. <div className="flex-1 overflow-hidden p-4">
  509. {loading ? (
  510. <div className="w-full h-full flex items-center justify-center">
  511. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  512. </div>
  513. ) : activeTab === '3d' && capabilities ? (
  514. <div
  515. ref={splitContainerRef}
  516. className={`w-full h-full flex flex-col ${splitFullscreen ? 'gap-0 min-h-0' : 'gap-3'}`}
  517. >
  518. {hasMultiplePlates && (
  519. <div
  520. ref={platesPanelRef}
  521. style={splitFullscreen && platePanelHeight != null ? { height: platePanelHeight } : undefined}
  522. className={`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${splitFullscreen ? 'flex flex-col shrink-0' : ''}`}
  523. >
  524. <div className="flex items-center gap-2 text-sm text-bambu-gray mb-2">
  525. <Layers className="w-4 h-4" />
  526. {t('modelViewer.plates')}
  527. {platesLoading && <Loader2 className="w-3 h-3 animate-spin" />}
  528. </div>
  529. <div className={splitFullscreen ? 'flex flex-col min-h-0 flex-1' : undefined}>
  530. <div
  531. ref={platesViewportRef}
  532. className={splitFullscreen ? 'min-h-0 overflow-hidden pr-1 flex-1' : undefined}
  533. >
  534. <div
  535. ref={platesGridRef}
  536. className={splitFullscreen ? 'grid gap-2' : 'grid grid-cols-2 md:grid-cols-3 gap-2'}
  537. style={splitFullscreen ? { gridTemplateColumns: `repeat(${plateColumns}, minmax(0, 1fr))` } : undefined}
  538. >
  539. <button
  540. type="button"
  541. onClick={() => setSelectedPlateId(null)}
  542. className={`flex items-center rounded-lg border text-left transition-colors ${
  543. splitFullscreen ? 'gap-1.5 p-1.5 w-full' : 'gap-2 p-2'
  544. } ${
  545. selectedPlateId == null
  546. ? 'border-bambu-green bg-bambu-green/10'
  547. : 'border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray'
  548. }`}
  549. >
  550. <div className={`rounded bg-bambu-dark-tertiary flex items-center justify-center ${
  551. splitFullscreen ? 'w-8 h-8' : 'w-10 h-10'
  552. }`}>
  553. <Layers className={`${splitFullscreen ? 'w-4 h-4' : 'w-5 h-5'} text-bambu-gray`} />
  554. </div>
  555. <div className="min-w-0 flex-1">
  556. <p className={`${splitFullscreen ? 'text-xs' : 'text-sm'} text-white font-medium truncate`}>{t('modelViewer.allPlates')}</p>
  557. <p className={`${splitFullscreen ? 'text-[10px]' : 'text-xs'} text-bambu-gray truncate`}>
  558. {t('modelViewer.plateCount', { count: plates.length })}
  559. </p>
  560. </div>
  561. {selectedPlateId == null && (
  562. <Check className={`${splitFullscreen ? 'w-3.5 h-3.5' : 'w-4 h-4'} text-bambu-green flex-shrink-0`} />
  563. )}
  564. </button>
  565. {pagedPlates.map((plate) => (
  566. <button
  567. key={plate.index}
  568. type="button"
  569. onClick={() => setSelectedPlateId(plate.index)}
  570. className={`flex items-center rounded-lg border text-left transition-colors ${
  571. splitFullscreen ? 'gap-1.5 p-1.5 w-full' : 'gap-2 p-2'
  572. } ${
  573. selectedPlateId === plate.index
  574. ? 'border-bambu-green bg-bambu-green/10'
  575. : 'border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray'
  576. }`}
  577. >
  578. {plate.has_thumbnail && plate.thumbnail_url ? (
  579. <img
  580. src={withMediaToken(plate.thumbnail_url)}
  581. alt={`Plate ${plate.index}`}
  582. className={`${splitFullscreen ? 'w-8 h-8' : 'w-10 h-10'} rounded object-cover bg-bambu-dark-tertiary`}
  583. />
  584. ) : (
  585. <div className={`rounded bg-bambu-dark-tertiary flex items-center justify-center ${
  586. splitFullscreen ? 'w-8 h-8' : 'w-10 h-10'
  587. }`}>
  588. <Layers className={`${splitFullscreen ? 'w-4 h-4' : 'w-5 h-5'} text-bambu-gray`} />
  589. </div>
  590. )}
  591. <div className="min-w-0 flex-1">
  592. <p className={`${splitFullscreen ? 'text-xs' : 'text-sm'} text-white font-medium truncate`}>
  593. {plate.name || t('modelViewer.plateNumber', { number: plate.index })}
  594. </p>
  595. <p className={`${splitFullscreen ? 'text-[10px]' : 'text-xs'} text-bambu-gray truncate`}>
  596. {t('modelViewer.objectCount', { count: plate.object_count ?? plate.objects?.length ?? 0 })}
  597. </p>
  598. </div>
  599. {selectedPlateId === plate.index && (
  600. <Check className={`${splitFullscreen ? 'w-3.5 h-3.5' : 'w-4 h-4'} text-bambu-green flex-shrink-0`} />
  601. )}
  602. </button>
  603. ))}
  604. </div>
  605. </div>
  606. {(selectedPlate || shouldPaginatePlates) && (
  607. <div className="mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto">
  608. {selectedPlate && (
  609. <div className="flex items-center gap-3 whitespace-nowrap">
  610. <span>{t('modelViewer.plateNumber', { number: selectedPlate.index })}</span>
  611. {selectedPlate.print_time_seconds != null && (
  612. <span>{t('modelViewer.eta', { minutes: Math.round(selectedPlate.print_time_seconds / 60) })}</span>
  613. )}
  614. {selectedPlate.filament_used_grams != null && (
  615. <span>{selectedPlate.filament_used_grams.toFixed(1)} g</span>
  616. )}
  617. {selectedPlate.filaments.length > 0 && (
  618. <span>{t('modelViewer.filamentCount', { count: selectedPlate.filaments.length })}</span>
  619. )}
  620. </div>
  621. )}
  622. {shouldPaginatePlates && (
  623. <div className={`flex items-center gap-2 whitespace-nowrap ${selectedPlate ? 'ml-auto' : ''}`}>
  624. <span>{t('modelViewer.pagination.pageOf', { current: platePage + 1, total: totalPlatePages })}</span>
  625. <div className="flex items-center gap-1">
  626. <button
  627. type="button"
  628. onClick={() => setPlatePage((prev) => Math.max(prev - 1, 0))}
  629. disabled={platePage === 0}
  630. className={`px-2 py-1 rounded border text-xs ${
  631. platePage === 0
  632. ? 'border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed'
  633. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  634. }`}
  635. >
  636. {t('modelViewer.pagination.prev')}
  637. </button>
  638. {(() => {
  639. const maxVisible = 5;
  640. let start = Math.max(0, platePage - Math.floor(maxVisible / 2));
  641. const end = Math.min(totalPlatePages, start + maxVisible);
  642. if (end - start < maxVisible) {
  643. start = Math.max(0, end - maxVisible);
  644. }
  645. const pages = Array.from({ length: end - start }, (_, i) => start + i);
  646. return (
  647. <>
  648. {start > 0 && (
  649. <button
  650. type="button"
  651. onClick={() => setPlatePage(0)}
  652. className={`px-2 py-1 rounded border text-xs ${
  653. platePage === 0
  654. ? 'border-bambu-green text-bambu-green'
  655. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  656. }`}
  657. >
  658. 1
  659. </button>
  660. )}
  661. {start > 1 && <span className="px-1">…</span>}
  662. {pages.map((pageNumber) => (
  663. <button
  664. key={pageNumber}
  665. type="button"
  666. onClick={() => setPlatePage(pageNumber)}
  667. className={`px-2 py-1 rounded border text-xs ${
  668. platePage === pageNumber
  669. ? 'border-bambu-green text-bambu-green'
  670. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  671. }`}
  672. >
  673. {pageNumber + 1}
  674. </button>
  675. ))}
  676. {end < totalPlatePages - 1 && <span className="px-1">…</span>}
  677. {end < totalPlatePages && (
  678. <button
  679. type="button"
  680. onClick={() => setPlatePage(totalPlatePages - 1)}
  681. className={`px-2 py-1 rounded border text-xs ${
  682. platePage === totalPlatePages - 1
  683. ? 'border-bambu-green text-bambu-green'
  684. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  685. }`}
  686. >
  687. {totalPlatePages}
  688. </button>
  689. )}
  690. </>
  691. );
  692. })()}
  693. <button
  694. type="button"
  695. onClick={() => setPlatePage((prev) => Math.min(prev + 1, totalPlatePages - 1))}
  696. disabled={platePage >= totalPlatePages - 1}
  697. className={`px-2 py-1 rounded border text-xs ${
  698. platePage >= totalPlatePages - 1
  699. ? 'border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed'
  700. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  701. }`}
  702. >
  703. {t('modelViewer.pagination.next')}
  704. </button>
  705. </div>
  706. </div>
  707. )}
  708. </div>
  709. )}
  710. </div>
  711. </div>
  712. )}
  713. {splitFullscreen && (
  714. <div
  715. role="separator"
  716. aria-orientation="horizontal"
  717. onMouseDown={(event) => {
  718. event.preventDefault();
  719. setIsDraggingDivider(true);
  720. setHasCustomSplit(true);
  721. }}
  722. className={`h-2 cursor-row-resize flex items-center justify-center ${
  723. isDraggingDivider ? 'bg-bambu-dark-tertiary' : 'bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary'
  724. }`}
  725. >
  726. <div className="w-12 h-1 rounded-full bg-bambu-gray/50" />
  727. </div>
  728. )}
  729. <div className={`flex-1 ${splitFullscreen ? 'min-h-0' : ''}`}>
  730. <ModelViewer
  731. url={isLibrary
  732. ? api.getLibraryFileDownloadUrl(libraryFileId!)
  733. : (capabilities.has_source
  734. ? api.getSource3mfDownloadUrl(archiveId!)
  735. : api.getArchiveDownload(archiveId!))}
  736. fileType={fileType}
  737. buildVolume={capabilities.build_volume}
  738. filamentColors={capabilities.filament_colors}
  739. selectedPlateId={selectedPlateId}
  740. className="w-full h-full"
  741. />
  742. </div>
  743. </div>
  744. ) : (
  745. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  746. {t('modelViewer.noPreview')}
  747. </div>
  748. )}
  749. </div>
  750. </div>
  751. </div>
  752. );
  753. }