Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/image viewer: replace the old vanilla-js-wheel-zoom-based image viewer with a new react-zoom-pan-pinch-based implementation
Adorian Doranaa085af1b922
diff --git a/apps/client/package.json b/apps/client/package.jsonindex b246f333a7..8c88d59476 100644--- a/apps/client/package.json+++ b/apps/client/package.json@@ -70,11 +70,11 @@"preact": "10.29.2","react-i18next": "17.0.8","react-window": "2.2.7",+ "react-zoom-pan-pinch": "4.0.3","reveal.js": "6.0.1","rrule": "2.8.1","svg-pan-zoom": "3.6.2",- "tabulator-tables": "6.4.0",- "vanilla-js-wheel-zoom": "9.0.4"+ "tabulator-tables": "6.4.0"},"devDependencies": {"@ckeditor/ckeditor5-inspector": "5.0.1",diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex beeb68da83..d0f78a99cd 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -513,6 +513,9 @@ 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/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 468795ff12..da548a2428 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -29,9 +29,6 @@ vi.mock("./syntax_highlight.js", () => ({const setupContextMenu = vi.fn((..._args: any[]) => {});vi.mock("../menus/image_context_menu.js", () => ({ default: { setupContextMenu: (...a: any[]) => setupContextMenu(...a) } }));-const wheelZoomCreate = vi.fn((..._args: any[]) => {});-vi.mock("vanilla-js-wheel-zoom", () => ({ default: { create: (...a: any[]) => wheelZoomCreate(...a) } }));-const enterProtectedSession = vi.fn((..._args: any[]) => {});vi.mock("./protected_session.js", () => ({ default: { enterProtectedSession: (...a: any[]) => enterProtectedSession(...a) } }));@@ -209,7 +206,6 @@ describe("getRenderedContent image rendering", () => {expect($img.attr("src")).toContain(`api/images/${note.noteId}/`);expect($img.attr("id")).toMatch(/^attachment-image-\d+$/);expect(setupContextMenu).toHaveBeenCalledOnce();- expect(wheelZoomCreate).not.toHaveBeenCalled();});it("renders an FAttachment image with an api/attachments url", async () => {@@ -219,28 +215,6 @@ describe("getRenderedContent image rendering", () => {expect($renderedContent.find("img").attr("src")).toContain(`api/attachments/${att.attachmentId}/image/`);});- it("initializes wheel zoom when imageHasZoom is set and the element is present", async () => {- const note = buildNote({ title: "Zoom", type: "canvas" });- const { $renderedContent } = await getRenderedContent(note, { imageHasZoom: true });- // the img must be attached to the live DOM so document.querySelector finds it- document.body.append($renderedContent[0]);- await new Promise((r) => requestAnimationFrame(() => r(null)));- await new Promise((r) => setTimeout(r, 0));- expect(wheelZoomCreate).toHaveBeenCalled();- $renderedContent.remove();- });-- it("retries via requestAnimationFrame while the element is missing", async () => {- const rafSpy = vi.spyOn(window, "requestAnimationFrame");- const note = buildNote({ title: "ZoomMiss", type: "mindMap" });- // Do NOT attach to the DOM, so querySelector returns null and it reschedules.- await getRenderedContent(note, { imageHasZoom: true });- await new Promise((r) => setTimeout(r, 0));- expect(rafSpy).toHaveBeenCalled();- expect(wheelZoomCreate).not.toHaveBeenCalled();- rafSpy.mockRestore();- });-it("appends OCR text for FNote images when showTextRepresentation and OCR succeeds", async () => {const note = buildNote({ title: "OcrPic", type: "spreadsheet" });server.get = vi.fn(async () => ({ success: true, hasOcr: true, text: "hello-ocr" })) as typeof server.get;diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 5a1bb8bbbc..590a9cca01 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -3,7 +3,6 @@ import "./content_renderer.css";import { normalizeMimeTypeForCKEditor, renderToHtml, type TextRepresentationResponse } from "@triliumnext/commons";import DOMPurify from "dompurify";import { h, render } from "preact";-import WheelZoom from 'vanilla-js-wheel-zoom';import FAttachment from "../entities/fattachment.js";import FNote from "../entities/fnote.js";@@ -25,7 +24,6 @@ let idCounter = 1;export interface RenderOptions {tooltip?: boolean;trim?: boolean;- imageHasZoom?: boolean;/** If enabled, it will prevent the default behavior in which an empty note would display a list of children. */noChildrenList?: boolean;/** If enabled, it will prevent rendering of included notes. */@@ -191,22 +189,6 @@ async function renderImage(entity: FNote | FAttachment, $renderedContent: JQuery$renderedContent.append($img);- if (options.imageHasZoom) {- const initZoom = async () => {- const element = document.querySelector(`#${$img.attr("id")}`);- if (element) {- WheelZoom.create(`#${$img.attr("id")}`, {- maxScale: 50,- speed: 1.3,- zoomOnClick: false- });- } else {- requestAnimationFrame(initZoom);- }- };- initZoom();- }-imageContextMenuService.setupContextMenu($img);if (entity instanceof FNote && options.showTextRepresentation) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a9b4a99214..128ba571ba 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -861,6 +861,11 @@"zoom_in_title": "Zoom In","zoom_out_title": "Zoom Out"},+ "image_buttons": {+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "reset_zoom": "Reset zoom"+ },"zpetne_odkazy": {"backlink_one": "{{count}} Backlink","backlink_other": "{{count}} Backlinks",diff --git a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx b/apps/client/src/widgets/FloatingButtonsDefinitions.tsxindex 0b11699a98..dd9f1ee645 100644--- a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx+++ b/apps/client/src/widgets/FloatingButtonsDefinitions.tsx@@ -59,6 +59,7 @@ export const DESKTOP_FLOATING_BUTTONS: FloatingButtonsList = [OpenElectronApiDocsButton,SaveToNoteButton,RelationMapButtons,+ ImageZoomButtons,CopyImageReferenceButton,ExportImageButtons,InAppHelpButton,@@ -279,6 +280,33 @@ 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.cssnew file mode 100644index 0000000000..4b2dece372--- /dev/null+++ b/apps/client/src/widgets/react/ImageViewer.css@@ -0,0 +1,17 @@+/* 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%;+ height: 100%;+}++.image-viewer-content.react-transform-component {+ width: 100%;+ height: 100%;+ align-items: center;+ justify-content: center;+}++.image-viewer-content img {+ max-width: 100%;+ max-height: 100%;+}diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsxnew file mode 100644index 0000000000..c3e599cd04--- /dev/null+++ b/apps/client/src/widgets/react/ImageViewer.tsx@@ -0,0 +1,32 @@+import "./ImageViewer.css";++import { Ref } from "preact";+import { type ReactZoomPanPinchRef,TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";++interface ImageViewerProps {+ src: string;+ imgClassName?: string;+ alt?: string;+ maxScale?: number;+ /** Exposes the zoom/pan instance so the parent can drive zoom in/out/reset. */+ apiRef?: Ref<ReactZoomPanPinchRef>;+}++/**+ * 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.+ */+export default function ImageViewer({ src, imgClassName, alt = "", maxScale = 50, apiRef }: ImageViewerProps) {+ return (+ <TransformWrapper+ ref={apiRef}+ maxScale={maxScale}+ centerOnInit+ doubleClick={{ mode: "reset" }}+ >+ <TransformComponent wrapperClass="image-viewer-viewport" contentClass="image-viewer-content">+ <img className={imgClassName} src={src} alt={alt} />+ </TransformComponent>+ </TransformWrapper>+ );+}diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsxindex 06111bb8bd..1a05bb179e 100644--- a/apps/client/src/widgets/type_widgets/Attachment.tsx+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx@@ -144,7 +144,7 @@ function AttachmentInfo({ attachment, isFullDetail }: { attachment: FAttachment,const supportsOcr = attachment.role === "image" || attachment.role === "file";function refresh() {- content_renderer.getRenderedContent(attachment, { imageHasZoom: isFullDetail })+ content_renderer.getRenderedContent(attachment).then(({ $renderedContent }) => {contentWrapper.current?.replaceChildren(...$renderedContent);});diff --git a/apps/client/src/widgets/type_widgets/Image.css b/apps/client/src/widgets/type_widgets/Image.cssindex 1e638f86be..97c7940dc5 100644--- a/apps/client/src/widgets/type_widgets/Image.css+++ b/apps/client/src/widgets/type_widgets/Image.css@@ -8,17 +8,13 @@.note-detail-image-wrapper {position: relative;- display: flex;- align-items: center;overflow: hidden;- justify-content: center;height: 100%;}-.note-detail-image-view {- display: block;- width: auto;- height: auto;- align-self: center;- flex-shrink: 0;-}\ No newline at end of file+/* Off-screen host used only to copy a clean image reference to the clipboard. */+.image-copy-reference-source {+ position: absolute;+ pointer-events: none;+ opacity: 0;+}diff --git a/apps/client/src/widgets/type_widgets/Image.tsx b/apps/client/src/widgets/type_widgets/Image.tsxindex 9386344237..d65d41b854 100644--- a/apps/client/src/widgets/type_widgets/Image.tsx+++ b/apps/client/src/widgets/type_widgets/Image.tsx@@ -1,52 +1,59 @@-import { useEffect, useRef, useState } from "preact/hooks";-import { createImageSrcUrl } from "../../services/utils";-import { useTriliumEvent, useUniqueName } from "../react/hooks";import "./Image.css";-import { TypeWidgetProps } from "./type_widget";-import WheelZoom from 'vanilla-js-wheel-zoom';++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 { refToJQuerySelector } from "../react/react_utils";import { copyImageReferenceToClipboard } from "../../services/image";+import { createImageSrcUrl } from "../../services/utils";+import { useTriliumEvent, useTriliumEvents } from "../react/hooks";+import ImageViewer from "../react/ImageViewer";+import { refToJQuerySelector } from "../react/react_utils";+import { TypeWidgetProps } from "./type_widget";export default function Image({ note, ntxId }: TypeWidgetProps) {- const uniqueId = useUniqueName("image");const containerRef = useRef<HTMLDivElement>(null);+ const copyRef = useRef<HTMLDivElement>(null);+ const zoomRef = useRef<ReactZoomPanPinchRef>(null);const [ refreshCounter, setRefreshCounter ] = useState(0);- // Set up pan & zoom- useEffect(() => {- const zoomInstance = WheelZoom.create(`#${uniqueId}`, {- maxScale: 50,- speed: 1.3,- zoomOnClick: false- });-- return () => zoomInstance.destroy();- }, [ note ]);-- // Set up context menuuseEffect(() => image_context_menu.setupContextMenu(refToJQuerySelector(containerRef)), []);- // Copy reference events+ // The ribbon's "copy reference" button triggers this. Copy a plain <img> rather than the+ // zoom wrapper so the clipboard gets clean markup without the transform containers.useTriliumEvent("copyImageReferenceToClipboard", ({ ntxId: eventNtxId }) => {- if (eventNtxId !== ntxId) return;- copyImageReferenceToClipboard(refToJQuerySelector(containerRef));+ if (eventNtxId !== ntxId || !copyRef.current) return;+ const img = document.createElement("img");+ img.src = createImageSrcUrl(note);+ copyRef.current.replaceChildren(img);+ copyImageReferenceToClipboard(refToJQuerySelector(copyRef));+ copyRef.current.replaceChildren();+ });++ useTriliumEvents([ "imageZoomIn", "imageZoomOut", "imageZoomReset" ], ({ ntxId: eventNtxId }, eventName) => {+ const zoom = zoomRef.current;+ if (eventNtxId !== ntxId || !zoom) return;+ if (eventName === "imageZoomIn") zoom.zoomIn();+ else if (eventName === "imageZoomOut") zoom.zoomOut();+ else zoom.resetTransform();});- // React to new revisions.+ // A new revision swaps the image content; remount so it re-fits to the viewport.useTriliumEvent("entitiesReloaded", ({ loadResults }) => {if (loadResults.isNoteReloaded(note.noteId)) {- setRefreshCounter(refreshCounter + 1);+ setRefreshCounter((c) => c + 1);}});return (<div ref={containerRef} className="note-detail-image-wrapper">- <img- id={uniqueId}- className="note-detail-image-view"+ <ImageViewer+ key={`${note.noteId}-${refreshCounter}`}+ apiRef={zoomRef}+ imgClassName="note-detail-image-view"src={createImageSrcUrl(note)}/>+ <div ref={copyRef} className="image-copy-reference-source" /></div>- )+ );}diff --git a/apps/standalone/package.json b/apps/standalone/package.jsonindex bd0799db1f..ebea69f6a3 100644--- a/apps/standalone/package.json+++ b/apps/standalone/package.json@@ -67,10 +67,10 @@"preact": "10.29.2","react-i18next": "17.0.8","react-window": "2.2.7",+ "react-zoom-pan-pinch": "4.0.3","reveal.js": "6.0.1","svg-pan-zoom": "3.6.2",- "tabulator-tables": "6.4.0",- "vanilla-js-wheel-zoom": "9.0.4"+ "tabulator-tables": "6.4.0"},"devDependencies": {"@types/aes-js": "3.1.4",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 46f355dd92..737222aa89 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -353,6 +353,9 @@ importers:react-window:specifier: 2.2.7+ react-zoom-pan-pinch:+ specifier: 4.0.3reveal.js:specifier: 6.0.1version: 6.0.1@@ -365,9 +368,6 @@ importers:tabulator-tables:specifier: 6.4.0version: 6.4.0- vanilla-js-wheel-zoom:- specifier: 9.0.4- version: 9.0.4devDependencies:'@ckeditor/ckeditor5-inspector':specifier: 5.0.1@@ -954,6 +954,9 @@ importers:react-window:specifier: 2.2.7+ react-zoom-pan-pinch:+ specifier: 4.0.3reveal.js:specifier: 6.0.1version: 6.0.1@@ -966,9 +969,6 @@ importers:tabulator-tables:specifier: 6.4.0version: 6.4.0- vanilla-js-wheel-zoom:- specifier: 9.0.4- version: 9.0.4devDependencies:'@ckeditor/ckeditor5-inspector':specifier: 5.0.1@@ -11509,6 +11509,13 @@ packages:react: ^18.0.0 || ^19.0.0react-dom: ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-N2Hi6L78fFmhRra+ORpFSW7WST5x6kxpOPplIvtB0b7b+U2anpo1z1wLgaWRPS2kUSqcraRG+JgBCIlDJnqqAg==}+ engines: {node: '>=8', npm: '>=5'}+ peerDependencies:+ react: '*'+ react-dom: '*'+resolution: {integrity: sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==}engines: {node: '>=0.10.0'}@@ -13029,9 +13036,6 @@ packages:resolution: {integrity: sha512-z2YZusTFC6KnLERx1cgoIRX2CjPRP0W75N+3CC6gbvdX5Ch47rZkEMGO2Xnf+IEmi3RiFLxS18gayMA27iU7Kg==}- resolution: {integrity: sha512-OjmS9ihEKBCRw2OQ7IiIdQGXdC5gTEEmtcAWZcPeNAJaYiS61KCd02Z72YMtIoXLGN5TZP+wliBMylLAsr6wow==}-resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}engines: {node: '>= 0.8'}@@ -26341,6 +26345,11 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])+ dependencies:+ react: 19.2.6+ react-dom: 19.2.6([email protected])+dependencies:loose-envify: 1.4.0@@ -28133,8 +28142,6 @@ snapshots:- [email protected]: {}-