Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client): share one set of zoom controls, and fix the step they take

Elian Doran89d53d6da97a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 33c2639c36..c6de663081 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1208,15 +1208,7 @@
},
"relation_map_buttons": {
"create_child_note_title": "Create child note and add it to map",
- "create_child_note_text": "Add note",
- "reset_pan_zoom_title": "Reset pan & zoom to initial coordinates and magnification",
- "zoom_in_title": "Zoom In",
- "zoom_out_title": "Zoom Out"
- },
- "image_buttons": {
- "zoom_in": "Zoom in",
- "zoom_out": "Zoom out",
- "reset_zoom": "Reset zoom"
+ "create_child_note_text": "Add note"
},
"image_navigation": {
"previous": "Previous image: {{- title}}",
@@ -3049,8 +3041,6 @@
"move-marker-toast-title": "Move marker",
"unable-to-load-map": "Unable to load map.",
"webgl-unavailable": "This map can't be drawn because WebGL isn't available. Check that hardware acceleration is enabled and that your graphics drivers are up to date.",
- "zoom-in": "Zoom in",
- "zoom-out": "Zoom out",
"enter-3d": "Tilt into a 3D view\nHold Ctrl and drag to tilt the map freely",
"exit-3d": "Lay the map flat again",
"close-details": "Close",
@@ -3350,10 +3340,7 @@
},
"svg": {
"export_to_png": "The diagram could not be exported to PNG.",
- "export_to_svg": "The diagram could not be exported to SVG.",
- "zoom_in": "Zoom in",
- "zoom_out": "Zoom out",
- "reset_zoom": "Reset zoom"
+ "export_to_svg": "The diagram could not be exported to SVG."
},
"code_theme": {
"title": "Appearance",
@@ -4004,9 +3991,6 @@
"tags-differ": "The selected nodes don't carry the same tags, so these can only be read.",
"add-tag": "Add this tag",
"remove-tag": "Remove this tag",
- "zoom-in": "Zoom in",
- "zoom-out": "Zoom out",
- "reset-zoom": "Reset zoom",
"center-map": "Center the map",
"direction-left": "Branches to the left",
"direction-right": "Branches to the right",
@@ -4301,5 +4285,10 @@
"creation-date": "Creation date & time",
"ascending": "Ascending",
"descending": "Descending"
+ },
+ "zoom_controls": {
+ "zoom_out": "Zoom out",
+ "reset": "Reset zoom",
+ "zoom_in": "Zoom in"
}
}
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
index e785e69fb7..8d2017b2a2 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
@@ -8,7 +8,7 @@ import { t } from "../../../services/i18n";
import toast from "../../../services/toast";
import { isMobile } from "../../../services/utils";
import { useFullscreen } from "../../react/hooks";
-import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton } from "../../react/OverlayControlGroup";
+import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton, ZoomControls } from "../../react/OverlayControlGroup";
import { ParentMap, useMapPitch } from "./map";
/**
@@ -88,20 +88,14 @@ export default function MapToolbar({ onLocationClick }: MapToolbarProps) {
className="geo-map-tilt-button"
onClick={() => map.easeTo({ pitch: isTilted ? 0 : TILTED_PITCH })}
/>
- {!isMobile() && <>
- <OverlayControlButton
- title={t("geo-map.zoom-out")}
- icon="bx-minus-circle"
- disabled={current <= map.getMinZoom()}
- onClick={() => map.zoomOut()}
+ {!isMobile() && (
+ <ZoomControls
+ canZoomIn={current < map.getMaxZoom()}
+ canZoomOut={current > map.getMinZoom()}
+ onZoomIn={() => map.zoomIn()}
+ onZoomOut={() => map.zoomOut()}
/>
- <OverlayControlButton
- title={t("geo-map.zoom-in")}
- icon="bx-plus-circle"
- disabled={current >= map.getMaxZoom()}
- onClick={() => map.zoomIn()}
- />
- </>}
+ )}
{locate && <OverlayControlButton
title={locateTitle(locate)}
icon="bx-current-location"
diff --git a/apps/client/src/widgets/react/ImageViewer.tsx b/apps/client/src/widgets/react/ImageViewer.tsx
index 4461aab5f1..155795fae9 100644
--- a/apps/client/src/widgets/react/ImageViewer.tsx
+++ b/apps/client/src/widgets/react/ImageViewer.tsx
@@ -1,8 +1,7 @@
import "./ImageViewer.css";
-import { Ref } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
-import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
+import { useEffect, useRef, useState } from "preact/hooks";
+import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
import { t } from "../../services/i18n";
import type { ShortcutHintDefinition } from "../../services/shortcut_hints";
@@ -11,7 +10,8 @@ import ShortcutHintButton from "../shortcut_hints/shortcut_hint_button";
import ContentErrorMessage from "./ContentErrorMessage";
import { useContextualShortcutHints } from "./hooks";
import { useImageViewerKeyboard } from "./image_viewer_keyboard";
-import OverlayControlGroup, { OverlayControlButton } from "./OverlayControlGroup";
+import OverlayControlGroup, { ZoomControls } from "./OverlayControlGroup";
+import { useZoomPanPinch } from "./zoom_pan";
interface ImageViewerProps {
src: string;
@@ -20,14 +20,10 @@ interface ImageViewerProps {
alt?: string;
minScale?: number;
maxScale?: number;
- /** Exposes the zoom/pan instance so the parent can drive zoom in/out/reset. */
- apiRef?: Ref<ReactZoomPanPinchRef>;
}
/** 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;
/** Reveal the image even if `decode()` never settles (it can stall for some images, e.g. SVGs). */
const REVEAL_FALLBACK_MS = 1000;
@@ -76,7 +72,7 @@ export function evaluateImageZoom(scale: number, img: { naturalWidth: number; cl
* Interactive image viewer: the image is fit to the viewport on load, then the user can zoom
* (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) {
+export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.5, maxScale = 50 }: ImageViewerProps) {
const [ pannable, setPannable ] = useState(false);
const [ panning, setPanning ] = useState(false);
const [ largeZoom, setLargeZoom ] = useState(false);
@@ -85,14 +81,6 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
const [ loadingError, setLoadingError ] = 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 ]);
// Recompute the cursor/rendering flags and the displayed (native-relative) zoom percentage.
// The setters bail out on identical values, so no manual change checks are needed.
@@ -100,9 +88,11 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
const { pannable: nextPannable, largeZoom: nextLargeZoom, nativeScale } = evaluateImageZoom(scale, imgRef.current);
setPannable(nextPannable);
setLargeZoom(nextLargeZoom);
- setZoomPercent(Math.round(nativeScale * 100));
+ setZoomPercent(nativeScale * 100);
};
+ const zoom = useZoomPanPinch({ minScale, maxScale, onScaleChange: updateZoomState });
+
// 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
@@ -124,7 +114,7 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
};
const reveal = () => settle(() => {
setLoaded(true);
- updateZoomState(zoomRef.current?.instance?.state?.scale ?? 1);
+ updateZoomState(zoom.ref.current?.instance?.state?.scale ?? 1);
});
const timer = setTimeout(reveal, REVEAL_FALLBACK_MS);
if (typeof img.decode === "function") {
@@ -143,7 +133,7 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
return () => settle(() => {});
}, [ src ]);
- useImageViewerKeyboard(zoomRef, rootRef);
+ useImageViewerKeyboard(zoom.ref, rootRef);
useContextualShortcutHints(IMAGE_VIEWER_HINTS);
const wrapperClass = [
@@ -158,7 +148,7 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
return (
<div ref={rootRef} tabIndex={0} className="image-viewer-root">
<TransformWrapper
- ref={setZoomRef}
+ ref={zoom.ref}
minScale={minScale}
maxScale={maxScale}
centerOnInit
@@ -166,7 +156,7 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
wheel={{ step: 0.0085 }}
autoAlignment={{ disabled: true }}
doubleClick={{ mode: "reset" }}
- onTransform={(_ref, { scale }) => updateZoomState(scale)}
+ onTransform={zoom.onTransform}
onPanningStart={() => setPanning(true)}
onPanningStop={() => setPanning(false)}
>
@@ -190,20 +180,13 @@ export default function ImageViewer({ src, imgClassName, alt = "", minScale = 0.
{!isMobile() && loaded && (
<OverlayControlGroup className="image-viewer-controls" placement="bottom-end">
- <OverlayControlButton
- title={t("image_buttons.zoom_out")}
- icon="bx-minus-circle"
- onClick={() => zoomRef.current?.zoomOut(BUTTON_ZOOM_STEP)}
- />
- <OverlayControlButton
- title={t("image_buttons.reset_zoom")}
- text={`${zoomPercent}%`}
- onClick={() => zoomRef.current?.resetTransform()}
- />
- <OverlayControlButton
- title={t("image_buttons.zoom_in")}
- icon="bx-plus-circle"
- onClick={() => zoomRef.current?.zoomIn(BUTTON_ZOOM_STEP)}
+ <ZoomControls
+ percent={zoomPercent}
+ canZoomIn={zoom.canZoomIn}
+ canZoomOut={zoom.canZoomOut}
+ onZoomIn={zoom.zoomIn}
+ onZoomOut={zoom.zoomOut}
+ onReset={zoom.reset}
/>
</OverlayControlGroup>
)}
diff --git a/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx
index 9bae4fff81..b5a0f49fae 100644
--- a/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx
+++ b/apps/client/src/widgets/react/OverlayControlGroup.spec.tsx
@@ -7,7 +7,7 @@ const { staticTooltipSpy } = vi.hoisted(() => ({ staticTooltipSpy: vi.fn() }));
vi.mock("./hooks", () => ({ useStaticTooltip: staticTooltipSpy }));
vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
-import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton } from "./OverlayControlGroup";
+import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton, ZoomControls } from "./OverlayControlGroup";
let container: HTMLDivElement;
@@ -306,3 +306,46 @@ describe("OverlayFullscreenButton", () => {
expect(onToggle).toHaveBeenCalledWith();
});
});
+
+describe("ZoomControls", () => {
+ const handlers = () => ({ onZoomIn: vi.fn(), onZoomOut: vi.fn(), onReset: vi.fn() });
+
+ it("rounds the percentage it is handed, and hands each press back to the caller", () => {
+ const on = handlers();
+ mount(<ZoomControls percent={144.4} {...on} />);
+
+ const [ zoomOut, readout, zoomIn ] = container.querySelectorAll("button");
+ expect(readout.textContent).toBe("144%");
+ expect(zoomOut.getAttribute("aria-label")).toBe("zoom_controls.zoom_out");
+ expect(zoomIn.getAttribute("aria-label")).toBe("zoom_controls.zoom_in");
+
+ act(() => zoomOut.click());
+ act(() => readout.click());
+ act(() => zoomIn.click());
+ expect(on.onZoomOut).toHaveBeenCalledTimes(1);
+ expect(on.onReset).toHaveBeenCalledTimes(1);
+ expect(on.onZoomIn).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves the two steps alive unless told a bound has been reached", () => {
+ mount(<ZoomControls percent={100} {...handlers()} />);
+ for (const button of container.querySelectorAll("button")) expect(button.disabled).toBe(false);
+
+ act(() => render(<ZoomControls percent={100} canZoomIn={false} canZoomOut={false} {...handlers()} />, container));
+ const [ zoomOut, readout, zoomIn ] = container.querySelectorAll("button");
+ expect(zoomOut.disabled).toBe(true);
+ expect(zoomIn.disabled).toBe(true);
+ // The way back is never refused: a bound is about the steps, not about the fitted view.
+ expect(readout.disabled).toBe(false);
+ });
+
+ it("shows the two steps alone where the content has no percentage worth saying, as a map has not", () => {
+ const on = handlers();
+ mount(<ZoomControls onZoomIn={on.onZoomIn} onZoomOut={on.onZoomOut} />);
+
+ const buttons = container.querySelectorAll("button");
+ expect(buttons).toHaveLength(2);
+ expect([ ...buttons ].map((b) => b.getAttribute("aria-label")))
+ .toEqual([ "zoom_controls.zoom_out", "zoom_controls.zoom_in" ]);
+ });
+});
diff --git a/apps/client/src/widgets/react/OverlayControlGroup.tsx b/apps/client/src/widgets/react/OverlayControlGroup.tsx
index a67b3a2923..739bd1d7f7 100644
--- a/apps/client/src/widgets/react/OverlayControlGroup.tsx
+++ b/apps/client/src/widgets/react/OverlayControlGroup.tsx
@@ -175,5 +175,54 @@ export function OverlayFullscreenButton({ isFullscreen, onToggle }: OverlayFulls
);
}
+interface ZoomControlsProps {
+ /**
+ * The scale as a percentage of whatever the content's own hundred is — its native resolution,
+ * its fitted view, its natural size. Left out, the two steps stand alone: a map's zoom level is a
+ * number out of the cartographer's toolbox, not the reader's.
+ */
+ percent?: number;
+ /** Whether either step has room left; a step that would do nothing is shown disabled. */
+ canZoomIn?: boolean;
+ canZoomOut?: boolean;
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+ /** Only reached through the readout, so only needed where there is a `percent` to show. */
+ onReset?: () => void;
+}
+
+/**
+ * The zoom steps every set of controls over content carries: out, the scale, and in.
+ *
+ * Buttons rather than a group of their own, the image viewer and the diagram preview showing nothing
+ * else while the maps stand them among a tilt, a recenter and a fullscreen. What a hundred percent
+ * means is the content's to say, so the readout is handed a percentage rather than a scale.
+ */
+export function ZoomControls({ percent, canZoomIn = true, canZoomOut = true, onZoomIn, onZoomOut, onReset }: ZoomControlsProps) {
+ return (
+ <>
+ <OverlayControlButton
+ title={t("zoom_controls.zoom_out")}
+ icon="bx-minus-circle"
+ disabled={!canZoomOut}
+ onClick={onZoomOut}
+ />
+ {percent !== undefined && (
+ <OverlayControlButton
+ title={t("zoom_controls.reset")}
+ text={`${Math.round(percent)}%`}
+ onClick={onReset}
+ />
+ )}
+ <OverlayControlButton
+ title={t("zoom_controls.zoom_in")}
+ icon="bx-plus-circle"
+ disabled={!canZoomIn}
+ onClick={onZoomIn}
+ />
+ </>
+ );
+}
+
/** Which way the tooltips on a group open, handed down by the group rather than repeated on each button. */
const TooltipDirection = createContext<ActionButtonProps["titlePosition"]>("top");
diff --git a/apps/client/src/widgets/react/zoom_pan.spec.ts b/apps/client/src/widgets/react/zoom_pan.spec.ts
new file mode 100644
index 0000000000..c098548658
--- /dev/null
+++ b/apps/client/src/widgets/react/zoom_pan.spec.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { zoomStep } from "./zoom_pan";
+
+describe("zoomStep", () => {
+ it("is the increment react-zoom-pan-pinch needs for a ×1.2 step, at any scale", () => {
+ // The library adds the step to the current scale, so what is asserted is where each press
+ // lands rather than the increment itself.
+ expect(1 + zoomStep(1, "in")).toBeCloseTo(1.2);
+ expect(1 - zoomStep(1, "out")).toBeCloseTo(1 / 1.2);
+
+ // A fixed increment would be a leap here and a crawl at the other end; these stay a fifth
+ // of what is on screen apart.
+ expect(0.6 + zoomStep(0.6, "in")).toBeCloseTo(0.72);
+ expect(8 + zoomStep(8, "in")).toBeCloseTo(9.6);
+
+ // A step out undoes a step in, so the readout returns to where it started.
+ const zoomedIn = 3 + zoomStep(3, "in");
+ expect(zoomedIn - zoomStep(zoomedIn, "out")).toBeCloseTo(3);
+ });
+});
diff --git a/apps/client/src/widgets/react/zoom_pan.ts b/apps/client/src/widgets/react/zoom_pan.ts
new file mode 100644
index 0000000000..957680febb
--- /dev/null
+++ b/apps/client/src/widgets/react/zoom_pan.ts
@@ -0,0 +1,73 @@
+import type { RefObject } from "preact";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import type { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
+
+interface ZoomPanPinchOptions {
+ /** The closest in and the furthest out the content can be taken, as the wrapper is given them. */
+ minScale: number;
+ maxScale: number;
+ /** Puts the scale back to 1 when this changes, for a wrapper that is remounted under the hook. */
+ resetOn?: unknown;
+ /** Called with the scale on every change, for whatever else a caller derives from it. */
+ onScaleChange?: (scale: number) => void;
+}
+
+/**
+ * Drives a react-zoom-pan-pinch instance: the ref to hand `TransformWrapper`, the scale it is at,
+ * whether either step has room left, and the three things a set of zoom controls does to it.
+ *
+ * `onTransform` goes on the wrapper, so the scale here follows every change — a button, the wheel,
+ * a pinch, a double click.
+ */
+export function useZoomPanPinch({ minScale, maxScale, resetOn, onScaleChange }: ZoomPanPinchOptions) {
+ const ref = useRef<ReactZoomPanPinchRef>(null);
+ const [ scale, setScale ] = useState(1);
+
+ // Read through a ref so a caller can pass a fresh closure without rewiring the wrapper.
+ const onScaleChangeRef = useRef(onScaleChange);
+ useEffect(() => { onScaleChangeRef.current = onScaleChange; });
+
+ useEffect(() => { setScale(1); }, [ resetOn ]);
+
+ const onTransform = useCallback((_ref: ReactZoomPanPinchRef, state: { scale: number }) => {
+ setScale(state.scale);
+ onScaleChangeRef.current?.(state.scale);
+ }, []);
+
+ return {
+ ref,
+ scale,
+ onTransform,
+ canZoomIn: scale < maxScale * (1 - ZOOM_LIMIT_TOLERANCE),
+ canZoomOut: scale > minScale * (1 + ZOOM_LIMIT_TOLERANCE),
+ zoomIn: () => ref.current?.zoomIn(zoomStep(currentScale(ref), "in")),
+ zoomOut: () => ref.current?.zoomOut(zoomStep(currentScale(ref), "out")),
+ reset: () => ref.current?.resetTransform()
+ };
+}
+
+/** What one press of a zoom step multiplies the scale by. */
+const ZOOM_STEP = 1.2;
+/**
+ * How near a bound counts as being on it. The zoom animation reaches its target by adding the whole
+ * difference back to the scale it started from, which can land a float's width short of the bound.
+ */
+const ZOOM_LIMIT_TOLERANCE = 1e-6;
+
+/**
+ * The increment that takes `scale` one {@link ZOOM_STEP} in the given direction.
+ *
+ * react-zoom-pan-pinch adds the step to the current scale rather than multiplying by it (see
+ * `handleCalculateButtonZoom`), so a fixed step is a leap at the bottom of the range and a crawl at
+ * the top: from a fitted view one press of a 0.5 step reaches a `minScale` of 0.5, while 98 more are
+ * needed to reach a `maxScale` of 50. Scaling the step by the scale it applies to keeps every press
+ * the same proportion of what is on screen.
+ */
+export function zoomStep(scale: number, direction: "in" | "out") {
+ return direction === "in" ? scale * (ZOOM_STEP - 1) : scale * (1 - 1 / ZOOM_STEP);
+}
+
+/** The scale the instance is at now, read as a button is pressed rather than when it was drawn. */
+function currentScale(ref: RefObject<ReactZoomPanPinchRef>) {
+ return ref.current?.instance?.state?.scale ?? 1;
+}
diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx
index 5a01a20a94..ed2f504e29 100644
--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.spec.tsx
@@ -26,15 +26,18 @@ vi.mock("react-zoom-pan-pinch", async () => {
return {
TransformWrapper: forwardRef((props: FakeProps, ref) => {
transformWrapperSpy(props);
- const scale = useRef(1);
+ // One object, mutated in place: `useZoomPanPinch` reads `instance.state.scale` as a
+ // button is pressed, so a fresh snapshot per render would be one step behind.
+ const state = useRef({ scale: 1 });
const apply = (target: number) => {
const rounded = Number(target.toFixed(3));
- scale.current = Math.min(props.maxScale, Math.max(props.minScale, rounded));
- props.onTransform?.(null, { scale: scale.current });
+ state.current.scale = Math.min(props.maxScale, Math.max(props.minScale, rounded));
+ props.onTransform?.(null, { scale: state.current.scale });
};
useImperativeHandle(ref, () => ({
- zoomIn: (step: number) => apply(scale.current + step),
- zoomOut: (step: number) => apply(scale.current - step),
+ instance: { state: state.current },
+ zoomIn: (step: number) => apply(state.current.scale + step),
+ zoomOut: (step: number) => apply(state.current.scale - step),
resetTransform: () => apply(1)
}));
return props.children;
diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx
index 61160ef054..5aeea23941 100644
--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx
@@ -1,14 +1,14 @@
-import { RefObject } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
-import { type ReactZoomPanPinchRef, TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
+import { useCallback, useEffect, useState } from "preact/hooks";
+import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
import utils from "../../../services/utils";
import { useTriliumEvent } from "../../react/hooks";
-import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import OverlayControlGroup, { ZoomControls } from "../../react/OverlayControlGroup";
import { RawHtmlBlock } from "../../react/RawHtml";
+import { useZoomPanPinch } from "../../react/zoom_pan";
import SplitEditor, { SplitEditorProps } from "./SplitEditor";
interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {
@@ -41,15 +41,13 @@ interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {
export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg, ...props }: SvgSplitEditorProps) {
const [ svg, setSvg ] = useState<string>();
const [ error, setError ] = useState<string | null | undefined>();
- const [ zoom, setZoom ] = useState(1);
- const zoomRef = useRef<ReactZoomPanPinchRef>(null);
+ const zoom = useZoomPanPinch({ minScale: MIN_ZOOM, maxScale: MAX_ZOOM, resetOn: note.noteId });
// Reset the render state when switching notes so a previous note's render (and the
// "showing last valid render" badge) can't briefly carry over to a different note.
useEffect(() => {
setSvg(undefined);
setError(undefined);
- setZoom(1);
}, [ note.noteId ]);
// Render the SVG.
@@ -129,20 +127,31 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg
// The transform sits on an ancestor of the diagram, so it survives a re-render
// of the same note. Keying it on the note drops it when a different one opens.
key={note.noteId}
- ref={zoomRef}
+ ref={zoom.ref}
minScale={MIN_ZOOM}
maxScale={MAX_ZOOM}
centerOnInit
centerZoomedOut
doubleClick={{ mode: "reset" }}
- onTransform={(_ref, { scale }) => setZoom(scale)}
+ onTransform={zoom.onTransform}
>
<TransformComponent wrapperClass="svg-preview-viewport" contentClass="svg-preview-content">
<RawHtmlBlock className="render-container" html={svg} />
</TransformComponent>
</TransformWrapper>
)}
- previewButtons={!!svg && <PreviewControls zoomRef={zoomRef} zoom={zoom} />}
+ previewButtons={!!svg && (
+ <OverlayControlGroup className="svg-preview-controls" placement="bottom-end">
+ <ZoomControls
+ percent={zoom.scale * 100}
+ canZoomIn={zoom.canZoomIn}
+ canZoomOut={zoom.canZoomOut}
+ onZoomIn={zoom.zoomIn}
+ onZoomOut={zoom.zoomOut}
+ onReset={zoom.reset}
+ />
+ </OverlayControlGroup>
+ )}
{...props}
/>
);
@@ -157,52 +166,3 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg
*/
const MIN_ZOOM = 0.5;
const MAX_ZOOM = 10;
-/** What one press of a zoom step multiplies the scale by. */
-const ZOOM_STEP = 1.2;
-/**
- * How near a bound counts as being on it. The zoom animation reaches its target by adding the whole
- * difference back to the scale it started from, which can land a float's width short of the bound.
- */
-const ZOOM_LIMIT_TOLERANCE = 1e-6;
-
-/**
- * The zoom controls in the corner of the rendered diagram: a step in each direction, and between
- * them a readout that fits the diagram back to the pane when pressed.
- *
- * They stand on the {@link OverlayControlGroup} the image viewer's zoom buttons stand on, as the
- * two maps' controls do. The readout is a percentage of the fitted view, so a diagram opens at 100%.
- */
-function PreviewControls({ zoomRef, zoom }: { zoomRef: RefObject<ReactZoomPanPinchRef>; zoom: number }) {
- return (
- <OverlayControlGroup className="svg-preview-controls" placement="bottom-end">
- <OverlayControlButton
- title={t("svg.zoom_out")}
- icon="bx-minus-circle"
- disabled={zoom <= MIN_ZOOM * (1 + ZOOM_LIMIT_TOLERANCE)}
- onClick={() => zoomRef.current?.zoomOut(zoomStep(zoom, "out"))}
- />
- <OverlayControlButton
- title={t("svg.reset_zoom")}
- text={`${Math.round(zoom * 100)}%`}
- onClick={() => zoomRef.current?.resetTransform()}
- />
- <OverlayControlButton
- title={t("svg.zoom_in")}
- icon="bx-plus-circle"
- disabled={zoom >= MAX_ZOOM * (1 - ZOOM_LIMIT_TOLERANCE)}
- onClick={() => zoomRef.current?.zoomIn(zoomStep(zoom, "in"))}
- />
- </OverlayControlGroup>
- );
-}
-
-/**
- * The increment that takes `scale` one {@link ZOOM_STEP} in the given direction.
- *
- * react-zoom-pan-pinch adds the step to the current scale, so a fixed step would be a leap at the
- * bottom of the range and a crawl at the top. Scaling the step by the scale it applies to keeps
- * every press the same proportion of what is on screen.
- */
-function zoomStep(scale: number, direction: "in" | "out") {
- return direction === "in" ? scale * (ZOOM_STEP - 1) : scale * (1 - 1 / ZOOM_STEP);
-}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx
index 2e44ad1f0f..c970fdf0e1 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx
@@ -6,7 +6,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import { isMobile } from "../../../services/utils";
import { useFullscreen } from "../../react/hooks";
-import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton } from "../../react/OverlayControlGroup";
+import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton, ZoomControls } from "../../react/OverlayControlGroup";
import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";
import { centerMapOn, type MapPoint, readMapCenter, stepZoom } from "./viewport";
@@ -55,25 +55,16 @@ export default function MapToolbar({ mind }: MapToolbarProps) {
/>
)}
- {!isMobile() && <>
- <OverlayControlButton
- title={t("mind-map.zoom-out")}
- icon="bx-minus-circle"
- disabled={zoomedOut === null}
- onClick={() => zoomedOut !== null && mind.scale(zoomedOut)}
- />
- <OverlayControlButton
- title={t("mind-map.reset-zoom")}
- text={`${Math.round(scale * 100)}%`}
- onClick={() => mind.scale(1)}
+ {!isMobile() && (
+ <ZoomControls
+ percent={scale * 100}
+ canZoomIn={zoomedIn !== null}
+ canZoomOut={zoomedOut !== null}
+ onZoomIn={() => { if (zoomedIn !== null) mind.scale(zoomedIn); }}
+ onZoomOut={() => { if (zoomedOut !== null) mind.scale(zoomedOut); }}
+ onReset={() => mind.scale(1)}
/>
- <OverlayControlButton
- title={t("mind-map.zoom-in")}
- icon="bx-plus-circle"
- disabled={zoomedIn === null}
- onClick={() => zoomedIn !== null && mind.scale(zoomedIn)}
- />
- </>}
+ )}
<OverlayControlButton
title={t("mind-map.center-map")}
icon="bx-current-location"
diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx
index d947b725a5..cc921ca9ac 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx
@@ -4,7 +4,7 @@ import type { PanZoom } from "panzoom";
import { useEffect, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
-import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import OverlayControlGroup, { OverlayControlButton, ZoomControls } from "../../react/OverlayControlGroup";
/** What the buttons ask for, which is what the map itself answers (see `usePanZoom` in RelationMap.tsx). */
export type MapCommand = "relationMapResetZoomIn" | "relationMapResetZoomOut" | "relationMapResetPanZoom";
@@ -38,22 +38,13 @@ export default function MapToolbar({ panZoom, onCommand }: MapToolbarProps) {
return (
<OverlayControlGroup className="relation-map-toolbar" placement="bottom-end">
- <OverlayControlButton
- title={t("relation_map_buttons.zoom_out_title")}
- icon="bx-minus-circle"
- disabled={scale <= panZoom.getMinZoom()}
- onClick={() => onCommand("relationMapResetZoomOut")}
- />
- <OverlayControlButton
- title={t("relation_map_buttons.reset_pan_zoom_title")}
- text={`${Math.round(scale * 100)}%`}
- onClick={() => onCommand("relationMapResetPanZoom")}
- />
- <OverlayControlButton
- title={t("relation_map_buttons.zoom_in_title")}
- icon="bx-plus-circle"
- disabled={scale >= panZoom.getMaxZoom()}
- onClick={() => onCommand("relationMapResetZoomIn")}
+ <ZoomControls
+ percent={scale * 100}
+ canZoomIn={scale < panZoom.getMaxZoom()}
+ canZoomOut={scale > panZoom.getMinZoom()}
+ onZoomIn={() => onCommand("relationMapResetZoomIn")}
+ onZoomOut={() => onCommand("relationMapResetZoomOut")}
+ onReset={() => onCommand("relationMapResetPanZoom")}
/>
</OverlayControlGroup>
);