ConfigureAmsSlotModal.tsx 79 KB

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