FileManagerModal.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. import { useEffect, useMemo, useRef, useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import {
  5. X,
  6. Folder,
  7. File,
  8. ChevronLeft,
  9. Download,
  10. Trash2,
  11. Loader2,
  12. HardDrive,
  13. RefreshCw,
  14. Film,
  15. FileBox,
  16. FileText,
  17. Image,
  18. Search,
  19. ArrowUpDown,
  20. CheckSquare,
  21. Square,
  22. MinusSquare,
  23. Box,
  24. } from 'lucide-react';
  25. import { api } from '../api/client';
  26. import { parseUTCDate } from '../utils/date';
  27. import { Button } from './Button';
  28. import { ConfirmModal } from './ConfirmModal';
  29. import { ModelViewer } from './ModelViewer';
  30. import { GcodeToolpathViewer } from './GcodeToolpathViewer';
  31. import type { PlateMetadata } from '../types/plates';
  32. import { useToast } from '../contexts/ToastContext';
  33. import { formatFileSize } from '../utils/file';
  34. interface FileManagerModalProps {
  35. printerId: number;
  36. printerName: string;
  37. onClose: () => void;
  38. }
  39. type PrinterViewerTab = '3d' | 'gcode';
  40. interface PrinterFileViewerModalProps {
  41. printerId: number;
  42. filePath: string;
  43. filename: string;
  44. onClose: () => void;
  45. }
  46. function PrinterFileViewerModal({ printerId, filePath, filename, onClose }: PrinterFileViewerModalProps) {
  47. const [activeTab, setActiveTab] = useState<PrinterViewerTab | null>(null);
  48. const [plates, setPlates] = useState<PlateMetadata[]>([]);
  49. const [platesLoading, setPlatesLoading] = useState(false);
  50. const [selectedPlateId, setSelectedPlateId] = useState<number | null>(null);
  51. const ext = filename.toLowerCase().split('.').pop() || '';
  52. const hasModel = ext === '3mf' || ext === 'stl';
  53. const hasGcode = ext === 'gcode' || ext === '3mf';
  54. useEffect(() => {
  55. setActiveTab(hasModel ? '3d' : hasGcode ? 'gcode' : null);
  56. }, [hasModel, hasGcode]);
  57. useEffect(() => {
  58. setPlates([]);
  59. setSelectedPlateId(null);
  60. if (!hasModel) return;
  61. setPlatesLoading(true);
  62. api.getPrinterFilePlates(printerId, filePath)
  63. .then((data) => setPlates(data.plates || []))
  64. .catch(() => setPlates([]))
  65. .finally(() => setPlatesLoading(false));
  66. }, [filePath, hasModel, printerId]);
  67. const hasMultiplePlates = plates.length > 1;
  68. const selectedPlate = selectedPlateId == null
  69. ? null
  70. : plates.find((plate) => plate.index === selectedPlateId) ?? null;
  71. return (
  72. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6" onClick={onClose}>
  73. <div
  74. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col"
  75. onClick={(e) => e.stopPropagation()}
  76. >
  77. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  78. <h2 className="text-lg font-semibold text-white truncate flex-1 mr-4">{filename}</h2>
  79. <Button variant="ghost" size="sm" onClick={onClose}>
  80. <X className="w-5 h-5" />
  81. </Button>
  82. </div>
  83. <div className="flex border-b border-bambu-dark-tertiary">
  84. <button
  85. onClick={() => hasModel && setActiveTab('3d')}
  86. disabled={!hasModel}
  87. className={`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${
  88. activeTab === '3d'
  89. ? 'text-bambu-green border-b-2 border-bambu-green'
  90. : hasModel
  91. ? 'text-bambu-gray hover:text-white'
  92. : 'text-bambu-gray/30 cursor-not-allowed'
  93. }`}
  94. >
  95. <Box className="w-4 h-4" />
  96. 3D Model
  97. {!hasModel && <span className="text-xs">(not available)</span>}
  98. </button>
  99. <button
  100. onClick={() => hasGcode && setActiveTab('gcode')}
  101. disabled={!hasGcode}
  102. className={`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${
  103. activeTab === 'gcode'
  104. ? 'text-bambu-green border-b-2 border-bambu-green'
  105. : hasGcode
  106. ? 'text-bambu-gray hover:text-white'
  107. : 'text-bambu-gray/30 cursor-not-allowed'
  108. }`}
  109. >
  110. <FileText className="w-4 h-4" />
  111. G-code Preview
  112. {!hasGcode && <span className="text-xs">(not sliced)</span>}
  113. </button>
  114. </div>
  115. <div className="flex-1 overflow-hidden p-4">
  116. {activeTab === '3d' && hasModel ? (
  117. <div className="w-full h-full flex flex-col gap-3">
  118. {hasMultiplePlates && (
  119. <div className="rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3">
  120. <div className="flex items-center gap-2 text-sm text-bambu-gray mb-2">
  121. <Box className="w-4 h-4" />
  122. Plates
  123. {platesLoading && <Loader2 className="w-3 h-3 animate-spin" />}
  124. </div>
  125. <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
  126. <button
  127. type="button"
  128. onClick={() => setSelectedPlateId(null)}
  129. className={`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${
  130. selectedPlateId == null
  131. ? 'border-bambu-green bg-bambu-green/10'
  132. : 'border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray'
  133. }`}
  134. >
  135. <div className="w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center">
  136. <Box className="w-5 h-5 text-bambu-gray" />
  137. </div>
  138. <div className="min-w-0 flex-1">
  139. <p className="text-sm text-white font-medium truncate">All Plates</p>
  140. <p className="text-xs text-bambu-gray truncate">
  141. {plates.length} plate{plates.length !== 1 ? 's' : ''}
  142. </p>
  143. </div>
  144. {selectedPlateId == null && (
  145. <CheckSquare className="w-4 h-4 text-bambu-green flex-shrink-0" />
  146. )}
  147. </button>
  148. {plates.map((plate) => (
  149. <button
  150. key={plate.index}
  151. type="button"
  152. onClick={() => setSelectedPlateId(plate.index)}
  153. className={`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${
  154. selectedPlateId === plate.index
  155. ? 'border-bambu-green bg-bambu-green/10'
  156. : 'border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray'
  157. }`}
  158. >
  159. {plate.has_thumbnail ? (
  160. <img
  161. src={api.getPrinterFilePlateThumbnail(printerId, plate.index, filePath)}
  162. alt={`Plate ${plate.index}`}
  163. className="w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"
  164. />
  165. ) : (
  166. <div className="w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center">
  167. <Box className="w-5 h-5 text-bambu-gray" />
  168. </div>
  169. )}
  170. <div className="min-w-0 flex-1">
  171. <p className="text-sm text-white font-medium truncate">
  172. {plate.name || `Plate ${plate.index}`}
  173. </p>
  174. <p className="text-xs text-bambu-gray truncate">
  175. {plate.objects.length > 0
  176. ? plate.objects.slice(0, 2).join(', ') + (plate.objects.length > 2 ? '…' : '')
  177. : `${plate.filaments.length} filament${plate.filaments.length !== 1 ? 's' : ''}`}
  178. </p>
  179. </div>
  180. {selectedPlateId === plate.index && (
  181. <CheckSquare className="w-4 h-4 text-bambu-green flex-shrink-0" />
  182. )}
  183. </button>
  184. ))}
  185. </div>
  186. {selectedPlate && (
  187. <div className="mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1">
  188. <span>Plate {selectedPlate.index}</span>
  189. {selectedPlate.print_time_seconds != null && (
  190. <span>ETA {Math.round(selectedPlate.print_time_seconds / 60)} min</span>
  191. )}
  192. {selectedPlate.filament_used_grams != null && (
  193. <span>{selectedPlate.filament_used_grams.toFixed(1)} g</span>
  194. )}
  195. {selectedPlate.filaments.length > 0 && (
  196. <span>{selectedPlate.filaments.length} filament{selectedPlate.filaments.length !== 1 ? 's' : ''}</span>
  197. )}
  198. </div>
  199. )}
  200. </div>
  201. )}
  202. <div className="flex-1">
  203. <ModelViewer
  204. url={api.getPrinterFileDownloadUrl(printerId, filePath)}
  205. fileType={ext}
  206. selectedPlateId={selectedPlateId}
  207. className="w-full h-full"
  208. />
  209. </div>
  210. </div>
  211. ) : activeTab === 'gcode' && hasGcode ? (
  212. <GcodeToolpathViewer
  213. gcodeUrl={api.getPrinterFileGcodeUrl(printerId, filePath)}
  214. className="w-full h-full"
  215. />
  216. ) : (
  217. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  218. No preview available for this file
  219. </div>
  220. )}
  221. </div>
  222. </div>
  223. </div>
  224. );
  225. }
  226. function formatStorageSize(bytes: number): string {
  227. if (bytes === 0) return '0 GB';
  228. const gb = bytes / (1024 * 1024 * 1024);
  229. if (gb >= 1) {
  230. return `${gb.toFixed(1)} GB`;
  231. }
  232. const mb = bytes / (1024 * 1024);
  233. return `${mb.toFixed(0)} MB`;
  234. }
  235. function getFileIcon(filename: string, isDirectory: boolean) {
  236. if (isDirectory) return Folder;
  237. const ext = filename.toLowerCase().split('.').pop() || '';
  238. switch (ext) {
  239. case '3mf':
  240. return FileBox;
  241. case 'gcode':
  242. return FileText;
  243. case 'mp4':
  244. case 'avi':
  245. return Film;
  246. case 'png':
  247. case 'jpg':
  248. case 'jpeg':
  249. return Image;
  250. default:
  251. return File;
  252. }
  253. }
  254. type SortOption = 'name-asc' | 'name-desc' | 'size-asc' | 'size-desc' | 'date-asc' | 'date-desc';
  255. const SORT_OPTIONS: { value: SortOption; label: string }[] = [
  256. { value: 'name-asc', label: 'Name (A-Z)' },
  257. { value: 'name-desc', label: 'Name (Z-A)' },
  258. { value: 'size-asc', label: 'Size (smallest)' },
  259. { value: 'size-desc', label: 'Size (largest)' },
  260. { value: 'date-asc', label: 'Date (oldest)' },
  261. { value: 'date-desc', label: 'Date (newest)' },
  262. ];
  263. export function FileManagerModal({ printerId, printerName, onClose }: FileManagerModalProps) {
  264. const { t } = useTranslation();
  265. const { showToast } = useToast();
  266. const queryClient = useQueryClient();
  267. const [currentPath, setCurrentPath] = useState('/');
  268. const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());
  269. const [searchQuery, setSearchQuery] = useState('');
  270. const [filesToDelete, setFilesToDelete] = useState<string[]>([]);
  271. const [sortBy, setSortBy] = useState<SortOption>('name-asc');
  272. const [downloadProgress, setDownloadProgress] = useState<{ current: number; total: number } | null>(null);
  273. const [viewerFile, setViewerFile] = useState<{ path: string; name: string } | null>(null);
  274. const selectionAnchorRef = useRef<string | null>(null);
  275. const downloadAbortRef = useRef<AbortController | null>(null);
  276. // Close on Escape key
  277. useEffect(() => {
  278. const handleKeyDown = (e: KeyboardEvent) => {
  279. if (e.key === 'Escape') onClose();
  280. };
  281. window.addEventListener('keydown', handleKeyDown);
  282. return () => window.removeEventListener('keydown', handleKeyDown);
  283. }, [onClose]);
  284. // No auto-poll: every refetch opens a fresh FTPS connection (TLS handshake
  285. // and all) to the printer, and a 30s interval saturated fragile printer
  286. // controllers like the P1S — MQTT, FTP and the camera all timed out
  287. // together while this modal sat open (#1480). A printer's file list only
  288. // changes on upload / delete (the mutations below invalidate the query)
  289. // or when a print finishes; the manual Refresh button covers the rest.
  290. const { data, isLoading, refetch } = useQuery({
  291. queryKey: ['printerFiles', printerId, currentPath],
  292. queryFn: () => api.getPrinterFiles(printerId, currentPath),
  293. });
  294. const { data: storageData } = useQuery({
  295. queryKey: ['printerStorage', printerId],
  296. queryFn: () => api.getPrinterStorage(printerId),
  297. staleTime: 30000, // Cache for 30 seconds
  298. });
  299. const visibleFiles = useMemo(() => [...(data?.files ?? [])]
  300. .filter((file) => !searchQuery || file.name.toLowerCase().includes(searchQuery.toLowerCase()))
  301. .sort((a, b) => {
  302. if (a.is_directory && !b.is_directory) return -1;
  303. if (!a.is_directory && b.is_directory) return 1;
  304. switch (sortBy) {
  305. case 'name-asc':
  306. return a.name.localeCompare(b.name);
  307. case 'name-desc':
  308. return b.name.localeCompare(a.name);
  309. case 'size-asc':
  310. return a.size - b.size;
  311. case 'size-desc':
  312. return b.size - a.size;
  313. case 'date-asc': {
  314. const aTime = a.mtime ? parseUTCDate(a.mtime)?.getTime() ?? 0 : 0;
  315. const bTime = b.mtime ? parseUTCDate(b.mtime)?.getTime() ?? 0 : 0;
  316. return aTime - bTime;
  317. }
  318. case 'date-desc': {
  319. const aTime = a.mtime ? parseUTCDate(a.mtime)?.getTime() ?? 0 : 0;
  320. const bTime = b.mtime ? parseUTCDate(b.mtime)?.getTime() ?? 0 : 0;
  321. return bTime - aTime;
  322. }
  323. default:
  324. return a.name.localeCompare(b.name);
  325. }
  326. }), [data?.files, searchQuery, sortBy]);
  327. // Drop selections the user can no longer see -- but only when the listing is
  328. // real. An unreachable printer answers with an empty file list and a warning,
  329. // and treating that as "those files are gone" would throw away a selection
  330. // the user made moments ago because one poll happened to fail.
  331. const listingIsReal = !!data && !data.warnings?.includes('printer_unavailable');
  332. useEffect(() => {
  333. if (!listingIsReal) return;
  334. const visiblePaths = new Set(visibleFiles.filter(file => !file.is_directory).map(file => file.path));
  335. setSelectedFiles(current => new Set([...current].filter(path => visiblePaths.has(path))));
  336. if (selectionAnchorRef.current && !visiblePaths.has(selectionAnchorRef.current)) {
  337. selectionAnchorRef.current = null;
  338. }
  339. }, [visibleFiles, listingIsReal]);
  340. useEffect(() => () => downloadAbortRef.current?.abort(), []);
  341. const deleteMutation = useMutation({
  342. mutationFn: async (paths: string[]) => {
  343. // Delete files one by one
  344. for (const path of paths) {
  345. await api.deletePrinterFile(printerId, path);
  346. }
  347. },
  348. onSuccess: () => {
  349. showToast(t('printerFiles.toast.filesDeleted', { count: filesToDelete.length }));
  350. queryClient.invalidateQueries({ queryKey: ['printerFiles', printerId] });
  351. setSelectedFiles(new Set());
  352. selectionAnchorRef.current = null;
  353. setFilesToDelete([]);
  354. },
  355. onError: (error: Error) => {
  356. showToast(t('printerFiles.toast.deleteFailed', { error: error.message }), 'error');
  357. },
  358. });
  359. const navigateToFolder = (path: string) => {
  360. setCurrentPath(path);
  361. setSelectedFiles(new Set());
  362. selectionAnchorRef.current = null;
  363. };
  364. const navigateUp = () => {
  365. if (currentPath === '/') return;
  366. const parts = currentPath.split('/').filter(Boolean);
  367. parts.pop();
  368. setCurrentPath(parts.length ? '/' + parts.join('/') : '/');
  369. setSelectedFiles(new Set());
  370. selectionAnchorRef.current = null;
  371. };
  372. const toggleFileSelection = (path: string, e: React.MouseEvent) => {
  373. e.stopPropagation();
  374. const selectablePaths = visibleFiles.filter(file => !file.is_directory).map(file => file.path);
  375. const anchorIndex = selectionAnchorRef.current
  376. ? selectablePaths.indexOf(selectionAnchorRef.current)
  377. : -1;
  378. const targetIndex = selectablePaths.indexOf(path);
  379. const extendsRange = e.shiftKey && anchorIndex !== -1 && targetIndex !== -1;
  380. // Moved out of the state updater deliberately: React may run an updater
  381. // more than once, and a ref assignment is not the kind of thing that
  382. // survives being replayed by accident.
  383. if (!extendsRange) selectionAnchorRef.current = path;
  384. setSelectedFiles(prev => {
  385. const next = new Set(prev);
  386. if (extendsRange) {
  387. const start = Math.min(anchorIndex, targetIndex);
  388. const end = Math.max(anchorIndex, targetIndex);
  389. selectablePaths.slice(start, end + 1).forEach(rangePath => next.add(rangePath));
  390. } else if (next.has(path)) {
  391. next.delete(path);
  392. } else {
  393. next.add(path);
  394. }
  395. return next;
  396. });
  397. };
  398. const selectAllFiles = () => {
  399. const filePaths = visibleFiles.filter(file => !file.is_directory).map(file => file.path);
  400. setSelectedFiles(new Set(filePaths));
  401. selectionAnchorRef.current = null;
  402. };
  403. const deselectAllFiles = () => {
  404. setSelectedFiles(new Set());
  405. selectionAnchorRef.current = null;
  406. };
  407. const handleDownload = async () => {
  408. if (selectedFiles.size === 0) return;
  409. const paths = visibleFiles.filter(file => !file.is_directory && selectedFiles.has(file.path)).map(file => file.path);
  410. if (paths.length === 0) return;
  411. const controller = new AbortController();
  412. downloadAbortRef.current = controller;
  413. setDownloadProgress({ current: 0, total: paths.length });
  414. try {
  415. const sizes = Object.fromEntries(paths.map(path => [
  416. path,
  417. data?.files.find(file => file.path === path)?.size ?? 0,
  418. ]));
  419. const result = await api.downloadPrinterFilesAsZip(
  420. printerId,
  421. paths,
  422. sizes,
  423. paths.length === 1
  424. ? data?.files.find(file => file.path === paths[0])?.name ?? 'printer-file'
  425. : `${printerName.replace(/[^a-zA-Z0-9]/g, '_')}-files.zip`,
  426. paths.length > 1,
  427. controller.signal,
  428. (completed, total) => setDownloadProgress({ current: completed, total }),
  429. );
  430. if (result.failed > 0) {
  431. showToast(t('printerFiles.zipPartial', {
  432. successful: result.successful,
  433. total: result.requested,
  434. }), 'warning');
  435. } else {
  436. showToast(t('printerFiles.zipStarted', { count: result.successful }));
  437. }
  438. setSelectedFiles(new Set());
  439. selectionAnchorRef.current = null;
  440. } catch (error) {
  441. showToast(t('printerFiles.downloadFailed', {
  442. error: error instanceof Error ? error.message : t('printerFiles.unknownError'),
  443. }), 'error');
  444. } finally {
  445. if (downloadAbortRef.current === controller) downloadAbortRef.current = null;
  446. setDownloadProgress(null);
  447. }
  448. };
  449. const handleDelete = () => {
  450. if (selectedFiles.size === 0) return;
  451. setFilesToDelete(
  452. visibleFiles.filter(file => !file.is_directory && selectedFiles.has(file.path)).map(file => file.path),
  453. );
  454. };
  455. // Quick navigation buttons for common directories
  456. const quickDirs = [
  457. { path: '/', label: 'Root' },
  458. { path: '/cache', label: 'Cache' },
  459. { path: '/model', label: 'Models' },
  460. { path: '/timelapse', label: 'Timelapse' },
  461. ];
  462. return (
  463. <div
  464. className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
  465. onClick={onClose}
  466. >
  467. <div
  468. className="w-full max-w-3xl max-h-[85vh] flex flex-col bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden"
  469. onClick={(e) => e.stopPropagation()}
  470. >
  471. {/* Header */}
  472. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0">
  473. <div className="flex items-center gap-3">
  474. <HardDrive className="w-5 h-5 text-bambu-green" />
  475. <div>
  476. <h2 className="text-lg font-semibold text-white">{t('printerFiles.title')}</h2>
  477. <p className="text-sm text-bambu-gray">{printerName}</p>
  478. </div>
  479. </div>
  480. <div className="flex items-center gap-4">
  481. {/* Storage info */}
  482. {storageData && (storageData.used_bytes != null || storageData.free_bytes != null) && (
  483. <div className="text-sm text-bambu-gray flex items-center gap-2">
  484. {storageData.used_bytes != null && (
  485. <span>{t('printerFiles.storageUsed')} {formatStorageSize(storageData.used_bytes)}</span>
  486. )}
  487. {storageData.used_bytes != null && storageData.free_bytes != null && (
  488. <span className="text-bambu-dark-tertiary">|</span>
  489. )}
  490. {storageData.free_bytes != null && (
  491. <span>{t('printerFiles.storageFree')} {formatStorageSize(storageData.free_bytes)}</span>
  492. )}
  493. </div>
  494. )}
  495. <button
  496. onClick={onClose}
  497. className="text-bambu-gray hover:text-white transition-colors"
  498. title="Close file manager"
  499. aria-label="Close file manager"
  500. >
  501. <X className="w-5 h-5" />
  502. </button>
  503. </div>
  504. </div>
  505. {/* Quick Navigation */}
  506. <div className="flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0">
  507. {quickDirs.map((dir) => (
  508. <button
  509. key={dir.path}
  510. onClick={() => {
  511. navigateToFolder(dir.path);
  512. setSearchQuery('');
  513. }}
  514. className={`px-3 py-1 text-sm rounded-full transition-colors ${
  515. currentPath === dir.path
  516. ? 'bg-bambu-green text-white'
  517. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  518. }`}
  519. >
  520. {dir.label}
  521. </button>
  522. ))}
  523. <div className="flex-1" />
  524. <div className="relative">
  525. <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  526. <input
  527. type="text"
  528. placeholder={t('printerFiles.filterPlaceholder')}
  529. value={searchQuery}
  530. onChange={(e) => setSearchQuery(e.target.value)}
  531. className="w-40 pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  532. />
  533. </div>
  534. <div className="relative flex items-center gap-1">
  535. <ArrowUpDown className="w-4 h-4 text-bambu-gray" />
  536. <select
  537. value={sortBy}
  538. onChange={(e) => setSortBy(e.target.value as SortOption)}
  539. className="appearance-none bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm py-1.5 pl-2 pr-6 focus:border-bambu-green focus:outline-none cursor-pointer"
  540. title="Sort files"
  541. aria-label="Sort files"
  542. >
  543. {SORT_OPTIONS.map((option) => (
  544. <option key={option.value} value={option.value}>
  545. {option.label}
  546. </option>
  547. ))}
  548. </select>
  549. </div>
  550. <Button
  551. variant="secondary"
  552. size="sm"
  553. onClick={() => refetch()}
  554. disabled={isLoading}
  555. aria-label={t('common.refresh')}
  556. title={t('common.refresh')}
  557. >
  558. <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
  559. </Button>
  560. </div>
  561. {/* Path breadcrumb */}
  562. <div className="flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0">
  563. <button
  564. onClick={navigateUp}
  565. disabled={currentPath === '/'}
  566. className="p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed"
  567. title="Go to parent folder"
  568. aria-label="Go to parent folder"
  569. >
  570. <ChevronLeft className="w-4 h-4" />
  571. </button>
  572. <span className="text-bambu-gray font-mono">{currentPath}</span>
  573. </div>
  574. {/* File list */}
  575. <div className="flex-1 overflow-y-auto p-2 min-h-0">
  576. {isLoading ? (
  577. <div className="flex items-center justify-center py-12">
  578. <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
  579. </div>
  580. ) : data?.warnings?.includes('printer_unavailable') ? (
  581. <div className="text-center py-12 text-amber-600 dark:text-amber-400">
  582. {t('printerFiles.printerUnavailable')}
  583. </div>
  584. ) : !data?.files?.length ? (
  585. <div className="text-center py-12 text-bambu-gray">
  586. {t('printerFiles.noFiles')}
  587. </div>
  588. ) : (
  589. <div className="space-y-1">
  590. {visibleFiles.map((file) => {
  591. const FileIcon = getFileIcon(file.name, file.is_directory);
  592. const isSelected = selectedFiles.has(file.path);
  593. return (
  594. <div
  595. key={file.path}
  596. className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${
  597. isSelected
  598. ? 'bg-bambu-green/20 border border-bambu-green/50'
  599. : 'hover:bg-bambu-dark-tertiary'
  600. }`}
  601. onClick={(event) => {
  602. if (file.is_directory) {
  603. navigateToFolder(file.path);
  604. } else {
  605. toggleFileSelection(file.path, event);
  606. }
  607. }}
  608. >
  609. {/* Checkbox for files only */}
  610. {!file.is_directory ? (
  611. <button
  612. onClick={(e) => toggleFileSelection(file.path, e)}
  613. className="flex-shrink-0 text-bambu-gray hover:text-white"
  614. aria-label={t(isSelected ? 'printerFiles.deselectFile' : 'printerFiles.selectFile', {
  615. name: file.name,
  616. })}
  617. title={t('printerFiles.shiftSelectHint')}
  618. >
  619. {isSelected ? (
  620. <CheckSquare className="w-5 h-5 text-bambu-green" />
  621. ) : (
  622. <Square className="w-5 h-5" />
  623. )}
  624. </button>
  625. ) : null}
  626. <FileIcon
  627. className={`w-5 h-5 flex-shrink-0 ${
  628. file.is_directory ? 'text-bambu-green' : 'text-bambu-gray'
  629. }`}
  630. />
  631. <span className="flex-1 text-white truncate">{file.name}</span>
  632. {!file.is_directory && (
  633. <div className="flex items-center gap-3">
  634. <span className="text-sm text-bambu-gray">
  635. {formatFileSize(file.size)}
  636. </span>
  637. {(file.name.toLowerCase().endsWith('.3mf') || file.name.toLowerCase().endsWith('.gcode') || file.name.toLowerCase().endsWith('.stl')) && (
  638. <button
  639. onClick={(e) => {
  640. e.stopPropagation();
  641. setViewerFile({ path: file.path, name: file.name });
  642. }}
  643. className="p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green"
  644. title="3D View"
  645. >
  646. <Box className="w-4 h-4" />
  647. </button>
  648. )}
  649. </div>
  650. )}
  651. {file.is_directory && (
  652. <ChevronLeft className="w-4 h-4 text-bambu-gray rotate-180" />
  653. )}
  654. </div>
  655. );
  656. })}
  657. </div>
  658. )}
  659. </div>
  660. {/* Action bar */}
  661. <div className="flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0">
  662. <div className="flex items-center gap-4">
  663. <div className="text-sm text-bambu-gray">
  664. {selectedFiles.size > 0
  665. ? `${selectedFiles.size} selected`
  666. : searchQuery
  667. ? `${data?.files?.filter(f => f.name.toLowerCase().includes(searchQuery.toLowerCase())).length || 0} of ${data?.files?.length || 0} items`
  668. : `${data?.files?.length || 0} items`
  669. }
  670. </div>
  671. {/* Select All / Deselect All */}
  672. {data?.files?.some(f => !f.is_directory) && (
  673. <div className="flex items-center gap-2">
  674. {selectedFiles.size > 0 ? (
  675. <button
  676. onClick={deselectAllFiles}
  677. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  678. >
  679. <MinusSquare className="w-4 h-4" />
  680. Deselect All
  681. </button>
  682. ) : (
  683. <button
  684. onClick={selectAllFiles}
  685. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  686. >
  687. <CheckSquare className="w-4 h-4" />
  688. Select All
  689. </button>
  690. )}
  691. </div>
  692. )}
  693. </div>
  694. <div className="flex gap-2">
  695. <Button
  696. variant="secondary"
  697. disabled={selectedFiles.size === 0 || downloadProgress !== null}
  698. onClick={handleDownload}
  699. >
  700. {downloadProgress ? (
  701. <>
  702. <Loader2 className="w-4 h-4 animate-spin" />
  703. {downloadProgress.current}/{downloadProgress.total}
  704. </>
  705. ) : (
  706. <>
  707. <Download className="w-4 h-4" />
  708. Download{selectedFiles.size > 1 ? ` (${selectedFiles.size})` : ''}
  709. </>
  710. )}
  711. </Button>
  712. <Button
  713. variant="secondary"
  714. disabled={selectedFiles.size === 0 || deleteMutation.isPending}
  715. onClick={handleDelete}
  716. className="text-red-700 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"
  717. >
  718. {deleteMutation.isPending ? (
  719. <Loader2 className="w-4 h-4 animate-spin" />
  720. ) : (
  721. <Trash2 className="w-4 h-4" />
  722. )}
  723. {t('printerFiles.deleteButton')}{selectedFiles.size > 1 ? ` (${selectedFiles.size})` : ''}
  724. </Button>
  725. </div>
  726. </div>
  727. </div>
  728. {/* Delete Confirmation Modal */}
  729. {filesToDelete.length > 0 && (
  730. <ConfirmModal
  731. title={filesToDelete.length > 1 ? t('printerFiles.deleteFiles', { count: filesToDelete.length }) : t('fileManager.deleteFile')}
  732. message={
  733. filesToDelete.length > 1
  734. ? t('printerFiles.deleteFilesConfirm', { count: filesToDelete.length })
  735. : t('printerFiles.deleteFileConfirm', { name: filesToDelete[0].split('/').pop() })
  736. }
  737. confirmText={t('common.delete')}
  738. variant="danger"
  739. onConfirm={() => {
  740. deleteMutation.mutate(filesToDelete);
  741. }}
  742. onCancel={() => setFilesToDelete([])}
  743. />
  744. )}
  745. {viewerFile && (
  746. <PrinterFileViewerModal
  747. printerId={printerId}
  748. filePath={viewerFile.path}
  749. filename={viewerFile.name}
  750. onClose={() => setViewerFile(null)}
  751. />
  752. )}
  753. </div>
  754. );
  755. }