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
refactor(relation_map): drive the toolbars with callbacks, not app events
Elian Doranf64e9dbca1e1
diff --git a/.claude/skills/building-client-ui/SKILL.md b/.claude/skills/building-client-ui/SKILL.mdindex e3f03ca410..8251709b2c 100644--- a/.claude/skills/building-client-ui/SKILL.md+++ b/.claude/skills/building-client-ui/SKILL.md@@ -147,7 +147,7 @@ Rules for `OverlayControlButton`, which cover every case seen so far:- **`active`/`disabled` are props**, not classes concatenated into `className`.- **Pass `overCanvas`** when the group stands over something that is dragged (a map), so a press on a button is not taken for the start of a drag.- **Where the group stands is the group's own**, via `placement` (`top`/`bottom` × `start`/`center`/`end`): it pins itself over the nearest positioned ancestor, and its tooltips open away from that edge. **Never write `position: absolute` plus insets at the call site.** What the caller does hand over, in that widget's CSS, is the room to keep from the edges (`--overlay-group-inset`, or the per-edge `--overlay-group-inset-top`/`-bottom`/`-start`/`-end` where one edge differs — a fullscreen map clearing a notch, which spells that inset `var(--safe-area-inset-top, env(safe-area-inset-top))`, never a bare `env()`, since Android leaves `env()` at `0`) and the `z-index`. `titlePosition` overrides the tooltip direction and is rarely right; only add a class to a *button* if a rule actually uses it.-- **Overlay controls exist in every layout.** Never gate a group on `isExperimentalFeatureEnabled("new-layout")`, and when an action moves onto a group, **delete its twin in `FloatingButtonsDefinitions.tsx`** rather than keeping both: that bar only renders in the old layout (`desktop_layout.tsx` mounts it with `!isNewLayout`), so a layout-gated group plus a floating fallback means two implementations of one button that drift. Keep the underlying app commands (e.g. `relationMapResetZoomIn`) even once the group is their only caller — note scripts can fire them via `api.triggerCommand`.+- **Overlay controls exist in every layout.** Never gate a group on `isExperimentalFeatureEnabled("new-layout")`, and when an action moves onto a group, **delete its twin in `FloatingButtonsDefinitions.tsx`** rather than keeping both: that bar only renders in the old layout (`desktop_layout.tsx` mounts it with `!isNewLayout`), so a layout-gated group plus a floating fallback means two implementations of one button that drift. A Preact view wires its own groups to callbacks — the relation map's toolbars call `useMapZoom` and `useNotePlacement` directly rather than going through app events.- Reuse shared labels from the `common` translation namespace (e.g. `common.fullscreen`) rather than adding a per-widget copy of a string the app already has.Worked examples to read before adding a new one: `apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx` (group + toolbar + fullscreen), `type_widgets/relation_map/MapToolbar.tsx`, `collections/geomap/MapToolbar.tsx`, `type_widgets/helpers/SvgSplitEditor.tsx`.diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 8e754b69e4..35f05071f0 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -581,11 +581,6 @@ type EventMappings = {};noteTypeMimeChanged: { noteId: string };zenModeChanged: { isEnabled: boolean };- relationMapCreateChildNote: { ntxId: string | null | undefined };- relationMapResetPanZoom: { ntxId: string | null | undefined };- relationMapResetZoomIn: { ntxId: string | null | undefined };- relationMapResetZoomOut: { ntxId: string | null | undefined };- relationMapFitToView: { ntxId: string | null | undefined };activeNoteChanged: {ntxId: string | null | undefined};showAddLinkDialog: AddLinkOpts;showContentEmbedDialog: ContentEmbedOpts;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.tsxindex ce7a0bb503..112adecd38 100644--- a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.spec.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.spec.tsx@@ -6,7 +6,7 @@ import { act } from "preact/test-utils";import { describe, expect, it, vi } from "vitest";import { renderInto } from "../../../test/render";-import MapToolbar, { EditToolbar, type MapCommand } from "./MapToolbar";+import MapToolbar, { EditToolbar } from "./MapToolbar";vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));@@ -30,7 +30,7 @@ describe("relation map MapToolbar", () => {expect([ zoomOut()?.disabled, zoomIn()?.disabled ]).toEqual([ false, true ]);});- it("asks for what each button stands for rather than moving the map itself", () => {+ it("calls the action of each button", () => {const { commands, readout, zoomIn, zoomOut, fit } = renderToolbar();act(() => zoomOut()?.click());@@ -38,7 +38,7 @@ describe("relation map MapToolbar", () => {act(() => zoomIn()?.click());act(() => fit()?.click());- expect(commands).toEqual([ "relationMapResetZoomOut", "relationMapResetPanZoom", "relationMapResetZoomIn", "relationMapFitToView" ]);+ expect(commands).toEqual([ "zoomOut", "reset", "zoomIn", "fit" ]);});});@@ -70,17 +70,18 @@ describe("relation map EditToolbar", () => {});});-/** Builds the camera group, holding on to what the buttons ask for. */+/** Builds the camera group, recording which action each button calls. */function renderToolbar() {- const commands: MapCommand[] = [];+ const commands: string[] = [];+ const actions = {+ zoomIn: () => commands.push("zoomIn"),+ zoomOut: () => commands.push("zoomOut"),+ reset: () => commands.push("reset"),+ fit: () => commands.push("fit")+ };let container: HTMLElement | undefined;const rerender = (zoom: Partial<Parameters<typeof MapToolbar>[0]["zoom"]> = {}) => act(() => {- container = renderInto(- <MapToolbar- zoom={{ scale: 1, canZoomIn: true, canZoomOut: true, ...zoom }}- onCommand={(command) => commands.push(command)}- />- );+ container = renderInto(<MapToolbar zoom={{ scale: 1, canZoomIn: true, canZoomOut: true, ...actions, ...zoom }} />);});rerender();if (!container) throw new Error("the toolbar was not rendered");diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsxindex ba531b6bd1..88ae2ec496 100644--- a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx@@ -3,13 +3,18 @@ import "./MapToolbar.css";import { t } from "../../../services/i18n";import OverlayControlGroup, { OverlayControlButton, ZoomControls } from "../../react/OverlayControlGroup";-/** What the buttons ask for, which is what the map itself answers (see `useMapZoom` in RelationMap.tsx). */-export type MapCommand = "relationMapResetZoomIn" | "relationMapResetZoomOut" | "relationMapResetPanZoom" | "relationMapFitToView";-interface MapToolbarProps {- /** The scale the map is drawn at, and whether each zoom step has room left. */- zoom: { scale: number; canZoomIn: boolean; canZoomOut: boolean };- onCommand: (command: MapCommand) => void;+ /** The map's scale, whether each zoom step has room left, and the actions of the buttons (see+ * `useMapZoom` in RelationMap.tsx). */+ zoom: {+ scale: number;+ canZoomIn: boolean;+ canZoomOut: boolean;+ zoomIn(): void;+ zoomOut(): void;+ reset(): void;+ fit(): void;+ };}/**@@ -22,26 +27,24 @@ interface MapToolbarProps {* 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 a script can- * trigger (`api.triggerCommand`), which is why they outlive the floating buttons that were the other- * caller. 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.+ * A step is disabled once the scale reaches the end of the map's zoom range, and the last button+ * fits all the notes into the view.*/-export default function MapToolbar({ zoom, onCommand }: MapToolbarProps) {+export default function MapToolbar({ zoom }: MapToolbarProps) {return (<OverlayControlGroup className="relation-map-toolbar" placement="bottom-end"><ZoomControlspercent={zoom.scale * 100}canZoomIn={zoom.canZoomIn}canZoomOut={zoom.canZoomOut}- onZoomIn={() => onCommand("relationMapResetZoomIn")}- onZoomOut={() => onCommand("relationMapResetZoomOut")}- onReset={() => onCommand("relationMapResetPanZoom")}+ onZoomIn={zoom.zoomIn}+ onZoomOut={zoom.zoomOut}+ onReset={zoom.reset}/><OverlayControlButtontitle={t("relation_map.fit_to_view")}icon="bx-scan"- onClick={() => onCommand("relationMapFitToView")}+ onClick={zoom.fit}/></OverlayControlGroup>);diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsxindex 62c1d50b65..88e501225f 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx@@ -28,8 +28,6 @@ vi.mock("react-zoom-pan-pinch", () => ({TransformComponent: (props: { children?: ComponentChildren }) => <div>{props.children}</div>}));-import Component from "../../../components/component";-import { ParentComponent } from "../../react/react_utils";import type RelationMapApi from "./api";import type { MapTransform } from "./api";import { MapViewport, useCanvasClicks, useMapZoom, useRevealSelectedBox } from "./RelationMap";@@ -239,7 +237,6 @@ describe("relation map zoom", () => {const setTransform = vi.fn();let boxes = [ { x: 0, y: 0, width: 1840, height: 100 } ];let zoom: ReturnType<typeof useMapZoom> | undefined;- const component = new Component();afterEach(() => {if (container) {@@ -253,7 +250,7 @@ describe("relation map zoom", () => {function Harness({ loadedTransform }: { loadedTransform: MapTransform }) {const [ viewport, setViewport ] = useState<HTMLDivElement | null>(null);const mapApiRef = useRef({ setTransform } as unknown as RelationMapApi);- zoom = useMapZoom({ ntxId: "map", viewport, loadedTransform, mapApiRef, getBoxes: () => boxes });+ zoom = useMapZoom({ viewport, loadedTransform, mapApiRef, getBoxes: () => boxes });return <MapViewport zoom={zoom} viewportRef={setViewport}><div className="note-box" /></MapViewport>;}@@ -261,7 +258,7 @@ describe("relation map zoom", () => {container = document.createElement("div");document.body.appendChild(container);act(() => render(- <ParentComponent.Provider value={component}><Harness loadedTransform={loadedTransform} /></ParentComponent.Provider>,+ <Harness loadedTransform={loadedTransform} />,container as HTMLElement));}@@ -274,8 +271,7 @@ describe("relation map zoom", () => {Object.defineProperty(viewport, "clientWidth", { value: 1000 });Object.defineProperty(viewport, "clientHeight", { value: 600 });}- const trigger = (name: "relationMapResetPanZoom" | "relationMapResetZoomIn" | "relationMapResetZoomOut", ntxId: string) =>- act(() => { component.handleEvent(name, { ntxId }); });+ const run = (action: "reset" | "fit" | "zoomIn" | "zoomOut") => act(() => { zoom?.[action](); });it("pans an unbounded canvas, and leaves boxes, labels and relations to be dragged and clicked", () => {mount({ x: 0, y: 0, scale: 1 });@@ -291,7 +287,7 @@ describe("relation map zoom", () => {expect(state()).toEqual({ positionX: -800, positionY: 600, scale: 1.5 });expect(zoom?.scale).toBe(1.5);- trigger("relationMapResetPanZoom", "map");+ run("reset");expect(state()).toEqual({ positionX: 0, positionY: 0, scale: 1 });expect(setTransform).toHaveBeenLastCalledWith({ x: 0, y: 0, scale: 1 });});@@ -300,24 +296,21 @@ describe("relation map zoom", () => {mount({ x: -800, y: 600, scale: 2 });sizeViewport();- act(() => { component.handleEvent("relationMapFitToView", { ntxId: "map" }); });+ run("fit");expect(state()).toEqual({ positionX: 40, positionY: 251, scale: 0.5 });boxes = [];- act(() => { component.handleEvent("relationMapFitToView", { ntxId: "map" }); });+ run("fit");expect(state()).toEqual({ positionX: 40, positionY: 251, scale: 0.5 });});- it("steps the zoom on the commands of its own map only", () => {+ it("steps the zoom", () => {mount({ x: 0, y: 0, scale: 1 });- trigger("relationMapResetZoomIn", "other");- expect(state()?.scale).toBe(1);-- trigger("relationMapResetZoomIn", "map");+ run("zoomIn");expect(state()?.scale).toBeCloseTo(1.2);- trigger("relationMapResetZoomOut", "map");+ run("zoomOut");expect(state()?.scale).toBeCloseTo(1);});});diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsxindex e0a39a17dc..736a7b851a 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx@@ -15,9 +15,10 @@ import note_create from "../../../services/note_create";import server from "../../../services/server";import toast from "../../../services/toast";import { isMobile } from "../../../services/utils";-import { useEditorSpacedUpdate, useNoteLabelBoolean, useTriliumEvent, useTriliumEvents } from "../../react/hooks";+import { useEditorSpacedUpdate, useNoteLabelBoolean } from "../../react/hooks";import { useZoomPanPinch, useZoomPanWheel } from "../../react/zoom_pan";import { useZoomPanKeyboard } from "../../react/zoom_pan_keyboard";+import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";import { TypeWidgetProps } from "../type_widget";import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry, MapTransform } from "./api";import Connections from "./Connections";@@ -30,7 +31,7 @@ import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";import RelationNamePopover, { useRelationNamePrompt } from "./RelationNamePopover";import { CLICK_TOLERANCE, fitTransform, getMousePosition, idToNoteId, noteIdToId, revealOffset } from "./utils";-export default function RelationMap({ note, noteContext, ntxId, parentComponent }: TypeWidgetProps) {+export default function RelationMap({ note, noteContext, ntxId }: TypeWidgetProps) {const [ data, setData ] = useState<MapData>();// The same read-only the note's own bar of actions read while the + stood there.const [ isReadOnly ] = useNoteLabelBoolean(note, "readOnly");@@ -90,7 +91,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent});const boxesRef = useRef<Map<string, Box>>(new Map());- const mapZoom = useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef, getBoxes: () => boxesRef.current.values() });+ const mapZoom = useMapZoom({ viewport, loadedTransform, mapApiRef, getBoxes: () => boxesRef.current.values() });const { getScale } = mapZoom;const [ selection, setSelection ] = useState<PaneSelection | null>(null);const noteIdsOnMap = useMemo(() => data?.notes.map((entry) => entry.noteId) ?? [], [ data ]);@@ -185,13 +186,13 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent<EditToolbarisReadOnly={isReadOnly}placing={placement.placing}- onTogglePlacement={() => parentComponent?.triggerEvent("relationMapCreateChildNote", { ntxId })}+ onTogglePlacement={placement.toggle}/>- <MapToolbar- zoom={mapZoom}- onCommand={(command) => parentComponent?.triggerEvent(command, { ntxId })}- />+ <MapToolbar zoom={mapZoom} />++ {/* The note pane takes the top-right corner while it is open. */}+ {!isMobile() && !selection && <ShortcutHintButton />}<NotePanepaneRef={paneRef}@@ -217,12 +218,11 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent/*** Pans and zooms the map with react-zoom-pan-pinch, as the image viewer does, on a canvas without* bounds. Restores `loadedTransform` whenever the note's content loads, saves every change to the- * map's data, and answers the zoom commands, which scripts can trigger too. Fitting shows all of- * `getBoxes()` at once. The wheel zooms without- * the map being focused, since the map fills its pane and has no page to scroll.+ * map's data, and returns the actions of the zoom toolbar: `reset` goes back to the origin at+ * 100%, and `fit` shows all of `getBoxes()` at once. The wheel zooms without the map being+ * focused, since the map fills its pane and has no page to scroll.*/-export function useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef, getBoxes }: {- ntxId: string | null | undefined;+export function useMapZoom({ viewport, loadedTransform, mapApiRef, getBoxes }: {/** The focusable element the keyboard and the wheel act on. */viewport: HTMLDivElement | null;loadedTransform: MapTransform | undefined;@@ -254,22 +254,14 @@ export function useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef, getBoxapi.setTransform(positionX + dx, positionY + dy, scale, REVEAL_ANIMATION_MS);}, [ ref ]);- useTriliumEvents([ "relationMapResetPanZoom", "relationMapResetZoomIn", "relationMapResetZoomOut", "relationMapFitToView" ], ({ ntxId: eventNtxId }, eventName) => {- if (eventNtxId !== ntxId) return;-- if (eventName === "relationMapResetPanZoom") {- ref.current?.setTransform(0, 0, 1);- } else if (eventName === "relationMapFitToView") {- const fitted = viewport && fitTransform(getBoxes(), { width: viewport.clientWidth, height: viewport.clientHeight }, MIN_SCALE);- if (fitted) ref.current?.setTransform(fitted.x, fitted.y, fitted.scale, REVEAL_ANIMATION_MS);- } else if (eventName === "relationMapResetZoomIn") {- zoom.zoomIn();- } else {- zoom.zoomOut();- }- });+ const reset = useCallback(() => ref.current?.setTransform(0, 0, 1), [ ref ]);++ const fit = useCallback(() => {+ const fitted = viewport && fitTransform(getBoxes(), { width: viewport.clientWidth, height: viewport.clientHeight }, MIN_SCALE);+ if (fitted) ref.current?.setTransform(fitted.x, fitted.y, fitted.scale, REVEAL_ANIMATION_MS);+ }, [ ref, viewport, getBoxes ]);- return { ...zoom, onTransform, getScale, moveBy };+ return { ...zoom, onTransform, getScale, moveBy, reset, fit };}/**@@ -415,11 +407,10 @@ function useNotePlacement({ ntxId, note, containerRef, getScale, mapApiRef, onArconst [ placing, setPlacing ] = useState(false);const ghostRef = useRef<HTMLDivElement>(null);- useTriliumEvent("relationMapCreateChildNote", ({ ntxId: eventNtxId }) => {- if (eventNtxId !== ntxId) return;+ const toggle = useCallback(() => {if (!placing) onArm();setPlacing(!placing);- });+ }, [ placing, onArm ]);// Depends on `placing` rather than on the code that turned placement mode on, so the toast and// the listener are removed on cancel, after placement and on unmount.@@ -479,7 +470,7 @@ function useNotePlacement({ ntxId, note, containerRef, getScale, mapApiRef, onAronCreated(created.noteId);}, [ note, containerRef, getScale, mapApiRef, onCreated ]);- return { placing, ghostRef, followPointer, hideGhost, placeAt };+ return { placing, toggle, ghostRef, followPointer, hideGhost, placeAt };}/**