File size: 13,541 Bytes
d02c2a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | 'use client';
import { createGlobalState } from 'react-global-hooks';
import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react';
import { FaUpload, FaTimesCircle, FaSpinner } from 'react-icons/fa';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { apiClient } from '@/utils/api';
export interface AddImagesModalState {
datasetName: string;
onComplete?: () => void;
openedByDrag?: boolean;
}
export const addImagesModalState = createGlobalState<AddImagesModalState | null>(null);
export const openImagesModal = (datasetName: string, onComplete: () => void) => {
addImagesModalState.set({ datasetName, onComplete });
};
/** Call on a page that knows its datasetName — auto-opens the modal when files are dragged onto the page. */
export function useOpenImagesModalOnDrag(datasetName: string, onComplete: () => void) {
const onCompleteRef = useRef(onComplete);
onCompleteRef.current = onComplete;
useEffect(() => {
if (!datasetName) return;
let depth = 0;
const isFileDrag = (e: DragEvent) => {
const types = e?.dataTransfer?.types;
return !!types && Array.from(types).includes('Files');
};
const onDragEnter = (e: DragEvent) => {
if (!isFileDrag(e)) return;
depth += 1;
if (depth === 1) {
if (!addImagesModalState.get()) {
addImagesModalState.set({ datasetName, onComplete: onCompleteRef.current, openedByDrag: true });
}
}
e.preventDefault();
};
const onDragLeave = (e: DragEvent) => {
if (!isFileDrag(e)) return;
depth = Math.max(0, depth - 1);
if (depth === 0) {
const current = addImagesModalState.get();
if (current?.openedByDrag) {
addImagesModalState.set(null);
}
}
};
const onDrop = (e: DragEvent) => {
if (!isFileDrag(e)) return;
depth = 0;
// Files were dropped — modal is now committed, no longer dismissable by drag-out
const current = addImagesModalState.get();
if (current?.openedByDrag) {
addImagesModalState.set({ ...current, openedByDrag: false });
}
};
window.addEventListener('dragenter', onDragEnter);
window.addEventListener('dragleave', onDragLeave);
window.addEventListener('drop', onDrop);
return () => {
window.removeEventListener('dragenter', onDragEnter);
window.removeEventListener('dragleave', onDragLeave);
window.removeEventListener('drop', onDrop);
};
}, [datasetName]);
}
type AcceptMap = { [mime: string]: string[] };
type FileStatus = 'pending' | 'uploading' | 'error';
interface FileEntry {
id: number;
file: File;
status: FileStatus;
progress: number;
error?: string;
}
const MAX_CONCURRENT = 3;
const ROW_HEIGHT = 32;
const VISIBLE_ROWS = 8;
let nextId = 0;
export default function AddImagesModal() {
const [modalInfo, setModalInfo] = addImagesModalState.use();
const open = modalInfo !== null;
const [isUploading, setIsUploading] = useState(false);
const [fileEntries, setFileEntries] = useState<FileEntry[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [doneCount, setDoneCount] = useState(0);
const [errorCount, setErrorCount] = useState(0);
const abortRef = useRef(false);
const modalInfoRef = useRef(modalInfo);
modalInfoRef.current = modalInfo;
const datasetName = modalInfo?.datasetName ?? '';
const uploadSingleFile = useCallback(
async (entry: FileEntry): Promise<'done' | 'error'> => {
if (abortRef.current) return 'error';
const id = entry.id;
setFileEntries(prev =>
prev.map(e => (e.id === id ? { ...e, status: 'uploading' as FileStatus, progress: 0 } : e)),
);
const formData = new FormData();
formData.append('files', entry.file);
formData.append('datasetName', datasetName || '');
try {
await apiClient.post('/api/datasets/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: pe => {
const percent = Math.round(((pe.loaded || 0) * 100) / (pe.total || pe.loaded || 1));
setFileEntries(prev => prev.map(e => (e.id === id ? { ...e, progress: percent } : e)));
},
timeout: 0,
});
setFileEntries(prev => prev.filter(e => e.id !== id));
setDoneCount(prev => prev + 1);
return 'done';
} catch (err) {
console.error(`Upload failed for ${entry.file.name}:`, err);
setFileEntries(prev =>
prev.map(e =>
e.id === id
? { ...e, status: 'error' as FileStatus, error: err instanceof Error ? err.message : 'Upload failed' }
: e,
),
);
setErrorCount(prev => prev + 1);
return 'error';
}
},
[datasetName],
);
const resetState = useCallback(() => {
setFileEntries([]);
setTotalCount(0);
setDoneCount(0);
setErrorCount(0);
}, []);
const processQueue = useCallback(
async (entries: FileEntry[]) => {
setIsUploading(true);
abortRef.current = false;
let nextIndex = 0;
const runNext = async (): Promise<void> => {
while (nextIndex < entries.length) {
if (abortRef.current) return;
const idx = nextIndex++;
await uploadSingleFile(entries[idx]);
}
};
const workers = Array.from({ length: Math.min(MAX_CONCURRENT, entries.length) }, () => runNext());
await Promise.all(workers);
setIsUploading(false);
if (!abortRef.current) {
modalInfoRef.current?.onComplete?.();
setModalInfo(null);
resetState();
}
},
[uploadSingleFile, setModalInfo, resetState],
);
const onDrop = useCallback(
(acceptedFiles: File[]) => {
if (acceptedFiles.length === 0) return;
const entries: FileEntry[] = acceptedFiles.map(file => ({
id: nextId++,
file,
status: 'pending' as FileStatus,
progress: 0,
}));
setFileEntries(entries);
setTotalCount(entries.length);
setDoneCount(0);
setErrorCount(0);
processQueue(entries);
},
[processQueue],
);
const handleCancel = useCallback(() => {
abortRef.current = true;
setIsUploading(false);
setModalInfo(null);
resetState();
}, [setModalInfo, resetState]);
const dropAccept = useMemo<AcceptMap>(
() => ({
'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'],
'video/*': ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.m4v', '.flv'],
'audio/*': ['.mp3', '.wav', '.flac', '.ogg'],
'text/*': ['.txt'],
}),
[],
);
const {
getRootProps,
getInputProps,
isDragActive,
open: openFilePicker,
} = useDropzone({
onDrop,
accept: dropAccept,
multiple: true,
noClick: true,
noKeyboard: true,
});
const overallPercent = totalCount > 0 ? Math.round(((doneCount + errorCount) / totalCount) * 100) : 0;
return (
<Dialog
open={open}
onClose={() => {
if (!isUploading) handleCancel();
}}
className="relative z-10"
>
<DialogBackdrop
transition
className="fixed inset-0 bg-gray-900/75 transition-opacity data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in"
/>
<div className="fixed inset-0 z-10 w-screen overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<DialogPanel
transition
className="relative transform overflow-hidden rounded-lg bg-gray-800 text-left shadow-xl transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in sm:my-8 sm:w-full sm:max-w-lg data-closed:sm:translate-y-0 data-closed:sm:scale-95"
>
<div className="bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div className="text-center">
<DialogTitle as="h3" className="text-base font-semibold text-gray-200 mb-4">
Add Images to: {datasetName}
</DialogTitle>
{/* Drop zone + click to select */}
<div {...getRootProps()} className="w-full">
<input {...getInputProps()} />
<div
onClick={() => {
if (!isUploading) openFilePicker();
}}
className={`h-40 w-full flex flex-col items-center justify-center border-2 border-dashed rounded-lg cursor-pointer transition-colors
${isDragActive ? 'border-blue-400 bg-blue-500/10' : 'border-gray-600 hover:border-gray-400'}`}
>
<FaUpload className="size-8 mb-3 text-gray-400" />
{!isUploading ? (
<>
<p className="text-sm text-gray-200 text-center">Drag & drop files here or click to select</p>
<p className="text-xs text-gray-400 mt-1">Images, videos, or .txt supported</p>
</>
) : (
<p className="text-sm text-gray-200 text-center">Drop more files to add to queue</p>
)}
</div>
</div>
{/* Upload progress */}
{isUploading && (
<div className="mt-4">
<p className="text-sm font-semibold text-gray-200 mb-2">
Uploading… {doneCount + errorCount} / {totalCount}
</p>
<div className="w-full h-2.5 bg-white/20 rounded-full overflow-hidden">
<div
className="h-2.5 bg-blue-500 rounded-full transition-[width] duration-150 ease-linear"
style={{ width: `${overallPercent}%` }}
/>
</div>
{errorCount > 0 && (
<p className="text-xs text-red-400 mt-1">
{errorCount} file{errorCount !== 1 ? 's' : ''} failed
</p>
)}
</div>
)}
{/* File progress list */}
{fileEntries.length > 0 && (
<div className="mt-3">
<FileProgressList entries={fileEntries} />
</div>
)}
</div>
</div>
<div className="bg-gray-700 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
<button
type="button"
onClick={handleCancel}
className={`inline-flex w-full justify-center rounded-md px-3 py-2 text-sm font-semibold text-white shadow-xs sm:ml-3 sm:w-auto ${
isUploading ? 'bg-red-600 hover:bg-red-500' : 'bg-gray-600 hover:bg-gray-500'
}`}
>
{isUploading ? 'Cancel Upload' : 'Close'}
</button>
</div>
</DialogPanel>
</div>
</div>
</Dialog>
);
}
/** Virtualized file progress list */
function FileProgressList({ entries }: { entries: FileEntry[] }) {
const containerRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const totalHeight = entries.length * ROW_HEIGHT;
const containerHeight = Math.min(entries.length, VISIBLE_ROWS) * ROW_HEIGHT;
const startIdx = Math.floor(scrollTop / ROW_HEIGHT);
const endIdx = Math.min(entries.length, startIdx + VISIBLE_ROWS + 2);
const visibleEntries = entries.slice(startIdx, endIdx);
const offsetY = startIdx * ROW_HEIGHT;
const onScroll = useCallback(() => {
if (containerRef.current) {
setScrollTop(containerRef.current.scrollTop);
}
}, []);
return (
<div
ref={containerRef}
onScroll={onScroll}
className="rounded-xl bg-black/60 backdrop-blur-sm border border-white/10 overflow-y-auto"
style={{ height: containerHeight + 2 }}
>
<div style={{ height: totalHeight, position: 'relative' }}>
<div style={{ position: 'absolute', top: offsetY, left: 0, right: 0 }}>
{visibleEntries.map(entry => (
<FileRow key={entry.id} entry={entry} />
))}
</div>
</div>
</div>
);
}
function FileRow({ entry }: { entry: FileEntry }) {
return (
<div className="flex items-center gap-2 px-3 text-xs font-mono" style={{ height: ROW_HEIGHT }}>
<span className="flex-shrink-0 w-4 text-center">
{entry.status === 'error' && <FaTimesCircle className="text-red-400 inline" />}
{entry.status === 'uploading' && <FaSpinner className="text-blue-400 inline animate-spin" />}
{entry.status === 'pending' && <span className="inline-block w-2 h-2 rounded-full bg-white/30" />}
</span>
<span className="truncate flex-1 opacity-80" title={entry.file.name}>
{entry.file.name}
</span>
<span className="flex-shrink-0 w-16 text-right">
{entry.status === 'uploading' && <span className="text-blue-300">{entry.progress}%</span>}
{entry.status === 'error' && <span className="text-red-400">Failed</span>}
{entry.status === 'pending' && <span className="text-white/30">Queued</span>}
</span>
</div>
);
}
|