UploadModal.tsx 10 KB

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