ConfigureAmsSlotModal.tsx 88 KB

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