import type { ArtifactCatalogItem, RetainedArtifactReference } from "@opengeni/sdk"; import { ChevronLeftIcon, ChevronRightIcon, DownloadIcon, Loader2Icon, XIcon } from "lucide-react"; import { Dialog } from "radix-ui"; import { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, } from "react"; import { isRetainedImageContentType, useRetainedImageObjectUrl } from "../../../artifacts"; import { useZoomPan, useZoomPanShortcuts, ZoomControls, ZoomPanSurface, type ZoomPanController, } from "../../../components/zoom-pan-image"; import { createWorkspaceRetainedArtifactLoader } from "../../../timeline"; import { ownsArrowKeys } from "../../../lib/keyboard-targets"; import { Button } from "../../../ui/button"; import { userErrorText } from "../../../ui/api-error"; import { useAppContext } from "../../app-context"; import { EditableArtifactSurface } from "../../lib/app-surfaces"; import { artifactKey, isEditableArtifactKind } from "../../lib/artifact-catalog"; import { saveRetainedArtifact } from "../../lib/retained-artifact-download"; import { toast } from "../../lib/toast"; import { LoadingPanel } from "../common"; import { ArtifactFullWindowBar, ArtifactFullWindowDialog } from "./artifact-full-view"; import { ArtifactTypeIcon } from "./artifact-page-chrome"; import { cachedRetainedArtifactLoader, cachedRetainedMetadata, retainedImageCache, retainedImageScope, } from "./retained-image-cache"; const RetainedArtifactRoute = lazy(() => import("../../routes/retained-artifact").then((module) => ({ default: module.RetainedArtifactRoute, })), ); const ArtifactDetailRoute = lazy(() => import("../../routes/artifacts").then((module) => ({ default: module.ArtifactDetailRoute })), ); /** Images on either side of the one on screen start loading, so stepping is instant. */ const PRELOAD_NEIGHBOURS = 1; /** A horizontal touch drag at least this long steps to the neighbouring artifact. */ const SWIPE_DISTANCE = 48; /** True while another dialog or menu (a share confirmation, a ⋯ menu) is open over the viewer. */ function layerAbove(viewer: HTMLElement | null): boolean { if (!viewer) return false; for (const layer of document.querySelectorAll( '[role="dialog"], [role="alertdialog"], [role="menu"]', )) { if (layer !== viewer && !viewer.contains(layer) && !layer.contains(viewer)) return true; } return false; } type AppClient = ReturnType["client"]; type ImageSources = ReturnType; function imageSources(client: AppClient, accessKeyVersion: number, workspaceId: string) { const cache = retainedImageCache(client); return { metadata: (artifactId: string) => cachedRetainedMetadata( cache, retainedImageScope(accessKeyVersion, workspaceId, artifactId), () => client.getRetainedArtifact(workspaceId, artifactId), ), load: cachedRetainedArtifactLoader( cache, accessKeyVersion, workspaceId, createWorkspaceRetainedArtifactLoader(client, workspaceId), ), }; } function useImageSources(workspaceId: string): ImageSources { const { client, accessKeyVersion } = useAppContext(); return useMemo( () => imageSources(client, accessKeyVersion, workspaceId), [client, accessKeyVersion, workspaceId], ); } /** * Warms the page's retained-image cache for an image the viewer may step to * next, so its bytes are already here when it is shown. Failures are ignored: * showing the image asks again and reports them. */ function preloadImage(sources: ImageSources, artifactId: string) { void sources .metadata(artifactId) .then((artifact) => { if (!artifact.available || !isRetainedImageContentType(artifact.contentType)) return null; return sources.load(artifact, new AbortController().signal); }) .then((source) => { // A signed URL warms the browser's own cache instead. if (source && !(source instanceof Uint8Array) && source.url.trim()) { const image = new Image(); image.src = source.url; } }) .catch(() => {}); } /** * One large viewer for the artifacts a list shows. It steps through exactly * that list in its order, so search, filters and sorting carry over, with the * previous/next buttons, the Left/Right arrow keys or a swipe. Images fill the * window; every other kind shows the preview it has in the session panel. A * Radix dialog over the whole window, like an artifact's full view, so Escape * closes it and focus returns to the list. */ export function ArtifactViewer({ workspaceId, items, currentKey, onCurrentKeyChange, onClose, actions, }: { workspaceId: string; items: readonly ArtifactCatalogItem[]; /** `artifactKey` of the artifact on screen. */ currentKey: string; onCurrentKeyChange: (key: string) => void; onClose: () => void; /** The current artifact's own menu (Open, Copy link, …), at the end of the header. */ actions?: ReactNode; }) { const index = items.findIndex((item) => artifactKey(item) === currentKey); const item = index >= 0 ? items[index]! : null; const content = useRef(null); const body = useRef(null); const sources = useImageSources(workspaceId); // Zoom belongs to the image on screen: stepping starts the next one fitted. const zoom = useZoomPan(currentKey); // The artifact left the list (archived, deleted, refreshed away): nothing to show. useEffect(() => { if (!item) onClose(); }, [item, onClose]); const step = useCallback( (delta: 1 | -1) => { const next = index >= 0 ? items[index + delta] : undefined; if (next) onCurrentKeyChange(artifactKey(next)); }, [index, items, onCurrentKeyChange], ); const isImage = item?.kind === "image"; useZoomPanShortcuts(zoom, isImage); useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return; if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return; // A held key steps once, rather than loading every artifact it races past. if (event.shiftKey || event.repeat || event.isComposing || event.keyCode === 229) return; const target = event.target; // Keys in another dialog (a share confirmation), a field or a menu stay // there, and so do keys inside a document or Site being worked on. Focus // that fell to the page (its button became disabled) still belongs here, // unless another dialog or menu is open on top of the viewer. const onPage = (target === document.body || target === document.documentElement) && !layerAbove(content.current); if (!onPage && (!(target instanceof Node) || !content.current?.contains(target))) return; if (ownsArrowKeys(target)) return; if (!isImage && target instanceof Node && body.current?.contains(target)) return; event.preventDefault(); step(event.key === "ArrowLeft" ? -1 : 1); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [isImage, step]); // Clicking Next at the end (or Fit once fitted) disables the focused button and // drops focus to the page; bring it back so Tab and the keys stay in the viewer. const zoomed = zoom.view !== null && !zoom.view.fit; useLayoutEffect(() => { const viewer = content.current; const active = document.activeElement; if (!viewer) return; if ( active === document.body || (active instanceof HTMLButtonElement && active.disabled && viewer.contains(active)) ) viewer.focus(); }, [index, zoomed]); // Only the neighbours' ids matter: the list is rebuilt on every parent render. const neighbours = useMemo(() => { if (index < 0) return ""; const ids: string[] = []; for (let offset = 1; offset <= PRELOAD_NEIGHBOURS; offset++) { for (const neighbour of [items[index + offset], items[index - offset]]) { if (neighbour?.kind === "image") ids.push(neighbour.id); } } return ids.join("\n"); }, [index, items]); const preloaded = useRef(new Set()); useEffect(() => { for (const id of neighbours ? neighbours.split("\n") : []) { if (preloaded.current.has(id)) continue; preloaded.current.add(id); preloadImage(sources, id); } }, [neighbours, sources]); // A one-finger horizontal swipe on a touch screen steps too. A second finger // makes it a pinch, which never steps. const swipe = useRef<{ pointerId: number; x: number; y: number } | null>(null); const touches = useRef(new Set()); const onPointerDown = (event: PointerEvent) => { if (event.pointerType !== "touch") return; // A first finger starts afresh: a lift missed while a document was shown is forgotten. if (event.isPrimary) touches.current.clear(); touches.current.add(event.pointerId); // A zoomed image pans under the finger instead. swipe.current = touches.current.size === 1 && !zoomed ? { pointerId: event.pointerId, x: event.clientX, y: event.clientY } : null; }; const onPointerEnd = (event: PointerEvent) => { if (event.pointerType !== "touch") return; touches.current.delete(event.pointerId); const start = swipe.current; if (!start || start.pointerId !== event.pointerId) return; swipe.current = null; if (event.type !== "pointerup" || zoomed) return; const dx = event.clientX - start.x; const dy = event.clientY - start.y; if (Math.abs(dx) >= SWIPE_DISTANCE && Math.abs(dx) > Math.abs(dy) * 1.5) step(dx < 0 ? 1 : -1); }; if (!item) return null; const count = items.length; return ( { // The keys work at once, and no button lights up a focus ring. event.preventDefault(); content.current?.focus(); }} > {item.title} {item.kind === "image" ? ( ) : null}
{index + 1} of {count} {item.kind === "image" ? ( ) : null} {actions}
); } /** The image itself, or the preview the artifact has in the session panel. */ function ViewerBody({ workspaceId, item, zoom, }: { workspaceId: string; item: ArtifactCatalogItem; zoom: ZoomPanController; }) { if (item.kind === "image") return ; if (isEditableArtifactKind(item.kind)) return ; return ( }> {item.kind === "site" ? ( ) : (
)}
); } /** True once a wait is long enough to notice, so a cached image never flashes a spinner. */ function useNoticeable(waiting: boolean) { const [noticeable, setNoticeable] = useState(false); useEffect(() => { if (!waiting) { setNoticeable(false); return; } const timer = setTimeout(() => setNoticeable(true), 250); return () => clearTimeout(timer); }, [waiting]); return noticeable; } type ImageState = | { kind: "loading" } | { kind: "ready"; artifact: RetainedArtifactReference } | { kind: "failed" }; function usableImage(artifact: { available: boolean }, artifactId: string) { const reference = artifact as RetainedArtifactReference; return ( artifact.available && reference.artifactId === artifactId && isRetainedImageContentType(reference.contentType) ); } function ViewerImage({ workspaceId, item, zoom, }: { workspaceId: string; item: ArtifactCatalogItem; zoom: ZoomPanController; }) { const { client, accessKeyVersion } = useAppContext(); const sources = useImageSources(workspaceId); const scope = retainedImageScope(accessKeyVersion, workspaceId, item.id); const [retry, setRetry] = useState(0); // A preloaded neighbour starts from what this page already has. const [state, setState] = useState(() => { const cached = retainedImageCache(client).peek(`${scope}meta`); return cached && usableImage(cached, item.id) ? { kind: "ready", artifact: cached } : { kind: "loading" }; }); useEffect(() => { let active = true; void sources .metadata(item.id) .then((artifact) => { if (!active) return; setState((current) => !usableImage(artifact, item.id) ? { kind: "failed" } : current.kind === "ready" && current.artifact === artifact ? current : { kind: "ready", artifact: artifact as RetainedArtifactReference }, ); }) .catch(() => { if (active) setState({ kind: "failed" }); }); return () => { active = false; }; }, [sources, item.id, retry]); // Retry means "fetch again": never answer it from the cache. const retryFresh = () => { retainedImageCache(client).forget(scope); setState({ kind: "loading" }); setRetry((value) => value + 1); }; const noticeable = useNoticeable(state.kind === "loading"); if (state.kind === "failed") return ; if (state.kind === "loading") return ; return ( ); } function ImageLoading({ visible }: { visible: boolean }) { return (
{visible ? : null} Loading image…
); } function ImageUnavailable({ title, onRetry }: { title: string; onRetry: () => void }) { return (

{title} couldn't be shown.{" "}

); } /** * The image fitted to the window (small screenshots enlarged up to 2x), with * zoom and pan: click for actual size, Cmd/Ctrl + wheel, pinch, the header's * buttons or Cmd/Ctrl + plus, minus and zero. */ function ZoomableImage({ artifact, load, alt, onRetry, zoom, }: { artifact: RetainedArtifactReference; load: ImageSources["load"]; alt: string; onRetry: () => void; zoom: ZoomPanController; }) { const image = useRetainedImageObjectUrl(artifact, load); const [failed, setFailed] = useState(false); const noticeable = useNoticeable(image.kind === "loading"); if (image.kind === "loading") return ; if (image.kind !== "ready" || failed) return ; return ( setFailed(true)} imageClassName="rounded-md shadow-og-lg" /> ); } function ImageDownloadButton({ workspaceId, sources, item, }: { workspaceId: string; sources: ImageSources; item: ArtifactCatalogItem; }) { const { client } = useAppContext(); const [busy, setBusy] = useState(false); const download = async () => { if (busy) return; setBusy(true); try { const artifact = await sources.metadata(item.id); if (!usableImage(artifact, item.id)) throw new Error("This image is no longer available."); const reference = artifact as RetainedArtifactReference; // Usually the bytes on screen, already in the page's cache. const source = await sources.load(reference, new AbortController().signal); const bytes = source instanceof Uint8Array ? source : (await client.downloadRetainedArtifact(workspaceId, reference)).bytes; saveRetainedArtifact(reference, bytes, item.title); } catch (error) { toast.error("Couldn't download the image", { description: userErrorText(error) }); } finally { setBusy(false); } }; return ( ); }