Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): replace the map's own corner bar with one of Trilium's

Elian Doran9d538cf4ba33
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9c277c934a..f63d974bad 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3565,7 +3565,12 @@
"tags-placeholder": "Type a tag and press Enter",
"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"
+ "remove-tag": "Remove this tag",
+ "zoom-in": "Zoom in",
+ "zoom-out": "Zoom out",
+ "center-map": "Center the map",
+ "fullscreen": "Fullscreen",
+ "exit-fullscreen": "Exit fullscreen"
},
"llm": {
"disabled_placeholder": "AI features are turned off. Enable them to configure providers and MCP.",
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.css b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.css
new file mode 100644
index 0000000000..7f6fa633c4
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.css
@@ -0,0 +1,34 @@
+/*
+ * The bar is dressed as the node panel standing above it is (see NodePanel.css): the same surface,
+ * the same border and the same blur, so that the two read as one piece of furniture in that corner
+ * rather than as two things that happen to be there. Where they stand and how much room the one
+ * leaves the other is settled between them in MindMap.css.
+ */
+.mind-map-container .mind-map-toolbar {
+ position: absolute;
+ bottom: var(--mind-map-inset-bottom);
+ inset-inline-end: var(--mind-map-inset);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px;
+ background: var(--menu-background-color);
+ color: var(--menu-text-color);
+ border: 1px solid var(--dropdown-border-color);
+ border-radius: 8px;
+ box-shadow: 0 2px 8px #0003;
+ backdrop-filter: blur(10px);
+}
+
+/* The buttons are on the bar's own surface rather than on the shell's, so they take their color
+ from it — as the ones inside a menu do. */
+.mind-map-container .mind-map-toolbar .tn-tool-button {
+ color: inherit;
+}
+
+/* A step that would carry the map past the scale it is allowed does nothing (see viewport.ts), and
+ the button for it says as much rather than merely failing to answer. */
+.mind-map-container .mind-map-toolbar .tn-tool-button:disabled {
+ opacity: .4;
+ pointer-events: none;
+}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx
new file mode 100644
index 0000000000..cb7143e5d8
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.spec.tsx
@@ -0,0 +1,169 @@
+import type { MindElixirInstance } from "mind-elixir";
+import { act } from "preact/test-utils";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+import MapToolbar from "./MapToolbar";
+
+/**
+ * A stand-in for the Mind Elixir instance exposing only what the toolbar touches: the scale and its
+ * range, the element that goes fullscreen, the map's own transform, and the ways it is moved.
+ */
+function buildMind({ scaleVal = 1 } = {}) {
+ const el = document.createElement("div");
+ el.requestFullscreen = vi.fn(async () => {});
+ document.body.appendChild(el);
+
+ const listeners = new Map<string, ((...args: unknown[]) => void)[]>();
+ const scale = vi.fn((value: number) => {
+ mind.scaleVal = value;
+ for (const listener of listeners.get("scale") ?? []) listener(value);
+ });
+
+ const mind = {
+ el,
+ container: { getBoundingClientRect: () => ({ width: 800, height: 600 }) },
+ map: { style: { transform: "translate3d(0px, 0px, 0) scale(1)" } },
+ scaleVal,
+ scaleSensitivity: 0.1,
+ scaleMin: 0.2,
+ scaleMax: 1.4,
+ scale,
+ toCenter: vi.fn(),
+ move: vi.fn(),
+ bus: {
+ addListener: (type: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(type, [ ...(listeners.get(type) ?? []), listener ]);
+ },
+ removeListener: (type: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(type, (listeners.get(type) ?? []).filter((held) => held !== listener));
+ }
+ }
+ } as unknown as MindElixirInstance;
+
+ return mind;
+}
+
+/** The order the toolbar lays its buttons out in. */
+const ZOOM_IN = 0;
+const ZOOM_OUT = 1;
+const CENTER = 2;
+const FULLSCREEN = 3;
+
+/** Builds the bar and settles it, so that what it listens to is listened to before it is spoken to. */
+function renderToolbar(mind: MindElixirInstance) {
+ let container: HTMLElement | undefined;
+ act(() => { container = renderInto(<MapToolbar mind={mind} />); });
+ if (!container) throw new Error("the toolbar was not rendered");
+ return container;
+}
+
+function buttons(container: HTMLElement) {
+ return [ ...container.querySelectorAll<HTMLButtonElement>(".mind-map-toolbar button") ];
+}
+
+function press(container: HTMLElement, index: number) {
+ act(() => buttons(container)[index].click());
+}
+
+/** Puts the document in or out of fullscreen and tells whoever is listening, as the browser does. */
+function setFullscreenElement(element: Element | null) {
+ Object.defineProperty(document, "fullscreenElement", { value: element, configurable: true });
+ act(() => { document.dispatchEvent(new Event("fullscreenchange")); });
+}
+
+beforeEach(() => {
+ Object.defineProperty(document, "fullscreenElement", { value: null, configurable: true });
+ document.exitFullscreen = vi.fn(async () => {});
+});
+
+describe("MapToolbar", () => {
+ it("offers the four things the map's own bar did, in one row", () => {
+ const container = renderToolbar(buildMind());
+
+ expect(buttons(container)).toHaveLength(4);
+ expect(buttons(container)[CENTER].className).toContain("bx-current-location");
+ expect(buttons(container)[FULLSCREEN].className).toContain("bx-fullscreen");
+ });
+
+ it("zooms by one step of the map's own sensitivity, in either direction", () => {
+ const mind = buildMind();
+ const container = renderToolbar(mind);
+
+ press(container, ZOOM_IN);
+ expect(vi.mocked(mind.scale).mock.calls[0][0]).toBeCloseTo(1.1);
+
+ press(container, ZOOM_OUT);
+ expect(vi.mocked(mind.scale).mock.calls[1][0]).toBeCloseTo(1);
+ });
+
+ it("disables the step that would carry the map past the scale it is allowed", () => {
+ const mind = buildMind({ scaleVal: 1.35 });
+ const container = renderToolbar(mind);
+
+ expect(buttons(container)[ZOOM_IN].disabled).toBe(true);
+ expect(buttons(container)[ZOOM_OUT].disabled).toBe(false);
+ });
+
+ it("follows the scale as the map reports it, not only as the buttons set it", () => {
+ const mind = buildMind({ scaleVal: 1 });
+ const container = renderToolbar(mind);
+ expect(buttons(container)[ZOOM_IN].disabled).toBe(false);
+
+ // As the wheel or a fit of the map would.
+ act(() => mind.scale(1.4));
+
+ expect(buttons(container)[ZOOM_IN].disabled).toBe(true);
+ });
+
+ it("centres the map", () => {
+ const mind = buildMind();
+ const container = renderToolbar(mind);
+
+ press(container, CENTER);
+
+ expect(mind.toCenter).toHaveBeenCalled();
+ });
+
+ it("gives the map the screen and takes it back, saying which it is offering", () => {
+ const mind = buildMind();
+ const container = renderToolbar(mind);
+
+ press(container, FULLSCREEN);
+ expect(mind.el.requestFullscreen).toHaveBeenCalled();
+
+ setFullscreenElement(mind.el);
+ expect(buttons(container)[FULLSCREEN].className).toContain("bx-exit-fullscreen");
+
+ press(container, FULLSCREEN);
+ expect(document.exitFullscreen).toHaveBeenCalled();
+ });
+
+ it("puts back what was in the middle of the view once the screen has changed size", () => {
+ const mind = buildMind();
+ const container = renderToolbar(mind);
+
+ press(container, FULLSCREEN);
+ // The middle of the map was 400/300 from its origin; the screen it lands on is larger.
+ mind.container.getBoundingClientRect = () => ({ width: 1920, height: 1080 }) as DOMRect;
+ setFullscreenElement(mind.el);
+
+ expect(mind.move).toHaveBeenCalledWith((1920 - 800) / 2, (1080 - 600) / 2);
+ });
+
+ it("leaves the map alone on a change of screen it was not asked for", () => {
+ const mind = buildMind();
+ const container = renderToolbar(mind);
+
+ press(container, FULLSCREEN);
+ setFullscreenElement(mind.el);
+ vi.mocked(mind.move).mockClear();
+
+ // Left by pressing Escape rather than the button, so there is no point to put back — as
+ // there was none in the map's own bar.
+ setFullscreenElement(null);
+
+ expect(mind.move).not.toHaveBeenCalled();
+ expect(buttons(container)[FULLSCREEN].className).toContain("bx-fullscreen");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx
new file mode 100644
index 0000000000..460626c30a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx
@@ -0,0 +1,137 @@
+import "./MapToolbar.css";
+
+import type { MindElixirInstance } from "mind-elixir";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import ActionButton, { type ActionButtonProps } from "../../react/ActionButton";
+import { centerMapOn, type MapPoint, readMapCenter, stepZoom } from "./viewport";
+
+interface MapToolbarProps {
+ mind: MindElixirInstance;
+}
+
+/**
+ * The bar standing in the bottom corner of a mind map: the scale the map is drawn at, where it
+ * stands, and how much of the screen it is given.
+ *
+ * Mind Elixir puts a bar of its own in that corner, which is hidden (see MindMap.css). It is the one
+ * piece of furniture the library lays over the map, and it was dressed in neither Trilium's buttons
+ * nor Trilium's colors — it kept its own icons and its own surface next to the node panel above it.
+ * Everything it did is done here, over the same instance.
+ */
+export default function MapToolbar({ mind }: MapToolbarProps) {
+ const scale = useMapScale(mind);
+ const [ isFullscreen, toggleFullscreen ] = useMapFullscreen(mind);
+
+ const limits = { sensitivity: mind.scaleSensitivity, min: mind.scaleMin, max: mind.scaleMax };
+ const zoomedIn = stepZoom(scale, 1, limits);
+ const zoomedOut = stepZoom(scale, -1, limits);
+
+ return (
+ <div
+ className="mind-map-toolbar"
+ /* Keep interactions inside the bar from reaching the map underneath, which would
+ otherwise take a press on a button for the start of a drag or a selection. */
+ onMouseDown={(e) => e.stopPropagation()}
+ >
+ <ToolbarButton
+ icon="bx bx-zoom-in"
+ text={t("mind-map.zoom-in")}
+ disabled={zoomedIn === null}
+ onClick={() => zoomedIn !== null && mind.scale(zoomedIn)}
+ />
+
+ <ToolbarButton
+ icon="bx bx-zoom-out"
+ text={t("mind-map.zoom-out")}
+ disabled={zoomedOut === null}
+ onClick={() => zoomedOut !== null && mind.scale(zoomedOut)}
+ />
+
+ <ToolbarButton
+ icon="bx bx-current-location"
+ text={t("mind-map.center-map")}
+ onClick={() => mind.toCenter()}
+ />
+
+ <ToolbarButton
+ icon={isFullscreen ? "bx bx-exit-fullscreen" : "bx bx-fullscreen"}
+ text={isFullscreen ? t("mind-map.exit-fullscreen") : t("mind-map.fullscreen")}
+ onClick={toggleFullscreen}
+ />
+ </div>
+ );
+}
+
+/** Dressed as the buttons floating over a rendered diagram are (see SplitEditor's `PreviewButton`). */
+function ToolbarButton(props: Omit<ActionButtonProps, "titlePosition">) {
+ return <ActionButton
+ {...props}
+ className="tn-tool-button"
+ noIconActionClass
+ // The bar sits at the foot of the map, where a tooltip under it would fall off the edge.
+ titlePosition="top"
+ />;
+}
+
+/**
+ * The scale the map is drawn at, followed as it changes — by these buttons, by the wheel, or by the
+ * map fitting itself. What it is read for is whether there is any room left to zoom, which is what
+ * leaves a button that would do nothing disabled instead.
+ */
+function useMapScale(mind: MindElixirInstance) {
+ const [ scale, setScale ] = useState(mind.scaleVal);
+
+ useEffect(() => {
+ // The map may have been moved between being built and being listened to.
+ setScale(mind.scaleVal);
+
+ mind.bus.addListener("scale", setScale);
+ return () => mind.bus.removeListener("scale", setScale);
+ }, [ mind ]);
+
+ return scale;
+}
+
+/**
+ * Whether the map has the screen to itself, and the way to give it or take it back.
+ *
+ * What was in the middle of the view is put back in the middle of the new one: the map is drawn at
+ * the same scale on a canvas of a different size, and would otherwise keep the offset it had and
+ * slide off towards the corner it is pinned to. The point is taken as the change is asked for and
+ * spent when it lands — a change is only reported once the view has already been resized, leaving
+ * nothing to measure by then. A screen left by pressing Escape is therefore not followed, as it was
+ * not by the bar this one replaces.
+ */
+function useMapFullscreen(mind: MindElixirInstance): [ boolean, () => void ] {
+ const [ isFullscreen, setFullscreen ] = useState(() => document.fullscreenElement === mind.el);
+ const center = useRef<MapPoint | null>(null);
+
+ useEffect(() => {
+ const onFullscreenChange = () => {
+ setFullscreen(document.fullscreenElement === mind.el);
+
+ const taken = center.current;
+ center.current = null;
+ if (taken) centerMapOn(mind, taken);
+ };
+
+ document.addEventListener("fullscreenchange", onFullscreenChange);
+ return () => document.removeEventListener("fullscreenchange", onFullscreenChange);
+ }, [ mind ]);
+
+ const toggle = useCallback(() => {
+ center.current = readMapCenter(mind);
+
+ const changed = document.fullscreenElement ? document.exitFullscreen() : mind.el.requestFullscreen();
+ // A refused request leaves the view the size it was, so there is nothing to put back — and
+ // holding on to the point would move the map on whatever change came next.
+ changed?.catch((e) => {
+ center.current = null;
+ console.warn("Could not change the mind map's fullscreen state:", e);
+ });
+ }, [ mind ]);
+
+ return [ isFullscreen, toggle ];
+}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MindMap.css b/apps/client/src/widgets/type_widgets/mind_map/MindMap.css
index 0fb3a1a8ab..3f701b8e89 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/MindMap.css
+++ b/apps/client/src/widgets/type_widgets/mind_map/MindMap.css
@@ -7,6 +7,30 @@
height: 100%;
}
+/*
+ * The corner the map's own furniture stands in: the toolbar at the foot of it (see MapToolbar.css)
+ * and the node panel above (see NodePanel.css). Both are placed from here, so that the two agree on
+ * where the one ends and the other may begin — including in fullscreen, where the edges of the map
+ * are the edges of the screen and part of them may not be the screen's to draw on.
+ */
+.mind-map-container {
+ --mind-map-inset: 20px;
+ --mind-map-inset-top: var(--mind-map-inset);
+ --mind-map-inset-bottom: var(--mind-map-inset);
+ /* What a row of icon buttons, its padding and its border come out at — the room the panel above
+ the toolbar has to leave for it. */
+ --mind-map-toolbar-height: 42px;
+}
+
+/*
+ * Replaced by our own, which stands in the same corner and does the same four things (see
+ * MapToolbar.tsx). Hidden rather than left out: the map offers no way to drop the one bar without
+ * the other, and the bar of direction buttons in the opposite corner is still the library's.
+ */
+.mind-map-container .mind-elixir-toolbar.rb {
+ display: none;
+}
+
/* Hosts our own floating UI on top of the map, without interfering with the DOM managed by Mind Elixir. */
.mind-map-container .mind-map-overlay {
position: absolute;
@@ -59,12 +83,13 @@
display: none;
}
+/* On a screen of its own, the map keeps clear of whatever the screen keeps for itself. */
.mind-map-container:fullscreen {
- .rb {
- bottom: calc(20px + env(safe-area-inset-bottom));
- }
+ --mind-map-inset-top: calc(var(--mind-map-inset) + env(safe-area-inset-top));
+ --mind-map-inset-bottom: calc(var(--mind-map-inset) + env(safe-area-inset-bottom));
+ /* The library's own bar of direction buttons, which its stylesheet pins to the top corner. */
.lt {
- top: calc(20px + env(safe-area-inset-top));
+ top: var(--mind-map-inset-top);
}
}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx b/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx
index b4b372a18f..003438cbff 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/MindMap.tsx
@@ -18,6 +18,7 @@ import { TypeWidgetProps } from "../type_widget";
import { renderMindMapPreviewSvg } from "./export";
import { renderIconClasses } from "./icons";
import { renderNodeLinks } from "./links";
+import MapToolbar from "./MapToolbar";
import NodePanel from "./NodePanel";
/**
@@ -67,8 +68,13 @@ function sanitizeMindMapNode(value: unknown): void {
interface MindElixirProps {
apiRef?: RefObject<MindElixirInstance>;
- /** Rendered in an overlay on top of the map, outside of the DOM managed by Mind Elixir. */
- children?: ComponentChildren;
+ /**
+ * Rendered in an overlay on top of the map, outside of the DOM managed by Mind Elixir, and given
+ * the instance it stands over. Asked for rather than handed in, the instance being built after
+ * the first render and again whenever the map has to be rebuilt — what is drawn over it follows
+ * onto the new one instead of holding a reference to the one it was born with.
+ */
+ children?: (mind: MindElixirInstance) => ComponentChildren;
containerProps?: Omit<HTMLAttributes<HTMLDivElement>, "ref">;
containerRef?: RefObject<HTMLDivElement>;
editable: boolean;
@@ -190,11 +196,15 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {
onKeyDown
}}
>
- {/* Offered on a read-only map as well: Mind Elixir still selects a node there, and the
- panel then holds the memo alone — the one thing a node carries that the map itself
- never draws, and which would otherwise be out of reach (see NodePanel). */}
- {selectedNodes.length > 0 && apiRef.current &&
- <NodePanel mind={apiRef.current} noteId={note.noteId} nodes={selectedNodes} readOnly={isReadOnly} />}
+ {(mind) => <>
+ <MapToolbar mind={mind} />
+
+ {/* Offered on a read-only map as well: Mind Elixir still selects a node there, and
+ the panel then holds the memo alone — the one thing a node carries that the map
+ itself never draws, and which would otherwise be out of reach (see NodePanel). */}
+ {selectedNodes.length > 0 &&
+ <NodePanel mind={mind} noteId={note.noteId} nodes={selectedNodes} readOnly={isReadOnly} />}
+ </>}
</MindElixir>
);
}
@@ -337,7 +347,9 @@ function MindElixir({ children, containerRef: externalContainerRef, containerPro
return (
<>
<div ref={containerRef} {...containerProps} />
- {createPortal(<>{children}</>, overlayEl)}
+ {/* Read afresh on every render, which follows every build of the instance (see
+ `instanceVersion` above); until the first one there is nothing to draw over. */}
+ {createPortal(<>{apiRef.current && children?.(apiRef.current)}</>, overlayEl)}
</>
);
}
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
index 6773e32e39..32fde6b5ae 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.css
@@ -2,17 +2,16 @@
/* Below the floating buttons of the note, which stand in this corner. */
--node-panel-top: 60px;
/*
- * And above the map's own buttons, which stand in the corner under it: zooming, centring and
- * going fullscreen sit 20px up from the foot of the map and are 41px tall, in a row inset as far
- * from the edge as the panel is. The panel is drawn over them, so a panel that reached the foot
- * of the map would take the top half of every one of those buttons with it — the clicks along
- * with the sight of them. What is kept is that 61px and a gap over it.
+ * And above the map's toolbar, which stands in the corner under it, inset as far from the edge
+ * as the panel is (see MapToolbar.css). The panel is drawn over it, so a panel that reached the
+ * foot of the map would take the top half of every one of those buttons with it — the clicks
+ * along with the sight of them. What is kept is the bar's own room and as much again over it.
*/
- --node-panel-foot: 80px;
+ --node-panel-foot: calc(var(--mind-map-inset-bottom) + var(--mind-map-toolbar-height) + var(--mind-map-inset));
position: absolute;
top: var(--node-panel-top);
- inset-inline-end: 20px;
+ inset-inline-end: var(--mind-map-inset);
width: 240px;
max-height: calc(100% - var(--node-panel-top) - var(--node-panel-foot));
/* The tab strip is the panel's header and stays put; only the tab under it scrolls. */
@@ -28,11 +27,11 @@
backdrop-filter: blur(10px);
}
-/* Both sets of buttons move with the safe areas in fullscreen (see MindMap.css), and the room kept
- clear of them moves with them. */
+/* On a screen of its own the panel starts where the map does, there being no note buttons over it
+ there. The room it leaves for the toolbar follows the foot of the map on its own, both being
+ reckoned from the same insets (see MindMap.css). */
.mind-map-container:fullscreen .mind-map-node-panel {
- --node-panel-top: calc(20px + env(safe-area-inset-top));
- --node-panel-foot: calc(80px + env(safe-area-inset-bottom));
+ --node-panel-top: var(--mind-map-inset-top);
}
/*
diff --git a/apps/client/src/widgets/type_widgets/mind_map/viewport.spec.ts b/apps/client/src/widgets/type_widgets/mind_map/viewport.spec.ts
new file mode 100644
index 0000000000..cb00f5fe1b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mind_map/viewport.spec.ts
@@ -0,0 +1,99 @@
+import type { MindElixirInstance } from "mind-elixir";
+import { describe, expect, it, vi } from "vitest";
+
+import { centerMapOn, parseMapTranslation, readMapCenter, stepZoom } from "./viewport";
+
+const LIMITS = { sensitivity: 0.1, min: 0.2, max: 1.4 };
+
+/**
+ * A stand-in for the Mind Elixir instance exposing only what the viewport helpers touch: the size of
+ * the view, the transform the map is drawn with, the scale, and the way it is moved.
+ */
+function buildMind({ width = 800, height = 600, transform = "", scaleVal = 1 } = {}) {
+ const move = vi.fn();
+ const mind = {
+ container: { getBoundingClientRect: () => ({ width, height }) },
+ map: { style: { transform } },
+ scaleVal,
+ move
+ } as unknown as MindElixirInstance;
+
+ return { mind, move };
+}
+
+describe("stepZoom", () => {
+ it("steps by the sensitivity in either direction", () => {
+ expect(stepZoom(1, 1, LIMITS)).toBeCloseTo(1.1);
+ expect(stepZoom(1, -1, LIMITS)).toBeCloseTo(0.9);
+ });
+
+ it("refuses the step that would leave the range, and only at the end being moved towards", () => {
+ expect(stepZoom(1.35, 1, LIMITS)).toBeNull();
+ expect(stepZoom(1.35, -1, LIMITS)).toBeCloseTo(1.25);
+ expect(stepZoom(0.25, -1, LIMITS)).toBeNull();
+ expect(stepZoom(0.25, 1, LIMITS)).toBeCloseTo(0.35);
+ });
+
+ it("still zooms a map drawn smaller than the minimum, as fitting one to a small pane leaves it", () => {
+ expect(stepZoom(0.1, 1, LIMITS)).toBeCloseTo(0.2);
+ expect(stepZoom(0.1, -1, LIMITS)).toBeNull();
+ });
+
+ it("allows the step that lands on the end of the range", () => {
+ const limits = { sensitivity: 0.5, min: 0.5, max: 1.5 };
+ expect(stepZoom(1, 1, limits)).toBe(1.5);
+ expect(stepZoom(1, -1, limits)).toBe(0.5);
+ });
+});
+
+describe("parseMapTranslation", () => {
+ it("reads the offset Mind Elixir writes, whether or not a scale follows it", () => {
+ expect(parseMapTranslation("translate3d(120px, -40px, 0) scale(0.8)")).toEqual({ x: 120, y: -40 });
+ expect(parseMapTranslation("translate3d(1.5px, 2.5px, 0)")).toEqual({ x: 1.5, y: 2.5 });
+ });
+
+ it("takes a map that has not been placed yet to sit at the origin", () => {
+ expect(parseMapTranslation("")).toEqual({ x: 0, y: 0 });
+ expect(parseMapTranslation("none")).toEqual({ x: 0, y: 0 });
+ expect(parseMapTranslation("scale(2)")).toEqual({ x: 0, y: 0 });
+ });
+});
+
+describe("readMapCenter / centerMapOn", () => {
+ it("reads the point of the map lying in the middle of the view, in the map's own coordinates", () => {
+ const { mind } = buildMind({
+ width: 800, height: 600,
+ transform: "translate3d(100px, 50px, 0) scale(2)",
+ scaleVal: 2
+ });
+
+ // The middle of the view is 300px right of and 250px below the map's origin on screen,
+ // which the map draws at half that in its own coordinates.
+ expect(readMapCenter(mind)).toEqual({ x: 150, y: 125 });
+ });
+
+ it("moves by whatever it takes to bring a point back to the middle", () => {
+ const { mind, move } = buildMind({
+ width: 400, height: 300,
+ transform: "translate3d(0px, 0px, 0) scale(1)"
+ });
+
+ centerMapOn(mind, { x: 50, y: 25 });
+
+ expect(move).toHaveBeenCalledWith(150, 125);
+ });
+
+ it("puts back what it read once the view has changed size", () => {
+ const transform = "translate3d(100px, 50px, 0) scale(1)";
+ const { mind: small } = buildMind({ width: 800, height: 600, transform });
+ const center = readMapCenter(small);
+
+ // The same map, drawn at the same offset and scale, on a view the size of a screen.
+ const { mind: large, move } = buildMind({ width: 1920, height: 1080, transform });
+ centerMapOn(large, center);
+
+ const [ dx, dy ] = move.mock.calls[0];
+ expect(dx).toBeCloseTo((1920 - 800) / 2);
+ expect(dy).toBeCloseTo((1080 - 600) / 2);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/mind_map/viewport.ts b/apps/client/src/widgets/type_widgets/mind_map/viewport.ts
new file mode 100644
index 0000000000..45a3cad351
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mind_map/viewport.ts
@@ -0,0 +1,80 @@
+import type { MindElixirInstance } from "mind-elixir";
+
+/** A point of the map, in the map's own coordinates — the ones a node is laid out in. */
+export interface MapPoint {
+ x: number;
+ y: number;
+}
+
+/** What one step of the zoom buttons is worth, and how far they are allowed to carry the map. */
+export interface ZoomLimits {
+ /** How much the scale changes by in one step. */
+ sensitivity: number;
+ min: number;
+ max: number;
+}
+
+/**
+ * The scale the map takes on when zoomed one step in (`1`) or out (`-1`), or `null` where the step
+ * would carry it past the end of the range it is allowed.
+ *
+ * Mind Elixir refuses such a step silently, so the same reckoning is done here to leave the button
+ * for it disabled rather than idle. Only the end being moved towards is looked at, as the library
+ * does: a map already drawn smaller than its own minimum — which is what fitting it to a small pane
+ * leaves — can still be zoomed in from there.
+ */
+export function stepZoom(scale: number, direction: 1 | -1, { sensitivity, min, max }: ZoomLimits): number | null {
+ const stepped = scale + direction * sensitivity;
+ if (direction < 0 ? stepped < min : stepped > max) return null;
+ return stepped;
+}
+
+/**
+ * The point of the map that lies in the middle of the view.
+ *
+ * Read from the translation the map is drawn with rather than from where it lands on screen, that
+ * being what {@link centerMapOn} writes back through and what Mind Elixir itself reckons in.
+ */
+export function readMapCenter(mind: MindElixirInstance): MapPoint {
+ const { width, height } = mind.container.getBoundingClientRect();
+ const { x, y } = parseMapTranslation(mind.map.style.transform);
+
+ return {
+ x: (width / 2 - x) / mind.scaleVal,
+ y: (height / 2 - y) / mind.scaleVal
+ };
+}
+
+/**
+ * Moves the map so that the given point of it lies in the middle of the view, at whatever scale the
+ * map is currently drawn at.
+ *
+ * Paired with {@link readMapCenter} across a change of the size of the view — going fullscreen and
+ * coming back — where the map would otherwise keep the offset it had and slide off towards the
+ * corner it is pinned to.
+ */
+export function centerMapOn(mind: MindElixirInstance, center: MapPoint) {
+ const { width, height } = mind.container.getBoundingClientRect();
+ const { x, y } = parseMapTranslation(mind.map.style.transform);
+
+ mind.move(
+ width / 2 - center.x * mind.scaleVal - x,
+ height / 2 - center.y * mind.scaleVal - y
+ );
+}
+
+/**
+ * The offset a map is drawn at, taken from the `translate3d` Mind Elixir writes onto it — the one
+ * form it ever writes, and the one its own `move` reads back. A map that has not been placed yet
+ * carries no transform at all, which is the origin.
+ */
+export function parseMapTranslation(transform: string): MapPoint {
+ const match = /translate3d\(([^,]+),\s*([^,)]+)/.exec(transform);
+ const x = Number.parseFloat(match?.[1] ?? "");
+ const y = Number.parseFloat(match?.[2] ?? "");
+
+ return {
+ x: Number.isFinite(x) ? x : 0,
+ y: Number.isFinite(y) ? y : 0
+ };
+}