ConfigureAmsSlotModal.tsx 80 KB

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