ConfigureAmsSlotModal.tsx 32 KB

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