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
feat(relation_map): add a fit-to-view button
Elian Doranbcd52ca8a12d
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex eeb94b86fc..8e754b69e4 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -585,6 +585,7 @@ type EventMappings = {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/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9aae2dcd83..3f89b68332 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1673,7 +1673,8 @@"expand_note_pane": "Expand the note to fill the map","restore_note_pane": "Put the note back beside the map","note_color": "Note color",- "remove_from_map": "Remove from map"+ "remove_from_map": "Remove from map",+ "fit_to_view": "Fit to view"},"render": {"setup_title": "Display custom HTML or Preact JSX inside this note",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 4bfab23592..ce7a0bb503 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@@ -31,13 +31,14 @@ describe("relation map MapToolbar", () => {});it("asks for what each button stands for rather than moving the map itself", () => {- const { commands, readout, zoomIn, zoomOut } = renderToolbar();+ const { commands, readout, zoomIn, zoomOut, fit } = renderToolbar();act(() => zoomOut()?.click());act(() => readout()?.click());act(() => zoomIn()?.click());+ act(() => fit()?.click());- expect(commands).toEqual([ "relationMapResetZoomOut", "relationMapResetPanZoom", "relationMapResetZoomIn" ]);+ expect(commands).toEqual([ "relationMapResetZoomOut", "relationMapResetPanZoom", "relationMapResetZoomIn", "relationMapFitToView" ]);});});@@ -90,7 +91,8 @@ function renderToolbar() {rerender,zoomOut: () => all()[0],readout: () => all()[1],- zoomIn: () => all()[2]+ zoomIn: () => all()[2],+ fit: () => all()[3]};}diff --git a/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/relation_map/MapToolbar.tsxindex fb3346e7cc..ba531b6bd1 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 { 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";+export type MapCommand = "relationMapResetZoomIn" | "relationMapResetZoomOut" | "relationMapResetPanZoom" | "relationMapFitToView";interface MapToolbarProps {/** The scale the map is drawn at, and whether each zoom step has room left. */@@ -38,6 +38,11 @@ export default function MapToolbar({ zoom, onCommand }: MapToolbarProps) {onZoomOut={() => onCommand("relationMapResetZoomOut")}onReset={() => onCommand("relationMapResetPanZoom")}/>+ <OverlayControlButton+ title={t("relation_map.fit_to_view")}+ icon="bx-scan"+ onClick={() => onCommand("relationMapFitToView")}+ /></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 bfd0dac0aa..62c1d50b65 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@@ -237,6 +237,7 @@ describe("relation map revealing the selected box", () => {describe("relation map zoom", () => {let container: HTMLElement | undefined;const setTransform = vi.fn();+ let boxes = [ { x: 0, y: 0, width: 1840, height: 100 } ];let zoom: ReturnType<typeof useMapZoom> | undefined;const component = new Component();@@ -252,7 +253,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 });+ zoom = useMapZoom({ ntxId: "map", viewport, loadedTransform, mapApiRef, getBoxes: () => boxes });return <MapViewport zoom={zoom} viewportRef={setViewport}><div className="note-box" /></MapViewport>;}@@ -265,6 +266,14 @@ describe("relation map zoom", () => {}const state = () => zoom?.ref.current?.instance.state;++ /** Gives the viewport a 1000 × 600 layout, which happy-dom does not compute. */+ function sizeViewport() {+ const viewport = container?.querySelector(".relation-map-viewport");+ if (!viewport) throw new Error("no viewport");+ 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 }); });@@ -287,6 +296,18 @@ describe("relation map zoom", () => {expect(setTransform).toHaveBeenLastCalledWith({ x: 0, y: 0, scale: 1 });});+ it("fits all the boxes into the view, and does nothing on an empty map", () => {+ mount({ x: -800, y: 600, scale: 2 });+ sizeViewport();++ act(() => { component.handleEvent("relationMapFitToView", { ntxId: "map" }); });+ expect(state()).toEqual({ positionX: 40, positionY: 251, scale: 0.5 });++ boxes = [];+ act(() => { component.handleEvent("relationMapFitToView", { ntxId: "map" }); });+ expect(state()).toEqual({ positionX: 40, positionY: 251, scale: 0.5 });+ });+it("steps the zoom on the commands of its own map only", () => {mount({ x: 0, y: 0, scale: 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 8e33b2df4b..9a054172a9 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx@@ -28,7 +28,7 @@ import MapToolbar, { EditToolbar } from "./MapToolbar";import { GhostNoteBox, NoteBox } from "./NoteBox";import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";import RelationNamePopover, { useRelationNamePrompt } from "./RelationNamePopover";-import { CLICK_TOLERANCE, getMousePosition, idToNoteId, noteIdToId, revealOffset } from "./utils";+import { CLICK_TOLERANCE, fitTransform, getMousePosition, idToNoteId, noteIdToId, revealOffset } from "./utils";export default function RelationMap({ note, noteContext, ntxId, parentComponent }: TypeWidgetProps) {const [ data, setData ] = useState<MapData>();@@ -89,7 +89,8 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent}});- const mapZoom = useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef });+ const boxesRef = useRef<Map<string, Box>>(new Map());+ const mapZoom = useMapZoom({ ntxId, 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 ]);@@ -117,6 +118,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponentconst { dragged, startDrag } = useBoxDragging({ containerRef, mapApiRef, getScale });const { pending, startDrawing } = useRelationDrawing({ containerRef, mapApiRef, getScale, askRelationName: relationNamePrompt.ask });const { boxes, onBoxResize } = useBoxes(data?.notes, dragged);+ boxesRef.current = boxes;useRevealSelectedBox({ wrapperRef, containerRef, moveBy: mapZoom.moveBy, noteId: selection?.noteId });const hoveredNoteId = useHoveredBox(containerRef);@@ -215,15 +217,18 @@ 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. The wheel zooms without+ * 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.*/-export function useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef }: {+export function useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef, getBoxes }: {ntxId: string | null | undefined;/** The focusable element the keyboard and the wheel act on. */viewport: HTMLDivElement | null;loadedTransform: MapTransform | undefined;mapApiRef: RefObject<RelationMapApi | null>;+ /** The boxes on the map, in unzoomed map pixels. */+ getBoxes(): Iterable<Box>;}) {const zoom = useZoomPanPinch({ minScale: MIN_SCALE, maxScale: MAX_SCALE });const { ref } = zoom;@@ -249,11 +254,14 @@ export function useMapZoom({ ntxId, viewport, loadedTransform, mapApiRef }: {api.setTransform(positionX + dx, positionY + dy, scale, REVEAL_ANIMATION_MS);}, [ ref ]);- useTriliumEvents([ "relationMapResetPanZoom", "relationMapResetZoomIn", "relationMapResetZoomOut" ], ({ ntxId: eventNtxId }, eventName) => {+ 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 {@@ -299,7 +307,7 @@ const MAX_SCALE = 2;const PAN_EXCLUDED = [ "note-box", "connection-label", "relation-map-connection-hit" ];-/** How long panning a selected box into view takes. */+/** How long panning a selected box into view, or fitting the map to the view, takes. */const REVEAL_ANIMATION_MS = 300;function useRelationData(noteId: string, mapData: MapData | undefined, mapApiRef: RefObject<RelationMapApi | null>) {diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.spec.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.spec.tsindex f7386fe4c5..0e228a646a 100644--- a/apps/client/src/widgets/type_widgets/relation_map/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { PANE_WIDTH, revealOffset } from "./utils";+import { fitTransform, PANE_WIDTH, revealOffset } from "./utils";/** A map 1200 × 800 at the origin of the page, with room for the pane beside the boxes. */const MAP = { left: 0, top: 0, right: 1200, bottom: 800 };@@ -42,3 +42,22 @@ describe("revealOffset", () => {expect(revealOffset(box(-100, 100), narrow, false)?.dx).toBeGreaterThan(0);});});++describe("fitTransform", () => {+ const viewport = { width: 1000, height: 600 };++ it("centers a map that fits at its own size above the toolbars, without enlarging it", () => {+ const boxes = [ { x: 100, y: 100, width: 100, height: 40 }, { x: 300, y: 200, width: 100, height: 40 } ];++ expect(fitTransform(boxes, viewport, 0.3)).toEqual({ x: 250, y: 106, scale: 1 });+ });++ it("shrinks a map too large for the view, down to the smallest scale", () => {+ expect(fitTransform([ { x: 0, y: 0, width: 1840, height: 100 } ], viewport, 0.3)).toEqual({ x: 40, y: 251, scale: 0.5 });+ expect(fitTransform([ { x: 0, y: 0, width: 92000, height: 100 } ], viewport, 0.3)?.scale).toBe(0.3);+ });++ it("has nothing to fit on an empty map", () => {+ expect(fitTransform([], viewport, 0.3)).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.tsindex b8bf3c5a1c..d255b04a05 100644--- a/apps/client/src/widgets/type_widgets/relation_map/utils.ts+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.ts@@ -70,3 +70,33 @@ export function revealOffset(box: Rect, map: Rect, isRtl: boolean) {return dx || dy ? { dx, dy } : null;}++/** Gap between the boxes and the edges of the view after a fit. */+const FIT_PADDING = 40;++/**+ * The transform that shows all of `boxes` (in unzoomed map pixels) centered in a viewport of the+ * given size, above the toolbars at its foot, or `null` when there are no boxes. The map is never+ * enlarged past its own size, and never shrunk below `minScale`.+ */+export function fitTransform(boxes: Iterable<{ x: number; y: number; width: number; height: number }>, viewport: { width: number; height: number }, minScale: number) {+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;+ for (const box of boxes) {+ left = Math.min(left, box.x);+ top = Math.min(top, box.y);+ right = Math.max(right, box.x + box.width);+ bottom = Math.max(bottom, box.y + box.height);+ }+ if (left === Infinity) return null;++ const height = viewport.height - MAP_FOOT;+ const scale = Math.max(minScale, Math.min(1,+ (viewport.width - 2 * FIT_PADDING) / (right - left),+ (height - 2 * FIT_PADDING) / (bottom - top)));++ return {+ x: (viewport.width - (right - left) * scale) / 2 - left * scale,+ y: (height - (bottom - top) * scale) / 2 - top * scale,+ scale+ };+}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.htmlindex 08ac57d72d..d1f4179ae6 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html@@ -54,6 +54,10 @@is not shown if the map is read-only.</li><li>To rename or delete a relationship, right click it and select the correspondingoption.</li>+ <li>To move around the map, drag an empty part of it, and zoom with the mouse+ wheel or the buttons at the bottom-right corner. Clicking the zoom percentage+ goes back to 100%, and <span class="tn-icon bx bx-scan"></span> <em>Fit to view</em> zooms+ and pans so that all the notes are visible.</li></ul><h2>Note panel</h2><p>When a note on the map is clicked, a panel opens to the right of the mapdiff --git a/docs/User Guide/User Guide/Note Types/Relation Map.md b/docs/User Guide/User Guide/Note Types/Relation Map.mdindex f57c4fe289..b73346314e 100644--- a/docs/User Guide/User Guide/Note Types/Relation Map.md+++ b/docs/User Guide/User Guide/Note Types/Relation Map.md@@ -19,6 +19,7 @@ Relation map is a type of note which visualizes notes and their [relations](..* To open the note in a new tab instead, <kbd>Ctrl</kbd>+click it or click it with the middle mouse button. <kbd>Shift</kbd>+click opens it in a new window. The right click menu offers the same options.* To edit the title of a note, change its color or delete it (either from the map, or delete it completely), right click the note. The color picker is not shown if the map is read-only.* To rename or delete a relationship, right click it and select the corresponding option.+* To move around the map, drag an empty part of it, and zoom with the mouse wheel or the buttons at the bottom-right corner. Clicking the zoom percentage goes back to 100%, and <span class="tn-icon bx bx-scan"></span> _Fit to view_ zooms and pans so that all the notes are visible.## Note panel