Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): add zoom/pan to the shared file-preview image kernel (#893)

Call Whited8c182960910
diff --git a/ui/src/components/ui/file-preview.tsx b/ui/src/components/ui/file-preview.tsx
index 72aa71c58..a191e6f1a 100644
--- a/ui/src/components/ui/file-preview.tsx
+++ b/ui/src/components/ui/file-preview.tsx
@@ -1,8 +1,9 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
+import { ChevronLeft, ChevronRight, Download, Loader2, Maximize2, ZoomIn, ZoomOut } from 'lucide-react';
import clsx from 'clsx';
+import { Button } from '@/components/ui/button';
import { Markdown } from '@/components/ui/markdown';
import { useTheme } from '@/context/ThemeContext';
import { apiFetch } from '@/lib/apiFetch';
@@ -17,6 +18,7 @@ import {
codeLanguage,
previewRenderKind,
} from '@/lib/filePreview';
+import { FIT_VIEW, type ImageView, clampPan, maxScale, oneToOneScale, toggleScale, zoomPercent, zoomToPoint } from '@/lib/imageZoom';
// ── Shared file-preview kernel ("Quick Look") ───────────────────────────────
// One read-only renderer for every previewable file, reused by the File Browser overlay, the editor's
@@ -44,17 +46,22 @@ export type PreviewSource = {
// lives in its own module and loads lazily here.
const PreviewJson = React.lazy(() => import('@/components/ui/preview-json'));
-export const FilePreview: React.FC<{ source: PreviewSource; className?: string; onText?: (text: string) => void }> = ({
+// ``onDownload`` — optional. When set, the image renderer's control cluster shows a download button
+// that invokes it. Only a shell that does NOT already expose its own download affordance should pass
+// it (today: the editor's preview tab); the chat modal, Files Preview window and mobile overlay carry
+// download in their own chrome, so they leave this unset to avoid a duplicate control.
+export const FilePreview: React.FC<{ source: PreviewSource; className?: string; onText?: (text: string) => void; onDownload?: () => void }> = ({
source,
className,
onText,
+ onDownload,
}) => {
const { t } = useTranslation();
const kind = previewRenderKind(source.name, source.mime, source.ext);
if (!kind) return <Centered className={className}>{t('preview.unsupported')}</Centered>;
if (kind === 'image')
- return source.url ? <ImageBody src={source.url} name={source.name} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
+ return source.url ? <ImageBody src={source.url} name={source.name} className={className} onDownload={onDownload} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
if (kind === 'pdf')
return source.url ? <PdfView url={source.url} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
if (kind === 'docx' || kind === 'xlsx' || kind === 'pptx') {
@@ -83,34 +90,209 @@ const Spinner: React.FC<{ className?: string }> = ({ className }) => (
);
// ── Image / SVG ──────────────────────────────────────────────────────────────
-// Fit-to-container by default; click toggles 1:1 actual size. `src` is a content URL (raster) or a
-// data: URL (SVG rendered from its text) — an <img> neutralizes any script in an SVG, so it's safe.
-const ImageBody: React.FC<{ src: string; name?: string; className?: string }> = ({ src, name, className }) => {
+// Fit-to-container by default, with zoom/pan matching the chat lightbox's feel (image-viewer.tsx):
+// wheel / trackpad zoom anchored at the cursor, pinch zoom + drag pan on touch, double-click / tap to
+// toggle fit ⇄ 100% (actual pixels), and a floating control cluster (zoom out / percent / zoom in /
+// reset — plus an optional download when the surrounding shell offers none of its own). The transform
+// is hand-rolled (pure math in ``@/lib/imageZoom``) rather than pulling react-zoom-pan-pinch into the
+// kernel: the kernel keeps every heavy engine out of the shared bundle, and a single <img>'s zoom does
+// not warrant a dependency. Every shell that renders the kernel inherits this automatically. `src` is a
+// content URL (raster) or a data: URL (SVG rendered from its text — an <img> neutralizes any SVG script).
+const WHEEL_ZOOM_SENSITIVITY = 0.0015; // per normalized wheel-delta pixel; a ~100px notch is ~±16%
+const BUTTON_ZOOM_STEP = 1.5; // ×/÷ per zoom-in / zoom-out button press
+// Overlay buttons sit on the dark image mat, so the themed ghost foreground/hover (tuned for app
+// surfaces) would vanish — override to white-on-translucent, compact, while keeping Button's focus /
+// disabled / aria→title behavior. Mirrors image-viewer.tsx's OVERLAY_BTN.
+const ZOOM_BTN = 'h-8 w-8 rounded-full text-white hover:bg-white/15 hover:text-white';
+
+const ImageBody: React.FC<{ src: string; name?: string; className?: string; onDownload?: () => void }> = ({ src, name, className, onDownload }) => {
const { t } = useTranslation();
const [status, setStatus] = React.useState<'loading' | 'ready' | 'error'>('loading');
- const [actual, setActual] = React.useState(false);
+ const [view, setView] = React.useState<ImageView>(FIT_VIEW);
+ // The 1:1 scale (natural ÷ fit): drives the percent readout, the double-click 100% target and the
+ // max zoom. Measured on load and re-measured on resize, because the fit size tracks the container.
+ const [oneToOne, setOneToOne] = React.useState(1);
+
+ const stageRef = React.useRef<HTMLDivElement>(null);
+ const imgRef = React.useRef<HTMLImageElement>(null);
+ // Live touch/mouse pointers, tracked across moves so lifting one finger transitions cleanly from a
+ // pinch back to a one-finger pan. ``pinch`` holds the previous two-finger distance/midpoint.
+ const pointers = React.useRef(new Map<number, { x: number; y: number }>());
+ const pinch = React.useRef<{ dist: number; midX: number; midY: number } | null>(null);
+
React.useEffect(() => {
setStatus('loading');
- setActual(false);
+ setView(FIT_VIEW);
}, [src]);
+ // Read geometry straight from the DOM on every gesture, so zoom/pan stays correct after the shell
+ // (e.g. the Preview window) is resized with no stored size to go stale. ``offsetWidth/Height`` are
+ // the untransformed fit-layout sizes — the CSS transform doesn't affect them. Coordinates returned
+ // are the stage centre in client space (the anchor origin the zoom math expects).
+ const measure = React.useCallback(() => {
+ const stage = stageRef.current;
+ const img = imgRef.current;
+ if (!stage || !img) return null;
+ const rect = stage.getBoundingClientRect();
+ const one = oneToOneScale(img.naturalWidth, img.offsetWidth);
+ return { cx: rect.left + rect.width / 2, cy: rect.top + rect.height / 2, cw: rect.width, ch: rect.height, fw: img.offsetWidth, fh: img.offsetHeight, one, max: maxScale(one) };
+ }, []);
+
+ // Native, non-passive wheel listener: React's synthetic onWheel is passive, so preventDefault (which
+ // stops the shell/page from scrolling while we zoom) wouldn't take. Cursor-anchored.
+ React.useEffect(() => {
+ const stage = stageRef.current;
+ if (!stage) return;
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ const m = measure();
+ if (!m) return;
+ // Normalize line / page delta modes to pixels so a mouse wheel and a trackpad feel consistent.
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? m.ch : 1;
+ const factor = Math.exp(-e.deltaY * unit * WHEEL_ZOOM_SENSITIVITY);
+ setView((v) => clampPan(zoomToPoint(v, v.scale * factor, e.clientX - m.cx, e.clientY - m.cy, m.max), m.fw, m.fh, m.cw, m.ch));
+ };
+ stage.addEventListener('wheel', onWheel, { passive: false });
+ return () => stage.removeEventListener('wheel', onWheel);
+ }, [measure]);
+
+ // Re-clamp the pan (and refresh the 1:1 scale for the readout) when the stage resizes — a shrunk
+ // window must not leave a zoomed image showing dead margin.
+ React.useEffect(() => {
+ const stage = stageRef.current;
+ if (!stage || typeof ResizeObserver === 'undefined') return;
+ const ro = new ResizeObserver(() => {
+ const m = measure();
+ if (!m) return;
+ setOneToOne(m.one);
+ setView((v) => clampPan(v, m.fw, m.fh, m.cw, m.ch));
+ });
+ ro.observe(stage);
+ return () => ro.disconnect();
+ }, [measure]);
+
+ const onPointerDown = (e: React.PointerEvent) => {
+ if (status !== 'ready') return;
+ stageRef.current?.setPointerCapture(e.pointerId);
+ pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ if (pointers.current.size === 2) {
+ const [a, b] = [...pointers.current.values()];
+ pinch.current = { dist: Math.hypot(a.x - b.x, a.y - b.y), midX: (a.x + b.x) / 2, midY: (a.y + b.y) / 2 };
+ }
+ };
+
+ const onPointerMove = (e: React.PointerEvent) => {
+ const prev = pointers.current.get(e.pointerId);
+ if (!prev) return;
+ const cur = { x: e.clientX, y: e.clientY };
+ pointers.current.set(e.pointerId, cur);
+ const m = measure();
+ if (!m) return;
+ if (pointers.current.size >= 2 && pinch.current) {
+ // Pinch: scale by the change in finger distance (anchored at the midpoint) AND pan by the
+ // midpoint's own movement, so two fingers zoom and drag at once.
+ const [a, b] = [...pointers.current.values()];
+ const dist = Math.hypot(a.x - b.x, a.y - b.y);
+ const midX = (a.x + b.x) / 2;
+ const midY = (a.y + b.y) / 2;
+ const ratio = pinch.current.dist > 0 ? dist / pinch.current.dist : 1;
+ const dx = midX - pinch.current.midX;
+ const dy = midY - pinch.current.midY;
+ pinch.current = { dist, midX, midY };
+ setView((v) => {
+ const zoomed = zoomToPoint(v, v.scale * ratio, midX - m.cx, midY - m.cy, m.max);
+ return clampPan({ scale: zoomed.scale, x: zoomed.x + dx, y: zoomed.y + dy }, m.fw, m.fh, m.cw, m.ch);
+ });
+ } else if (pointers.current.size === 1) {
+ // Drag pan — only meaningful once zoomed in (clampPan pins a fit-sized image centred anyway).
+ const dx = cur.x - prev.x;
+ const dy = cur.y - prev.y;
+ setView((v) => (v.scale > 1 ? clampPan({ scale: v.scale, x: v.x + dx, y: v.y + dy }, m.fw, m.fh, m.cw, m.ch) : v));
+ }
+ };
+
+ const endPointer = (e: React.PointerEvent) => {
+ pointers.current.delete(e.pointerId);
+ if (pointers.current.size < 2) pinch.current = null;
+ };
+
+ const onDoubleClick = (e: React.MouseEvent) => {
+ if (status !== 'ready') return;
+ const m = measure();
+ if (!m) return;
+ setView((v) => clampPan(zoomToPoint(v, toggleScale(v.scale, m.one, m.max), e.clientX - m.cx, e.clientY - m.cy, m.max), m.fw, m.fh, m.cw, m.ch));
+ };
+
+ // Buttons zoom about the stage centre (anchor 0,0 in centre-relative coords).
+ const zoomByButton = (dir: 1 | -1) => {
+ const m = measure();
+ if (!m) return;
+ setView((v) => clampPan(zoomToPoint(v, dir > 0 ? v.scale * BUTTON_ZOOM_STEP : v.scale / BUTTON_ZOOM_STEP, 0, 0, m.max), m.fw, m.fh, m.cw, m.ch));
+ };
+
if (status === 'error') return <Centered className={clsx('!bg-[#0c0c0f]', className)}>{t('preview.failed')}</Centered>;
+
+ const atFit = view.scale <= 1.001;
+ const atMax = view.scale >= maxScale(oneToOne) - 0.001;
+
return (
- <div className={clsx('grid h-full min-h-0 place-items-center overflow-auto bg-[#0c0c0f] p-4', className)}>
- {status === 'loading' && <div className="col-start-1 row-start-1 text-[12px] text-muted">{t('common.loading')}</div>}
- <img
- src={src}
- alt={name || ''}
- onLoad={() => setStatus('ready')}
- onError={() => setStatus('error')}
- onClick={() => setActual((a) => !a)}
- draggable={false}
- className={clsx(
- 'col-start-1 row-start-1 select-none',
- actual ? 'max-w-none cursor-zoom-out' : 'max-h-full max-w-full cursor-zoom-in object-contain',
- status !== 'ready' && 'opacity-0',
- )}
- />
+ <div className={clsx('relative h-full min-h-0 overflow-hidden bg-[#0c0c0f]', className)}>
+ <div
+ ref={stageRef}
+ className="absolute inset-0 touch-none select-none overflow-hidden"
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endPointer}
+ onPointerCancel={endPointer}
+ onDoubleClick={onDoubleClick}
+ >
+ {status === 'loading' && <div className="absolute inset-0 grid place-items-center text-[12px] text-muted">{t('common.loading')}</div>}
+ <img
+ ref={imgRef}
+ src={src}
+ alt={name || ''}
+ onLoad={() => {
+ setStatus('ready');
+ const m = measure();
+ if (m) setOneToOne(m.one);
+ }}
+ onError={() => setStatus('error')}
+ draggable={false}
+ style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }}
+ className={clsx(
+ 'absolute inset-0 m-auto max-h-full max-w-full object-contain',
+ status !== 'ready' && 'opacity-0',
+ view.scale > 1 ? 'cursor-grab active:cursor-grabbing' : 'cursor-zoom-in',
+ )}
+ />
+ </div>
+ {status === 'ready' && (
+ // Control cluster — a sibling of the gesture stage so its own clicks/wheel never feed the
+ // pan/zoom handlers. The strip is transparent to pointer events except the pill; the bottom
+ // safe-area inset keeps it clear of the mobile home indicator inside the full-screen overlay.
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-3" style={{ paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))' }}>
+ <div className="pointer-events-auto flex items-center gap-0.5 rounded-full bg-black/55 px-1 py-1 text-white shadow-lg backdrop-blur-sm">
+ <Button variant="ghost" size="icon" className={ZOOM_BTN} onClick={() => zoomByButton(-1)} disabled={atFit} aria-label={t('preview.zoomOut')}>
+ <ZoomOut className="size-4" />
+ </Button>
+ <span className="min-w-[3.25rem] text-center text-[11px] font-medium tabular-nums" aria-live="polite">
+ {zoomPercent(view.scale, oneToOne)}%
+ </span>
+ <Button variant="ghost" size="icon" className={ZOOM_BTN} onClick={() => zoomByButton(1)} disabled={atMax} aria-label={t('preview.zoomIn')}>
+ <ZoomIn className="size-4" />
+ </Button>
+ <span className="mx-0.5 h-4 w-px bg-white/20" aria-hidden />
+ <Button variant="ghost" size="icon" className={ZOOM_BTN} onClick={() => setView(FIT_VIEW)} disabled={atFit} aria-label={t('preview.resetZoom')}>
+ <Maximize2 className="size-4" />
+ </Button>
+ {onDownload && (
+ <Button variant="ghost" size="icon" className={ZOOM_BTN} onClick={onDownload} aria-label={t('preview.download')}>
+ <Download className="size-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
</div>
);
};
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index f169e435d..1f89e828f 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -758,7 +758,10 @@ export const EditorApp: React.FC<{
tabs.map((tab) => (
<div key={tab.id} className={clsx('absolute inset-0', active === tab.id ? 'block' : 'hidden')}>
{tab.kind === 'preview' && tab.path ? (
- <FilePreview source={{ url: contentUrl(tab.path), name: tab.name }} />
+ // Preview tabs have no chrome of their own (unlike the chat modal / Files
+ // Preview window / mobile overlay), so hand the kernel a download action for
+ // its image control cluster — the one image shell that would otherwise lack it.
+ <FilePreview source={{ url: contentUrl(tab.path), name: tab.name }} onDownload={() => downloadFile(tab.path!)} />
) : (
<Suspense fallback={<div className="grid h-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}>
<FileEditorPane
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 034e9e3c0..9cc7ee339 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -21,7 +21,11 @@
"truncated": "Large file — showing only the first part.",
"empty": "This file is empty.",
"csvTruncated": "Showing the first {{count}} rows",
- "csvColsTruncated": "Showing {{shown}} of {{total}} columns"
+ "csvColsTruncated": "Showing {{shown}} of {{total}} columns",
+ "zoomIn": "Zoom in",
+ "zoomOut": "Zoom out",
+ "resetZoom": "Reset zoom",
+ "download": "Download"
},
"common": {
"back": "Back",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 59d1bc137..8da4be510 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -21,7 +21,11 @@
"truncated": "文件较大,仅显示开头部分。",
"empty": "此文件为空。",
"csvTruncated": "仅显示前 {{count}} 行",
- "csvColsTruncated": "显示前 {{shown}} 列,共 {{total}} 列"
+ "csvColsTruncated": "显示前 {{shown}} 列,共 {{total}} 列",
+ "zoomIn": "放大",
+ "zoomOut": "缩小",
+ "resetZoom": "重置缩放",
+ "download": "下载"
},
"common": {
"back": "返回",
diff --git a/ui/src/lib/imageZoom.test.ts b/ui/src/lib/imageZoom.test.ts
new file mode 100644
index 000000000..7d5a0c311
--- /dev/null
+++ b/ui/src/lib/imageZoom.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ FIT_VIEW,
+ MAX_ZOOM_FACTOR,
+ clamp,
+ clampPan,
+ maxScale,
+ oneToOneScale,
+ toggleScale,
+ zoomPercent,
+ zoomToPoint,
+} from './imageZoom';
+
+// The kernel image zoom is measured against these: they encode the interaction feel (min at fit,
+// cursor-anchored zoom, bounded pan, fit⇄100% toggle) that jsdom can't exercise because it does no
+// layout. If any of these fail, the on-screen behavior is wrong.
+
+describe('oneToOneScale', () => {
+ it('is 1 when the image fits at its natural size (fit did not shrink it)', () => {
+ expect(oneToOneScale(400, 400)).toBe(1);
+ });
+ it('is the shrink ratio for an image whose fit is below its natural size', () => {
+ expect(oneToOneScale(2000, 500)).toBe(4); // shown at a quarter → 1:1 is 4× the fit
+ });
+ it('never drops below 1 and tolerates unknown (0) sizes', () => {
+ expect(oneToOneScale(300, 600)).toBe(1); // fit somehow larger → clamp to 1, don't downscale
+ expect(oneToOneScale(0, 500)).toBe(1);
+ expect(oneToOneScale(500, 0)).toBe(1);
+ });
+});
+
+describe('maxScale', () => {
+ it('is the 5× fit ceiling for a normal image', () => {
+ expect(maxScale(1)).toBe(MAX_ZOOM_FACTOR);
+ expect(maxScale(3)).toBe(MAX_ZOOM_FACTOR);
+ });
+ it('rises to the 1:1 scale so an oversized image can always reach 100%', () => {
+ expect(maxScale(8)).toBe(8);
+ });
+});
+
+describe('zoomPercent', () => {
+ it('reads 100% at the 1:1 scale regardless of how much fit shrank the image', () => {
+ expect(zoomPercent(4, 4)).toBe(100); // oversized image, at 1:1
+ expect(zoomPercent(1, 1)).toBe(100); // small image, fit already == natural
+ });
+ it('reads below 100% at fit for an oversized image', () => {
+ expect(zoomPercent(1, 4)).toBe(25); // fit shows a quarter of natural
+ });
+});
+
+describe('zoomToPoint', () => {
+ it('clamps scale to [1, max] and never zooms out past fit', () => {
+ expect(zoomToPoint(FIT_VIEW, 0.5, 0, 0, 5).scale).toBe(1);
+ expect(zoomToPoint(FIT_VIEW, 99, 0, 0, 5).scale).toBe(5);
+ });
+ it('keeps the anchor point visually fixed (cursor-anchored zoom)', () => {
+ // Zooming from fit to 2× about a point 100px right of centre: that point must stay put, so the
+ // image centre shifts left by the amount the point moved out under it.
+ const out = zoomToPoint(FIT_VIEW, 2, 100, 0, 5);
+ expect(out.scale).toBe(2);
+ // image-local anchor before = (ax - x)/scale = 100; after must map back to the same screen ax:
+ // ax === x' + scale*localAnchor → 100 === out.x + 2*100 → out.x === -100
+ expect(out.x).toBe(-100);
+ expect(out.y).toBe(0);
+ });
+ it('anchors at the centre for button/reset zoom (ax=ay=0 leaves the centre fixed)', () => {
+ const out = zoomToPoint(FIT_VIEW, 3, 0, 0, 5);
+ expect(out).toEqual({ scale: 3, x: 0, y: 0 });
+ });
+});
+
+describe('clampPan', () => {
+ const FIT_W = 800;
+ const FIT_H = 600;
+ const CW = 800;
+ const CH = 600;
+ it('pins a not-yet-overflowing image centred (no pan possible)', () => {
+ const out = clampPan({ scale: 1, x: 120, y: -80 }, FIT_W, FIT_H, CW, CH);
+ expect(out.scale).toBe(1);
+ // Both axes recentre to zero; `=== 0` (not toBe) so a harmless signed zero from clamping a
+ // negative offset to a zero bound passes — translate(-0px) and translate(0px) are identical.
+ expect(out.x === 0).toBe(true);
+ expect(out.y === 0).toBe(true);
+ });
+ it('allows pan up to half the overflow once the image is larger than the container', () => {
+ // scale 2 → image 1600×1200, container 800×600 → overflow 800×600 → half = 400×300.
+ expect(clampPan({ scale: 2, x: 1000, y: 1000 }, FIT_W, FIT_H, CW, CH)).toEqual({ scale: 2, x: 400, y: 300 });
+ expect(clampPan({ scale: 2, x: -1000, y: -1000 }, FIT_W, FIT_H, CW, CH)).toEqual({ scale: 2, x: -400, y: -300 });
+ });
+ it('leaves an in-bounds pan untouched', () => {
+ expect(clampPan({ scale: 2, x: 50, y: -25 }, FIT_W, FIT_H, CW, CH)).toEqual({ scale: 2, x: 50, y: -25 });
+ });
+});
+
+describe('toggleScale', () => {
+ it('jumps from fit to 100% natural for an oversized image', () => {
+ expect(toggleScale(1, 4, maxScale(4))).toBe(4);
+ });
+ it('jumps back to fit from any zoomed-in state', () => {
+ expect(toggleScale(4, 4, maxScale(4))).toBe(1);
+ expect(toggleScale(2.5, 4, maxScale(4))).toBe(1);
+ });
+ it('nudges to 2× instead of a no-op when the image already fits at 1:1', () => {
+ expect(toggleScale(1, 1, maxScale(1))).toBe(2);
+ });
+});
+
+describe('clamp', () => {
+ it('bounds a value to [lo, hi]', () => {
+ expect(clamp(5, 0, 10)).toBe(5);
+ expect(clamp(-1, 0, 10)).toBe(0);
+ expect(clamp(11, 0, 10)).toBe(10);
+ });
+});
diff --git a/ui/src/lib/imageZoom.ts b/ui/src/lib/imageZoom.ts
new file mode 100644
index 000000000..c986d2a08
--- /dev/null
+++ b/ui/src/lib/imageZoom.ts
@@ -0,0 +1,82 @@
+// Pure transform math for the shared file-preview kernel's image zoom/pan (the DOM/React glue lives in
+// file-preview.tsx's ImageBody and feeds these functions the measured element sizes). Kept DOM-free so
+// it can be unit-tested in isolation — jsdom does no layout, so the interaction feel can only be
+// verified here, on the math.
+//
+// Model: an <img> is laid out at its "fit" size (object-contain within the container) and CENTERED at
+// rest, then `transform: translate(x, y) scale(s)` is applied about the element's own centre. So:
+// - `scale === 1` is the fit view (the baseline; we never zoom out past it);
+// - `x` / `y` are screen-space pan offsets of the image centre from the container centre;
+// - anchor coordinates passed to `zoomToPoint` are ALSO relative to the container centre.
+// This mirrors the chat lightbox (image-viewer.tsx): min scale at fit, cursor-anchored wheel zoom, and
+// pan bounded so the image can't be dragged off its own frame. It adds the two things the kernel needs
+// that the lightbox doesn't have — a fit⇄100% double-click and a percent-of-natural readout.
+
+export type ImageView = { scale: number; x: number; y: number };
+
+/** The rest view: fit, centred, unpanned. */
+export const FIT_VIEW: ImageView = { scale: 1, x: 0, y: 0 };
+
+/** Ceiling for a normal image: 5× the fit size (matches the chat lightbox's maxScale). */
+export const MAX_ZOOM_FACTOR = 5;
+
+export function clamp(value: number, lo: number, hi: number): number {
+ return value < lo ? lo : value > hi ? hi : value;
+}
+
+/**
+ * The scale at which the fit-laid-out image is shown at its natural pixel size (1 image px = 1 CSS px).
+ * `fit` never upscales, so this is always ≥ 1; a huge image has a large 1:1 scale, a small one has 1.
+ * Falls back to 1 when a size is unknown (e.g. an SVG with no intrinsic dimensions reports 0).
+ */
+export function oneToOneScale(naturalWidth: number, fitWidth: number): number {
+ return naturalWidth > 0 && fitWidth > 0 ? Math.max(1, naturalWidth / fitWidth) : 1;
+}
+
+/**
+ * Max scale for an image. At least 5× fit (the lightbox feel), but never below 1:1 — an image whose
+ * fit is already below its natural size (1:1 scale > 5) must still be zoomable all the way to 100%.
+ */
+export function maxScale(oneToOne: number): number {
+ return Math.max(MAX_ZOOM_FACTOR, oneToOne);
+}
+
+/** Percent of natural size shown at `scale` (fit-relative). 100 == 1:1 pixels; <100 == shrunk to fit. */
+export function zoomPercent(scale: number, oneToOne: number): number {
+ return Math.round((scale / oneToOne) * 100);
+}
+
+/**
+ * Zoom to `nextScaleRaw` (clamped to [1, max]) while keeping the point (ax, ay) — in container-centre
+ * coordinates — visually fixed. Pan is NOT bounded here; the caller applies clampPan with the measured
+ * element sizes afterward. Standard cursor-anchored formula: the anchor's image-local position is
+ * preserved across the scale change.
+ */
+export function zoomToPoint(view: ImageView, nextScaleRaw: number, ax: number, ay: number, max: number): ImageView {
+ const scale = clamp(nextScaleRaw, FIT_VIEW.scale, max);
+ const k = scale / view.scale;
+ return { scale, x: ax - k * (ax - view.x), y: ay - k * (ay - view.y) };
+}
+
+/**
+ * Bound the pan so the scaled image always covers the container when it's larger than it, and is
+ * pinned centred (offset 0) on any axis where it's smaller. `fitWidth`/`fitHeight` are the untransformed
+ * (scale-1) element sizes; the scaled size is those × `view.scale`.
+ */
+export function clampPan(view: ImageView, fitWidth: number, fitHeight: number, containerWidth: number, containerHeight: number): ImageView {
+ const overflowX = Math.max(0, (fitWidth * view.scale - containerWidth) / 2);
+ const overflowY = Math.max(0, (fitHeight * view.scale - containerHeight) / 2);
+ return { scale: view.scale, x: clamp(view.x, -overflowX, overflowX), y: clamp(view.y, -overflowY, overflowY) };
+}
+
+/**
+ * Target scale for a double-click / double-tap. From ~fit, jump to 100% natural; from any zoomed-in
+ * state, jump back to fit. When the image already fits at 1:1 (its natural size is ≤ the fit size, so
+ * 100% == fit), nudge to 2× instead so the gesture is never a no-op.
+ */
+export function toggleScale(scale: number, oneToOne: number, max: number): number {
+ const atFit = scale <= FIT_VIEW.scale + 0.01;
+ if (!atFit) return FIT_VIEW.scale;
+ const target = oneToOne > FIT_VIEW.scale + 0.01 ? oneToOne : Math.min(2, max);
+ return clamp(target, FIT_VIEW.scale, max);
+}