Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client/overlay): put the relation map's zoom on the control group

Elian Doran9997969e10a5
diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.css b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.css
new file mode 100644
index 0000000000..6df988cdee
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.css
@@ -0,0 +1,6 @@
+.relation-map-wrapper .relation-map-toolbar {
+ position: absolute;
+ inset-inline-end: var(--overlay-button-inset, 10px);
+ bottom: var(--overlay-button-inset, 10px);
+ z-index: 10;
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.spec.tsx
new file mode 100644
index 0000000000..629b17bc07
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.spec.tsx
@@ -0,0 +1,114 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// The bootstrap tooltip the buttons wear needs real layout, which happy-dom hasn't.
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useStaticTooltip: () => {}
+}));
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+import MapToolbar, { type MapCommand } from "./MapToolbar";
+
+let container: HTMLDivElement;
+
+afterEach(() => {
+ act(() => render(null, container));
+ container.remove();
+});
+
+describe("MapToolbar", () => {
+ it("says the scale the map is drawn at, following it as the map is moved", () => {
+ const map = fakeMap();
+ mount(map);
+
+ expect(readout().textContent).toBe("100%");
+
+ act(() => map.moveTo(2.5));
+ expect(readout().textContent).toBe("250%");
+
+ // A pan leaves the scale where it was, so the readout says the same thing.
+ act(() => map.moveTo(2.5));
+ expect(readout().textContent).toBe("250%");
+ });
+
+ it("leaves a step with no room left to it disabled", () => {
+ const map = fakeMap();
+ mount(map);
+
+ expect([ zoomOut().disabled, zoomIn().disabled ]).toEqual([ false, false ]);
+
+ act(() => map.moveTo(MIN_ZOOM));
+ expect([ zoomOut().disabled, zoomIn().disabled ]).toEqual([ true, false ]);
+
+ act(() => map.moveTo(MAX_ZOOM));
+ expect([ zoomOut().disabled, zoomIn().disabled ]).toEqual([ false, true ]);
+ });
+
+ it("asks for what each button stands for rather than moving the map itself", () => {
+ const commands: MapCommand[] = [];
+ const map = fakeMap();
+ mount(map, (command) => commands.push(command));
+
+ act(() => zoomOut().click());
+ act(() => readout().click());
+ act(() => zoomIn().click());
+
+ expect(commands).toEqual([ "relationMapResetZoomOut", "relationMapResetPanZoom", "relationMapResetZoomIn" ]);
+ expect(map.transformListeners()).toBe(1);
+ });
+
+ it("stands aside while there is no map to read, and stops listening to one that is torn down", () => {
+ const map = fakeMap();
+ mount(undefined);
+ expect(container.querySelector(".relation-map-toolbar")).toBeNull();
+
+ mount(map);
+ expect(map.transformListeners()).toBe(1);
+
+ act(() => render(null, container));
+ expect(map.transformListeners()).toBe(0);
+ });
+});
+
+const MIN_ZOOM = 0.3;
+const MAX_ZOOM = 2;
+
+/** A stand-in for panzoom: a scale that can be moved, told to whoever asked to be told. */
+function fakeMap() {
+ let scale = 1;
+ const listeners = new Set<() => void>();
+
+ return {
+ getTransform: () => ({ x: 0, y: 0, scale }),
+ getMinZoom: () => MIN_ZOOM,
+ getMaxZoom: () => MAX_ZOOM,
+ on: (_event: string, handler: () => void) => listeners.add(handler),
+ off: (_event: string, handler: () => void) => listeners.delete(handler),
+ /** Reports a move, as the library does for a pan as well as for a zoom. */
+ moveTo: (newScale: number) => {
+ scale = newScale;
+ for (const listener of listeners) listener();
+ },
+ transformListeners: () => listeners.size
+ };
+}
+
+function mount(map: ReturnType<typeof fakeMap> | undefined, onCommand: (command: MapCommand) => void = () => {}) {
+ container ??= document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(
+ <MapToolbar panZoom={map as unknown as Parameters<typeof MapToolbar>[0]["panZoom"]} onCommand={onCommand} />,
+ container
+ ));
+ return container;
+}
+
+function buttons() {
+ return container.querySelectorAll<HTMLButtonElement>(".relation-map-toolbar button");
+}
+
+const zoomOut = () => buttons()[0];
+const readout = () => buttons()[1];
+const zoomIn = () => buttons()[2];
diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx
new file mode 100644
index 0000000000..2fa0ecd1a7
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx
@@ -0,0 +1,84 @@
+import "./MapToolbar.css";
+
+import type { PanZoom } from "panzoom";
+import { useEffect, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import OverlayControlGroup, { OverlayControlButton } 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";
+
+interface MapToolbarProps {
+ /** The map the scale is read from, or `undefined` while there is none yet. */
+ panZoom: PanZoom | undefined;
+ onCommand: (command: MapCommand) => void;
+}
+
+/**
+ * The controls standing in the corner of a relation map: how close in it is drawn, and the way back
+ * to where it started.
+ *
+ * They stand on the {@link OverlayControlGroup} the image viewer's zoom buttons stand on (see
+ * {@link ImageViewer}), as the other two maps' controls and the diagram preview's do, in place of the
+ * three floating buttons that were here before. The readout between the steps says the scale the way
+ * those do — a hundred being the map drawn at its own size — and pressed, takes the map back there
+ * and to the corner it started in, which is what the button wearing a crop mark did.
+ *
+ * What the three do is asked for as commands rather than done here, the same commands the floating
+ * buttons above the map ask for (`RelationMapButtons` in FloatingButtonsDefinitions.tsx): the map is
+ * driven from two places, and how far a step goes is settled in the one place that answers them. The
+ * map itself is only read from — for the scale to show, and for the ends of its range, which is what
+ * leaves a step with nothing left to give disabled. Absent until there is a map to read.
+ */
+export default function MapToolbar({ panZoom, onCommand }: MapToolbarProps) {
+ const scale = useMapScale(panZoom);
+
+ if (!panZoom) return null;
+
+ return (
+ <OverlayControlGroup className="relation-map-toolbar">
+ <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")}
+ />
+ </OverlayControlGroup>
+ );
+}
+
+/**
+ * The scale the map is drawn at, followed as it changes — by these buttons, by the wheel, or by the
+ * saved view being restored.
+ *
+ * Read off the map's own transform, which it reports as it is panned as well as zoomed: a pan leaves
+ * the scale where it was, and a state set to the number it already holds costs nothing.
+ */
+function useMapScale(panZoom: PanZoom | undefined) {
+ const [ scale, setScale ] = useState(1);
+
+ useEffect(() => {
+ if (!panZoom) return;
+
+ const report = () => setScale(panZoom.getTransform().scale);
+ // The map may have been moved between being built and being listened to.
+ report();
+
+ panZoom.on("transform", report);
+ return () => panZoom.off("transform", report);
+ }, [ panZoom ]);
+
+ return scale;
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
index 01eebf53a0..10cdcd0399 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
@@ -2,7 +2,10 @@ import "./RelationMap.css";
import { CreateChildrenResponse, RelationMapPostResponse } from "@triliumnext/commons";
import { jsPlumbInstance, OnConnectionBindInfo } from "jsplumb";
-import panzoom, { PanZoomOptions } from "panzoom";
+// The library's own types rather than the hand-written `PanZoom` in types.d.ts, which stops at the
+// handful of calls the map made when it was written and knows nothing of the rest — the ends of the
+// zoom range, or unsubscribing from a report.
+import panzoom, { PanZoom, PanZoomOptions } from "panzoom";
import { RefObject } from "preact";
import { HTMLProps } from "preact/compat";
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
@@ -13,12 +16,12 @@ import { isExperimentalFeatureEnabled } from "../../../services/experimental_fea
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
-import ActionButton from "../../react/ActionButton";
import { useEditorSpacedUpdate, useTriliumEvent, useTriliumEvents } from "../../react/hooks";
import { TypeWidgetProps } from "../type_widget";
import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry, RelationType } from "./api";
import { buildRelationContextMenuHandler } from "./context_menu";
import { JsPlumb } from "./jsplumb";
+import MapToolbar from "./MapToolbar";
import { NoteBox } from "./NoteBox";
import setupOverlays, { uniDirectionalOverlays } from "./overlays";
import { getMousePosition, getZoom, idToNoteId, noteIdToId, promptForRelationName } from "./utils";
@@ -118,7 +121,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
const connectionCallback = useRelationCreation({ mapApiRef, jsPlumbApiRef: pbApiRef });
- usePanZoom({
+ const panZoom = usePanZoom({
ntxId,
containerRef,
options: {
@@ -163,36 +166,20 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
</JsPlumb>
{isNewLayout && (
- <div className="btn-group btn-group-sm content-floating-buttons bottom-right">
- <ActionButton
- icon="bx bx-zoom-in"
- text={t("relation_map_buttons.zoom_in_title")}
- onClick={() => parentComponent?.triggerEvent("relationMapResetZoomIn", { ntxId })}
- className="tn-tool-button"
- noIconActionClass
- />
-
- <ActionButton
- icon="bx bx-zoom-out"
- text={t("relation_map_buttons.zoom_out_title")}
- onClick={() => parentComponent?.triggerEvent("relationMapResetZoomOut", { ntxId })}
- className="tn-tool-button"
- noIconActionClass
- />
-
- <ActionButton
- icon="bx bx-crop"
- text={t("relation_map_buttons.reset_pan_zoom_title")}
- onClick={() => parentComponent?.triggerEvent("relationMapResetPanZoom", { ntxId })}
- className="tn-tool-button"
- noIconActionClass
- />
- </div>
+ <MapToolbar
+ panZoom={panZoom}
+ onCommand={(command) => parentComponent?.triggerEvent(command, { ntxId })}
+ />
)}
</div>
);
}
+/**
+ * Sets the map up to be panned and zoomed, answers the commands that drive it, and hands the
+ * instance back so that the controls over the map can read it — as state rather than as the ref the
+ * commands are answered from, so that they are drawn afresh when the map is rebuilt under a new one.
+ */
function usePanZoom({ ntxId, containerRef, options, transformData, onTransform }: {
ntxId: string | null | undefined;
containerRef: RefObject<HTMLDivElement>;
@@ -201,11 +188,13 @@ function usePanZoom({ ntxId, containerRef, options, transformData, onTransform }
onTransform: (pzInstance: PanZoom) => void
}) {
const apiRef = useRef<PanZoom>(null);
+ const [ panZoom, setPanZoom ] = useState<PanZoom>();
useEffect(() => {
if (!containerRef.current) return;
const pzInstance = panzoom(containerRef.current, options);
apiRef.current = pzInstance;
+ setPanZoom(pzInstance);
if (transformData) {
pzInstance.zoomTo(0, 0, transformData.scale);
@@ -216,10 +205,13 @@ function usePanZoom({ ntxId, containerRef, options, transformData, onTransform }
}
if (onTransform) {
- apiRef.current!.on("transform", () => onTransform(pzInstance));
+ pzInstance.on("transform", () => onTransform(pzInstance));
}
- return () => pzInstance.dispose();
+ return () => {
+ setPanZoom(undefined);
+ pzInstance.dispose();
+ };
}, [ containerRef, onTransform ]);
useTriliumEvents([ "relationMapResetPanZoom", "relationMapResetZoomIn", "relationMapResetZoomOut" ], ({ ntxId: eventNtxId }, eventName) => {
@@ -236,6 +228,8 @@ function usePanZoom({ ntxId, containerRef, options, transformData, onTransform }
pzInstance.zoomTo(0, 0, 0.8);
}
});
+
+ return panZoom;
}
async function useRelationData(noteId: string, mapData: MapData | undefined, mapApiRef: RefObject<RelationMapApi>, jsPlumbRef: RefObject<jsPlumbInstance>) {