Skip to content

Build your personal knowledge base with Trilium Notes

client/image viewer: add a keyboard controller

Adorian Doran4db4b2f14e55
diff --git a/apps/client/src/widgets/react/ImageViewer.css b/apps/client/src/widgets/react/ImageViewer.css
index 5e5cfe866a..3ae53f7171 100644
--- a/apps/client/src/widgets/react/ImageViewer.css
+++ b/apps/client/src/widgets/react/ImageViewer.css
@@ -1,3 +1,10 @@
+/* Focusable wrapper that receives keyboard zoom/pan; fills the available space. */
+.image-viewer-root {
+ width: 100%;
+ height: 100%;
+ outline: none;
+}
+
/* Make the library's viewport fill the available space so the image fits and pans within it. */
.image-viewer-viewport.react-transform-wrapper {
width: 100%;
diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsx
index 128be79aef..843ad3fa7e 100644
--- a/apps/client/src/widgets/react/ImageViewer.tsx
+++ b/apps/client/src/widgets/react/ImageViewer.tsx
@@ -1,9 +1,11 @@
import "./ImageViewer.css";
import { Ref } from "preact";
-import { useRef, useState } from "preact/hooks";
+import { useCallback, useRef, useState } from "preact/hooks";
import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
+import { useImageViewerKeyboard } from "./image_viewer_keyboard";
+
interface ImageViewerProps {
src: string;
imgClassName?: string;
@@ -39,6 +41,17 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
const [ panning, setPanning ] = useState(false);
const [ largeZoom, setLargeZoom ] = useState(false);
const imgRef = useRef<HTMLImageElement>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const zoomRef = useRef<ReactZoomPanPinchRef>(null);
+
+ // Keep our own ref to drive keyboard control, while still forwarding to the caller's apiRef.
+ const setZoomRef = useCallback((instance: ReactZoomPanPinchRef | null) => {
+ zoomRef.current = instance;
+ if (typeof apiRef === "function") apiRef(instance);
+ else if (apiRef) (apiRef as { current: ReactZoomPanPinchRef | null }).current = instance;
+ }, [ apiRef ]);
+
+ useImageViewerKeyboard(zoomRef, rootRef);
const wrapperClass = [
"image-viewer-viewport",
@@ -48,26 +61,28 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
].filter(Boolean).join(" ");
return (
- <TransformWrapper
- ref={apiRef}
- minScale={minScale}
- maxScale={maxScale}
- centerOnInit
- centerZoomedOut
- wheel={{ step: 0.0085 }}
- autoAlignment={{ disabled: true }}
- doubleClick={{ mode: "reset" }}
- onTransform={(_ref, { scale }) => {
- const { pannable: nextPannable, largeZoom: nextLargeZoom } = evaluateImageZoom(scale, imgRef.current);
- if (nextPannable !== pannable) setPannable(nextPannable);
- if (nextLargeZoom !== largeZoom) setLargeZoom(nextLargeZoom);
- }}
- onPanningStart={() => setPanning(true)}
- onPanningStop={() => setPanning(false)}
- >
- <TransformComponent wrapperClass={wrapperClass} contentClass="image-viewer-content">
- <img ref={imgRef} className={imgClassName} src={src} alt={alt} />
- </TransformComponent>
- </TransformWrapper>
+ <div ref={rootRef} tabIndex={0} className="image-viewer-root">
+ <TransformWrapper
+ ref={setZoomRef}
+ minScale={minScale}
+ maxScale={maxScale}
+ centerOnInit
+ centerZoomedOut
+ wheel={{ step: 0.0085 }}
+ autoAlignment={{ disabled: true }}
+ doubleClick={{ mode: "reset" }}
+ onTransform={(_ref, { scale }) => {
+ const { pannable: nextPannable, largeZoom: nextLargeZoom } = evaluateImageZoom(scale, imgRef.current);
+ if (nextPannable !== pannable) setPannable(nextPannable);
+ if (nextLargeZoom !== largeZoom) setLargeZoom(nextLargeZoom);
+ }}
+ onPanningStart={() => setPanning(true)}
+ onPanningStop={() => setPanning(false)}
+ >
+ <TransformComponent wrapperClass={wrapperClass} contentClass="image-viewer-content">
+ <img ref={imgRef} className={imgClassName} src={src} alt={alt} />
+ </TransformComponent>
+ </TransformWrapper>
+ </div>
);
}
diff --git a/apps/client/src/widgets/react/image_viewer_keyboard.spec.ts b/apps/client/src/widgets/react/image_viewer_keyboard.spec.ts
new file mode 100644
index 0000000000..65c56864b2
--- /dev/null
+++ b/apps/client/src/widgets/react/image_viewer_keyboard.spec.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import { clampPan, codeToControl, getPanDelta } from "./image_viewer_keyboard";
+
+describe("codeToControl", () => {
+ it("maps zoom/reset keys (Equal/Minus/Slash, numpad, Q/E) regardless of modifiers", () => {
+ expect(codeToControl("Equal")).toBe("zoomIn");
+ expect(codeToControl("NumpadAdd")).toBe("zoomIn");
+ expect(codeToControl("KeyE")).toBe("zoomIn");
+ expect(codeToControl("Minus")).toBe("zoomOut");
+ expect(codeToControl("NumpadSubtract")).toBe("zoomOut");
+ expect(codeToControl("KeyQ")).toBe("zoomOut");
+ expect(codeToControl("Slash")).toBe("reset");
+ expect(codeToControl("NumpadDivide")).toBe("reset");
+ });
+
+ it("maps arrows and WASD to pan controls", () => {
+ expect(codeToControl("ArrowUp")).toBe("panUp");
+ expect(codeToControl("KeyW")).toBe("panUp");
+ expect(codeToControl("ArrowDown")).toBe("panDown");
+ expect(codeToControl("KeyS")).toBe("panDown");
+ expect(codeToControl("ArrowLeft")).toBe("panLeft");
+ expect(codeToControl("KeyA")).toBe("panLeft");
+ expect(codeToControl("ArrowRight")).toBe("panRight");
+ expect(codeToControl("KeyD")).toBe("panRight");
+ });
+
+ it("ignores unrelated keys", () => {
+ expect(codeToControl("KeyZ")).toBeNull();
+ expect(codeToControl("Space")).toBeNull();
+ });
+});
+
+describe("getPanDelta", () => {
+ it("translates the content opposite the viewed direction", () => {
+ expect(getPanDelta([ "panRight" ], false, 1).dx).toBeLessThan(0);
+ expect(getPanDelta([ "panLeft" ], false, 1).dx).toBeGreaterThan(0);
+ expect(getPanDelta([ "panUp" ], false, 1).dy).toBeGreaterThan(0);
+ expect(getPanDelta([ "panDown" ], false, 1).dy).toBeLessThan(0);
+ });
+
+ it("cancels opposing keys and scales by elapsed time", () => {
+ expect(getPanDelta([ "panLeft", "panRight" ], false, 1)).toEqual({ dx: 0, dy: 0 });
+ const slow = getPanDelta([ "panRight" ], false, 0.5).dx;
+ const fast = getPanDelta([ "panRight" ], false, 1).dx;
+ expect(fast).toBe(slow * 2);
+ });
+
+ it("speeds up while Shift is held", () => {
+ const normal = Math.abs(getPanDelta([ "panRight" ], false, 1).dx);
+ const fast = Math.abs(getPanDelta([ "panRight" ], true, 1).dx);
+ expect(fast).toBeGreaterThan(normal);
+ });
+});
+
+describe("clampPan", () => {
+ const bounds = { minPositionX: -100, maxPositionX: 0, minPositionY: -50, maxPositionY: 0 };
+
+ it("leaves an in-bounds position unchanged", () => {
+ expect(clampPan(-40, -20, bounds)).toEqual({ x: -40, y: -20 });
+ });
+
+ it("clamps a position past either edge", () => {
+ expect(clampPan(20, 20, bounds)).toEqual({ x: 0, y: 0 });
+ expect(clampPan(-200, -200, bounds)).toEqual({ x: -100, y: -50 });
+ });
+});
diff --git a/apps/client/src/widgets/react/image_viewer_keyboard.ts b/apps/client/src/widgets/react/image_viewer_keyboard.ts
new file mode 100644
index 0000000000..aa473cbf90
--- /dev/null
+++ b/apps/client/src/widgets/react/image_viewer_keyboard.ts
@@ -0,0 +1,167 @@
+import { useEffect } from "preact/hooks";
+import type { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
+
+export type ImageViewerControl =
+ | "zoomIn" | "zoomOut" | "reset"
+ | "panUp" | "panDown" | "panLeft" | "panRight";
+
+/** Continuous keyboard zoom rate, as a per-second exponent fed to the library's zoomIn/zoomOut. */
+const ZOOM_RATE = 2.5;
+/** Continuous keyboard pan speed, in CSS pixels per second. */
+const PAN_SPEED = 1200;
+/** Pan speed multiplier while Shift is held. */
+const PAN_FAST_FACTOR = 2.5;
+
+/**
+ * Maps a physical key (`KeyboardEvent.code`) to a viewer control, independent of modifiers — so the
+ * zoom/reset keys work with or without Ctrl/Cmd. Using `code` keeps it keyboard-layout independent.
+ */
+export function codeToControl(code: string): ImageViewerControl | null {
+ switch (code) {
+ case "Equal": case "NumpadAdd": case "KeyE": return "zoomIn";
+ case "Minus": case "NumpadSubtract": case "KeyQ": return "zoomOut";
+ case "Slash": case "NumpadDivide": return "reset";
+ case "ArrowUp": case "KeyW": return "panUp";
+ case "ArrowDown": case "KeyS": return "panDown";
+ case "ArrowLeft": case "KeyA": return "panLeft";
+ case "ArrowRight": case "KeyD": return "panRight";
+ default: return null;
+ }
+}
+
+/**
+ * Pan delta (in content-translation pixels) for the held direction controls. An arrow/WASD key
+ * moves the *view* that way (Right reveals the right side), so the content translates the opposite
+ * way. Scaled by elapsed time, so the speed is frame-rate independent; Shift speeds it up.
+ */
+export function getPanDelta(controls: Iterable<ImageViewerControl>, shiftKey: boolean, dtSeconds: number): { dx: number; dy: number } {
+ const held = controls instanceof Set ? controls : new Set(controls);
+ const speed = PAN_SPEED * (shiftKey ? PAN_FAST_FACTOR : 1) * dtSeconds;
+ let dx = 0;
+ let dy = 0;
+ if (held.has("panLeft")) dx += speed;
+ if (held.has("panRight")) dx -= speed;
+ if (held.has("panUp")) dy += speed;
+ if (held.has("panDown")) dy -= speed;
+ return { dx, dy };
+}
+
+interface PanBounds { minPositionX: number; maxPositionX: number; minPositionY: number; maxPositionY: number; }
+
+/** Clamps a candidate content position to the library's computed pan bounds. */
+export function clampPan(x: number, y: number, bounds: PanBounds): { x: number; y: number } {
+ return {
+ x: Math.min(Math.max(x, bounds.minPositionX), bounds.maxPositionX),
+ y: Math.min(Math.max(y, bounds.minPositionY), bounds.maxPositionY)
+ };
+}
+
+/**
+ * Wires keyboard zoom (`+`/`-`/`/`, with or without Ctrl/Cmd) and pan (arrows / WASD, Shift to speed
+ * up) onto the focusable `elementRef`, driving the react-zoom-pan-pinch instance in `apiRef`. While
+ * keys are held it runs a requestAnimationFrame loop that reuses the library's own
+ * `zoomIn`/`zoomOut`/`setTransform`, so the motion is smooth and stays within the library's bounds.
+ * Only active while the element is focused.
+ */
+export function useImageViewerKeyboard(
+ apiRef: { current: ReactZoomPanPinchRef | null },
+ elementRef: { current: HTMLElement | null }
+) {
+ useEffect(() => {
+ const element = elementRef.current;
+ if (!element) return;
+
+ const heldCodes = new Set<string>();
+ let shift = false;
+ let rafId = 0;
+ let lastTime = 0;
+
+ const stop = () => {
+ if (rafId) cancelAnimationFrame(rafId);
+ rafId = 0;
+ lastTime = 0;
+ };
+
+ const activeControls = () => {
+ const controls: ImageViewerControl[] = [];
+ for (const code of heldCodes) {
+ const control = codeToControl(code);
+ if (control && control !== "reset") controls.push(control);
+ }
+ return controls;
+ };
+
+ const tick = (time: number) => {
+ const dt = lastTime ? Math.min((time - lastTime) / 1000, 0.05) : 0;
+ lastTime = time;
+
+ const api = apiRef.current;
+ const controls = activeControls();
+ if (api && dt > 0 && controls.length) {
+ if (controls.includes("zoomIn")) api.zoomIn(ZOOM_RATE * dt, 0);
+ if (controls.includes("zoomOut")) api.zoomOut(ZOOM_RATE * dt, 0);
+
+ const { dx, dy } = getPanDelta(controls, shift, dt);
+ if (dx || dy) {
+ const { scale, positionX, positionY } = api.instance.state;
+ const bounds = api.instance.bounds;
+ if (bounds) {
+ const next = clampPan(positionX + dx, positionY + dy, bounds);
+ api.setTransform(next.x, next.y, scale, 0);
+ }
+ }
+ }
+
+ if (controls.length) rafId = requestAnimationFrame(tick);
+ else stop();
+ };
+
+ const start = () => {
+ if (!rafId) rafId = requestAnimationFrame(tick);
+ };
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ shift = e.shiftKey;
+ const control = codeToControl(e.code);
+ if (!control) return;
+ // Claim the key so the browser (Ctrl +/-) and Trilium's global shortcuts
+ // (arrow tree navigation, app zoom, quick search) don't also act on it.
+ e.preventDefault();
+ e.stopPropagation();
+ if (control === "reset") {
+ apiRef.current?.resetTransform();
+ return;
+ }
+ heldCodes.add(e.code);
+ start();
+ };
+
+ const onKeyUp = (e: KeyboardEvent) => {
+ shift = e.shiftKey;
+ heldCodes.delete(e.code);
+ };
+
+ const onBlur = () => {
+ heldCodes.clear();
+ stop();
+ };
+
+ // Focus on pointer release (capture phase). The library calls preventDefault on mousedown
+ // for panning, which both stops propagation and reverts a focus set during the press — so we
+ // focus on the capture-phase pointerup, once the press has been fully handled.
+ const onPointerUp = () => element.focus();
+
+ element.addEventListener("keydown", onKeyDown);
+ element.addEventListener("keyup", onKeyUp);
+ element.addEventListener("blur", onBlur);
+ element.addEventListener("pointerup", onPointerUp, true);
+
+ return () => {
+ element.removeEventListener("keydown", onKeyDown);
+ element.removeEventListener("keyup", onKeyUp);
+ element.removeEventListener("blur", onBlur);
+ element.removeEventListener("pointerup", onPointerUp, true);
+ stop();
+ };
+ }, [ apiRef, elementRef ]);
+}