FileUploadModal.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import { useState, useRef, useEffect, type DragEvent } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Upload,
  5. X,
  6. File,
  7. Loader2,
  8. CheckCircle,
  9. XCircle,
  10. Archive as ArchiveIcon,
  11. Printer,
  12. Image,
  13. } from 'lucide-react';
  14. import { api } from '../api/client';
  15. import type { LibraryFileUploadResponse } from '../api/client';
  16. import { Button } from './Button';
  17. interface UploadFile {
  18. file: File;
  19. status: 'pending' | 'uploading' | 'success' | 'error';
  20. error?: string;
  21. isZip?: boolean;
  22. is3mf?: boolean;
  23. extractedCount?: number;
  24. }
  25. interface FileUploadModalProps {
  26. folderId: number | null;
  27. onClose: () => void;
  28. onUploadComplete: () => void;
  29. /** Called after each file is successfully uploaded with its response data. Return a string to show an error and prevent modal from closing. */
  30. onFileUploaded?: (file: LibraryFileUploadResponse) => string | void;
  31. /** When true, automatically uploads the file as soon as it's added and closes the modal */
  32. autoUpload?: boolean;
  33. /** Validate files before adding. Return a string to reject with an error message. */
  34. validateFile?: (file: File) => string | undefined;
  35. /** Restrict file picker to specific file types (e.g. ".gcode,.gcode.3mf") */
  36. accept?: string;
  37. /** Pre-seed the modal with files (e.g. from a page-wide drop) on first mount. */
  38. initialFiles?: File[];
  39. }
  40. export function FileUploadModal({ folderId, onClose, onUploadComplete, onFileUploaded, autoUpload, validateFile, accept, initialFiles }: FileUploadModalProps) {
  41. const { t } = useTranslation();
  42. const [files, setFiles] = useState<UploadFile[]>([]);
  43. const [isDragging, setIsDragging] = useState(false);
  44. const [isUploading, setIsUploading] = useState(false);
  45. const [preserveZipStructure, setPreserveZipStructure] = useState(true);
  46. const [createFolderFromZip, setCreateFolderFromZip] = useState(false);
  47. const [generateStlThumbnails, setGenerateStlThumbnails] = useState(true);
  48. const [uploadError, setUploadError] = useState<string | null>(null);
  49. const fileInputRef = useRef<HTMLInputElement>(null);
  50. const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
  51. e.preventDefault();
  52. setIsDragging(true);
  53. };
  54. const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
  55. e.preventDefault();
  56. setIsDragging(false);
  57. };
  58. const handleDrop = (e: DragEvent<HTMLDivElement>) => {
  59. e.preventDefault();
  60. setIsDragging(false);
  61. addFiles(Array.from(e.dataTransfer.files));
  62. };
  63. const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
  64. if (e.target.files) {
  65. addFiles(Array.from(e.target.files));
  66. }
  67. };
  68. const updateFileStatus = (file: File, update: Partial<UploadFile>) => {
  69. setFiles((prev) => prev.map((f) => (f.file === file ? { ...f, ...update } : f)));
  70. };
  71. const uploadFiles = async (filesToUpload: UploadFile[]) => {
  72. setIsUploading(true);
  73. for (const uf of filesToUpload) {
  74. if (uf.status !== 'pending') continue;
  75. updateFileStatus(uf.file, { status: 'uploading' });
  76. try {
  77. if (uf.isZip) {
  78. const result = await api.extractZipFile(uf.file, folderId, preserveZipStructure, createFolderFromZip, generateStlThumbnails);
  79. updateFileStatus(uf.file, {
  80. status: result.errors.length > 0 && result.extracted === 0 ? 'error' : 'success',
  81. extractedCount: result.extracted,
  82. error: result.errors.length > 0 ? t('fileManager.zipFilesFailed', '{{count}} files failed', { count: result.errors.length }) : undefined,
  83. });
  84. } else {
  85. const result = await api.uploadLibraryFile(uf.file, folderId, generateStlThumbnails);
  86. updateFileStatus(uf.file, { status: 'success' });
  87. const error = onFileUploaded?.(result);
  88. if (error) {
  89. setUploadError(error);
  90. setFiles([]);
  91. setIsUploading(false);
  92. return;
  93. }
  94. }
  95. } catch (err) {
  96. updateFileStatus(uf.file, {
  97. status: 'error',
  98. error: err instanceof Error ? err.message : t('fileManager.uploadFailed', 'Upload failed'),
  99. });
  100. }
  101. }
  102. setIsUploading(false);
  103. onUploadComplete();
  104. // #1401: don't auto-close if any file ended with an error — the user
  105. // needs to see the rejection message (e.g. "raw .gcode upload"), not
  106. // have the modal vanish before they can read it. Closing happens via
  107. // the X / Close button instead, after the user has seen what failed.
  108. setFiles((prev) => {
  109. const anyFailed = prev.some((f) => f.status === 'error');
  110. if (!anyFailed) {
  111. onClose();
  112. }
  113. return prev;
  114. });
  115. };
  116. const addFiles = (newFiles: File[]) => {
  117. setUploadError(null);
  118. if (validateFile) {
  119. for (const file of newFiles) {
  120. const error = validateFile(file);
  121. if (error) {
  122. setUploadError(error);
  123. return;
  124. }
  125. }
  126. }
  127. const toUpload: UploadFile[] = newFiles.map((file) => ({
  128. file,
  129. status: 'pending' as const,
  130. isZip: file.name.toLowerCase().endsWith('.zip'),
  131. is3mf: file.name.toLowerCase().endsWith('.3mf'),
  132. }));
  133. setFiles((prev) => [...prev, ...toUpload]);
  134. if (autoUpload && newFiles.length > 0) {
  135. uploadFiles(toUpload);
  136. }
  137. };
  138. const removeFile = (index: number) => {
  139. setFiles((prev) => prev.filter((_, i) => i !== index));
  140. };
  141. // Seed once on mount when the parent passed initialFiles (page-wide drop).
  142. // The ref/list shape means a subsequent re-render with the same files won't
  143. // double-add — only the first non-empty initialFiles arg ever flows through.
  144. const seededInitialRef = useRef(false);
  145. useEffect(() => {
  146. if (seededInitialRef.current) return;
  147. if (!initialFiles || initialFiles.length === 0) return;
  148. seededInitialRef.current = true;
  149. addFiles(initialFiles);
  150. // eslint-disable-next-line react-hooks/exhaustive-deps
  151. }, []);
  152. const hasZipFiles = files.some((f) => f.isZip && f.status === 'pending');
  153. const hasStlFiles = files.some((f) => f.file.name.toLowerCase().endsWith('.stl') && f.status === 'pending');
  154. const has3mfFiles = files.some((f) => f.is3mf && f.status === 'pending');
  155. const pendingCount = files.filter((f) => f.status === 'pending').length;
  156. const allDone = files.length > 0 && pendingCount === 0 && !isUploading;
  157. return (
  158. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  159. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary">
  160. <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
  161. <h2 className="text-lg font-semibold text-white">{t('fileManager.uploadFiles')}</h2>
  162. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  163. <X className="w-5 h-5 text-bambu-gray" />
  164. </button>
  165. </div>
  166. <div className="p-4 space-y-4">
  167. {/* Drop Zone */}
  168. <div
  169. onDragOver={handleDragOver}
  170. onDragLeave={handleDragLeave}
  171. onDrop={handleDrop}
  172. onClick={() => fileInputRef.current?.click()}
  173. className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
  174. isDragging
  175. ? 'border-bambu-green bg-bambu-green/10'
  176. : 'border-bambu-dark-tertiary hover:border-bambu-green/50'
  177. }`}
  178. >
  179. <Upload className={`w-10 h-10 mx-auto mb-3 ${isDragging ? 'text-bambu-green' : 'text-bambu-gray'}`} />
  180. <p className="text-white font-medium">
  181. {isDragging ? t('fileManager.dropFilesHere') : t('fileManager.dragDropFiles')}
  182. </p>
  183. <p className="text-sm text-bambu-gray mt-1">{t('fileManager.orClickToBrowse')}</p>
  184. <p className="text-xs text-bambu-gray/70 mt-2">{t('fileManager.allFileTypesSupported')}</p>
  185. </div>
  186. <input
  187. ref={fileInputRef}
  188. type="file"
  189. multiple
  190. accept={accept}
  191. className="hidden"
  192. onChange={handleFileSelect}
  193. />
  194. {/* ZIP Options */}
  195. {hasZipFiles && (
  196. <div className="p-3 bg-blue-50 dark:bg-blue-500/10 border border-blue-300 dark:border-blue-500/30 rounded-lg">
  197. <div className="flex items-start gap-3">
  198. <ArchiveIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
  199. <div className="flex-1">
  200. <p className="text-sm text-blue-700 dark:text-blue-300 font-medium">{t('fileManager.zipFilesDetected')}</p>
  201. <p className="text-xs text-blue-700/80 dark:text-blue-300/70 mt-1">
  202. {t('fileManager.zipExtractOptions')}
  203. </p>
  204. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  205. <input
  206. type="checkbox"
  207. checked={preserveZipStructure}
  208. onChange={(e) => setPreserveZipStructure(e.target.checked)}
  209. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  210. />
  211. <span className="text-sm text-white">{t('fileManager.preserveZipStructure')}</span>
  212. </label>
  213. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  214. <input
  215. type="checkbox"
  216. checked={createFolderFromZip}
  217. onChange={(e) => setCreateFolderFromZip(e.target.checked)}
  218. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  219. />
  220. <span className="text-sm text-white">{t('fileManager.createFolderFromZip')}</span>
  221. </label>
  222. </div>
  223. </div>
  224. </div>
  225. )}
  226. {/* 3MF File Info */}
  227. {has3mfFiles && (
  228. <div className="p-3 bg-purple-50 dark:bg-purple-500/10 border border-purple-300 dark:border-purple-500/30 rounded-lg">
  229. <div className="flex items-start gap-3">
  230. <Printer className="w-5 h-5 text-purple-600 dark:text-purple-400 mt-0.5 flex-shrink-0" />
  231. <div className="flex-1">
  232. <p className="text-sm text-purple-700 dark:text-purple-300 font-medium">{t('fileManager.threemfDetected')}</p>
  233. <p className="text-xs text-purple-700/80 dark:text-purple-300/70 mt-1">
  234. {t('fileManager.threemfExtractionInfo')}
  235. </p>
  236. </div>
  237. </div>
  238. </div>
  239. )}
  240. {/* STL Thumbnail Options */}
  241. {(hasStlFiles || hasZipFiles) && (
  242. <div className="p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg">
  243. <div className="flex items-start gap-3">
  244. <Image className="w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0" />
  245. <div className="flex-1">
  246. <p className="text-sm text-bambu-green font-medium">{t('fileManager.stlThumbnailGeneration')}</p>
  247. <p className="text-xs text-bambu-green/70 mt-1">
  248. {hasZipFiles && !hasStlFiles
  249. ? t('fileManager.zipMayContainStl')
  250. : t('fileManager.thumbnailsCanBeGenerated')}
  251. </p>
  252. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  253. <input
  254. type="checkbox"
  255. checked={generateStlThumbnails}
  256. onChange={(e) => setGenerateStlThumbnails(e.target.checked)}
  257. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  258. />
  259. <span className="text-sm text-white">{t('fileManager.generateThumbnailsForStl')}</span>
  260. </label>
  261. </div>
  262. </div>
  263. </div>
  264. )}
  265. {/* File List */}
  266. {files.length > 0 && (
  267. <div className="max-h-48 overflow-y-auto space-y-2">
  268. {files.map((uploadFile, index) => (
  269. <div
  270. key={index}
  271. className="flex items-center gap-3 p-2 bg-bambu-dark rounded-lg"
  272. >
  273. {uploadFile.isZip ? (
  274. <ArchiveIcon className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0" />
  275. ) : (
  276. <File className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  277. )}
  278. <div className="flex-1 min-w-0">
  279. <p className="text-sm text-white truncate">{uploadFile.file.name}</p>
  280. <p className="text-xs text-bambu-gray">
  281. {(uploadFile.file.size / 1024 / 1024).toFixed(2)} MB
  282. {uploadFile.isZip && uploadFile.status === 'pending' && (
  283. <span className="text-blue-700 dark:text-blue-400 ml-2">• {t('fileManager.willBeExtracted')}</span>
  284. )}
  285. {uploadFile.extractedCount !== undefined && (
  286. <span className="text-green-700 dark:text-green-400 ml-2">• {t('fileManager.filesExtracted', { count: uploadFile.extractedCount })}</span>
  287. )}
  288. </p>
  289. {/* #1401: errors render inline rather than as a hover-only
  290. title. The backend's rejection messages explain the
  291. actual fix (re-export as .gcode.3mf) — useless if the
  292. user can't read them. */}
  293. {uploadFile.status === 'error' && uploadFile.error && (
  294. <p className="text-xs text-red-700 dark:text-red-400 mt-1 break-words">{uploadFile.error}</p>
  295. )}
  296. </div>
  297. {uploadFile.status === 'pending' && (
  298. <button
  299. onClick={() => removeFile(index)}
  300. className="p-1 hover:bg-bambu-dark-tertiary rounded"
  301. >
  302. <X className="w-4 h-4 text-bambu-gray" />
  303. </button>
  304. )}
  305. {uploadFile.status === 'uploading' && (
  306. <Loader2 className="w-4 h-4 text-bambu-green animate-spin" />
  307. )}
  308. {uploadFile.status === 'success' && (
  309. <CheckCircle className="w-4 h-4 text-green-500" />
  310. )}
  311. {uploadFile.status === 'error' && (
  312. <span title={uploadFile.error}>
  313. <XCircle className="w-4 h-4 text-red-500" />
  314. </span>
  315. )}
  316. </div>
  317. ))}
  318. </div>
  319. )}
  320. {/* Compatibility Error */}
  321. {uploadError && (
  322. <div className="p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg">
  323. <div className="flex items-start gap-3">
  324. <XCircle className="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  325. <p className="text-sm text-red-700 dark:text-red-300">{uploadError}</p>
  326. </div>
  327. </div>
  328. )}
  329. </div>
  330. <div className="p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2">
  331. <Button variant="secondary" onClick={onClose}>
  332. {t('common.cancel')}
  333. </Button>
  334. {!allDone && (
  335. <Button
  336. onClick={() => uploadFiles(files)}
  337. disabled={pendingCount === 0 || isUploading}
  338. >
  339. {isUploading ? (
  340. <>
  341. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  342. {t('fileManager.uploading')}
  343. </>
  344. ) : (
  345. <>
  346. <Upload className="w-4 h-4 mr-2" />
  347. {t('common.upload')} {pendingCount > 0 ? `(${pendingCount})` : ''}
  348. </>
  349. )}
  350. </Button>
  351. )}
  352. </div>
  353. </div>
  354. </div>
  355. );
  356. }