FileManagerModal.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. import { useState, useEffect } 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 { GcodeViewer } from './GcodeViewer';
  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. <GcodeViewer
  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. // Close on Escape key
  275. useEffect(() => {
  276. const handleKeyDown = (e: KeyboardEvent) => {
  277. if (e.key === 'Escape') onClose();
  278. };
  279. window.addEventListener('keydown', handleKeyDown);
  280. return () => window.removeEventListener('keydown', handleKeyDown);
  281. }, [onClose]);
  282. const { data, isLoading, refetch } = useQuery({
  283. queryKey: ['printerFiles', printerId, currentPath],
  284. queryFn: () => api.getPrinterFiles(printerId, currentPath),
  285. });
  286. const { data: storageData } = useQuery({
  287. queryKey: ['printerStorage', printerId],
  288. queryFn: () => api.getPrinterStorage(printerId),
  289. staleTime: 30000, // Cache for 30 seconds
  290. });
  291. const deleteMutation = useMutation({
  292. mutationFn: async (paths: string[]) => {
  293. // Delete files one by one
  294. for (const path of paths) {
  295. await api.deletePrinterFile(printerId, path);
  296. }
  297. },
  298. onSuccess: () => {
  299. showToast(t('printerFiles.toast.filesDeleted', { count: filesToDelete.length }));
  300. queryClient.invalidateQueries({ queryKey: ['printerFiles', printerId] });
  301. setSelectedFiles(new Set());
  302. setFilesToDelete([]);
  303. },
  304. onError: (error: Error) => {
  305. showToast(t('printerFiles.toast.deleteFailed', { error: error.message }), 'error');
  306. },
  307. });
  308. const navigateToFolder = (path: string) => {
  309. setCurrentPath(path);
  310. setSelectedFiles(new Set());
  311. };
  312. const navigateUp = () => {
  313. if (currentPath === '/') return;
  314. const parts = currentPath.split('/').filter(Boolean);
  315. parts.pop();
  316. setCurrentPath(parts.length ? '/' + parts.join('/') : '/');
  317. setSelectedFiles(new Set());
  318. };
  319. const toggleFileSelection = (path: string, e: React.MouseEvent) => {
  320. e.stopPropagation();
  321. setSelectedFiles(prev => {
  322. const next = new Set(prev);
  323. if (next.has(path)) {
  324. next.delete(path);
  325. } else {
  326. next.add(path);
  327. }
  328. return next;
  329. });
  330. };
  331. const selectAllFiles = () => {
  332. if (!data?.files) return;
  333. const filePaths = data.files
  334. .filter(f => !f.is_directory && (!searchQuery || f.name.toLowerCase().includes(searchQuery.toLowerCase())))
  335. .map(f => f.path);
  336. setSelectedFiles(new Set(filePaths));
  337. };
  338. const deselectAllFiles = () => {
  339. setSelectedFiles(new Set());
  340. };
  341. const handleDownload = async () => {
  342. if (selectedFiles.size === 0) return;
  343. const paths = Array.from(selectedFiles);
  344. if (paths.length === 1) {
  345. // Single file - direct download with auth
  346. api.downloadPrinterFile(printerId, paths[0]).catch((err) => {
  347. console.error('Printer file download failed:', err);
  348. });
  349. setSelectedFiles(new Set());
  350. return;
  351. }
  352. // Multiple files - download as ZIP
  353. setDownloadProgress({ current: 0, total: paths.length });
  354. try {
  355. const blob = await api.downloadPrinterFilesAsZip(printerId, paths);
  356. const url = URL.createObjectURL(blob);
  357. const a = document.createElement('a');
  358. a.href = url;
  359. a.download = `${printerName.replace(/[^a-zA-Z0-9]/g, '_')}-files.zip`;
  360. document.body.appendChild(a);
  361. a.click();
  362. document.body.removeChild(a);
  363. URL.revokeObjectURL(url);
  364. showToast(`Downloaded ${paths.length} files as ZIP`);
  365. setSelectedFiles(new Set());
  366. } catch (error) {
  367. showToast(`Download failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
  368. } finally {
  369. setDownloadProgress(null);
  370. }
  371. };
  372. const handleDelete = () => {
  373. if (selectedFiles.size === 0) return;
  374. setFilesToDelete(Array.from(selectedFiles));
  375. };
  376. // Quick navigation buttons for common directories
  377. const quickDirs = [
  378. { path: '/', label: 'Root' },
  379. { path: '/cache', label: 'Cache' },
  380. { path: '/model', label: 'Models' },
  381. { path: '/timelapse', label: 'Timelapse' },
  382. ];
  383. return (
  384. <div
  385. className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
  386. onClick={onClose}
  387. >
  388. <div
  389. 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"
  390. onClick={(e) => e.stopPropagation()}
  391. >
  392. {/* Header */}
  393. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0">
  394. <div className="flex items-center gap-3">
  395. <HardDrive className="w-5 h-5 text-bambu-green" />
  396. <div>
  397. <h2 className="text-lg font-semibold text-white">{t('printerFiles.title')}</h2>
  398. <p className="text-sm text-bambu-gray">{printerName}</p>
  399. </div>
  400. </div>
  401. <div className="flex items-center gap-4">
  402. {/* Storage info */}
  403. {storageData && (storageData.used_bytes != null || storageData.free_bytes != null) && (
  404. <div className="text-sm text-bambu-gray flex items-center gap-2">
  405. {storageData.used_bytes != null && (
  406. <span>{t('printerFiles.storageUsed')} {formatStorageSize(storageData.used_bytes)}</span>
  407. )}
  408. {storageData.used_bytes != null && storageData.free_bytes != null && (
  409. <span className="text-bambu-dark-tertiary">|</span>
  410. )}
  411. {storageData.free_bytes != null && (
  412. <span>{t('printerFiles.storageFree')} {formatStorageSize(storageData.free_bytes)}</span>
  413. )}
  414. </div>
  415. )}
  416. <button
  417. onClick={onClose}
  418. className="text-bambu-gray hover:text-white transition-colors"
  419. title="Close file manager"
  420. aria-label="Close file manager"
  421. >
  422. <X className="w-5 h-5" />
  423. </button>
  424. </div>
  425. </div>
  426. {/* Quick Navigation */}
  427. <div className="flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0">
  428. {quickDirs.map((dir) => (
  429. <button
  430. key={dir.path}
  431. onClick={() => {
  432. navigateToFolder(dir.path);
  433. setSearchQuery('');
  434. }}
  435. className={`px-3 py-1 text-sm rounded-full transition-colors ${
  436. currentPath === dir.path
  437. ? 'bg-bambu-green text-white'
  438. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  439. }`}
  440. >
  441. {dir.label}
  442. </button>
  443. ))}
  444. <div className="flex-1" />
  445. <div className="relative">
  446. <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  447. <input
  448. type="text"
  449. placeholder={t('printerFiles.filterPlaceholder')}
  450. value={searchQuery}
  451. onChange={(e) => setSearchQuery(e.target.value)}
  452. 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"
  453. />
  454. </div>
  455. <div className="relative flex items-center gap-1">
  456. <ArrowUpDown className="w-4 h-4 text-bambu-gray" />
  457. <select
  458. value={sortBy}
  459. onChange={(e) => setSortBy(e.target.value as SortOption)}
  460. 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"
  461. title="Sort files"
  462. aria-label="Sort files"
  463. >
  464. {SORT_OPTIONS.map((option) => (
  465. <option key={option.value} value={option.value}>
  466. {option.label}
  467. </option>
  468. ))}
  469. </select>
  470. </div>
  471. <Button
  472. variant="secondary"
  473. size="sm"
  474. onClick={() => refetch()}
  475. disabled={isLoading}
  476. >
  477. <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
  478. </Button>
  479. </div>
  480. {/* Path breadcrumb */}
  481. <div className="flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0">
  482. <button
  483. onClick={navigateUp}
  484. disabled={currentPath === '/'}
  485. className="p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed"
  486. title="Go to parent folder"
  487. aria-label="Go to parent folder"
  488. >
  489. <ChevronLeft className="w-4 h-4" />
  490. </button>
  491. <span className="text-bambu-gray font-mono">{currentPath}</span>
  492. </div>
  493. {/* File list */}
  494. <div className="flex-1 overflow-y-auto p-2 min-h-0">
  495. {isLoading ? (
  496. <div className="flex items-center justify-center py-12">
  497. <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
  498. </div>
  499. ) : !data?.files?.length ? (
  500. <div className="text-center py-12 text-bambu-gray">
  501. No files in this directory
  502. </div>
  503. ) : (
  504. <div className="space-y-1">
  505. {/* Filter and sort: directories first, then files with selected sort */}
  506. {[...data.files]
  507. .filter((file) =>
  508. !searchQuery || file.name.toLowerCase().includes(searchQuery.toLowerCase())
  509. )
  510. .sort((a, b) => {
  511. // Directories always first
  512. if (a.is_directory && !b.is_directory) return -1;
  513. if (!a.is_directory && b.is_directory) return 1;
  514. // Apply selected sort within same type
  515. switch (sortBy) {
  516. case 'name-asc':
  517. return a.name.localeCompare(b.name);
  518. case 'name-desc':
  519. return b.name.localeCompare(a.name);
  520. case 'size-asc':
  521. return a.size - b.size;
  522. case 'size-desc':
  523. return b.size - a.size;
  524. case 'date-asc': {
  525. const aTime = a.mtime ? parseUTCDate(a.mtime)?.getTime() ?? 0 : 0;
  526. const bTime = b.mtime ? parseUTCDate(b.mtime)?.getTime() ?? 0 : 0;
  527. return aTime - bTime;
  528. }
  529. case 'date-desc': {
  530. const aTime = a.mtime ? parseUTCDate(a.mtime)?.getTime() ?? 0 : 0;
  531. const bTime = b.mtime ? parseUTCDate(b.mtime)?.getTime() ?? 0 : 0;
  532. return bTime - aTime;
  533. }
  534. default:
  535. return a.name.localeCompare(b.name);
  536. }
  537. })
  538. .map((file) => {
  539. const FileIcon = getFileIcon(file.name, file.is_directory);
  540. const isSelected = selectedFiles.has(file.path);
  541. return (
  542. <div
  543. key={file.path}
  544. className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${
  545. isSelected
  546. ? 'bg-bambu-green/20 border border-bambu-green/50'
  547. : 'hover:bg-bambu-dark-tertiary'
  548. }`}
  549. onClick={() => {
  550. if (file.is_directory) {
  551. navigateToFolder(file.path);
  552. }
  553. }}
  554. >
  555. {/* Checkbox for files only */}
  556. {!file.is_directory ? (
  557. <button
  558. onClick={(e) => toggleFileSelection(file.path, e)}
  559. className="flex-shrink-0 text-bambu-gray hover:text-white"
  560. >
  561. {isSelected ? (
  562. <CheckSquare className="w-5 h-5 text-bambu-green" />
  563. ) : (
  564. <Square className="w-5 h-5" />
  565. )}
  566. </button>
  567. ) : null}
  568. <FileIcon
  569. className={`w-5 h-5 flex-shrink-0 ${
  570. file.is_directory ? 'text-bambu-green' : 'text-bambu-gray'
  571. }`}
  572. />
  573. <span className="flex-1 text-white truncate">{file.name}</span>
  574. {!file.is_directory && (
  575. <div className="flex items-center gap-3">
  576. <span className="text-sm text-bambu-gray">
  577. {formatFileSize(file.size)}
  578. </span>
  579. {(file.name.toLowerCase().endsWith('.3mf') || file.name.toLowerCase().endsWith('.gcode') || file.name.toLowerCase().endsWith('.stl')) && (
  580. <button
  581. onClick={(e) => {
  582. e.stopPropagation();
  583. setViewerFile({ path: file.path, name: file.name });
  584. }}
  585. className="p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green"
  586. title="3D View"
  587. >
  588. <Box className="w-4 h-4" />
  589. </button>
  590. )}
  591. </div>
  592. )}
  593. {file.is_directory && (
  594. <ChevronLeft className="w-4 h-4 text-bambu-gray rotate-180" />
  595. )}
  596. </div>
  597. );
  598. })}
  599. </div>
  600. )}
  601. </div>
  602. {/* Action bar */}
  603. <div className="flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0">
  604. <div className="flex items-center gap-4">
  605. <div className="text-sm text-bambu-gray">
  606. {selectedFiles.size > 0
  607. ? `${selectedFiles.size} selected`
  608. : searchQuery
  609. ? `${data?.files?.filter(f => f.name.toLowerCase().includes(searchQuery.toLowerCase())).length || 0} of ${data?.files?.length || 0} items`
  610. : `${data?.files?.length || 0} items`
  611. }
  612. </div>
  613. {/* Select All / Deselect All */}
  614. {data?.files?.some(f => !f.is_directory) && (
  615. <div className="flex items-center gap-2">
  616. {selectedFiles.size > 0 ? (
  617. <button
  618. onClick={deselectAllFiles}
  619. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  620. >
  621. <MinusSquare className="w-4 h-4" />
  622. Deselect All
  623. </button>
  624. ) : (
  625. <button
  626. onClick={selectAllFiles}
  627. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors"
  628. >
  629. <CheckSquare className="w-4 h-4" />
  630. Select All
  631. </button>
  632. )}
  633. </div>
  634. )}
  635. </div>
  636. <div className="flex gap-2">
  637. <Button
  638. variant="secondary"
  639. disabled={selectedFiles.size === 0 || downloadProgress !== null}
  640. onClick={handleDownload}
  641. >
  642. {downloadProgress ? (
  643. <>
  644. <Loader2 className="w-4 h-4 animate-spin" />
  645. {downloadProgress.current}/{downloadProgress.total}
  646. </>
  647. ) : (
  648. <>
  649. <Download className="w-4 h-4" />
  650. Download{selectedFiles.size > 1 ? ` (${selectedFiles.size})` : ''}
  651. </>
  652. )}
  653. </Button>
  654. <Button
  655. variant="secondary"
  656. disabled={selectedFiles.size === 0 || deleteMutation.isPending}
  657. onClick={handleDelete}
  658. className="text-red-400 hover:text-red-300"
  659. >
  660. {deleteMutation.isPending ? (
  661. <Loader2 className="w-4 h-4 animate-spin" />
  662. ) : (
  663. <Trash2 className="w-4 h-4" />
  664. )}
  665. {t('printerFiles.deleteButton')}{selectedFiles.size > 1 ? ` (${selectedFiles.size})` : ''}
  666. </Button>
  667. </div>
  668. </div>
  669. </div>
  670. {/* Delete Confirmation Modal */}
  671. {filesToDelete.length > 0 && (
  672. <ConfirmModal
  673. title={filesToDelete.length > 1 ? t('printerFiles.deleteFiles', { count: filesToDelete.length }) : t('fileManager.deleteFile')}
  674. message={
  675. filesToDelete.length > 1
  676. ? t('printerFiles.deleteFilesConfirm', { count: filesToDelete.length })
  677. : t('printerFiles.deleteFileConfirm', { name: filesToDelete[0].split('/').pop() })
  678. }
  679. confirmText={t('common.delete')}
  680. variant="danger"
  681. onConfirm={() => {
  682. deleteMutation.mutate(filesToDelete);
  683. }}
  684. onCancel={() => setFilesToDelete([])}
  685. />
  686. )}
  687. {viewerFile && (
  688. <PrinterFileViewerModal
  689. printerId={printerId}
  690. filePath={viewerFile.path}
  691. filename={viewerFile.name}
  692. onClose={() => setViewerFile(null)}
  693. />
  694. )}
  695. </div>
  696. );
  697. }