import { useCallback, useEffect, useRef, useState } from "react"; import { Icon } from "./Icon"; import { ImageAnnotator } from "./ImageAnnotator"; import { compose } from "../compose"; import { toast } from "../dialogs"; import { useT } from "../i18n"; /** Images that open in the viewer: everything in the app, except UI chrome. */ const SKIP = ".viewer-overlay, .sidebar, .topbar, button, .modal-backdrop .viewer, .model-viewer, .media-stage, .composer, .brand, .login"; interface Item { src: string; alt: string; } const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v)); /** * Popup image viewer: a click on any image of the app opens it fullscreen. * Pinch / wheel / double tap to zoom, drag to pan, arrows or swipe for the other * images of the same chat, Esc to close. Mounted once; listens for clicks globally. */ export function ImageViewer() { const t = useT(); const [list, setList] = useState([]); const [idx, setIdx] = useState(0); const [open, setOpen] = useState(false); // Chat the image belongs to (for "use in message"); drawing mode. const [sessionId, setSessionId] = useState(); const [marking, setMarking] = useState(false); const [view, setView] = useState({ x: 0, y: 0, s: 1 }); const pointers = useRef(new Map()); const gesture = useRef<{ d: number; s: number } | null>(null); const moved = useRef(false); const lastTap = useRef(0); const swipe = useRef<{ x: number; y: number } | null>(null); const reset = useCallback(() => setView({ x: 0, y: 0, s: 1 }), []); const close = useCallback(() => setOpen(false), []); const go = useCallback( (d: number) => { setIdx((i) => clamp(i + d, 0, list.length - 1)); reset(); }, [list.length, reset], ); useEffect(() => { const onClick = (e: MouseEvent) => { const img = (e.target as HTMLElement | null)?.closest?.("img"); if (!img || img.closest(SKIP) || e.defaultPrevented || e.button !== 0) return; if (img.naturalWidth && img.naturalWidth < 24) return; // icons e.preventDefault(); // the surrounding link would open a new tab e.stopPropagation(); const scope = img.closest(".chat, .files-main, .gallery, .main") ?? document; const all = [...scope.querySelectorAll("img")].filter((i) => !i.closest(SKIP) && i.src && (i.naturalWidth === 0 || i.naturalWidth >= 24)); const seen = new Set(); const items: Item[] = []; let start = 0; for (const i of all) { if (seen.has(i.currentSrc || i.src)) { if (i === img) start = items.findIndex((x) => x.src === (i.currentSrc || i.src)); continue; } seen.add(i.currentSrc || i.src); if (i === img) start = items.length; items.push({ src: i.currentSrc || i.src, alt: i.alt }); } setSessionId((img.closest("[data-session-id]") as HTMLElement | null)?.dataset.sessionId); setMarking(false); setList(items.length ? items : [{ src: img.currentSrc || img.src, alt: img.alt }]); setIdx(Math.max(0, start)); reset(); setOpen(true); }; // Capture phase: before the link around a thumbnail navigates. document.addEventListener("click", onClick, true); return () => document.removeEventListener("click", onClick, true); }, [reset]); useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => { if (marking) return; if (e.key === "Escape") close(); else if (e.key === "ArrowLeft") go(-1); else if (e.key === "ArrowRight") go(1); else if (e.key === "+" || e.key === "=") setView((v) => ({ ...v, s: clamp(v.s * 1.25, 1, 8) })); else if (e.key === "-") setView((v) => ({ ...v, s: clamp(v.s / 1.25, 1, 8), ...(v.s / 1.25 <= 1 ? { x: 0, y: 0 } : {}) })); else return; e.preventDefault(); }; 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; }; }, [open, close, go, marking]); if (!open || !list[idx]) return null; const cur = list[idx]; /** The image as a file for the composer (variants, questions about it, …). */ async function useInChat() { try { const blob = await (await fetch(cur.src, { credentials: "same-origin" })).blob(); const ext = blob.type.split("/")[1]?.split("+")[0] || "png"; compose({ sessionId: sessionId!, files: [new File([blob], `image.${ext}`, { type: blob.type || "image/png" })] }); toast(t("viewer.attached"), "success"); close(); } catch { toast(t("viewer.annotateFailed")); } } const dist = () => { const [a, b] = [...pointers.current.values()]; return Math.hypot(a.x - b.x, a.y - b.y); }; return (
{ if (!moved.current) close(); }} onWheel={(e) => setView((v) => { const s = clamp(v.s * (e.deltaY < 0 ? 1.15 : 1 / 1.15), 1, 8); return s === 1 ? { x: 0, y: 0, s } : { ...v, s }; })} >
e.stopPropagation()}> {list.length > 1 ? `${idx + 1} / ${list.length}` : ""} {cur.alt && !/^(image|SVG)$/i.test(cur.alt) ? cur.alt : ""} {sessionId && ( <> )}
{marking && ( setMarking(false)} onDone={(file) => { compose({ sessionId: sessionId!, files: [file] }); toast(t("viewer.attached"), "success"); close(); }} /> )} {!marking && idx > 0 && ( )} {!marking && idx < list.length - 1 && ( )} {!marking && {cur.alt} 1 ? "grab" : "zoom-in" }} onClick={(e) => e.stopPropagation()} onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY }); moved.current = false; if (pointers.current.size === 2) gesture.current = { d: dist(), s: view.s }; else swipe.current = { x: e.clientX, y: e.clientY }; }} onPointerMove={(e) => { const p = pointers.current.get(e.pointerId); if (!p) return; const dx = e.clientX - p.x; const dy = e.clientY - p.y; pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (pointers.current.size === 2 && gesture.current) { moved.current = true; const s = clamp((gesture.current.s * dist()) / gesture.current.d, 1, 8); setView((v) => (s === 1 ? { x: 0, y: 0, s } : { ...v, s })); } else if (view.s > 1) { if (Math.abs(dx) + Math.abs(dy) > 1) moved.current = true; setView((v) => ({ ...v, x: v.x + dx, y: v.y + dy })); } }} onPointerUp={(e) => { pointers.current.delete(e.pointerId); gesture.current = null; const s0 = swipe.current; swipe.current = null; if (s0 && view.s === 1) { const dx = e.clientX - s0.x; const dy = e.clientY - s0.y; if (Math.abs(dx) > 60 && Math.abs(dx) > Math.abs(dy) * 1.5) { moved.current = true; go(dx < 0 ? 1 : -1); } else if (dy > 90 && Math.abs(dy) > Math.abs(dx) * 1.5) { moved.current = true; close(); } } // Double tap / double click: zoom in or back. if (!moved.current) { const now = Date.now(); if (now - lastTap.current < 300) setView((v) => (v.s > 1 ? { x: 0, y: 0, s: 1 } : { ...v, s: 2.5 })); lastTap.current = now; } }} onPointerCancel={(e) => { pointers.current.delete(e.pointerId); gesture.current = null; }} />}
); }