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(client): hide unlinked notes from the sidebar's note map
Elian Doran8a49ebf427ea
diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsxindex 37a0a27f23..824c567ebc 100644--- a/apps/client/src/widgets/note_map/NoteMap.tsx+++ b/apps/client/src/widgets/note_map/NoteMap.tsx@@ -17,7 +17,7 @@ import NoItems from "../react/NoItems";import Slider from "../react/Slider";import { loadNotesAndRelations, NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";import { CssData, setupRendering } from "./rendering";-import { MapType, NoteMapWidgetMode, rgb2hex } from "./utils";+import { isRootedAtCurrentNote, MapType, NoteMapWidgetMode, rgb2hex } from "./utils";/** Maximum number of notes to render in the note map before showing a warning. */const MAX_NOTES_THRESHOLD = 1_000;@@ -44,7 +44,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {const notesAndRelationsRef = useRef<NotesAndRelationsData>();const mapRootId = useMemo(() => {- if (note.noteId && widgetMode === "ribbon") {+ if (note.noteId && isRootedAtCurrentNote(widgetMode)) {return note.noteId;} else if (mapRootIdLabel === "hoisted") {return hoisted_note.getHoistedNoteId();@@ -78,7 +78,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {const labelValues = (name: string) => note.getLabels(name).map(l => l.value) ?? [];const excludeRelations = labelValues("mapExcludeRelation");const includeRelations = labelValues("mapIncludeRelation");- loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType).then((notesAndRelations) => {+ loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType, widgetMode === "sidebar").then((notesAndRelations) => {if (disposed || !containerRef.current || !styleResolverRef.current) return;// Guard against rendering too many notes which would freeze the browser.diff --git a/apps/client/src/widgets/note_map/data.spec.ts b/apps/client/src/widgets/note_map/data.spec.tsnew file mode 100644index 0000000000..a2b6664102--- /dev/null+++ b/apps/client/src/widgets/note_map/data.spec.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest";++import { dropUnlinkedNotes } from "./data";++describe("dropUnlinkedNotes", () => {+ const nodes = [ { id: "root" }, { id: "source" }, { id: "target" }, { id: "loose" } ];+ const links = [ { id: "source-target", sourceNoteId: "source", targetNoteId: "target", names: [ "relates" ] } ];++ it("keeps the notes a relation touches along with the map root, and drops the rest", () => {+ expect(dropUnlinkedNotes(nodes, links, "root")).toEqual([ { id: "root" }, { id: "source" }, { id: "target" } ]);++ // Nothing linked at all: the root still stands on its own rather than leaving an empty map.+ expect(dropUnlinkedNotes(nodes, [], "root")).toEqual([ { id: "root" } ]);++ // A root that isn't among the nodes (a search note removes itself) doesn't conjure one up.+ expect(dropUnlinkedNotes(nodes, [], "missing")).toEqual([]);+ });+});diff --git a/apps/client/src/widgets/note_map/data.ts b/apps/client/src/widgets/note_map/data.tsindex 1f54f66b31..2b3367a544 100644--- a/apps/client/src/widgets/note_map/data.ts+++ b/apps/client/src/widgets/note_map/data.ts@@ -36,20 +36,33 @@ export interface NotesAndRelationsData {noteIdToSizeMap: Record<string, number>;}-export async function loadNotesAndRelations(mapRootNoteId: string, excludeRelations: string[], includeRelations: string[], mapType: MapType): Promise<NotesAndRelationsData> {+/**+ * @param hideUnlinkedNotes drops the notes that no relation touches from a link map, keeping only+ * the map root itself. The link map's nodes are the root's whole subtree+ * while its edges are relations only, so every descendant without a+ * relation is drawn as a loose dot — and still pushes the rest of the graph+ * around through the charge force. Worth hiding in a small local view of+ * one note; the full-size maps keep the subtree their users expect of them.+ */+export async function loadNotesAndRelations(mapRootNoteId: string, excludeRelations: string[], includeRelations: string[], mapType: MapType, hideUnlinkedNotes = false): Promise<NotesAndRelationsData> {const resp = await server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, {excludeRelations, includeRelations});const noteIdToSizeMap = calculateNodeSizes(resp, mapType);const links = getGroupedLinks(resp.links);- const nodes = resp.notes.map(([noteId, title, type, color]) => ({+ let nodes = resp.notes.map(([noteId, title, type, color]) => ({id: noteId,name: title,type: type,color: color}));+ // A tree map links every node to its parent, so it has no unlinked notes to speak of.+ if (hideUnlinkedNotes && mapType === "link") {+ nodes = dropUnlinkedNotes(nodes, links, mapRootNoteId);+ }+return {noteIdToSizeMap,nodes,@@ -62,6 +75,16 @@ export async function loadNotesAndRelations(mapRootNoteId: string, excludeRelati};}+/**+ * Keeps only the notes some relation touches, plus the map root itself — a note with no relations at+ * all is still worth showing as itself, rather than as an empty map.+ */+export function dropUnlinkedNotes<T extends { id: string }>(nodes: T[], links: GroupedLink[], mapRootNoteId: string) {+ const linkedNoteIds = new Set(links.flatMap((link) => [ link.sourceNoteId, link.targetNoteId ]));++ return nodes.filter((node) => node.id === mapRootNoteId || linkedNoteIds.has(node.id));+}+function calculateNodeSizes(resp: NoteMapPostResponse, mapType: MapType) {const noteIdToSizeMap: Record<string, number> = {};diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.tsindex f0242556cc..6ce68f524d 100644--- a/apps/client/src/widgets/note_map/rendering.ts+++ b/apps/client/src/widgets/note_map/rendering.ts@@ -1,7 +1,7 @@import type ForceGraph from "force-graph";import { NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";import { LinkObject, NodeObject } from "force-graph";-import { generateColorFromString, MapType, NoteMapWidgetMode } from "./utils";+import { generateColorFromString, isRootedAtCurrentNote, MapType, NoteMapWidgetMode } from "./utils";import { escapeHtml } from "../../services/utils";import FNote from "../../entities/fnote";@@ -38,7 +38,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOfunction getColorForNode(node: NoteMapNodeObject) {if (node.color) {return node.color;- } else if (widgetMode === "ribbon" && node.id === noteId) {+ } else if (isRootedAtCurrentNote(widgetMode) && node.id === noteId) {return "red"; // subtree root mark as red} else {return generateColorFromString(node.type, themeStyle);@@ -211,7 +211,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO* @returns a teardown function to call when the graph is discarded.*/function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, container: HTMLElement, { note, noteId, widgetMode, notesAndRelations }: Pick<RenderData, "note" | "noteId" | "widgetMode" | "notesAndRelations">) {- const framedNoteIds = (widgetMode === "ribbon" && note?.type !== "search")+ const framedNoteIds = (isRootedAtCurrentNote(widgetMode) && note?.type !== "search")? getSubGraphConnectedToCurrentNote(noteId, notesAndRelations): getNoteIdsWithLinks(notesAndRelations);@@ -220,7 +220,7 @@ function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, cconst nodeFilter = framedNoteIds.size > 1? (node: NoteMapNodeObject) => framedNoteIds.has(node.id): undefined;- const padding = widgetMode === "ribbon" ? 50 : 30;+ const padding = isRootedAtCurrentNote(widgetMode) ? 50 : 30;// Panning or zooming hands the view over to the user for good — re-fitting under their fingers// would make the map impossible to explore while it is still settling.diff --git a/apps/client/src/widgets/note_map/utils.ts b/apps/client/src/widgets/note_map/utils.tsindex 923b5cb001..25996e9fcd 100644--- a/apps/client/src/widgets/note_map/utils.ts+++ b/apps/client/src/widgets/note_map/utils.ts@@ -1,6 +1,11 @@-export type NoteMapWidgetMode = "ribbon" | "hoisted" | "type";+export type NoteMapWidgetMode = "ribbon" | "sidebar" | "hoisted" | "type";export type MapType = "tree" | "link";+/** Whether the map is rooted at the note being read, rather than at a configured or hoisted note. */+export function isRootedAtCurrentNote(widgetMode: NoteMapWidgetMode) {+ return widgetMode === "ribbon" || widgetMode === "sidebar";+}+export function rgb2hex(rgb: string) {return `#${(rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/) || []).slice(1)diff --git a/apps/client/src/widgets/sidebar/NoteMap.tsx b/apps/client/src/widgets/sidebar/NoteMap.tsxindex 46d326e3ee..14abbc9fb3 100644--- a/apps/client/src/widgets/sidebar/NoteMap.tsx+++ b/apps/client/src/widgets/sidebar/NoteMap.tsx@@ -17,10 +17,11 @@ export default function NoteMap() {<RightPanelWidget id="noteMap" title={t("note_map.title")}>{note && (<div class="sidebar-note-map" ref={containerRef}>- {/* "ribbon" mode roots the map at the note being read, which is what a+ {/* "sidebar" mode roots the map at the note being read, which is what aconnections panel is about (the other modes root it at a configured- or hoisted note). */}- <NoteMapEl note={note} widgetMode="ribbon" parentRef={containerRef} />+ or hoisted note), and drops the notes nothing links to — see+ loadNotesAndRelations. */}+ <NoteMapEl note={note} widgetMode="sidebar" parentRef={containerRef} /></div>)}</RightPanelWidget>