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(note_map): add zoom steps and a fit to view button
Elian Dorana700d2f14891
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 2e68efc5b3..2d76682cd4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1340,6 +1340,7 @@"title": "Note Map","fix-nodes": "Fix nodes","link-distance": "Link distance",+ "fit-to-view": "Fit to view","too-many-notes_one": "There is {{count}} note here. Showing it may slow things down.","too-many-notes_other": "There are {{count}} notes here. Showing them all may slow things down.","show-anyway": "Show map"diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsxindex 904f8a1a2c..adbeb9855f 100644--- a/apps/client/src/widgets/note_map/NoteMap.tsx+++ b/apps/client/src/widgets/note_map/NoteMap.tsx@@ -10,14 +10,16 @@ import link_context_menu from "../../menus/link_context_menu";import hoisted_note from "../../services/hoisted_note";import { resolveIconGlyphs, warmIconFonts } from "../../services/icon_glyphs";import { t } from "../../services/i18n";+import { isMobile } from "../../services/utils";import Button from "../react/Button";import { useColorScheme, useElementSize, useNoteLabel, useTriliumOption } from "../react/hooks";import NoItems from "../react/NoItems";-import OverlayControlGroup, { OverlayControlButton } from "../react/OverlayControlGroup";+import OverlayControlGroup, { OverlayControlButton, ZoomControls } from "../react/OverlayControlGroup";import Slider from "../react/Slider";+import { ZOOM_STEP } from "../react/zoom_pan";import { loadNotesAndRelations, NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";import { MapTypeOverlayButtons } from "./MapTypeSwitcher";-import { CssData, setupRendering } from "./rendering";+import { CssData, type MapRendering, setupRendering } from "./rendering";import { isRootedAtCurrentNote, MapType, NOTE_MAP_TYPE_OPTION, NoteMapWidgetMode, rgb2hex, toMapType, usesReaderPreference } from "./utils";/** Maximum number of notes to render in the note map before showing a warning. */@@ -52,6 +54,9 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteIdconst [ tooManyNotes, setTooManyNotes ] = useState<number | null>(null);const [ bypassLimit, setBypassLimit ] = useState(false);const notesAndRelationsRef = useRef<NotesAndRelationsData | undefined>(undefined);+ const renderingRef = useRef<MapRendering | undefined>(undefined);+ const [ canZoomIn, setCanZoomIn ] = useState(true);+ const [ canZoomOut, setCanZoomOut ] = useState(true);const mapRootId = useMemo(() => {if (note.noteId && isRootedAtCurrentNote(widgetMode)) {@@ -84,7 +89,7 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteId// Navigating away mid-load must not let the outgoing note's data land on the new graph.let disposed = false;- let teardownRendering: (() => void) | undefined;+ let rendering: MapRendering | undefined;const labelValues = (name: string) => note.getLabels(name).map(l => l.value) ?? [];const excludeRelations = labelValues("mapExcludeRelation");const includeRelations = labelValues("mapIncludeRelation");@@ -109,7 +114,7 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteIdconst iconGlyphs = resolveIconGlyphs(notesAndRelations.nodes.map((node) => node.icon), containerRef.current);// Configure rendering properties.- teardownRendering = setupRendering(graph, {+ rendering = setupRendering(graph, {note,mapRootId,noteIdToSizeMap: notesAndRelations.noteIdToSizeMap,@@ -118,8 +123,13 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteIdthemeStyle,widgetMode,container,- iconGlyphs+ iconGlyphs,+ onZoom: (scale) => {+ setCanZoomIn(scale < graph.maxZoom());+ setCanZoomOut(scale > graph.minZoom());+ }});+ renderingRef.current = rendering;// Interactiongraph@@ -148,7 +158,8 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteIdreturn () => {disposed = true;- teardownRendering?.();+ rendering?.teardown();+ renderingRef.current = undefined;// Stops the render loop; without it the discarded graph keeps animating against a// detached canvas for the rest of the session.graph._destructor();@@ -227,6 +238,23 @@ export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteId/></div></OverlayControlGroup>++ {/* The steps stay home on mobile, as on the geo map: the fingers already zoom. */}+ <OverlayControlGroup className="note-map-zoom-controls" placement="bottom-end" overCanvas>+ {!isMobile() && (+ <ZoomControls+ canZoomIn={canZoomIn}+ canZoomOut={canZoomOut}+ onZoomIn={() => renderingRef.current?.zoomBy(ZOOM_STEP)}+ onZoomOut={() => renderingRef.current?.zoomBy(1 / ZOOM_STEP)}+ />+ )}+ <OverlayControlButton+ title={t("note_map.fit-to-view")}+ icon="bx-scan"+ onClick={() => renderingRef.current?.fitToView()}+ />+ </OverlayControlGroup></>)}diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.tsindex 5829f76186..247c68b890 100644--- a/apps/client/src/widgets/note_map/rendering.ts+++ b/apps/client/src/widgets/note_map/rendering.ts@@ -12,6 +12,9 @@ const TICKS_UNTIL_DAMPED = 60;/** What a map of a single note is shown at, there being no extent to fit — see {@link setupFraming}. */const LONE_NOTE_ZOOM = 4;+/** How long a zoom step or a fit to the view takes to play out. */+const ZOOM_ANIMATION_MS = 250;+/** How large a note's dot has to come out on screen, in pixels, before its icon is drawn inside it. */const MIN_ICON_RADIUS = 7;@@ -115,10 +118,20 @@ interface RenderData {container: HTMLElement;/** What each note's icon class resolves to, as the icon pack draws it — see icon_glyphs.ts. */iconGlyphs: Map<string, IconGlyph>;+ /** Called with the scale of the view after every zoom, for controls that depend on it. */+ onZoom?: (scale: number) => void;}-/** @returns a teardown function to call when the graph is discarded. */-export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, { note, mapRootId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData, container, iconGlyphs }: RenderData) {+/** What the map's controls drive the drawn graph through. */+export interface MapRendering {+ /** Fits the view to the notes the map is framed on as it loads, and stops following the layout. */+ fitToView(): void;+ /** Zooms the view by `factor` around its middle, and stops following the layout. */+ zoomBy(factor: number): void;+ /** Undoes the setup, to call when the graph is discarded. */+ teardown(): void;+}+export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, { note, mapRootId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData, container, iconGlyphs, onZoom }: RenderData): MapRendering {// What the map is showing of the note under the pointer: the note itself, the notes a relation// runs between it and, and those relations. Worked out once when the hover changes rather than// while painting, so that every note of a frame is painted knowing the same thing.@@ -463,7 +476,10 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOctx.fill();}).nodeLabel((node) => getTooltip(node))- .onZoom((zoom) => zoomLevel = zoom.k);+ .onZoom((zoom) => {+ zoomLevel = zoom.k;+ onZoom?.(zoom.k);+ });graph.linkWidth((link) => LINK_WIDTH + (HIGHLIGHT_LINK_WIDTH - LINK_WIDTH) * Math.max(0, linkFocus.get(link)))@@ -492,11 +508,21 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOgraph.d3Force("charge")?.strength(boundedCharge);graph.d3Force("charge")?.distanceMax(1000);- const stopFraming = setupFraming(graph, container, { note, widgetMode, notesAndRelations, hopDistances });+ const framing = setupFraming(graph, container, { note, widgetMode, notesAndRelations, hopDistances });- return () => {- clearTimeout(fadeTimer);- stopFraming();+ return {+ fitToView() {+ framing.release();+ framing.fit(ZOOM_ANIMATION_MS);+ },+ zoomBy(factor) {+ framing.release();+ graph.zoom(graph.zoom() * factor, ZOOM_ANIMATION_MS);+ },+ teardown() {+ clearTimeout(fadeTimer);+ framing.stop();+ }};}@@ -718,7 +744,8 @@ export function createFade<T>(elements: T[], getTarget: (element: T) => number)* force-graph's default zoom meanwhile (a few nodes around the origin, the rest already spread out* of sight) and then jumps to the real framing when it finally fires.*- * @returns a teardown function to call when the graph is discarded.+ * @returns `fit()`, which frames the view as the map does while it settles, `release()`, which stops+ * the framing, and `stop()`, to call when the graph is discarded.*/function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, container: HTMLElement, { note, widgetMode, notesAndRelations, hopDistances }: Pick<RenderData, "note" | "widgetMode" | "notesAndRelations"> & { hopDistances: Map<string, number> }) {const { framedNoteIds, framesSubset, padding, fittedNoteCount } = planFraming({ widgetMode, noteType: note?.type, notesAndRelations, hopDistances });@@ -740,15 +767,19 @@ function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, ccontainer.addEventListener("wheel", releaseFraming, listenerOptions);container.addEventListener("pointerdown", releaseFraming, listenerOptions);+ // Fitting is what centres the view on the note, whether or not its zoom is kept.+ const fit = (duration: number) => {+ graph.zoomToFit(duration, padding, nodeFilter);++ if (fittedNoteCount <= 1) {+ graph.zoom(LONE_NOTE_ZOOM, duration);+ }+ };+let ticks = 0;graph.onEngineTick(() => {if (framing) {- // Fitting is what centres the view on the note, whether or not its zoom is kept.- graph.zoomToFit(0, padding, nodeFilter);-- if (fittedNoteCount <= 1) {- graph.zoom(LONE_NOTE_ZOOM, 0);- }+ fit(0);}// Damping, once the graph has had the room to spread out, so that a small map comes to rest@@ -758,9 +789,13 @@ function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, c}});- return () => {- container.removeEventListener("wheel", releaseFraming, listenerOptions);- container.removeEventListener("pointerdown", releaseFraming, listenerOptions);+ return {+ fit,+ release: releaseFraming,+ stop() {+ container.removeEventListener("wheel", releaseFraming, listenerOptions);+ container.removeEventListener("pointerdown", releaseFraming, listenerOptions);+ }};}diff --git a/apps/client/src/widgets/react/zoom_pan.ts b/apps/client/src/widgets/react/zoom_pan.tsindex 7e69ab274a..020571f1be 100644--- a/apps/client/src/widgets/react/zoom_pan.ts+++ b/apps/client/src/widgets/react/zoom_pan.ts@@ -104,7 +104,7 @@ export function useZoomPanWheel(}/** What one press of a zoom step multiplies the scale by. */-const ZOOM_STEP = 1.2;+export const ZOOM_STEP = 1.2;/** What one wheel notch multiplies the scale by. Below {@link ZOOM_STEP}: notches arrive in bursts. */const WHEEL_STEP = 1.1;/** The pixel `deltaY` of one mouse-wheel notch. A trackpad reports a fraction of this per event. */diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).htmlindex 98883fd8f8..f2910812cd 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).html@@ -59,6 +59,16 @@<li>When hovering over a node, the adjacent relations and nodes are highlighted.</li><li>The distance between nodes can be adjusted via the slider in the bottom-left.Similarly, this value is not saved.</li>+ <li>To zoom, use the mouse wheel, pinch on a touch screen, or press the <span+ class="tn-icon bx bx-plus-circle"></span> and <span class="tn-icon bx bx-minus-circle"></span> buttons+ in the bottom-right corner.+ <ul>+ <li>To bring the whole map back into view, press the <span class="tn-icon bx bx-scan"></span> <em>Fit to view</em> button+ next to them.</li>+ <li>The zoom buttons are not shown on mobile, where pinching zooms instead.+ The <em>Fit to view</em> button is always shown.</li>+ </ul>+ </li><li><a class="reference-link" href="#root/_help_MKmLg5x6xkor">Archived Notes</a> aregenerally ignored by the note map in order to reduce clutter. There isone exception: if the root note is also archived, then all archived notesdiff --git a/docs/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).md b/docs/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).mdindex eba30d7ea6..a6f73c24fd 100644--- a/docs/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).md+++ b/docs/User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map).md@@ -30,6 +30,9 @@ The note map comes into multiple flavors:* To have the notes remain in the same position as they were dragged, press the _Fix nodes_ button. The position of the notes is not saved, so it will return to normal once you navigate to another note or restart the application.* When hovering over a node, the adjacent relations and nodes are highlighted.* The distance between nodes can be adjusted via the slider in the bottom-left. Similarly, this value is not saved.+* To zoom, use the mouse wheel, pinch on a touch screen, or press the <span class="tn-icon bx bx-plus-circle"></span> and <span class="tn-icon bx bx-minus-circle"></span> buttons in the bottom-right corner.+ * To bring the whole map back into view, press the <span class="tn-icon bx bx-scan"></span> _Fit to view_ button next to them.+ * The zoom buttons are not shown on mobile, where pinching zooms instead. The _Fit to view_ button is always shown.* <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Notes/Archived%20Notes.md">Archived Notes</a> are generally ignored by the note map in order to reduce clutter. There is one exception: if the root note is also archived, then all archived notes are displayed too.## Link Map