ConfigureAmsSlotModal.tsx 75 KB

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