SliceModal.tsx 64 KB

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