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: add entrance transition
Adorian Doran72026ebef2bf
diff --git a/apps/client/src/widgets/react/ImageViewer.css b/apps/client/src/widgets/react/ImageViewer.cssindex c8e10450dd..73e66b3aa1 100644--- a/apps/client/src/widgets/react/ImageViewer.css+++ b/apps/client/src/widgets/react/ImageViewer.css@@ -33,6 +33,23 @@.image-viewer-content img {max-width: 100%;max-height: 100%;+ opacity: 1;+ transition: opacity 300ms ease-out;+}++/* The image stays hidden until it has decoded, then fades in; it is also hidden on error. */+.image-viewer-viewport:not(.img-loaded) .image-viewer-content img,+.image-viewer-viewport.img-loading-error .image-viewer-content img {+ opacity: 0;+}++/* A failed load tints the viewport red. */+.image-viewer-viewport {+ transition: background-color 300ms ease-out;+}++.image-viewer-viewport.img-loading-error {+ background-color: var(--dropdown-item-icon-destructive-color);}/* The the grab cursor only while the image is large enough to pan (zoomed past fit). */diff --git a/apps/client/src/widgets/react/ImageViewer.spec.tsx b/apps/client/src/widgets/react/ImageViewer.spec.tsxindex 7aac45231d..3f74c09dee 100644--- a/apps/client/src/widgets/react/ImageViewer.spec.tsx+++ b/apps/client/src/widgets/react/ImageViewer.spec.tsx@@ -1,5 +1,5 @@import { type ComponentChildren, render } from "preact";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// Capture the props handed to the zoom library without mounting it (it needs real layout).const { transformWrapperSpy } = vi.hoisted(() => ({ transformWrapperSpy: vi.fn() }));@@ -9,7 +9,10 @@ vi.mock("react-zoom-pan-pinch", () => ({transformWrapperSpy(props);return props.children;},- TransformComponent: (props: { children?: ComponentChildren }) => props.children+ // Surface the dynamic wrapper class so tests can observe the loaded/load-error state.+ TransformComponent: (props: { children?: ComponentChildren; wrapperClass?: string }) => (+ <div className={props.wrapperClass}>{props.children}</div>+ )}));// Avoid pulling the real hooks module (bootstrap tooltips + app context) into the test.@@ -24,7 +27,17 @@ function renderViewer(props: Parameters<typeof ImageViewer>[0]) {}describe("ImageViewer", () => {- beforeEach(() => transformWrapperSpy.mockClear());+ // The viewer reveals via HTMLImageElement.decode(); stub it so both paths are deterministic+ // (happy-dom does no real image loading). Default resolves so the timer never lingers.+ let originalDecode: typeof HTMLImageElement.prototype.decode;+ beforeEach(() => {+ transformWrapperSpy.mockClear();+ originalDecode = HTMLImageElement.prototype.decode;+ HTMLImageElement.prototype.decode = () => Promise.resolve();+ });+ afterEach(() => {+ HTMLImageElement.prototype.decode = originalDecode;+ });it("renders the image with the given src, alt and class", () => {const container = renderViewer({ src: "api/images/abc/Pic", imgClassName: "note-detail-image-view", alt: "Pic" });@@ -53,6 +66,35 @@ describe("ImageViewer", () => {expect(props.minScale).toBe(1);expect(props.maxScale).toBe(8);});++ const wrapperClassList = (container: HTMLElement) => container.querySelector(".image-viewer-viewport")?.classList;++ it("starts hidden — image not yet revealed, neither loaded nor failed, no zoom controls", () => {+ // decode() resolves on a microtask, so synchronously after render the image is still hidden.+ const container = renderViewer({ src: "x" });+ expect(wrapperClassList(container)?.contains("img-loaded")).toBe(false);+ expect(wrapperClassList(container)?.contains("img-loading-error")).toBe(false);+ // The image is present (so it can fade in) but the controls wait until it has loaded.+ expect(container.querySelector("img")).not.toBeNull();+ expect(container.querySelector(".image-viewer-controls")).toBeNull();+ });++ it("reveals the image and its zoom controls once it decodes", async () => {+ const container = renderViewer({ src: "x" });++ await vi.waitFor(() => expect(wrapperClassList(container)?.contains("img-loaded")).toBe(true));+ expect(wrapperClassList(container)?.contains("img-loading-error")).toBe(false);+ expect(container.querySelector(".image-viewer-controls")).not.toBeNull();+ });++ it("tints the viewport red, keeping the image hidden, when decoding fails", async () => {+ HTMLImageElement.prototype.decode = () => Promise.reject(new Error("decode failed"));+ const container = renderViewer({ src: "x" });++ await vi.waitFor(() => expect(wrapperClassList(container)?.contains("img-loading-error")).toBe(true));+ expect(wrapperClassList(container)?.contains("img-loaded")).toBe(false);+ expect(container.querySelector(".image-viewer-controls")).toBeNull();+ });});describe("evaluateImageZoom", () => {diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsxindex babec02ff0..cd71cbacc4 100644--- a/apps/client/src/widgets/react/ImageViewer.tsx+++ b/apps/client/src/widgets/react/ImageViewer.tsx@@ -1,7 +1,7 @@import "./ImageViewer.css";import { Ref } from "preact";-import { useCallback, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";import { t } from "../../services/i18n";@@ -24,6 +24,8 @@ interface ImageViewerProps {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;+/** Reveal the image even if `decode()` never settles (it can stall for some images, e.g. SVGs). */+const REVEAL_FALLBACK_MS = 1000;/*** Derives the zoom-driven values: whether the image is pannable (zoomed past the fitted size),@@ -45,6 +47,8 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.const [ panning, setPanning ] = useState(false);const [ largeZoom, setLargeZoom ] = useState(false);const [ zoomPercent, setZoomPercent ] = useState(0);+ const [ loaded, setLoaded ] = useState(false);+ const [ loadingError, setLoadingError ] = useState(false);const imgRef = useRef<HTMLImageElement>(null);const rootRef = useRef<HTMLDivElement>(null);const zoomRef = useRef<ReactZoomPanPinchRef>(null);@@ -59,11 +63,6 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.else if (apiRef) (apiRef as { current: ReactZoomPanPinchRef | null }).current = instance;}, [ 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);@@ -73,11 +72,47 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.if (percent !== zoomPercent) setZoomPercent(percent);};+ // Reveal (or fail) the image, driven by decode() rather than the load event. decode() resolves once+ // the bitmap is ready whether or not we observed `load`, so a fast/cached image that finishes before+ // the handler is wired can't stay hidden forever (a race the load event has). Large images therefore+ // fade in on real pixels; the timer guarantees we always reveal even if decode() never settles (it+ // can, e.g. for some SVGs). Where decode() is unavailable, the load/error events take over.+ useEffect(() => {+ setLoaded(false);+ setLoadingError(false);++ const img = imgRef.current;+ if (!img || typeof img.decode !== "function") return;++ let settled = false;+ const settle = (action: () => void) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ action();+ };+ const reveal = () => settle(() => {+ setLoaded(true);+ updateZoomState(zoomRef.current?.instance?.state?.scale ?? 1);+ });+ const timer = setTimeout(reveal, REVEAL_FALLBACK_MS);+ img.decode().then(reveal, () => settle(() => setLoadingError(true)));++ return () => settle(() => {});+ }, [ src ]); // eslint-disable-line react-hooks/exhaustive-deps -- updateZoomState identity changes each render++ 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" });+const wrapperClass = ["image-viewer-viewport",pannable && "pannable",panning && "panning",- largeZoom && "tn-image-large-zoom"+ largeZoom && "tn-image-large-zoom",+ loaded && "img-loaded",+ loadingError && "img-loading-error"].filter(Boolean).join(" ");return (@@ -101,12 +136,19 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.className={imgClassName}src={src}alt={alt}- onLoad={() => updateZoomState(zoomRef.current?.instance.state.scale ?? 1)}+ onLoad={() => {+ // The decode() effect handles the reveal where supported; this only covers the rare+ // environment without decode() (the effect bails there).+ if (typeof imgRef.current?.decode === "function") return;+ setLoaded(true);+ updateZoomState(zoomRef.current?.instance?.state?.scale ?? 1);+ }}+ onError={() => setLoadingError(true)}/></TransformComponent></TransformWrapper>- {!isMobile() && (+ {!isMobile() && loaded && (<div className="image-viewer-controls"><buttonref={zoomOutRef}