FileUploadModal.tsx 15 KB

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