SliceModal.tsx 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. import { Cloud, CloudOff, Cog, Loader2, RefreshCw, X } from 'lucide-react';
  2. import { useEffect, useMemo, useState } from 'react';
  3. import { useTranslation } from 'react-i18next';
  4. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  5. import {
  6. api,
  7. type PresetRef,
  8. type PresetSource,
  9. type SliceJobProgress,
  10. type SliceRequest,
  11. type SlicerCloudStatus,
  12. type UnifiedPreset,
  13. type UnifiedPresetsBySlot,
  14. type UnifiedPresetsResponse,
  15. } from '../api/client';
  16. import { useSliceJobTracker } from '../contexts/SliceJobTrackerContext';
  17. import { useToast } from '../contexts/ToastContext';
  18. import { PlatePickerModal } from './PlatePickerModal';
  19. import type { DesignOverride, PlateFilament } from '../types/plates';
  20. import {
  21. presetCompatibility,
  22. buildCompatibilityIndex,
  23. EMPTY_COMPATIBILITY_INDEX,
  24. type PrinterCompatibilityIndex,
  25. } from '../utils/slicerPrinterMatch';
  26. import {
  27. findPreset,
  28. findPresetByName,
  29. pickDefault,
  30. pickFilamentForSlot,
  31. pickProcessDefault,
  32. type Slot,
  33. } from '../utils/slicePresetPicker';
  34. export type SliceSource =
  35. | { kind: 'libraryFile'; id: number; filename: string }
  36. | { kind: 'archive'; id: number; filename: string };
  37. interface SliceModalProps {
  38. source: SliceSource;
  39. onClose: () => void;
  40. }
  41. function toRefValue(ref: PresetRef | null): string {
  42. // The HTML `<select>` value space is flat strings; encode source + id so
  43. // the same preset name can live in multiple tiers without collision.
  44. return ref ? `${ref.source}:${ref.id}` : '';
  45. }
  46. function fromRefValue(raw: string): PresetRef | null {
  47. if (!raw) return null;
  48. const idx = raw.indexOf(':');
  49. if (idx < 0) return null;
  50. const source = raw.slice(0, idx) as PresetSource;
  51. const id = raw.slice(idx + 1);
  52. if (source !== 'orca_cloud' && source !== 'cloud' && source !== 'local' && source !== 'standard') return null;
  53. return { source, id };
  54. }
  55. // Inline spinner for the filament-requirements query. The backend runs a
  56. // preview slice on first open of an unsliced project file (cached after);
  57. // on a complex multi-color model that's a real slice — multi-second to
  58. // multi-minute. The static "Analyzing plate filaments…" string left
  59. // users wondering whether anything was happening, so the spinner now
  60. // shows elapsed seconds, polls the sidecar's --pipe progress (via the
  61. // /slicer/preview-progress proxy) for live stage + percent, and after ~5s
  62. // surfaces a "this is a one-time slice — repeat opens are instant"
  63. // note so users don't worry it'll be slow forever.
  64. //
  65. // requestId: a UUID generated by the modal when the filament-requirements
  66. // fetch starts. Forwarded to the sidecar via the API call AND used here
  67. // to poll the matching progress snapshot. Same id, two consumers.
  68. function FilamentAnalysisSpinner({
  69. requestId,
  70. sourceName,
  71. }: {
  72. requestId: string;
  73. sourceName: string;
  74. }) {
  75. const { t } = useTranslation();
  76. const { showPersistentToast, dismissToast } = useToast();
  77. const [elapsed, setElapsed] = useState(0);
  78. const [progress, setProgress] = useState<SliceJobProgress | null>(null);
  79. // Defensive decode — see prettifyFilename comment in SliceJobTrackerContext.
  80. let prettyName = sourceName;
  81. try {
  82. prettyName = decodeURIComponent(sourceName);
  83. } catch {
  84. /* keep raw on malformed encoding */
  85. }
  86. // Elapsed-time tick.
  87. useEffect(() => {
  88. const startedAt = Date.now();
  89. const id = setInterval(() => setElapsed(Math.floor((Date.now() - startedAt) / 1000)), 1000);
  90. return () => clearInterval(id);
  91. }, []);
  92. // Progress polling — once per second while the spinner is mounted.
  93. // Mirrors the slice-job tracker's cadence. Sidecar 404s during the
  94. // race window between fetch start and progressStore.start() are
  95. // swallowed by the API method (returns null) so we keep polling.
  96. useEffect(() => {
  97. let cancelled = false;
  98. const id = setInterval(async () => {
  99. if (cancelled) return;
  100. const snap = await api.getPreviewSliceProgress(requestId);
  101. if (!cancelled && snap) setProgress(snap);
  102. }, 1000);
  103. return () => {
  104. cancelled = true;
  105. clearInterval(id);
  106. };
  107. }, [requestId]);
  108. // Mirror the spinner's contents into a persistent toast so the user
  109. // sees activity even when their cursor is elsewhere on the page.
  110. // Dismissed in the parent's effect when the requirements arrive.
  111. const toastId = `slice-preview-${requestId}`;
  112. useEffect(() => {
  113. const hasUseful = progress && progress.stage && progress.total_percent > 0;
  114. const elapsedStr = formatElapsed(elapsed);
  115. if (hasUseful) {
  116. showPersistentToast(
  117. toastId,
  118. t(
  119. 'slice.previewWithProgress',
  120. 'Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}',
  121. {
  122. name: prettyName,
  123. stage: progress!.stage,
  124. percent: Math.min(100, Math.max(0, Math.round(progress!.total_percent))),
  125. elapsed: elapsedStr,
  126. },
  127. ),
  128. 'loading',
  129. );
  130. } else {
  131. showPersistentToast(
  132. toastId,
  133. t('slice.previewToast', {
  134. name: prettyName,
  135. elapsed: elapsedStr,
  136. }),
  137. 'loading',
  138. );
  139. }
  140. return () => {
  141. dismissToast(toastId);
  142. };
  143. }, [elapsed, progress, prettyName, showPersistentToast, dismissToast, t, toastId]);
  144. const stage = progress?.stage;
  145. const percent = progress?.total_percent;
  146. const inlineLabel =
  147. stage && typeof percent === 'number' && percent > 0
  148. ? `${stage} (${Math.min(100, Math.max(0, Math.round(percent)))}%)`
  149. : t('slice.analyzingPlateFilaments');
  150. return (
  151. <div className="flex flex-col gap-1 text-bambu-gray text-sm py-2">
  152. <div className="flex items-center gap-2">
  153. <Loader2 className="w-4 h-4 animate-spin" />
  154. {inlineLabel}
  155. <span className="text-xs tabular-nums">{elapsed}s</span>
  156. </div>
  157. {elapsed >= 5 && (
  158. <div className="text-xs text-bambu-gray/70 pl-6">
  159. {t(
  160. 'slice.analyzingPlateFilamentsHint',
  161. 'Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.',
  162. )}
  163. </div>
  164. )}
  165. </div>
  166. );
  167. }
  168. function formatElapsed(seconds: number): string {
  169. const s = Math.max(0, Math.floor(seconds));
  170. if (s < 60) return `${s}s`;
  171. const m = Math.floor(s / 60);
  172. const remS = s % 60;
  173. if (m < 60) return `${m}m ${remS}s`;
  174. const h = Math.floor(m / 60);
  175. const remM = m % 60;
  176. return `${h}h ${remM}m`;
  177. }
  178. // Render a slicer parameter value for the design-settings list. Bambu's process
  179. // schema stores everything as strings or arrays of strings, so this only has to
  180. // flatten arrays and keep scalars readable — no unit or type interpretation,
  181. // which would rot against every slicer release.
  182. function formatDesignValue(value: unknown): string {
  183. if (Array.isArray(value)) return value.map((v) => String(v)).join(', ');
  184. if (value == null) return '';
  185. return String(value);
  186. }
  187. export function SliceModal({ source, onClose }: SliceModalProps) {
  188. const { t } = useTranslation();
  189. const { trackJob } = useSliceJobTracker();
  190. const queryClient = useQueryClient();
  191. const [printerPreset, setPrinterPreset] = useState<PresetRef | null>(null);
  192. const [processPreset, setProcessPreset] = useState<PresetRef | null>(null);
  193. // One filament ref per plate slot, in plate order. For STL / single-plate /
  194. // single-color sources this is a one-element array; multi-color 3MFs get one
  195. // entry per AMS slot the plate uses. Pre-pick (effect below) initialises
  196. // each slot from the source plate's required (type, colour).
  197. const [filamentPresets, setFilamentPresets] = useState<(PresetRef | null)[]>([]);
  198. const [errorMessage, setErrorMessage] = useState<string | null>(null);
  199. // null = plate not yet picked (or single-plate / non-3MF — picker is skipped
  200. // and we'll backfill 1 at submit time). Set to a 1-indexed plate number once
  201. // the user picks one (or implicitly for single-plate sources).
  202. const [selectedPlate, setSelectedPlate] = useState<number | null>(null);
  203. // "Slice all plates" mode: sends ``plate=0`` to the backend which forwards
  204. // ``--slice 0`` to the BS CLI, producing a single output 3MF whose
  205. // ``Metadata/plate_N.gcode`` entries are *all* plates sliced together —
  206. // one archive, one file, all plates. Distinct from the per-plate
  207. // ``selectedPlate`` mode (which slices just that one plate). Filament
  208. // selection in this mode covers every slot the project defines, not
  209. // just the slots the currently-visible plate happens to use — see
  210. // ``allProjectFilamentSlots`` below.
  211. const [sliceAllPlates, setSliceAllPlates] = useState(false);
  212. // Build-plate override (#1337). null = inherit from the process preset
  213. // (the default). Set to a canonical slicer enum value to patch
  214. // curr_bed_type into the resolved process JSON before slicing — needed
  215. // because the process preset's default plate (typically "Cool Plate") is
  216. // incompatible with high-temp filaments like ABS / ASA / PC, and the
  217. // user had no way to switch plates without cloning the preset.
  218. const [bedType, setBedType] = useState<string | null>(null);
  219. // "Slice as designed" (#2611). When on, the backend honours the source
  220. // 3MF's embedded project_settings.config (the designer's own wall count,
  221. // infill, etc.) instead of the picked process/filament profiles. Only
  222. // offered when the picked printer matches the design's target model —
  223. // see canUseEmbedded below.
  224. const [useEmbedded, setUseEmbedded] = useState(false);
  225. // Auto-orient / auto-arrange (#2548) — the GUI's two layout buttons,
  226. // forwarded as the slicer's --orient / --arrange CLI actions. Per-slice
  227. // and off by default: both rewrite the object placement the file came
  228. // with, so they are something the user asks for, never a default. Kept
  229. // enabled in embedded mode, unlike the process-level options around
  230. // them — these act on the geometry, whichever config drives the slice.
  231. const [autoOrient, setAutoOrient] = useState(false);
  232. const [autoArrange, setAutoArrange] = useState(false);
  233. // #2622: process settings the designer changed away from the stock preset,
  234. // carried onto the picked process profile so a cross-printer re-slice keeps
  235. // the model's intended wall count / infill / first layer instead of losing
  236. // them to --load-settings. Keys the file flags as machine-coupled (speeds,
  237. // accelerations, prime-tower geometry) are listed but start unticked — those
  238. // were tuned for the designer's printer and can be plain wrong on another.
  239. const [designKeys, setDesignKeys] = useState<Set<string>>(new Set());
  240. const [designExpanded, setDesignExpanded] = useState(false);
  241. // Slicer Pipelines (#1425) — apply a saved preset bundle to all four slots
  242. // with one pick, or save the current selection as a new pipeline.
  243. const pipelinesQuery = useQuery({
  244. queryKey: ['slicer-pipelines'],
  245. queryFn: () => api.listSlicerPipelines(),
  246. staleTime: 60_000,
  247. });
  248. const [savePipelineOpen, setSavePipelineOpen] = useState(false);
  249. const [pipelineDraftName, setPipelineDraftName] = useState('');
  250. const { showToast } = useToast();
  251. const createPipelineMutation = useMutation({
  252. mutationFn: (body: {
  253. name: string;
  254. printer_preset: PresetRef;
  255. process_preset: PresetRef;
  256. filament_presets: PresetRef[];
  257. bed_type: string | null;
  258. }) => api.createSlicerPipeline(body),
  259. onSuccess: () => {
  260. queryClient.invalidateQueries({ queryKey: ['slicer-pipelines'] });
  261. showToast(t('slice.pipelines.toast.saved', 'Pipeline saved'), 'success');
  262. setSavePipelineOpen(false);
  263. setPipelineDraftName('');
  264. },
  265. onError: (err: Error) => {
  266. showToast(err.message || t('slice.pipelines.toast.saveFailed', 'Save failed'), 'error');
  267. },
  268. });
  269. const platesQuery = useQuery({
  270. queryKey: ['slicePlates', source.kind, source.id],
  271. queryFn: async () => {
  272. if (source.kind === 'libraryFile') {
  273. return api.getLibraryFilePlates(source.id);
  274. }
  275. return api.getArchivePlates(source.id);
  276. },
  277. staleTime: 60_000,
  278. });
  279. const isMultiPlate =
  280. !!platesQuery.data?.is_multi_plate && (platesQuery.data?.plates?.length ?? 0) > 1;
  281. // Single-plate / non-3MF / fetch failure: skip the picker, default to plate 1
  282. // at submit time so the backend's existing default behaviour is preserved.
  283. const needsPlatePicker = isMultiPlate && selectedPlate == null;
  284. // Per-plate filament requirements via the same endpoint the print/schedule
  285. // modal uses. Reusing it here keeps the SliceModal honest with whatever
  286. // logic that endpoint applies (slice_info parsing, future enhancements for
  287. // unsliced project files, dual-nozzle fields, etc.) instead of duplicating
  288. // extraction. plate_id is always sent: single-plate falls through to plate
  289. // 1 server-side; multi-plate uses the user's pick.
  290. const effectivePlateId = selectedPlate ?? 1;
  291. // Generate a request_id per (source, plate) pair so the backend's
  292. // preview-slice and the FilamentAnalysisSpinner's progress poll share
  293. // the same id. useMemo keeps it stable across renders within the same
  294. // pair; switching plates regenerates so a stale poll doesn't bleed
  295. // progress between plates.
  296. const previewRequestId = useMemo(() => {
  297. const random =
  298. typeof crypto !== 'undefined' && 'randomUUID' in crypto
  299. ? crypto.randomUUID()
  300. : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
  301. // Tag the id with the (source, plate) so logs/Network panel show which
  302. // pair owns the poll. Also lets the lint rule see the deps in use.
  303. return `${source.kind}-${source.id}-p${effectivePlateId}-${random}`;
  304. }, [source.kind, source.id, effectivePlateId]);
  305. const filamentReqsQuery = useQuery({
  306. queryKey: ['sliceFilamentReqs', source.kind, source.id, effectivePlateId],
  307. queryFn: async () => {
  308. // `fullSlots`: one row per project slot, not only the ones this plate
  309. // prints with. The list below is positional all the way to the CLI's
  310. // filament_N.json parts, so a source whose only used slot is 4 has to
  311. // present four rows — otherwise the single pick binds to slot 1 and
  312. // slot 4 slices with whatever the source had baked in (#2712). The
  313. // unused rows stay disabled exactly as before.
  314. if (source.kind === 'libraryFile') {
  315. return api.getLibraryFileFilamentRequirements(source.id, effectivePlateId, previewRequestId, true);
  316. }
  317. return api.getArchiveFilamentRequirements(source.id, effectivePlateId, previewRequestId, true);
  318. },
  319. enabled: !needsPlatePicker,
  320. staleTime: 60_000,
  321. });
  322. // Filament slot list for the active plate. Falls back to one synthetic slot
  323. // for STL/STEP and any "no metadata available" case so the modal still
  324. // works (single dropdown, mono-color slice). In ``sliceAllPlates`` mode
  325. // we keep the same slot list (the backend already returns every project
  326. // slot via ``extract_project_filaments_from_3mf``'s fallback path when
  327. // slice_info doesn't carry per-plate filaments) but override every
  328. // slot's ``used_in_plate`` flag to ``true`` so the dropdown labels
  329. // drop the "— not used by this plate" suffix and the dropdowns become
  330. // selectable. Across the whole project, every defined slot IS used by
  331. // at least one plate, so this is correct in slice-all mode.
  332. const filamentSlots = useMemo<PlateFilament[]>(() => {
  333. const reqs = filamentReqsQuery.data?.filaments ?? [];
  334. const base: PlateFilament[] =
  335. reqs.length > 0
  336. ? (reqs as PlateFilament[])
  337. : [{ slot_id: 1, type: '', color: '', used_grams: 0, used_meters: 0 }];
  338. if (sliceAllPlates) {
  339. return base.map((slot) => ({ ...slot, used_in_plate: true }));
  340. }
  341. return base;
  342. }, [sliceAllPlates, filamentReqsQuery.data]);
  343. const presetsQuery = useQuery({
  344. queryKey: ['slicerPresets'],
  345. queryFn: () => api.getSlicerPresets(),
  346. staleTime: 60_000,
  347. // Don't fetch presets while the plate picker is on screen — saves a
  348. // round-trip if the user cancels out of the plate step.
  349. enabled: !platesQuery.isLoading && !needsPlatePicker,
  350. });
  351. // Manual refresh — bypasses the backend's 5-minute cloud cache and 1-hour
  352. // bundled cache for one call so users who deleted a preset in Bambu
  353. // Studio / Bambu Handy see the change immediately (#1581). The cache write
  354. // inside _fetch_cloud_presets / _fetch_bundled_presets refills with the
  355. // fresh result so subsequent normal callers still get cached responses.
  356. const [isRefreshing, setIsRefreshing] = useState(false);
  357. const handleRefreshPresets = async () => {
  358. if (isRefreshing) return;
  359. setIsRefreshing(true);
  360. try {
  361. const fresh = await api.getSlicerPresets({ refresh: true });
  362. queryClient.setQueryData(['slicerPresets'], fresh);
  363. } catch {
  364. // Fall through to invalidate so React Query retries via its normal
  365. // path on the next render — surfacing the failure through the existing
  366. // presetsQuery.isError banner instead of duplicating error UI here.
  367. queryClient.invalidateQueries({ queryKey: ['slicerPresets'] });
  368. } finally {
  369. setIsRefreshing(false);
  370. }
  371. };
  372. // Canonical Bambu printer-model registry — drives the @BBL <code> name
  373. // fallback in slicerPrinterMatch for cloud / standard presets (#1325).
  374. // Long staleTime: the registry only changes across backend releases.
  375. const printerModelsQuery = useQuery({
  376. queryKey: ['slicerPrinterModels'],
  377. queryFn: api.getSlicerPrinterModels,
  378. staleTime: Infinity,
  379. });
  380. // Selected-printer context for the process / filament filter (#1325).
  381. const selectedPrinterName = useMemo<string | null>(() => {
  382. if (!presetsQuery.data || !printerPreset) return null;
  383. return findPreset(presetsQuery.data, printerPreset, 'printer')?.name ?? null;
  384. }, [presetsQuery.data, printerPreset]);
  385. // Compatibility ground truth: the slicer's own `compatible_printers` list
  386. // on local-imported presets, plus the @BBL <code> name fallback for cloud
  387. // / standard presets via the backend Bambu printer-model registry.
  388. const compatIndex = useMemo<PrinterCompatibilityIndex>(
  389. () => buildCompatibilityIndex(printerModelsQuery.data ?? {}),
  390. [printerModelsQuery.data],
  391. );
  392. // Printer / process preset names the source 3MF was prepared with. The
  393. // plates query resolves before the presets query (the latter is gated on
  394. // it), so these are known by the time the pre-pick effects run.
  395. const embeddedPrinter = platesQuery.data?.embedded_printer ?? null;
  396. const designOverrides = useMemo<DesignOverride[]>(
  397. () => platesQuery.data?.design_overrides ?? [],
  398. [platesQuery.data],
  399. );
  400. const embeddedProcess = platesQuery.data?.embedded_process ?? null;
  401. // "Slice as designed" is offered only when the source carries embedded
  402. // settings (a real project 3MF, not an STL) AND the picked printer matches
  403. // the design's target model. The match gate is load-bearing: honouring
  404. // embedded settings for a different model would place the model on the
  405. // wrong bed. Names come from the same preset namespace, so a normalised
  406. // (strip "# " prefix, case-fold) equality is enough.
  407. const canUseEmbedded = useMemo<boolean>(() => {
  408. if (!embeddedPrinter || !embeddedProcess || !selectedPrinterName) return false;
  409. const norm = (s: string) => s.replace(/^#\s*/, '').trim().toLowerCase();
  410. return norm(selectedPrinterName) === norm(embeddedPrinter);
  411. }, [embeddedPrinter, embeddedProcess, selectedPrinterName]);
  412. // Drop back to profile slicing whenever the toggle stops being offered
  413. // (e.g. the user switches to a printer that doesn't match the design).
  414. useEffect(() => {
  415. if (!canUseEmbedded) setUseEmbedded(false);
  416. }, [canUseEmbedded]);
  417. // Pre-tick the printer-independent design settings once the source's list
  418. // arrives. Machine-coupled keys stay off until the user opts in explicitly.
  419. useEffect(() => {
  420. setDesignKeys(new Set(designOverrides.filter((o) => !o.printer_coupled).map((o) => o.key)));
  421. }, [designOverrides]);
  422. // Printer pre-pick: defaults to the printer the 3MF was prepared for when
  423. // that preset is available, else the first listed printer. Runs once when
  424. // presets first arrive; later re-renders preserve any manual choice.
  425. useEffect(() => {
  426. const data = presetsQuery.data;
  427. if (!data) return;
  428. if (printerPreset == null) {
  429. setPrinterPreset(
  430. findPresetByName(data, 'printer', embeddedPrinter) ?? pickDefault(data, 'printer'),
  431. );
  432. }
  433. // eslint-disable-next-line react-hooks/exhaustive-deps
  434. }, [presetsQuery.data, embeddedPrinter]);
  435. // Process pre-pick / re-pick (#1325): defaults to a process compatible with
  436. // the selected printer, and re-defaults when a printer change leaves the
  437. // current process incompatible. A compatible or unknown manual pick is kept.
  438. useEffect(() => {
  439. const data = presetsQuery.data;
  440. if (!data) return;
  441. setProcessPreset((current) => {
  442. if (current) {
  443. const p = findPreset(data, current, 'process');
  444. if (p && presetCompatibility(p, 'process', selectedPrinterName, compatIndex) !== 'mismatch') {
  445. return current;
  446. }
  447. }
  448. return pickProcessDefault(data, selectedPrinterName, compatIndex, embeddedProcess);
  449. });
  450. }, [presetsQuery.data, selectedPrinterName, compatIndex, embeddedProcess]);
  451. // Filament pre-pick: re-runs when the active filament-slot count changes
  452. // (plate selection, single-plate metadata arriving) or the selected printer
  453. // changes. Each slot scores every available filament preset against the
  454. // slot's required (type, colour); an existing pick (incl. a user override)
  455. // is kept as long as it's still compatible with the selected printer, while
  456. // null slots and printer-incompatible picks are re-picked (#1325).
  457. useEffect(() => {
  458. const data = presetsQuery.data;
  459. if (!data) return;
  460. setFilamentPresets((current) => {
  461. return filamentSlots.map((slot, i) => {
  462. const cur = current[i] ?? null;
  463. if (cur) {
  464. const p = findPreset(data, cur, 'filament');
  465. if (p && presetCompatibility(p, 'filament', selectedPrinterName, compatIndex) !== 'mismatch') {
  466. return cur;
  467. }
  468. }
  469. return pickFilamentForSlot(
  470. data,
  471. { type: slot.type, color: slot.color },
  472. selectedPrinterName,
  473. compatIndex,
  474. );
  475. });
  476. });
  477. }, [presetsQuery.data, filamentSlots, selectedPrinterName, compatIndex]);
  478. const enqueueMutation = useMutation({
  479. mutationFn: async (plate: number | null) => {
  480. const body = buildSliceBody(plate);
  481. if (source.kind === 'libraryFile') {
  482. return api.sliceLibraryFile(source.id, body);
  483. }
  484. return api.sliceArchive(source.id, body);
  485. },
  486. onSuccess: (enqueue) => {
  487. trackJob(enqueue.job_id, source.kind, source.filename);
  488. onClose();
  489. },
  490. onError: (err: unknown) => {
  491. const msg = err instanceof Error ? err.message : String(err);
  492. setErrorMessage(msg);
  493. },
  494. });
  495. // Body builder shared by the single-plate and slice-all paths. ``plate``
  496. // is the 1-indexed plate number to slice, or ``null`` for STL / single-
  497. // plate 3MF sources where the field is omitted entirely.
  498. function buildSliceBody(plate: number | null): SliceRequest {
  499. if (
  500. !printerPreset ||
  501. !processPreset ||
  502. filamentPresets.length === 0 ||
  503. filamentPresets.some((r) => r == null)
  504. ) {
  505. throw new Error(t('slice.allPresetsRequired'));
  506. }
  507. return {
  508. printer_preset: printerPreset,
  509. process_preset: processPreset,
  510. filament_preset: filamentPresets[0] as PresetRef,
  511. filament_presets: filamentPresets as PresetRef[],
  512. ...(plate != null ? { plate } : {}),
  513. ...(bedType != null ? { bed_type: bedType } : {}),
  514. // The preset refs above are still sent (the backend validator requires
  515. // them) but go unused when this flag is set — the slicer falls back on
  516. // the file's embedded project_settings.config instead.
  517. ...(useEmbedded && canUseEmbedded ? { use_embedded_settings: true } : {}),
  518. // Carried design settings are patched onto the resolved process JSON,
  519. // which the embedded-settings path never sends — so they are mutually
  520. // exclusive by construction (#2622).
  521. ...(!useEmbedded && designKeys.size > 0 ? { design_overrides: [...designKeys] } : {}),
  522. // Sent only when on. The backend defaults both to false, so omitting
  523. // them keeps the request identical to what older clients send.
  524. ...(autoOrient ? { auto_orient: true } : {}),
  525. ...(autoArrange ? { auto_arrange: true } : {}),
  526. };
  527. }
  528. // Slice button stays disabled until the preview slice / embedded-metadata
  529. // read has succeeded (filamentReqsQuery.isSuccess) and every filament slot
  530. // has a picked profile.
  531. const isReady =
  532. printerPreset != null &&
  533. processPreset != null &&
  534. filamentReqsQuery.isSuccess &&
  535. filamentPresets.length > 0 &&
  536. filamentPresets.every((r) => r != null);
  537. const isEnqueuing = enqueueMutation.isPending;
  538. const totalPlateCount = platesQuery.data?.plates?.length ?? 0;
  539. const canSliceAll = isMultiPlate && totalPlateCount > 1 && !needsPlatePicker;
  540. // Step 1: plate picker for multi-plate 3MF sources. Cancelling closes the
  541. // entire flow (matches the existing PlatePickerModal contract used by the
  542. // archive g-code-viewer entry point).
  543. if (needsPlatePicker && platesQuery.data) {
  544. return (
  545. <PlatePickerModal
  546. plates={platesQuery.data.plates}
  547. onSelect={(plateIndex) => setSelectedPlate(plateIndex)}
  548. onClose={onClose}
  549. />
  550. );
  551. }
  552. // Step 2 (or only step for single-plate / non-3MF / load-failure): preset
  553. // picker. While the plates query is in-flight we still render the shell
  554. // because the presets query is gated on it; the loader covers both.
  555. return (
  556. <div
  557. className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
  558. onClick={() => {
  559. if (!isEnqueuing) onClose();
  560. }}
  561. >
  562. <div
  563. className="w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60"
  564. onClick={(e) => e.stopPropagation()}
  565. >
  566. {/* Header */}
  567. <div className="flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40">
  568. <div className="min-w-0">
  569. <h3 className="text-white font-medium flex items-center gap-2">
  570. <Cog className="w-4 h-4" />
  571. {t('slice.title')}
  572. </h3>
  573. <p className="text-xs text-bambu-gray mt-1 truncate" title={source.filename}>
  574. {source.filename}
  575. {selectedPlate != null
  576. ? ` • ${t('archives.platePicker.plateLabel', { index: selectedPlate })}`
  577. : ''}
  578. </p>
  579. </div>
  580. <button
  581. onClick={onClose}
  582. disabled={isEnqueuing}
  583. className="flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50"
  584. aria-label={t('common.close')}
  585. >
  586. <X className="w-5 h-5" />
  587. </button>
  588. </div>
  589. {/* Body */}
  590. <div className="flex-1 overflow-y-auto p-4 space-y-4">
  591. {/* Preset listing loader — printer/process dropdowns can't render
  592. without it. Plate query reuses the same spinner since it's
  593. also blocking. */}
  594. {(platesQuery.isLoading || presetsQuery.isLoading) && (
  595. <div className="flex items-center gap-2 text-bambu-gray text-sm">
  596. <Loader2 className="w-4 h-4 animate-spin" />
  597. {t('slice.loadingPresets')}
  598. </div>
  599. )}
  600. {presetsQuery.isError && (
  601. <div className="text-sm text-red-700 dark:text-red-400" role="alert">
  602. {t(
  603. 'slice.presetsLoadFailed',
  604. 'Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.',
  605. )}
  606. </div>
  607. )}
  608. {presetsQuery.data && (
  609. <>
  610. <div className="flex items-start justify-between gap-2">
  611. <div className="flex-1 space-y-2">
  612. <CloudStatusBanner status={presetsQuery.data.cloud_status} cloudName="bambu" />
  613. <CloudStatusBanner status={presetsQuery.data.orca_cloud_status} cloudName="orca" />
  614. </div>
  615. <button
  616. type="button"
  617. onClick={handleRefreshPresets}
  618. disabled={isRefreshing || isEnqueuing}
  619. className="flex-shrink-0 inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/40 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
  620. title={t('slice.refreshPresetsTitle')}
  621. aria-label={t('slice.refreshPresets')}
  622. >
  623. <RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
  624. {t('slice.refreshPresets')}
  625. </button>
  626. </div>
  627. {/* CloudStatusBanner above is hidden via flex-1 wrapper when
  628. status === 'ok' (returns null in that case), but the Refresh
  629. button stays visible regardless so users can pick up cloud /
  630. bundled changes even when sign-in is healthy. */}
  631. {/* Slicer Pipelines (#1425): apply a saved preset bundle to all
  632. four slots, or save the current selection as a pipeline.
  633. Pipelines are managed in Settings → Workflow → Pipelines. */}
  634. <div className="flex flex-wrap items-center gap-2 px-2 py-1.5 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary">
  635. <span className="text-xs font-medium text-bambu-gray flex items-center gap-1">
  636. <Cog className="w-3.5 h-3.5" /> {t('slice.pipelines.label', 'Pipeline')}
  637. </span>
  638. <select
  639. value=""
  640. disabled={isEnqueuing || (pipelinesQuery.data?.pipelines.length ?? 0) === 0}
  641. onChange={(e) => {
  642. const id = parseInt(e.target.value, 10);
  643. if (Number.isNaN(id)) return;
  644. const picked = pipelinesQuery.data?.pipelines.find((p) => p.id === id);
  645. if (!picked) return;
  646. // Apply slot state. The filament list is right-padded from
  647. // current state so a pipeline with fewer entries than the
  648. // current source's slot count keeps the existing tail.
  649. setPrinterPreset(picked.printer_preset);
  650. setProcessPreset(picked.process_preset);
  651. setBedType(picked.bed_type);
  652. setFilamentPresets((current) => {
  653. const next = current.length > 0 ? [...current] : picked.filament_presets.map(() => null);
  654. for (let i = 0; i < next.length; i++) {
  655. if (i < picked.filament_presets.length) {
  656. next[i] = picked.filament_presets[i];
  657. }
  658. }
  659. return next;
  660. });
  661. showToast(t('slice.pipelines.toast.applied', 'Applied "{{name}}"', { name: picked.name }), 'success');
  662. // Reset the dropdown so the user can re-apply the same
  663. // pipeline if needed (selects don't fire onChange when
  664. // value reselects the same option).
  665. e.target.value = '';
  666. }}
  667. className="text-xs px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white disabled:opacity-50 disabled:cursor-not-allowed flex-1 min-w-[10ch]"
  668. aria-label={t('slice.pipelines.applyAria', 'Apply pipeline')}
  669. >
  670. <option value="">
  671. {(pipelinesQuery.data?.pipelines.length ?? 0) === 0
  672. ? t('slice.pipelines.empty', 'No saved pipelines')
  673. : t('slice.pipelines.applyPrompt', 'Apply pipeline…')}
  674. </option>
  675. {pipelinesQuery.data?.pipelines.map((p) => (
  676. <option key={p.id} value={p.id}>
  677. {p.name}
  678. </option>
  679. ))}
  680. </select>
  681. {!savePipelineOpen ? (
  682. <button
  683. type="button"
  684. onClick={() => {
  685. setPipelineDraftName('');
  686. setSavePipelineOpen(true);
  687. }}
  688. disabled={
  689. isEnqueuing ||
  690. !printerPreset ||
  691. !processPreset ||
  692. filamentPresets.length === 0 ||
  693. filamentPresets.some((f) => f === null)
  694. }
  695. className="text-xs px-2 py-1 bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green border border-bambu-green/40 rounded disabled:opacity-50 disabled:cursor-not-allowed"
  696. title={t('slice.pipelines.saveTitle', 'Save the current four-slot selection as a reusable pipeline')}
  697. >
  698. {t('slice.pipelines.saveButton', 'Save as pipeline')}
  699. </button>
  700. ) : (
  701. <div className="flex items-center gap-1 flex-1 min-w-[16ch]">
  702. <input
  703. autoFocus
  704. value={pipelineDraftName}
  705. onChange={(e) => setPipelineDraftName(e.target.value)}
  706. placeholder={t('slice.pipelines.namePlaceholder', 'Pipeline name')}
  707. aria-label={t('slice.pipelines.nameAria', 'New pipeline name')}
  708. className="flex-1 text-xs px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white"
  709. />
  710. <button
  711. type="button"
  712. onClick={() => {
  713. const trimmed = pipelineDraftName.trim();
  714. if (!trimmed || !printerPreset || !processPreset) return;
  715. const nonNull = filamentPresets.filter((f): f is PresetRef => f !== null);
  716. if (nonNull.length === 0) return;
  717. createPipelineMutation.mutate({
  718. name: trimmed,
  719. printer_preset: printerPreset,
  720. process_preset: processPreset,
  721. filament_presets: nonNull,
  722. bed_type: bedType,
  723. });
  724. }}
  725. disabled={createPipelineMutation.isPending || !pipelineDraftName.trim()}
  726. className="text-xs px-2 py-1 bg-bambu-green hover:bg-bambu-green/80 text-white rounded disabled:opacity-50"
  727. >
  728. {createPipelineMutation.isPending ? (
  729. <Loader2 className="w-3 h-3 animate-spin" />
  730. ) : (
  731. t('common.save', 'Save')
  732. )}
  733. </button>
  734. <button
  735. type="button"
  736. onClick={() => {
  737. setSavePipelineOpen(false);
  738. setPipelineDraftName('');
  739. }}
  740. className="text-xs px-2 py-1 text-bambu-gray hover:text-white"
  741. >
  742. {t('common.cancel', 'Cancel')}
  743. </button>
  744. </div>
  745. )}
  746. </div>
  747. <PresetDropdown
  748. label={t('slice.printer')}
  749. slot="printer"
  750. data={presetsQuery.data}
  751. value={printerPreset}
  752. onChange={setPrinterPreset}
  753. // Locked in embedded mode too: the picked printer is unused on
  754. // the embedded-settings path, and changing it away from the
  755. // design's target would drop canUseEmbedded and yank the toggle
  756. // out from under the user (#2611).
  757. disabled={isEnqueuing || useEmbedded}
  758. />
  759. {/* "Slice as designed" (#2611): honour the file's embedded
  760. settings instead of the picked process/filament. Offered
  761. only when the picked printer matches the design's target. */}
  762. {canUseEmbedded && (
  763. <label className="flex items-start gap-2 text-sm text-bambu-gray cursor-pointer select-none">
  764. <input
  765. type="checkbox"
  766. checked={useEmbedded}
  767. onChange={(e) => setUseEmbedded(e.target.checked)}
  768. disabled={isEnqueuing}
  769. className="mt-0.5 cursor-pointer"
  770. />
  771. <span>
  772. {t('slice.useEmbedded')}
  773. <span className="block text-xs text-bambu-gray/70">
  774. {t('slice.useEmbeddedHint')}
  775. </span>
  776. </span>
  777. </label>
  778. )}
  779. <PresetDropdown
  780. label={t('slice.process')}
  781. slot="process"
  782. data={presetsQuery.data}
  783. value={processPreset}
  784. onChange={setProcessPreset}
  785. disabled={isEnqueuing || useEmbedded}
  786. selectedPrinterName={selectedPrinterName}
  787. compatIndex={compatIndex}
  788. />
  789. {/* Designer's process tweaks (#2622). BambuStudio records which
  790. keys deviate from the stock preset in the 3MF itself, so a
  791. re-slice for another printer can carry them instead of
  792. flattening them under --load-settings. Hidden entirely when
  793. the source lists none, and disabled in embedded mode where
  794. the process JSON these patch is never sent. */}
  795. {designOverrides.length > 0 && (
  796. <div className="rounded-lg border border-bambu-dark-tertiary bg-bambu-dark/40 p-3">
  797. <button
  798. type="button"
  799. onClick={() => setDesignExpanded((v) => !v)}
  800. className="flex w-full items-center justify-between gap-2 text-left"
  801. >
  802. <span className="text-sm text-white">
  803. {t('slice.designSettings')}
  804. <span className="block text-xs text-bambu-gray/70">
  805. {t('slice.designSettingsHint', { count: designOverrides.length })}
  806. </span>
  807. </span>
  808. <span className="shrink-0 text-xs text-bambu-gray">
  809. {t('slice.designSettingsSelected', { selected: designKeys.size, total: designOverrides.length })}
  810. </span>
  811. </button>
  812. {designExpanded && (
  813. <div className="mt-3 space-y-1.5 border-t border-bambu-dark-tertiary pt-3">
  814. {designOverrides.map((o) => (
  815. <label
  816. key={o.key}
  817. className={`flex items-start gap-2 text-xs ${useEmbedded ? 'opacity-50' : 'cursor-pointer'}`}
  818. >
  819. <input
  820. type="checkbox"
  821. checked={designKeys.has(o.key)}
  822. disabled={isEnqueuing || useEmbedded}
  823. onChange={(e) => {
  824. setDesignKeys((prev) => {
  825. const next = new Set(prev);
  826. if (e.target.checked) next.add(o.key);
  827. else next.delete(o.key);
  828. return next;
  829. });
  830. }}
  831. className="mt-0.5 shrink-0 cursor-pointer"
  832. />
  833. <span className="min-w-0 flex-1">
  834. <span className="font-mono text-bambu-gray">{o.key}</span>
  835. <span className="ml-1.5 break-all text-white">{formatDesignValue(o.value)}</span>
  836. {o.printer_coupled && (
  837. <span
  838. className="ml-1.5 rounded bg-amber-100 px-1 py-0.5 text-[10px] text-amber-700 dark:bg-amber-500/20 dark:text-amber-400"
  839. title={t('slice.designSettingsPrinterCoupledHint')}
  840. >
  841. {t('slice.designSettingsPrinterCoupled')}
  842. </span>
  843. )}
  844. </span>
  845. </label>
  846. ))}
  847. </div>
  848. )}
  849. </div>
  850. )}
  851. {/* Bed-type override (#1337). Always visible, always enabled.
  852. The backend patches curr_bed_type on the resolved process
  853. JSON before forwarding to the sidecar. */}
  854. {/* Bed-type patches curr_bed_type onto the resolved process
  855. JSON, which the embedded-settings path never sends — so it
  856. has no effect there and is disabled to avoid implying it
  857. does. */}
  858. <BedTypeDropdown
  859. value={bedType}
  860. onChange={setBedType}
  861. disabled={isEnqueuing || useEmbedded}
  862. />
  863. {/* Layout passes (#2548) — the GUI's "Auto orient" / "Auto
  864. arrange". Not disabled in embedded mode: these are CLI
  865. actions on the geometry, so they work regardless of where
  866. the print config comes from. */}
  867. <div className="flex flex-col gap-2">
  868. <label className="flex items-start gap-2 text-sm text-bambu-gray cursor-pointer select-none">
  869. <input
  870. type="checkbox"
  871. checked={autoOrient}
  872. onChange={(e) => setAutoOrient(e.target.checked)}
  873. disabled={isEnqueuing}
  874. className="mt-0.5 cursor-pointer"
  875. />
  876. <span>
  877. {t('slice.autoOrient')}
  878. <span className="block text-xs text-bambu-gray/70">
  879. {t('slice.autoOrientHint')}
  880. </span>
  881. </span>
  882. </label>
  883. <label className="flex items-start gap-2 text-sm text-bambu-gray cursor-pointer select-none">
  884. <input
  885. type="checkbox"
  886. checked={autoArrange}
  887. onChange={(e) => setAutoArrange(e.target.checked)}
  888. disabled={isEnqueuing}
  889. className="mt-0.5 cursor-pointer"
  890. />
  891. <span>
  892. {t('slice.autoArrange')}
  893. <span className="block text-xs text-bambu-gray/70">
  894. {t('slice.autoArrangeHint')}
  895. </span>
  896. </span>
  897. </label>
  898. </div>
  899. {/* Filament reqs may need a server-side preview-slice for
  900. unsliced project files (single-pass, then cached). Show a
  901. scoped spinner so the user sees the printer/process
  902. dropdowns instead of an opaque "Loading presets…" wait. */}
  903. {filamentReqsQuery.isLoading ? (
  904. <FilamentAnalysisSpinner
  905. requestId={previewRequestId}
  906. sourceName={source.filename}
  907. />
  908. ) : (
  909. filamentSlots.map((slot, idx) => {
  910. // Slots flagged by the backend as not used by the
  911. // picked plate are auto-picked from project metadata
  912. // and disabled — the slicer CLI still needs a
  913. // profile per project slot, but the user shouldn't
  914. // have to think about slots their plate doesn't
  915. // paint with. used_in_plate defaults to true when
  916. // missing (sliced 3MFs and the no-flag legacy path).
  917. const isUsed = slot.used_in_plate !== false;
  918. const baseLabel =
  919. filamentSlots.length > 1
  920. ? t('slice.filamentSlot', {
  921. index: idx + 1,
  922. type: slot.type,
  923. })
  924. : t('slice.filament');
  925. const label = isUsed
  926. ? baseLabel
  927. : `${baseLabel} ${t('slice.notUsedByPlate')}`;
  928. return (
  929. <PresetDropdown
  930. key={`filament-${idx}`}
  931. label={label}
  932. slot="filament"
  933. data={presetsQuery.data}
  934. value={filamentPresets[idx] ?? null}
  935. onChange={(ref) =>
  936. setFilamentPresets((current) => {
  937. const next = current.length === filamentSlots.length
  938. ? [...current]
  939. : filamentSlots.map((_, i) => current[i] ?? null);
  940. next[idx] = ref;
  941. return next;
  942. })
  943. }
  944. disabled={isEnqueuing || !isUsed || useEmbedded}
  945. swatchColor={filamentSlots.length > 1 ? slot.color : undefined}
  946. selectedPrinterName={selectedPrinterName}
  947. compatIndex={compatIndex}
  948. />
  949. );
  950. })
  951. )}
  952. </>
  953. )}
  954. {errorMessage && (
  955. <div className="text-sm text-red-700 dark:text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2" role="alert">
  956. {errorMessage}
  957. </div>
  958. )}
  959. </div>
  960. {/* Footer */}
  961. <div className="flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40">
  962. <button
  963. type="button"
  964. onClick={onClose}
  965. disabled={isEnqueuing}
  966. className="px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50"
  967. >
  968. {t('common.cancel')}
  969. </button>
  970. {canSliceAll && (
  971. <label
  972. className="flex items-center gap-2 mr-auto text-sm text-bambu-gray cursor-pointer select-none"
  973. title={t('slice.actionAllTitle', { count: totalPlateCount })}
  974. >
  975. <input
  976. type="checkbox"
  977. checked={sliceAllPlates}
  978. onChange={(e) => setSliceAllPlates(e.target.checked)}
  979. disabled={isEnqueuing}
  980. className="cursor-pointer"
  981. />
  982. {t('slice.allPlatesToggle', { count: totalPlateCount })}
  983. </label>
  984. )}
  985. <button
  986. type="button"
  987. onClick={() => {
  988. setErrorMessage(null);
  989. // ``plate=0`` is the sidecar's "all plates" sentinel — passes
  990. // ``--slice 0`` to the BS CLI which produces a single 3MF
  991. // with one ``Metadata/plate_N.gcode`` entry per plate.
  992. const platePayload = sliceAllPlates ? 0 : selectedPlate;
  993. enqueueMutation.mutate(platePayload);
  994. }}
  995. disabled={!isReady || isEnqueuing}
  996. className="px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
  997. >
  998. {isEnqueuing ? (
  999. <>
  1000. <Loader2 className="w-4 h-4 animate-spin" />
  1001. {t('slice.enqueuing')}
  1002. </>
  1003. ) : sliceAllPlates ? (
  1004. t('slice.actionAll', { count: totalPlateCount })
  1005. ) : (
  1006. t('slice.action')
  1007. )}
  1008. </button>
  1009. </div>
  1010. </div>
  1011. </div>
  1012. );
  1013. }
  1014. function CloudStatusBanner({
  1015. status,
  1016. cloudName = 'bambu',
  1017. }: {
  1018. status: SlicerCloudStatus;
  1019. cloudName?: 'bambu' | 'orca';
  1020. }) {
  1021. const { t } = useTranslation();
  1022. // `ok` is the happy path. `not_authenticated` is silenced too: a user who
  1023. // hasn't signed in (or has explicitly logged out — #1712) doesn't need a
  1024. // permanent nag at the top of the modal; sign-in lives on the Profiles
  1025. // page if they want it. Only `expired` and `unreachable` surface — those
  1026. // are real breakage states a previously-signed-in user needs to see.
  1027. if (status === 'ok' || status === 'not_authenticated') return null;
  1028. // Same status vocabulary for both Bambu and Orca Cloud — only the
  1029. // user-facing text varies. The fallbacks below name each cloud explicitly
  1030. // so the banner makes sense without translation when i18n hasn't been
  1031. // updated for a new locale.
  1032. const messages =
  1033. cloudName === 'orca'
  1034. ? {
  1035. expired: {
  1036. key: 'slice.orcaCloud.expired',
  1037. fallback: 'Orca Cloud session expired — sign in again to refresh your Orca presets.',
  1038. },
  1039. unreachable: {
  1040. key: 'slice.orcaCloud.unreachable',
  1041. fallback: 'Orca Cloud is unreachable right now. Other presets still work.',
  1042. },
  1043. }
  1044. : {
  1045. expired: {
  1046. key: 'slice.cloud.expired',
  1047. fallback: 'Bambu Cloud session expired — sign in again to refresh your cloud presets.',
  1048. },
  1049. unreachable: {
  1050. key: 'slice.cloud.unreachable',
  1051. fallback: 'Bambu Cloud is unreachable right now. Local and standard presets still work.',
  1052. },
  1053. };
  1054. const tones: Record<'expired' | 'unreachable', { tone: string; icon: typeof Cloud }> = {
  1055. expired: {
  1056. tone: 'border-amber-300 dark:border-amber-700/40 bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200',
  1057. icon: CloudOff,
  1058. },
  1059. unreachable: {
  1060. tone: 'border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray',
  1061. icon: CloudOff,
  1062. },
  1063. };
  1064. const { tone, icon: Icon } = tones[status];
  1065. const { key, fallback } = messages[status];
  1066. return (
  1067. <div className={`flex items-start gap-2 text-xs rounded-md border p-2 ${tone}`} role="status">
  1068. <Icon className="w-4 h-4 flex-shrink-0 mt-0.5" />
  1069. <span>{t(key, fallback)}</span>
  1070. </div>
  1071. );
  1072. }
  1073. // Build-plate options offered in the SliceModal (#1337). Values are the
  1074. // canonical strings the slicer's StaticPrintConfig validator accepts as
  1075. // `curr_bed_type` — BambuStudio is the default sidecar, so this matches its
  1076. // enum; OrcaSlicer accepts the same set with a Supertack alias that users
  1077. // can target via the same dropdown if they re-import their presets.
  1078. const BED_TYPE_OPTIONS: { value: string; labelKey: string; fallback: string }[] = [
  1079. { value: 'Cool Plate', labelKey: 'slice.bedType.coolPlate', fallback: 'Cool Plate' },
  1080. {
  1081. value: 'Cool Plate (SuperTack)',
  1082. labelKey: 'slice.bedType.coolPlateSuperTack',
  1083. fallback: 'Cool Plate SuperTack',
  1084. },
  1085. { value: 'Engineering Plate', labelKey: 'slice.bedType.engineering', fallback: 'Engineering Plate' },
  1086. { value: 'High Temp Plate', labelKey: 'slice.bedType.highTemp', fallback: 'High Temp Plate' },
  1087. { value: 'Textured PEI Plate', labelKey: 'slice.bedType.texturedPEI', fallback: 'Textured PEI Plate' },
  1088. { value: 'Smooth PEI Plate', labelKey: 'slice.bedType.smoothPEI', fallback: 'Smooth PEI Plate' },
  1089. ];
  1090. function BedTypeDropdown({
  1091. value,
  1092. onChange,
  1093. disabled,
  1094. }: {
  1095. value: string | null;
  1096. onChange: (value: string | null) => void;
  1097. disabled?: boolean;
  1098. }) {
  1099. const { t } = useTranslation();
  1100. return (
  1101. <label className="block">
  1102. <span className="block text-xs text-bambu-gray mb-1">
  1103. {t('slice.bedType.label')}
  1104. </span>
  1105. <select
  1106. value={value ?? ''}
  1107. onChange={(e) => onChange(e.target.value === '' ? null : e.target.value)}
  1108. disabled={disabled}
  1109. className="w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50"
  1110. >
  1111. <option value="">{t('slice.bedType.auto')}</option>
  1112. {BED_TYPE_OPTIONS.map((opt) => (
  1113. <option key={opt.value} value={opt.value}>
  1114. {t(opt.labelKey, opt.fallback)}
  1115. </option>
  1116. ))}
  1117. </select>
  1118. </label>
  1119. );
  1120. }
  1121. interface PresetDropdownProps {
  1122. label: string;
  1123. slot: Slot;
  1124. data: UnifiedPresetsResponse;
  1125. value: PresetRef | null;
  1126. onChange: (ref: PresetRef | null) => void;
  1127. disabled?: boolean;
  1128. // Optional colour swatch shown next to the label — used for multi-color
  1129. // filament slots so the user can see at a glance which slot they're
  1130. // configuring against the source 3MF's per-slot colour.
  1131. swatchColor?: string;
  1132. // Selected printer context (#1325). When provided for a process / filament
  1133. // slot, presets that resolve to a different printer (per compatIndex) move
  1134. // into a trailing "Other printers" group instead of the main tier list.
  1135. selectedPrinterName?: string | null;
  1136. compatIndex?: PrinterCompatibilityIndex;
  1137. }
  1138. function PresetDropdown({
  1139. label,
  1140. slot,
  1141. data,
  1142. value,
  1143. onChange,
  1144. disabled,
  1145. swatchColor,
  1146. selectedPrinterName,
  1147. compatIndex,
  1148. }: PresetDropdownProps) {
  1149. const { t } = useTranslation();
  1150. // Tier sections (imported → cloud → standard), plus — for a process /
  1151. // filament slot with a selected printer — a trailing group of presets that
  1152. // resolve to a different printer (#1325). Compatibility-unknown presets
  1153. // stay in their tier, so a custom / untagged preset is never hidden, and
  1154. // empty sections collapse out.
  1155. const { sections, otherEntries } = useMemo(() => {
  1156. const tiers: { key: keyof UnifiedPresetsResponse; label: string; fallback: string }[] = [
  1157. { key: 'local', label: 'slice.tier.local', fallback: 'Imported' },
  1158. { key: 'orca_cloud', label: 'slice.tier.orcaCloud', fallback: 'Orca Cloud' },
  1159. { key: 'cloud', label: 'slice.tier.cloud', fallback: 'Bambu Cloud' },
  1160. { key: 'standard', label: 'slice.tier.standard', fallback: 'Standard' },
  1161. ];
  1162. const filterByPrinter = slot !== 'printer';
  1163. const compatSections: { tierLabel: string; entries: UnifiedPreset[] }[] = [];
  1164. const other: UnifiedPreset[] = [];
  1165. for (const { key, label: lk, fallback } of tiers) {
  1166. const entries = (data[key] as UnifiedPresetsBySlot)[slot];
  1167. if (!filterByPrinter) {
  1168. if (entries.length > 0) compatSections.push({ tierLabel: t(lk, fallback), entries });
  1169. continue;
  1170. }
  1171. const compatible: UnifiedPreset[] = [];
  1172. for (const p of entries) {
  1173. if (
  1174. presetCompatibility(
  1175. p,
  1176. // filterByPrinter is true here, so slot is never 'printer'.
  1177. slot as 'process' | 'filament',
  1178. selectedPrinterName ?? null,
  1179. compatIndex ?? EMPTY_COMPATIBILITY_INDEX,
  1180. ) === 'mismatch'
  1181. ) {
  1182. other.push(p);
  1183. } else {
  1184. compatible.push(p);
  1185. }
  1186. }
  1187. if (compatible.length > 0) {
  1188. compatSections.push({ tierLabel: t(lk, fallback), entries: compatible });
  1189. }
  1190. }
  1191. return { sections: compatSections, otherEntries: other };
  1192. }, [data, slot, t, selectedPrinterName, compatIndex]);
  1193. const totalEntries =
  1194. sections.reduce((sum, s) => sum + s.entries.length, 0) + otherEntries.length;
  1195. return (
  1196. <label className="block">
  1197. <span className="flex items-center gap-2 text-xs text-bambu-gray mb-1">
  1198. {swatchColor && (
  1199. <span
  1200. className="inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary"
  1201. style={{ backgroundColor: swatchColor || 'transparent' }}
  1202. aria-hidden
  1203. />
  1204. )}
  1205. <span>{label}</span>
  1206. </span>
  1207. <select
  1208. value={toRefValue(value)}
  1209. onChange={(e) => onChange(fromRefValue(e.target.value))}
  1210. disabled={disabled || totalEntries === 0}
  1211. className="w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50"
  1212. >
  1213. <option value="">
  1214. {totalEntries === 0
  1215. ? t('slice.noPresetsForSlot')
  1216. : t('slice.selectPreset')}
  1217. </option>
  1218. {sections.map((section) => (
  1219. <optgroup key={section.tierLabel} label={section.tierLabel}>
  1220. {section.entries.map((p) => (
  1221. <option key={`${p.source}:${p.id}`} value={`${p.source}:${p.id}`}>
  1222. {p.name}
  1223. </option>
  1224. ))}
  1225. </optgroup>
  1226. ))}
  1227. {otherEntries.length > 0 && (
  1228. <optgroup label={t('slice.otherPrinters')}>
  1229. {otherEntries.map((p) => (
  1230. <option key={`${p.source}:${p.id}`} value={`${p.source}:${p.id}`}>
  1231. {p.name}
  1232. </option>
  1233. ))}
  1234. </optgroup>
  1235. )}
  1236. </select>
  1237. </label>
  1238. );
  1239. }