ConfigureAmsSlotModal.tsx 61 KB

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