ConfigureAmsSlotModal.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. import { useState, useMemo, useEffect, useCallback } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import { X, Loader2, Settings2, ChevronDown, CheckCircle2, RotateCcw } from 'lucide-react';
  4. import { useTranslation } from 'react-i18next';
  5. import { api } from '../api/client';
  6. import type { KProfile } from '../api/client';
  7. import { Button } from './Button';
  8. interface SlotInfo {
  9. amsId: number;
  10. trayId: number;
  11. trayCount: number;
  12. trayType?: string;
  13. trayColor?: string;
  14. traySubBrands?: string;
  15. trayInfoIdx?: string;
  16. }
  17. // Get proper AMS label (handles HT AMS with ID 128+)
  18. function getAmsLabel(amsId: number, trayCount: number): string {
  19. // External spool
  20. if (amsId === 255) return 'External';
  21. let normalizedId: number;
  22. let isHt = false;
  23. if (amsId >= 128 && amsId <= 135) {
  24. // HT AMS range: 128-135 → A-H
  25. normalizedId = amsId - 128;
  26. isHt = true;
  27. } else if (amsId >= 0 && amsId <= 3) {
  28. // Regular AMS range: 0-3 → A-D
  29. normalizedId = amsId;
  30. // Check tray count as secondary indicator
  31. isHt = trayCount === 1;
  32. } else {
  33. // Unknown range - fallback to A
  34. normalizedId = 0;
  35. }
  36. // Cap to valid letter range (A-H)
  37. normalizedId = Math.max(0, Math.min(normalizedId, 7));
  38. const letter = String.fromCharCode(65 + normalizedId);
  39. return isHt ? `HT-${letter}` : `AMS-${letter}`;
  40. }
  41. // Convert setting_id to tray_info_idx (filament_id format)
  42. // Bambu format: setting_id "GFSL05" → tray_info_idx "GFL05"
  43. function convertToTrayInfoIdx(settingId: string): string {
  44. // Strip version suffix if present (e.g., GFSL05_07 -> GFSL05)
  45. const baseId = settingId.includes('_') ? settingId.split('_')[0] : settingId;
  46. // Bambu presets start with "GFS" - remove the 'S' to get filament_id
  47. if (baseId.startsWith('GFS')) {
  48. return 'GF' + baseId.slice(3);
  49. }
  50. // User presets (PFUS*, PFSP*) - use the base setting_id (without version suffix)
  51. // This follows the pattern that filament_id and setting_id share the same base ID
  52. if (baseId.startsWith('PFUS') || baseId.startsWith('PFSP')) {
  53. return baseId; // Use base ID without version suffix
  54. }
  55. // For other formats, use as-is
  56. return baseId;
  57. }
  58. interface ConfigureAmsSlotModalProps {
  59. isOpen: boolean;
  60. onClose: () => void;
  61. printerId: number;
  62. slotInfo: SlotInfo;
  63. nozzleDiameter?: string;
  64. onSuccess?: () => void;
  65. }
  66. // Known filament material types
  67. const MATERIAL_TYPES = ['PLA', 'PETG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'NYLON', 'PVA', 'HIPS', 'PP', 'PET'];
  68. // Extract filament type from preset name by finding known material type
  69. function parsePresetName(name: string): { material: string; brand: string; variant: string } {
  70. // Remove printer/nozzle suffix first
  71. const withoutSuffix = name.replace(/@.+$/, '').trim();
  72. // Try to find a known material type in the name
  73. const upperName = withoutSuffix.toUpperCase();
  74. for (const mat of MATERIAL_TYPES) {
  75. // Use word boundary to match whole words only
  76. const regex = new RegExp(`\\b${mat}\\b`, 'i');
  77. if (regex.test(upperName)) {
  78. // Found material, extract brand (everything before material) and variant (after)
  79. const parts = withoutSuffix.split(regex);
  80. const brand = parts[0]?.trim() || '';
  81. const variant = parts[1]?.trim() || '';
  82. return { material: mat, brand, variant };
  83. }
  84. }
  85. // Fallback: assume first word is brand, second is material
  86. const parts = withoutSuffix.split(/\s+/);
  87. if (parts.length >= 2) {
  88. return { material: parts[1], brand: parts[0], variant: parts.slice(2).join(' ') };
  89. }
  90. return { material: withoutSuffix, brand: '', variant: '' };
  91. }
  92. // Check if a preset is a user preset (not built-in)
  93. function isUserPreset(settingId: string): boolean {
  94. // Built-in presets have specific patterns, user presets are UUIDs
  95. return !settingId.startsWith('GF') && !settingId.startsWith('P1');
  96. }
  97. // Common color name to hex mapping
  98. const COLOR_NAME_MAP: Record<string, string> = {
  99. // Basic colors
  100. 'white': 'FFFFFF',
  101. 'black': '000000',
  102. 'red': 'FF0000',
  103. 'green': '00FF00',
  104. 'blue': '0000FF',
  105. 'yellow': 'FFFF00',
  106. 'cyan': '00FFFF',
  107. 'magenta': 'FF00FF',
  108. 'orange': 'FFA500',
  109. 'purple': '800080',
  110. 'pink': 'FFC0CB',
  111. 'brown': '8B4513',
  112. 'gray': '808080',
  113. 'grey': '808080',
  114. // Filament-specific colors
  115. 'jade white': 'FFFEF2',
  116. 'ivory': 'FFFFF0',
  117. 'beige': 'F5F5DC',
  118. 'cream': 'FFFDD0',
  119. 'silver': 'C0C0C0',
  120. 'gold': 'FFD700',
  121. 'bronze': 'CD7F32',
  122. 'copper': 'B87333',
  123. 'navy': '000080',
  124. 'teal': '008080',
  125. 'olive': '808000',
  126. 'maroon': '800000',
  127. 'coral': 'FF7F50',
  128. 'salmon': 'FA8072',
  129. 'lime': '32CD32',
  130. 'mint': '98FF98',
  131. 'forest green': '228B22',
  132. 'sky blue': '87CEEB',
  133. 'royal blue': '4169E1',
  134. 'turquoise': '40E0D0',
  135. 'lavender': 'E6E6FA',
  136. 'violet': 'EE82EE',
  137. 'plum': 'DDA0DD',
  138. 'tan': 'D2B48C',
  139. 'chocolate': 'D2691E',
  140. 'charcoal': '36454F',
  141. 'slate': '708090',
  142. 'transparent': '000000', // Will need special handling
  143. 'natural': 'F5F5DC',
  144. 'wood': 'DEB887',
  145. };
  146. // Quick-select color presets (common filament colors)
  147. // Basic colors shown by default
  148. const QUICK_COLORS_BASIC = [
  149. { name: 'White', hex: 'FFFFFF' },
  150. { name: 'Black', hex: '000000' },
  151. { name: 'Red', hex: 'FF0000' },
  152. { name: 'Blue', hex: '0000FF' },
  153. { name: 'Green', hex: '00AA00' },
  154. { name: 'Yellow', hex: 'FFFF00' },
  155. { name: 'Orange', hex: 'FFA500' },
  156. { name: 'Gray', hex: '808080' },
  157. ];
  158. // Extended colors shown when expanded
  159. const QUICK_COLORS_EXTENDED = [
  160. { name: 'Cyan', hex: '00FFFF' },
  161. { name: 'Magenta', hex: 'FF00FF' },
  162. { name: 'Purple', hex: '800080' },
  163. { name: 'Pink', hex: 'FFC0CB' },
  164. { name: 'Brown', hex: '8B4513' },
  165. { name: 'Beige', hex: 'F5F5DC' },
  166. { name: 'Navy', hex: '000080' },
  167. { name: 'Teal', hex: '008080' },
  168. { name: 'Lime', hex: '32CD32' },
  169. { name: 'Gold', hex: 'FFD700' },
  170. { name: 'Silver', hex: 'C0C0C0' },
  171. { name: 'Maroon', hex: '800000' },
  172. { name: 'Olive', hex: '808000' },
  173. { name: 'Coral', hex: 'FF7F50' },
  174. { name: 'Salmon', hex: 'FA8072' },
  175. { name: 'Turquoise', hex: '40E0D0' },
  176. { name: 'Violet', hex: 'EE82EE' },
  177. { name: 'Indigo', hex: '4B0082' },
  178. { name: 'Chocolate', hex: 'D2691E' },
  179. { name: 'Tan', hex: 'D2B48C' },
  180. { name: 'Slate', hex: '708090' },
  181. { name: 'Charcoal', hex: '36454F' },
  182. { name: 'Ivory', hex: 'FFFFF0' },
  183. { name: 'Cream', hex: 'FFFDD0' },
  184. ];
  185. // Try to convert color name to hex
  186. function colorNameToHex(name: string): string | null {
  187. const normalized = name.toLowerCase().trim();
  188. return COLOR_NAME_MAP[normalized] || null;
  189. }
  190. export function ConfigureAmsSlotModal({
  191. isOpen,
  192. onClose,
  193. printerId,
  194. slotInfo,
  195. nozzleDiameter = '0.4',
  196. onSuccess,
  197. }: ConfigureAmsSlotModalProps) {
  198. const { t } = useTranslation();
  199. const [selectedPresetId, setSelectedPresetId] = useState<string>('');
  200. const [selectedKProfile, setSelectedKProfile] = useState<KProfile | null>(null);
  201. const [colorHex, setColorHex] = useState<string>(''); // Just the 6-char hex, no alpha
  202. const [colorInput, setColorInput] = useState<string>(''); // User's text input (name or hex)
  203. const [searchQuery, setSearchQuery] = useState('');
  204. const [showSuccess, setShowSuccess] = useState(false);
  205. const [showExtendedColors, setShowExtendedColors] = useState(false);
  206. // Fetch cloud settings
  207. const { data: cloudSettings, isLoading: settingsLoading } = useQuery({
  208. queryKey: ['cloudSettings'],
  209. queryFn: () => api.getCloudSettings(),
  210. enabled: isOpen,
  211. });
  212. // Fetch K profiles
  213. const { data: kprofilesData, isLoading: kprofilesLoading } = useQuery({
  214. queryKey: ['kprofiles', printerId, nozzleDiameter],
  215. queryFn: () => api.getKProfiles(printerId, nozzleDiameter),
  216. enabled: isOpen && !!printerId,
  217. });
  218. // Configure slot mutation
  219. const configureMutation = useMutation({
  220. mutationFn: async () => {
  221. if (!selectedPresetId) throw new Error('No filament preset selected');
  222. // Get the selected preset details
  223. const selectedPreset = cloudSettings?.filament.find(p => p.setting_id === selectedPresetId);
  224. if (!selectedPreset) throw new Error('Selected preset not found');
  225. // Parse the preset name for filament info
  226. const parsed = parsePresetName(selectedPreset.name);
  227. // Get cali_idx from selected K profile's slot_id (-1 = use default 0.020)
  228. const caliIdx = selectedKProfile?.slot_id ?? -1;
  229. // Use custom color if set, otherwise use current slot color or default
  230. const color = colorHex || slotInfo.trayColor?.slice(0, 6) || 'FFFFFF';
  231. // Create the tray_sub_brands from preset name (without printer/nozzle suffix)
  232. const traySubBrands = selectedPreset.name.replace(/@.+$/, '').trim();
  233. // Get tray_info_idx: for user presets, fetch detail to get filament_id or derive from base_id
  234. let trayInfoIdx = convertToTrayInfoIdx(selectedPresetId);
  235. // For user presets (not starting with GF), fetch the detail to get the real filament_id
  236. if (!selectedPresetId.startsWith('GFS')) {
  237. try {
  238. const detail = await api.getCloudSettingDetail(selectedPresetId);
  239. if (detail.filament_id) {
  240. trayInfoIdx = detail.filament_id;
  241. } else if (detail.base_id) {
  242. // If no filament_id but has base_id (e.g., "GFSL05_09"), derive tray_info_idx from it
  243. // This is common for user presets that inherit from Bambu presets
  244. trayInfoIdx = convertToTrayInfoIdx(detail.base_id);
  245. console.log(`Derived tray_info_idx from base_id: ${detail.base_id} -> ${trayInfoIdx}`);
  246. }
  247. } catch (e) {
  248. console.warn('Failed to fetch preset detail for filament_id:', e);
  249. // Fall back to derived tray_info_idx
  250. }
  251. }
  252. // Default temp range based on material type
  253. let tempMin = 190;
  254. let tempMax = 230;
  255. const material = parsed.material.toUpperCase();
  256. if (material.includes('PLA')) {
  257. tempMin = 190;
  258. tempMax = 230;
  259. } else if (material.includes('PETG')) {
  260. tempMin = 220;
  261. tempMax = 260;
  262. } else if (material.includes('ABS')) {
  263. tempMin = 240;
  264. tempMax = 280;
  265. } else if (material.includes('ASA')) {
  266. tempMin = 240;
  267. tempMax = 280;
  268. } else if (material.includes('TPU')) {
  269. tempMin = 200;
  270. tempMax = 240;
  271. } else if (material.includes('PC')) {
  272. tempMin = 260;
  273. tempMax = 300;
  274. } else if (material.includes('PA') || material.includes('NYLON')) {
  275. tempMin = 250;
  276. tempMax = 290;
  277. }
  278. // Parse K value from selected profile
  279. const kValue = selectedKProfile?.k_value ? parseFloat(selectedKProfile.k_value) : 0;
  280. // Configure the slot via MQTT
  281. const result = await api.configureAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId, {
  282. tray_info_idx: trayInfoIdx,
  283. tray_type: parsed.material || 'PLA',
  284. tray_sub_brands: traySubBrands,
  285. tray_color: color + 'FF', // Add alpha
  286. nozzle_temp_min: tempMin,
  287. nozzle_temp_max: tempMax,
  288. cali_idx: caliIdx,
  289. nozzle_diameter: nozzleDiameter,
  290. setting_id: selectedPresetId, // Full setting ID for slicer compatibility
  291. // Pass K profile's filament_id and setting_id for proper linking
  292. kprofile_filament_id: selectedKProfile?.filament_id,
  293. kprofile_setting_id: selectedKProfile?.setting_id || undefined,
  294. // Also pass the K value directly for extrusion_cali_set command
  295. k_value: kValue,
  296. });
  297. // Save the preset mapping so we can display the correct name in the UI
  298. // This is needed because user presets use filament_id (e.g., P285e239) as tray_info_idx,
  299. // which can't be resolved to a name via the filamentInfo API
  300. try {
  301. await api.saveSlotPreset(printerId, slotInfo.amsId, slotInfo.trayId, selectedPresetId, traySubBrands);
  302. } catch (e) {
  303. console.warn('Failed to save slot preset mapping:', e);
  304. // Don't fail the whole operation - slot was configured successfully
  305. }
  306. return result;
  307. },
  308. onSuccess: () => {
  309. setShowSuccess(true);
  310. onSuccess?.();
  311. // Close after showing success briefly
  312. setTimeout(() => {
  313. setShowSuccess(false);
  314. onClose();
  315. }, 1500);
  316. },
  317. });
  318. // Reset slot mutation
  319. const resetMutation = useMutation({
  320. mutationFn: async () => {
  321. return api.resetAmsSlot(printerId, slotInfo.amsId, slotInfo.trayId);
  322. },
  323. onSuccess: () => {
  324. setShowSuccess(true);
  325. onSuccess?.();
  326. setTimeout(() => {
  327. setShowSuccess(false);
  328. onClose();
  329. }, 1500);
  330. },
  331. });
  332. // Filter filament presets based on search
  333. const filteredPresets = useMemo(() => {
  334. if (!cloudSettings?.filament) return [];
  335. const query = searchQuery.toLowerCase();
  336. return cloudSettings.filament
  337. .filter(p => {
  338. if (!query) return true;
  339. return p.name.toLowerCase().includes(query);
  340. })
  341. .sort((a, b) => {
  342. // Sort user presets first, then alphabetically
  343. const aIsUser = isUserPreset(a.setting_id);
  344. const bIsUser = isUserPreset(b.setting_id);
  345. if (aIsUser && !bIsUser) return -1;
  346. if (!aIsUser && bIsUser) return 1;
  347. return a.name.localeCompare(b.name);
  348. });
  349. }, [cloudSettings?.filament, searchQuery]);
  350. // Get full preset name for K profile filtering (brand + material, without printer suffix)
  351. const selectedPresetInfo = useMemo(() => {
  352. if (!selectedPresetId || !cloudSettings?.filament) return null;
  353. const selectedPreset = cloudSettings.filament.find(p => p.setting_id === selectedPresetId);
  354. if (!selectedPreset) return null;
  355. // Remove printer/nozzle suffix (e.g., "@BBL X1C" or "@0.4 nozzle")
  356. let nameWithoutSuffix = selectedPreset.name.replace(/@.+$/, '').trim();
  357. // Strip leading "# " from custom preset names (user convention)
  358. if (nameWithoutSuffix.startsWith('# ')) {
  359. nameWithoutSuffix = nameWithoutSuffix.slice(2).trim();
  360. }
  361. const parsed = parsePresetName(nameWithoutSuffix);
  362. return {
  363. fullName: nameWithoutSuffix,
  364. material: parsed.material,
  365. brand: parsed.brand,
  366. };
  367. }, [selectedPresetId, cloudSettings?.filament]);
  368. // For backwards compatibility with the label
  369. const selectedMaterial = selectedPresetInfo?.fullName || '';
  370. const matchingKProfiles = useMemo(() => {
  371. if (!kprofilesData?.profiles || !selectedPresetInfo) return [];
  372. const { fullName, material, brand } = selectedPresetInfo;
  373. const upperFullName = fullName.toUpperCase();
  374. const upperMaterial = material.toUpperCase();
  375. const upperBrand = brand.toUpperCase();
  376. // Material must be at least 2 chars to avoid false positives
  377. if (!upperMaterial || upperMaterial.length < 2) return [];
  378. // Filter profiles - require brand match if brand is present in selected preset
  379. const filtered = kprofilesData.profiles.filter(p => {
  380. const profileName = p.name.toUpperCase();
  381. // If the selected preset has a brand (e.g., "Azurefilm PLA Wood"),
  382. // only show profiles that match the brand
  383. if (upperBrand) {
  384. // Must contain the brand name
  385. if (!profileName.includes(upperBrand)) {
  386. return false;
  387. }
  388. // And must contain the material type
  389. if (!profileName.includes(upperMaterial)) {
  390. return false;
  391. }
  392. return true;
  393. }
  394. // No brand in selected preset - match on full name or material
  395. // Priority 1: Exact match with full name
  396. if (profileName.includes(upperFullName)) {
  397. return true;
  398. }
  399. // Priority 2: Material type match (only when no brand specified)
  400. if (profileName.includes(upperMaterial)) {
  401. return true;
  402. }
  403. // Check for common material aliases
  404. const aliases: Record<string, string[]> = {
  405. 'NYLON': ['PA', 'PA-CF', 'PA6'],
  406. 'PA': ['NYLON'],
  407. };
  408. const materialAliases = aliases[upperMaterial] || [];
  409. for (const alias of materialAliases) {
  410. if (profileName.includes(alias)) {
  411. return true;
  412. }
  413. }
  414. return false;
  415. });
  416. // Deduplicate profiles with same name and k_value (multi-nozzle printers have duplicates)
  417. // Prefer extruder_id=1 (High Flow) profiles as they're more commonly used on H2D
  418. const seen = new Map<string, KProfile>();
  419. for (const profile of filtered) {
  420. const key = `${profile.name}|${profile.k_value}`;
  421. const existing = seen.get(key);
  422. if (!existing) {
  423. seen.set(key, profile);
  424. } else if (profile.extruder_id === 1 && existing.extruder_id === 0) {
  425. // Replace extruder_id=0 profile with extruder_id=1 (High Flow) profile
  426. seen.set(key, profile);
  427. }
  428. }
  429. return Array.from(seen.values());
  430. }, [kprofilesData?.profiles, selectedPresetInfo]);
  431. // Pre-select current profile when modal opens, reset when closes
  432. useEffect(() => {
  433. if (isOpen && cloudSettings?.filament) {
  434. // Try to pre-select current profile based on trayInfoIdx
  435. if (slotInfo.trayInfoIdx) {
  436. const currentPreset = cloudSettings.filament.find(
  437. p => p.setting_id === slotInfo.trayInfoIdx
  438. );
  439. if (currentPreset) {
  440. setSelectedPresetId(currentPreset.setting_id);
  441. }
  442. }
  443. } else if (!isOpen) {
  444. // Reset when modal closes
  445. setSelectedPresetId('');
  446. setSelectedKProfile(null);
  447. setColorHex('');
  448. setColorInput('');
  449. setSearchQuery('');
  450. setShowSuccess(false);
  451. }
  452. }, [isOpen, cloudSettings?.filament, slotInfo.trayInfoIdx]);
  453. // Auto-select best matching K profile when preset changes
  454. useEffect(() => {
  455. if (matchingKProfiles.length > 0) {
  456. // Auto-select first matching profile
  457. setSelectedKProfile(matchingKProfiles[0]);
  458. } else {
  459. setSelectedKProfile(null);
  460. }
  461. }, [selectedPresetId, matchingKProfiles]);
  462. // Escape key handler
  463. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  464. if (e.key === 'Escape') {
  465. onClose();
  466. }
  467. }, [onClose]);
  468. useEffect(() => {
  469. if (isOpen) {
  470. document.addEventListener('keydown', handleKeyDown);
  471. return () => document.removeEventListener('keydown', handleKeyDown);
  472. }
  473. }, [isOpen, handleKeyDown]);
  474. if (!isOpen) return null;
  475. const isLoading = settingsLoading || kprofilesLoading;
  476. const canSave = selectedPresetId && !configureMutation.isPending;
  477. // Get display color (custom or slot default)
  478. const displayColor = colorHex || slotInfo.trayColor?.slice(0, 6) || 'FFFFFF';
  479. return (
  480. <div className="fixed inset-0 z-50 flex items-center justify-center">
  481. {/* Backdrop */}
  482. <div
  483. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  484. onClick={onClose}
  485. />
  486. {/* Modal */}
  487. <div className="relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl">
  488. {/* Header */}
  489. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  490. <div className="flex items-center gap-2">
  491. <Settings2 className="w-5 h-5 text-bambu-blue" />
  492. <h2 className="text-lg font-semibold text-white">Configure AMS Slot</h2>
  493. </div>
  494. <button
  495. onClick={onClose}
  496. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  497. >
  498. <X className="w-5 h-5" />
  499. </button>
  500. </div>
  501. {/* Content */}
  502. <div className="p-4 space-y-4 max-h-[60vh] overflow-y-auto">
  503. {/* Success overlay */}
  504. {showSuccess && (
  505. <div className="absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl">
  506. <div className="text-center space-y-3">
  507. <CheckCircle2 className="w-16 h-16 text-bambu-green mx-auto" />
  508. <p className="text-lg font-semibold text-white">Slot Configured!</p>
  509. <p className="text-sm text-bambu-gray">{t('configureAmsSlot.settingsSentToPrinter')}</p>
  510. </div>
  511. </div>
  512. )}
  513. {/* Slot info */}
  514. <div className="p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary">
  515. <p className="text-xs text-bambu-gray mb-1">Configuring slot:</p>
  516. <div className="flex items-center gap-2">
  517. {slotInfo.trayColor && (
  518. <span
  519. className="w-4 h-4 rounded-full border border-white/20"
  520. style={{ backgroundColor: `#${slotInfo.trayColor.slice(0, 6)}` }}
  521. />
  522. )}
  523. <span className="text-white font-medium">
  524. {getAmsLabel(slotInfo.amsId, slotInfo.trayCount)} Slot {slotInfo.trayId + 1}
  525. </span>
  526. {slotInfo.traySubBrands && (
  527. <span className="text-bambu-gray">({slotInfo.traySubBrands})</span>
  528. )}
  529. </div>
  530. </div>
  531. {isLoading ? (
  532. <div className="flex justify-center py-8">
  533. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  534. </div>
  535. ) : (
  536. <>
  537. {/* Filament Profile Select */}
  538. <div>
  539. <label className="block text-sm text-bambu-gray mb-2">
  540. Filament Profile <span className="text-red-400">*</span>
  541. </label>
  542. <div className="relative">
  543. <input
  544. type="text"
  545. placeholder={t('configureAmsSlot.searchPresets')}
  546. value={searchQuery}
  547. onChange={(e) => setSearchQuery(e.target.value)}
  548. 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"
  549. />
  550. <div className="max-h-48 overflow-y-auto space-y-1">
  551. {filteredPresets.length === 0 ? (
  552. <p className="text-center py-4 text-bambu-gray">
  553. {cloudSettings?.filament?.length === 0
  554. ? 'No cloud presets. Login to Bambu Cloud to sync.'
  555. : 'No matching presets found.'}
  556. </p>
  557. ) : (
  558. filteredPresets.map((preset) => (
  559. <button
  560. key={preset.setting_id}
  561. onClick={() => setSelectedPresetId(preset.setting_id)}
  562. className={`w-full p-2 rounded-lg border text-left transition-colors ${
  563. selectedPresetId === preset.setting_id
  564. ? 'bg-bambu-green/20 border-bambu-green'
  565. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  566. }`}
  567. >
  568. <div className="flex items-center justify-between">
  569. <span className="text-white text-sm truncate">{preset.name}</span>
  570. {isUserPreset(preset.setting_id) && (
  571. <span className="text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue">
  572. {t('configureAmsSlot.custom')}
  573. </span>
  574. )}
  575. </div>
  576. </button>
  577. ))
  578. )}
  579. </div>
  580. </div>
  581. </div>
  582. {/* K Profile Select */}
  583. <div>
  584. <label className="block text-sm text-bambu-gray mb-2">
  585. K Profile (Pressure Advance)
  586. {selectedMaterial && (
  587. <span className="ml-2 text-xs text-bambu-blue">
  588. Filtering for: {selectedMaterial}
  589. </span>
  590. )}
  591. </label>
  592. {matchingKProfiles.length > 0 ? (
  593. <div className="relative">
  594. <select
  595. value={selectedKProfile?.name || ''}
  596. onChange={(e) => {
  597. const profile = matchingKProfiles.find(p => p.name === e.target.value);
  598. setSelectedKProfile(profile || null);
  599. }}
  600. 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"
  601. >
  602. <option value="">No K profile (use default 0.020)</option>
  603. {matchingKProfiles.map((profile) => (
  604. <option key={`${profile.name}-${profile.extruder_id}`} value={profile.name}>
  605. {profile.name} (K={profile.k_value})
  606. </option>
  607. ))}
  608. </select>
  609. <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  610. </div>
  611. ) : selectedPresetId ? (
  612. <p className="text-sm text-bambu-gray italic py-2">
  613. No matching K profiles found. Default K=0.020 will be used.
  614. </p>
  615. ) : (
  616. <span className="inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30">
  617. Select a filament profile first
  618. </span>
  619. )}
  620. {selectedKProfile && (
  621. <p className="text-xs text-bambu-green mt-1">
  622. K={selectedKProfile.k_value} from printer calibration
  623. </p>
  624. )}
  625. </div>
  626. {/* Optional: Custom color */}
  627. <div>
  628. <label className="block text-sm text-bambu-gray mb-2">
  629. Custom Color (optional)
  630. </label>
  631. {/* Quick color buttons */}
  632. <div className="flex flex-wrap gap-1.5 mb-2">
  633. {QUICK_COLORS_BASIC.map((color) => (
  634. <button
  635. key={color.hex}
  636. onClick={() => {
  637. setColorHex(color.hex);
  638. setColorInput(color.name);
  639. }}
  640. className={`w-7 h-7 rounded-md border-2 transition-all ${
  641. colorHex === color.hex
  642. ? 'border-bambu-green scale-110'
  643. : 'border-white/20 hover:border-white/40'
  644. }`}
  645. style={{ backgroundColor: `#${color.hex}` }}
  646. title={color.name}
  647. />
  648. ))}
  649. <button
  650. onClick={() => setShowExtendedColors(!showExtendedColors)}
  651. 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"
  652. title={showExtendedColors ? 'Show less colors' : 'Show more colors'}
  653. >
  654. {showExtendedColors ? '−' : '+'}
  655. </button>
  656. </div>
  657. {/* Extended colors (collapsible) */}
  658. {showExtendedColors && (
  659. <div className="flex flex-wrap gap-1.5 mb-2">
  660. {QUICK_COLORS_EXTENDED.map((color) => (
  661. <button
  662. key={color.hex}
  663. onClick={() => {
  664. setColorHex(color.hex);
  665. setColorInput(color.name);
  666. }}
  667. className={`w-7 h-7 rounded-md border-2 transition-all ${
  668. colorHex === color.hex
  669. ? 'border-bambu-green scale-110'
  670. : 'border-white/20 hover:border-white/40'
  671. }`}
  672. style={{ backgroundColor: `#${color.hex}` }}
  673. title={color.name}
  674. />
  675. ))}
  676. </div>
  677. )}
  678. {/* Color input: name or hex */}
  679. <div className="flex gap-2 items-center">
  680. <div
  681. className="w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0"
  682. style={{ backgroundColor: `#${displayColor}` }}
  683. />
  684. <input
  685. type="text"
  686. placeholder={t('configureAmsSlot.colorPlaceholder')}
  687. value={colorInput}
  688. onChange={(e) => {
  689. const input = e.target.value;
  690. setColorInput(input);
  691. // Try to parse as color name first
  692. const nameHex = colorNameToHex(input);
  693. if (nameHex) {
  694. setColorHex(nameHex);
  695. } else {
  696. // Try to parse as hex code
  697. const cleaned = input.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
  698. if (cleaned.length === 6) {
  699. setColorHex(cleaned);
  700. } else if (cleaned.length === 3) {
  701. // Expand shorthand hex (e.g., F00 -> FF0000)
  702. setColorHex(cleaned.split('').map(c => c + c).join(''));
  703. }
  704. }
  705. }}
  706. 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"
  707. />
  708. {colorHex && (
  709. <button
  710. onClick={() => {
  711. setColorHex('');
  712. setColorInput('');
  713. }}
  714. className="px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded"
  715. title={t('configureAmsSlot.clearCustomColor')}
  716. >
  717. Clear
  718. </button>
  719. )}
  720. </div>
  721. {colorHex && (
  722. <p className="text-xs text-bambu-gray mt-1.5">
  723. Hex: #{colorHex}
  724. </p>
  725. )}
  726. </div>
  727. </>
  728. )}
  729. </div>
  730. {/* Footer */}
  731. <div className="flex justify-between p-4 border-t border-bambu-dark-tertiary">
  732. {/* Reset button on the left */}
  733. <Button
  734. variant="secondary"
  735. onClick={() => resetMutation.mutate()}
  736. disabled={resetMutation.isPending || configureMutation.isPending}
  737. className="text-red-400 hover:text-red-300 hover:bg-red-500/10"
  738. >
  739. {resetMutation.isPending ? (
  740. <>
  741. <Loader2 className="w-4 h-4 animate-spin" />
  742. Resetting...
  743. </>
  744. ) : (
  745. <>
  746. <RotateCcw className="w-4 h-4" />
  747. Reset Slot
  748. </>
  749. )}
  750. </Button>
  751. {/* Cancel and Configure buttons on the right */}
  752. <div className="flex gap-2">
  753. <Button variant="secondary" onClick={onClose}>
  754. Cancel
  755. </Button>
  756. <Button
  757. onClick={() => configureMutation.mutate()}
  758. disabled={!canSave}
  759. >
  760. {configureMutation.isPending ? (
  761. <>
  762. <Loader2 className="w-4 h-4 animate-spin" />
  763. Configuring...
  764. </>
  765. ) : (
  766. <>
  767. <Settings2 className="w-4 h-4" />
  768. Configure Slot
  769. </>
  770. )}
  771. </Button>
  772. </div>
  773. </div>
  774. {/* Error */}
  775. {(configureMutation.isError || resetMutation.isError) && (
  776. <div className="mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400">
  777. {(configureMutation.error as Error)?.message || (resetMutation.error as Error)?.message}
  778. </div>
  779. )}
  780. </div>
  781. </div>
  782. );
  783. }