UploadModal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { useState, useCallback, useRef, useEffect } from 'react';
  2. import { useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { Upload, X, File, CheckCircle, AlertCircle, Loader2 } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { BulkUploadResult } from '../api/client';
  7. import { Card, CardContent } from './Card';
  8. import { Button } from './Button';
  9. import { useToast } from '../contexts/ToastContext';
  10. interface FileWithStatus {
  11. file: File;
  12. status: 'pending' | 'uploading' | 'success' | 'error';
  13. error?: string;
  14. archiveId?: number;
  15. }
  16. interface UploadModalProps {
  17. onClose: () => void;
  18. initialFiles?: File[];
  19. }
  20. export function UploadModal({ onClose, initialFiles }: UploadModalProps) {
  21. const { t } = useTranslation();
  22. const queryClient = useQueryClient();
  23. const { showToast } = useToast();
  24. const fileInputRef = useRef<HTMLInputElement>(null);
  25. const [files, setFiles] = useState<FileWithStatus[]>(() =>
  26. initialFiles?.filter(f => f.name.endsWith('.3mf')).map(file => ({ file, status: 'pending' as const })) || []
  27. );
  28. const [isDragging, setIsDragging] = useState(false);
  29. const [uploadResult, setUploadResult] = useState<BulkUploadResult | null>(null);
  30. // Close on Escape key
  31. useEffect(() => {
  32. const handleKeyDown = (e: KeyboardEvent) => {
  33. if (e.key === 'Escape') onClose();
  34. };
  35. window.addEventListener('keydown', handleKeyDown);
  36. return () => window.removeEventListener('keydown', handleKeyDown);
  37. }, [onClose]);
  38. const uploadMutation = useMutation({
  39. mutationFn: (filesToUpload: File[]) =>
  40. api.uploadArchivesBulk(filesToUpload),
  41. onSuccess: (result, sent) => {
  42. setUploadResult(result);
  43. queryClient.invalidateQueries({ queryKey: ['archives'] });
  44. queryClient.invalidateQueries({ queryKey: ['archiveStats'] });
  45. // Update file statuses based on result. Each outcome names its file by
  46. // position in the batch sent; two files can share a name.
  47. setFiles((prev) =>
  48. prev.map((f) => {
  49. const success = result.results.find((r) => sent[r.index] === f.file);
  50. const error = result.errors.find((e) => sent[e.index] === f.file);
  51. if (success) {
  52. return { ...f, status: 'success', archiveId: success.id };
  53. }
  54. if (error) {
  55. return { ...f, status: 'error', error: error.error };
  56. }
  57. return f;
  58. })
  59. );
  60. // Show toast
  61. if (result.failed === 0) {
  62. showToast(`${result.uploaded} file${result.uploaded !== 1 ? 's' : ''} uploaded`);
  63. } else if (result.uploaded === 0) {
  64. showToast(`Failed to upload ${result.failed} file${result.failed !== 1 ? 's' : ''}`, 'error');
  65. } else {
  66. showToast(`${result.uploaded} uploaded, ${result.failed} failed`, 'warning');
  67. }
  68. },
  69. onError: () => {
  70. setFiles((prev) =>
  71. prev.map((f) => ({ ...f, status: 'error', error: 'Upload failed' }))
  72. );
  73. showToast('Upload failed', 'error');
  74. },
  75. });
  76. const handleDragOver = useCallback((e: React.DragEvent) => {
  77. e.preventDefault();
  78. setIsDragging(true);
  79. }, []);
  80. const handleDragLeave = useCallback((e: React.DragEvent) => {
  81. e.preventDefault();
  82. setIsDragging(false);
  83. }, []);
  84. const handleDrop = useCallback((e: React.DragEvent) => {
  85. e.preventDefault();
  86. setIsDragging(false);
  87. const droppedFiles = Array.from(e.dataTransfer.files).filter((f) =>
  88. f.name.endsWith('.3mf')
  89. );
  90. if (droppedFiles.length > 0) {
  91. setFiles((prev) => [
  92. ...prev,
  93. ...droppedFiles.map((file) => ({ file, status: 'pending' as const })),
  94. ]);
  95. }
  96. }, []);
  97. const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  98. const selectedFiles = Array.from(e.target.files || []).filter((f) =>
  99. f.name.endsWith('.3mf')
  100. );
  101. if (selectedFiles.length > 0) {
  102. setFiles((prev) => [
  103. ...prev,
  104. ...selectedFiles.map((file) => ({ file, status: 'pending' as const })),
  105. ]);
  106. }
  107. // Reset input so same file can be selected again
  108. if (fileInputRef.current) {
  109. fileInputRef.current.value = '';
  110. }
  111. }, []);
  112. const removeFile = useCallback((index: number) => {
  113. setFiles((prev) => prev.filter((_, i) => i !== index));
  114. }, []);
  115. const handleUpload = () => {
  116. if (files.length === 0) return;
  117. const pendingFiles = files.filter((f) => f.status === 'pending');
  118. if (pendingFiles.length === 0) return;
  119. setFiles((prev) =>
  120. prev.map((f) =>
  121. f.status === 'pending' ? { ...f, status: 'uploading' } : f
  122. )
  123. );
  124. uploadMutation.mutate(pendingFiles.map((f) => f.file));
  125. };
  126. const pendingCount = files.filter((f) => f.status === 'pending').length;
  127. const isUploading = uploadMutation.isPending;
  128. return (
  129. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
  130. <Card className="w-full max-w-2xl max-h-[90vh] flex flex-col">
  131. <CardContent className="p-0 flex flex-col h-full">
  132. {/* Header */}
  133. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  134. <h2 className="text-xl font-semibold text-white">{t('uploadModal.title')}</h2>
  135. <button
  136. onClick={onClose}
  137. className="text-bambu-gray hover:text-white transition-colors"
  138. >
  139. <X className="w-5 h-5" />
  140. </button>
  141. </div>
  142. {/* Drop Zone */}
  143. <div className="p-4">
  144. <div
  145. className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
  146. isDragging
  147. ? 'border-bambu-green bg-bambu-green/10'
  148. : 'border-bambu-dark-tertiary hover:border-bambu-gray'
  149. }`}
  150. onDragOver={handleDragOver}
  151. onDragLeave={handleDragLeave}
  152. onDrop={handleDrop}
  153. >
  154. <Upload className="w-12 h-12 mx-auto mb-4 text-bambu-gray" />
  155. <p className="text-white mb-2">
  156. {t('uploadModal.dragDrop')}
  157. </p>
  158. <p className="text-bambu-gray text-sm mb-4">{t('uploadModal.or')}</p>
  159. <Button
  160. variant="secondary"
  161. onClick={() => fileInputRef.current?.click()}
  162. disabled={isUploading}
  163. >
  164. {t('uploadModal.browseFiles')}
  165. </Button>
  166. <input
  167. ref={fileInputRef}
  168. type="file"
  169. accept=".3mf"
  170. multiple
  171. className="hidden"
  172. onChange={handleFileSelect}
  173. />
  174. </div>
  175. </div>
  176. {/* Info about printer model extraction */}
  177. <div className="px-4 pb-4">
  178. <p className="text-xs text-bambu-gray">
  179. {t('uploadModal.extractionInfo')}
  180. </p>
  181. </div>
  182. {/* File List */}
  183. {files.length > 0 && (
  184. <div className="px-4 pb-4 max-h-60 overflow-y-auto">
  185. <div className="space-y-2">
  186. {files.map((f, index) => (
  187. <div
  188. key={`${f.file.name}-${index}`}
  189. className="flex items-center gap-3 p-3 bg-bambu-dark rounded-lg"
  190. >
  191. <File className="w-5 h-5 text-bambu-gray flex-shrink-0" />
  192. <span className="flex-1 text-white text-sm truncate">
  193. {f.file.name}
  194. </span>
  195. <span className="text-xs text-bambu-gray">
  196. {(f.file.size / (1024 * 1024)).toFixed(1)} MB
  197. </span>
  198. {f.status === 'pending' && (
  199. <button
  200. onClick={() => removeFile(index)}
  201. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 transition-colors"
  202. disabled={isUploading}
  203. >
  204. <X className="w-4 h-4" />
  205. </button>
  206. )}
  207. {f.status === 'uploading' && (
  208. <Loader2 className="w-4 h-4 text-bambu-green animate-spin" />
  209. )}
  210. {f.status === 'success' && (
  211. <CheckCircle className="w-4 h-4 text-bambu-green" />
  212. )}
  213. {f.status === 'error' && (
  214. <div className="flex items-center gap-2">
  215. <span className="text-xs text-red-700 dark:text-red-400">{f.error}</span>
  216. <AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400" />
  217. </div>
  218. )}
  219. </div>
  220. ))}
  221. </div>
  222. </div>
  223. )}
  224. {/* Upload Result Summary */}
  225. {uploadResult && (
  226. <div className="px-4 pb-4">
  227. <div className="p-3 bg-bambu-dark rounded-lg">
  228. <p className="text-sm text-white">
  229. <span className="text-bambu-green">{uploadResult.uploaded}</span> {t('uploadModal.uploaded')}
  230. {uploadResult.failed > 0 && (
  231. <>, <span className="text-red-700 dark:text-red-400">{uploadResult.failed}</span> {t('uploadModal.failed')}</>
  232. )}
  233. </p>
  234. </div>
  235. </div>
  236. )}
  237. {/* Footer */}
  238. <div className="flex gap-3 p-4 border-t border-bambu-dark-tertiary">
  239. <Button variant="secondary" onClick={onClose} className="flex-1">
  240. {uploadResult ? t('common.close') : t('common.cancel')}
  241. </Button>
  242. {!uploadResult && (
  243. <Button
  244. onClick={handleUpload}
  245. disabled={pendingCount === 0 || isUploading}
  246. className="flex-1"
  247. >
  248. {isUploading ? (
  249. <>
  250. <Loader2 className="w-4 h-4 animate-spin" />
  251. {t('uploadModal.uploading')}
  252. </>
  253. ) : (
  254. <>
  255. <Upload className="w-4 h-4" />
  256. {t('uploadModal.upload')} {pendingCount > 0 && `(${pendingCount})`}
  257. </>
  258. )}
  259. </Button>
  260. )}
  261. </div>
  262. </CardContent>
  263. </Card>
  264. </div>
  265. );
  266. }