Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

feat(ui): zoom and pan in full screen and the inpaint editor (#19)

Gabriele Lozupone751773031a80
diff --git a/src/components/Compare.tsx b/src/components/Compare.tsx
index 2b36fef..e4ed28a 100644
--- a/src/components/Compare.tsx
+++ b/src/components/Compare.tsx
@@ -1,12 +1,13 @@
// Before / after views for results made from another image (edit, inpaint, expand, upscale).
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { urls } from "../lib/api";
import { diffPixels, type CompareBase, type CompareMode } from "../lib/logic";
import { setState, useStore } from "../lib/store";
import type { GenerationRecord } from "../lib/types";
import { Seg, useFit } from "./ui";
import { FullscreenButton } from "./Viewer";
+import { ZoomPan } from "./ZoomPan";
const MODES: { value: CompareMode; label: string }[] = [
{ value: "off", label: "Result" },
@@ -33,6 +34,8 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
const [holding, setHolding] = useState(false);
const [phase, setPhase] = useState<"before" | "after">("after");
const dragging = useRef(false);
+ const boxRef = useRef<HTMLDivElement>(null);
+ const contentSize = useMemo(() => ({ width: g.width, height: g.height }), [g.width, g.height]);
const after = urls.gen(g.id);
const before = urls.input(base.inputId);
@@ -60,9 +63,9 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
};
}, []);
- const setFromPointer = (e: React.PointerEvent<HTMLDivElement>) => {
- const r = e.currentTarget.getBoundingClientRect();
- setSplit(Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)));
+ const setFromPointer = (clientX: number) => {
+ const r = boxRef.current?.getBoundingClientRect();
+ if (r && r.width > 0) setSplit(Math.min(1, Math.max(0, (clientX - r.left) / r.width)));
};
const showBefore = holding || (mode === "flicker" && phase === "before");
@@ -70,20 +73,31 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
const pct = (v: number) => `${v * 100}%`;
const { x, y, w, h } = base.rect;
- return (
- <div className={fullscreen ? "viewer-frame" : "stage-frame"} ref={ref}>
+ // In full screen the box keeps the image's own size inside ZoomPan, which scales it; `k`
+ // undoes that scale for the labels and the slider handle so they stay at screen size.
+ // While zoomed in a drag pans the image; the handle still moves the split.
+ const frame = (scale: number, zoomed: boolean) => {
+ const k = 1 / scale;
+ const tag = (side: "left" | "right") => ({ transform: `scale(${k})`, transformOrigin: `top ${side}` });
+ return (
<div
- className={`compare-box ${mode === "slider" ? "slider" : ""}`}
- style={{ width: box.w, height: box.h }}
+ ref={boxRef}
+ className={`compare-box ${mode === "slider" ? "slider" : ""} ${zoomed ? "zoomed" : ""}`}
+ style={fullscreen ? { width: g.width, height: g.height } : { width: box.w, height: box.h }}
onPointerDown={(e) => {
- if (e.button !== 0) return;
+ if (e.button !== 0 || zoomed) return;
+ e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
if (mode === "slider") {
dragging.current = true;
- setFromPointer(e);
+ setFromPointer(e.clientX);
} else if (mode === "off") setHolding(true);
}}
- onPointerMove={(e) => dragging.current && setFromPointer(e)}
+ onPointerMove={(e) => {
+ if (!dragging.current) return;
+ e.stopPropagation();
+ setFromPointer(e.clientX);
+ }}
onPointerUp={() => {
dragging.current = false;
if (mode === "off") setHolding(false);
@@ -93,10 +107,10 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
setHolding(false);
}}
onDoubleClick={() => setState({ overlay: null })}
- title={mode === "off" ? "Press and hold (or hold B) to see the original" : undefined}
+ title={mode === "off" && !zoomed ? "Press and hold (or hold B) to see the original" : undefined}
>
<img className="compare-img" src={after} alt={g.prompt} draggable={false} />
- {mode === "diff" && !holding && <DiffCanvas after={after} before={before} rect={base.rect} />}
+ {mode === "diff" && !holding && <DiffCanvas after={after} before={before} rect={base.rect} tagStyle={tag("left")} />}
{/* The original stays mounted (hidden) so switching is instant. */}
<div
className="compare-before"
@@ -109,14 +123,23 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
</div>
{mode === "slider" && !holding && (
<>
- <div className="compare-handle" style={{ left: pct(split) }}>
- <span />
+ <div
+ className="compare-handle"
+ style={{ left: pct(split), width: 2 * k, marginLeft: -k }}
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ e.stopPropagation();
+ boxRef.current?.setPointerCapture(e.pointerId);
+ dragging.current = true;
+ }}
+ >
+ <span style={{ transform: `scale(${k})` }} />
</div>
- <span className="compare-tag left">Before</span>
- <span className="compare-tag right">After</span>
+ <span className="compare-tag left" style={tag("left")}>Before</span>
+ <span className="compare-tag right" style={tag("right")}>After</span>
</>
)}
- {label && <span className="compare-tag left">{label}</span>}
+ {label && <span className="compare-tag left" style={tag("left")}>{label}</span>}
{!fullscreen && (
<div className="compare-overlay" onPointerDown={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<CompareBar />
@@ -126,6 +149,20 @@ export function CompareFrame({ g, base, fullscreen = false, onFullscreen }: { g:
<FullscreenButton hint="Hold B for the original" onOpen={onFullscreen} content={<CompareFullscreen g={g} base={base} />} />
)}
</div>
+ );
+ };
+
+ if (fullscreen)
+ return (
+ <div className="viewer-frame">
+ <ZoomPan contentSize={contentSize} resetKey={g.id} enableToggleZoom={false} minimapSrc={after}>
+ {({ transform, isZoomed }) => frame(transform.scale, isZoomed)}
+ </ZoomPan>
+ </div>
+ );
+ return (
+ <div className="stage-frame" ref={ref}>
+ {frame(1, false)}
</div>
);
}
@@ -143,7 +180,7 @@ export function CompareFullscreen({ g, base }: { g: GenerationRecord; base: Comp
}
/** Highlights what changed: dimmed result, changed pixels in red. */
-function DiffCanvas({ after, before, rect }: { after: string; before: string; rect: CompareBase["rect"] }) {
+function DiffCanvas({ after, before, rect, tagStyle }: { after: string; before: string; rect: CompareBase["rect"]; tagStyle?: CSSProperties }) {
const ref = useRef<HTMLCanvasElement>(null);
const [share, setShare] = useState<number | null>(null);
const [error, setError] = useState(false);
@@ -192,7 +229,7 @@ function DiffCanvas({ after, before, rect }: { after: string; before: string; re
return (
<>
<canvas ref={ref} className="compare-diff" />
- <span className="compare-tag left">
+ <span className="compare-tag left" style={tagStyle}>
{error ? "Could not compare the images" : share === null ? "Comparing…" : share < 0.001 ? "No visible change" : `≈${share < 0.01 ? "<1" : Math.round(share * 100)}% of the image changed`}
</span>
</>
diff --git a/src/components/Gallery.tsx b/src/components/Gallery.tsx
index 77dd673..40280c1 100644
--- a/src/components/Gallery.tsx
+++ b/src/components/Gallery.tsx
@@ -284,7 +284,7 @@ function Preview(props: {
</button>
</div>
{full && (
- <Fullscreen hint="Click to zoom to 100 %" onClose={() => setFull(false)} nav={nav}>
+ <Fullscreen hint="Scroll or click to zoom · Drag to pan" onClose={() => setFull(false)} nav={nav}>
<ZoomImage key={g.id} src={urls.gen(g.id)} alt={g.prompt} />
</Fullscreen>
)}
diff --git a/src/components/InpaintEditor.tsx b/src/components/InpaintEditor.tsx
index 7d5bfc5..d5398a8 100644
--- a/src/components/InpaintEditor.tsx
+++ b/src/components/InpaintEditor.tsx
@@ -1,9 +1,11 @@
-import { Brush, Check, Contrast, Eraser, Redo2, Trash2, Undo2, X } from "lucide-react";
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { Brush, Check, Contrast, Eraser, Hand, Redo2, Trash2, Undo2, X } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, urls } from "../lib/api";
+import { shortcut } from "../lib/platform";
import { focusPrompt, getState, setState, toastError, updateComposer, useStore } from "../lib/store";
import { IconButton } from "./ui";
-import { shortcut } from "../lib/platform";
+import { isTyping } from "./Viewer";
+import { ZoomPan } from "./ZoomPan";
type Op =
| { kind: "stroke"; erase: boolean; size: number; points: [number, number][] }
@@ -12,22 +14,25 @@ type Op =
/** Mask canvas resolution cap (the backend resizes the mask to the source anyway). */
const MAX_MASK_SIDE = 2048;
+/** Soft edge of the exported mask, in mask px. Brush strokes are never exactly binary, so the
+ * service keeps this softness for the blend instead of adding its own. */
+const FEATHER = 8;
export function InpaintEditor() {
const ref0 = useStore((s) => s.composer.refs[0]);
const existingMask = useStore((s) => s.composer.mask);
const [ops, setOps] = useState<Op[]>([]);
const [redo, setRedo] = useState<Op[]>([]);
- const [erase, setErase] = useState(false);
+ const [tool, setTool] = useState<"brush" | "eraser" | "pan">("brush");
+ const [spacePressed, setSpacePressed] = useState(false);
+ // Right button held: the other tool is in use, and the toolbar shows it.
+ const [swapped, setSwapped] = useState(false);
const [brush, setBrush] = useState(48); // in screen px
- const [feather, setFeather] = useState(8); // in mask px
const [busy, setBusy] = useState(false);
const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
- const stageRef = useRef<HTMLDivElement>(null);
const current = useRef<Op | null>(null);
- const [disp, setDisp] = useState({ w: 0, h: 0 });
const srcW = ref0?.width ?? 1;
const srcH = ref0?.height ?? 1;
@@ -36,19 +41,8 @@ export function InpaintEditor() {
const mh = Math.max(1, Math.round(srcH * scale));
const src = ref0 ? (ref0.source.startsWith("gen:") ? urls.gen(ref0.source.slice(4)) : urls.input(ref0.source.slice(6))) : "";
- // Fit the image into the stage.
- useLayoutEffect(() => {
- const el = stageRef.current;
- if (!el) return;
- const ro = new ResizeObserver(() => {
- const W = el.clientWidth - 48;
- const H = el.clientHeight - 24;
- const s = Math.min(W / srcW, H / srcH);
- setDisp({ w: Math.floor(srcW * s), h: Math.floor(srcH * s) });
- });
- ro.observe(el);
- return () => ro.disconnect();
- }, [srcW, srcH]);
+ const isPanningActive = spacePressed || tool === "pan";
+ const erase = tool === "eraser";
// Load an existing mask for re-editing (as a base raster op).
const baseMask = useRef<HTMLImageElement | null>(null);
@@ -69,7 +63,8 @@ export function InpaintEditor() {
(list: Op[]) => {
const c = canvasRef.current;
if (!c) return;
- const ctx = c.getContext("2d")!;
+ const ctx = c.getContext("2d");
+ if (!ctx) return;
ctx.globalCompositeOperation = "source-over";
ctx.clearRect(0, 0, mw, mh);
const lastClear = list.map((o) => o.kind).lastIndexOf("clear");
@@ -78,16 +73,18 @@ export function InpaintEditor() {
const tmp = document.createElement("canvas");
tmp.width = mw;
tmp.height = mh;
- const t = tmp.getContext("2d")!;
- t.drawImage(baseMask.current, 0, 0, mw, mh);
- const d = t.getImageData(0, 0, mw, mh);
- for (let i = 0; i < d.data.length; i += 4) {
- const v = d.data[i];
- d.data[i] = d.data[i + 1] = d.data[i + 2] = 255;
- d.data[i + 3] = v;
+ const t = tmp.getContext("2d");
+ if (t) {
+ t.drawImage(baseMask.current, 0, 0, mw, mh);
+ const d = t.getImageData(0, 0, mw, mh);
+ for (let i = 0; i < d.data.length; i += 4) {
+ const v = d.data[i];
+ d.data[i] = d.data[i + 1] = d.data[i + 2] = 255;
+ d.data[i + 3] = v;
+ }
+ t.putImageData(d, 0, 0);
+ ctx.drawImage(tmp, 0, 0);
}
- t.putImageData(d, 0, 0);
- ctx.drawImage(tmp, 0, 0);
}
for (const op of list.slice(lastClear + 1)) render2(ctx, op, mw, mh);
},
@@ -97,30 +94,75 @@ export function InpaintEditor() {
useEffect(() => redraw(ops), [ops, redraw]);
const toMask = (e: React.PointerEvent): [number, number] => {
- const r = canvasRef.current!.getBoundingClientRect();
- return [((e.clientX - r.left) / r.width) * mw, ((e.clientY - r.top) / r.height) * mh];
+ const c = canvasRef.current;
+ if (!c) return [0, 0];
+ const r = c.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) return [0, 0];
+ const x = Math.min(mw, Math.max(0, ((e.clientX - r.left) / r.width) * mw));
+ const y = Math.min(mh, Math.max(0, ((e.clientY - r.top) / r.height) * mh));
+ return [x, y];
+ };
+
+ const maskBrush = () => {
+ const r = canvasRef.current?.getBoundingClientRect();
+ if (!r || r.width <= 0) return (brush * mw) / Math.max(1, srcW);
+ return (brush / r.width) * mw;
};
- const maskBrush = () => (brush * mw) / Math.max(1, disp.w);
const onDown = (e: React.PointerEvent) => {
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
- current.current = { kind: "stroke", erase: erase || e.button === 2, size: maskBrush(), points: [toMask(e)] };
- const ctx = canvasRef.current!.getContext("2d")!;
- render2(ctx, current.current, mw, mh);
+ // If middle click or pan mode active, let event bubble to ZoomPan for panning
+ if (e.button === 1 || isPanningActive) return;
+ if (e.button !== 0 && e.button !== 2) return;
+
+ e.stopPropagation();
+ try {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ } catch {}
+
+ // Right button: the other tool (erases with the brush, paints with the eraser), as in mask editors.
+ const isErasing = e.button === 2 ? !erase : erase;
+ setSwapped(e.button === 2);
+ current.current = { kind: "stroke", erase: isErasing, size: maskBrush(), points: [toMask(e)] };
+ const ctx = canvasRef.current?.getContext("2d");
+ if (ctx) render2(ctx, current.current, mw, mh);
};
- const onMove = (e: React.PointerEvent) => {
- const r = canvasRef.current!.getBoundingClientRect();
- setCursor({ x: e.clientX - r.left, y: e.clientY - r.top });
+
+ const onMove = (e: React.PointerEvent, transformScale: number) => {
+ if (isPanningActive) {
+ setCursor(null);
+ return;
+ }
+
+ const c = canvasRef.current;
+ if (c) {
+ const r = c.getBoundingClientRect();
+ if (r.width > 0 && r.height > 0) {
+ setCursor({
+ x: (e.clientX - r.left) / transformScale,
+ y: (e.clientY - r.top) / transformScale,
+ });
+ }
+ }
+
const op = current.current;
if (!op || op.kind !== "stroke") return;
+ e.stopPropagation();
op.points.push(toMask(e));
- const ctx = canvasRef.current!.getContext("2d")!;
- render2(ctx, { ...op, points: op.points.slice(-2) }, mw, mh);
+ const ctx = canvasRef.current?.getContext("2d");
+ if (ctx) render2(ctx, { ...op, points: op.points.slice(-2) }, mw, mh);
};
- const onUp = () => {
+
+ const onUp = (e: React.PointerEvent) => {
if (current.current) {
+ e.stopPropagation();
+ try {
+ if ((e.target as HTMLElement).hasPointerCapture(e.pointerId)) {
+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);
+ }
+ } catch {}
const op = current.current;
current.current = null;
+ setSwapped(false);
setOps((o) => [...o, op]);
setRedo([]);
}
@@ -133,6 +175,7 @@ export function InpaintEditor() {
return o.slice(0, -1);
});
};
+
const redoOp = () => {
setRedo((r) => {
if (!r.length) return r;
@@ -140,31 +183,65 @@ export function InpaintEditor() {
return r.slice(0, -1);
});
};
+
const push = (op: Op) => {
setOps((o) => [...o, op]);
setRedo([]);
};
+ // Keyboard navigation, shortcuts, and spacebar-hold pan detection
useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (isTyping(e.target)) return;
+
+ if (e.code === "Space" && !e.repeat) {
+ e.preventDefault();
+ setSpacePressed(true);
+ } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
e.preventDefault();
e.shiftKey ? redoOp() : undo();
} else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") {
e.preventDefault();
redoOp();
- } else if (e.key === "Escape") setState({ overlay: null });
- else if (e.key === "[") setBrush((b) => Math.max(4, b - 8));
- else if (e.key === "]") setBrush((b) => Math.min(400, b + 8));
- else if (e.key.toLowerCase() === "e") setErase((v) => !v);
+ } else if (e.key === "Escape") {
+ setState({ overlay: null });
+ } else if (e.key === "[") {
+ setBrush((b) => Math.max(4, b - 8));
+ } else if (e.key === "]") {
+ setBrush((b) => Math.min(400, b + 8));
+ } else if (e.key.toLowerCase() === "b") {
+ setTool("brush");
+ } else if (e.key.toLowerCase() === "e") {
+ setTool((t) => (t === "eraser" ? "brush" : "eraser"));
+ } else if (e.key.toLowerCase() === "h") {
+ setTool((t) => (t === "pan" ? "brush" : "pan"));
+ }
+ };
+
+ const onKeyUp = (e: KeyboardEvent) => {
+ if (e.code === "Space") {
+ setSpacePressed(false);
+ }
+ };
+
+ const onBlur = () => {
+ setSpacePressed(false);
};
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- });
+
+ window.addEventListener("keydown", onKeyDown);
+ window.addEventListener("keyup", onKeyUp);
+ window.addEventListener("blur", onBlur);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ window.removeEventListener("keyup", onKeyUp);
+ window.removeEventListener("blur", onBlur);
+ };
+ }, []);
const done = async () => {
const c = canvasRef.current;
if (!c || !ref0) return;
+
// Export: white = edit on black, feathered.
const out = document.createElement("canvas");
out.width = mw;
@@ -172,9 +249,10 @@ export function InpaintEditor() {
const ctx = out.getContext("2d")!;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, mw, mh);
- if (feather > 0) ctx.filter = `blur(${feather / 2}px)`;
+ ctx.filter = `blur(${FEATHER / 2}px)`;
ctx.drawImage(c, 0, 0);
ctx.filter = "none";
+
// Detect empty mask.
const data = c.getContext("2d")!.getImageData(0, 0, mw, mh).data;
let any = false;
@@ -184,14 +262,18 @@ export function InpaintEditor() {
break;
}
}
+
if (!any) {
updateComposer({ mask: null });
setState({ overlay: null });
return;
}
+
setBusy(true);
try {
- const blob: Blob = await new Promise((res, rej) => out.toBlob((b) => (b ? res(b) : rej(new Error("export failed"))), "image/png"));
+ const blob: Blob = await new Promise((res, rej) =>
+ out.toBlob((b) => (b ? res(b) : rej(new Error("export failed"))), "image/png"),
+ );
const rec = await api.upload(blob, "mask.png");
const refKey = getState().composer.refs[0]?.key;
if (refKey) updateComposer({ mask: { inputId: rec.id, refKey }, outpaint: null, mode: "auto" });
@@ -207,6 +289,9 @@ export function InpaintEditor() {
useEffect(() => {
if (!ref0) setState({ overlay: null });
}, [ref0]);
+
+ const contentSize = useMemo(() => ({ width: srcW, height: srcH }), [srcW, srcH]);
+
if (!ref0) return null;
return (
@@ -218,41 +303,98 @@ export function InpaintEditor() {
<X size={18} />
</IconButton>
</div>
- <div className="editor-stage" ref={stageRef}>
- <div className="mask-wrap" style={{ width: disp.w, height: disp.h }} onContextMenu={(e) => e.preventDefault()}>
- <img ref={imgRef} src={src} alt="" draggable={false} style={{ width: disp.w, height: disp.h }} />
- <canvas
- ref={canvasRef}
- width={mw}
- height={mh}
- onPointerDown={onDown}
- onPointerMove={onMove}
- onPointerUp={onUp}
- onPointerCancel={onUp}
- onPointerLeave={() => setCursor(null)}
- />
- {cursor && <div className="brush-cursor" style={{ left: cursor.x, top: cursor.y, width: brush, height: brush }} />}
- </div>
+
+ <div className="editor-stage">
+ <ZoomPan
+ contentSize={contentSize}
+ resetKey={src}
+ enableToggleZoom={false}
+ enablePan={isPanningActive}
+ className="inpaint-zoom-viewport"
+ minimapSrc={src}
+ >
+ {({ transform, isPanning }) => (
+ <div
+ className="mask-wrap"
+ style={{
+ width: srcW,
+ height: srcH,
+ cursor: isPanningActive ? (isPanning ? "grabbing" : "grab") : "none",
+ }}
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ <img
+ ref={imgRef}
+ src={src}
+ alt=""
+ draggable={false}
+ style={{ width: "100%", height: "100%", display: "block" }}
+ />
+ <canvas
+ ref={canvasRef}
+ width={mw}
+ height={mh}
+ style={{
+ position: "absolute",
+ inset: 0,
+ width: "100%",
+ height: "100%",
+ cursor: isPanningActive ? (isPanning ? "grabbing" : "grab") : "none",
+ }}
+ onPointerDown={onDown}
+ onPointerMove={(e) => onMove(e, transform.scale)}
+ onPointerUp={onUp}
+ onPointerCancel={onUp}
+ onPointerLeave={() => setCursor(null)}
+ />
+ {cursor && !isPanningActive && (
+ <div
+ className="brush-cursor"
+ style={{
+ left: cursor.x,
+ top: cursor.y,
+ width: brush / transform.scale,
+ height: brush / transform.scale,
+ }}
+ />
+ )}
+ </div>
+ )}
+ </ZoomPan>
</div>
+
<div className="editor-tools">
<div className="group">
- <IconButton title="Brush" active={!erase} onClick={() => setErase(false)}>
+ <IconButton
+ title="Brush (B) · right-click erases"
+ active={(swapped ? tool === "eraser" : tool === "brush") && !spacePressed}
+ onClick={() => setTool("brush")}
+ >
<Brush size={17} />
</IconButton>
- <IconButton title="Eraser (E)" active={erase} onClick={() => setErase(true)}>
+ <IconButton
+ title="Eraser (E) · right-click paints"
+ active={(swapped ? tool === "brush" : tool === "eraser") && !spacePressed}
+ onClick={() => setTool("eraser")}
+ >
<Eraser size={17} />
</IconButton>
+ <IconButton
+ title="Move (H) · or drag with the middle button, or hold Space"
+ active={tool === "pan" || spacePressed}
+ onClick={() => setTool((t) => (t === "pan" ? "brush" : "pan"))}
+ >
+ <Hand size={17} />
+ </IconButton>
</div>
+
<div className="group">
<label className="slider" title="Brush size ( [ and ] )">
Size
<input type="range" min={4} max={400} value={brush} onChange={(e) => setBrush(Number(e.target.value))} />
</label>
- <label className="slider" title="Soft edge">
- Feather
- <input type="range" min={0} max={64} value={feather} onChange={(e) => setFeather(Number(e.target.value))} />
- </label>
</div>
+
<div className="group">
<IconButton title={`Undo (${shortcut("Z")})`} onClick={undo} disabled={!ops.length}>
<Undo2 size={17} />
@@ -267,6 +409,7 @@ export function InpaintEditor() {
<Trash2 size={17} />
</IconButton>
</div>
+
<button className="btn primary" onClick={done} disabled={busy}>
<Check size={15} /> Done
</button>
diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx
index f6e23f7..291027e 100644
--- a/src/components/Stage.tsx
+++ b/src/components/Stage.tsx
@@ -668,7 +668,7 @@ function StageFullscreen({ item, session, showOriginal, onClose }: { item: Sessi
const base = g ? compareBase(g) : null;
const from = g?.pipeline?.original_path ? g.pipeline.enlarged_from : null;
let content: React.ReactNode;
- let hint = "Click to zoom to 100 %";
+ let hint = "Scroll or click to zoom · Drag to pan";
if (g && from && showOriginal) content = <ZoomImage key={`original-${g.id}`} src={urls.genOriginal(g.id)} alt={`${g.prompt} (before upscaling)`} />;
else if (g && base) {
content = <CompareFullscreen key={g.id} g={g} base={base} />;
diff --git a/src/components/Viewer.tsx b/src/components/Viewer.tsx
index 33712b1..0eb7c4f 100644
--- a/src/components/Viewer.tsx
+++ b/src/components/Viewer.tsx
@@ -2,9 +2,10 @@
// (the live before/after comparison, or a zoomable image).
import { ChevronLeft, ChevronRight, Maximize2, X } from "lucide-react";
-import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { native } from "../lib/native";
+import { ZoomPan } from "./ZoomPan";
export const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(t.tagName));
@@ -178,58 +179,7 @@ function FullscreenShell({ children, hint, onClose, nav }: { children: ReactNode
);
}
-/** Fit to screen; click for 100 % at that point, drag to pan, click again to fit. */
+/** Fit to screen; wheel to zoom, drag to pan, click to toggle 100%, + / - / 0 / 1 shortcuts. */
export function ZoomImage({ src, alt }: { src: string; alt: string }) {
- const scroller = useRef<HTMLDivElement>(null);
- const [zoom, setZoom] = useState<{ fx: number; fy: number } | null>(null);
- const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
- const drag = useRef<{ x: number; y: number; sl: number; st: number; moved: boolean } | null>(null);
-
- useLayoutEffect(() => {
- const el = scroller.current;
- if (!el || !zoom || !natural) return;
- el.scrollLeft = zoom.fx * natural.w - el.clientWidth / 2;
- el.scrollTop = zoom.fy * natural.h - el.clientHeight / 2;
- }, [zoom, natural]);
-
- const el = scroller.current;
- const canZoom = !natural || !el || natural.w > el.clientWidth || natural.h > el.clientHeight;
-
- return (
- <div
- ref={scroller}
- className={`viewer-scroll ${zoom ? "zoomed" : ""}`}
- onPointerDown={(e) => {
- if (!zoom || e.button !== 0) return;
- drag.current = { x: e.clientX, y: e.clientY, sl: e.currentTarget.scrollLeft, st: e.currentTarget.scrollTop, moved: false };
- e.currentTarget.setPointerCapture(e.pointerId);
- }}
- onPointerMove={(e) => {
- const d = drag.current;
- if (!d) return;
- if (Math.abs(e.clientX - d.x) + Math.abs(e.clientY - d.y) > 4) d.moved = true;
- e.currentTarget.scrollLeft = d.sl - (e.clientX - d.x);
- e.currentTarget.scrollTop = d.st - (e.clientY - d.y);
- }}
- onPointerUp={() => {
- const d = drag.current;
- drag.current = null;
- if (zoom && d && !d.moved) setZoom(null);
- }}
- >
- <img
- className="viewer-img"
- src={src}
- alt={alt}
- draggable={false}
- style={zoom && natural ? { width: natural.w, height: natural.h, maxWidth: "none", maxHeight: "none", cursor: "inherit" } : { cursor: canZoom ? "zoom-in" : "default" }}
- onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}
- onClick={(e) => {
- if (zoom || !canZoom) return;
- const r = e.currentTarget.getBoundingClientRect();
- setZoom({ fx: (e.clientX - r.left) / r.width, fy: (e.clientY - r.top) / r.height });
- }}
- />
- </div>
- );
+ return <ZoomPan src={src} alt={alt} />;
}
diff --git a/src/components/ZoomPan.tsx b/src/components/ZoomPan.tsx
new file mode 100644
index 0000000..5f37674
--- /dev/null
+++ b/src/components/ZoomPan.tsx
@@ -0,0 +1,356 @@
+import { Minus, Plus } from "lucide-react";
+import React, { useEffect, useImperativeHandle, useState } from "react";
+import { useZoomPan } from "../lib/useZoomPan";
+import {
+ centerOnContentFraction,
+ minimapSize,
+ visibleContentRect,
+ type Size,
+ type ZoomTransform,
+} from "../lib/zoomMath";
+import { isTyping, useMouseActive } from "./Viewer";
+import { getState } from "../lib/store";
+
+export interface ZoomPanContext {
+ transform: ZoomTransform;
+ isZoomed: boolean;
+ isPanning: boolean;
+ isPinching: boolean;
+ zoomIn: () => void;
+ zoomOut: () => void;
+ zoomFit: () => void;
+ zoom100: () => void;
+ toggleZoom: () => void;
+ setTransform: (transform: ZoomTransform | ((prev: ZoomTransform) => ZoomTransform)) => void;
+}
+
+export interface ZoomPanProps {
+ /** Optional content size; if omitted with an image, measured automatically */
+ contentSize?: Size | null;
+ /** Image source if using ZoomPan directly as an image viewer */
+ src?: string;
+ /** Image alt text */
+ alt?: string;
+ /** Child elements to transform (e.g. compare frame, canvas, or custom layout) */
+ children?: React.ReactNode | ((zoom: ZoomPanContext) => React.ReactNode);
+ /** Enable click to toggle between fit and 100% (default true) */
+ enableToggleZoom?: boolean;
+ /** Enable pointer drag pan (default true) */
+ enablePan?: boolean;
+ /** Image for the mini-map shown while zoomed in (defaults to `src`) */
+ minimapSrc?: string;
+ /** Reset key to reset transform when changed */
+ resetKey?: string | number;
+ /** Additional class name for the viewport */
+ className?: string;
+ /** Ref to access zoom/pan actions imperatively */
+ zoomRef?: React.Ref<ZoomPanHandle>;
+}
+
+export interface ZoomPanHandle {
+ zoomIn: () => void;
+ zoomOut: () => void;
+ zoomFit: () => void;
+ zoom100: () => void;
+ toggleZoom: () => void;
+ setTransform: (transform: ZoomTransform | ((prev: ZoomTransform) => ZoomTransform)) => void;
+ transform: ZoomTransform;
+ isZoomed: boolean;
+ isPanning: boolean;
+ isPinching: boolean;
+}
+
+export interface MiniMapProps {
+ contentSize: Size;
+ containerSize: Size;
+ transform: ZoomTransform;
+ src?: string;
+ maxSide?: number;
+ onNavigate: (nextTransform: ZoomTransform) => void;
+}
+
+export function MiniMap({
+ contentSize,
+ containerSize,
+ transform,
+ src,
+ maxSide = 140,
+ onNavigate,
+}: MiniMapProps) {
+ const mapRef = React.useRef<HTMLDivElement | null>(null);
+ const isDraggingRef = React.useRef(false);
+
+ const mapSize = minimapSize(contentSize, maxSide);
+ const rect = visibleContentRect(transform, containerSize, contentSize);
+
+ const handlePointer = React.useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ const el = mapRef.current;
+ if (!el) return;
+ const b = el.getBoundingClientRect();
+ if (b.width <= 0 || b.height <= 0) return;
+ const fx = (e.clientX - b.left) / b.width;
+ const fy = (e.clientY - b.top) / b.height;
+ const next = centerOnContentFraction(fx, fy, transform, containerSize, contentSize);
+ onNavigate(next);
+ },
+ [containerSize, contentSize, onNavigate, transform],
+ );
+
+ const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ e.stopPropagation();
+ e.preventDefault();
+ isDraggingRef.current = true;
+ try {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ } catch {
+ /* ignore */
+ }
+ handlePointer(e);
+ };
+
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingRef.current) return;
+ e.stopPropagation();
+ e.preventDefault();
+ handlePointer(e);
+ };
+
+ const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingRef.current) return;
+ isDraggingRef.current = false;
+ e.stopPropagation();
+ try {
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ }
+ } catch {
+ /* ignore */
+ }
+ };
+
+ return (
+ <div
+ ref={mapRef}
+ className="zoom-minimap"
+ style={{
+ width: mapSize.width,
+ height: mapSize.height,
+ }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ onClick={(e) => e.stopPropagation()}
+ >
+ {src && (
+ <img
+ src={src}
+ alt=""
+ draggable={false}
+ className="zoom-minimap-img"
+ />
+ )}
+ <div
+ className="zoom-minimap-viewport"
+ style={{
+ left: `${rect.x * 100}%`,
+ top: `${rect.y * 100}%`,
+ width: `${rect.w * 100}%`,
+ height: `${rect.h * 100}%`,
+ }}
+ />
+ </div>
+ );
+}
+
+export function ZoomPan({
+ contentSize,
+ src,
+ alt = "",
+ children,
+ enableToggleZoom = true,
+ enablePan = true,
+ minimapSrc,
+ resetKey,
+ className = "",
+ zoomRef,
+}: ZoomPanProps) {
+ const [naturalSize, setNaturalSize] = useState<Size | null>(null);
+ const activeContentSize = (src && naturalSize) ? naturalSize : (contentSize ?? naturalSize);
+
+ const [mouseActive, wakeMouse] = useMouseActive(2200);
+
+ // Clear natural size when src changes so dimensions of old image do not linger
+ useEffect(() => {
+ setNaturalSize(null);
+ }, [src]);
+
+ // Show the toolbar on open; it hides while the mouse rests and comes back when it moves.
+ useEffect(() => {
+ wakeMouse();
+ }, [wakeMouse]);
+
+ const zoom = useZoomPan({
+ contentSize: activeContentSize,
+ resetKey: resetKey ?? src,
+ enableToggleZoom,
+ enablePan,
+ });
+
+ useImperativeHandle(
+ zoomRef,
+ () => ({
+ zoomIn: zoom.zoomIn,
+ zoomOut: zoom.zoomOut,
+ zoomFit: zoom.zoomFit,
+ zoom100: zoom.zoom100,
+ toggleZoom: zoom.toggleZoom,
+ setTransform: zoom.setTransform,
+ transform: zoom.transform,
+ isZoomed: zoom.isZoomed,
+ isPanning: zoom.isPanning,
+ isPinching: zoom.isPinching,
+ }),
+ [zoom],
+ );
+
+ // Keyboard navigation for zoom (+, -, 0, 1)
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (isTyping(e.target)) return;
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
+ // Another panel covers this view (the inpaint editor is a panel with its own ZoomPan).
+ if (getState().overlay && !ref.current?.closest(".overlay")) return;
+
+ // When a full-screen viewer is open, only the ZoomPan inside the viewer handles shortcuts
+ const viewer = document.querySelector(".viewer");
+ if (viewer && !ref.current?.closest(".viewer")) return;
+
+ if (e.key === "+" || e.key === "=" || e.key === "Add") {
+ e.preventDefault();
+ zoom.zoomIn();
+ } else if (e.key === "-" || e.key === "_" || e.key === "Subtract") {
+ e.preventDefault();
+ zoom.zoomOut();
+ } else if (e.key === "0") {
+ e.preventDefault();
+ zoom.zoomFit();
+ } else if (e.key === "1") {
+ e.preventDefault();
+ zoom.zoom100();
+ }
+ };
+
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [zoom]);
+
+ const {
+ ref,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ onPointerCancel,
+ onPointerDownCapture,
+ onPointerMoveCapture,
+ onPointerUpCapture,
+ onPointerCancelCapture,
+ style,
+ } = zoom.containerProps;
+
+ const zoomPercent = Math.round(zoom.transform.scale * 100);
+ const isMinimapVisible =
+ zoom.isZoomed &&
+ activeContentSize &&
+ activeContentSize.width > 0 &&
+ activeContentSize.height > 0;
+
+ return (
+ <div
+ ref={ref}
+ className={`zoom-pan-viewport ${zoom.isZoomed ? "zoomed" : ""} ${className}`}
+ style={style}
+ onPointerDownCapture={(e) => {
+ wakeMouse();
+ onPointerDownCapture(e);
+ }}
+ onPointerMoveCapture={onPointerMoveCapture}
+ onPointerUpCapture={onPointerUpCapture}
+ onPointerCancelCapture={onPointerCancelCapture}
+ onPointerDown={(e) => {
+ wakeMouse();
+ onPointerDown(e);
+ }}
+ onPointerMove={(e) => {
+ wakeMouse();
+ onPointerMove(e);
+ }}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerCancel}
+ >
+ <div
+ className="zoom-pan-content"
+ style={{
+ width: activeContentSize?.width,
+ height: activeContentSize?.height,
+ transform: `translate3d(${zoom.transform.x}px, ${zoom.transform.y}px, 0px) scale(${zoom.transform.scale})`,
+ transformOrigin: "0 0",
+ willChange: zoom.isPanning ? "transform" : "auto",
+ }}
+ >
+ {typeof children === "function" ? children(zoom) : children}
+ {src && (
+ <img
+ src={src}
+ alt={alt}
+ draggable={false}
+ className="zoom-pan-img"
+ onLoad={(e) => {
+ setNaturalSize({
+ width: e.currentTarget.naturalWidth,
+ height: e.currentTarget.naturalHeight,
+ });
+ }}
+ />
+ )}
+ </div>
+
+ {isMinimapVisible && (
+ <MiniMap
+ contentSize={zoom.contentSize}
+ containerSize={zoom.containerSize}
+ transform={zoom.transform}
+ src={minimapSrc ?? src}
+ onNavigate={zoom.setTransform}
+ />
+ )}
+
+ <div
+ className={`zoom-controls ${mouseActive || zoom.isPanning ? "visible" : "hidden"}`}
+ onPointerDown={(e) => {
+ wakeMouse();
+ e.stopPropagation();
+ }}
+ onPointerMove={(e) => {
+ wakeMouse();
+ e.stopPropagation();
+ }}
+ onPointerEnter={wakeMouse}
+ onClick={(e) => e.stopPropagation()}
+ onDoubleClick={(e) => e.stopPropagation()}
+ >
+ <button className="zoom-btn" title="Zoom out (-)" aria-label="Zoom out" onClick={zoom.zoomOut}>
+ <Minus size={15} />
+ </button>
+ <span className="zoom-pct" aria-live="polite">{zoomPercent}%</span>
+ <button className="zoom-btn" title="Zoom in (+)" aria-label="Zoom in" onClick={zoom.zoomIn}>
+ <Plus size={15} />
+ </button>
+ <button className="zoom-btn text" title="Fit to screen (0)" disabled={!zoom.isZoomed} onClick={zoom.zoomFit}>
+ Fit
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/lib/useZoomPan.test.tsx b/src/lib/useZoomPan.test.tsx
new file mode 100644
index 0000000..8ae8ae8
--- /dev/null
+++ b/src/lib/useZoomPan.test.tsx
@@ -0,0 +1,1020 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { useZoomPan, type UseZoomPanOptions, type UseZoomPanReturn } from "./useZoomPan";
+
+// Configure React act environment
+// @ts-expect-error React testing environment flag
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("useZoomPan hook", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+ let hookResult: UseZoomPanReturn;
+
+ function TestComponent(props: { options?: UseZoomPanOptions }) {
+ hookResult = useZoomPan(props.options);
+ return (
+ <div
+ {...hookResult.containerProps}
+ style={{ ...hookResult.containerProps.style, width: 800, height: 600, position: "relative" }}
+ >
+ <div ref={hookResult.contentRef} />
+ </div>
+ );
+ }
+
+ beforeEach(() => {
+ // Mock ResizeObserver
+ globalThis.ResizeObserver = class ResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ };
+
+ // Mock getBoundingClientRect
+ Element.prototype.getBoundingClientRect = function () {
+ return {
+ width: 800,
+ height: 600,
+ top: 0,
+ left: 0,
+ bottom: 600,
+ right: 800,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ };
+ };
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("initializes with default fit transform for given contentSize", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 1600, height: 1200 } }} />);
+ });
+
+ expect(hookResult).toBeDefined();
+ expect(hookResult.containerSize).toEqual({ width: 800, height: 600 });
+ // Fit of 1600x1200 in 800x600 is scale 0.5, centered at (0, 0)
+ expect(hookResult.transform.scale).toBe(0.5);
+ expect(hookResult.transform.x).toBe(0);
+ expect(hookResult.transform.y).toBe(0);
+ expect(hookResult.isZoomed).toBe(false);
+ expect(hookResult.isPanning).toBe(false);
+ });
+
+ it("canZoom is true for larger images", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 2000, height: 1500 } }} />);
+ });
+ expect(hookResult.canZoom).toBe(true);
+ });
+
+ it("zoomIn, zoomOut, and zoomFit update transform correctly", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 1600, height: 1200 } }} />);
+ });
+
+ const initialScale = hookResult.transform.scale;
+ expect(initialScale).toBe(0.5);
+
+ act(() => {
+ hookResult.zoomIn();
+ });
+ expect(hookResult.transform.scale).toBeGreaterThan(initialScale);
+ expect(hookResult.isZoomed).toBe(true);
+
+ act(() => {
+ hookResult.zoomOut();
+ });
+ expect(hookResult.transform.scale).toBeLessThanOrEqual(initialScale * 1.5);
+
+ act(() => {
+ hookResult.zoomFit();
+ });
+ expect(hookResult.transform.scale).toBe(hookResult.fitTransform.scale);
+ expect(hookResult.isZoomed).toBe(false);
+ });
+
+ it("zoom100 sets scale to 1.0", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 1200, height: 900 } }} />);
+ });
+
+ act(() => {
+ hookResult.zoom100();
+ });
+ expect(hookResult.transform.scale).toBe(1.0);
+ expect(hookResult.isZoomed).toBe(true);
+ });
+
+ it("toggleZoom switches between fit and 100%", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 2000, height: 1500 } }} />);
+ });
+
+ expect(hookResult.isZoomed).toBe(false);
+
+ // Toggle -> should zoom to 100%
+ act(() => {
+ hookResult.toggleZoom();
+ });
+ expect(hookResult.transform.scale).toBe(1.0);
+ expect(hookResult.isZoomed).toBe(true);
+
+ // Toggle again -> should return to fit
+ act(() => {
+ hookResult.toggleZoom();
+ });
+ expect(hookResult.isZoomed).toBe(false);
+ });
+
+ it("sets cursorStyle to default when enableToggleZoom is false and not zoomed", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 2000, height: 1500 }, enableToggleZoom: false }} />);
+ });
+ expect(hookResult.containerProps.style.cursor).toBe("default");
+
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 2000, height: 1500 }, enableToggleZoom: true }} />);
+ });
+ expect(hookResult.containerProps.style.cursor).toBe("zoom-in");
+ });
+
+ it("setTransform clamps offsets to bounds", () => {
+ act(() => {
+ root.render(<TestComponent options={{ contentSize: { width: 1000, height: 1000 } }} />);
+ });
+
+ act(() => {
+ hookResult.setTransform({ x: 99999, y: 99999, scale: 2.0 });
+ });
+
+ // Offset must be clamped, not arbitrarily out of bounds
+ expect(hookResult.transform.x).toBeLessThan(99999);
+ expect(hookResult.transform.y).toBeLessThan(99999);
+ });
+});
+
+import { ZoomPan } from "../components/ZoomPan";
+import { setState, updateComposer } from "./store";
+
+describe("ZoomPan component & Stage integration", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ setState({ overlay: null });
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ setState({ overlay: null });
+ });
+
+ it("renders the zoom toolbar", () => {
+ act(() => {
+ root.render(<ZoomPan contentSize={{ width: 1600, height: 1200 }} />);
+ });
+
+ expect(container.querySelector(".zoom-controls")).not.toBeNull();
+ });
+
+ it("remounting with a different key resets zoom/pan transform", () => {
+ let zoomHandle: any;
+
+ act(() => {
+ root.render(
+ <ZoomPan
+ key="item-1"
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ // Zoom in on version 1
+ act(() => {
+ zoomHandle?.zoomIn();
+ zoomHandle?.zoomIn();
+ });
+ expect(zoomHandle.transform.scale).toBeGreaterThan(0.5);
+
+ // Switch to version 2 (simulating timeline version switch via key change)
+ act(() => {
+ root.render(
+ <ZoomPan
+ key="item-2"
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ // Version 2 starts cleanly at initial fit scale (0.5 for 1600x1200 in 800x600)
+ expect(zoomHandle.transform.scale).toBe(0.5);
+ expect(zoomHandle.transform.x).toBe(0);
+ expect(zoomHandle.transform.y).toBe(0);
+ });
+
+ it("guards keyboard zoom shortcuts when overlay or typing is active", () => {
+ let zoomHandle: any;
+
+ act(() => {
+ root.render(
+ <ZoomPan
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ const initialScale = zoomHandle.transform.scale;
+
+ // Simulate typing in prompt/input
+ const input = document.createElement("input");
+ document.body.appendChild(input);
+ input.focus();
+ act(() => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "+", bubbles: true }));
+ });
+ expect(zoomHandle.transform.scale).toBe(initialScale); // Not changed
+
+ input.remove();
+
+ // Simulate modal overlay active (e.g. settings)
+ setState({ overlay: "settings" });
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "+", bubbles: true }));
+ });
+ expect(zoomHandle.transform.scale).toBe(initialScale); // Not changed
+
+ setState({ overlay: null });
+
+ // With no overlay and not typing: shortcut works
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "+", bubbles: true }));
+ });
+ expect(zoomHandle.transform.scale).toBeGreaterThan(initialScale);
+
+ // Numpad Subtract zooms out
+ const zoomedScale = zoomHandle.transform.scale;
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Subtract", bubbles: true }));
+ });
+ expect(zoomHandle.transform.scale).toBeLessThan(zoomedScale);
+
+ // Numpad Add zooms in
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Add", bubbles: true }));
+ });
+ expect(zoomHandle.transform.scale).toBeGreaterThan(initialScale);
+ });
+
+ it("resets transform to fit when contentSize changes without remounting", () => {
+ let zoomHandle: any;
+
+ act(() => {
+ root.render(
+ <ZoomPan
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ expect(zoomHandle.transform.scale).toBe(0.5);
+
+ // User zooms in on image 1
+ act(() => {
+ zoomHandle.zoomIn();
+ zoomHandle.zoomIn();
+ });
+ expect(zoomHandle.transform.scale).toBeGreaterThan(0.5);
+
+ // Content size changes (new image loaded into same component instance)
+ act(() => {
+ root.render(
+ <ZoomPan
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ contentSize={{ width: 800, height: 600 }}
+ />,
+ );
+ });
+
+ // Content change should automatically reset to fit (fit of 800x600 in 800x600 is 1.0)
+ expect(zoomHandle.transform.scale).toBe(1.0);
+ expect(zoomHandle.transform.x).toBe(0);
+ expect(zoomHandle.transform.y).toBe(0);
+ });
+
+ it("resets transform to fit when resetKey changes", () => {
+ let zoomHandle: any;
+
+ act(() => {
+ root.render(
+ <ZoomPan
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ src="gen-1.png"
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ expect(zoomHandle.transform.scale).toBe(0.5);
+
+ // User zooms in
+ act(() => {
+ zoomHandle.zoomIn();
+ zoomHandle.zoomIn();
+ });
+ expect(zoomHandle.transform.scale).toBeGreaterThan(0.5);
+
+ // Image src changes with identical dimensions
+ act(() => {
+ root.render(
+ <ZoomPan
+ zoomRef={(ref) => {
+ zoomHandle = ref;
+ }}
+ src="gen-2.png"
+ contentSize={{ width: 1600, height: 1200 }}
+ />,
+ );
+ });
+
+ // Should reset to fit
+ expect(zoomHandle.transform.scale).toBe(0.5);
+ expect(zoomHandle.transform.x).toBe(0);
+ expect(zoomHandle.transform.y).toBe(0);
+ });
+});
+
+import { CompareFrame, CompareFullscreen } from "../components/Compare";
+import type { CompareBase } from "./logic";
+import type { GenerationRecord } from "./types";
+import { vi } from "vitest";
+
+describe("CompareFrame & ZoomPan Integration", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ const mockGen = {
+ id: "gen1",
+ mode: "edit",
+ prompt: "make it sunset",
+ width: 1600,
+ height: 1200,
+ references: [{ index: 0, input_id: "in1", width: 1600, height: 1200 }],
+ outpaint: null,
+ } as unknown as GenerationRecord;
+
+ const mockBase: CompareBase = {
+ inputId: "in1",
+ rect: { x: 0, y: 0, w: 1, h: 1 },
+ };
+
+ beforeEach(() => {
+ if (!Element.prototype.setPointerCapture) Element.prototype.setPointerCapture = () => {};
+ if (!Element.prototype.releasePointerCapture) Element.prototype.releasePointerCapture = () => {};
+ if (!Element.prototype.hasPointerCapture) Element.prototype.hasPointerCapture = () => false;
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ setState({ overlay: null, compare: "slider" });
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ setState({ overlay: null, compare: "slider" });
+ });
+
+ it("renders the full-screen CompareFrame inside ZoomPan with content matching generation dimensions", () => {
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} fullscreen />);
+ });
+
+ expect(container.querySelector(".zoom-pan-viewport")).not.toBeNull();
+
+ const content = container.querySelector(".zoom-pan-content") as HTMLElement;
+ expect(content).not.toBeNull();
+ expect(content.style.width).toBe("1600px");
+ expect(content.style.height).toBe("1200px");
+
+ // Both before and after images must be mounted
+ const afterImg = container.querySelector(".compare-img") as HTMLImageElement;
+ expect(afterImg).not.toBeNull();
+ expect(afterImg.src).toContain("gen1");
+
+ const beforeContainer = container.querySelector(".compare-before");
+ expect(beforeContainer).not.toBeNull();
+ const beforeImg = beforeContainer?.querySelector("img") as HTMLImageElement;
+ expect(beforeImg).not.toBeNull();
+ expect(beforeImg.src).toContain("in1");
+ });
+
+ it("renders interactive split slider in content space at 50% split", () => {
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const handle = container.querySelector(".compare-handle") as HTMLElement;
+ expect(handle).not.toBeNull();
+ expect(handle.style.left).toBe("50%");
+
+ const before = container.querySelector(".compare-before") as HTMLElement;
+ expect(before.style.clipPath).toBe("inset(0 50% 0 0)");
+
+ // Labels
+ expect(container.textContent).toContain("Before");
+ expect(container.textContent).toContain("After");
+ });
+
+ it("tracks slider dragging via pointer events across content space", () => {
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const handle = container.querySelector(".compare-handle") as HTMLElement;
+ expect(handle).not.toBeNull();
+
+ // Pointer down at 50% (400px of 800px width)
+ act(() => {
+ handle.dispatchEvent(new PointerEvent("pointerdown", { clientX: 400, button: 0, bubbles: true }));
+ });
+
+ // Move pointer to 75% (600px of 800px width)
+ act(() => {
+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: 600, bubbles: true }));
+ });
+
+ expect(handle.style.left).toBe("75%");
+ const before = container.querySelector(".compare-before") as HTMLElement;
+ expect(before.style.clipPath).toBe("inset(0 25% 0 0)");
+
+ // Pointer up to complete drag
+ act(() => {
+ handle.dispatchEvent(new PointerEvent("pointerup", { clientX: 600, bubbles: true }));
+ });
+
+ expect(handle.style.left).toBe("75%");
+ });
+
+ it("hold 'B' key reveals the full original image and restores on keyup", () => {
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const before = container.querySelector(".compare-before") as HTMLElement;
+ expect(before.style.clipPath).toBe("inset(0 50% 0 0)");
+
+ // Press and hold 'B'
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "b" }));
+ });
+
+ // In holding mode, clipPath is cleared to show full original
+ expect(before.style.clipPath).toBe("");
+ expect(before.style.visibility).toBe("visible");
+
+ // Release 'B'
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keyup", { key: "b" }));
+ });
+
+ // Restores split slider clipPath
+ expect(before.style.clipPath).toBe("inset(0 50% 0 0)");
+ });
+
+ it("flicker mode flips phase automatically using timer", () => {
+ vi.useFakeTimers();
+ setState({ compare: "flicker", flickerMs: 150 });
+
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const before = container.querySelector(".compare-before") as HTMLElement;
+ // Initial phase in flicker is "before"
+ expect(before.style.visibility).toBe("visible");
+
+ // Advance 150ms -> flips to "after" (before hidden)
+ act(() => {
+ vi.advanceTimersByTime(150);
+ });
+ expect(before.style.visibility).toBe("hidden");
+
+ // Advance 150ms -> flips back to "before"
+ act(() => {
+ vi.advanceTimersByTime(150);
+ });
+ expect(before.style.visibility).toBe("visible");
+
+ vi.useRealTimers();
+ });
+
+ it("does not zoom on the stage: no viewport or zoom controls, CompareBar and full-screen button kept", () => {
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ expect(container.querySelector(".zoom-pan-viewport")).toBeNull();
+ expect(container.querySelector(".zoom-controls")).toBeNull();
+ expect(container.querySelector(".compare-overlay .compare-bar")).not.toBeNull();
+ expect(container.querySelector(".fullscreen-btn")).not.toBeNull();
+ });
+
+ it("mouse press-and-hold in mode 'off' shows original and restores on pointerup/cancel", () => {
+ setState({ compare: "off" });
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const box = container.querySelector(".compare-box") as HTMLElement;
+ const before = container.querySelector(".compare-before") as HTMLElement;
+ expect(box).not.toBeNull();
+ expect(before.style.visibility).toBe("hidden");
+
+ // Pointer down on box shows original with Before label
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointerdown", { button: 0, bubbles: true }));
+ });
+ expect(before.style.visibility).toBe("visible");
+ expect(container.textContent).toContain("Before");
+
+ // Pointer up restores result
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointerup", { button: 0, bubbles: true }));
+ });
+ expect(before.style.visibility).toBe("hidden");
+
+ // Pointer down followed by pointer cancel also restores result
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointerdown", { button: 0, bubbles: true }));
+ });
+ expect(before.style.visibility).toBe("visible");
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointercancel", { bubbles: true }));
+ });
+ expect(before.style.visibility).toBe("hidden");
+ });
+
+ it("clicking on compare-box in slider mode updates split position when unzoomed", () => {
+ setState({ compare: "slider" });
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const box = container.querySelector(".compare-box") as HTMLElement;
+ const handle = container.querySelector(".compare-handle") as HTMLElement;
+ expect(handle.style.left).toBe("50%");
+
+ // Click at 25% (200px of 800px width)
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointerdown", { clientX: 200, button: 0, bubbles: true }));
+ });
+ expect(handle.style.left).toBe("25%");
+
+ // Drag to 60% (480px)
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointermove", { clientX: 480, bubbles: true }));
+ });
+ expect(handle.style.left).toBe("60%");
+
+ act(() => {
+ box.dispatchEvent(new PointerEvent("pointerup", { clientX: 480, bubbles: true }));
+ });
+ expect(handle.style.left).toBe("60%");
+ });
+
+ it("hides slider handle and Before/After tags when hold 'B' is active in slider mode", () => {
+ setState({ compare: "slider" });
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ expect(container.querySelector(".compare-handle")).not.toBeNull();
+ expect(container.textContent).toContain("Before");
+ expect(container.textContent).toContain("After");
+
+ // Press 'B'
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "b" }));
+ });
+
+ // Handle is hidden, tags are replaced by single "Before" indicator
+ expect(container.querySelector(".compare-handle")).toBeNull();
+ expect(container.textContent).toContain("Before");
+ expect(container.textContent).not.toContain("After");
+
+ // Release 'B'
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keyup", { key: "b" }));
+ });
+
+ expect(container.querySelector(".compare-handle")).not.toBeNull();
+ expect(container.textContent).toContain("Before");
+ expect(container.textContent).toContain("After");
+ });
+
+ it("renders DiffCanvas inside compare-box with correct layout in diff mode", () => {
+ setState({ compare: "diff" });
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} />);
+ });
+
+ const box = container.querySelector(".compare-box") as HTMLElement;
+ expect(box).not.toBeNull();
+ const diffCanvas = box.querySelector(".compare-diff");
+ expect(diffCanvas).not.toBeNull();
+ });
+
+ it("renders CompareFullscreen with viewer-frame and external compare bar", () => {
+ act(() => {
+ root.render(<CompareFullscreen g={mockGen} base={mockBase} />);
+ });
+
+ // Fullscreen viewer-frame
+ expect(container.querySelector(".viewer-frame")).not.toBeNull();
+ expect(container.querySelector(".zoom-pan-viewport")).not.toBeNull();
+ expect(container.querySelector(".zoom-controls")).not.toBeNull();
+
+ // Fullscreen has compare bar outside the viewer frame
+ expect(container.querySelector(".viewer-compare-bar .compare-bar")).not.toBeNull();
+ });
+
+ it("switches across all compare modes in full screen without resetting the zoom transform", () => {
+ setState({ compare: "slider" });
+
+ act(() => {
+ root.render(<CompareFrame g={mockGen} base={mockBase} fullscreen />);
+ });
+
+ const content = container.querySelector(".zoom-pan-content") as HTMLElement;
+ const initial = content.style.transform;
+ expect(initial).not.toBe("");
+ expect(container.querySelector(".compare-handle")).not.toBeNull();
+
+ for (const mode of ["flicker", "diff", "off", "slider"] as const) {
+ act(() => {
+ setState({ compare: mode });
+ });
+ expect(content.style.transform).toBe(initial);
+ }
+ expect(container.querySelector(".compare-handle")).not.toBeNull();
+ });
+});
+
+import { InpaintEditor } from "../components/InpaintEditor";
+
+describe("InpaintEditor & ZoomPan Integration", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ if (!Element.prototype.setPointerCapture) Element.prototype.setPointerCapture = () => {};
+ if (!Element.prototype.releasePointerCapture) Element.prototype.releasePointerCapture = () => {};
+ if (!Element.prototype.hasPointerCapture) Element.prototype.hasPointerCapture = () => false;
+
+ HTMLCanvasElement.prototype.getContext = (() => ({
+ globalCompositeOperation: "source-over",
+ clearRect: () => {},
+ drawImage: () => {},
+ getImageData: () => ({ data: new Uint8ClampedArray(100) }),
+ putImageData: () => {},
+ beginPath: () => {},
+ arc: () => {},
+ fill: () => {},
+ moveTo: () => {},
+ lineTo: () => {},
+ stroke: () => {},
+ fillRect: () => {},
+ })) as any;
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ setState({ overlay: null });
+ updateComposer({ refs: [{ key: "r1", source: "input:in1", width: 1600, height: 900, name: "photo.png" }], mask: null });
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("renders InpaintEditor wrapped inside ZoomPan with inpaint-zoom-viewport", () => {
+ act(() => {
+ root.render(
+ <InpaintEditor />,
+ );
+ });
+
+ const viewport = container.querySelector(".inpaint-zoom-viewport");
+ expect(viewport).not.toBeNull();
+ const maskWrap = container.querySelector(".mask-wrap") as HTMLElement;
+ expect(maskWrap).not.toBeNull();
+ expect(maskWrap.style.width).toBe("1600px");
+ expect(maskWrap.style.height).toBe("900px");
+ });
+
+ it("toggles pan mode via Spacebar hold and Hand tool button", () => {
+ act(() => {
+ root.render(
+ <InpaintEditor />,
+ );
+ });
+
+ const canvas = container.querySelector("canvas") as HTMLCanvasElement;
+ expect(canvas).not.toBeNull();
+
+ // Default: brush active, cursor is none (custom circle cursor)
+ expect(canvas.style.cursor).toBe("none");
+
+ // Press and hold Spacebar -> switches to pan mode with grab cursor
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { code: "Space" }));
+ });
+ expect(canvas.style.cursor).toBe("grab");
+
+ // Release Spacebar -> returns to brush mode
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keyup", { code: "Space" }));
+ });
+ expect(canvas.style.cursor).toBe("none");
+
+ // Press 'H' -> activates Pan/Hand tool
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "h" }));
+ });
+ expect(canvas.style.cursor).toBe("grab");
+
+ // Press 'B' -> switches back to Brush
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "b" }));
+ });
+ expect(canvas.style.cursor).toBe("none");
+ });
+
+ it("adjusts brush size via [ and ] shortcuts", () => {
+ act(() => {
+ root.render(
+ <InpaintEditor />,
+ );
+ });
+
+ const sizeInput = container.querySelector('input[type="range"][min="4"]') as HTMLInputElement;
+ expect(sizeInput).not.toBeNull();
+ const initialSize = Number(sizeInput.value);
+
+ // Increase size with ']'
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "]" }));
+ });
+ expect(Number(sizeInput.value)).toBe(initialSize + 8);
+
+ // Decrease size with '['
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "[" }));
+ });
+ expect(Number(sizeInput.value)).toBe(initialSize);
+ });
+
+ it("always shows the zoom controls and has no Feather slider (fixed soft edge)", () => {
+ act(() => {
+ root.render(
+ <InpaintEditor />,
+ );
+ });
+
+ expect(container.querySelector(".zoom-controls")).not.toBeNull();
+ expect(container.querySelector('button[title="Hide zoom controls"]')).toBeNull();
+ expect(container.textContent).not.toContain("Feather");
+ });
+});
+
+describe("Gestures, Inertia & MiniMap", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ setState({ overlay: null });
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("handles multi-touch pinch to zoom in and out", () => {
+ let hookResult!: UseZoomPanReturn;
+ function Test() {
+ hookResult = useZoomPan({ contentSize: { width: 1600, height: 1200 } });
+ return <div {...hookResult.containerProps} />;
+ }
+
+ act(() => {
+ root.render(<Test />);
+ });
+
+ const initialScale = hookResult.transform.scale;
+
+ // Finger 1 down
+ act(() => {
+ hookResult.containerProps.onPointerDownCapture({
+ pointerId: 1,
+ pointerType: "touch",
+ clientX: 300,
+ clientY: 300,
+ stopPropagation: () => {},
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+ expect(hookResult.isPinching).toBe(false);
+
+ // Finger 2 down
+ act(() => {
+ hookResult.containerProps.onPointerDownCapture({
+ pointerId: 2,
+ pointerType: "touch",
+ clientX: 500,
+ clientY: 300,
+ stopPropagation: () => {},
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+ expect(hookResult.isPinching).toBe(true);
+
+ // Spread fingers apart (move finger 2 from 500 to 700)
+ act(() => {
+ hookResult.containerProps.onPointerMoveCapture({
+ pointerId: 2,
+ clientX: 700,
+ clientY: 300,
+ stopPropagation: () => {},
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+ expect(hookResult.transform.scale).toBeGreaterThan(initialScale);
+
+ // Finger up
+ act(() => {
+ hookResult.containerProps.onPointerUpCapture({
+ pointerId: 2,
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+ expect(hookResult.isPinching).toBe(false);
+ });
+
+ it("supports middle-mouse click and drag panning", () => {
+ let hookResult!: UseZoomPanReturn;
+ function Test() {
+ hookResult = useZoomPan({ contentSize: { width: 1600, height: 1200 }, enablePan: false });
+ return <div {...hookResult.containerProps} />;
+ }
+
+ act(() => {
+ root.render(<Test />);
+ });
+
+ act(() => {
+ hookResult.zoom100(); // Zoom in to enable panning room
+ });
+
+ const startX = hookResult.transform.x;
+ const startY = hookResult.transform.y;
+
+ // Middle-click down (button === 1)
+ act(() => {
+ hookResult.containerProps.onPointerDown({
+ button: 1,
+ clientX: 400,
+ clientY: 300,
+ preventDefault: () => {},
+ currentTarget: { setPointerCapture: () => {} },
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+
+ // Move
+ act(() => {
+ hookResult.containerProps.onPointerMove({
+ clientX: 350,
+ clientY: 250,
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+
+ expect(hookResult.isPanning).toBe(true);
+ expect(hookResult.transform.x).toBe(startX - 50);
+ expect(hookResult.transform.y).toBe(startY - 50);
+
+ // Up
+ act(() => {
+ hookResult.containerProps.onPointerUp({
+ button: 1,
+ clientX: 350,
+ clientY: 250,
+ currentTarget: { releasePointerCapture: () => {}, hasPointerCapture: () => false },
+ } as unknown as React.PointerEvent<HTMLDivElement>);
+ });
+ expect(hookResult.isPanning).toBe(false);
+ });
+
+ it("shows the MiniMap navigator by itself while zoomed in", () => {
+ act(() => {
+ root.render(<ZoomPan src="/photo.png" contentSize={{ width: 1600, height: 1200 }} />);
+ });
+
+ // Initially at fit scale: no MiniMap, Fit disabled
+ const fit = () => container.querySelector('button[title="Fit to screen (0)"]') as HTMLButtonElement;
+ expect(container.querySelector(".zoom-minimap")).toBeNull();
+ expect(fit().disabled).toBe(true);
+
+ act(() => {
+ (container.querySelector('button[aria-label="Zoom in"]') as HTMLButtonElement).click();
+ });
+ expect(fit().disabled).toBe(false);
+
+ // MiniMap navigator and viewport rect should be rendered
+ const minimap = container.querySelector(".zoom-minimap");
+ expect(minimap).not.toBeNull();
+ expect(container.querySelector(".zoom-minimap-viewport")).not.toBeNull();
+
+ // Pointer on the MiniMap
+ const minimapEl = minimap as HTMLElement;
+ minimapEl.getBoundingClientRect = () => ({
+ width: 140,
+ height: 105,
+ left: 600,
+ top: 400,
+ right: 740,
+ bottom: 505,
+ x: 600,
+ y: 400,
+ toJSON: () => {},
+ });
+
+ act(() => {
+ const pEvent = new MouseEvent("pointerdown", {
+ bubbles: true,
+ clientX: 670,
+ clientY: 452.5,
+ });
+ minimapEl.dispatchEvent(pEvent);
+ });
+
+ expect(container.querySelector(".zoom-minimap")).not.toBeNull();
+ });
+
+ it("keeps the same toolbar items at every zoom level", () => {
+ act(() => {
+ root.render(<ZoomPan src="/photo.png" contentSize={{ width: 1600, height: 1200 }} />);
+ });
+
+ const items = () => [...container.querySelectorAll(".zoom-controls > *")].map((el) => el.getAttribute("title") ?? el.className);
+ const atFit = items();
+ expect(atFit).toHaveLength(4);
+ act(() => {
+ (container.querySelector('button[aria-label="Zoom in"]') as HTMLButtonElement).click();
+ });
+ expect(items()).toEqual(atFit);
+ });
+});
+
+
diff --git a/src/lib/useZoomPan.ts b/src/lib/useZoomPan.ts
new file mode 100644
index 0000000..2df1cfc
--- /dev/null
+++ b/src/lib/useZoomPan.ts
@@ -0,0 +1,517 @@
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ calculateFit,
+ clampOffset,
+ clampScale,
+ inertiaStep,
+ INERTIA_START_SPEED,
+ nextZoomStep,
+ pinchTransform,
+ releaseVelocity,
+ zoomAtFocalPoint,
+ type MotionSample,
+ type PinchStart,
+ type Point,
+ type Size,
+ type ZoomTransform,
+} from "./zoomMath";
+
+/** Users who asked the OS for less motion get no momentum. */
+const prefersReducedMotion = () =>
+ typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+export interface UseZoomPanOptions {
+ /** Dimensions of the content being displayed (image, canvas, compare box) */
+ contentSize?: Size | null;
+ /** Optional key/signal to reset zoom/pan when the displayed item or version changes */
+ resetKey?: string | number;
+ /** Max scale for auto-fit (default 1.0: small images will not be enlarged past 100% on fit) */
+ maxFitScale?: number;
+ /** Enable mouse wheel zoom (default true) */
+ enableWheel?: boolean;
+ /** Enable pointer drag pan (default true) */
+ enablePan?: boolean;
+ /** Enable click to toggle between fit and 100% (default true) */
+ enableToggleZoom?: boolean;
+ /** Keep panning with momentum after a fast drag is released (default true; off with reduced motion) */
+ enableInertia?: boolean;
+ /** Two-finger pinch zoom on touch screens (default true) */
+ enablePinch?: boolean;
+ /** Called when a pinch begins, so children can abandon a stroke or slider drag started by the first finger */
+ onGestureStart?: () => void;
+ /** Callback on transform change */
+ onChange?: (transform: ZoomTransform) => void;
+}
+
+export interface UseZoomPanReturn {
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ contentRef: React.RefObject<HTMLDivElement | null>;
+ transform: ZoomTransform;
+ containerSize: Size;
+ /** Content size used for fitting/clamping (never 0) */
+ contentSize: Size;
+ isZoomed: boolean;
+ isPanning: boolean;
+ isPinching: boolean;
+ canZoom: boolean;
+ fitTransform: ZoomTransform;
+ zoomIn: () => void;
+ zoomOut: () => void;
+ zoomFit: () => void;
+ zoom100: (focalPoint?: Point) => void;
+ toggleZoom: (focalPoint?: Point) => void;
+ setTransform: (transform: ZoomTransform | ((prev: ZoomTransform) => ZoomTransform)) => void;
+ containerProps: {
+ ref: React.RefObject<HTMLDivElement | null>;
+ onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerMove: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerUp: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerCancel: (e: React.PointerEvent<HTMLDivElement>) => void;
+ /** Capture-phase handlers: track every finger for pinch even when a child stops propagation */
+ onPointerDownCapture: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerMoveCapture: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerUpCapture: (e: React.PointerEvent<HTMLDivElement>) => void;
+ onPointerCancelCapture: (e: React.PointerEvent<HTMLDivElement>) => void;
+ style: React.CSSProperties;
+ };
+}
+
+export function useZoomPan(options: UseZoomPanOptions = {}): UseZoomPanReturn {
+ const {
+ contentSize = null,
+ resetKey,
+ maxFitScale = 1,
+ enableWheel = true,
+ enablePan = true,
+ enableToggleZoom = true,
+ enableInertia = true,
+ enablePinch = true,
+ onGestureStart,
+ onChange,
+ } = options;
+
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const contentRef = useRef<HTMLDivElement | null>(null);
+
+ const [containerSize, setContainerSize] = useState<Size>({ width: 0, height: 0 });
+ const [transform, setTransformState] = useState<ZoomTransform>({ x: 0, y: 0, scale: 1 });
+ const [isPanning, setIsPanning] = useState(false);
+ const [isPinching, setIsPinching] = useState(false);
+
+ // Track if user is currently at "fit" scale so resize preserves fit
+ const wasAtFitRef = useRef(true);
+ const prevResetKeyRef = useRef(resetKey);
+ const prevContentRef = useRef<Size | null>(null);
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+ const onGestureStartRef = useRef(onGestureStart);
+ onGestureStartRef.current = onGestureStart;
+
+ const contentWidth = contentSize && contentSize.width > 0 ? contentSize.width : 1;
+ const contentHeight = contentSize && contentSize.height > 0 ? contentSize.height : 1;
+ const content: Size = useMemo(
+ () => ({ width: contentWidth, height: contentHeight }),
+ [contentWidth, contentHeight],
+ );
+
+ const fitTransform = useMemo(() => {
+ return calculateFit(containerSize, content, maxFitScale);
+ }, [containerSize, content, maxFitScale]);
+
+ // Latest values for gesture/animation callbacks that outlive a render (rAF, capture handlers).
+ const geomRef = useRef({ container: containerSize, content, fitScale: fitTransform.scale });
+ geomRef.current = { container: containerSize, content, fitScale: fitTransform.scale };
+
+ // Inertia (momentum) animation.
+ const inertiaRaf = useRef<number | null>(null);
+ const stopInertia = useCallback(() => {
+ if (inertiaRaf.current !== null) {
+ cancelAnimationFrame(inertiaRaf.current);
+ inertiaRaf.current = null;
+ }
+ }, []);
+ useEffect(() => stopInertia, [stopInertia]);
+
+ const canZoom = useMemo(() => {
+ if (!contentSize || containerSize.width <= 0 || containerSize.height <= 0) return true;
+ return contentSize.width > containerSize.width || contentSize.height > containerSize.height || fitTransform.scale < 0.99;
+ }, [contentSize?.width, contentSize?.height, containerSize.width, containerSize.height, fitTransform.scale]);
+
+ const isZoomed = useMemo(() => {
+ return transform.scale > fitTransform.scale * 1.02;
+ }, [transform.scale, fitTransform.scale]);
+
+ const updateTransform = useCallback(
+ (next: ZoomTransform | ((prev: ZoomTransform) => ZoomTransform)) => {
+ stopInertia();
+ setTransformState((prev) => {
+ const resolved = typeof next === "function" ? next(prev) : next;
+ const clamped = clampOffset({ x: resolved.x, y: resolved.y }, resolved.scale, containerSize, content);
+ const finalTransform = { scale: resolved.scale, x: clamped.x, y: clamped.y };
+ wasAtFitRef.current = Math.abs(finalTransform.scale - fitTransform.scale) < 0.005;
+ return finalTransform;
+ });
+ },
+ [containerSize, content, fitTransform.scale, stopInertia],
+ );
+
+ useEffect(() => {
+ onChangeRef.current?.(transform);
+ }, [transform.scale, transform.x, transform.y]);
+
+ // Measure container dimensions
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+
+ const ro = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const { width, height } = entry.contentRect;
+ if (width > 0 && height > 0) {
+ setContainerSize({ width: Math.round(width), height: Math.round(height) });
+ }
+ }
+ });
+
+ ro.observe(el);
+ const rect = el.getBoundingClientRect();
+ if (rect.width > 0 && rect.height > 0) {
+ setContainerSize({ width: Math.round(rect.width), height: Math.round(rect.height) });
+ }
+
+ return () => ro.disconnect();
+ }, []);
+
+ // Update transform on container resize or content change
+ useLayoutEffect(() => {
+ if (containerSize.width <= 0 || containerSize.height <= 0) return;
+ if (content.width <= 0 || content.height <= 0) return;
+
+ const isFirstRun = prevContentRef.current === null;
+ const contentChanged =
+ prevContentRef.current !== null &&
+ (content.width !== prevContentRef.current.width || content.height !== prevContentRef.current.height);
+ const resetKeyChanged = resetKey !== undefined && resetKey !== prevResetKeyRef.current;
+
+ prevContentRef.current = content;
+ prevResetKeyRef.current = resetKey;
+
+ if (isFirstRun || resetKeyChanged || contentChanged || wasAtFitRef.current) {
+ if (resetKeyChanged || contentChanged) stopInertia();
+ wasAtFitRef.current = true;
+ setTransformState(fitTransform);
+ } else {
+ // Re-clamp current transform to new container dimensions
+ setTransformState((prev) => {
+ const clamped = clampOffset({ x: prev.x, y: prev.y }, prev.scale, containerSize, content);
+ if (clamped.x === prev.x && clamped.y === prev.y) return prev;
+ return { ...prev, x: clamped.x, y: clamped.y };
+ });
+ }
+ }, [containerSize.width, containerSize.height, content.width, content.height, resetKey, fitTransform]);
+
+ // Zoom actions
+ const zoomFit = useCallback(() => {
+ wasAtFitRef.current = true;
+ updateTransform(fitTransform);
+ }, [fitTransform, updateTransform]);
+
+ const zoom100 = useCallback(
+ (focal?: Point) => {
+ const focalPoint = focal ?? {
+ x: containerSize.width / 2,
+ y: containerSize.height / 2,
+ };
+ updateTransform((prev) => zoomAtFocalPoint(prev, focalPoint, 1.0, containerSize, content));
+ },
+ [containerSize, content, updateTransform],
+ );
+
+ const zoomIn = useCallback(() => {
+ const focalPoint = { x: containerSize.width / 2, y: containerSize.height / 2 };
+ const nextScale = nextZoomStep(transform.scale, "in");
+ updateTransform((prev) => zoomAtFocalPoint(prev, focalPoint, nextScale, containerSize, content));
+ }, [containerSize, content, transform.scale, updateTransform]);
+
+ const zoomOut = useCallback(() => {
+ const focalPoint = { x: containerSize.width / 2, y: containerSize.height / 2 };
+ const nextScale = nextZoomStep(transform.scale, "out");
+ updateTransform((prev) => zoomAtFocalPoint(prev, focalPoint, nextScale, containerSize, content));
+ }, [containerSize, content, transform.scale, updateTransform]);
+
+ const toggleZoom = useCallback(
+ (focal?: Point) => {
+ if (isZoomed) {
+ zoomFit();
+ } else {
+ zoom100(focal);
+ }
+ },
+ [isZoomed, zoomFit, zoom100],
+ );
+
+ // Wheel listener with non-passive event registration to prevent page scroll
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el || !enableWheel) return;
+
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ stopInertia();
+
+ const rect = el.getBoundingClientRect();
+ const focalPoint: Point = {
+ x: e.clientX - rect.left,
+ y: e.clientY - rect.top,
+ };
+
+ // Handle trackpad pinch (ctrlKey) vs standard mouse wheel
+ const delta = -e.deltaY;
+ const sensitivity = e.ctrlKey ? 0.012 : 0.002;
+ const zoomFactor = Math.min(1.4, Math.max(0.7, Math.exp(delta * sensitivity)));
+
+ setTransformState((prev) => {
+ const nextScale = clampScale(prev.scale * zoomFactor);
+ const next = zoomAtFocalPoint(prev, focalPoint, nextScale, containerSize, content);
+ wasAtFitRef.current = Math.abs(next.scale - fitTransform.scale) < 0.005;
+ return next;
+ });
+ };
+
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => el.removeEventListener("wheel", onWheel);
+ }, [containerSize, content, enableWheel, fitTransform.scale, stopInertia]);
+
+ // Pointer drag panning
+ const dragRef = useRef<{
+ startX: number;
+ startY: number;
+ initialX: number;
+ initialY: number;
+ moved: boolean;
+ } | null>(null);
+ /** Recent pointer positions during a drag, for the release velocity. */
+ const samplesRef = useRef<MotionSample[]>([]);
+ const transformRef = useRef(transform);
+ transformRef.current = transform;
+
+ const startInertia = useCallback(
+ (velocity: Point) => {
+ stopInertia();
+ if (!enableInertia || prefersReducedMotion() || typeof requestAnimationFrame !== "function") return;
+ if (Math.hypot(velocity.x, velocity.y) < INERTIA_START_SPEED) return;
+ let v = velocity;
+ let pos = transformRef.current;
+ let last = performance.now();
+ const frame = (t: number) => {
+ // Cap dt so a stalled tab does not jump the image across the screen.
+ const dt = Math.min(48, Math.max(1, t - last));
+ last = t;
+ const g = geomRef.current;
+ const step = inertiaStep(pos, v, dt, g.container, g.content);
+ pos = step.transform;
+ v = step.velocity;
+ setTransformState(pos);
+ inertiaRaf.current = step.done ? null : requestAnimationFrame(frame);
+ };
+ inertiaRaf.current = requestAnimationFrame(frame);
+ },
+ [enableInertia, stopInertia],
+ );
+
+ // ---- Two-finger pinch -------------------------------------------------------------------
+ // Tracked in the capture phase so it works over children that stop propagation (the inpaint
+ // canvas, the compare slider): those see the first finger, then `onGestureStart` tells them
+ // to drop what it started.
+ const touches = useRef(new Map<number, Point>());
+ const pinchRef = useRef<PinchStart | null>(null);
+ /** After a pinch, the remaining finger does nothing until every finger is lifted. */
+ const suppressRef = useRef(false);
+
+ const localPoint = (e: React.PointerEvent): Point => {
+ const r = containerRef.current?.getBoundingClientRect();
+ return { x: e.clientX - (r?.left ?? 0), y: e.clientY - (r?.top ?? 0) };
+ };
+
+ const onPointerDownCapture = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ // Any new touch or click catches a fling in progress.
+ stopInertia();
+ if (!enablePinch || e.pointerType !== "touch") return;
+ touches.current.set(e.pointerId, localPoint(e));
+ if (touches.current.size === 2 && !pinchRef.current) {
+ const [p1, p2] = [...touches.current.values()];
+ dragRef.current = null;
+ setIsPanning(false);
+ pinchRef.current = { transform: transformRef.current, p1, p2 };
+ suppressRef.current = true;
+ setIsPinching(true);
+ onGestureStartRef.current?.();
+ e.stopPropagation();
+ }
+ },
+ [enablePinch, stopInertia],
+ );
+
+ const onPointerMoveCapture = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
+ if (!touches.current.has(e.pointerId)) return;
+ touches.current.set(e.pointerId, localPoint(e));
+ const start = pinchRef.current;
+ if (start && touches.current.size >= 2) {
+ const [p1, p2] = [...touches.current.values()];
+ const g = geomRef.current;
+ const next = pinchTransform(start, p1, p2, g.container, g.content);
+ wasAtFitRef.current = Math.abs(next.scale - g.fitScale) < 0.005;
+ setTransformState(next);
+ }
+ if (suppressRef.current) e.stopPropagation();
+ }, []);
+
+ const onTouchEndCapture = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
+ if (!touches.current.delete(e.pointerId)) return;
+ if (pinchRef.current && touches.current.size < 2) {
+ pinchRef.current = null;
+ setIsPinching(false);
+ }
+ if (touches.current.size === 0) suppressRef.current = false;
+ }, []);
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (pinchRef.current || suppressRef.current) return;
+ // Middle button always pans (also where left-drag belongs to a tool, e.g. the inpaint brush).
+ const middle = e.button === 1;
+ if (!enablePan && !middle) return;
+ if (e.button !== 0 && !middle) return;
+ // No browser autoscroll on middle-drag.
+ if (middle) e.preventDefault();
+
+ dragRef.current = {
+ startX: e.clientX,
+ startY: e.clientY,
+ initialX: transform.x,
+ initialY: transform.y,
+ moved: false,
+ };
+ samplesRef.current = [{ t: performance.now(), x: e.clientX, y: e.clientY }];
+ if (typeof e.currentTarget.setPointerCapture === "function") {
+ try {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ } catch {
+ /* ignore pointer capture failure */
+ }
+ }
+ },
+ [enablePan, transform.x, transform.y],
+ );
+
+ const onPointerMove = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ const d = dragRef.current;
+ if (!d) return;
+
+ const dx = e.clientX - d.startX;
+ const dy = e.clientY - d.startY;
+
+ if (!d.moved && Math.hypot(dx, dy) > 4) {
+ d.moved = true;
+ setIsPanning(true);
+ }
+
+ if (d.moved) {
+ const now = performance.now();
+ const samples = samplesRef.current;
+ samples.push({ t: now, x: e.clientX, y: e.clientY });
+ while (samples.length > 2 && now - samples[0].t > 150) samples.shift();
+
+ const rawOffset = { x: d.initialX + dx, y: d.initialY + dy };
+ const clamped = clampOffset(rawOffset, transform.scale, containerSize, content);
+ setTransformState((prev) => {
+ const next = { ...prev, x: clamped.x, y: clamped.y };
+ return next;
+ });
+ }
+ },
+ [containerSize, content, transform.scale],
+ );
+
+ const onPointerUp = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ const d = dragRef.current;
+ dragRef.current = null;
+ setIsPanning(false);
+
+ if (typeof e.currentTarget.releasePointerCapture === "function") {
+ try {
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ }
+ } catch {
+ /* ignore pointer capture release failure */
+ }
+ }
+
+ if (d?.moved) {
+ startInertia(releaseVelocity(samplesRef.current, performance.now()));
+ } else if (d && enableToggleZoom && e.button === 0) {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const focal: Point = {
+ x: e.clientX - rect.left,
+ y: e.clientY - rect.top,
+ };
+ toggleZoom(focal);
+ }
+ samplesRef.current = [];
+ },
+ [enableToggleZoom, startInertia, toggleZoom],
+ );
+
+ const onPointerCancel = useCallback(() => {
+ dragRef.current = null;
+ samplesRef.current = [];
+ setIsPanning(false);
+ }, []);
+
+ const cursorStyle = useMemo(() => {
+ if (isPanning) return "grabbing";
+ if (isZoomed) return "grab";
+ if (enableToggleZoom) return canZoom ? "zoom-in" : "default";
+ return "default";
+ }, [canZoom, enableToggleZoom, isPanning, isZoomed]);
+
+ return {
+ containerRef,
+ contentRef,
+ transform,
+ containerSize,
+ contentSize: content,
+ isZoomed,
+ isPanning,
+ isPinching,
+ canZoom,
+ fitTransform,
+ zoomIn,
+ zoomOut,
+ zoomFit,
+ zoom100,
+ toggleZoom,
+ setTransform: updateTransform,
+ containerProps: {
+ ref: containerRef,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ onPointerCancel,
+ onPointerDownCapture,
+ onPointerMoveCapture,
+ onPointerUpCapture: onTouchEndCapture,
+ onPointerCancelCapture: onTouchEndCapture,
+ style: {
+ cursor: cursorStyle,
+ touchAction: "none",
+ userSelect: "none",
+ },
+ },
+ };
+}
diff --git a/src/lib/zoomMath.test.ts b/src/lib/zoomMath.test.ts
new file mode 100644
index 0000000..5c43fa6
--- /dev/null
+++ b/src/lib/zoomMath.test.ts
@@ -0,0 +1,268 @@
+import { describe, expect, it } from "vitest";
+import {
+ calculateFit,
+ centerOnContentFraction,
+ clampOffset,
+ clampScale,
+ inertiaStep,
+ minimapSize,
+ nextZoomStep,
+ pinchTransform,
+ releaseVelocity,
+ screenToContentPoint,
+ visibleContentRect,
+ zoomAtFocalPoint,
+} from "./zoomMath";
+
+describe("zoomMath", () => {
+ const container = { width: 800, height: 600 };
+ const content = { width: 1600, height: 1200 };
+
+ describe("calculateFit", () => {
+ it("fits larger content centered inside container", () => {
+ const fit = calculateFit(container, content);
+ expect(fit.scale).toBe(0.5);
+ expect(fit.x).toBe(0); // 1600 * 0.5 = 800, fits exactly
+ expect(fit.y).toBe(0); // 1200 * 0.5 = 600, fits exactly
+ });
+
+ it("centers content with different aspect ratio", () => {
+ // 800x600 container, 1000x1000 square content
+ const square = { width: 1000, height: 1000 };
+ const fit = calculateFit(container, square);
+ // scale should be 600 / 1000 = 0.6
+ expect(fit.scale).toBe(0.6);
+ expect(fit.y).toBe(0); // 1000 * 0.6 = 600
+ expect(fit.x).toBe((800 - 600) / 2); // 100px letterbox on left and right
+ });
+
+ it("respects maxScale for smaller content", () => {
+ const small = { width: 200, height: 150 };
+ const fit = calculateFit(container, small, 1);
+ expect(fit.scale).toBe(1); // Not enlarged past 1.0
+ expect(fit.x).toBe((800 - 200) / 2); // 300
+ expect(fit.y).toBe((600 - 150) / 2); // 225
+ });
+ });
+
+ describe("clampOffset", () => {
+ it("centers content when it fits within container", () => {
+ const offset = clampOffset({ x: 50, y: -20 }, 0.5, container, content);
+ // Content is 1600x1200 at scale 0.5 -> 800x600, exactly container size
+ expect(offset.x).toBe(0);
+ expect(offset.y).toBe(0);
+ });
+
+ it("clamps panning when zoomed in", () => {
+ // Scale 1.0 -> content is 1600x1200. Container is 800x600.
+ // x valid range is [800 - 1600, 0] = [-800, 0]
+ // y valid range is [600 - 1200, 0] = [-600, 0]
+ expect(clampOffset({ x: 100, y: 50 }, 1, container, content)).toEqual({ x: 0, y: 0 });
+ expect(clampOffset({ x: -1000, y: -800 }, 1, container, content)).toEqual({ x: -800, y: -600 });
+ expect(clampOffset({ x: -300, y: -200 }, 1, container, content)).toEqual({ x: -300, y: -200 });
+ });
+ });
+
+ describe("zoomAtFocalPoint", () => {
+ it("preserves point under focal position when scaling up", () => {
+ const current = { x: 0, y: 0, scale: 0.5 };
+ const focal = { x: 400, y: 300 }; // Center of 800x600 container
+ // Content point under focal: (400 - 0) / 0.5 = 800, (300 - 0) / 0.5 = 600 (center of 1600x1200)
+ const next = zoomAtFocalPoint(current, focal, 1.0, container, content);
+ expect(next.scale).toBe(1.0);
+ // After scale 1.0, center of 1600x1200 should still be at 400, 300:
+ // rawX = 400 - 800 * 1 = -400
+ // rawY = 300 - 600 * 1 = -300
+ expect(next.x).toBe(-400);
+ expect(next.y).toBe(-300);
+ });
+
+ it("clamps boundaries properly when zooming near edges", () => {
+ const current = { x: 0, y: 0, scale: 0.5 };
+ const focal = { x: 0, y: 0 }; // Top-left corner
+ const next = zoomAtFocalPoint(current, focal, 2.0, container, content);
+ expect(next.scale).toBe(2.0);
+ expect(next.x).toBe(0);
+ expect(next.y).toBe(0);
+ });
+ });
+
+ describe("screenToContentPoint", () => {
+ it("undoes the pan and the scale", () => {
+ const p = screenToContentPoint({ x: 400, y: 300 }, { x: -200, y: -150, scale: 1.5 });
+ expect(p.x).toBeCloseTo(400);
+ expect(p.y).toBeCloseTo(300);
+ });
+ });
+
+ describe("nextZoomStep", () => {
+ it("steps up and down logically", () => {
+ expect(nextZoomStep(1.0, "in")).toBe(1.25);
+ expect(nextZoomStep(1.25, "in")).toBe(1.5);
+ expect(nextZoomStep(1.0, "out")).toBe(0.75);
+ expect(nextZoomStep(0.75, "out")).toBe(0.67);
+ });
+ });
+
+ describe("clampScale", () => {
+ it("constrains within bounds", () => {
+ expect(clampScale(0.01)).toBe(0.05);
+ expect(clampScale(50)).toBe(32);
+ expect(clampScale(1.5)).toBe(1.5);
+ });
+ });
+
+ describe("pinchTransform", () => {
+ it("scales according to change in finger distance", () => {
+ const start = {
+ transform: { x: 0, y: 0, scale: 1 },
+ p1: { x: 300, y: 300 },
+ p2: { x: 500, y: 300 }, // distance = 200
+ };
+ // Distance increases to 400 (ratio = 2.0)
+ const p1 = { x: 200, y: 300 };
+ const p2 = { x: 600, y: 300 };
+ const next = pinchTransform(start, p1, p2, container, content);
+ expect(next.scale).toBe(2);
+ });
+
+ it("keeps midpoint anchor steady during pinch", () => {
+ const start = {
+ transform: { x: -100, y: -100, scale: 1 },
+ p1: { x: 300, y: 300 },
+ p2: { x: 500, y: 300 }, // midpoint = (400, 300)
+ };
+ // Move both fingers right by 50px while maintaining distance
+ const p1 = { x: 350, y: 300 };
+ const p2 = { x: 550, y: 300 };
+ const next = pinchTransform(start, p1, p2, container, content);
+ expect(next.scale).toBe(1);
+ // Midpoint shifted right by 50px, content should pan right by 50px
+ expect(next.x).toBe(-50);
+ expect(next.y).toBe(-100);
+ });
+ });
+
+ describe("releaseVelocity", () => {
+ it("computes release velocity in px/ms from recent samples", () => {
+ const samples = [
+ { t: 0, x: 100, y: 100 },
+ { t: 50, x: 200, y: 150 },
+ { t: 100, x: 300, y: 200 },
+ ];
+ const v = releaseVelocity(samples, 100, 100);
+ // dt = 100 - 0 = 100ms, dx = 200, dy = 100
+ expect(v.x).toBe(2);
+ expect(v.y).toBe(1);
+ });
+
+ it("returns zero velocity if pointer stopped moving before release", () => {
+ const samples = [
+ { t: 0, x: 100, y: 100 },
+ { t: 50, x: 300, y: 300 },
+ ];
+ // Released at t = 200ms (> 100ms after last sample)
+ const v = releaseVelocity(samples, 200, 100);
+ expect(v).toEqual({ x: 0, y: 0 });
+ });
+
+ it("returns zero velocity for fewer than 2 samples", () => {
+ expect(releaseVelocity([], 100)).toEqual({ x: 0, y: 0 });
+ expect(releaseVelocity([{ t: 100, x: 10, y: 10 }], 100)).toEqual({ x: 0, y: 0 });
+ });
+ });
+
+ describe("inertiaStep", () => {
+ it("advances position by velocity * dt and decays velocity", () => {
+ const transform = { x: -400, y: -300, scale: 1 };
+ const velocity = { x: 0.5, y: 0.2 };
+ const step = inertiaStep(transform, velocity, 16, container, content, 0.9);
+
+ // x should advance: -400 + 0.5 * 16 = -392
+ expect(step.transform.x).toBeCloseTo(-392);
+ expect(step.transform.y).toBeCloseTo(-296.8);
+ // velocity decays by friction 0.9
+ expect(step.velocity.x).toBeCloseTo(0.45);
+ expect(step.velocity.y).toBeCloseTo(0.18);
+ expect(step.done).toBe(false);
+ });
+
+ it("zeros velocity on axis when hitting pan bounds", () => {
+ // Content 1600x1200, container 800x600, scale 1.0. Max x is 0.
+ const transform = { x: -5, y: -300, scale: 1 };
+ const velocity = { x: 1.0, y: 0 }; // Moving right, would exceed 0
+ const step = inertiaStep(transform, velocity, 16, container, content);
+
+ expect(step.transform.x).toBe(0);
+ expect(step.velocity.x).toBe(0);
+ expect(step.done).toBe(true);
+ });
+ });
+
+ describe("visibleContentRect", () => {
+ it("returns full fraction (0, 0, 1, 1) when at fit scale", () => {
+ // Content 1600x1200 at scale 0.5 fits 800x600 container exactly
+ const transform = { x: 0, y: 0, scale: 0.5 };
+ const rect = visibleContentRect(transform, container, content);
+ expect(rect.x).toBe(0);
+ expect(rect.y).toBe(0);
+ expect(rect.w).toBe(1);
+ expect(rect.h).toBe(1);
+ });
+
+ it("returns fraction of visible area when zoomed in", () => {
+ // Scale 1.0, container 800x600, content 1600x1200
+ // Pan centered: x = -400, y = -300
+ const transform = { x: -400, y: -300, scale: 1 };
+ const rect = visibleContentRect(transform, container, content);
+
+ // x0 = 400 / 1 / 1600 = 0.25
+ // y0 = 300 / 1 / 1200 = 0.25
+ // x1 = (800 + 400) / 1600 = 0.75 -> w = 0.5
+ // y1 = (600 + 300) / 1200 = 0.75 -> h = 0.5
+ expect(rect.x).toBeCloseTo(0.25);
+ expect(rect.y).toBeCloseTo(0.25);
+ expect(rect.w).toBeCloseTo(0.5);
+ expect(rect.h).toBeCloseTo(0.5);
+ });
+ });
+
+ describe("centerOnContentFraction", () => {
+ it("centers on content point at fraction fx, fy", () => {
+ // Center of content (0.5, 0.5) at scale 1.0 in 800x600 container
+ const transform = { x: 0, y: 0, scale: 1 };
+ const next = centerOnContentFraction(0.5, 0.5, transform, container, content);
+
+ // Content center = (800, 600)
+ // container center = (400, 300)
+ // x = 400 - 800 * 1 = -400
+ // y = 300 - 600 * 1 = -300
+ expect(next.x).toBe(-400);
+ expect(next.y).toBe(-300);
+ expect(next.scale).toBe(1);
+ });
+
+ it("clamps offsets at edges when centering near boundary", () => {
+ const transform = { x: 0, y: 0, scale: 1 };
+ const next = centerOnContentFraction(0, 0, transform, container, content);
+ // Top left fraction (0, 0), clamped to max x = 0, y = 0
+ expect(next.x).toBe(0);
+ expect(next.y).toBe(0);
+ });
+ });
+
+ describe("minimapSize", () => {
+ it("computes aspect-ratio box within maxSide", () => {
+ // 1600x1200 -> aspect ratio 4:3. maxSide 160 -> width 160, height 120
+ const size = minimapSize(content, 160);
+ expect(size.width).toBe(160);
+ expect(size.height).toBe(120);
+
+ // Portrait: 1200x1600 -> width 120, height 160
+ const portrait = minimapSize({ width: 1200, height: 1600 }, 160);
+ expect(portrait.width).toBe(120);
+ expect(portrait.height).toBe(160);
+ });
+ });
+});
+
diff --git a/src/lib/zoomMath.ts b/src/lib/zoomMath.ts
new file mode 100644
index 0000000..22e0799
--- /dev/null
+++ b/src/lib/zoomMath.ts
@@ -0,0 +1,247 @@
+/**
+ * Pure math helpers for 2D zoom and pan transformations.
+ */
+
+export interface Size {
+ width: number;
+ height: number;
+}
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+export interface ZoomTransform {
+ x: number;
+ y: number;
+ scale: number;
+}
+
+export const MIN_ZOOM_SCALE = 0.05;
+export const MAX_ZOOM_SCALE = 32;
+
+/**
+ * Standard discrete zoom levels used for step-wise zooming (+/- buttons or shortcuts).
+ */
+export const ZOOM_STEPS = [0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 1, 1.25, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32];
+
+/**
+ * Clamps scale within safe bounds.
+ */
+export function clampScale(scale: number, min = MIN_ZOOM_SCALE, max = MAX_ZOOM_SCALE): number {
+ return Math.min(max, Math.max(min, scale));
+}
+
+/**
+ * Calculates transform to fit content centered inside container.
+ * If maxScale is set (e.g. 1.0), prevents enlarging content smaller than container.
+ */
+export function calculateFit(container: Size, content: Size, maxScale = 1): ZoomTransform {
+ if (container.width <= 0 || container.height <= 0 || content.width <= 0 || content.height <= 0) {
+ return { x: 0, y: 0, scale: 1 };
+ }
+ const fitScale = Math.min(container.width / content.width, container.height / content.height);
+ const scale = clampScale(maxScale > 0 ? Math.min(fitScale, maxScale) : fitScale);
+ const x = (container.width - content.width * scale) / 2;
+ const y = (container.height - content.height * scale) / 2;
+ return { x, y, scale };
+}
+
+/**
+ * Clamps translation offsets so zoomed content does not get lost outside container viewport.
+ * If content fits along an axis, it is centered.
+ */
+export function clampOffset(offset: Point, scale: number, container: Size, content: Size): Point {
+ const renderedW = content.width * scale;
+ const renderedH = content.height * scale;
+
+ let x: number;
+ if (renderedW <= container.width) {
+ x = (container.width - renderedW) / 2;
+ } else {
+ // When larger than container, cannot pan past left edge (0) or right edge (container.width - renderedW)
+ x = Math.max(container.width - renderedW, Math.min(0, offset.x));
+ }
+
+ let y: number;
+ if (renderedH <= container.height) {
+ y = (container.height - renderedH) / 2;
+ } else {
+ // Cannot pan past top edge (0) or bottom edge (container.height - renderedH)
+ y = Math.max(container.height - renderedH, Math.min(0, offset.y));
+ }
+
+ return { x, y };
+}
+
+/**
+ * Zooms into or out of a specific focal point in container coordinates.
+ * The content point directly beneath focalPoint remains pinned at focalPoint after scaling.
+ */
+export function zoomAtFocalPoint(
+ current: ZoomTransform,
+ focalPoint: Point,
+ targetScale: number,
+ container: Size,
+ content: Size,
+): ZoomTransform {
+ const scale = clampScale(targetScale);
+ if (current.scale <= 0) return { x: 0, y: 0, scale };
+
+ // Determine the content-space coordinate currently under focalPoint
+ const contentX = (focalPoint.x - current.x) / current.scale;
+ const contentY = (focalPoint.y - current.y) / current.scale;
+
+ // New translation that preserves the content coordinate under focalPoint
+ const rawX = focalPoint.x - contentX * scale;
+ const rawY = focalPoint.y - contentY * scale;
+
+ const clamped = clampOffset({ x: rawX, y: rawY }, scale, container, content);
+ return {
+ scale,
+ x: clamped.x,
+ y: clamped.y,
+ };
+}
+
+/**
+ * Maps a container screen point to coordinates within content space.
+ */
+export function screenToContentPoint(screenPoint: Point, transform: ZoomTransform): Point {
+ return {
+ x: (screenPoint.x - transform.x) / transform.scale,
+ y: (screenPoint.y - transform.y) / transform.scale,
+ };
+}
+
+/**
+ * Finds the next discrete zoom step for stepping in or out.
+ */
+export function nextZoomStep(currentScale: number, direction: "in" | "out"): number {
+ const tolerance = 0.02;
+ if (direction === "in") {
+ const next = ZOOM_STEPS.find((s) => s > currentScale * (1 + tolerance));
+ return next ?? clampScale(currentScale * 1.25);
+ } else {
+ const prev = [...ZOOM_STEPS].reverse().find((s) => s < currentScale * (1 - tolerance));
+ return prev ?? clampScale(currentScale / 1.25);
+ }
+}
+
+// Gestures (pinch, inertia) and the mini-map navigator.
+
+/** State captured when a two-finger pinch begins. Points are in container coordinates. */
+export interface PinchStart {
+ transform: ZoomTransform;
+ p1: Point;
+ p2: Point;
+}
+
+/**
+ * Two-finger pinch: scales by the change in finger distance and keeps the content point that was
+ * under the starting midpoint under the current midpoint, so the image follows both fingers
+ * (zoom and pan in one gesture).
+ */
+export function pinchTransform(start: PinchStart, p1: Point, p2: Point, container: Size, content: Size): ZoomTransform {
+ const d0 = Math.hypot(start.p2.x - start.p1.x, start.p2.y - start.p1.y);
+ const d1 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const ratio = d0 > 0 && d1 > 0 ? d1 / d0 : 1;
+ const scale = clampScale(start.transform.scale * ratio);
+
+ const m0 = { x: (start.p1.x + start.p2.x) / 2, y: (start.p1.y + start.p2.y) / 2 };
+ const m1 = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
+ const anchor = screenToContentPoint(m0, start.transform);
+
+ const clamped = clampOffset({ x: m1.x - anchor.x * scale, y: m1.y - anchor.y * scale }, scale, container, content);
+ return { scale, x: clamped.x, y: clamped.y };
+}
+
+/** A pointer position sample used to estimate release velocity (t in ms). */
+export interface MotionSample {
+ t: number;
+ x: number;
+ y: number;
+}
+
+/**
+ * Release velocity in px/ms from the samples of the last `windowMs`. A pointer that stopped before
+ * being released (no recent samples) has zero velocity, so it does not fling.
+ */
+export function releaseVelocity(samples: MotionSample[], now: number, windowMs = 100): Point {
+ const recent = samples.filter((s) => now - s.t <= windowMs);
+ if (recent.length < 2) return { x: 0, y: 0 };
+ const a = recent[0];
+ const b = recent[recent.length - 1];
+ const dt = b.t - a.t;
+ if (dt <= 0) return { x: 0, y: 0 };
+ return { x: (b.x - a.x) / dt, y: (b.y - a.y) / dt };
+}
+
+/** Velocity (px/ms) below which a fling stops. */
+export const INERTIA_MIN_SPEED = 0.02;
+/** Release speed (px/ms) needed to start a fling (~150 px/s). */
+export const INERTIA_START_SPEED = 0.15;
+/** Velocity kept per 16 ms frame. */
+export const INERTIA_FRICTION = 0.92;
+
+/**
+ * One inertia frame: moves by velocity × dt, decays the velocity (frame-rate independent), and
+ * stops an axis that hits the pan bounds so the image does not "stick" against an edge.
+ */
+export function inertiaStep(
+ transform: ZoomTransform,
+ velocity: Point,
+ dtMs: number,
+ container: Size,
+ content: Size,
+ friction = INERTIA_FRICTION,
+): { transform: ZoomTransform; velocity: Point; done: boolean } {
+ const raw = { x: transform.x + velocity.x * dtMs, y: transform.y + velocity.y * dtMs };
+ const clamped = clampOffset(raw, transform.scale, container, content);
+ const decay = Math.pow(friction, dtMs / 16);
+ const vx = Math.abs(clamped.x - raw.x) > 0.01 ? 0 : velocity.x * decay;
+ const vy = Math.abs(clamped.y - raw.y) > 0.01 ? 0 : velocity.y * decay;
+ const done = Math.hypot(vx, vy) < INERTIA_MIN_SPEED;
+ return { transform: { scale: transform.scale, x: clamped.x, y: clamped.y }, velocity: { x: vx, y: vy }, done };
+}
+
+/** Rectangle as fractions (0..1) of the content. */
+export interface FractionRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+/** The part of the content visible in the viewport, as fractions of the content (for the mini-map). */
+export function visibleContentRect(transform: ZoomTransform, container: Size, content: Size): FractionRect {
+ if (transform.scale <= 0 || content.width <= 0 || content.height <= 0) return { x: 0, y: 0, w: 1, h: 1 };
+ const x0 = Math.max(0, -transform.x / transform.scale / content.width);
+ const y0 = Math.max(0, -transform.y / transform.scale / content.height);
+ const x1 = Math.min(1, (container.width - transform.x) / transform.scale / content.width);
+ const y1 = Math.min(1, (container.height - transform.y) / transform.scale / content.height);
+ return { x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) };
+}
+
+/** Pans (same scale) so the content point at fractions (fx, fy) sits in the viewport centre. */
+export function centerOnContentFraction(
+ fx: number,
+ fy: number,
+ transform: ZoomTransform,
+ container: Size,
+ content: Size,
+): ZoomTransform {
+ const cx = Math.min(1, Math.max(0, fx)) * content.width;
+ const cy = Math.min(1, Math.max(0, fy)) * content.height;
+ const raw = { x: container.width / 2 - cx * transform.scale, y: container.height / 2 - cy * transform.scale };
+ const clamped = clampOffset(raw, transform.scale, container, content);
+ return { scale: transform.scale, x: clamped.x, y: clamped.y };
+}
+
+/** Mini-map box size: the content's aspect ratio within a `maxSide` square. */
+export function minimapSize(content: Size, maxSide = 160): Size {
+ if (content.width <= 0 || content.height <= 0) return { width: maxSide, height: maxSide };
+ const k = maxSide / Math.max(content.width, content.height);
+ return { width: Math.round(content.width * k), height: Math.round(content.height * k) };
+}
diff --git a/src/styles.css b/src/styles.css
index 9dded5b..975e450 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -316,7 +316,7 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font
.editor-tools .slider { display: flex; align-items: center; gap: 8px; padding: 0 10px; font-size: 12px; color: var(--text-2); }
.editor-tools .slider input { width: 110px; }
.mask-wrap { position: relative; touch-action: none; }
-.mask-wrap img { display: block; max-width: 100%; max-height: 100%; user-select: none; -webkit-user-drag: none; }
+.mask-wrap img { display: block; width: 100%; height: 100%; user-select: none; -webkit-user-drag: none; }
.mask-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; mix-blend-mode: difference; opacity: 0.75; cursor: none; }
.brush-cursor { position: absolute; pointer-events: none; border: 1.5px solid #fff; mix-blend-mode: difference; border-radius: 50%; transform: translate(-50%, -50%); }
@@ -390,11 +390,14 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font
.compare-overlay .seg button.on { background: rgba(255, 255, 255, 0.92); color: #111; box-shadow: none; }
.compare-box { position: relative; border-radius: 6px; overflow: hidden; touch-action: none; user-select: none; background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
.compare-box.slider { cursor: ew-resize; }
+.compare-box.slider.zoomed { cursor: inherit; }
.compare-img, .compare-diff { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
/* Areas the original did not cover (expanded edges) show the checkerboard. */
.compare-before { position: absolute; inset: 0; background-color: var(--bg); background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
.compare-before img { position: absolute; display: block; }
-.compare-handle { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); pointer-events: none; }
+.compare-handle { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); cursor: ew-resize; }
+/* a wider grab area, so the handle can be dragged while zoomed in */
+.compare-handle::after { content: ""; position: absolute; top: 0; bottom: 0; left: -14px; right: -14px; }
.compare-handle span { position: absolute; top: 50%; left: 50%; width: 28px; height: 28px; margin: -14px 0 0 -14px; border-radius: 50%; background: #fff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); }
.compare-handle span::before, .compare-handle span::after { content: ""; position: absolute; top: 9px; border: 5px solid transparent; }
.compare-handle span::before { left: 2px; border-right-color: #333; }
@@ -416,10 +419,29 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font
.viewer-scroll.zoomed { display: block; overflow: auto; cursor: grab; scrollbar-width: none; }
.viewer-scroll.zoomed:active { cursor: grabbing; }
.viewer-img { max-width: 100vw; max-height: 100vh; object-fit: contain; display: block; cursor: zoom-in; user-select: none; }
+/* zoom and pan (full screen and the inpaint editor): components/ZoomPan.tsx */
+.zoom-pan-viewport { position: absolute; inset: 0; overflow: hidden; }
+.zoom-pan-content { position: absolute; top: 0; left: 0; }
+.zoom-pan-img { display: block; width: 100%; height: 100%; user-select: none; pointer-events: none; }
+.zoom-controls { position: absolute; bottom: 16px; left: 50%; z-index: 10; display: flex; align-items: center; gap: 2px; padding: 3px; border-radius: 10px; color: #fff; background: rgba(0, 0, 0, 0.55); backdrop-filter: blur(10px); transform: translateX(-50%); transition: opacity 0.2s; }
+.zoom-controls.hidden { opacity: 0; pointer-events: none; }
+.zoom-btn { height: 28px; min-width: 28px; border-radius: 8px; display: grid; place-items: center; color: rgba(255, 255, 255, 0.8); }
+.zoom-btn.text { padding: 0 10px; font-size: 12px; }
+.zoom-btn:hover:not(:disabled) { background: rgba(255, 255, 255, 0.15); color: #fff; }
+.zoom-pct { width: 52px; text-align: center; font-size: 12px; font-variant-numeric: tabular-nums; }
+.zoom-minimap { position: absolute; right: 16px; bottom: 16px; z-index: 10; border-radius: 10px; overflow: hidden; background: rgba(0, 0, 0, 0.55); backdrop-filter: blur(10px); cursor: crosshair; touch-action: none; }
+.zoom-minimap-img { display: block; width: 100%; height: 100%; opacity: 0.7; pointer-events: none; }
+.zoom-minimap-viewport { position: absolute; border: 1.5px solid #fff; border-radius: 3px; box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.4); pointer-events: none; }
/* comparison full screen: the frame leaves room for the view switch at the bottom */
.viewer-frame { position: absolute; inset: 60px 12px 64px; display: flex; align-items: center; justify-content: center; }
.viewer-compare-bar { position: absolute; left: 0; right: 0; bottom: 14px; display: flex; justify-content: center; }
.viewer-compare-bar .compare-bar { margin: 0; padding: 4px; border-radius: 12px; background: rgba(20, 20, 20, 0.85); }
+/* full screen is viewed from further away: larger view switch and zoom bar */
+.viewer-compare-bar .seg button { height: 34px; padding: 0 16px; font-size: 13px; }
+.viewer .zoom-btn { height: 36px; min-width: 36px; }
+.viewer .zoom-btn.text { padding: 0 14px; }
+.viewer .zoom-btn.text, .viewer .zoom-pct { font-size: 13px; }
+.viewer .zoom-pct { width: 60px; }
.viewer-bar { position: absolute; top: 12px; right: 12px; display: flex; align-items: center; gap: 10px; }
.viewer-hint, .viewer-tag { font-size: 12px; color: rgba(255, 255, 255, 0.8); background: rgba(0, 0, 0, 0.55); padding: 4px 10px; border-radius: 8px; }
.viewer-tag { color: #fff; font-weight: 600; }