'use client'; import { useState, useEffect, useMemo, useCallback, useRef } from 'react'; import { createPortal } from 'react-dom'; import { Dialog, DialogBackdrop, DialogPanel } from '@headlessui/react'; import { SampleConfig, SampleItem } from '@/types'; import { Cog } from 'lucide-react'; import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/react'; 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 numSamples: number; // number of samples per row sampleImages: string[]; // all sample images sampleConfig: SampleConfig | null; onChange: (nextPath: string | null) => void; // parent setter refreshSampleImages?: () => void; } export default function SampleImageViewer({ imgPath, numSamples, sampleImages, sampleConfig, onChange, refreshSampleImages, }: Props) { const [mounted, setMounted] = useState(false); const [isOpen, setIsOpen] = useState(Boolean(imgPath)); const [showingControlIdx, setShowingControlIdx] = useState(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]); const onCancel = useCallback(() => { setShowingControlIdx(null); setIsOpen(false); }, []); const imgInfo = useMemo(() => { // handle windows C:\\Apps\\AI-Toolkit\\AI-Toolkit\\output\\LoRA-Name\\samples\\1763563000704__000004000_0.jpg const ii = { filename: '', step: 0, promptIdx: 0 }; if (imgPath) { // handle windows let filename: string | null = null; if (imgPath.includes('\\')) { const parts = imgPath.split('\\'); filename = parts[parts.length - 1]; } else { filename = imgPath.split('/').pop() || null; } if (!filename) { console.error('Filename could not be determined from imgPath:', imgPath); return ii; } ii.filename = filename; const parts = filename .split('.')[0] .split('_') .filter(p => p !== ''); if (parts.length === 3) { ii.step = parseInt(parts[1]); ii.promptIdx = parseInt(parts[2]); } else { console.error('Unexpected filename format for sample image:', filename); } } return ii; }, [imgPath]); const setImageAtIndex = useCallback( (idx: number) => { if (idx < 0 || idx >= sampleImages.length) return; setShowingControlIdx(null); onChange(sampleImages[idx]); }, [sampleImages, numSamples, onChange], ); const currentIndex = useMemo(() => { if (!imgPath) return -1; return sampleImages.findIndex(img => img === imgPath); }, [imgPath, sampleImages]); const handleArrowUp = useCallback(() => { if (currentIndex === -1) return; setImageAtIndex(currentIndex - numSamples); }, [numSamples, currentIndex, setImageAtIndex]); const handleArrowDown = useCallback(() => { if (currentIndex === -1) return; setImageAtIndex(currentIndex + numSamples); }, [numSamples, currentIndex, setImageAtIndex]); const handleArrowLeft = useCallback(() => { if (currentIndex === -1) return; if (imgInfo.promptIdx === 0) return; const minIdx = currentIndex - imgInfo.promptIdx; const nextIdx = currentIndex - 1; if (nextIdx < minIdx) return; setImageAtIndex(nextIdx); }, [sampleImages, currentIndex, imgInfo.promptIdx, setImageAtIndex]); const handleArrowRight = useCallback(() => { if (currentIndex === -1) return; const stepMinIdx = currentIndex - imgInfo.promptIdx; const maxIdx = stepMinIdx + numSamples - 1; const nextIdx = currentIndex + 1; if (nextIdx > maxIdx) return; setImageAtIndex(nextIdx); }, [sampleImages, currentIndex, imgInfo.promptIdx, setImageAtIndex]); const handleDelete = useCallback(() => { if (!imgPath) return; openConfirm({ title: 'Delete Sample', message: `Are you sure you want to delete this sample? This action cannot be undone.`, type: 'warning', confirmText: 'Delete', onConfirm: () => { apiClient .post('/api/img/delete', { imgPath: imgPath }) .then(() => { console.log('Image deleted:', imgPath); onChange(null); if (refreshSampleImages) { refreshSampleImages(); } }) .catch(error => { console.error('Error deleting image:', error); }); }, }); }, [imgPath, onChange, refreshSampleImages]); const sampleItem = useMemo(() => { if (!sampleConfig) return null; if (imgInfo.promptIdx < 0) return null; if (imgInfo.promptIdx >= sampleConfig.samples.length) return null; return sampleConfig.samples[imgInfo.promptIdx]; }, [sampleConfig, imgInfo.promptIdx]); const controlImages = useMemo(() => { if (!imgPath) return []; let controlImageArr: string[] = []; if (sampleItem?.ctrl_img) { // can be a an array of paths, or a single path if (Array.isArray(sampleItem.ctrl_img)) { controlImageArr = sampleItem.ctrl_img; } else { controlImageArr = [sampleItem.ctrl_img]; } } else if (sampleItem?.ctrl_img_1) { controlImageArr.push(sampleItem.ctrl_img_1); } if (sampleItem?.ctrl_img_2) { controlImageArr.push(sampleItem.ctrl_img_2); } if (sampleItem?.ctrl_img_3) { controlImageArr.push(sampleItem.ctrl_img_3); } // filter out nulls controlImageArr = controlImageArr.filter(ci => ci !== null && ci !== undefined && ci !== ''); return controlImageArr; }, [sampleItem, imgPath]); const seed = useMemo(() => { if (!sampleItem) return '?'; if (sampleItem.seed !== undefined) return sampleItem.seed; if (sampleConfig?.walk_seed) { return sampleConfig.seed + imgInfo.promptIdx; } return sampleConfig?.seed ?? '?'; }, [sampleItem, sampleConfig]); const displayedImgPath = useMemo(() => { if (showingControlIdx !== null && controlImages[showingControlIdx]) { return controlImages[showingControlIdx]; } return imgPath; }, [showingControlIdx, controlImages, imgPath]); // keyboard events while open useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (!isOpen) return; switch (event.key) { case 'Escape': onCancel(); break; case 'ArrowUp': handleArrowUp(); break; case 'ArrowDown': handleArrowDown(); break; case 'ArrowLeft': handleArrowLeft(); break; case 'ArrowRight': handleArrowRight(); break; case 'Delete': case 'Backspace': handleDelete(); break; default: break; } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, [isOpen, onCancel, handleArrowUp, handleArrowDown, handleArrowLeft, handleArrowRight, 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; // px before a swipe counts 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 a pinch happened or we're zoomed in, don't treat as a swipe. 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) { // Horizontal swipe: left = next (ArrowRight), right = prev (ArrowLeft) if (dx < 0) handleArrowRight(); else handleArrowLeft(); } else { // Vertical swipe: up = next step (ArrowDown), down = prev step (ArrowUp) if (dy < 0) handleArrowDown(); else handleArrowUp(); } }, [handleArrowLeft, handleArrowRight, handleArrowUp, handleArrowDown], ); if (!mounted) return null; return createPortal(
{displayedImgPath && (isAudio(displayedImgPath) ? (
) : isVideo(displayedImgPath) ? (
{/* # make full width */}
{sampleItem?.prompt && (
Prompt: {sampleItem.prompt}
)}
{controlImages.length > 0 && (
{showingControlIdx !== null && ( Main setShowingControlIdx(null)} title="Main image" /> )} {controlImages.map((ci, idx) => ( {`Control setShowingControlIdx(idx)} title={`Control image ${idx + 1}`} /> ))}
)}
Step: {imgInfo.step.toLocaleString()}
Sample #: {imgInfo.promptIdx + 1}
Seed: {seed}
{imgPath && isAudio(imgPath) && ( Download )}
Delete Sample
, document.body, ); }