Skip to content

Build your personal knowledge base with Trilium Notes

client/image viewer: add zoom buttons

Adorian Doran0f3d5d40bc57
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 5ed4dd09ca..12f356b664 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -515,9 +515,6 @@ type EventMappings = {
relationMapResetPanZoom: { ntxId: string | null | undefined };
relationMapResetZoomIn: { ntxId: string | null | undefined };
relationMapResetZoomOut: { ntxId: string | null | undefined };
- imageZoomIn: { ntxId: string | null | undefined };
- imageZoomOut: { ntxId: string | null | undefined };
- imageZoomReset: { ntxId: string | null | undefined };
activeNoteChanged: {ntxId: string | null | undefined};
showAddLinkDialog: AddLinkOpts;
showIncludeDialog: IncludeNoteOpts;
diff --git a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx b/apps/client/src/widgets/FloatingButtonsDefinitions.tsx
index b0c7db596f..c21de3c166 100644
--- a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx
+++ b/apps/client/src/widgets/FloatingButtonsDefinitions.tsx
@@ -59,7 +59,6 @@ export const DESKTOP_FLOATING_BUTTONS: FloatingButtonsList = [
OpenElectronApiDocsButton,
SaveToNoteButton,
RelationMapButtons,
- ImageZoomButtons,
CopyImageReferenceButton,
ExportImageButtons,
ExportSpreadsheetButton,
@@ -281,33 +280,6 @@ function RelationMapButtons({ note, isDefaultViewMode, triggerEvent }: FloatingB
);
}
-function ImageZoomButtons({ note, isDefaultViewMode, triggerEvent }: FloatingButtonContext) {
- const isEnabled = note.type === "image" && note.isContentAvailable() && isDefaultViewMode;
- return isEnabled && (
- <>
- <FloatingButton
- icon="bx bx-crop"
- text={t("image_buttons.reset_zoom")}
- onClick={() => triggerEvent("imageZoomReset")}
- />
-
- <div className="btn-group">
- <FloatingButton
- icon="bx bx-zoom-in"
- text={t("image_buttons.zoom_in")}
- onClick={() => triggerEvent("imageZoomIn")}
- />
-
- <FloatingButton
- icon="bx bx-zoom-out"
- text={t("image_buttons.zoom_out")}
- onClick={() => triggerEvent("imageZoomOut")}
- />
- </div>
- </>
- );
-}
-
function CopyImageReferenceButton({ note, isDefaultViewMode }: FloatingButtonContext) {
const hiddenImageCopyRef = useRef<HTMLDivElement>(null);
const isEnabled = (
diff --git a/apps/client/src/widgets/react/ImageViewer.css b/apps/client/src/widgets/react/ImageViewer.css
index 9705973400..c8e10450dd 100644
--- a/apps/client/src/widgets/react/ImageViewer.css
+++ b/apps/client/src/widgets/react/ImageViewer.css
@@ -1,10 +1,22 @@
/* Focusable wrapper that receives keyboard zoom/pan; fills the available space. */
.image-viewer-root {
+ position: relative;
width: 100%;
height: 100%;
outline: none;
}
+/* Zoom controls pinned to the bottom-right corner of the viewport. */
+.image-viewer-controls {
+ position: absolute;
+ inset-inline-end: 10px;
+ bottom: 10px;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
/* 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.spec.tsx b/apps/client/src/widgets/react/ImageViewer.spec.tsx
index 8fe8f6ad69..7aac45231d 100644
--- a/apps/client/src/widgets/react/ImageViewer.spec.tsx
+++ b/apps/client/src/widgets/react/ImageViewer.spec.tsx
@@ -12,6 +12,9 @@ vi.mock("react-zoom-pan-pinch", () => ({
TransformComponent: (props: { children?: ComponentChildren }) => props.children
}));
+// Avoid pulling the real hooks module (bootstrap tooltips + app context) into the test.
+vi.mock("./hooks", () => ({ useStaticTooltip: () => {} }));
+
import ImageViewer, { evaluateImageZoom } from "./ImageViewer";
function renderViewer(props: Parameters<typeof ImageViewer>[0]) {
@@ -78,4 +81,10 @@ describe("evaluateImageZoom", () => {
expect(evaluateImageZoom(50, null).largeZoom).toBe(false);
expect(evaluateImageZoom(50, img(0, 800)).largeZoom).toBe(false);
});
+
+ it("reports on-screen size relative to native resolution", () => {
+ expect(evaluateImageZoom(1, img(800, 800)).nativeScale).toBe(1);
+ expect(evaluateImageZoom(5, img(4000, 800)).nativeScale).toBe(1); // 0.2x fit, 1x native at scale 5
+ expect(evaluateImageZoom(50, null).nativeScale).toBe(0);
+ });
});
diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsx
index 843ad3fa7e..babec02ff0 100644
--- a/apps/client/src/widgets/react/ImageViewer.tsx
+++ b/apps/client/src/widgets/react/ImageViewer.tsx
@@ -4,6 +4,9 @@ import { Ref } from "preact";
import { useCallback, useRef, useState } from "preact/hooks";
import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
+import { t } from "../../services/i18n";
+import { isMobile } from "../../services/utils";
+import { useStaticTooltip } from "./hooks";
import { useImageViewerKeyboard } from "./image_viewer_keyboard";
interface ImageViewerProps {
@@ -19,30 +22,35 @@ interface ImageViewerProps {
/** Beyond this multiple of the image's native resolution, switch to crisp (non-smoothed) rendering. */
const CRISP_NATIVE_SCALE = 4;
+/** Scale step applied per zoom-in/out button click (react-zoom-pan-pinch's zoomIn/zoomOut step). */
+const BUTTON_ZOOM_STEP = 0.5;
/**
- * Derives the zoom-driven flags: whether the image is pannable (zoomed past the fitted size) and
- * whether it's enlarged beyond {@link CRISP_NATIVE_SCALE}× its native resolution. `clientWidth` is
- * the un-transformed fitted width, so `clientWidth * scale / naturalWidth` is the on-screen size in
- * multiples of the image's real pixels.
+ * Derives the zoom-driven values: whether the image is pannable (zoomed past the fitted size),
+ * whether it's enlarged beyond {@link CRISP_NATIVE_SCALE}× its native resolution, and `nativeScale` —
+ * the on-screen size as a multiple of the image's real pixels (`clientWidth * scale / naturalWidth`,
+ * where `clientWidth` is the un-transformed fitted width).
*/
export function evaluateImageZoom(scale: number, img: { naturalWidth: number; clientWidth: number } | null) {
- const pannable = scale > 1;
const nativeScale = img && img.naturalWidth > 0 ? (img.clientWidth * scale) / img.naturalWidth : 0;
- return { pannable, largeZoom: nativeScale > CRISP_NATIVE_SCALE };
+ return { pannable: scale > 1, largeZoom: nativeScale > CRISP_NATIVE_SCALE, nativeScale };
}
/**
* Interactive image viewer: the image is fit to the viewport on load, then the user can zoom
- * (wheel/pinch/buttons) and pan (drag). Double-clicking resets back to the fitted view.
+ * (wheel/pinch/buttons/keyboard) and pan (drag/keyboard). Double-clicking resets to the fitted view.
*/
export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.5, maxScale = 50, apiRef }: ImageViewerProps) {
const [ pannable, setPannable ] = useState(false);
const [ panning, setPanning ] = useState(false);
const [ largeZoom, setLargeZoom ] = useState(false);
+ const [ zoomPercent, setZoomPercent ] = useState(0);
const imgRef = useRef<HTMLImageElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const zoomRef = useRef<ReactZoomPanPinchRef>(null);
+ const zoomOutRef = useRef<HTMLButtonElement>(null);
+ const zoomLevelRef = useRef<HTMLButtonElement>(null);
+ const zoomInRef = useRef<HTMLButtonElement>(null);
// Keep our own ref to drive keyboard control, while still forwarding to the caller's apiRef.
const setZoomRef = useCallback((instance: ReactZoomPanPinchRef | null) => {
@@ -52,6 +60,18 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
}, [ apiRef ]);
useImageViewerKeyboard(zoomRef, rootRef);
+ useStaticTooltip(zoomOutRef, { title: t("image_buttons.zoom_out"), placement: "top" });
+ useStaticTooltip(zoomLevelRef, { title: t("image_buttons.reset_zoom"), placement: "top" });
+ useStaticTooltip(zoomInRef, { title: t("image_buttons.zoom_in"), placement: "top" });
+
+ // Recompute the cursor/rendering flags and the displayed (native-relative) zoom percentage.
+ const updateZoomState = (scale: number) => {
+ const { pannable: nextPannable, largeZoom: nextLargeZoom, nativeScale } = evaluateImageZoom(scale, imgRef.current);
+ if (nextPannable !== pannable) setPannable(nextPannable);
+ if (nextLargeZoom !== largeZoom) setLargeZoom(nextLargeZoom);
+ const percent = Math.round(nativeScale * 100);
+ if (percent !== zoomPercent) setZoomPercent(percent);
+ };
const wrapperClass = [
"image-viewer-viewport",
@@ -71,18 +91,42 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
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);
- }}
+ onTransform={(_ref, { scale }) => updateZoomState(scale)}
onPanningStart={() => setPanning(true)}
onPanningStop={() => setPanning(false)}
>
<TransformComponent wrapperClass={wrapperClass} contentClass="image-viewer-content">
- <img ref={imgRef} className={imgClassName} src={src} alt={alt} />
+ <img
+ ref={imgRef}
+ className={imgClassName}
+ src={src}
+ alt={alt}
+ onLoad={() => updateZoomState(zoomRef.current?.instance.state.scale ?? 1)}
+ />
</TransformComponent>
</TransformWrapper>
+
+ {!isMobile() && (
+ <div className="image-viewer-controls">
+ <button
+ ref={zoomOutRef}
+ className="icon-action bx bx-zoom-out"
+ onClick={() => zoomRef.current?.zoomOut(BUTTON_ZOOM_STEP)}
+ />
+ <button
+ ref={zoomLevelRef}
+ className="image-viewer-zoom-level"
+ onClick={() => zoomRef.current?.resetTransform()}
+ >
+ {zoomPercent}%
+ </button>
+ <button
+ ref={zoomInRef}
+ className="icon-action bx bx-zoom-in"
+ onClick={() => zoomRef.current?.zoomIn(BUTTON_ZOOM_STEP)}
+ />
+ </div>
+ )}
</div>
);
}
diff --git a/apps/client/src/widgets/type_widgets/Image.tsx b/apps/client/src/widgets/type_widgets/Image.tsx
index a4b1b1e627..8ab762d400 100644
--- a/apps/client/src/widgets/type_widgets/Image.tsx
+++ b/apps/client/src/widgets/type_widgets/Image.tsx
@@ -1,20 +1,17 @@
import "./Image.css";
import { useEffect, useRef, useState } from "preact/hooks";
-import type { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
import image_context_menu from "../../menus/image_context_menu";
import { copyImageReferenceToClipboard } from "../../services/image";
import { createImageSrcUrl } from "../../services/utils";
-import { useTriliumEvent, useTriliumEvents } from "../react/hooks";
+import { useTriliumEvent } from "../react/hooks";
import ImageViewer from "../react/ImageViewer";
import { refToJQuerySelector } from "../react/react_utils";
-import { applyImageZoom } from "./image_zoom";
import { TypeWidgetProps } from "./type_widget";
export default function Image({ note, ntxId }: TypeWidgetProps) {
const containerRef = useRef<HTMLDivElement>(null);
- const zoomRef = useRef<ReactZoomPanPinchRef>(null);
const [ refreshCounter, setRefreshCounter ] = useState(0);
useEffect(() => image_context_menu.setupContextMenu(refToJQuerySelector(containerRef)), []);
@@ -27,10 +24,6 @@ export default function Image({ note, ntxId }: TypeWidgetProps) {
if ($img.length) copyImageReferenceToClipboard($img.parent());
});
- useTriliumEvents([ "imageZoomIn", "imageZoomOut", "imageZoomReset" ], ({ ntxId: eventNtxId }, eventName) =>
- applyImageZoom(zoomRef.current, eventName, eventNtxId, ntxId)
- );
-
// A new revision swaps the image content; remount so it re-fits to the viewport.
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (loadResults.isNoteReloaded(note.noteId)) {
@@ -42,7 +35,6 @@ export default function Image({ note, ntxId }: TypeWidgetProps) {
<div ref={containerRef} className="note-detail-image-wrapper">
<ImageViewer
key={`${note.noteId}-${refreshCounter}`}
- apiRef={zoomRef}
imgClassName="note-detail-image-view"
src={createImageSrcUrl(note)}
alt={note.title}
diff --git a/apps/client/src/widgets/type_widgets/image_zoom.spec.ts b/apps/client/src/widgets/type_widgets/image_zoom.spec.ts
deleted file mode 100644
index 777c3d2256..0000000000
--- a/apps/client/src/widgets/type_widgets/image_zoom.spec.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
-import { describe, expect, it, vi } from "vitest";
-
-import { applyImageZoom } from "./image_zoom";
-
-function stubZoom() {
- return { zoomIn: vi.fn(), zoomOut: vi.fn(), resetTransform: vi.fn() };
-}
-
-const asRef = (zoom: ReturnType<typeof stubZoom>) => zoom as unknown as ReactZoomPanPinchRef;
-
-describe("applyImageZoom", () => {
- it("routes each event to its matching zoom action", () => {
- const zoomIn = stubZoom();
- applyImageZoom(asRef(zoomIn), "imageZoomIn", "ntx", "ntx");
- expect(zoomIn.zoomIn).toHaveBeenCalledOnce();
- expect(zoomIn.zoomOut).not.toHaveBeenCalled();
- expect(zoomIn.resetTransform).not.toHaveBeenCalled();
-
- const zoomOut = stubZoom();
- applyImageZoom(asRef(zoomOut), "imageZoomOut", "ntx", "ntx");
- expect(zoomOut.zoomOut).toHaveBeenCalledOnce();
- expect(zoomOut.zoomIn).not.toHaveBeenCalled();
- expect(zoomOut.resetTransform).not.toHaveBeenCalled();
-
- const reset = stubZoom();
- applyImageZoom(asRef(reset), "imageZoomReset", "ntx", "ntx");
- expect(reset.resetTransform).toHaveBeenCalledOnce();
- expect(reset.zoomIn).not.toHaveBeenCalled();
- expect(reset.zoomOut).not.toHaveBeenCalled();
- });
-
- it("zooms in and out by the same configured step", () => {
- const zoom = stubZoom();
- applyImageZoom(asRef(zoom), "imageZoomIn", "ntx", "ntx");
- applyImageZoom(asRef(zoom), "imageZoomOut", "ntx", "ntx");
- const inStep = zoom.zoomIn.mock.calls[0][0];
- const outStep = zoom.zoomOut.mock.calls[0][0];
- expect(inStep).toBeTypeOf("number");
- expect(inStep).toBe(outStep);
- });
-
- it("ignores events from a different note context", () => {
- const zoom = stubZoom();
- applyImageZoom(asRef(zoom), "imageZoomIn", "ntx-a", "ntx-b");
- expect(zoom.zoomIn).not.toHaveBeenCalled();
- });
-
- it("is a no-op when the zoom instance is not ready", () => {
- expect(() => applyImageZoom(null, "imageZoomReset", "ntx", "ntx")).not.toThrow();
- });
-});
diff --git a/apps/client/src/widgets/type_widgets/image_zoom.ts b/apps/client/src/widgets/type_widgets/image_zoom.ts
deleted file mode 100644
index c8621cc902..0000000000
--- a/apps/client/src/widgets/type_widgets/image_zoom.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
-
-/** Scale factor applied per zoom-in/out button click (react-zoom-pan-pinch's zoomIn/zoomOut step). */
-export const IMAGE_ZOOM_STEP = 0.5;
-
-export type ImageZoomEvent = "imageZoomIn" | "imageZoomOut" | "imageZoomReset";
-
-/** Routes an image-zoom event to the matching zoom action, scoped to the originating note context. */
-export function applyImageZoom(
- zoom: ReactZoomPanPinchRef | null,
- eventName: ImageZoomEvent,
- eventNtxId: string | null | undefined,
- ntxId: string | null | undefined
-) {
- if (!zoom || eventNtxId !== ntxId) return;
-
- if (eventName === "imageZoomIn") zoom.zoomIn(IMAGE_ZOOM_STEP);
- else if (eventName === "imageZoomOut") zoom.zoomOut(IMAGE_ZOOM_STEP);
- else zoom.resetTransform();
-}