ConfigureAmsSlotModal.tsx 68 KB

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