'use client'; import { useState, useEffect, useMemo, useCallback, useRef } from 'react'; import { createPortal } from 'react-dom'; import { Dialog, DialogBackdrop, DialogPanel } from '@headlessui/react'; import { Cog } from 'lucide-react'; import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/react'; import classNames from 'classnames'; import { openConfirm } from './ConfirmModal'; import { apiClient } from '@/utils/api'; import { isVideo, isAudio } from '@/utils/basic'; import AudioPlayer from './AudioPlayer'; import { TransformWrapper, TransformComponent } from 'react-zoom-pan-pinch'; interface Props { imgPath: string | null; // current image path imageList: string[]; // all dataset image paths onChange: (nextPath: string | null) => void; // parent setter refreshImages?: () => void; onCaptionSaved?: (imgPath: string, caption: string) => void; } export default function DatasetImageViewer({ imgPath, imageList, onChange, refreshImages, onCaptionSaved }: Props) { const [mounted, setMounted] = useState(false); const [isOpen, setIsOpen] = useState(Boolean(imgPath)); const [caption, setCaption] = useState(''); const [savedCaption, setSavedCaption] = useState(''); const [isCaptionLoaded, setIsCaptionLoaded] = useState(false); const captionRef = useRef(''); const savedCaptionRef = useRef(''); const currentImgPathRef = useRef(null); const captionAbortRef = useRef(null); useEffect(() => setMounted(true), []); // open/close based on external value useEffect(() => { setIsOpen(Boolean(imgPath)); }, [imgPath]); // after close, clear parent state post-transition useEffect(() => { if (!isOpen && imgPath) { const t = setTimeout(() => onChange(null), 300); return () => clearTimeout(t); } }, [isOpen, imgPath, onChange]); // Keep refs in sync so we can save the latest caption on unmount/navigation useEffect(() => { captionRef.current = caption; }, [caption]); useEffect(() => { savedCaptionRef.current = savedCaption; }, [savedCaption]); const filename = useMemo(() => { if (!imgPath) return ''; if (imgPath.includes('\\')) { const parts = imgPath.split('\\'); return parts[parts.length - 1]; } return imgPath.split('/').pop() || ''; }, [imgPath]); const currentIndex = useMemo(() => { if (!imgPath) return -1; return imageList.findIndex(img => img === imgPath); }, [imgPath, imageList]); const saveCaptionForPath = useCallback( (path: string, value: string, prevSaved: string) => { const trimmed = value.trim(); if (trimmed === prevSaved.trim()) return; apiClient .post('/api/img/caption', { imgPath: path, caption: trimmed }) .then(() => { if (currentImgPathRef.current === path) { setSavedCaption(trimmed); } onCaptionSaved?.(path, trimmed); }) .catch(error => { console.error('Error saving caption:', error); }); }, [onCaptionSaved], ); const saveCaption = useCallback(() => { if (!imgPath) return; saveCaptionForPath(imgPath, caption, savedCaption); }, [imgPath, caption, savedCaption, saveCaptionForPath]); // Fetch caption whenever the image changes; save any pending edits on the previous image first useEffect(() => { const previousPath = currentImgPathRef.current; if (previousPath && previousPath !== imgPath) { saveCaptionForPath(previousPath, captionRef.current, savedCaptionRef.current); } currentImgPathRef.current = imgPath; if (!imgPath) { setCaption(''); setSavedCaption(''); setIsCaptionLoaded(false); return; } captionAbortRef.current?.abort(); const controller = new AbortController(); captionAbortRef.current = controller; setIsCaptionLoaded(false); setCaption(''); setSavedCaption(''); apiClient .post('/api/caption/get', { imgPath }, { signal: controller.signal }) .then(res => res.data) .then(data => { if (controller.signal.aborted) return; const text = data ? `${data}` : ''; setCaption(text); setSavedCaption(text); setIsCaptionLoaded(true); }) .catch(error => { if (controller.signal.aborted) return; console.error('Error fetching caption:', error); setIsCaptionLoaded(true); }); return () => { controller.abort(); }; }, [imgPath, saveCaptionForPath]); // Save any pending caption when the viewer fully unmounts useEffect(() => { return () => { const path = currentImgPathRef.current; if (path) { saveCaptionForPath(path, captionRef.current, savedCaptionRef.current); } }; }, [saveCaptionForPath]); const onCancel = useCallback(() => { saveCaption(); setIsOpen(false); }, [saveCaption]); const setImageAtIndex = useCallback( (idx: number) => { if (idx < 0 || idx >= imageList.length) return; onChange(imageList[idx]); }, [imageList, onChange], ); const handlePrev = useCallback(() => { if (currentIndex <= 0) return; setImageAtIndex(currentIndex - 1); }, [currentIndex, setImageAtIndex]); const handleNext = useCallback(() => { if (currentIndex === -1 || currentIndex >= imageList.length - 1) return; setImageAtIndex(currentIndex + 1); }, [currentIndex, imageList.length, setImageAtIndex]); const handleDelete = useCallback(() => { if (!imgPath) return; openConfirm({ title: 'Delete Image', message: `Are you sure you want to delete this image? This action cannot be undone.`, type: 'warning', confirmText: 'Delete', onConfirm: () => { apiClient .post('/api/img/delete', { imgPath }) .then(() => { console.log('Image deleted:', imgPath); onChange(null); if (refreshImages) refreshImages(); }) .catch(error => { console.error('Error deleting image:', error); }); }, }); }, [imgPath, onChange, refreshImages]); // keyboard events while open — skip nav while caption textarea is focused useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (!isOpen) return; const target = event.target as HTMLElement | null; const tag = target?.tagName; const isTyping = tag === 'TEXTAREA' || tag === 'INPUT' || (target?.isContentEditable ?? false); if (event.key === 'Escape') { onCancel(); return; } if (isTyping) return; switch (event.key) { case 'ArrowLeft': case 'ArrowUp': handlePrev(); break; case 'ArrowRight': case 'ArrowDown': handleNext(); break; case 'Delete': case 'Backspace': handleDelete(); break; default: break; } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, [isOpen, onCancel, handlePrev, handleNext, handleDelete]); // Touch swipe navigation const touchStartRef = useRef<{ x: number; y: number } | null>(null); const multiTouchRef = useRef(false); const zoomedRef = useRef(false); const SWIPE_THRESHOLD = 40; const onTouchStart = useCallback((e: React.TouchEvent) => { if (e.touches.length > 1) { multiTouchRef.current = true; touchStartRef.current = null; return; } multiTouchRef.current = false; const t = e.touches[0]; if (!t) return; touchStartRef.current = { x: t.clientX, y: t.clientY }; }, []); const onTouchEnd = useCallback( (e: React.TouchEvent) => { const start = touchStartRef.current; touchStartRef.current = null; if (multiTouchRef.current || zoomedRef.current) { if (e.touches.length === 0) multiTouchRef.current = false; return; } if (!start) return; const t = e.changedTouches[0]; if (!t) return; const dx = t.clientX - start.x; const dy = t.clientY - start.y; const absX = Math.abs(dx); const absY = Math.abs(dy); if (absX < SWIPE_THRESHOLD && absY < SWIPE_THRESHOLD) return; if (absX > absY) { if (dx < 0) handleNext(); else handlePrev(); } else { if (dy < 0) handleNext(); else handlePrev(); } }, [handleNext, handlePrev], ); const handleCaptionKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); saveCaption(); } }; const isCaptionCurrent = caption.trim() === savedCaption.trim(); if (!mounted) return null; return createPortal(
{imgPath && (isAudio(imgPath) ? (
) : isVideo(imgPath) ? (
File: {filename}
{currentIndex >= 0 ? `${currentIndex + 1} / ${imageList.length}` : ''}