Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): relate a map to the notes its nodes link to

Elian Doranf80b453202db
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 0708f17aec..a3b2588f12 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -1,4 +1,4 @@
-import { BAttribute, becca, becca_easy_mocking, checkImageAttachments, collectCanvasImageFileIds, findBookmarks, findLlmChatLinks, saveLinks } from "@triliumnext/core";
+import { BAttribute, becca, becca_easy_mocking, checkImageAttachments, collectCanvasImageFileIds, findBookmarks, findLlmChatLinks, findMindMapLinks, saveLinks } from "@triliumnext/core";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { randomString } from "./utils.js";
@@ -737,6 +737,63 @@ describe("saveLinks", () => {
});
});
+describe("findMindMapLinks", () => {
+ type FoundLink = { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string };
+
+ /** A map whose nodes carry the given links, one per node, nested a level deep. */
+ function buildMap(...links: (string | undefined)[]) {
+ const [ rootLink, ...childLinks ] = links;
+ return JSON.stringify({
+ nodeData: {
+ id: "root",
+ topic: "Root",
+ hyperLink: rootLink,
+ children: childLinks.map((hyperLink, index) => ({
+ id: `n${index}`,
+ topic: `Node ${index}`,
+ hyperLink,
+ children: []
+ }))
+ }
+ });
+ }
+
+ it("collects the notes the nodes link to, wherever in the map they sit", () => {
+ const links: FoundLink[] = [];
+
+ findMindMapLinks(buildMap("#root/abc123", "#root/parent/def456", undefined, "#root"), links);
+
+ expect(links).toEqual([
+ { name: "internalLink", value: "abc123" },
+ // The whole path is stored, but it is the note at the end of it that is linked.
+ { name: "internalLink", value: "def456" },
+ { name: "internalLink", value: "root" }
+ ]);
+ });
+
+ it("takes nothing from a node pointing outside Trilium", () => {
+ const links: FoundLink[] = [];
+
+ findMindMapLinks(buildMap(
+ "https://example.com",
+ "mailto:[email protected]",
+ // An address of its own that happens to carry a note path is still a page elsewhere.
+ "https://example.com/#root/abc123"
+ ), links);
+
+ expect(links).toEqual([]);
+ });
+
+ it("survives content it cannot read", () => {
+ const links: FoundLink[] = [];
+
+ findMindMapLinks("not valid json", links);
+ findMindMapLinks(JSON.stringify({ nodeData: { id: "root", hyperLink: 42 } }), links);
+
+ expect(links).toEqual([]);
+ });
+});
+
describe("findLlmChatLinks", () => {
it("extracts wiki-links from assistant text blocks", () => {
const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index fab709fea1..ae67bb9d25 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -92,7 +92,7 @@ export { default as SearchContext } from "./services/search/search_context";
export { default as search, } from "./services/search/services/search";
export { type default as SearchResult } from "./services/search/search_result";
export { type SearchParams } from "./services/search/services/types";
-export { checkImageAttachments, collectCanvasImageFileIds, default as note_service, findBookmarks, findLlmChatLinks, saveLinks } from "./services/notes";
+export { checkImageAttachments, collectCanvasImageFileIds, default as note_service, findBookmarks, findLlmChatLinks, findMindMapLinks, saveLinks } from "./services/notes";
export type { NoteParams } from "./services/notes";
export * as sanitize from "./services/sanitizer";
export * as routes from "./routes";
diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.ts
index 0025493247..7115e58fee 100644
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@ -390,6 +390,27 @@ describe("notes service (real DB)", () => {
expect(newContent).toContain(`attachmentId=${attachments[0].attachmentId}`);
expect(newContent).not.toContain("data:image/png;base64");
});
+
+ it("relates a mind map to the notes its nodes link to, and lets go of the ones dropped", () => {
+ const target = createNote("root", { title: "spec-map-target" });
+ const map = createNote("root", {
+ title: "spec-map",
+ type: "mindMap",
+ mime: "application/json",
+ content: `{"nodeData":{"id":"root","topic":"Root"}}`
+ });
+ const buildMap = (hyperLink: string) =>
+ JSON.stringify({ nodeData: { id: "root", topic: "Root", children: [{ id: "a", topic: "A", hyperLink }] } });
+
+ getContext().init(() => saveLinks(map.note, buildMap(`#root/${target.note.noteId}`)));
+
+ const relation = map.note.getRelations().find((r) => r.name === "internalLink");
+ expect(relation?.value).toBe(target.note.noteId);
+
+ // Pointed elsewhere, the node no longer relates the two notes.
+ getContext().init(() => saveLinks(map.note, buildMap("https://example.com")));
+ expect(map.note.getRelations().some((r) => r.name === "internalLink" && !r.isDeleted)).toBe(false);
+ });
});
describe("updateNoteData", () => {
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 02cf7b0141..98db221092 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -789,6 +789,60 @@ function findRelationMapLinks(content: string, foundLinks: FoundLink[]) {
}
}
+/**
+ * Collects the notes a mind map's nodes link to.
+ *
+ * A node carries one link of its own, which the editor writes as the in-app address a note link
+ * wears everywhere else (`#root/…`, see the client's `mind_map_links`); anything else is an address
+ * outside Trilium and is not a link between notes. The whole map is walked rather than only its
+ * nodes, so that a link stays found wherever Mind Elixir comes to keep one.
+ */
+export function findMindMapLinks(content: string, foundLinks: FoundLink[]) {
+ try {
+ collectMindMapLinks(JSON.parse(content), foundLinks);
+ } catch (e: any) {
+ getLog().error(`Could not scan for mind map links: ${e.message}`);
+ }
+}
+
+function collectMindMapLinks(value: unknown, foundLinks: FoundLink[]) {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ collectMindMapLinks(item, foundLinks);
+ }
+ return;
+ }
+
+ if (!value || typeof value !== "object") {
+ return;
+ }
+
+ const record = value as Record<string, unknown>;
+ const noteId = getMindMapLinkTarget(record.hyperLink);
+ if (noteId) {
+ foundLinks.push({
+ name: "internalLink",
+ value: noteId
+ });
+ }
+
+ for (const key of Object.keys(record)) {
+ collectMindMapLinks(record[key], foundLinks);
+ }
+}
+
+/**
+ * The note a link points at, or `null` where it points elsewhere. The whole value has to be the
+ * address, so that a page whose own address happens to carry `#root/…` is not read as a note.
+ */
+function getMindMapLinkTarget(link: unknown): string | null {
+ if (typeof link !== "string" || !/^#root(\/[a-zA-Z0-9_]+)*$/.test(link)) {
+ return null;
+ }
+
+ return link.split("/").at(-1)?.replace(/^#/, "") ?? null;
+}
+
const imageUrlToAttachmentIdMapping: Record<string, string> = {};
async function downloadImage(noteId: string, imageUrl: string) {
@@ -1039,9 +1093,9 @@ export function saveLinks(note: BNote, content: string | Uint8Array) {
// erasure. There are no Trilium internal links to extract from canvas content.
({ forceFrontendReload, content } = checkImageAttachments(note, content));
} else if (note.type === "mindMap" && typeof content === "string") {
+ findMindMapLinks(content, foundLinks);
// Mind map node images are stored as attachments referenced by URL from the map JSON; scan
- // for orphans (inserted-then-removed images) so they get scheduled for erasure. No Trilium
- // internal links are extracted from map content: a node's link is stored as a plain URL.
+ // for orphans (inserted-then-removed images) so they get scheduled for erasure.
({ forceFrontendReload, content } = checkImageAttachments(note, content));
} else if (note.type === "relationMap" && typeof content === "string") {
findRelationMapLinks(content, foundLinks);
@@ -1321,7 +1375,9 @@ function getUndeletedParentBranchIds(noteId: string, deleteId: string) {
}
function scanForLinks(note: BNote, content: string | Uint8Array) {
- if (!note || !["text", "relationMap"].includes(note.type)) {
+ // A mind map is scanned here as well as on save, so that one arriving by import carries its
+ // links to the notes it points at without having to be opened and edited first.
+ if (!note || !["text", "relationMap", "mindMap"].includes(note.type)) {
return;
}