"use client"; import { useEffect, useCallback } from "react"; import { createPortal } from "react-dom"; import { X, ChevronLeft, ChevronRight } from "lucide-react"; export type LightboxItem = { src: string; alt?: string; }; type ImageLightboxProps = { items: LightboxItem[]; index: number; onClose: () => void; onIndexChange: (index: number) => void; }; /** 全屏图箱:Esc 关闭,多图时左右切换 */ export default function ImageLightbox({ items, index, onClose, onIndexChange, }: ImageLightboxProps) { const total = items.length; const current = items[index]; const hasNav = total > 1; const goPrev = useCallback(() => { if (!hasNav) return; onIndexChange((index - 1 + total) % total); }, [hasNav, index, total, onIndexChange]); const goNext = useCallback(() => { if (!hasNav) return; onIndexChange((index + 1) % total); }, [hasNav, index, total, onIndexChange]); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); else if (e.key === "ArrowLeft") goPrev(); else if (e.key === "ArrowRight") goNext(); }; window.addEventListener("keydown", onKey); const prev = document.body.style.overflow; document.body.style.overflow = "hidden"; return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = prev; }; }, [onClose, goPrev, goNext]); if (!current || typeof document === "undefined") return null; return createPortal(