FileUploadModal.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. onClose();
  103. };
  104. const addFiles = (newFiles: File[]) => {
  105. setUploadError(null);
  106. if (validateFile) {
  107. for (const file of newFiles) {
  108. const error = validateFile(file);
  109. if (error) {
  110. setUploadError(error);
  111. return;
  112. }
  113. }
  114. }
  115. const toUpload: UploadFile[] = newFiles.map((file) => ({
  116. file,
  117. status: 'pending' as const,
  118. isZip: file.name.toLowerCase().endsWith('.zip'),
  119. is3mf: file.name.toLowerCase().endsWith('.3mf'),
  120. }));
  121. setFiles((prev) => [...prev, ...toUpload]);
  122. if (autoUpload && newFiles.length > 0) {
  123. uploadFiles(toUpload);
  124. }
  125. };
  126. const removeFile = (index: number) => {
  127. setFiles((prev) => prev.filter((_, i) => i !== index));
  128. };
  129. const hasZipFiles = files.some((f) => f.isZip && f.status === 'pending');
  130. const hasStlFiles = files.some((f) => f.file.name.toLowerCase().endsWith('.stl') && f.status === 'pending');
  131. const has3mfFiles = files.some((f) => f.is3mf && f.status === 'pending');
  132. const pendingCount = files.filter((f) => f.status === 'pending').length;
  133. const allDone = files.length > 0 && pendingCount === 0 && !isUploading;
  134. return (
  135. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  136. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary">
  137. <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
  138. <h2 className="text-lg font-semibold text-white">{t('fileManager.uploadFiles')}</h2>
  139. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  140. <X className="w-5 h-5 text-bambu-gray" />
  141. </button>
  142. </div>
  143. <div className="p-4 space-y-4">
  144. {/* Drop Zone */}
  145. <div
  146. onDragOver={handleDragOver}
  147. onDragLeave={handleDragLeave}
  148. onDrop={handleDrop}
  149. onClick={() => fileInputRef.current?.click()}
  150. className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
  151. isDragging
  152. ? 'border-bambu-green bg-bambu-green/10'
  153. : 'border-bambu-dark-tertiary hover:border-bambu-green/50'
  154. }`}
  155. >
  156. <Upload className={`w-10 h-10 mx-auto mb-3 ${isDragging ? 'text-bambu-green' : 'text-bambu-gray'}`} />
  157. <p className="text-white font-medium">
  158. {isDragging ? t('fileManager.dropFilesHere') : t('fileManager.dragDropFiles')}
  159. </p>
  160. <p className="text-sm text-bambu-gray mt-1">{t('fileManager.orClickToBrowse')}</p>
  161. <p className="text-xs text-bambu-gray/70 mt-2">{t('fileManager.allFileTypesSupported')}</p>
  162. </div>
  163. <input
  164. ref={fileInputRef}
  165. type="file"
  166. multiple
  167. accept={accept}
  168. className="hidden"
  169. onChange={handleFileSelect}
  170. />
  171. {/* ZIP Options */}
  172. {hasZipFiles && (
  173. <div className="p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">
  174. <div className="flex items-start gap-3">
  175. <ArchiveIcon className="w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0" />
  176. <div className="flex-1">
  177. <p className="text-sm text-blue-300 font-medium">{t('fileManager.zipFilesDetected')}</p>
  178. <p className="text-xs text-blue-300/70 mt-1">
  179. {t('fileManager.zipExtractOptions')}
  180. </p>
  181. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  182. <input
  183. type="checkbox"
  184. checked={preserveZipStructure}
  185. onChange={(e) => setPreserveZipStructure(e.target.checked)}
  186. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  187. />
  188. <span className="text-sm text-white">{t('fileManager.preserveZipStructure')}</span>
  189. </label>
  190. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  191. <input
  192. type="checkbox"
  193. checked={createFolderFromZip}
  194. onChange={(e) => setCreateFolderFromZip(e.target.checked)}
  195. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  196. />
  197. <span className="text-sm text-white">{t('fileManager.createFolderFromZip')}</span>
  198. </label>
  199. </div>
  200. </div>
  201. </div>
  202. )}
  203. {/* 3MF File Info */}
  204. {has3mfFiles && (
  205. <div className="p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg">
  206. <div className="flex items-start gap-3">
  207. <Printer className="w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0" />
  208. <div className="flex-1">
  209. <p className="text-sm text-purple-300 font-medium">{t('fileManager.threemfDetected')}</p>
  210. <p className="text-xs text-purple-300/70 mt-1">
  211. {t('fileManager.threemfExtractionInfo')}
  212. </p>
  213. </div>
  214. </div>
  215. </div>
  216. )}
  217. {/* STL Thumbnail Options */}
  218. {(hasStlFiles || hasZipFiles) && (
  219. <div className="p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg">
  220. <div className="flex items-start gap-3">
  221. <Image className="w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0" />
  222. <div className="flex-1">
  223. <p className="text-sm text-bambu-green font-medium">{t('fileManager.stlThumbnailGeneration')}</p>
  224. <p className="text-xs text-bambu-green/70 mt-1">
  225. {hasZipFiles && !hasStlFiles
  226. ? t('fileManager.zipMayContainStl')
  227. : t('fileManager.thumbnailsCanBeGenerated')}
  228. </p>
  229. <label className="flex items-center gap-2 mt-2 cursor-pointer">
  230. <input
  231. type="checkbox"
  232. checked={generateStlThumbnails}
  233. onChange={(e) => setGenerateStlThumbnails(e.target.checked)}
  234. className="w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  235. />
  236. <span className="text-sm text-white">{t('fileManager.generateThumbnailsForStl')}</span>
  237. </label>
  238. </div>
  239. </div>
  240. </div>
  241. )}
  242. {/* File List */}
  243. {files.length > 0 && (
  244. <div className="max-h-48 overflow-y-auto space-y-2">
  245. {files.map((uploadFile, index) => (
  246. <div
  247. key={index}
  248. className="flex items-center gap-3 p-2 bg-bambu-dark rounded-lg"
  249. >
  250. {uploadFile.isZip ? (
  251. <ArchiveIcon className="w-4 h-4 text-blue-400 flex-shrink-0" />
  252. ) : (
  253. <File className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  254. )}
  255. <div className="flex-1 min-w-0">
  256. <p className="text-sm text-white truncate">{uploadFile.file.name}</p>
  257. <p className="text-xs text-bambu-gray">
  258. {(uploadFile.file.size / 1024 / 1024).toFixed(2)} MB
  259. {uploadFile.isZip && uploadFile.status === 'pending' && (
  260. <span className="text-blue-400 ml-2">• {t('fileManager.willBeExtracted')}</span>
  261. )}
  262. {uploadFile.extractedCount !== undefined && (
  263. <span className="text-green-400 ml-2">• {t('fileManager.filesExtracted', { count: uploadFile.extractedCount })}</span>
  264. )}
  265. </p>
  266. </div>
  267. {uploadFile.status === 'pending' && (
  268. <button
  269. onClick={() => removeFile(index)}
  270. className="p-1 hover:bg-bambu-dark-tertiary rounded"
  271. >
  272. <X className="w-4 h-4 text-bambu-gray" />
  273. </button>
  274. )}
  275. {uploadFile.status === 'uploading' && (
  276. <Loader2 className="w-4 h-4 text-bambu-green animate-spin" />
  277. )}
  278. {uploadFile.status === 'success' && (
  279. <CheckCircle className="w-4 h-4 text-green-500" />
  280. )}
  281. {uploadFile.status === 'error' && (
  282. <span title={uploadFile.error}>
  283. <XCircle className="w-4 h-4 text-red-500" />
  284. </span>
  285. )}
  286. </div>
  287. ))}
  288. </div>
  289. )}
  290. {/* Compatibility Error */}
  291. {uploadError && (
  292. <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
  293. <div className="flex items-start gap-3">
  294. <XCircle className="w-5 h-5 text-red-400 mt-0.5 flex-shrink-0" />
  295. <p className="text-sm text-red-300">{uploadError}</p>
  296. </div>
  297. </div>
  298. )}
  299. </div>
  300. <div className="p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2">
  301. <Button variant="secondary" onClick={onClose}>
  302. {t('common.cancel')}
  303. </Button>
  304. {!allDone && (
  305. <Button
  306. onClick={() => uploadFiles(files)}
  307. disabled={pendingCount === 0 || isUploading}
  308. >
  309. {isUploading ? (
  310. <>
  311. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  312. {t('fileManager.uploading')}
  313. </>
  314. ) : (
  315. <>
  316. <Upload className="w-4 h-4 mr-2" />
  317. {t('common.upload')} {pendingCount > 0 ? `(${pendingCount})` : ''}
  318. </>
  319. )}
  320. </Button>
  321. )}
  322. </div>
  323. </div>
  324. </div>
  325. );
  326. }