Skip to content

Build your personal knowledge base with Trilium Notes

feat(relation_map): pan a selected note into view beside the pane

Elian Doran53956bbe836e
diff --git a/apps/client/src/widgets/type_widgets/relation_map/NotePane.css b/apps/client/src/widgets/type_widgets/relation_map/NotePane.css
index 4fe7b1d4ef..9ca3a99883 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NotePane.css
+++ b/apps/client/src/widgets/type_widgets/relation_map/NotePane.css
@@ -1,6 +1,6 @@
.relation-map-wrapper {
--relation-map-inset: var(--overlay-button-inset, 10px);
- /* Must agree with `PANE_WIDTH` in RelationMap.tsx. */
+ /* Must agree with `PANE_WIDTH` in utils.ts. */
--relation-map-pane-width: 380px;
}
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.tsx
index 4b98b5b501..7601480ad9 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
@@ -1,9 +1,10 @@
+import type { PanZoom } from "panzoom";
import { render } from "preact";
import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useCanvasClicks } from "./RelationMap";
+import { useCanvasClicks, useRevealSelectedBox } from "./RelationMap";
import { noteIdToId } from "./utils";
describe("relation map canvas clicks", () => {
@@ -112,3 +113,81 @@ describe("relation map canvas clicks", () => {
expect(onSelectNote).not.toHaveBeenCalled();
});
});
+
+describe("relation map revealing the selected box", () => {
+ let container: HTMLElement | undefined;
+ const moveBy = vi.fn();
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ moveBy.mockClear();
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ function Harness({ noteId }: { noteId: string | undefined }) {
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLDivElement>(null);
+ useRevealSelectedBox({ wrapperRef, containerRef: canvasRef, panZoom: { moveBy } as unknown as PanZoom, noteId });
+ return (
+ <div ref={wrapperRef} className="wrapper">
+ <div ref={canvasRef} className="canvas" />
+ </div>
+ );
+ }
+
+ /** Lays the map out at 1200 × 800, which happy-dom does not do by itself. */
+ function mount(noteId: string | undefined) {
+ act(() => render(<Harness noteId={noteId} />, container as HTMLElement));
+ const wrapper = container?.querySelector<HTMLElement>(".wrapper");
+ if (wrapper) placeAt(wrapper, { left: 0, top: 0, right: 1200, bottom: 800 });
+ }
+
+ /** Adds a box to the canvas at the given page position, as `NoteBox` would render it. */
+ function addBox(noteId: string, left: number) {
+ const box = document.createElement("div");
+ box.id = noteIdToId(noteId);
+ placeAt(box, { left, top: 100, right: left + 160, bottom: 150 });
+ act(() => { container?.querySelector(".canvas")?.appendChild(box); });
+ }
+
+ function placeAt(element: HTMLElement, rect: { left: number; top: number; right: number; bottom: number }) {
+ element.getBoundingClientRect = () => ({ ...rect, x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top, toJSON: () => rect });
+ }
+
+ it("pans a box out from under the pane, and leaves one alone that stands clear", () => {
+ addBoxBeforeMount("under", 1000);
+ expect(moveBy).toHaveBeenCalledTimes(1);
+ const [ dx, dy, smooth ] = moveBy.mock.calls[0];
+ expect(dx).toBeLessThan(0);
+ expect([ dy, smooth ]).toEqual([ 0, true ]);
+
+ moveBy.mockClear();
+ addBoxBeforeMount("clear", 100);
+ expect(moveBy).not.toHaveBeenCalled();
+ });
+
+ it("waits for the box of a note placed a moment ago", async () => {
+ mount("placed");
+ expect(moveBy).not.toHaveBeenCalled();
+
+ addBox("placed", 1000);
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve)); });
+ expect(moveBy).toHaveBeenCalledTimes(1);
+ });
+
+ /** The box is on the map before the note is selected, as for a box that is clicked. */
+ function addBoxBeforeMount(noteId: string, left: number) {
+ if (container) render(null, container);
+ mount(undefined);
+ addBox(noteId, left);
+ mount(noteId);
+ }
+});
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 daf04c31bc..76cd366019 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
@@ -15,6 +15,7 @@ import { t } from "../../../services/i18n";
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 { TypeWidgetProps } from "../type_widget";
import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry, RelationType } from "./api";
@@ -25,7 +26,7 @@ import { GhostNoteBox, NoteBox } from "./NoteBox";
import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";
import setupOverlays, { uniDirectionalOverlays } from "./overlays";
import RelationNamePopover, { type AskRelationName, useRelationNamePrompt } from "./RelationNamePopover";
-import { getMousePosition, getZoom, idToNoteId, noteIdToId } from "./utils";
+import { getMousePosition, getZoom, idToNoteId, noteIdToId, revealOffset } from "./utils";
declare module "jsplumb" {
@@ -48,6 +49,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
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");
+ const wrapperRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const mapApiRef = useRef<RelationMapApi>(null);
const pbApiRef = useRef<jsPlumbInstance>(null);
@@ -149,10 +151,12 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
onTransform
});
+ useRevealSelectedBox({ wrapperRef, containerRef, panZoom, noteId: selection?.noteId });
useRelationData(note.noteId, data, mapApiRef, pbApiRef);
return (
<div
+ ref={wrapperRef}
className={clsx("relation-map-wrapper", placement.placing && "placing-note")}
onMouseMove={placement.followPointer}
onMouseLeave={placement.hideGhost}
@@ -490,6 +494,51 @@ export function useCanvasClicks({ containerRef, placing, onPlace, onSelectNote,
};
}
+/**
+ * Pans the map so the box of the selected note stands clear of the note pane and the edges of the
+ * map (see {@link revealOffset}). A phone shows the note as a dialog over the whole screen, so the
+ * map is left where it is there.
+ *
+ * The box of a note placed a moment ago is not on the map yet: `NoteBox` renders it once the note
+ * has loaded, so the pan waits for it to appear in the container.
+ */
+export function useRevealSelectedBox({ wrapperRef, containerRef, panZoom, noteId }: {
+ wrapperRef: RefObject<HTMLDivElement | null>;
+ containerRef: RefObject<HTMLDivElement | null>;
+ panZoom: PanZoom | undefined;
+ noteId: string | undefined;
+}) {
+ useEffect(() => {
+ const wrapper = wrapperRef.current;
+ const container = containerRef.current;
+ if (!noteId || !wrapper || !container || !panZoom || isMobile()) return;
+
+ const id = noteIdToId(noteId);
+ const findBox = () => [ ...container.children ].find((child) => child.id === id);
+ const reveal = (box: Element) => {
+ const offset = revealOffset(box.getBoundingClientRect(), wrapper.getBoundingClientRect(), glob.isRtl);
+ if (offset) {
+ panZoom.moveBy(offset.dx, offset.dy, true);
+ }
+ };
+
+ const box = findBox();
+ if (box) {
+ reveal(box);
+ return;
+ }
+
+ const observer = new MutationObserver(() => {
+ const box = findBox();
+ if (!box) return;
+ observer.disconnect();
+ reveal(box);
+ });
+ observer.observe(container, { childList: true });
+ return () => observer.disconnect();
+ }, [ wrapperRef, containerRef, panZoom, noteId ]);
+}
+
/** Where the pointer stands on a box being placed: the top centre of its title. */
const PLACEMENT_OFFSET = { x: 80, y: 15 };
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.ts
new file mode 100644
index 0000000000..f7386fe4c5
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.spec.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+
+import { 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 };
+/** Where the pane starts, in a left-to-right app: its width and the inset away from the right. */
+const PANE_LEFT = MAP.right - 10 - PANE_WIDTH;
+
+function box(left: number, top: number, width = 160, height = 50) {
+ return { left, top, right: left + width, bottom: top + height };
+}
+
+describe("revealOffset", () => {
+ it("leaves a box alone that already stands clear of the pane and the edges", () => {
+ expect(revealOffset(box(100, 100), MAP, false)).toBeNull();
+ });
+
+ it("brings a box under the pane to the middle of what the pane leaves uncovered, horizontally only", () => {
+ const offset = revealOffset(box(PANE_LEFT + 50, 300), MAP, false);
+ const centre = (PANE_LEFT + 50 + 80) + (offset?.dx ?? 0);
+
+ expect(offset?.dy).toBe(0);
+ expect(centre).toBeCloseTo(PANE_LEFT / 2);
+ });
+
+ it("brings back a box off the top or down behind the foot toolbars", () => {
+ expect(revealOffset(box(100, -40), MAP, false)?.dy).toBeGreaterThan(0);
+ expect(revealOffset(box(100, MAP.bottom - 60), MAP, false)?.dy).toBeLessThan(0);
+ expect(revealOffset(box(100, -40), MAP, false)?.dx).toBe(0);
+ });
+
+ it("keeps clear of the pane on the left in a right-to-left app", () => {
+ expect(revealOffset(box(MAP.right - 200, 100), MAP, true)).toBeNull();
+ expect(revealOffset(box(50, 100), MAP, true)?.dx).toBeGreaterThan(0);
+ });
+
+ it("only keeps the box on screen when the map is too narrow to leave room beside the pane", () => {
+ const narrow = { ...MAP, right: PANE_WIDTH + 100 };
+
+ expect(revealOffset(box(250, 100), narrow, false)).toBeNull();
+ expect(revealOffset(box(-100, 100), narrow, false)?.dx).toBeGreaterThan(0);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
index e131a7b8e1..afa1e949e7 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/utils.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
@@ -33,3 +33,55 @@ export function getMousePosition(evt: MouseEvent, container: HTMLDivElement, zoo
y: ((evt.clientY ?? 0) - rect.top) / zoom
};
}
+
+/** Must agree with `--relation-map-pane-width` in NotePane.css. */
+export const PANE_WIDTH = 380;
+
+/** Must agree with `--relation-map-inset` in NotePane.css. */
+const MAP_INSET = 10;
+
+/** How far into the map the pane reaches from its trailing edge: its width plus the inset. */
+const PANE_REACH = PANE_WIDTH + MAP_INSET;
+
+/** Must agree with the pane's `bottom` in NotePane.css, which clears the toolbars at the foot. */
+const MAP_FOOT = 2 * MAP_INSET + 28;
+
+/** The room kept between a revealed box and whatever bounds the visible part of the map. */
+const AIR = 20;
+
+/** Below this much room beside the pane, the pane is treated as covering the whole map. */
+const MIN_UNCOVERED_WIDTH = 200;
+
+interface Rect {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+/**
+ * How far to pan the map so that `box` stands in the part of it the note pane leaves uncovered,
+ * or `null` when it already does. Each axis on which the box does not fit is centred in that part;
+ * an axis on which it fits is left alone.
+ *
+ * Both rectangles are in page coordinates, as `getBoundingClientRect()` gives them, which is also
+ * what `PanZoom.moveBy()` takes.
+ */
+export function revealOffset(box: Rect, map: Rect, isRtl: boolean) {
+ const paneReach = map.right - map.left - PANE_REACH >= MIN_UNCOVERED_WIDTH ? PANE_REACH : 0;
+ const visible = {
+ left: map.left + (isRtl ? paneReach : 0) + AIR,
+ right: map.right - (isRtl ? 0 : paneReach) - AIR,
+ top: map.top + AIR,
+ bottom: map.bottom - MAP_FOOT - AIR
+ };
+
+ const dx = box.left >= visible.left && box.right <= visible.right
+ ? 0
+ : (visible.left + visible.right) / 2 - (box.left + box.right) / 2;
+ const dy = box.top >= visible.top && box.bottom <= visible.bottom
+ ? 0
+ : (visible.top + visible.bottom) / 2 - (box.top + box.bottom) / 2;
+
+ return dx || dy ? { dx, dy } : null;
+}
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.html
index deda66c83b..1fe07716d9 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
@@ -51,7 +51,9 @@
</ul>
<h2>Note panel</h2>
<p>When a note on the map is clicked, a panel opens to the right of the map
- and the note is highlighted. The panel contains:</p>
+ and the note is highlighted. If the panel would cover the note, or the
+ note is partly off-screen, the map pans to bring it into view. The panel
+ contains:</p>
<ul>
<li>The title and icon of the note, both editable.</li>
<li>A button to expand the panel over the whole map, and to restore it afterwards.</li>
diff --git a/docs/User Guide/User Guide/Note Types/Relation Map.md b/docs/User Guide/User Guide/Note Types/Relation Map.md
index ed06420ae4..c8dc236d7d 100644
--- a/docs/User Guide/User Guide/Note Types/Relation Map.md
+++ b/docs/User Guide/User Guide/Note Types/Relation Map.md
@@ -20,7 +20,7 @@ Relation map is a type of note which visualizes notes and their [relations](..
## Note panel
-When a note on the map is clicked, a panel opens to the right of the map and the note is highlighted. The panel contains:
+When a note on the map is clicked, a panel opens to the right of the map and the note is highlighted. If the panel would cover the note, or the note is partly off-screen, the map pans to bring it into view. The panel contains:
* The title and icon of the note, both editable.
* A button to expand the panel over the whole map, and to restore it afterwards.