ConfigureAmsSlotModal.tsx 87 KB

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