import { memo, useCallback, useEffect, useEffectEvent, useState } from "react"; import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; interface ExpandedImageDialogProps { preview: ExpandedImagePreview; onClose: () => void; } function useExpandedImagePreviewNavigation(sourcePreview: ExpandedImagePreview) { const [navigationState, setNavigationState] = useState(() => ({ sourcePreview, index: sourcePreview.index, })); const index = navigationState.sourcePreview === sourcePreview ? navigationState.index : sourcePreview.index; const navigateImage = useCallback( (direction: -1 | 1) => { setNavigationState((existing) => { if (sourcePreview.images.length <= 1) return existing; const currentIndex = existing.sourcePreview === sourcePreview ? existing.index : sourcePreview.index; const nextIndex = (currentIndex + direction + sourcePreview.images.length) % sourcePreview.images.length; if (nextIndex === currentIndex && existing.sourcePreview === sourcePreview) { return existing; } return { sourcePreview, index: nextIndex }; }); }, [sourcePreview], ); return { images: sourcePreview.images, index, navigateImage, }; } function useExpandedImageKeyboardShortcuts(input: { imageCount: number; navigateImage: (direction: -1 | 1) => void; onClose: () => void; }) { const onKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); input.onClose(); return; } if (input.imageCount <= 1) return; if (event.key === "ArrowLeft") { event.preventDefault(); event.stopPropagation(); input.navigateImage(-1); return; } if (event.key !== "ArrowRight") return; event.preventDefault(); event.stopPropagation(); input.navigateImage(1); }); useEffect(() => { window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, []); } export const ExpandedImageDialog = memo(function ExpandedImageDialog({ preview: initialPreview, onClose, }: ExpandedImageDialogProps) { const { images, index, navigateImage } = useExpandedImagePreviewNavigation(initialPreview); useExpandedImageKeyboardShortcuts({ imageCount: images.length, navigateImage, onClose, }); const item = images[index]; if (!item) return null; return (
)}
{item.name}

{item.name} {images.length > 1 ? ` (${index + 1}/${images.length})` : ""}

{images.length > 1 && ( )}
); });