"use client"; import Image from "next/image"; import { Download, X } from "lucide-react"; import { useEffect, useRef, useSyncExternalStore } from "react"; import { createPortal } from "react-dom"; import type { MediaPreview } from "@/lib/media"; type MediaPreviewModalProps = { preview: MediaPreview; onClose: () => void; }; const subscribeToClient = () => () => undefined; const getClientSnapshot = () => true; const getServerSnapshot = () => false; export default function MediaPreviewModal({ preview, onClose }: MediaPreviewModalProps) { const closeButtonRef = useRef(null); const onCloseRef = useRef(onClose); const canUseDOM = useSyncExternalStore( subscribeToClient, getClientSnapshot, getServerSnapshot, ); useEffect(() => { onCloseRef.current = onClose; }, [onClose]); useEffect(() => { const previousOverflow = document.body.style.overflow; const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; const shouldRestoreFocus = previousFocus?.matches(":focus-visible") ?? false; document.body.style.overflow = "hidden"; closeButtonRef.current?.focus(); const handleEscape = (event: KeyboardEvent) => { if (event.key !== "Escape") return; event.preventDefault(); event.stopImmediatePropagation(); onCloseRef.current(); }; document.addEventListener("keydown", handleEscape, true); return () => { document.removeEventListener("keydown", handleEscape, true); document.body.style.overflow = previousOverflow; if (shouldRestoreFocus) previousFocus?.focus(); }; }, []); const downloadUrl = preview.downloadUrl; if (!canUseDOM) return null; return createPortal(
event.stopPropagation()} > {downloadUrl ? ( ) : null}
{preview.type === "image" ? ( {preview.name} ) : (
event.stopPropagation()} >
)}
, document.body, ); }