ConfigureAmsSlotModal.tsx 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. import { useState, useMemo, useEffect, useCallback, useRef } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Loader2, Settings2, ChevronDown, CheckCircle2, RotateCcw } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { KProfile } from '../api/client';
  7. import { matchesPrinterModelSuffix, presetCompatibility, buildCompatibilityIndex, extractPresetModel } from '../utils/slicerPrinterMatch';
  8. import { toFilamentId } from './spool-form/utils';
  9. import { Button } from './Button';
  10. import { ConfirmModal } from './ConfirmModal';
  11. import { getAmsLabel } from '../utils/amsHelpers';
  12. import { getSwatchStyle } from '../utils/colors';
  13. import { useCancellableTimeout } from '../hooks/useCancellableTimeout';
  14. import { flowApplies, flowLabel, normaliseFlow } from '../utils/nozzleFlow';
  15. import { useToast } from '../contexts/ToastContext';
  16. import { ACTIVE_PRINT_STATES } from '../utils/printer';
  17. interface SlotInfo {
  18. amsId: number;
  19. trayId: number;
  20. trayType?: string;
  21. trayColor?: string;
  22. traySubBrands?: string;
  23. trayInfoIdx?: string;
  24. extruderId?: number;
  25. caliIdx?: number | null;
  26. savedPresetId?: string;
  27. }
  28. // Convert setting_id to tray_info_idx (filament_id format)
  29. // Bambu format: setting_id "GFSL05" → tray_info_idx "GFL05"
  30. function convertToTrayInfoIdx(settingId: string): string {
  31. // Strip version suffix if present (e.g., GFSL05_07 -> GFSL05)
  32. const baseId = settingId.includes('_') ? settingId.split('_')[0] : settingId;
  33. // Bambu presets start with "GFS" - remove the 'S' to get filament_id
  34. if (baseId.startsWith('GFS')) {
  35. return 'GF' + baseId.slice(3);
  36. }
  37. // User presets (PFUS*, PFSP*) - use the base setting_id (without version suffix)
  38. // This follows the pattern that filament_id and setting_id share the same base ID
  39. if (baseId.startsWith('PFUS') || baseId.startsWith('PFSP')) {
  40. return baseId; // Use base ID without version suffix
  41. }
  42. // For other formats, use as-is
  43. return baseId;
  44. }
  45. interface ConfigureAmsSlotModalProps {
  46. isOpen: boolean;
  47. onClose: () => void;
  48. printerId: number;
  49. slotInfo: SlotInfo;
  50. nozzleDiameter?: string;
  51. printerModel?: string;
  52. onSuccess?: () => void;
  53. fullScreen?: boolean;
  54. // The printer's gcode state; a reset is refused while a print is loaded.
  55. printerState?: string | null;
  56. }
  57. // Known filament material types
  58. const MATERIAL_TYPES = ['PLA', 'PETG', 'PCTG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'NYLON', 'PVA', 'HIPS', 'PP', 'PET'];
  59. // Extract filament type from preset name by finding known material type
  60. function parsePresetName(name: string): { material: string; brand: string; variant: string } {
  61. // Remove printer/nozzle suffix first
  62. const withoutSuffix = name.replace(/@.+$/, '').trim();
  63. const upperName = withoutSuffix.toUpperCase();
  64. // Handle "X Support for Y" pattern: the filament type is Y, not X.
  65. // e.g. "PLA Support for PETG PETG Basic" → material is PETG
  66. const supportMatch = upperName.match(/\bSUPPORT\s+FOR\s+/);
  67. if (supportMatch) {
  68. const afterSupport = upperName.slice(supportMatch.index! + supportMatch[0].length);
  69. for (const mat of MATERIAL_TYPES) {
  70. const regex = new RegExp(`\\b${mat}\\b`);
  71. if (regex.test(afterSupport)) {
  72. const brand = withoutSuffix.slice(0, supportMatch.index).trim();
  73. return { material: mat, brand, variant: 'Support' };
  74. }
  75. }
  76. }
  77. // Try to find a known material type in the name
  78. for (const mat of MATERIAL_TYPES) {
  79. // Use word boundary to match whole words only
  80. const regex = new RegExp(`\\b${mat}\\b`, 'i');
  81. if (regex.test(upperName)) {
  82. // Found material, extract brand (everything before material) and variant (after)
  83. const parts = withoutSuffix.split(regex);
  84. const brand = parts[0]?.trim() || '';
  85. const variant = parts[1]?.trim() || '';
  86. return { material: mat, brand, variant };
  87. }
  88. }
  89. // Fallback: assume first word is brand, second is material
  90. const parts = withoutSuffix.split(/\s+/);
  91. if (parts.length >= 2) {
  92. return { material: parts[1], brand: parts[0], variant: parts.slice(2).join(' ') };
  93. }
  94. return { material: withoutSuffix, brand: '', variant: '' };
  95. }
  96. // Identity of a K-profile inside the picker. Both profile lists are
  97. // deduplicated on name+k_value, so this is unique across the whole option set
  98. // — unlike the bare name, which two profiles can share (#2710).
  99. // Option identity. The extruder has to be in here: the printer's calibration
  100. // table is numbered per nozzle, so one filament calibrated on both hotends gives
  101. // two profiles with the same name — and on a Filament Track Switch machine they
  102. // are both offered, because such a slot can reach either nozzle. Keying on
  103. // name+K alone made the two indistinguishable and, when their K happened to
  104. // match, silently collapsed them into whichever came first.
  105. // "[HF] " / "[S] " for a profile measured on a high-flow or standard nozzle;
  106. // nothing where the printer declares no flow (an X1C declares none).
  107. function kProfileFlowPrefix(profile: KProfile): string {
  108. const label = flowLabel(normaliseFlow(profile.nozzle_id));
  109. return label ? `[${label}] ` : '';
  110. }
  111. function kProfileOptionValue(profile: KProfile): string {
  112. return `${profile.extruder_id ?? 0}|${profile.name}|${profile.k_value}`;
  113. }
  114. /**
  115. * Does the printer file its calibration table per hotend?
  116. *
  117. * It is not a property of the machine but of the table it sent. When the
  118. * slot's own hotend appears in it, an index means "entry N of *that* hotend's
  119. * table" and the tagging is load-bearing. When the hotend appears nowhere, the
  120. * tagging says nothing about this slot and scoping by it only hides profiles
  121. * the slot really does use.
  122. */
  123. function tableNamesThisHotend(profiles: KProfile[], extruderId: number | undefined): boolean {
  124. if (extruderId === undefined) return false;
  125. return profiles.some(p => (p.extruder_id ?? 0) === extruderId);
  126. }
  127. /**
  128. * The profile a slot's `cali_idx` points at.
  129. *
  130. * Scoped to the slot's own hotend where the table names it: on the
  131. * maintainer's H2C, index 16 is the left hotend's black PLA at K=0.018 and
  132. * index 15 is the right's at K=0.020, so a right-hand slot bound to 16 must
  133. * come up empty rather than follow the index into the left's table.
  134. *
  135. * Where the table does not name the hotend, the printer is filing one profile
  136. * per filament instead — an X2D's second AMS points at the same entries as its
  137. * first — and demanding a match found nothing at all, leaving every slot on
  138. * that AMS unconfigured with no error (#3044). There the index stands alone.
  139. */
  140. function findProfileByCaliIdx(
  141. profiles: KProfile[],
  142. caliIdx: number,
  143. extruderId: number | undefined
  144. ): KProfile | undefined {
  145. if (tableNamesThisHotend(profiles, extruderId)) {
  146. return profiles.find(p => p.slot_id === caliIdx && (p.extruder_id ?? 0) === extruderId);
  147. }
  148. return profiles.find(p => p.slot_id === caliIdx);
  149. }
  150. // Suffix naming the hotend a profile was calibrated on, for printers that have
  151. // more than one. Empty on single-nozzle machines, where it would be noise.
  152. function kProfileNozzleSuffix(profile: KProfile, isDualNozzle: boolean, t: (k: string) => string): string {
  153. if (!isDualNozzle) return '';
  154. return ` \u00b7 ${profile.extruder_id === 1 ? t('common.left') : t('common.right')}`;
  155. }
  156. // Check if a preset is a user preset (not built-in)
  157. function isUserPreset(settingId: string): boolean {
  158. // Built-in presets have specific patterns, user presets are UUIDs
  159. return !settingId.startsWith('GF') && !settingId.startsWith('P1');
  160. }
  161. // Common color name to hex mapping
  162. const COLOR_NAME_MAP: Record<string, string> = {
  163. // Basic colors
  164. 'white': 'FFFFFF',
  165. 'black': '000000',
  166. 'red': 'FF0000',
  167. 'green': '00FF00',
  168. 'blue': '0000FF',
  169. 'yellow': 'FFFF00',
  170. 'cyan': '00FFFF',
  171. 'magenta': 'FF00FF',
  172. 'orange': 'FFA500',
  173. 'purple': '800080',
  174. 'pink': 'FFC0CB',
  175. 'brown': '8B4513',
  176. 'gray': '808080',
  177. 'grey': '808080',
  178. // Filament-specific colors
  179. 'jade white': 'FFFEF2',
  180. 'ivory': 'FFFFF0',
  181. 'beige': 'F5F5DC',
  182. 'cream': 'FFFDD0',
  183. 'silver': 'C0C0C0',
  184. 'gold': 'FFD700',
  185. 'bronze': 'CD7F32',
  186. 'copper': 'B87333',
  187. 'navy': '000080',
  188. 'teal': '008080',
  189. 'olive': '808000',
  190. 'maroon': '800000',
  191. 'coral': 'FF7F50',
  192. 'salmon': 'FA8072',
  193. 'lime': '32CD32',
  194. 'mint': '98FF98',
  195. 'forest green': '228B22',
  196. 'sky blue': '87CEEB',
  197. 'royal blue': '4169E1',
  198. 'turquoise': '40E0D0',
  199. 'lavender': 'E6E6FA',
  200. 'violet': 'EE82EE',
  201. 'plum': 'DDA0DD',
  202. 'tan': 'D2B48C',
  203. 'chocolate': 'D2691E',
  204. 'charcoal': '36454F',
  205. 'slate': '708090',
  206. 'transparent': '000000', // Will need special handling
  207. 'natural': 'F5F5DC',
  208. 'wood': 'DEB887',
  209. };
  210. // Quick-select color presets (common filament colors)
  211. // Basic colors shown by default
  212. const QUICK_COLORS_BASIC = [
  213. { name: 'White', hex: 'FFFFFF' },
  214. { name: 'Black', hex: '000000' },
  215. { name: 'Red', hex: 'FF0000' },
  216. { name: 'Blue', hex: '0000FF' },
  217. { name: 'Green', hex: '00AA00' },
  218. { name: 'Yellow', hex: 'FFFF00' },
  219. { name: 'Orange', hex: 'FFA500' },
  220. { name: 'Gray', hex: '808080' },
  221. ];
  222. // Extended colors shown when expanded
  223. const QUICK_COLORS_EXTENDED = [
  224. { name: 'Cyan', hex: '00FFFF' },
  225. { name: 'Magenta', hex: 'FF00FF' },
  226. { name: 'Purple', hex: '800080' },
  227. { name: 'Pink', hex: 'FFC0CB' },
  228. { name: 'Brown', hex: '8B4513' },
  229. { name: 'Beige', hex: 'F5F5DC' },
  230. { name: 'Navy', hex: '000080' },
  231. { name: 'Teal', hex: '008080' },
  232. { name: 'Lime', hex: '32CD32' },
  233. { name: 'Gold', hex: 'FFD700' },
  234. { name: 'Silver', hex: 'C0C0C0' },
  235. { name: 'Maroon', hex: '800000' },
  236. { name: 'Olive', hex: '808000' },
  237. { name: 'Coral', hex: 'FF7F50' },
  238. { name: 'Salmon', hex: 'FA8072' },
  239. { name: 'Turquoise', hex: '40E0D0' },
  240. { name: 'Violet', hex: 'EE82EE' },
  241. { name: 'Indigo', hex: '4B0082' },
  242. { name: 'Chocolate', hex: 'D2691E' },
  243. { name: 'Tan', hex: 'D2B48C' },
  244. { name: 'Slate', hex: '708090' },
  245. { name: 'Charcoal', hex: '36454F' },
  246. { name: 'Ivory', hex: 'FFFFF0' },
  247. { name: 'Cream', hex: 'FFFDD0' },
  248. ];
  249. // Try to convert color name to hex
  250. function colorNameToHex(name: string): string | null {
  251. const normalized = name.toLowerCase().trim();
  252. return COLOR_NAME_MAP[normalized] || null;
  253. }
  254. // Escape regex metacharacters and turn whitespace into ``\s+`` so a literal
  255. export function ConfigureAmsSlotModal({
  256. isOpen,
  257. onClose,
  258. printerId,
  259. slotInfo,
  260. nozzleDiameter = '0.4',
  261. printerModel,
  262. onSuccess,
  263. fullScreen,
  264. printerState,
  265. }: ConfigureAmsSlotModalProps) {
  266. const { t } = useTranslation();
  267. const { showToast } = useToast();
  268. const [showResetConfirm, setShowResetConfirm] = useState(false);
  269. // A running print may be feeding from this tray.
  270. const printing = ACTIVE_PRINT_STATES.includes(printerState ?? '');
  271. const [selectedPresetId, setSelectedPresetId] = useState<string>('');
  272. // The preset the dialog preselected on open, i.e. what the slot is already
  273. // on. Lets the K-profile list tell "reopened the slot" from "picked another
  274. // filament" (#3216).
  275. const [openedPresetId, setOpenedPresetId] = useState<string>('');
  276. const [selectedKProfile, setSelectedKProfile] = useState<KProfile | null>(null);
  277. // The same value, readable at mutation-execute time rather than at
  278. // closure-capture time. useMutation hands its options to the observer from an
  279. // *effect*, so a click that lands between a commit and that effect flushing
  280. // runs the previous render's mutationFn — one that closed over the profile as
  281. // it was before the K-profile query resolved. The picker showed the right
  282. // profile and the printer was sent cali_idx -1, binding the default 0.020
  283. // instead of the calibrated K. Written during render on purpose: an effect
  284. // here would inherit the very flush ordering this exists to escape.
  285. const selectedKProfileRef = useRef<KProfile | null>(null);
  286. selectedKProfileRef.current = selectedKProfile;
  287. const [colorHex, setColorHex] = useState<string>(''); // Just the 6-char hex, no alpha
  288. const [colorInput, setColorInput] = useState<string>(''); // User's text input (name or hex)
  289. const [searchQuery, setSearchQuery] = useState('');
  290. const [showSuccess, setShowSuccess] = useState(false);
  291. const [showExtendedColors, setShowExtendedColors] = useState(false);
  292. const scrolledToRef = useRef<string>('');
  293. // The success state is held briefly before the modal closes itself; that
  294. // timer must not outlive the modal.
  295. const { schedule: scheduleClose } = useCancellableTimeout();
  296. // Fetch cloud settings (gracefully handle 401 when logged out)
  297. const { data: cloudSettings, isLoading: settingsLoading, isError: cloudError } = useQuery({
  298. queryKey: ['cloudSettings'],
  299. queryFn: () => api.getCloudSettings(),
  300. enabled: isOpen,
  301. retry: false,
  302. });
  303. // Orca Cloud filament profiles, same shape as Bambu Cloud's. Each query
  304. // is independent — the picker degrades gracefully if Orca Cloud isn't
  305. // connected (no entries surface, no error banner because we don't want
  306. // to nag users who deliberately only use Bambu Cloud).
  307. const { data: orcaCloudList } = useQuery({
  308. queryKey: ['orcaCloudProfilesForAmsSlot'],
  309. queryFn: () => api.orcaCloudListProfiles(),
  310. enabled: isOpen,
  311. retry: false,
  312. });
  313. // Fetch local presets
  314. const { data: localPresets, isLoading: localLoading } = useQuery({
  315. queryKey: ['localPresets'],
  316. queryFn: () => api.getLocalPresets(),
  317. enabled: isOpen,
  318. });
  319. // Fetch built-in filament names (static fallback)
  320. const { data: builtinFilaments, isLoading: builtinLoading } = useQuery({
  321. queryKey: ['builtinFilaments'],
  322. queryFn: () => api.getBuiltinFilaments(),
  323. enabled: isOpen,
  324. staleTime: Infinity,
  325. });
  326. // Fetch K profiles
  327. const { data: kprofilesData, isLoading: kprofilesLoading } = useQuery({
  328. queryKey: ['kprofiles', printerId, nozzleDiameter],
  329. queryFn: () => api.getKProfiles(printerId, nozzleDiameter),
  330. enabled: isOpen && !!printerId,
  331. });
  332. // Fetch color catalog
  333. const { data: colorCatalog } = useQuery({
  334. queryKey: ['colorCatalog'],
  335. queryFn: () => api.getColorCatalog(),
  336. enabled: isOpen,
  337. staleTime: Infinity,
  338. });
  339. // Backend Bambu printer-model registry — drives the @BBL short-code matcher
  340. // and (here) the reverse short-code → long-name lookup that lets us check
  341. // imported local presets' `compatible_printers` list against the slot's
  342. // printer (#1623). Long staleTime: the registry only changes across backend
  343. // releases.
  344. const { data: printerModelsData } = useQuery({
  345. queryKey: ['slicerPrinterModels'],
  346. queryFn: api.getSlicerPrinterModels,
  347. enabled: isOpen,
  348. staleTime: Infinity,
  349. });
  350. // What the spool in this slot is configured to use here: its filament preset
  351. // for this printer's MODEL and its K profile for this slot's hotend. Those
  352. // are the values the user set on the spool, so they are the right defaults
  353. // for a dialog that configures the slot that spool sits in -- the slot's own
  354. // last manual configuration and the tray's RFID data are the fallbacks, not
  355. // the other way round.
  356. const { data: slotSpoolDefaults } = useQuery({
  357. queryKey: ['slot-spool-defaults', printerId, slotInfo.amsId, slotInfo.trayId],
  358. queryFn: () => api.getSlotSpoolDefaults(printerId, slotInfo.amsId, slotInfo.trayId),
  359. enabled: isOpen,
  360. staleTime: 0,
  361. });
  362. const compatIndex = useMemo(
  363. () => buildCompatibilityIndex(printerModelsData ?? {}),
  364. [printerModelsData],
  365. );
  366. // The full printer-preset name for this slot's printer — e.g. the short
  367. // code "X1C" resolves to "Bambu Lab X1 Carbon 0.4 nozzle" via the backend
  368. // registry plus the slot's nozzle. Used to filter imported local presets
  369. // whose `compatible_printers` list is keyed by the full slicer preset name.
  370. // Null when the registry hasn't loaded or no model is known — caller skips
  371. // the filter in that case (fail-open, same shape as the cloud-preset filter).
  372. const fullPrinterName = useMemo<string | null>(() => {
  373. if (!printerModel || !printerModelsData) return null;
  374. for (const [longName, shortCode] of Object.entries(printerModelsData)) {
  375. if (shortCode === printerModel) {
  376. return `${longName.startsWith('Bambu Lab ') ? longName : `Bambu Lab ${longName}`} ${nozzleDiameter} nozzle`;
  377. }
  378. }
  379. return null;
  380. }, [printerModel, printerModelsData, nozzleDiameter]);
  381. // Configure slot mutation
  382. const configureMutation = useMutation({
  383. mutationFn: async () => {
  384. if (!selectedPresetId) throw new Error('No filament preset selected');
  385. // Determine preset source. Orca detection is done via setting_id
  386. // lookup as well as the ``orca_`` prefix because the saved-preset
  387. // pre-population on modal open (the useEffect at the top of this
  388. // component) writes ``slotInfo.savedPresetId`` verbatim — which for a
  389. // historical Orca save would be the raw UUID, no prefix. Falling
  390. // through to the cloud lookup in that case would have thrown
  391. // "Selected preset not found".
  392. const isLocal = selectedPresetId.startsWith('local_');
  393. const isBuiltin = selectedPresetId.startsWith('builtin_');
  394. const orcaSettingId = selectedPresetId.startsWith('orca_')
  395. ? selectedPresetId.replace('orca_', '')
  396. : selectedPresetId;
  397. const orcaPresetCandidate = (!isLocal && !isBuiltin)
  398. ? orcaCloudList?.filament.find(p => p.setting_id === orcaSettingId)
  399. : undefined;
  400. const isOrca = !!orcaPresetCandidate;
  401. const orcaPreset = orcaPresetCandidate ?? null;
  402. const localId = isLocal ? parseInt(selectedPresetId.replace('local_', ''), 10) : null;
  403. const builtinFilamentId = isBuiltin ? selectedPresetId.replace('builtin_', '') : null;
  404. const localPreset = isLocal
  405. ? localPresets?.filament.find(p => p.id === localId)
  406. : null;
  407. const builtinPreset = isBuiltin
  408. ? builtinFilaments?.find(b => b.filament_id === builtinFilamentId)
  409. : null;
  410. // Get the selected cloud preset details (null for local/builtin/orca presets)
  411. const selectedPreset = (!isLocal && !isBuiltin && !isOrca)
  412. ? cloudSettings?.filament.find(p => p.setting_id === selectedPresetId)
  413. : null;
  414. if (!isLocal && !isBuiltin && !isOrca && !selectedPreset) throw new Error('Selected preset not found');
  415. if (isLocal && !localPreset) throw new Error('Selected local preset not found');
  416. if (isBuiltin && !builtinPreset) throw new Error('Selected builtin preset not found');
  417. if (isOrca && !orcaPreset) throw new Error('Selected Orca Cloud preset not found');
  418. // Parse the preset name for filament info
  419. const presetName = isLocal
  420. ? localPreset!.name
  421. : isBuiltin
  422. ? builtinPreset!.name
  423. : isOrca
  424. ? orcaPreset!.name
  425. : selectedPreset!.name;
  426. const parsed = parsePresetName(presetName);
  427. // Get cali_idx from selected K profile's slot_id (-1 = use default 0.020)
  428. const caliIdx = selectedKProfileRef.current?.slot_id ?? -1;
  429. // Use custom color if set, otherwise use current slot color or default
  430. const color = colorHex || slotInfo.trayColor?.slice(0, 6) || 'FFFFFF';
  431. // Create the tray_sub_brands from preset name (without printer/nozzle suffix)
  432. const traySubBrands = presetName.replace(/@.+$/, '').trim();
  433. let trayInfoIdx: string;
  434. let settingId: string;
  435. // Parsed material from preset name — handles "Support for" patterns correctly.
  436. // Prefer this over stored filament_type which may have been parsed with old logic.
  437. const parsedMat = parsed.material.toUpperCase();
  438. // Generic Bambu filament-ID map used to derive a ``tray_info_idx`` for
  439. // local imports, which carry no Bambu setting_id of their own. The printer's
  440. // firmware needs SOMETHING in tray_info_idx to recognize the filament
  441. // type for HMS / drying / colour-matching; the closest generic Bambu
  442. // filament for the parsed material is the right choice.
  443. const GENERIC_IDS: Record<string, string> = {
  444. 'PLA': 'GFL99', 'PLA-CF': 'GFL98', 'PLA SILK': 'GFL96', 'PLA HIGH SPEED': 'GFL95',
  445. 'PETG': 'GFG99', 'PETG HF': 'GFG96', 'PETG-CF': 'GFG98', 'PCTG': 'GFG97',
  446. 'ABS': 'GFB99', 'ASA': 'GFB98',
  447. 'PC': 'GFC99',
  448. 'PA': 'GFN99', 'PA-CF': 'GFN98', 'NYLON': 'GFN99',
  449. 'TPU': 'GFU99',
  450. 'PVA': 'GFS99', 'HIPS': 'GFS98',
  451. 'PE': 'GFP99', 'PP': 'GFP97',
  452. };
  453. if (isLocal) {
  454. // Local presets have no Bambu Cloud setting_id, but need a valid
  455. // tray_info_idx for the printer to recognize the filament type.
  456. const material = (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : localPreset?.filament_type || parsed.material || '').toUpperCase();
  457. // Try exact match first, then base material (strip suffixes like "-CF", "+", " HF")
  458. trayInfoIdx = GENERIC_IDS[material]
  459. || GENERIC_IDS[material.replace(/[-\s]?CF$/, '')]
  460. || GENERIC_IDS[material.replace(/\+$/, '')]
  461. || GENERIC_IDS[material.split(/[-\s]/)[0]]
  462. || '';
  463. settingId = '';
  464. } else if (isOrca) {
  465. // The slot needs the profile's own filament_id: it is the one value
  466. // OrcaSlicer's "Sync filaments" matches a slot by, so anything else
  467. // reaches the slicer as "Generic <material>" (#3003, #3216). The
  468. // backend looks it up from orca_profile_id -- following the profile's
  469. // parents when it has none of its own -- logs the outcome, and falls
  470. // back to the generic for the material only when there is none.
  471. //
  472. // settingId stays empty: the profile id is a UUID, foreign to the
  473. // printer and to the slicer's slot matching alike.
  474. trayInfoIdx = '';
  475. settingId = '';
  476. } else if (isBuiltin) {
  477. // Built-in presets use the filament_id directly as tray_info_idx
  478. trayInfoIdx = builtinFilamentId!;
  479. settingId = '';
  480. } else {
  481. trayInfoIdx = convertToTrayInfoIdx(selectedPresetId);
  482. settingId = selectedPresetId;
  483. // User cloud presets may carry a distinct filament_id in the cloud detail
  484. // (e.g. "P285e239"); prefer it when present. Never fall back to base_id —
  485. // that collapses custom presets to the inherited generic's filament_id and
  486. // makes the slicer resolve the slot to "Generic …" instead (#1053).
  487. if (!selectedPresetId.startsWith('GFS')) {
  488. try {
  489. const detail = await api.getCloudSettingDetail(selectedPresetId);
  490. // The preset's own filament_id is what puts it in the slot as
  491. // itself — the printer stores that id and the slicer matches its
  492. // presets against it. Bambu Cloud normally returns it on the
  493. // envelope; the `setting` fallback covers a response that carries
  494. // it in the preset JSON instead. A preset created in Orca has none
  495. // in either place (#1053), and legitimately falls through.
  496. const nested = detail.setting?.filament_id;
  497. const ownFilamentId = detail.filament_id || (typeof nested === 'string' ? nested : '');
  498. if (ownFilamentId) {
  499. trayInfoIdx = ownFilamentId;
  500. }
  501. } catch (e) {
  502. console.warn('Failed to fetch preset detail for filament_id:', e);
  503. }
  504. }
  505. // Last resort: neither place had one, so trayInfoIdx is still the
  506. // cloud setting_id — and sending one is worse than sending nothing
  507. // (#3003). tray_info_idx is 8 characters on the printer; an
  508. // 18-character PFUS is stored truncated and acknowledged as a success,
  509. // so the slot ends up holding an id that resolves nowhere — the slicer
  510. // shows "Generic", and the calibration table, keyed by this field,
  511. // loses the slot too. Blank means the backend picks the slot's
  512. // existing filament id or a generic for the material; settingId still
  513. // carries the preset.
  514. if (/^(PFUS|PFSP|PFCN)/.test(trayInfoIdx)) {
  515. console.warn(
  516. `Cloud preset ${selectedPresetId} carries no filament_id in either place; ` +
  517. 'sending no tray_info_idx so the printer keeps a resolvable one.'
  518. );
  519. trayInfoIdx = '';
  520. }
  521. }
  522. // Default temp range — use local preset core fields if available
  523. let tempMin = isLocal && localPreset?.nozzle_temp_min ? localPreset.nozzle_temp_min : 190;
  524. let tempMax = isLocal && localPreset?.nozzle_temp_max ? localPreset.nozzle_temp_max : 230;
  525. if (!isLocal || isBuiltin || isOrca || (!localPreset?.nozzle_temp_min && !localPreset?.nozzle_temp_max)) {
  526. // Fall back to material-based defaults (prefer parsed material for "Support for" handling)
  527. const material = (isLocal
  528. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : localPreset?.filament_type || parsed.material || '')
  529. : parsed.material).toUpperCase();
  530. if (material.includes('PLA')) {
  531. tempMin = 190;
  532. tempMax = 230;
  533. } else if (material.includes('PETG')) {
  534. tempMin = 220;
  535. tempMax = 260;
  536. } else if (material.includes('ABS')) {
  537. tempMin = 240;
  538. tempMax = 280;
  539. } else if (material.includes('ASA')) {
  540. tempMin = 240;
  541. tempMax = 280;
  542. } else if (material.includes('TPU')) {
  543. tempMin = 200;
  544. tempMax = 240;
  545. } else if (material === 'PCTG') {
  546. tempMin = 220;
  547. tempMax = 260;
  548. } else if (material.includes('PC')) {
  549. tempMin = 260;
  550. tempMax = 300;
  551. } else if (material.includes('PA') || material.includes('NYLON')) {
  552. tempMin = 250;
  553. tempMax = 290;
  554. }
  555. }
  556. // Parse K value from selected profile
  557. const kValue = selectedKProfileRef.current?.k_value
  558. ? parseFloat(selectedKProfileRef.current.k_value)
  559. : 0;
  560. // Determine tray_type: prefer parsed material from preset name (handles "Support for"
  561. // patterns correctly) over stored filament_type which may have been parsed with old logic.
  562. const trayType = isLocal
  563. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : localPreset?.filament_type || parsed.material || 'PLA')
  564. : isOrca
  565. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : parsed.material || 'PLA')
  566. : (parsed.material || 'PLA');
  567. // Configure the slot via MQTT
  568. const result = await api.configureAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId, {
  569. tray_info_idx: trayInfoIdx,
  570. tray_type: trayType,
  571. tray_sub_brands: traySubBrands,
  572. tray_color: color + 'FF', // Add alpha
  573. nozzle_temp_min: tempMin,
  574. nozzle_temp_max: tempMax,
  575. cali_idx: caliIdx,
  576. nozzle_diameter: nozzleDiameter,
  577. setting_id: settingId, // Full setting ID for slicer compatibility (empty for local)
  578. // Pass K profile's filament_id and setting_id for proper linking
  579. kprofile_filament_id: selectedKProfileRef.current?.filament_id,
  580. kprofile_setting_id: selectedKProfileRef.current?.setting_id || undefined,
  581. // Also pass the K value directly for extrusion_cali_set command
  582. k_value: kValue,
  583. orca_profile_id: isOrca ? orcaSettingId : undefined,
  584. });
  585. if (result.k_value_unsent) {
  586. showToast(t('configureAmsSlot.kValueUnsent'), 'warning');
  587. }
  588. if (isOrca && result.orca_fallback_reason) {
  589. showToast(
  590. t(`configureAmsSlot.orcaFallback.${result.orca_fallback_reason}`, { material: trayType }),
  591. 'warning',
  592. );
  593. }
  594. // Save the preset mapping so we can display the correct name in the UI
  595. // This is needed because user presets use filament_id (e.g., P285e239) as tray_info_idx,
  596. // which can't be resolved to a name via the filamentInfo API
  597. const mappingPresetId = isLocal
  598. ? `local_${localId}`
  599. : isBuiltin
  600. ? `builtin_${builtinFilamentId}`
  601. : isOrca
  602. ? selectedPresetId
  603. : selectedPresetId;
  604. const mappingSource = isLocal
  605. ? 'local'
  606. : isBuiltin
  607. ? 'builtin'
  608. : isOrca
  609. ? 'orca_cloud'
  610. : 'cloud';
  611. try {
  612. // The filament id goes with it, so the slot card can tell when the slot
  613. // is re-configured from elsewhere and stop showing this preset (#3216).
  614. await api.saveSlotPreset(printerId, slotInfo.amsId, slotInfo.trayId, mappingPresetId, traySubBrands, mappingSource, result.tray_info_idx);
  615. } catch (e) {
  616. console.warn('Failed to save slot preset mapping:', e);
  617. // Don't fail the whole operation - slot was configured successfully
  618. }
  619. return result;
  620. },
  621. onSuccess: () => {
  622. setShowSuccess(true);
  623. onSuccess?.();
  624. // Close after showing success briefly
  625. scheduleClose(() => {
  626. setShowSuccess(false);
  627. onClose();
  628. }, 1500);
  629. },
  630. });
  631. // Reset slot mutation
  632. const resetMutation = useMutation({
  633. mutationFn: async () => {
  634. return api.resetAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId);
  635. },
  636. onSuccess: () => {
  637. setShowSuccess(true);
  638. onSuccess?.();
  639. scheduleClose(() => {
  640. setShowSuccess(false);
  641. onClose();
  642. }, 1500);
  643. },
  644. });
  645. // Unified preset item for the list (orca_cloud + cloud + local + builtin fallback)
  646. type PresetItem = { id: string; name: string; source: 'orca_cloud' | 'cloud' | 'local' | 'builtin'; isUser: boolean };
  647. // Filter filament presets based on search (merged orca_cloud + cloud + local + builtin)
  648. const filteredPresets = useMemo(() => {
  649. const query = searchQuery.toLowerCase();
  650. const items: PresetItem[] = [];
  651. // Collect IDs already covered by higher-priority tiers to avoid duplicates
  652. const coveredIds = new Set<string>();
  653. // Currently-configured preset should always be shown (bypass model filter)
  654. const savedId = slotInfo.savedPresetId;
  655. const trayIdx = slotInfo.trayInfoIdx;
  656. // 0. Orca Cloud filament presets — surfaced first because the user
  657. // explicitly opted into Orca sync; their picks should outrank Bambu Cloud
  658. // presets of the same name. IDs are prefixed ``orca_`` so the configure
  659. // flow can detect "this is an Orca preset" via a cheap string check
  660. // (mirrors the ``local_`` / ``builtin_`` prefix convention already in use).
  661. if (orcaCloudList?.filament) {
  662. for (const op of orcaCloudList.filament) {
  663. const orcaId = `orca_${op.setting_id}`;
  664. coveredIds.add(op.setting_id);
  665. coveredIds.add(orcaId);
  666. if (query && !op.name.toLowerCase().includes(query)) continue;
  667. if (printerModel) {
  668. const presetModel = extractPresetModel(op.name, printerModelsData ?? {});
  669. if (presetModel && !matchesPrinterModelSuffix(presetModel, printerModel)) continue;
  670. }
  671. // All Orca Cloud profiles are user-authored, so isUser is always true.
  672. items.push({ id: orcaId, name: op.name, source: 'orca_cloud', isUser: true });
  673. }
  674. }
  675. // 1. Cloud presets
  676. if (cloudSettings?.filament) {
  677. for (const cp of cloudSettings.filament) {
  678. if (coveredIds.has(cp.setting_id)) continue;
  679. coveredIds.add(cp.setting_id);
  680. // Keep preset if it matches the slot's saved mapping or current tray_info_idx
  681. const isSavedPreset = savedId === cp.setting_id;
  682. const isCurrentPreset = isSavedPreset
  683. || (trayIdx && (cp.setting_id === trayIdx || convertToTrayInfoIdx(cp.setting_id) === trayIdx));
  684. // Search filter applies to ALL presets (including saved) — no bypass
  685. if (query && !cp.name.toLowerCase().includes(query)) continue;
  686. // Filter by printer model if set (skip for current preset). Uses the
  687. // alias-aware match so Bambu's "A1 Mini" → "A1M" cloud rename (#1649)
  688. // doesn't hide A1 Mini cloud profiles.
  689. if (!isCurrentPreset && printerModel) {
  690. const presetModel = extractPresetModel(cp.name, printerModelsData ?? {});
  691. if (presetModel && !matchesPrinterModelSuffix(presetModel, printerModel)) continue;
  692. }
  693. items.push({ id: cp.setting_id, name: cp.name, source: 'cloud', isUser: isUserPreset(cp.setting_id) });
  694. }
  695. }
  696. // 2. Local presets — filter by the slicer's own ``compatible_printers``
  697. // list when present (#1623). LocalPreset.compatible_printers is a JSON-
  698. // encoded string array; presetCompatibility returns 'mismatch' when the
  699. // list is set and our derived full printer name isn't in it, 'unknown'
  700. // when neither the list nor an @BBL token is parseable — we hide on
  701. // 'mismatch' only so user-imported presets without compatible_printers
  702. // still surface (back-compat with the prior "always show" behaviour for
  703. // hand-edited / lossily-imported presets).
  704. if (localPresets?.filament) {
  705. const savedLocalId = slotInfo.savedPresetId;
  706. for (const lp of localPresets.filament) {
  707. const localId = `local_${lp.id}`;
  708. if (query && !lp.name.toLowerCase().includes(query)) continue;
  709. const isCurrentPreset = savedLocalId === localId;
  710. if (!isCurrentPreset && fullPrinterName) {
  711. let compatList: string[] | null = null;
  712. if (lp.compatible_printers) {
  713. try {
  714. const parsed = JSON.parse(lp.compatible_printers);
  715. if (Array.isArray(parsed)) compatList = parsed.filter((s): s is string => typeof s === 'string');
  716. } catch {
  717. compatList = null;
  718. }
  719. }
  720. const verdict = presetCompatibility(
  721. { name: lp.name, compatible_printers: compatList },
  722. 'filament',
  723. fullPrinterName,
  724. compatIndex,
  725. );
  726. if (verdict === 'mismatch') continue;
  727. }
  728. items.push({ id: localId, name: lp.name, source: 'local', isUser: false });
  729. }
  730. }
  731. // 3. Built-in filament names (fallback — only add entries not already covered)
  732. if (builtinFilaments) {
  733. for (const bf of builtinFilaments) {
  734. if (coveredIds.has(bf.filament_id)) continue;
  735. // Convert filament_id to setting_id format for cloud compatibility
  736. // e.g. "GFA00" → cloud setting_id would be "GFSA00" (insert S after GF)
  737. const settingId = bf.filament_id.startsWith('GF')
  738. ? 'GFS' + bf.filament_id.slice(2)
  739. : bf.filament_id;
  740. if (coveredIds.has(settingId)) continue;
  741. if (!query || bf.name.toLowerCase().includes(query)) {
  742. items.push({ id: `builtin_${bf.filament_id}`, name: bf.name, source: 'builtin', isUser: false });
  743. }
  744. }
  745. }
  746. // Sort: local first (user explicitly imported them), then orca_cloud,
  747. // then bambu cloud, then builtin fallback. Matches the SliceModal
  748. // tier priority.
  749. return items.sort((a, b) => {
  750. const sourceOrder = { local: 0, orca_cloud: 1, cloud: 2, builtin: 3 };
  751. if (a.source !== b.source) return sourceOrder[a.source] - sourceOrder[b.source];
  752. if (a.isUser && !b.isUser) return -1;
  753. if (!a.isUser && b.isUser) return 1;
  754. return a.name.localeCompare(b.name);
  755. });
  756. }, [orcaCloudList?.filament, cloudSettings?.filament, localPresets?.filament, builtinFilaments, searchQuery, printerModel, slotInfo.savedPresetId, slotInfo.trayInfoIdx, fullPrinterName, compatIndex, printerModelsData]);
  757. // Get full preset name for K profile filtering (brand + material, without printer suffix)
  758. const selectedPresetInfo = useMemo(() => {
  759. if (!selectedPresetId) return null;
  760. // Resolve the name from orca, cloud, local, or builtin presets. The
  761. // Orca branch tolerates both ``orca_<UUID>`` and a bare UUID — see the
  762. // configure-mutation comment for why the raw UUID also reaches us.
  763. // ``filamentId`` is the bare Bambu filament_id (e.g. "GFG98") when the
  764. // preset has one — used to id-match K-profiles directly without name
  765. // parsing (#1688). Empty string for paths with no usable filament_id
  766. // (orca presets, local presets), which makes the id-match branch skip.
  767. let presetName: string | null = null;
  768. let filamentId = '';
  769. if (selectedPresetId.startsWith('local_')) {
  770. const localId = parseInt(selectedPresetId.replace('local_', ''), 10);
  771. const lp = localPresets?.filament.find(p => p.id === localId);
  772. presetName = lp?.name || null;
  773. } else if (selectedPresetId.startsWith('builtin_')) {
  774. const builtinFilamentId = selectedPresetId.replace('builtin_', '');
  775. const bf = builtinFilaments?.find(b => b.filament_id === builtinFilamentId);
  776. presetName = bf?.name || null;
  777. filamentId = toFilamentId(builtinFilamentId);
  778. } else {
  779. const orcaCandidateId = selectedPresetId.startsWith('orca_')
  780. ? selectedPresetId.replace('orca_', '')
  781. : selectedPresetId;
  782. const op = orcaCloudList?.filament.find(p => p.setting_id === orcaCandidateId);
  783. if (op) {
  784. presetName = op.name;
  785. } else if (cloudSettings?.filament) {
  786. const cp = cloudSettings.filament.find(p => p.setting_id === selectedPresetId);
  787. presetName = cp?.name || null;
  788. if (cp) {
  789. // SlicerSetting only carries setting_id ("GFSG98_09"); toFilamentId
  790. // drops the variant suffix and the "S" infix to yield "GFG98".
  791. filamentId = toFilamentId(cp.setting_id);
  792. }
  793. }
  794. }
  795. if (!presetName) {
  796. return null;
  797. }
  798. // Remove printer/nozzle suffix (e.g., "@BBL X1C" or "@0.4 nozzle")
  799. let nameWithoutSuffix = presetName.replace(/@.+$/, '').trim();
  800. // Strip leading "# " from custom preset names (user convention)
  801. if (nameWithoutSuffix.startsWith('# ')) {
  802. nameWithoutSuffix = nameWithoutSuffix.slice(2).trim();
  803. }
  804. const parsed = parsePresetName(nameWithoutSuffix);
  805. return {
  806. fullName: nameWithoutSuffix,
  807. material: parsed.material,
  808. brand: parsed.brand,
  809. filamentId,
  810. };
  811. }, [selectedPresetId, cloudSettings?.filament, localPresets?.filament, builtinFilaments, orcaCloudList?.filament]);
  812. // For backwards compatibility with the label
  813. const selectedMaterial = selectedPresetInfo?.fullName || '';
  814. // Filter color catalog entries matching the selected preset's brand + material
  815. const catalogColors = useMemo(() => {
  816. if (!colorCatalog || !selectedPresetInfo) return [];
  817. const { fullName, brand } = selectedPresetInfo;
  818. // Try to find colors matching the full preset name (e.g., "PLA Metal")
  819. // The catalog uses the variant as part of the material field (e.g., material="PLA Metal")
  820. // Extract the full material+variant from the preset name
  821. const materialVariant = fullName.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i, '').trim();
  822. return colorCatalog.filter(entry => {
  823. const entryMaterial = (entry.material || '').toUpperCase();
  824. const entryManufacturer = entry.manufacturer.toUpperCase();
  825. // Match material: try full material+variant first, then just material type
  826. const materialMatch = entryMaterial === materialVariant.toUpperCase()
  827. || entryMaterial.includes(materialVariant.toUpperCase())
  828. || materialVariant.toUpperCase().includes(entryMaterial);
  829. if (!materialMatch) return false;
  830. // If brand is present, also match manufacturer
  831. if (brand) {
  832. const upperBrand = brand.toUpperCase();
  833. // Fuzzy match: "Bambu" matches "Bambu Lab", etc.
  834. if (!entryManufacturer.includes(upperBrand) && !upperBrand.includes(entryManufacturer)) {
  835. return false;
  836. }
  837. }
  838. return true;
  839. });
  840. }, [colorCatalog, selectedPresetInfo]);
  841. // Dual-nozzle if the printer reported calibration profiles for more than one
  842. // extruder. Self-contained, and exactly the condition under which naming the
  843. // hotend on each option is worth the space.
  844. const isDualNozzleProfiles = useMemo(
  845. () => new Set((kprofilesData?.profiles ?? []).map(p => p.extruder_id ?? 0)).size > 1,
  846. [kprofilesData?.profiles]
  847. );
  848. // The flow of the nozzle on the slot's hotend, from the printer status the
  849. // printer card already keeps (H2-series report HH01 / HS01; others nothing).
  850. const { data: printerStatus } = useQuery({
  851. queryKey: ['printerStatus', printerId],
  852. queryFn: () => api.getPrinterStatus(printerId),
  853. enabled: isOpen,
  854. });
  855. const fittedFlow = useMemo(() => {
  856. const nozzles = printerStatus?.nozzles ?? [];
  857. const extruder = slotInfo.extruderId ?? 0;
  858. return normaliseFlow(nozzles[extruder]?.nozzle_type) ?? normaliseFlow(nozzles[0]?.nozzle_type);
  859. }, [printerStatus?.nozzles, slotInfo.extruderId]);
  860. const matchingKProfiles = useMemo(() => {
  861. if (!kprofilesData?.profiles) return [];
  862. if (!selectedPresetInfo) {
  863. // Assigned-but-unconfigured slot (filament loaded but the printer hasn't
  864. // bound a preset yet: tray_type=""/tray_info_idx=""/no slot_preset_mappings
  865. // row). The cali_idx safety net further down lives past the main name+id
  866. // matcher and never runs from here, so surface the slot's currently-active
  867. // K-profile directly so Configure Slot keeps showing it across reopen
  868. // instead of dropping to default 0.020 (#1689 follow-up).
  869. const activeIdx = slotInfo.caliIdx;
  870. if (activeIdx != null && activeIdx > 0) {
  871. const active = findProfileByCaliIdx(kprofilesData.profiles, activeIdx, slotInfo.extruderId);
  872. if (active) return [active];
  873. }
  874. return [];
  875. }
  876. const { fullName, material, brand, filamentId } = selectedPresetInfo;
  877. const upperFullName = fullName.toUpperCase();
  878. const upperMaterial = material.toUpperCase();
  879. // "Generic" leads every built-in Bambu preset name ("Generic PLA",
  880. // "Generic PETG") but is not a manufacturer (#2710). Treating it as one
  881. // put the filter into brand-gated mode and demanded "GENERIC" in the
  882. // K-profile name, which no real profile has — so selecting a built-in
  883. // generic preset matched nothing at all.
  884. const upperBrand = brand.toUpperCase() === 'GENERIC' ? '' : brand.toUpperCase();
  885. const presetFid = filamentId; // already normalised via toFilamentId
  886. // Material must be at least 2 chars to avoid false positives
  887. if (!upperMaterial || upperMaterial.length < 2) return [];
  888. // Filter profiles - require brand match if brand is present in selected preset
  889. const filtered = kprofilesData.profiles.filter(p => {
  890. // Preferred: exact filament_id match (#1688). A user's custom K-profile
  891. // whose name doesn't agree with the slicer preset still surfaces when
  892. // both sides agree on filament_id.
  893. //
  894. // Generic GFx99 ids count here too (#2710). The equality test already
  895. // means both sides carry the *same* id, so the old "generic ids
  896. // over-match" exclusion could only ever fire when the selected preset
  897. // was itself the generic one — precisely the case where the match is
  898. // right. The printer keeps one calibration table per filament_id, so a
  899. // slot on "Generic PLA" should offer every profile calibrated under
  900. // Generic PLA, whatever the user named them.
  901. if (presetFid) {
  902. const calFid = toFilamentId(p.filament_id);
  903. if (calFid && calFid === presetFid) {
  904. return true;
  905. }
  906. }
  907. const profileName = p.name.toUpperCase();
  908. // If the selected preset has a brand (e.g., "Azurefilm PLA Wood"),
  909. // only show profiles that match the brand
  910. if (upperBrand) {
  911. // Must contain the brand name
  912. if (!profileName.includes(upperBrand)) {
  913. return false;
  914. }
  915. // And must contain the material type
  916. if (!profileName.includes(upperMaterial)) {
  917. return false;
  918. }
  919. return true;
  920. }
  921. // No brand in selected preset - match on full name or material
  922. // Priority 1: Exact match with full name
  923. if (profileName.includes(upperFullName)) {
  924. return true;
  925. }
  926. // Priority 2: Material type match (only when no brand specified)
  927. if (profileName.includes(upperMaterial)) {
  928. return true;
  929. }
  930. // Check for common material aliases
  931. const aliases: Record<string, string[]> = {
  932. 'NYLON': ['PA', 'PA-CF', 'PA6'],
  933. 'PA': ['NYLON'],
  934. };
  935. const materialAliases = aliases[upperMaterial] || [];
  936. for (const alias of materialAliases) {
  937. if (profileName.includes(alias)) {
  938. return true;
  939. }
  940. }
  941. return false;
  942. });
  943. // Scope to the slot's own nozzle where the table names it: a K-profile
  944. // calibrated on the other hotend is not a match for this slot, and offering
  945. // it as one is how the wrong K got bound. Those profiles are still
  946. // reachable below under "Other", where the option label names the hotend.
  947. //
  948. // Where the table names no profile on this hotend at all, scoping emptied
  949. // the list instead — the X2D case in #3044, where the second AMS's slots
  950. // point at the first's entries — so the tagging is ignored rather than
  951. // enforced.
  952. const onThisHotend = tableNamesThisHotend(kprofilesData.profiles, slotInfo.extruderId)
  953. ? filtered.filter(p => (p.extruder_id ?? 0) === slotInfo.extruderId)
  954. : filtered;
  955. // And to the flow of the nozzle fitted there: a K measured on a high-flow
  956. // nozzle is not a fact about a standard one, and the backend does not apply
  957. // it at assign time. Unknown flow on either side matches (an X1C reports
  958. // none). The others stay reachable under "Other", labelled [HF] / [S].
  959. const onThisNozzle = onThisHotend.filter(p => flowApplies(p.nozzle_id, fittedFlow));
  960. // Deduplicate genuine duplicates — same nozzle, same name, same K.
  961. const seen = new Map<string, KProfile>();
  962. for (const profile of onThisNozzle) {
  963. const key = kProfileOptionValue(profile);
  964. if (!seen.has(key)) seen.set(key, profile);
  965. }
  966. const result = Array.from(seen.values());
  967. // Always include the slot's currently-active K-profile (by cali_idx / slot_id),
  968. // even if its name and filament_id didn't match the selected preset (#1689).
  969. // A spool assigned under "Generic PLA" can have a K-profile actively bound on
  970. // the printer whose filament_id differs from "Generic PLA"; without this
  971. // safety net the modal shows "not assigned, default 0.020" while the printer
  972. // card's hover-card correctly shows the active profile.
  973. //
  974. // Only while the selected preset is still the slot's own, though: the
  975. // active profile belongs to whatever filament the slot is on now. Offered
  976. // for a different filament, the auto-select below picked it, and the
  977. // backend then realigned the slot to that profile's filament -- so
  978. // configuring Azurefilm on a slot that held Devil Design re-sent Devil
  979. // Design (#3216).
  980. const activeIdx = slotInfo.caliIdx;
  981. const onSlotsOwnPreset = (!!openedPresetId && selectedPresetId === openedPresetId)
  982. || (!!presetFid && presetFid === toFilamentId(slotInfo.trayInfoIdx));
  983. if (onSlotsOwnPreset && activeIdx != null && activeIdx > 0 && !result.some(p => p.slot_id === activeIdx)) {
  984. const active = findProfileByCaliIdx(kprofilesData.profiles, activeIdx, slotInfo.extruderId);
  985. if (active) result.unshift(active);
  986. }
  987. return result;
  988. }, [kprofilesData?.profiles, selectedPresetInfo, slotInfo.extruderId, slotInfo.caliIdx, slotInfo.trayInfoIdx, selectedPresetId, openedPresetId, fittedFlow]);
  989. // Every remaining K-profile the printer holds, offered under a separate group
  990. // after the matching ones (#2710). The matcher works off preset names and
  991. // filament ids, neither of which the user controls when they name a profile
  992. // after its colour — so there is always a residual chance it filters out a
  993. // profile the user wants. This makes that recoverable in the UI instead of
  994. // sending them to the slicer: the printer's own calibration table is the
  995. // authority on what can be selected, and the backend realigns the slot's
  996. // filament context to whichever profile is picked.
  997. const otherKProfiles = useMemo(() => {
  998. if (!kprofilesData?.profiles) return [];
  999. const matched = new Set(matchingKProfiles.map(p => kProfileOptionValue(p)));
  1000. // Same name+k_value dedup as the matching list, so a multi-nozzle printer's
  1001. // duplicate rows don't show up twice here either.
  1002. const seen = new Map<string, KProfile>();
  1003. for (const profile of kprofilesData.profiles) {
  1004. const key = kProfileOptionValue(profile);
  1005. if (matched.has(key)) continue;
  1006. if (!seen.has(key)) seen.set(key, profile);
  1007. }
  1008. return Array.from(seen.values()).sort((a, b) => a.name.localeCompare(b.name));
  1009. }, [kprofilesData?.profiles, matchingKProfiles]);
  1010. const hasAnyKProfile = matchingKProfiles.length > 0 || otherKProfiles.length > 0;
  1011. const selectKProfileByValue = useCallback((value: string) => {
  1012. if (!value) {
  1013. setSelectedKProfile(null);
  1014. return;
  1015. }
  1016. const profile = matchingKProfiles.find(p => kProfileOptionValue(p) === value)
  1017. || otherKProfiles.find(p => kProfileOptionValue(p) === value)
  1018. || null;
  1019. setSelectedKProfile(profile);
  1020. }, [matchingKProfiles, otherKProfiles]);
  1021. // Pre-select current profile when modal opens, reset when closes
  1022. useEffect(() => {
  1023. if (isOpen) {
  1024. // The spool's own per-model preset first -- see the query above.
  1025. if (slotSpoolDefaults?.slicer_filament) {
  1026. setSelectedPresetId(slotSpoolDefaults.slicer_filament);
  1027. setOpenedPresetId(slotSpoolDefaults.slicer_filament);
  1028. } else if (slotInfo.savedPresetId) {
  1029. setSelectedPresetId(slotInfo.savedPresetId);
  1030. setOpenedPresetId(slotInfo.savedPresetId);
  1031. } else if (slotInfo.trayInfoIdx && cloudSettings?.filament) {
  1032. // Fallback: try to match by tray_info_idx in cloud presets
  1033. // First try exact match on setting_id
  1034. let currentPreset = cloudSettings.filament.find(
  1035. p => p.setting_id === slotInfo.trayInfoIdx
  1036. );
  1037. // Then try matching by converting setting_id → filament_id format
  1038. if (!currentPreset) {
  1039. currentPreset = cloudSettings.filament.find(
  1040. p => convertToTrayInfoIdx(p.setting_id) === slotInfo.trayInfoIdx
  1041. );
  1042. }
  1043. if (currentPreset) {
  1044. setSelectedPresetId(currentPreset.setting_id);
  1045. setOpenedPresetId(currentPreset.setting_id);
  1046. }
  1047. } else if (slotInfo.trayInfoIdx && builtinFilaments?.length) {
  1048. // Last resort: match trayInfoIdx against builtin presets
  1049. const trayIdx = slotInfo.trayInfoIdx;
  1050. const match = builtinFilaments.find(bf => bf.filament_id === trayIdx);
  1051. if (match) {
  1052. setSelectedPresetId(`builtin_${match.filament_id}`);
  1053. setOpenedPresetId(`builtin_${match.filament_id}`);
  1054. }
  1055. }
  1056. // Pre-populate color from current slot (black is valid — empty slots don't pass trayColor)
  1057. if (slotInfo.trayColor) {
  1058. const hex = slotInfo.trayColor.slice(0, 6);
  1059. if (hex) {
  1060. setColorHex(hex);
  1061. }
  1062. }
  1063. } else {
  1064. // Reset when modal closes
  1065. setSelectedPresetId('');
  1066. setOpenedPresetId('');
  1067. setSelectedKProfile(null);
  1068. setColorHex('');
  1069. setColorInput('');
  1070. setSearchQuery('');
  1071. setShowSuccess(false);
  1072. scrolledToRef.current = '';
  1073. }
  1074. }, [
  1075. isOpen,
  1076. slotSpoolDefaults?.slicer_filament,
  1077. slotInfo.savedPresetId,
  1078. slotInfo.trayInfoIdx,
  1079. slotInfo.trayColor,
  1080. cloudSettings?.filament,
  1081. builtinFilaments,
  1082. ]);
  1083. // Auto-select best matching K profile when preset changes
  1084. useEffect(() => {
  1085. if (matchingKProfiles.length > 0) {
  1086. // The profile the spool is configured with for THIS hotend, if it still
  1087. // exists on the printer. Ahead of the slot's live cali_idx, which is
  1088. // whatever was selected last rather than what the spool is set to.
  1089. if (slotSpoolDefaults?.cali_idx != null) {
  1090. const configured = findProfileByCaliIdx(
  1091. matchingKProfiles,
  1092. slotSpoolDefaults.cali_idx,
  1093. slotSpoolDefaults.extruder ?? slotInfo.extruderId,
  1094. );
  1095. if (configured) {
  1096. setSelectedKProfile(configured);
  1097. return;
  1098. }
  1099. }
  1100. // Prefer the currently-active K-profile, resolved against this slot's own
  1101. // nozzle — the index alone is ambiguous across hotends.
  1102. if (slotInfo.caliIdx != null && slotInfo.caliIdx > 0) {
  1103. const active = findProfileByCaliIdx(matchingKProfiles, slotInfo.caliIdx, slotInfo.extruderId);
  1104. if (active) {
  1105. setSelectedKProfile(active);
  1106. return;
  1107. }
  1108. }
  1109. // Fallback: the first match. matchingKProfiles is already scoped to this
  1110. // slot's nozzle when we know which one it is, so this cannot hand over a
  1111. // profile calibrated on the other hotend.
  1112. setSelectedKProfile(matchingKProfiles[0]);
  1113. } else {
  1114. setSelectedKProfile(null);
  1115. }
  1116. }, [
  1117. selectedPresetId,
  1118. matchingKProfiles,
  1119. slotSpoolDefaults?.cali_idx,
  1120. slotSpoolDefaults?.extruder,
  1121. slotInfo.caliIdx,
  1122. slotInfo.extruderId,
  1123. ]);
  1124. // Escape key handler
  1125. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  1126. // Escape in the reset confirm closes only the confirm.
  1127. if (e.key === 'Escape' && !showResetConfirm) {
  1128. onClose();
  1129. }
  1130. }, [onClose, showResetConfirm]);
  1131. useEffect(() => {
  1132. if (isOpen) {
  1133. document.addEventListener('keydown', handleKeyDown);
  1134. return () => document.removeEventListener('keydown', handleKeyDown);
  1135. }
  1136. }, [isOpen, handleKeyDown]);
  1137. const isLoading = (settingsLoading && !cloudError) || localLoading || builtinLoading || kprofilesLoading;
  1138. // Scroll selected preset into view when data finishes loading or the selection changes.
  1139. // Uses a ref guard so scrollIntoView only fires once per selection, preventing the
  1140. // infinite scroll loop that occurred on Windows with inline callback refs.
  1141. useEffect(() => {
  1142. if (!isLoading && selectedPresetId && selectedPresetId !== scrolledToRef.current) {
  1143. const raf = requestAnimationFrame(() => {
  1144. const modal = document.querySelector('[class*="fixed inset-0 z-50"]');
  1145. const el = modal?.querySelector(`[data-preset-id="${CSS.escape(selectedPresetId)}"]`);
  1146. if (el) {
  1147. scrolledToRef.current = selectedPresetId;
  1148. el.scrollIntoView({ block: 'nearest' });
  1149. }
  1150. });
  1151. return () => cancelAnimationFrame(raf);
  1152. }
  1153. }, [selectedPresetId, isLoading]);
  1154. if (!isOpen) return null;
  1155. const canSave = selectedPresetId && !configureMutation.isPending;
  1156. // Get display color (custom or slot default)
  1157. // Not sliced to six: a clear tray reports RRGGBB00, and cutting the alpha off
  1158. // here previewed it as solid black. `colorHex` is the edited form value and is
  1159. // always six characters, so only the tray fallback ever carries an alpha (#2912).
  1160. const displayColor = colorHex || slotInfo.trayColor || 'FFFFFF';
  1161. return (
  1162. <div className={`fixed inset-0 z-50 flex ${fullScreen ? '' : 'items-center justify-center'}`}>
  1163. {/* Backdrop */}
  1164. {!fullScreen && (
  1165. <div
  1166. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  1167. onClick={onClose}
  1168. />
  1169. )}
  1170. {/* Modal */}
  1171. <div className={fullScreen
  1172. ? 'relative w-full h-full bg-bambu-dark-secondary flex flex-col'
  1173. : 'relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl'
  1174. }>
  1175. {/* Header */}
  1176. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0">
  1177. <div className="flex items-center gap-2">
  1178. <Settings2 className="w-5 h-5 text-bambu-blue" />
  1179. <h2 className="text-lg font-semibold text-white">{t('configureAmsSlot.title')}</h2>
  1180. {/* Inline slot info in fullScreen mode */}
  1181. {fullScreen && (
  1182. <div className="flex items-center gap-2 ml-4 text-sm text-bambu-gray">
  1183. <span className="text-white/30">|</span>
  1184. {slotInfo.trayColor && (
  1185. <span
  1186. className="w-4 h-4 rounded-full border border-black/20"
  1187. style={getSwatchStyle(slotInfo.trayColor)}
  1188. />
  1189. )}
  1190. <span className="text-white/70">
  1191. {t('configureAmsSlot.slotLabel', { ams: getAmsLabel(slotInfo.amsId), slot: slotInfo.trayId + 1 })}
  1192. </span>
  1193. {slotInfo.traySubBrands && (
  1194. <span>({slotInfo.traySubBrands})</span>
  1195. )}
  1196. </div>
  1197. )}
  1198. </div>
  1199. <button
  1200. onClick={onClose}
  1201. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  1202. >
  1203. <X className="w-5 h-5" />
  1204. </button>
  1205. </div>
  1206. {/* Content */}
  1207. <div className={`p-4 overflow-y-auto ${fullScreen ? 'flex-1 min-h-0' : 'space-y-4 max-h-[60vh]'}`}>
  1208. {/* Success overlay */}
  1209. {showSuccess && (
  1210. <div className="absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl">
  1211. <div className="text-center space-y-3">
  1212. <CheckCircle2 className="w-16 h-16 text-bambu-green mx-auto" />
  1213. <p className="text-lg font-semibold text-white">{t('configureAmsSlot.slotConfigured')}</p>
  1214. <p className="text-sm text-bambu-gray">{t('configureAmsSlot.settingsSentToPrinter')}</p>
  1215. </div>
  1216. </div>
  1217. )}
  1218. {/* Slot info */}
  1219. {!fullScreen && (
  1220. <div className="p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary">
  1221. <p className="text-xs text-bambu-gray mb-1">{t('configureAmsSlot.configuringSlot')}</p>
  1222. <div className="flex items-center gap-2">
  1223. {slotInfo.trayColor && (
  1224. <span
  1225. className="w-4 h-4 rounded-full border border-black/20"
  1226. style={getSwatchStyle(slotInfo.trayColor)}
  1227. />
  1228. )}
  1229. <span className="text-white font-medium">
  1230. {t('configureAmsSlot.slotLabel', { ams: getAmsLabel(slotInfo.amsId), slot: slotInfo.trayId + 1 })}
  1231. </span>
  1232. {slotInfo.traySubBrands && (
  1233. <span className="text-bambu-gray">({slotInfo.traySubBrands})</span>
  1234. )}
  1235. </div>
  1236. </div>
  1237. )}
  1238. {isLoading ? (
  1239. <div className="flex justify-center py-8">
  1240. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  1241. </div>
  1242. ) : fullScreen ? (
  1243. /* Two-column layout for kiosk display */
  1244. <div className="flex gap-4 h-full">
  1245. {/* Left column: Filament preset list (takes full height) */}
  1246. <div className="w-1/2 flex flex-col min-h-0">
  1247. <label className="block text-sm text-bambu-gray mb-2">
  1248. {t('configureAmsSlot.filamentProfile')} <span className="text-red-600 dark:text-red-400">*</span>
  1249. </label>
  1250. <input
  1251. type="text"
  1252. placeholder={t('configureAmsSlot.searchPresets')}
  1253. value={searchQuery}
  1254. onChange={(e) => setSearchQuery(e.target.value)}
  1255. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"
  1256. />
  1257. <div className="flex-1 min-h-0 overflow-y-auto space-y-1">
  1258. {filteredPresets.length === 0 ? (
  1259. <p className="text-center py-4 text-bambu-gray">
  1260. {(cloudSettings?.filament?.length === 0 && !localPresets?.filament?.length)
  1261. ? t('configureAmsSlot.noPresetsAvailable')
  1262. : t('configureAmsSlot.noMatchingPresets')}
  1263. </p>
  1264. ) : (
  1265. filteredPresets.map((preset) => (
  1266. <button
  1267. key={preset.id}
  1268. data-preset-id={preset.id}
  1269. onClick={() => setSelectedPresetId(preset.id)}
  1270. className={`group w-full p-2 rounded-lg border text-left transition-colors ${
  1271. selectedPresetId === preset.id
  1272. ? 'bg-bambu-green/20 border-bambu-green'
  1273. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  1274. }`}
  1275. >
  1276. <div className="flex items-center justify-between">
  1277. <span className="text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all" title={preset.name}>{preset.name}</span>
  1278. <div className="flex items-center gap-1 flex-shrink-0">
  1279. {preset.source === 'local' && (
  1280. <span className="text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400">
  1281. {t('profiles.localProfiles.badge')}
  1282. </span>
  1283. )}
  1284. {preset.source === 'orca_cloud' && (
  1285. <span className="text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400">
  1286. {t('configureAmsSlot.orcaCloud')}
  1287. </span>
  1288. )}
  1289. {preset.source === 'cloud' && (
  1290. <span className="text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue">
  1291. {t('configureAmsSlot.bambuCloud')}
  1292. </span>
  1293. )}
  1294. {preset.source === 'builtin' && (
  1295. <span className="text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400">
  1296. {t('configureAmsSlot.builtin')}
  1297. </span>
  1298. )}
  1299. </div>
  1300. </div>
  1301. </button>
  1302. ))
  1303. )}
  1304. </div>
  1305. </div>
  1306. {/* Right column: K Profile + Color */}
  1307. <div className="w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto">
  1308. {/* K Profile Select */}
  1309. <div>
  1310. <label className="block text-sm text-bambu-gray mb-2">
  1311. {t('configureAmsSlot.kProfileLabel')}
  1312. {selectedMaterial && (
  1313. <span className="ml-2 text-xs text-bambu-blue">
  1314. {t('configureAmsSlot.filteringFor', { material: selectedMaterial })}
  1315. </span>
  1316. )}
  1317. </label>
  1318. {hasAnyKProfile ? (
  1319. <div className="relative">
  1320. <select
  1321. value={selectedKProfile ? kProfileOptionValue(selectedKProfile) : ''}
  1322. onChange={(e) => selectKProfileByValue(e.target.value)}
  1323. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10"
  1324. >
  1325. <option value="">{t('configureAmsSlot.noKProfile')}</option>
  1326. {matchingKProfiles.map((profile) => (
  1327. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1328. {kProfileFlowPrefix(profile)}{profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1329. </option>
  1330. ))}
  1331. {otherKProfiles.length > 0 && (
  1332. <optgroup label={t('configureAmsSlot.otherKProfiles')}>
  1333. {otherKProfiles.map((profile) => (
  1334. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1335. {kProfileFlowPrefix(profile)}{profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1336. </option>
  1337. ))}
  1338. </optgroup>
  1339. )}
  1340. </select>
  1341. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  1342. </div>
  1343. ) : selectedPresetId ? (
  1344. <p className="text-sm text-bambu-gray italic py-2">
  1345. {t('configureAmsSlot.noMatchingKProfiles')}
  1346. </p>
  1347. ) : (
  1348. <span className="inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30">
  1349. {t('configureAmsSlot.selectFilamentFirst')}
  1350. </span>
  1351. )}
  1352. {selectedKProfile && (
  1353. <p className="text-xs text-bambu-green mt-1">
  1354. {t('configureAmsSlot.kFromCalibration', { value: selectedKProfile.k_value })}
  1355. </p>
  1356. )}
  1357. </div>
  1358. {/* Custom color */}
  1359. <div>
  1360. <label className="block text-sm text-bambu-gray mb-2">
  1361. {t('configureAmsSlot.customColorLabel')}
  1362. </label>
  1363. {catalogColors.length > 0 && (
  1364. <div className="mb-3">
  1365. <p className="text-xs text-bambu-gray mb-1.5">
  1366. {t('configureAmsSlot.presetColors', { name: selectedPresetInfo?.fullName })}
  1367. </p>
  1368. <div className="flex flex-wrap gap-1.5">
  1369. {catalogColors.map((entry) => (
  1370. <button
  1371. key={entry.id}
  1372. onClick={() => {
  1373. const hex = entry.hex_color.replace('#', '').toUpperCase();
  1374. setColorHex(hex);
  1375. setColorInput(entry.color_name);
  1376. }}
  1377. className={`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${
  1378. colorHex === entry.hex_color.replace('#', '').toUpperCase()
  1379. ? 'border-bambu-green scale-105'
  1380. : 'border-white/20 hover:border-white/40'
  1381. }`}
  1382. title={entry.color_name}
  1383. >
  1384. <span
  1385. className="w-4 h-4 rounded-full border border-black/20 flex-shrink-0"
  1386. style={{ backgroundColor: entry.hex_color }}
  1387. />
  1388. <span className="text-xs text-white/80 whitespace-nowrap">{entry.color_name}</span>
  1389. </button>
  1390. ))}
  1391. </div>
  1392. </div>
  1393. )}
  1394. <div className="flex flex-wrap gap-1.5 mb-2">
  1395. {QUICK_COLORS_BASIC.map((color) => (
  1396. <button
  1397. key={color.hex}
  1398. onClick={() => {
  1399. setColorHex(color.hex);
  1400. setColorInput(color.name);
  1401. }}
  1402. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1403. colorHex === color.hex
  1404. ? 'border-bambu-green scale-110'
  1405. : 'border-white/20 hover:border-white/40'
  1406. }`}
  1407. style={{ backgroundColor: `#${color.hex}` }}
  1408. title={color.name}
  1409. />
  1410. ))}
  1411. <button
  1412. onClick={() => setShowExtendedColors(!showExtendedColors)}
  1413. className="w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs"
  1414. title={showExtendedColors ? t('configureAmsSlot.showLessColors') : t('configureAmsSlot.showMoreColors')}
  1415. >
  1416. {showExtendedColors ? '−' : '+'}
  1417. </button>
  1418. </div>
  1419. {showExtendedColors && (
  1420. <div className="flex flex-wrap gap-1.5 mb-2">
  1421. {QUICK_COLORS_EXTENDED.map((color) => (
  1422. <button
  1423. key={color.hex}
  1424. onClick={() => {
  1425. setColorHex(color.hex);
  1426. setColorInput(color.name);
  1427. }}
  1428. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1429. colorHex === color.hex
  1430. ? 'border-bambu-green scale-110'
  1431. : 'border-white/20 hover:border-white/40'
  1432. }`}
  1433. style={{ backgroundColor: `#${color.hex}` }}
  1434. title={color.name}
  1435. />
  1436. ))}
  1437. </div>
  1438. )}
  1439. <div className="flex gap-2 items-center">
  1440. <div
  1441. className="w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0"
  1442. style={getSwatchStyle(displayColor)}
  1443. />
  1444. <input
  1445. type="text"
  1446. placeholder={t('configureAmsSlot.colorPlaceholder')}
  1447. value={colorInput}
  1448. onChange={(e) => {
  1449. const input = e.target.value;
  1450. setColorInput(input);
  1451. const nameHex = colorNameToHex(input);
  1452. if (nameHex) {
  1453. setColorHex(nameHex);
  1454. } else {
  1455. const cleaned = input.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
  1456. if (cleaned.length === 6) {
  1457. setColorHex(cleaned);
  1458. } else if (cleaned.length === 3) {
  1459. setColorHex(cleaned.split('').map(c => c + c).join(''));
  1460. }
  1461. }
  1462. }}
  1463. className="flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"
  1464. />
  1465. {colorHex && (
  1466. <button
  1467. onClick={() => {
  1468. setColorHex('');
  1469. setColorInput('');
  1470. }}
  1471. className="px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded"
  1472. title={t('configureAmsSlot.clearCustomColor')}
  1473. >
  1474. {t('configureAmsSlot.clear')}
  1475. </button>
  1476. )}
  1477. </div>
  1478. {colorHex && (
  1479. <p className="text-xs text-bambu-gray mt-1.5">
  1480. {t('configureAmsSlot.hexLabel', { hex: colorHex })}
  1481. </p>
  1482. )}
  1483. </div>
  1484. </div>
  1485. </div>
  1486. ) : (
  1487. <>
  1488. {/* Filament Profile Select */}
  1489. <div>
  1490. <label className="block text-sm text-bambu-gray mb-2">
  1491. {t('configureAmsSlot.filamentProfile')} <span className="text-red-600 dark:text-red-400">*</span>
  1492. </label>
  1493. <div className="relative">
  1494. <input
  1495. type="text"
  1496. placeholder={t('configureAmsSlot.searchPresets')}
  1497. value={searchQuery}
  1498. onChange={(e) => setSearchQuery(e.target.value)}
  1499. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"
  1500. />
  1501. <div className="max-h-48 overflow-y-auto space-y-1">
  1502. {filteredPresets.length === 0 ? (
  1503. <p className="text-center py-4 text-bambu-gray">
  1504. {(cloudSettings?.filament?.length === 0 && !localPresets?.filament?.length)
  1505. ? t('configureAmsSlot.noPresetsAvailable')
  1506. : t('configureAmsSlot.noMatchingPresets')}
  1507. </p>
  1508. ) : (
  1509. filteredPresets.map((preset) => (
  1510. <button
  1511. key={preset.id}
  1512. data-preset-id={preset.id}
  1513. onClick={() => setSelectedPresetId(preset.id)}
  1514. className={`group w-full p-2 rounded-lg border text-left transition-colors ${
  1515. selectedPresetId === preset.id
  1516. ? 'bg-bambu-green/20 border-bambu-green'
  1517. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  1518. }`}
  1519. >
  1520. <div className="flex items-center justify-between">
  1521. <span className="text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all" title={preset.name}>{preset.name}</span>
  1522. <div className="flex items-center gap-1 flex-shrink-0">
  1523. {preset.source === 'local' && (
  1524. <span className="text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400">
  1525. {t('profiles.localProfiles.badge')}
  1526. </span>
  1527. )}
  1528. {preset.source === 'orca_cloud' && (
  1529. <span className="text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400">
  1530. {t('configureAmsSlot.orcaCloud')}
  1531. </span>
  1532. )}
  1533. {preset.source === 'cloud' && (
  1534. <span className="text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue">
  1535. {t('configureAmsSlot.bambuCloud')}
  1536. </span>
  1537. )}
  1538. {preset.source === 'builtin' && (
  1539. <span className="text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400">
  1540. {t('configureAmsSlot.builtin')}
  1541. </span>
  1542. )}
  1543. </div>
  1544. </div>
  1545. </button>
  1546. ))
  1547. )}
  1548. </div>
  1549. </div>
  1550. </div>
  1551. {/* K Profile Select */}
  1552. <div>
  1553. <label className="block text-sm text-bambu-gray mb-2">
  1554. {t('configureAmsSlot.kProfileLabel')}
  1555. {selectedMaterial && (
  1556. <span className="ml-2 text-xs text-bambu-blue">
  1557. {t('configureAmsSlot.filteringFor', { material: selectedMaterial })}
  1558. </span>
  1559. )}
  1560. </label>
  1561. {hasAnyKProfile ? (
  1562. <div className="relative">
  1563. <select
  1564. value={selectedKProfile ? kProfileOptionValue(selectedKProfile) : ''}
  1565. onChange={(e) => selectKProfileByValue(e.target.value)}
  1566. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10"
  1567. >
  1568. <option value="">{t('configureAmsSlot.noKProfile')}</option>
  1569. {matchingKProfiles.map((profile) => (
  1570. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1571. {kProfileFlowPrefix(profile)}{profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1572. </option>
  1573. ))}
  1574. {otherKProfiles.length > 0 && (
  1575. <optgroup label={t('configureAmsSlot.otherKProfiles')}>
  1576. {otherKProfiles.map((profile) => (
  1577. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1578. {kProfileFlowPrefix(profile)}{profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1579. </option>
  1580. ))}
  1581. </optgroup>
  1582. )}
  1583. </select>
  1584. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  1585. </div>
  1586. ) : selectedPresetId ? (
  1587. <p className="text-sm text-bambu-gray italic py-2">
  1588. {t('configureAmsSlot.noMatchingKProfiles')}
  1589. </p>
  1590. ) : (
  1591. <span className="inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30">
  1592. {t('configureAmsSlot.selectFilamentFirst')}
  1593. </span>
  1594. )}
  1595. {selectedKProfile && (
  1596. <p className="text-xs text-bambu-green mt-1">
  1597. {t('configureAmsSlot.kFromCalibration', { value: selectedKProfile.k_value })}
  1598. </p>
  1599. )}
  1600. </div>
  1601. {/* Optional: Custom color */}
  1602. <div>
  1603. <label className="block text-sm text-bambu-gray mb-2">
  1604. {t('configureAmsSlot.customColorLabel')}
  1605. </label>
  1606. {/* Catalog colors matching selected preset */}
  1607. {catalogColors.length > 0 && (
  1608. <div className="mb-3">
  1609. <p className="text-xs text-bambu-gray mb-1.5">
  1610. {t('configureAmsSlot.presetColors', { name: selectedPresetInfo?.fullName })}
  1611. </p>
  1612. <div className="flex flex-wrap gap-1.5">
  1613. {catalogColors.map((entry) => (
  1614. <button
  1615. key={entry.id}
  1616. onClick={() => {
  1617. const hex = entry.hex_color.replace('#', '').toUpperCase();
  1618. setColorHex(hex);
  1619. setColorInput(entry.color_name);
  1620. }}
  1621. className={`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${
  1622. colorHex === entry.hex_color.replace('#', '').toUpperCase()
  1623. ? 'border-bambu-green scale-105'
  1624. : 'border-white/20 hover:border-white/40'
  1625. }`}
  1626. title={entry.color_name}
  1627. >
  1628. <span
  1629. className="w-4 h-4 rounded-full border border-black/20 flex-shrink-0"
  1630. style={{ backgroundColor: entry.hex_color }}
  1631. />
  1632. <span className="text-xs text-white/80 whitespace-nowrap">{entry.color_name}</span>
  1633. </button>
  1634. ))}
  1635. </div>
  1636. </div>
  1637. )}
  1638. {/* Quick color buttons */}
  1639. <div className="flex flex-wrap gap-1.5 mb-2">
  1640. {QUICK_COLORS_BASIC.map((color) => (
  1641. <button
  1642. key={color.hex}
  1643. onClick={() => {
  1644. setColorHex(color.hex);
  1645. setColorInput(color.name);
  1646. }}
  1647. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1648. colorHex === color.hex
  1649. ? 'border-bambu-green scale-110'
  1650. : 'border-white/20 hover:border-white/40'
  1651. }`}
  1652. style={{ backgroundColor: `#${color.hex}` }}
  1653. title={color.name}
  1654. />
  1655. ))}
  1656. <button
  1657. onClick={() => setShowExtendedColors(!showExtendedColors)}
  1658. className="w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs"
  1659. title={showExtendedColors ? t('configureAmsSlot.showLessColors') : t('configureAmsSlot.showMoreColors')}
  1660. >
  1661. {showExtendedColors ? '−' : '+'}
  1662. </button>
  1663. </div>
  1664. {/* Extended colors (collapsible) */}
  1665. {showExtendedColors && (
  1666. <div className="flex flex-wrap gap-1.5 mb-2">
  1667. {QUICK_COLORS_EXTENDED.map((color) => (
  1668. <button
  1669. key={color.hex}
  1670. onClick={() => {
  1671. setColorHex(color.hex);
  1672. setColorInput(color.name);
  1673. }}
  1674. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1675. colorHex === color.hex
  1676. ? 'border-bambu-green scale-110'
  1677. : 'border-white/20 hover:border-white/40'
  1678. }`}
  1679. style={{ backgroundColor: `#${color.hex}` }}
  1680. title={color.name}
  1681. />
  1682. ))}
  1683. </div>
  1684. )}
  1685. {/* Color input: name or hex */}
  1686. <div className="flex gap-2 items-center">
  1687. <div
  1688. className="w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0"
  1689. style={getSwatchStyle(displayColor)}
  1690. />
  1691. <input
  1692. type="text"
  1693. placeholder={t('configureAmsSlot.colorPlaceholder')}
  1694. value={colorInput}
  1695. onChange={(e) => {
  1696. const input = e.target.value;
  1697. setColorInput(input);
  1698. // Try to parse as color name first
  1699. const nameHex = colorNameToHex(input);
  1700. if (nameHex) {
  1701. setColorHex(nameHex);
  1702. } else {
  1703. // Try to parse as hex code
  1704. const cleaned = input.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
  1705. if (cleaned.length === 6) {
  1706. setColorHex(cleaned);
  1707. } else if (cleaned.length === 3) {
  1708. // Expand shorthand hex (e.g., F00 -> FF0000)
  1709. setColorHex(cleaned.split('').map(c => c + c).join(''));
  1710. }
  1711. }
  1712. }}
  1713. className="flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"
  1714. />
  1715. {colorHex && (
  1716. <button
  1717. onClick={() => {
  1718. setColorHex('');
  1719. setColorInput('');
  1720. }}
  1721. className="px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded"
  1722. title={t('configureAmsSlot.clearCustomColor')}
  1723. >
  1724. {t('configureAmsSlot.clear')}
  1725. </button>
  1726. )}
  1727. </div>
  1728. {colorHex && (
  1729. <p className="text-xs text-bambu-gray mt-1.5">
  1730. {t('configureAmsSlot.hexLabel', { hex: colorHex })}
  1731. </p>
  1732. )}
  1733. </div>
  1734. </>
  1735. )}
  1736. </div>
  1737. {/* Footer */}
  1738. <div className="flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0">
  1739. {/* Reset button on the left */}
  1740. <Button
  1741. variant="secondary"
  1742. onClick={() => setShowResetConfirm(true)}
  1743. disabled={printing || resetMutation.isPending || configureMutation.isPending}
  1744. title={printing ? t('configureAmsSlot.resetBlockedPrinting') : undefined}
  1745. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10"
  1746. >
  1747. {resetMutation.isPending ? (
  1748. <>
  1749. <Loader2 className="w-4 h-4 animate-spin" />
  1750. {t('configureAmsSlot.resetting')}
  1751. </>
  1752. ) : (
  1753. <>
  1754. <RotateCcw className="w-4 h-4" />
  1755. {t('configureAmsSlot.resetSlot')}
  1756. </>
  1757. )}
  1758. </Button>
  1759. {/* Cancel and Configure buttons on the right */}
  1760. <div className="flex gap-2">
  1761. <Button variant="secondary" onClick={onClose}>
  1762. {t('configureAmsSlot.cancel')}
  1763. </Button>
  1764. <Button
  1765. onClick={() => configureMutation.mutate()}
  1766. disabled={!canSave}
  1767. >
  1768. {configureMutation.isPending ? (
  1769. <>
  1770. <Loader2 className="w-4 h-4 animate-spin" />
  1771. {t('configureAmsSlot.configuring')}
  1772. </>
  1773. ) : (
  1774. <>
  1775. <Settings2 className="w-4 h-4" />
  1776. {t('configureAmsSlot.configureSlot')}
  1777. </>
  1778. )}
  1779. </Button>
  1780. </div>
  1781. </div>
  1782. {/* Error */}
  1783. {(configureMutation.isError || resetMutation.isError) && (
  1784. <div className="mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400">
  1785. {(configureMutation.error as Error)?.message || (resetMutation.error as Error)?.message}
  1786. </div>
  1787. )}
  1788. </div>
  1789. {showResetConfirm && (
  1790. <ConfirmModal
  1791. title={t('configureAmsSlot.resetConfirmTitle')}
  1792. message={t('configureAmsSlot.resetConfirmMessage')}
  1793. confirmText={t('configureAmsSlot.resetSlot')}
  1794. variant="danger"
  1795. overlayZIndex="z-[60]"
  1796. onConfirm={() => {
  1797. setShowResetConfirm(false);
  1798. resetMutation.mutate();
  1799. }}
  1800. onCancel={() => setShowResetConfirm(false)}
  1801. />
  1802. )}
  1803. </div>
  1804. );
  1805. }