ConfigureAmsSlotModal.tsx 84 KB

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