import React, { useCallback, useEffect, useId, useRef, useState, } from 'react'; import {createPortal} from 'react-dom'; import { TransformWrapper, TransformComponent, type ReactZoomPanPinchRef, } from 'react-zoom-pan-pinch'; import styles from './styles.module.css'; export interface ZoomableImageProps { src: string; alt: string; title?: string; /** Height of the inline preview frame (CSS). Default 360px. */ previewHeight?: string; } /** * Inline preview of a large diagram/PNG with an **Open & zoom** control that * opens a fullscreen lightbox (pan + wheel zoom via react-zoom-pan-pinch). * Preview fills the card width and crops from the top so tall diagrams stay readable. */ export default function ZoomableImage({ src, alt, title, previewHeight = '360px', }: ZoomableImageProps): JSX.Element { const [open, setOpen] = useState(false); const [portalReady, setPortalReady] = useState(false); // Start low so Fit can shrink below 1×; locked to fit scale after first fit. const [minScale, setMinScale] = useState(0.05); const titleId = useId(); const label = title || alt; const imgRef = useRef(null); const apiRef = useRef(null); const close = useCallback(() => setOpen(false), []); useEffect(() => { setPortalReady(true); }, []); useEffect(() => { if (!open) return; setMinScale(0.05); const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') close(); }; const prevOverflow = document.body.style.overflow; document.body.style.overflow = 'hidden'; window.addEventListener('keydown', onKey); return () => { document.body.style.overflow = prevOverflow; window.removeEventListener('keydown', onKey); }; }, [open, close]); const lockMinToFitScale = useCallback((scale: number) => { if (!Number.isFinite(scale) || scale <= 0) return; // Floor at fit — no zoom-out past the full-diagram view. setMinScale(Number(scale.toFixed(4))); }, []); const fitToView = useCallback( (animate = true) => { const api = apiRef.current; const img = imgRef.current; if (!api || !img) return; // zoomToElement scales the element into the TransformComponent viewport. try { api.zoomToElement( img, undefined, animate ? 200 : 0, 'easeOut', ); const applyFloor = () => { const scale = api.state.scale; lockMinToFitScale(scale); }; if (animate) { window.setTimeout(applyFloor, 220); } else { applyFloor(); } } catch { /* image or stage not ready */ } }, [lockMinToFitScale], ); const lightbox = open && portalReady ? createPortal(
{ apiRef.current = ref; requestAnimationFrame(() => fitToView(false)); }} > {({zoomIn, zoomOut}) => ( <>

{label}

{alt} fitToView(false)} />

Scroll to zoom · drag to pan · Esc to close

)}
, document.body, ) : null; return (
{title ?

{title}

: }
{alt}
{lightbox}
); }