ConfigureAmsSlotModal.tsx 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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. // An Orca Cloud profile's setting_id is a UUID the printer cannot hold,
  430. // so this used to skip straight to a generic — which meant every Orca
  431. // custom filament reached the slicer as "Generic <material>", without
  432. // ever asking whether the profile had a usable id (#3003).
  433. //
  434. // It usually does. The profile's slicer JSON carries its own
  435. // filament_id, the same 8-character "P…" the printer stores for a
  436. // Bambu custom preset, and OrcaProfileDetail deliberately exposes that
  437. // JSON under `setting` in the shape SlicerSettingDetail uses. So the
  438. // lookup is the same one the Bambu Cloud branch does below.
  439. //
  440. // settingId stays empty either way: it is the UUID that is foreign to
  441. // the slicer, not the filament id.
  442. let orcaFilamentId = '';
  443. try {
  444. const orcaDetail = await api.orcaCloudGetProfile(orcaSettingId);
  445. const fromProfile = orcaDetail.setting?.filament_id;
  446. if (typeof fromProfile === 'string' && fromProfile) {
  447. orcaFilamentId = fromProfile;
  448. }
  449. } catch (e) {
  450. console.warn('Failed to fetch Orca Cloud profile for filament_id:', e);
  451. }
  452. trayInfoIdx = orcaFilamentId;
  453. if (!trayInfoIdx) {
  454. // No id of its own — fall back to the generic for the material, the
  455. // same last resort every other source ends at.
  456. const material = (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : parsed.material || '').toUpperCase();
  457. trayInfoIdx = GENERIC_IDS[material]
  458. || GENERIC_IDS[material.replace(/[-\s]?CF$/, '')]
  459. || GENERIC_IDS[material.replace(/\+$/, '')]
  460. || GENERIC_IDS[material.split(/[-\s]/)[0]]
  461. || '';
  462. }
  463. settingId = '';
  464. } else if (isBuiltin) {
  465. // Built-in presets use the filament_id directly as tray_info_idx
  466. trayInfoIdx = builtinFilamentId!;
  467. settingId = '';
  468. } else {
  469. trayInfoIdx = convertToTrayInfoIdx(selectedPresetId);
  470. settingId = selectedPresetId;
  471. // User cloud presets may carry a distinct filament_id in the cloud detail
  472. // (e.g. "P285e239"); prefer it when present. Never fall back to base_id —
  473. // that collapses custom presets to the inherited generic's filament_id and
  474. // makes the slicer resolve the slot to "Generic …" instead (#1053).
  475. if (!selectedPresetId.startsWith('GFS')) {
  476. try {
  477. const detail = await api.getCloudSettingDetail(selectedPresetId);
  478. // The preset's own filament_id is what puts it in the slot as
  479. // itself — the printer stores that id and the slicer matches its
  480. // presets against it. Bambu Cloud normally returns it on the
  481. // envelope; the `setting` fallback covers a response that carries
  482. // it in the preset JSON instead. A preset created in Orca has none
  483. // in either place (#1053), and legitimately falls through.
  484. const nested = detail.setting?.filament_id;
  485. const ownFilamentId = detail.filament_id || (typeof nested === 'string' ? nested : '');
  486. if (ownFilamentId) {
  487. trayInfoIdx = ownFilamentId;
  488. }
  489. } catch (e) {
  490. console.warn('Failed to fetch preset detail for filament_id:', e);
  491. }
  492. }
  493. // Last resort: neither place had one, so trayInfoIdx is still the
  494. // cloud setting_id — and sending one is worse than sending nothing
  495. // (#3003). tray_info_idx is 8 characters on the printer; an
  496. // 18-character PFUS is stored truncated and acknowledged as a success,
  497. // so the slot ends up holding an id that resolves nowhere — the slicer
  498. // shows "Generic", and the calibration table, keyed by this field,
  499. // loses the slot too. Blank means the backend picks the slot's
  500. // existing filament id or a generic for the material; settingId still
  501. // carries the preset.
  502. if (/^(PFUS|PFSP|PFCN)/.test(trayInfoIdx)) {
  503. console.warn(
  504. `Cloud preset ${selectedPresetId} carries no filament_id in either place; ` +
  505. 'sending no tray_info_idx so the printer keeps a resolvable one.'
  506. );
  507. trayInfoIdx = '';
  508. }
  509. }
  510. // Default temp range — use local preset core fields if available
  511. let tempMin = isLocal && localPreset?.nozzle_temp_min ? localPreset.nozzle_temp_min : 190;
  512. let tempMax = isLocal && localPreset?.nozzle_temp_max ? localPreset.nozzle_temp_max : 230;
  513. if (!isLocal || isBuiltin || isOrca || (!localPreset?.nozzle_temp_min && !localPreset?.nozzle_temp_max)) {
  514. // Fall back to material-based defaults (prefer parsed material for "Support for" handling)
  515. const material = (isLocal
  516. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : localPreset?.filament_type || parsed.material || '')
  517. : parsed.material).toUpperCase();
  518. if (material.includes('PLA')) {
  519. tempMin = 190;
  520. tempMax = 230;
  521. } else if (material.includes('PETG')) {
  522. tempMin = 220;
  523. tempMax = 260;
  524. } else if (material.includes('ABS')) {
  525. tempMin = 240;
  526. tempMax = 280;
  527. } else if (material.includes('ASA')) {
  528. tempMin = 240;
  529. tempMax = 280;
  530. } else if (material.includes('TPU')) {
  531. tempMin = 200;
  532. tempMax = 240;
  533. } else if (material === 'PCTG') {
  534. tempMin = 220;
  535. tempMax = 260;
  536. } else if (material.includes('PC')) {
  537. tempMin = 260;
  538. tempMax = 300;
  539. } else if (material.includes('PA') || material.includes('NYLON')) {
  540. tempMin = 250;
  541. tempMax = 290;
  542. }
  543. }
  544. // Parse K value from selected profile
  545. const kValue = selectedKProfileRef.current?.k_value
  546. ? parseFloat(selectedKProfileRef.current.k_value)
  547. : 0;
  548. // Determine tray_type: prefer parsed material from preset name (handles "Support for"
  549. // patterns correctly) over stored filament_type which may have been parsed with old logic.
  550. const trayType = isLocal
  551. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : localPreset?.filament_type || parsed.material || 'PLA')
  552. : isOrca
  553. ? (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : parsed.material || 'PLA')
  554. : (parsed.material || 'PLA');
  555. // Configure the slot via MQTT
  556. const result = await api.configureAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId, {
  557. tray_info_idx: trayInfoIdx,
  558. tray_type: trayType,
  559. tray_sub_brands: traySubBrands,
  560. tray_color: color + 'FF', // Add alpha
  561. nozzle_temp_min: tempMin,
  562. nozzle_temp_max: tempMax,
  563. cali_idx: caliIdx,
  564. nozzle_diameter: nozzleDiameter,
  565. setting_id: settingId, // Full setting ID for slicer compatibility (empty for local)
  566. // Pass K profile's filament_id and setting_id for proper linking
  567. kprofile_filament_id: selectedKProfileRef.current?.filament_id,
  568. kprofile_setting_id: selectedKProfileRef.current?.setting_id || undefined,
  569. // Also pass the K value directly for extrusion_cali_set command
  570. k_value: kValue,
  571. });
  572. // Save the preset mapping so we can display the correct name in the UI
  573. // This is needed because user presets use filament_id (e.g., P285e239) as tray_info_idx,
  574. // which can't be resolved to a name via the filamentInfo API
  575. const mappingPresetId = isLocal
  576. ? `local_${localId}`
  577. : isBuiltin
  578. ? `builtin_${builtinFilamentId}`
  579. : isOrca
  580. ? selectedPresetId
  581. : selectedPresetId;
  582. const mappingSource = isLocal
  583. ? 'local'
  584. : isBuiltin
  585. ? 'builtin'
  586. : isOrca
  587. ? 'orca_cloud'
  588. : 'cloud';
  589. try {
  590. await api.saveSlotPreset(printerId, slotInfo.amsId, slotInfo.trayId, mappingPresetId, traySubBrands, mappingSource);
  591. } catch (e) {
  592. console.warn('Failed to save slot preset mapping:', e);
  593. // Don't fail the whole operation - slot was configured successfully
  594. }
  595. return result;
  596. },
  597. onSuccess: () => {
  598. setShowSuccess(true);
  599. onSuccess?.();
  600. // Close after showing success briefly
  601. scheduleClose(() => {
  602. setShowSuccess(false);
  603. onClose();
  604. }, 1500);
  605. },
  606. });
  607. // Reset slot mutation
  608. const resetMutation = useMutation({
  609. mutationFn: async () => {
  610. return api.resetAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId);
  611. },
  612. onSuccess: () => {
  613. setShowSuccess(true);
  614. onSuccess?.();
  615. scheduleClose(() => {
  616. setShowSuccess(false);
  617. onClose();
  618. }, 1500);
  619. },
  620. });
  621. // Unified preset item for the list (orca_cloud + cloud + local + builtin fallback)
  622. type PresetItem = { id: string; name: string; source: 'orca_cloud' | 'cloud' | 'local' | 'builtin'; isUser: boolean };
  623. // Filter filament presets based on search (merged orca_cloud + cloud + local + builtin)
  624. const filteredPresets = useMemo(() => {
  625. const query = searchQuery.toLowerCase();
  626. const items: PresetItem[] = [];
  627. // Collect IDs already covered by higher-priority tiers to avoid duplicates
  628. const coveredIds = new Set<string>();
  629. // Currently-configured preset should always be shown (bypass model filter)
  630. const savedId = slotInfo.savedPresetId;
  631. const trayIdx = slotInfo.trayInfoIdx;
  632. // 0. Orca Cloud filament presets — surfaced first because the user
  633. // explicitly opted into Orca sync; their picks should outrank Bambu Cloud
  634. // presets of the same name. IDs are prefixed ``orca_`` so the configure
  635. // flow can detect "this is an Orca preset" via a cheap string check
  636. // (mirrors the ``local_`` / ``builtin_`` prefix convention already in use).
  637. if (orcaCloudList?.filament) {
  638. for (const op of orcaCloudList.filament) {
  639. const orcaId = `orca_${op.setting_id}`;
  640. coveredIds.add(op.setting_id);
  641. coveredIds.add(orcaId);
  642. if (query && !op.name.toLowerCase().includes(query)) continue;
  643. if (printerModel) {
  644. const presetModel = extractPresetModel(op.name, printerModelsData ?? {});
  645. if (presetModel && !matchesPrinterModelSuffix(presetModel, printerModel)) continue;
  646. }
  647. // All Orca Cloud profiles are user-authored, so isUser is always true.
  648. items.push({ id: orcaId, name: op.name, source: 'orca_cloud', isUser: true });
  649. }
  650. }
  651. // 1. Cloud presets
  652. if (cloudSettings?.filament) {
  653. for (const cp of cloudSettings.filament) {
  654. if (coveredIds.has(cp.setting_id)) continue;
  655. coveredIds.add(cp.setting_id);
  656. // Keep preset if it matches the slot's saved mapping or current tray_info_idx
  657. const isSavedPreset = savedId === cp.setting_id;
  658. const isCurrentPreset = isSavedPreset
  659. || (trayIdx && (cp.setting_id === trayIdx || convertToTrayInfoIdx(cp.setting_id) === trayIdx));
  660. // Search filter applies to ALL presets (including saved) — no bypass
  661. if (query && !cp.name.toLowerCase().includes(query)) continue;
  662. // Filter by printer model if set (skip for current preset). Uses the
  663. // alias-aware match so Bambu's "A1 Mini" → "A1M" cloud rename (#1649)
  664. // doesn't hide A1 Mini cloud profiles.
  665. if (!isCurrentPreset && printerModel) {
  666. const presetModel = extractPresetModel(cp.name, printerModelsData ?? {});
  667. if (presetModel && !matchesPrinterModelSuffix(presetModel, printerModel)) continue;
  668. }
  669. items.push({ id: cp.setting_id, name: cp.name, source: 'cloud', isUser: isUserPreset(cp.setting_id) });
  670. }
  671. }
  672. // 2. Local presets — filter by the slicer's own ``compatible_printers``
  673. // list when present (#1623). LocalPreset.compatible_printers is a JSON-
  674. // encoded string array; presetCompatibility returns 'mismatch' when the
  675. // list is set and our derived full printer name isn't in it, 'unknown'
  676. // when neither the list nor an @BBL token is parseable — we hide on
  677. // 'mismatch' only so user-imported presets without compatible_printers
  678. // still surface (back-compat with the prior "always show" behaviour for
  679. // hand-edited / lossily-imported presets).
  680. if (localPresets?.filament) {
  681. const savedLocalId = slotInfo.savedPresetId;
  682. for (const lp of localPresets.filament) {
  683. const localId = `local_${lp.id}`;
  684. if (query && !lp.name.toLowerCase().includes(query)) continue;
  685. const isCurrentPreset = savedLocalId === localId;
  686. if (!isCurrentPreset && fullPrinterName) {
  687. let compatList: string[] | null = null;
  688. if (lp.compatible_printers) {
  689. try {
  690. const parsed = JSON.parse(lp.compatible_printers);
  691. if (Array.isArray(parsed)) compatList = parsed.filter((s): s is string => typeof s === 'string');
  692. } catch {
  693. compatList = null;
  694. }
  695. }
  696. const verdict = presetCompatibility(
  697. { name: lp.name, compatible_printers: compatList },
  698. 'filament',
  699. fullPrinterName,
  700. compatIndex,
  701. );
  702. if (verdict === 'mismatch') continue;
  703. }
  704. items.push({ id: localId, name: lp.name, source: 'local', isUser: false });
  705. }
  706. }
  707. // 3. Built-in filament names (fallback — only add entries not already covered)
  708. if (builtinFilaments) {
  709. for (const bf of builtinFilaments) {
  710. if (coveredIds.has(bf.filament_id)) continue;
  711. // Convert filament_id to setting_id format for cloud compatibility
  712. // e.g. "GFA00" → cloud setting_id would be "GFSA00" (insert S after GF)
  713. const settingId = bf.filament_id.startsWith('GF')
  714. ? 'GFS' + bf.filament_id.slice(2)
  715. : bf.filament_id;
  716. if (coveredIds.has(settingId)) continue;
  717. if (!query || bf.name.toLowerCase().includes(query)) {
  718. items.push({ id: `builtin_${bf.filament_id}`, name: bf.name, source: 'builtin', isUser: false });
  719. }
  720. }
  721. }
  722. // Sort: local first (user explicitly imported them), then orca_cloud,
  723. // then bambu cloud, then builtin fallback. Matches the SliceModal
  724. // tier priority.
  725. return items.sort((a, b) => {
  726. const sourceOrder = { local: 0, orca_cloud: 1, cloud: 2, builtin: 3 };
  727. if (a.source !== b.source) return sourceOrder[a.source] - sourceOrder[b.source];
  728. if (a.isUser && !b.isUser) return -1;
  729. if (!a.isUser && b.isUser) return 1;
  730. return a.name.localeCompare(b.name);
  731. });
  732. }, [orcaCloudList?.filament, cloudSettings?.filament, localPresets?.filament, builtinFilaments, searchQuery, printerModel, slotInfo.savedPresetId, slotInfo.trayInfoIdx, fullPrinterName, compatIndex, printerModelsData]);
  733. // Get full preset name for K profile filtering (brand + material, without printer suffix)
  734. const selectedPresetInfo = useMemo(() => {
  735. if (!selectedPresetId) return null;
  736. // Resolve the name from orca, cloud, local, or builtin presets. The
  737. // Orca branch tolerates both ``orca_<UUID>`` and a bare UUID — see the
  738. // configure-mutation comment for why the raw UUID also reaches us.
  739. // ``filamentId`` is the bare Bambu filament_id (e.g. "GFG98") when the
  740. // preset has one — used to id-match K-profiles directly without name
  741. // parsing (#1688). Empty string for paths with no usable filament_id
  742. // (orca presets, local presets), which makes the id-match branch skip.
  743. let presetName: string | null = null;
  744. let filamentId = '';
  745. if (selectedPresetId.startsWith('local_')) {
  746. const localId = parseInt(selectedPresetId.replace('local_', ''), 10);
  747. const lp = localPresets?.filament.find(p => p.id === localId);
  748. presetName = lp?.name || null;
  749. } else if (selectedPresetId.startsWith('builtin_')) {
  750. const builtinFilamentId = selectedPresetId.replace('builtin_', '');
  751. const bf = builtinFilaments?.find(b => b.filament_id === builtinFilamentId);
  752. presetName = bf?.name || null;
  753. filamentId = toFilamentId(builtinFilamentId);
  754. } else {
  755. const orcaCandidateId = selectedPresetId.startsWith('orca_')
  756. ? selectedPresetId.replace('orca_', '')
  757. : selectedPresetId;
  758. const op = orcaCloudList?.filament.find(p => p.setting_id === orcaCandidateId);
  759. if (op) {
  760. presetName = op.name;
  761. } else if (cloudSettings?.filament) {
  762. const cp = cloudSettings.filament.find(p => p.setting_id === selectedPresetId);
  763. presetName = cp?.name || null;
  764. if (cp) {
  765. // SlicerSetting only carries setting_id ("GFSG98_09"); toFilamentId
  766. // drops the variant suffix and the "S" infix to yield "GFG98".
  767. filamentId = toFilamentId(cp.setting_id);
  768. }
  769. }
  770. }
  771. if (!presetName) {
  772. return null;
  773. }
  774. // Remove printer/nozzle suffix (e.g., "@BBL X1C" or "@0.4 nozzle")
  775. let nameWithoutSuffix = presetName.replace(/@.+$/, '').trim();
  776. // Strip leading "# " from custom preset names (user convention)
  777. if (nameWithoutSuffix.startsWith('# ')) {
  778. nameWithoutSuffix = nameWithoutSuffix.slice(2).trim();
  779. }
  780. const parsed = parsePresetName(nameWithoutSuffix);
  781. return {
  782. fullName: nameWithoutSuffix,
  783. material: parsed.material,
  784. brand: parsed.brand,
  785. filamentId,
  786. };
  787. }, [selectedPresetId, cloudSettings?.filament, localPresets?.filament, builtinFilaments, orcaCloudList?.filament]);
  788. // For backwards compatibility with the label
  789. const selectedMaterial = selectedPresetInfo?.fullName || '';
  790. // Filter color catalog entries matching the selected preset's brand + material
  791. const catalogColors = useMemo(() => {
  792. if (!colorCatalog || !selectedPresetInfo) return [];
  793. const { fullName, brand } = selectedPresetInfo;
  794. // Try to find colors matching the full preset name (e.g., "PLA Metal")
  795. // The catalog uses the variant as part of the material field (e.g., material="PLA Metal")
  796. // Extract the full material+variant from the preset name
  797. const materialVariant = fullName.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i, '').trim();
  798. return colorCatalog.filter(entry => {
  799. const entryMaterial = (entry.material || '').toUpperCase();
  800. const entryManufacturer = entry.manufacturer.toUpperCase();
  801. // Match material: try full material+variant first, then just material type
  802. const materialMatch = entryMaterial === materialVariant.toUpperCase()
  803. || entryMaterial.includes(materialVariant.toUpperCase())
  804. || materialVariant.toUpperCase().includes(entryMaterial);
  805. if (!materialMatch) return false;
  806. // If brand is present, also match manufacturer
  807. if (brand) {
  808. const upperBrand = brand.toUpperCase();
  809. // Fuzzy match: "Bambu" matches "Bambu Lab", etc.
  810. if (!entryManufacturer.includes(upperBrand) && !upperBrand.includes(entryManufacturer)) {
  811. return false;
  812. }
  813. }
  814. return true;
  815. });
  816. }, [colorCatalog, selectedPresetInfo]);
  817. // Dual-nozzle if the printer reported calibration profiles for more than one
  818. // extruder. Self-contained, and exactly the condition under which naming the
  819. // hotend on each option is worth the space.
  820. const isDualNozzleProfiles = useMemo(
  821. () => new Set((kprofilesData?.profiles ?? []).map(p => p.extruder_id ?? 0)).size > 1,
  822. [kprofilesData?.profiles]
  823. );
  824. const matchingKProfiles = useMemo(() => {
  825. if (!kprofilesData?.profiles) return [];
  826. if (!selectedPresetInfo) {
  827. // Assigned-but-unconfigured slot (filament loaded but the printer hasn't
  828. // bound a preset yet: tray_type=""/tray_info_idx=""/no slot_preset_mappings
  829. // row). The cali_idx safety net further down lives past the main name+id
  830. // matcher and never runs from here, so surface the slot's currently-active
  831. // K-profile directly so Configure Slot keeps showing it across reopen
  832. // instead of dropping to default 0.020 (#1689 follow-up).
  833. const activeIdx = slotInfo.caliIdx;
  834. if (activeIdx != null && activeIdx > 0) {
  835. const active = findProfileByCaliIdx(kprofilesData.profiles, activeIdx, slotInfo.extruderId);
  836. if (active) return [active];
  837. }
  838. return [];
  839. }
  840. const { fullName, material, brand, filamentId } = selectedPresetInfo;
  841. const upperFullName = fullName.toUpperCase();
  842. const upperMaterial = material.toUpperCase();
  843. // "Generic" leads every built-in Bambu preset name ("Generic PLA",
  844. // "Generic PETG") but is not a manufacturer (#2710). Treating it as one
  845. // put the filter into brand-gated mode and demanded "GENERIC" in the
  846. // K-profile name, which no real profile has — so selecting a built-in
  847. // generic preset matched nothing at all.
  848. const upperBrand = brand.toUpperCase() === 'GENERIC' ? '' : brand.toUpperCase();
  849. const presetFid = filamentId; // already normalised via toFilamentId
  850. // Material must be at least 2 chars to avoid false positives
  851. if (!upperMaterial || upperMaterial.length < 2) return [];
  852. // Filter profiles - require brand match if brand is present in selected preset
  853. const filtered = kprofilesData.profiles.filter(p => {
  854. // Preferred: exact filament_id match (#1688). A user's custom K-profile
  855. // whose name doesn't agree with the slicer preset still surfaces when
  856. // both sides agree on filament_id.
  857. //
  858. // Generic GFx99 ids count here too (#2710). The equality test already
  859. // means both sides carry the *same* id, so the old "generic ids
  860. // over-match" exclusion could only ever fire when the selected preset
  861. // was itself the generic one — precisely the case where the match is
  862. // right. The printer keeps one calibration table per filament_id, so a
  863. // slot on "Generic PLA" should offer every profile calibrated under
  864. // Generic PLA, whatever the user named them.
  865. if (presetFid) {
  866. const calFid = toFilamentId(p.filament_id);
  867. if (calFid && calFid === presetFid) {
  868. return true;
  869. }
  870. }
  871. const profileName = p.name.toUpperCase();
  872. // If the selected preset has a brand (e.g., "Azurefilm PLA Wood"),
  873. // only show profiles that match the brand
  874. if (upperBrand) {
  875. // Must contain the brand name
  876. if (!profileName.includes(upperBrand)) {
  877. return false;
  878. }
  879. // And must contain the material type
  880. if (!profileName.includes(upperMaterial)) {
  881. return false;
  882. }
  883. return true;
  884. }
  885. // No brand in selected preset - match on full name or material
  886. // Priority 1: Exact match with full name
  887. if (profileName.includes(upperFullName)) {
  888. return true;
  889. }
  890. // Priority 2: Material type match (only when no brand specified)
  891. if (profileName.includes(upperMaterial)) {
  892. return true;
  893. }
  894. // Check for common material aliases
  895. const aliases: Record<string, string[]> = {
  896. 'NYLON': ['PA', 'PA-CF', 'PA6'],
  897. 'PA': ['NYLON'],
  898. };
  899. const materialAliases = aliases[upperMaterial] || [];
  900. for (const alias of materialAliases) {
  901. if (profileName.includes(alias)) {
  902. return true;
  903. }
  904. }
  905. return false;
  906. });
  907. // Scope to the slot's own nozzle when it is known: a K-profile calibrated on
  908. // the other hotend is not a match for this slot, and offering it as one is
  909. // how the wrong K got bound. Those profiles are still reachable below under
  910. // "Other", where the option label names the hotend.
  911. const onThisNozzle = slotInfo.extruderId === undefined
  912. ? filtered
  913. : filtered.filter(p => (p.extruder_id ?? 0) === slotInfo.extruderId);
  914. // Deduplicate genuine duplicates — same nozzle, same name, same K.
  915. const seen = new Map<string, KProfile>();
  916. for (const profile of onThisNozzle) {
  917. const key = kProfileOptionValue(profile);
  918. if (!seen.has(key)) seen.set(key, profile);
  919. }
  920. const result = Array.from(seen.values());
  921. // Always include the slot's currently-active K-profile (by cali_idx / slot_id),
  922. // even if its name and filament_id didn't match the selected preset (#1689).
  923. // A spool assigned under "Generic PLA" can have a K-profile actively bound on
  924. // the printer whose filament_id differs from "Generic PLA"; without this
  925. // safety net the modal shows "not assigned, default 0.020" while the printer
  926. // card's hover-card correctly shows the active profile.
  927. const activeIdx = slotInfo.caliIdx;
  928. if (activeIdx != null && activeIdx > 0 && !result.some(p => p.slot_id === activeIdx)) {
  929. const active = findProfileByCaliIdx(kprofilesData.profiles, activeIdx, slotInfo.extruderId);
  930. if (active) result.unshift(active);
  931. }
  932. return result;
  933. }, [kprofilesData?.profiles, selectedPresetInfo, slotInfo.extruderId, slotInfo.caliIdx]);
  934. // Every remaining K-profile the printer holds, offered under a separate group
  935. // after the matching ones (#2710). The matcher works off preset names and
  936. // filament ids, neither of which the user controls when they name a profile
  937. // after its colour — so there is always a residual chance it filters out a
  938. // profile the user wants. This makes that recoverable in the UI instead of
  939. // sending them to the slicer: the printer's own calibration table is the
  940. // authority on what can be selected, and the backend realigns the slot's
  941. // filament context to whichever profile is picked.
  942. const otherKProfiles = useMemo(() => {
  943. if (!kprofilesData?.profiles) return [];
  944. const matched = new Set(matchingKProfiles.map(p => kProfileOptionValue(p)));
  945. // Same name+k_value dedup as the matching list, so a multi-nozzle printer's
  946. // duplicate rows don't show up twice here either.
  947. const seen = new Map<string, KProfile>();
  948. for (const profile of kprofilesData.profiles) {
  949. const key = kProfileOptionValue(profile);
  950. if (matched.has(key)) continue;
  951. if (!seen.has(key)) seen.set(key, profile);
  952. }
  953. return Array.from(seen.values()).sort((a, b) => a.name.localeCompare(b.name));
  954. }, [kprofilesData?.profiles, matchingKProfiles]);
  955. const hasAnyKProfile = matchingKProfiles.length > 0 || otherKProfiles.length > 0;
  956. const selectKProfileByValue = useCallback((value: string) => {
  957. if (!value) {
  958. setSelectedKProfile(null);
  959. return;
  960. }
  961. const profile = matchingKProfiles.find(p => kProfileOptionValue(p) === value)
  962. || otherKProfiles.find(p => kProfileOptionValue(p) === value)
  963. || null;
  964. setSelectedKProfile(profile);
  965. }, [matchingKProfiles, otherKProfiles]);
  966. // Pre-select current profile when modal opens, reset when closes
  967. useEffect(() => {
  968. if (isOpen) {
  969. // The spool's own per-model preset first -- see the query above.
  970. if (slotSpoolDefaults?.slicer_filament) {
  971. setSelectedPresetId(slotSpoolDefaults.slicer_filament);
  972. } else if (slotInfo.savedPresetId) {
  973. setSelectedPresetId(slotInfo.savedPresetId);
  974. } else if (slotInfo.trayInfoIdx && cloudSettings?.filament) {
  975. // Fallback: try to match by tray_info_idx in cloud presets
  976. // First try exact match on setting_id
  977. let currentPreset = cloudSettings.filament.find(
  978. p => p.setting_id === slotInfo.trayInfoIdx
  979. );
  980. // Then try matching by converting setting_id → filament_id format
  981. if (!currentPreset) {
  982. currentPreset = cloudSettings.filament.find(
  983. p => convertToTrayInfoIdx(p.setting_id) === slotInfo.trayInfoIdx
  984. );
  985. }
  986. if (currentPreset) {
  987. setSelectedPresetId(currentPreset.setting_id);
  988. }
  989. } else if (slotInfo.trayInfoIdx && builtinFilaments?.length) {
  990. // Last resort: match trayInfoIdx against builtin presets
  991. const trayIdx = slotInfo.trayInfoIdx;
  992. const match = builtinFilaments.find(bf => bf.filament_id === trayIdx);
  993. if (match) {
  994. setSelectedPresetId(`builtin_${match.filament_id}`);
  995. }
  996. }
  997. // Pre-populate color from current slot (black is valid — empty slots don't pass trayColor)
  998. if (slotInfo.trayColor) {
  999. const hex = slotInfo.trayColor.slice(0, 6);
  1000. if (hex) {
  1001. setColorHex(hex);
  1002. }
  1003. }
  1004. } else {
  1005. // Reset when modal closes
  1006. setSelectedPresetId('');
  1007. setSelectedKProfile(null);
  1008. setColorHex('');
  1009. setColorInput('');
  1010. setSearchQuery('');
  1011. setShowSuccess(false);
  1012. scrolledToRef.current = '';
  1013. }
  1014. }, [
  1015. isOpen,
  1016. slotSpoolDefaults?.slicer_filament,
  1017. slotInfo.savedPresetId,
  1018. slotInfo.trayInfoIdx,
  1019. slotInfo.trayColor,
  1020. cloudSettings?.filament,
  1021. builtinFilaments,
  1022. ]);
  1023. // Auto-select best matching K profile when preset changes
  1024. useEffect(() => {
  1025. if (matchingKProfiles.length > 0) {
  1026. // The profile the spool is configured with for THIS hotend, if it still
  1027. // exists on the printer. Ahead of the slot's live cali_idx, which is
  1028. // whatever was selected last rather than what the spool is set to.
  1029. if (slotSpoolDefaults?.cali_idx != null) {
  1030. const configured = findProfileByCaliIdx(
  1031. matchingKProfiles,
  1032. slotSpoolDefaults.cali_idx,
  1033. slotSpoolDefaults.extruder ?? slotInfo.extruderId,
  1034. );
  1035. if (configured) {
  1036. setSelectedKProfile(configured);
  1037. return;
  1038. }
  1039. }
  1040. // Prefer the currently-active K-profile, resolved against this slot's own
  1041. // nozzle — the index alone is ambiguous across hotends.
  1042. if (slotInfo.caliIdx != null && slotInfo.caliIdx > 0) {
  1043. const active = findProfileByCaliIdx(matchingKProfiles, slotInfo.caliIdx, slotInfo.extruderId);
  1044. if (active) {
  1045. setSelectedKProfile(active);
  1046. return;
  1047. }
  1048. }
  1049. // Fallback: the first match. matchingKProfiles is already scoped to this
  1050. // slot's nozzle when we know which one it is, so this cannot hand over a
  1051. // profile calibrated on the other hotend.
  1052. setSelectedKProfile(matchingKProfiles[0]);
  1053. } else {
  1054. setSelectedKProfile(null);
  1055. }
  1056. }, [
  1057. selectedPresetId,
  1058. matchingKProfiles,
  1059. slotSpoolDefaults?.cali_idx,
  1060. slotSpoolDefaults?.extruder,
  1061. slotInfo.caliIdx,
  1062. slotInfo.extruderId,
  1063. ]);
  1064. // Escape key handler
  1065. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  1066. if (e.key === 'Escape') {
  1067. onClose();
  1068. }
  1069. }, [onClose]);
  1070. useEffect(() => {
  1071. if (isOpen) {
  1072. document.addEventListener('keydown', handleKeyDown);
  1073. return () => document.removeEventListener('keydown', handleKeyDown);
  1074. }
  1075. }, [isOpen, handleKeyDown]);
  1076. const isLoading = (settingsLoading && !cloudError) || localLoading || builtinLoading || kprofilesLoading;
  1077. // Scroll selected preset into view when data finishes loading or the selection changes.
  1078. // Uses a ref guard so scrollIntoView only fires once per selection, preventing the
  1079. // infinite scroll loop that occurred on Windows with inline callback refs.
  1080. useEffect(() => {
  1081. if (!isLoading && selectedPresetId && selectedPresetId !== scrolledToRef.current) {
  1082. const raf = requestAnimationFrame(() => {
  1083. const modal = document.querySelector('[class*="fixed inset-0 z-50"]');
  1084. const el = modal?.querySelector(`[data-preset-id="${CSS.escape(selectedPresetId)}"]`);
  1085. if (el) {
  1086. scrolledToRef.current = selectedPresetId;
  1087. el.scrollIntoView({ block: 'nearest' });
  1088. }
  1089. });
  1090. return () => cancelAnimationFrame(raf);
  1091. }
  1092. }, [selectedPresetId, isLoading]);
  1093. if (!isOpen) return null;
  1094. const canSave = selectedPresetId && !configureMutation.isPending;
  1095. // Get display color (custom or slot default)
  1096. // Not sliced to six: a clear tray reports RRGGBB00, and cutting the alpha off
  1097. // here previewed it as solid black. `colorHex` is the edited form value and is
  1098. // always six characters, so only the tray fallback ever carries an alpha (#2912).
  1099. const displayColor = colorHex || slotInfo.trayColor || 'FFFFFF';
  1100. return (
  1101. <div className={`fixed inset-0 z-50 flex ${fullScreen ? '' : 'items-center justify-center'}`}>
  1102. {/* Backdrop */}
  1103. {!fullScreen && (
  1104. <div
  1105. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  1106. onClick={onClose}
  1107. />
  1108. )}
  1109. {/* Modal */}
  1110. <div className={fullScreen
  1111. ? 'relative w-full h-full bg-bambu-dark-secondary flex flex-col'
  1112. : 'relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl'
  1113. }>
  1114. {/* Header */}
  1115. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0">
  1116. <div className="flex items-center gap-2">
  1117. <Settings2 className="w-5 h-5 text-bambu-blue" />
  1118. <h2 className="text-lg font-semibold text-white">{t('configureAmsSlot.title')}</h2>
  1119. {/* Inline slot info in fullScreen mode */}
  1120. {fullScreen && (
  1121. <div className="flex items-center gap-2 ml-4 text-sm text-bambu-gray">
  1122. <span className="text-white/30">|</span>
  1123. {slotInfo.trayColor && (
  1124. <span
  1125. className="w-4 h-4 rounded-full border border-black/20"
  1126. style={getSwatchStyle(slotInfo.trayColor)}
  1127. />
  1128. )}
  1129. <span className="text-white/70">
  1130. {t('configureAmsSlot.slotLabel', { ams: getAmsLabel(slotInfo.amsId, slotInfo.trayCount), slot: slotInfo.trayId + 1 })}
  1131. </span>
  1132. {slotInfo.traySubBrands && (
  1133. <span>({slotInfo.traySubBrands})</span>
  1134. )}
  1135. </div>
  1136. )}
  1137. </div>
  1138. <button
  1139. onClick={onClose}
  1140. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  1141. >
  1142. <X className="w-5 h-5" />
  1143. </button>
  1144. </div>
  1145. {/* Content */}
  1146. <div className={`p-4 overflow-y-auto ${fullScreen ? 'flex-1 min-h-0' : 'space-y-4 max-h-[60vh]'}`}>
  1147. {/* Success overlay */}
  1148. {showSuccess && (
  1149. <div className="absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl">
  1150. <div className="text-center space-y-3">
  1151. <CheckCircle2 className="w-16 h-16 text-bambu-green mx-auto" />
  1152. <p className="text-lg font-semibold text-white">{t('configureAmsSlot.slotConfigured')}</p>
  1153. <p className="text-sm text-bambu-gray">{t('configureAmsSlot.settingsSentToPrinter')}</p>
  1154. </div>
  1155. </div>
  1156. )}
  1157. {/* Slot info */}
  1158. {!fullScreen && (
  1159. <div className="p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary">
  1160. <p className="text-xs text-bambu-gray mb-1">{t('configureAmsSlot.configuringSlot')}</p>
  1161. <div className="flex items-center gap-2">
  1162. {slotInfo.trayColor && (
  1163. <span
  1164. className="w-4 h-4 rounded-full border border-black/20"
  1165. style={getSwatchStyle(slotInfo.trayColor)}
  1166. />
  1167. )}
  1168. <span className="text-white font-medium">
  1169. {t('configureAmsSlot.slotLabel', { ams: getAmsLabel(slotInfo.amsId, slotInfo.trayCount), slot: slotInfo.trayId + 1 })}
  1170. </span>
  1171. {slotInfo.traySubBrands && (
  1172. <span className="text-bambu-gray">({slotInfo.traySubBrands})</span>
  1173. )}
  1174. </div>
  1175. </div>
  1176. )}
  1177. {isLoading ? (
  1178. <div className="flex justify-center py-8">
  1179. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  1180. </div>
  1181. ) : fullScreen ? (
  1182. /* Two-column layout for kiosk display */
  1183. <div className="flex gap-4 h-full">
  1184. {/* Left column: Filament preset list (takes full height) */}
  1185. <div className="w-1/2 flex flex-col min-h-0">
  1186. <label className="block text-sm text-bambu-gray mb-2">
  1187. {t('configureAmsSlot.filamentProfile')} <span className="text-red-600 dark:text-red-400">*</span>
  1188. </label>
  1189. <input
  1190. type="text"
  1191. placeholder={t('configureAmsSlot.searchPresets')}
  1192. value={searchQuery}
  1193. onChange={(e) => setSearchQuery(e.target.value)}
  1194. 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"
  1195. />
  1196. <div className="flex-1 min-h-0 overflow-y-auto space-y-1">
  1197. {filteredPresets.length === 0 ? (
  1198. <p className="text-center py-4 text-bambu-gray">
  1199. {(cloudSettings?.filament?.length === 0 && !localPresets?.filament?.length)
  1200. ? t('configureAmsSlot.noPresetsAvailable')
  1201. : t('configureAmsSlot.noMatchingPresets')}
  1202. </p>
  1203. ) : (
  1204. filteredPresets.map((preset) => (
  1205. <button
  1206. key={preset.id}
  1207. data-preset-id={preset.id}
  1208. onClick={() => setSelectedPresetId(preset.id)}
  1209. className={`group w-full p-2 rounded-lg border text-left transition-colors ${
  1210. selectedPresetId === preset.id
  1211. ? 'bg-bambu-green/20 border-bambu-green'
  1212. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  1213. }`}
  1214. >
  1215. <div className="flex items-center justify-between">
  1216. <span className="text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all" title={preset.name}>{preset.name}</span>
  1217. <div className="flex items-center gap-1 flex-shrink-0">
  1218. {preset.source === 'local' && (
  1219. <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">
  1220. {t('profiles.localProfiles.badge')}
  1221. </span>
  1222. )}
  1223. {preset.source === 'orca_cloud' && (
  1224. <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">
  1225. {t('configureAmsSlot.orcaCloud')}
  1226. </span>
  1227. )}
  1228. {preset.source === 'cloud' && (
  1229. <span className="text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue">
  1230. {t('configureAmsSlot.bambuCloud')}
  1231. </span>
  1232. )}
  1233. {preset.source === 'builtin' && (
  1234. <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">
  1235. {t('configureAmsSlot.builtin')}
  1236. </span>
  1237. )}
  1238. </div>
  1239. </div>
  1240. </button>
  1241. ))
  1242. )}
  1243. </div>
  1244. </div>
  1245. {/* Right column: K Profile + Color */}
  1246. <div className="w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto">
  1247. {/* K Profile Select */}
  1248. <div>
  1249. <label className="block text-sm text-bambu-gray mb-2">
  1250. {t('configureAmsSlot.kProfileLabel')}
  1251. {selectedMaterial && (
  1252. <span className="ml-2 text-xs text-bambu-blue">
  1253. {t('configureAmsSlot.filteringFor', { material: selectedMaterial })}
  1254. </span>
  1255. )}
  1256. </label>
  1257. {hasAnyKProfile ? (
  1258. <div className="relative">
  1259. <select
  1260. value={selectedKProfile ? kProfileOptionValue(selectedKProfile) : ''}
  1261. onChange={(e) => selectKProfileByValue(e.target.value)}
  1262. 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"
  1263. >
  1264. <option value="">{t('configureAmsSlot.noKProfile')}</option>
  1265. {matchingKProfiles.map((profile) => (
  1266. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1267. {profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}{kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1268. </option>
  1269. ))}
  1270. {otherKProfiles.length > 0 && (
  1271. <optgroup label={t('configureAmsSlot.otherKProfiles')}>
  1272. {otherKProfiles.map((profile) => (
  1273. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1274. {profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}{kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}{kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1275. </option>
  1276. ))}
  1277. </optgroup>
  1278. )}
  1279. </select>
  1280. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  1281. </div>
  1282. ) : selectedPresetId ? (
  1283. <p className="text-sm text-bambu-gray italic py-2">
  1284. {t('configureAmsSlot.noMatchingKProfiles')}
  1285. </p>
  1286. ) : (
  1287. <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">
  1288. {t('configureAmsSlot.selectFilamentFirst')}
  1289. </span>
  1290. )}
  1291. {selectedKProfile && (
  1292. <p className="text-xs text-bambu-green mt-1">
  1293. {t('configureAmsSlot.kFromCalibration', { value: selectedKProfile.k_value })}
  1294. </p>
  1295. )}
  1296. </div>
  1297. {/* Custom color */}
  1298. <div>
  1299. <label className="block text-sm text-bambu-gray mb-2">
  1300. {t('configureAmsSlot.customColorLabel')}
  1301. </label>
  1302. {catalogColors.length > 0 && (
  1303. <div className="mb-3">
  1304. <p className="text-xs text-bambu-gray mb-1.5">
  1305. {t('configureAmsSlot.presetColors', { name: selectedPresetInfo?.fullName })}
  1306. </p>
  1307. <div className="flex flex-wrap gap-1.5">
  1308. {catalogColors.map((entry) => (
  1309. <button
  1310. key={entry.id}
  1311. onClick={() => {
  1312. const hex = entry.hex_color.replace('#', '').toUpperCase();
  1313. setColorHex(hex);
  1314. setColorInput(entry.color_name);
  1315. }}
  1316. className={`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${
  1317. colorHex === entry.hex_color.replace('#', '').toUpperCase()
  1318. ? 'border-bambu-green scale-105'
  1319. : 'border-white/20 hover:border-white/40'
  1320. }`}
  1321. title={entry.color_name}
  1322. >
  1323. <span
  1324. className="w-4 h-4 rounded-full border border-black/20 flex-shrink-0"
  1325. style={{ backgroundColor: entry.hex_color }}
  1326. />
  1327. <span className="text-xs text-white/80 whitespace-nowrap">{entry.color_name}</span>
  1328. </button>
  1329. ))}
  1330. </div>
  1331. </div>
  1332. )}
  1333. <div className="flex flex-wrap gap-1.5 mb-2">
  1334. {QUICK_COLORS_BASIC.map((color) => (
  1335. <button
  1336. key={color.hex}
  1337. onClick={() => {
  1338. setColorHex(color.hex);
  1339. setColorInput(color.name);
  1340. }}
  1341. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1342. colorHex === color.hex
  1343. ? 'border-bambu-green scale-110'
  1344. : 'border-white/20 hover:border-white/40'
  1345. }`}
  1346. style={{ backgroundColor: `#${color.hex}` }}
  1347. title={color.name}
  1348. />
  1349. ))}
  1350. <button
  1351. onClick={() => setShowExtendedColors(!showExtendedColors)}
  1352. 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"
  1353. title={showExtendedColors ? t('configureAmsSlot.showLessColors') : t('configureAmsSlot.showMoreColors')}
  1354. >
  1355. {showExtendedColors ? '−' : '+'}
  1356. </button>
  1357. </div>
  1358. {showExtendedColors && (
  1359. <div className="flex flex-wrap gap-1.5 mb-2">
  1360. {QUICK_COLORS_EXTENDED.map((color) => (
  1361. <button
  1362. key={color.hex}
  1363. onClick={() => {
  1364. setColorHex(color.hex);
  1365. setColorInput(color.name);
  1366. }}
  1367. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1368. colorHex === color.hex
  1369. ? 'border-bambu-green scale-110'
  1370. : 'border-white/20 hover:border-white/40'
  1371. }`}
  1372. style={{ backgroundColor: `#${color.hex}` }}
  1373. title={color.name}
  1374. />
  1375. ))}
  1376. </div>
  1377. )}
  1378. <div className="flex gap-2 items-center">
  1379. <div
  1380. className="w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0"
  1381. style={getSwatchStyle(displayColor)}
  1382. />
  1383. <input
  1384. type="text"
  1385. placeholder={t('configureAmsSlot.colorPlaceholder')}
  1386. value={colorInput}
  1387. onChange={(e) => {
  1388. const input = e.target.value;
  1389. setColorInput(input);
  1390. const nameHex = colorNameToHex(input);
  1391. if (nameHex) {
  1392. setColorHex(nameHex);
  1393. } else {
  1394. const cleaned = input.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
  1395. if (cleaned.length === 6) {
  1396. setColorHex(cleaned);
  1397. } else if (cleaned.length === 3) {
  1398. setColorHex(cleaned.split('').map(c => c + c).join(''));
  1399. }
  1400. }
  1401. }}
  1402. 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"
  1403. />
  1404. {colorHex && (
  1405. <button
  1406. onClick={() => {
  1407. setColorHex('');
  1408. setColorInput('');
  1409. }}
  1410. className="px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded"
  1411. title={t('configureAmsSlot.clearCustomColor')}
  1412. >
  1413. {t('configureAmsSlot.clear')}
  1414. </button>
  1415. )}
  1416. </div>
  1417. {colorHex && (
  1418. <p className="text-xs text-bambu-gray mt-1.5">
  1419. {t('configureAmsSlot.hexLabel', { hex: colorHex })}
  1420. </p>
  1421. )}
  1422. </div>
  1423. </div>
  1424. </div>
  1425. ) : (
  1426. <>
  1427. {/* Filament Profile Select */}
  1428. <div>
  1429. <label className="block text-sm text-bambu-gray mb-2">
  1430. {t('configureAmsSlot.filamentProfile')} <span className="text-red-600 dark:text-red-400">*</span>
  1431. </label>
  1432. <div className="relative">
  1433. <input
  1434. type="text"
  1435. placeholder={t('configureAmsSlot.searchPresets')}
  1436. value={searchQuery}
  1437. onChange={(e) => setSearchQuery(e.target.value)}
  1438. 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"
  1439. />
  1440. <div className="max-h-48 overflow-y-auto space-y-1">
  1441. {filteredPresets.length === 0 ? (
  1442. <p className="text-center py-4 text-bambu-gray">
  1443. {(cloudSettings?.filament?.length === 0 && !localPresets?.filament?.length)
  1444. ? t('configureAmsSlot.noPresetsAvailable')
  1445. : t('configureAmsSlot.noMatchingPresets')}
  1446. </p>
  1447. ) : (
  1448. filteredPresets.map((preset) => (
  1449. <button
  1450. key={preset.id}
  1451. data-preset-id={preset.id}
  1452. onClick={() => setSelectedPresetId(preset.id)}
  1453. className={`group w-full p-2 rounded-lg border text-left transition-colors ${
  1454. selectedPresetId === preset.id
  1455. ? 'bg-bambu-green/20 border-bambu-green'
  1456. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  1457. }`}
  1458. >
  1459. <div className="flex items-center justify-between">
  1460. <span className="text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all" title={preset.name}>{preset.name}</span>
  1461. <div className="flex items-center gap-1 flex-shrink-0">
  1462. {preset.source === 'local' && (
  1463. <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">
  1464. {t('profiles.localProfiles.badge')}
  1465. </span>
  1466. )}
  1467. {preset.source === 'orca_cloud' && (
  1468. <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">
  1469. {t('configureAmsSlot.orcaCloud')}
  1470. </span>
  1471. )}
  1472. {preset.source === 'cloud' && (
  1473. <span className="text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue">
  1474. {t('configureAmsSlot.bambuCloud')}
  1475. </span>
  1476. )}
  1477. {preset.source === 'builtin' && (
  1478. <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">
  1479. {t('configureAmsSlot.builtin')}
  1480. </span>
  1481. )}
  1482. </div>
  1483. </div>
  1484. </button>
  1485. ))
  1486. )}
  1487. </div>
  1488. </div>
  1489. </div>
  1490. {/* K Profile Select */}
  1491. <div>
  1492. <label className="block text-sm text-bambu-gray mb-2">
  1493. {t('configureAmsSlot.kProfileLabel')}
  1494. {selectedMaterial && (
  1495. <span className="ml-2 text-xs text-bambu-blue">
  1496. {t('configureAmsSlot.filteringFor', { material: selectedMaterial })}
  1497. </span>
  1498. )}
  1499. </label>
  1500. {hasAnyKProfile ? (
  1501. <div className="relative">
  1502. <select
  1503. value={selectedKProfile ? kProfileOptionValue(selectedKProfile) : ''}
  1504. onChange={(e) => selectKProfileByValue(e.target.value)}
  1505. 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"
  1506. >
  1507. <option value="">{t('configureAmsSlot.noKProfile')}</option>
  1508. {matchingKProfiles.map((profile) => (
  1509. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1510. {profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1511. </option>
  1512. ))}
  1513. {otherKProfiles.length > 0 && (
  1514. <optgroup label={t('configureAmsSlot.otherKProfiles')}>
  1515. {otherKProfiles.map((profile) => (
  1516. <option key={kProfileOptionValue(profile)} value={kProfileOptionValue(profile)}>
  1517. {profile.name} (K={profile.k_value}){kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}{kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}{kProfileNozzleSuffix(profile, isDualNozzleProfiles, t)}
  1518. </option>
  1519. ))}
  1520. </optgroup>
  1521. )}
  1522. </select>
  1523. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  1524. </div>
  1525. ) : selectedPresetId ? (
  1526. <p className="text-sm text-bambu-gray italic py-2">
  1527. {t('configureAmsSlot.noMatchingKProfiles')}
  1528. </p>
  1529. ) : (
  1530. <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">
  1531. {t('configureAmsSlot.selectFilamentFirst')}
  1532. </span>
  1533. )}
  1534. {selectedKProfile && (
  1535. <p className="text-xs text-bambu-green mt-1">
  1536. {t('configureAmsSlot.kFromCalibration', { value: selectedKProfile.k_value })}
  1537. </p>
  1538. )}
  1539. </div>
  1540. {/* Optional: Custom color */}
  1541. <div>
  1542. <label className="block text-sm text-bambu-gray mb-2">
  1543. {t('configureAmsSlot.customColorLabel')}
  1544. </label>
  1545. {/* Catalog colors matching selected preset */}
  1546. {catalogColors.length > 0 && (
  1547. <div className="mb-3">
  1548. <p className="text-xs text-bambu-gray mb-1.5">
  1549. {t('configureAmsSlot.presetColors', { name: selectedPresetInfo?.fullName })}
  1550. </p>
  1551. <div className="flex flex-wrap gap-1.5">
  1552. {catalogColors.map((entry) => (
  1553. <button
  1554. key={entry.id}
  1555. onClick={() => {
  1556. const hex = entry.hex_color.replace('#', '').toUpperCase();
  1557. setColorHex(hex);
  1558. setColorInput(entry.color_name);
  1559. }}
  1560. className={`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${
  1561. colorHex === entry.hex_color.replace('#', '').toUpperCase()
  1562. ? 'border-bambu-green scale-105'
  1563. : 'border-white/20 hover:border-white/40'
  1564. }`}
  1565. title={entry.color_name}
  1566. >
  1567. <span
  1568. className="w-4 h-4 rounded-full border border-black/20 flex-shrink-0"
  1569. style={{ backgroundColor: entry.hex_color }}
  1570. />
  1571. <span className="text-xs text-white/80 whitespace-nowrap">{entry.color_name}</span>
  1572. </button>
  1573. ))}
  1574. </div>
  1575. </div>
  1576. )}
  1577. {/* Quick color buttons */}
  1578. <div className="flex flex-wrap gap-1.5 mb-2">
  1579. {QUICK_COLORS_BASIC.map((color) => (
  1580. <button
  1581. key={color.hex}
  1582. onClick={() => {
  1583. setColorHex(color.hex);
  1584. setColorInput(color.name);
  1585. }}
  1586. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1587. colorHex === color.hex
  1588. ? 'border-bambu-green scale-110'
  1589. : 'border-white/20 hover:border-white/40'
  1590. }`}
  1591. style={{ backgroundColor: `#${color.hex}` }}
  1592. title={color.name}
  1593. />
  1594. ))}
  1595. <button
  1596. onClick={() => setShowExtendedColors(!showExtendedColors)}
  1597. 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"
  1598. title={showExtendedColors ? t('configureAmsSlot.showLessColors') : t('configureAmsSlot.showMoreColors')}
  1599. >
  1600. {showExtendedColors ? '−' : '+'}
  1601. </button>
  1602. </div>
  1603. {/* Extended colors (collapsible) */}
  1604. {showExtendedColors && (
  1605. <div className="flex flex-wrap gap-1.5 mb-2">
  1606. {QUICK_COLORS_EXTENDED.map((color) => (
  1607. <button
  1608. key={color.hex}
  1609. onClick={() => {
  1610. setColorHex(color.hex);
  1611. setColorInput(color.name);
  1612. }}
  1613. className={`w-7 h-7 rounded-md border-2 transition-all ${
  1614. colorHex === color.hex
  1615. ? 'border-bambu-green scale-110'
  1616. : 'border-white/20 hover:border-white/40'
  1617. }`}
  1618. style={{ backgroundColor: `#${color.hex}` }}
  1619. title={color.name}
  1620. />
  1621. ))}
  1622. </div>
  1623. )}
  1624. {/* Color input: name or hex */}
  1625. <div className="flex gap-2 items-center">
  1626. <div
  1627. className="w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0"
  1628. style={getSwatchStyle(displayColor)}
  1629. />
  1630. <input
  1631. type="text"
  1632. placeholder={t('configureAmsSlot.colorPlaceholder')}
  1633. value={colorInput}
  1634. onChange={(e) => {
  1635. const input = e.target.value;
  1636. setColorInput(input);
  1637. // Try to parse as color name first
  1638. const nameHex = colorNameToHex(input);
  1639. if (nameHex) {
  1640. setColorHex(nameHex);
  1641. } else {
  1642. // Try to parse as hex code
  1643. const cleaned = input.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
  1644. if (cleaned.length === 6) {
  1645. setColorHex(cleaned);
  1646. } else if (cleaned.length === 3) {
  1647. // Expand shorthand hex (e.g., F00 -> FF0000)
  1648. setColorHex(cleaned.split('').map(c => c + c).join(''));
  1649. }
  1650. }
  1651. }}
  1652. 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"
  1653. />
  1654. {colorHex && (
  1655. <button
  1656. onClick={() => {
  1657. setColorHex('');
  1658. setColorInput('');
  1659. }}
  1660. className="px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded"
  1661. title={t('configureAmsSlot.clearCustomColor')}
  1662. >
  1663. {t('configureAmsSlot.clear')}
  1664. </button>
  1665. )}
  1666. </div>
  1667. {colorHex && (
  1668. <p className="text-xs text-bambu-gray mt-1.5">
  1669. {t('configureAmsSlot.hexLabel', { hex: colorHex })}
  1670. </p>
  1671. )}
  1672. </div>
  1673. </>
  1674. )}
  1675. </div>
  1676. {/* Footer */}
  1677. <div className="flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0">
  1678. {/* Reset button on the left */}
  1679. <Button
  1680. variant="secondary"
  1681. onClick={() => resetMutation.mutate()}
  1682. disabled={resetMutation.isPending || configureMutation.isPending}
  1683. 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"
  1684. >
  1685. {resetMutation.isPending ? (
  1686. <>
  1687. <Loader2 className="w-4 h-4 animate-spin" />
  1688. {t('configureAmsSlot.resetting')}
  1689. </>
  1690. ) : (
  1691. <>
  1692. <RotateCcw className="w-4 h-4" />
  1693. {t('configureAmsSlot.resetSlot')}
  1694. </>
  1695. )}
  1696. </Button>
  1697. {/* Cancel and Configure buttons on the right */}
  1698. <div className="flex gap-2">
  1699. <Button variant="secondary" onClick={onClose}>
  1700. {t('configureAmsSlot.cancel')}
  1701. </Button>
  1702. <Button
  1703. onClick={() => configureMutation.mutate()}
  1704. disabled={!canSave}
  1705. >
  1706. {configureMutation.isPending ? (
  1707. <>
  1708. <Loader2 className="w-4 h-4 animate-spin" />
  1709. {t('configureAmsSlot.configuring')}
  1710. </>
  1711. ) : (
  1712. <>
  1713. <Settings2 className="w-4 h-4" />
  1714. {t('configureAmsSlot.configureSlot')}
  1715. </>
  1716. )}
  1717. </Button>
  1718. </div>
  1719. </div>
  1720. {/* Error */}
  1721. {(configureMutation.isError || resetMutation.isError) && (
  1722. <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">
  1723. {(configureMutation.error as Error)?.message || (resetMutation.error as Error)?.message}
  1724. </div>
  1725. )}
  1726. </div>
  1727. </div>
  1728. );
  1729. }