Skip to content

Build your personal knowledge base with Trilium Notes

chore(core): integrate the rest of the note map route

Elian Doran5fec715e3f32
diff --git a/apps/server/package.json b/apps/server/package.json
index 87b6c3f880..7b71677113 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -32,7 +32,6 @@
"dependencies": {
"better-sqlite3": "12.8.0",
"html-to-text": "9.0.5",
- "node-html-parser": "7.1.0",
"sucrase": "3.35.1"
},
"devDependencies": {
diff --git a/apps/server/src/routes/api/note_map.ts b/apps/server/src/routes/api/note_map.ts
deleted file mode 100644
index fa941b884c..0000000000
--- a/apps/server/src/routes/api/note_map.ts
+++ /dev/null
@@ -1,383 +0,0 @@
-import { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/commons";
-import type { Request } from "express";
-import { HTMLElement, parse, TextNode } from "node-html-parser";
-
-import becca from "../../becca/becca.js";
-import type BAttribute from "../../becca/entities/battribute.js";
-import type BNote from "../../becca/entities/bnote.js";
-
-interface TreeLink {
- sourceNoteId: string;
- targetNoteId: string;
-}
-
-function buildDescendantCountMap(noteIdsToCount: string[]) {
- if (!Array.isArray(noteIdsToCount)) {
- throw new Error("noteIdsToCount: type error");
- }
-
- const noteIdToCountMap = Object.create(null);
-
- function getCount(noteId: string) {
- if (!(noteId in noteIdToCountMap)) {
- const note = becca.getNote(noteId);
- if (!note) {
- return;
- }
-
- const hiddenImageNoteIds = note.getRelations("imageLink").map((rel) => rel.value);
- const childNoteIds = note.children.map((child) => child.noteId);
- const nonHiddenNoteIds = childNoteIds.filter((childNoteId) => !hiddenImageNoteIds.includes(childNoteId));
-
- noteIdToCountMap[noteId] = nonHiddenNoteIds.length;
-
- for (const child of note.children) {
- noteIdToCountMap[noteId] += getCount(child.noteId);
- }
- }
-
- return noteIdToCountMap[noteId];
- }
- noteIdsToCount.forEach((noteId) => {
- getCount(noteId);
- });
-
- return noteIdToCountMap;
-}
-function getNeighbors(note: BNote, depth: number): string[] {
- if (depth === 0) {
- return [];
- }
-
- const retNoteIds: string[] = [];
-
- function isIgnoredRelation(relation: BAttribute) {
- return ["relationMapLink", "template", "inherit", "image", "ancestor"].includes(relation.name);
- }
-
- // forward links
- for (const relation of note.getRelations()) {
- if (isIgnoredRelation(relation)) {
- continue;
- }
-
- const targetNote = relation.getTargetNote();
-
- if (!targetNote || targetNote.isLabelTruthy("excludeFromNoteMap")) {
- continue;
- }
-
- retNoteIds.push(targetNote.noteId);
-
- for (const noteId of getNeighbors(targetNote, depth - 1)) {
- retNoteIds.push(noteId);
- }
- }
-
- // backward links
- for (const relation of note.getTargetRelations()) {
- if (isIgnoredRelation(relation)) {
- continue;
- }
-
- const sourceNote = relation.getNote();
-
- if (!sourceNote || sourceNote.isLabelTruthy("excludeFromNoteMap")) {
- continue;
- }
-
- retNoteIds.push(sourceNote.noteId);
-
- for (const noteId of getNeighbors(sourceNote, depth - 1)) {
- retNoteIds.push(noteId);
- }
- }
-
- return retNoteIds;
-}
-
-function getLinkMap(req: Request<{ noteId: string }>) {
- const mapRootNote = becca.getNoteOrThrow(req.params.noteId);
-
- // if the map root itself has "excludeFromNoteMap" attribute (journal typically) then there wouldn't be anything
- // to display, so we'll just ignore it
- const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");
- let unfilteredNotes;
-
- const toSet = (data: unknown) => new Set<string>(data instanceof Array ? data : []);
-
- const excludeRelations = toSet(req.body.excludeRelations);
- const includeRelations = toSet(req.body.includeRelations);
-
- if (mapRootNote.type === "search") {
- // for search notes, we want to consider the direct search results only without the descendants
- unfilteredNotes = mapRootNote.getSearchResultNotes();
- } else {
- unfilteredNotes = mapRootNote.getSubtree({
- includeArchived: false,
- resolveSearch: true,
- includeHidden: mapRootNote.isInHiddenSubtree()
- }).notes;
- }
-
- const noteIds = new Set<string>(unfilteredNotes.filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap")).map((note) => note.noteId));
-
- if (mapRootNote.type === "search") {
- noteIds.delete(mapRootNote.noteId);
- }
-
- for (const noteId of getNeighbors(mapRootNote, 3)) {
- noteIds.add(noteId);
- }
-
- const noteIdsArray = Array.from(noteIds);
-
- const notes = noteIdsArray.map((noteId) => {
- const note = becca.getNoteOrThrow(noteId);
-
- return [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")];
- });
-
- const links = Object.values(becca.attributes)
- .filter((rel) => {
- if (rel.type !== "relation" || rel.name === "relationMapLink" || rel.name === "template" || rel.name === "inherit") {
- return false;
- } else if (!noteIds.has(rel.noteId) || !noteIds.has(rel.value)) {
- return false;
- } else if (rel.name === "imageLink") {
- const parentNote = becca.getNote(rel.noteId);
- if (!parentNote) {
- return false;
- }
-
- return !parentNote.getChildNotes().find((childNote) => childNote.noteId === rel.value);
- } else if (includeRelations.size != 0 && !includeRelations.has(rel.name)) {
- return false;
- } else if (excludeRelations.has(rel.name)) {
- return false;
- }
- return true;
-
- })
- .map((rel) => ({
- id: `${rel.noteId}-${rel.name}-${rel.value}`,
- sourceNoteId: rel.noteId,
- targetNoteId: rel.value,
- name: rel.name
- }));
-
- return {
- notes,
- noteIdToDescendantCountMap: buildDescendantCountMap(noteIdsArray),
- links
- };
-}
-
-function getTreeMap(req: Request<{ noteId: string }>) {
- const mapRootNote = becca.getNoteOrThrow(req.params.noteId);
- // if the map root itself has "excludeFromNoteMap" (journal typically) then there wouldn't be anything to display,
- // so we'll just ignore it
- const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");
- const subtree = mapRootNote.getSubtree({
- includeArchived: false,
- resolveSearch: true,
- includeHidden: mapRootNote.isInHiddenSubtree()
- });
-
- const notes = subtree.notes
- .filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap"))
- .filter((note) => {
- if (note.type !== "image" || note.getChildNotes().length > 0) {
- return true;
- }
-
- const imageLinkRelation = note.getTargetRelations().find((rel) => rel.name === "imageLink");
-
- if (!imageLinkRelation) {
- return true;
- }
-
- return !note.getParentNotes().find((parentNote) => parentNote.noteId === imageLinkRelation.noteId);
- })
- .map((note) => [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")]);
-
- const noteIds = new Set<string>();
- notes.forEach(([noteId]) => noteId && noteIds.add(noteId));
-
- const links: TreeLink[] = [];
-
- for (const { parentNoteId, childNoteId } of subtree.relationships) {
- if (!noteIds.has(parentNoteId) || !noteIds.has(childNoteId)) {
- continue;
- }
-
- links.push({
- sourceNoteId: parentNoteId,
- targetNoteId: childNoteId
- });
- }
-
- const noteIdToDescendantCountMap = buildDescendantCountMap(Array.from(noteIds));
-
- updateDescendantCountMapForSearch(noteIdToDescendantCountMap, subtree.relationships);
-
- return {
- notes,
- noteIdToDescendantCountMap,
- links
- };
-}
-
-function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<string, number>, relationships: { parentNoteId: string; childNoteId: string }[]) {
- for (const { parentNoteId, childNoteId } of relationships) {
- const parentNote = becca.notes[parentNoteId];
- if (!parentNote || parentNote.type !== "search") {
- continue;
- }
-
- noteIdToDescendantCountMap[parentNote.noteId] = noteIdToDescendantCountMap[parentNoteId] || 0;
- noteIdToDescendantCountMap[parentNote.noteId] += noteIdToDescendantCountMap[childNoteId] || 1;
- }
-}
-
-function removeImages(document: HTMLElement) {
- const images = document.getElementsByTagName("img");
- for (const image of images) {
- image.remove();
- }
-}
-
-const EXCERPT_CHAR_LIMIT = 200;
-type ElementOrText = HTMLElement | TextNode;
-
-export function findExcerpts(sourceNote: BNote, referencedNoteId: string) {
- const html = sourceNote.getContent();
- const document = parse(html.toString());
-
- const excerpts: string[] = [];
-
- removeImages(document);
-
- for (const linkEl of document.querySelectorAll("a")) {
- console.log("Got ", linkEl.innerHTML);
- const href = linkEl.getAttribute("href");
-
- if (!href || !href.endsWith(referencedNoteId)) {
- continue;
- }
-
- linkEl.classList.add("backlink-link");
-
- let centerEl: HTMLElement = linkEl;
-
- while (centerEl.tagName !== "BODY" && centerEl.parentNode && (centerEl.parentNode?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {
- centerEl = centerEl.parentNode;
- }
-
- const excerptEls: ElementOrText[] = [centerEl];
- let excerptLength = centerEl.textContent?.length || 0;
- let left: ElementOrText = centerEl;
- let right: ElementOrText = centerEl;
-
- while (excerptLength < EXCERPT_CHAR_LIMIT) {
- let added = false;
-
- const prev: HTMLElement | null = left.previousElementSibling;
-
- if (prev) {
- const prevText = prev.textContent || "";
-
- if (prevText.length + excerptLength > EXCERPT_CHAR_LIMIT) {
- const prefix = prevText.substr(prevText.length - (EXCERPT_CHAR_LIMIT - excerptLength));
-
- const textNode = new TextNode(`…${prefix}`);
- excerptEls.unshift(textNode);
-
- break;
- }
-
- left = prev;
- excerptEls.unshift(left);
- excerptLength += prevText.length;
- added = true;
- }
-
- const next: HTMLElement | null = right.nextElementSibling;
-
- if (next) {
- const nextText = next.textContent;
-
- if (nextText && nextText.length + excerptLength > EXCERPT_CHAR_LIMIT) {
- const suffix = nextText.substr(nextText.length - (EXCERPT_CHAR_LIMIT - excerptLength));
-
- const textNode = new TextNode(`${suffix}…`);
- excerptEls.push(textNode);
-
- break;
- }
-
- right = next;
- excerptEls.push(right);
- excerptLength += nextText?.length || 0;
- added = true;
- }
-
- if (!added) {
- break;
- }
- }
-
- const excerptWrapper = new HTMLElement("div", {});
- excerptWrapper.classList.add("ck-content");
- excerptWrapper.classList.add("backlink-excerpt");
-
- for (const childEl of excerptEls) {
- excerptWrapper.appendChild(childEl);
- }
-
- excerpts.push(excerptWrapper.outerHTML);
- }
- return excerpts;
-}
-
-// TODO: Deduplicate with core
-function getFilteredBacklinks(note: BNote): BAttribute[] {
- return (
- note
- .getTargetRelations()
- // search notes have "ancestor" relations which are not interesting
- .filter((relation) => !!relation.getNote() && relation.getNote().type !== "search")
- );
-}
-
-function getBacklinks(req: Request<{ noteId: string }>): BacklinksResponse {
- const { noteId } = req.params;
- const note = becca.getNoteOrThrow(noteId);
-
- let backlinksWithExcerptCount = 0;
-
- return getFilteredBacklinks(note).map((backlink) => {
- const sourceNote = backlink.note;
-
- if (sourceNote.type !== "text" || backlinksWithExcerptCount > 50) {
- return {
- noteId: sourceNote.noteId,
- relationName: backlink.name
- } satisfies BacklinksResponse[number];
- }
-
- backlinksWithExcerptCount++;
-
- const excerpts = findExcerpts(sourceNote, noteId);
- return {
- noteId: sourceNote.noteId,
- excerpts
- } satisfies BacklinksResponse[number];
- });
-}
-
-export default {
- getLinkMap,
- getTreeMap,
- getBacklinks
-};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index d2bb246041..edb17af7a9 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -28,7 +28,6 @@ import fontsRoute from "./api/fonts.js";
import importRoute from "./api/import.js";
import loginApiRoute from "./api/login.js";
import metricsRoute from "./api/metrics.js";
-import noteMapRoute from "./api/note_map.js";
import otherRoute from "./api/other.js";
import passwordApiRoute from "./api/password.js";
import recoveryCodes from './api/recovery_codes.js';
@@ -210,10 +209,6 @@ function register(app: express.Application) {
apiRoute(PST, "/api/other/render-markdown", otherRoute.renderMarkdown);
apiRoute(PST, "/api/other/to-markdown", otherRoute.toMarkdown);
- apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);
- apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);
- apiRoute(GET, "/api/note-map/:noteId/backlinks", noteMapRoute.getBacklinks);
-
shareRoutes.register(router);
etapiAuthRoutes.register(router, [loginRateLimiter]);
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 629b09e34c..1adcbe58c3 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -9,13 +9,14 @@
"dependencies": {
"@braintree/sanitize-url": "7.1.1",
"@triliumnext/commons": "workspace:*",
+ "async-mutex": "0.5.0",
"escape-html": "1.0.3",
"i18next": "25.10.3",
"mime-types": "3.0.2",
+ "node-html-parser": "7.1.0",
"sanitize-filename": "1.6.4",
"sanitize-html": "2.17.2",
- "unescape": "1.0.1",
- "async-mutex": "0.5.0"
+ "unescape": "1.0.1"
},
"devDependencies": {
"@types/escape-html": "1.0.4",
diff --git a/apps/server/src/routes/api/note_map.spec.ts b/packages/trilium-core/src/routes/api/note_map.spec.ts
similarity index 100%
rename from apps/server/src/routes/api/note_map.spec.ts
rename to packages/trilium-core/src/routes/api/note_map.spec.ts
diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.ts
index d42e989588..603cfa8033 100644
--- a/packages/trilium-core/src/routes/api/note_map.ts
+++ b/packages/trilium-core/src/routes/api/note_map.ts
@@ -1,8 +1,343 @@
-import type { Request } from "express";
import BAttribute from "../../becca/entities/battribute";
import BNote from "../../becca/entities/bnote";
import becca from "../../becca/becca";
-import type { BacklinkCountResponse } from "@triliumnext/commons";
+import type { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/commons";
+import type { Request } from "express";
+import { HTMLElement, parse, TextNode } from "node-html-parser";
+
+interface TreeLink {
+ sourceNoteId: string;
+ targetNoteId: string;
+}
+
+function buildDescendantCountMap(noteIdsToCount: string[]) {
+ if (!Array.isArray(noteIdsToCount)) {
+ throw new Error("noteIdsToCount: type error");
+ }
+
+ const noteIdToCountMap = Object.create(null);
+
+ function getCount(noteId: string) {
+ if (!(noteId in noteIdToCountMap)) {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return;
+ }
+
+ const hiddenImageNoteIds = note.getRelations("imageLink").map((rel) => rel.value);
+ const childNoteIds = note.children.map((child) => child.noteId);
+ const nonHiddenNoteIds = childNoteIds.filter((childNoteId) => !hiddenImageNoteIds.includes(childNoteId));
+
+ noteIdToCountMap[noteId] = nonHiddenNoteIds.length;
+
+ for (const child of note.children) {
+ noteIdToCountMap[noteId] += getCount(child.noteId);
+ }
+ }
+
+ return noteIdToCountMap[noteId];
+ }
+ noteIdsToCount.forEach((noteId) => {
+ getCount(noteId);
+ });
+
+ return noteIdToCountMap;
+}
+function getNeighbors(note: BNote, depth: number): string[] {
+ if (depth === 0) {
+ return [];
+ }
+
+ const retNoteIds: string[] = [];
+
+ function isIgnoredRelation(relation: BAttribute) {
+ return ["relationMapLink", "template", "inherit", "image", "ancestor"].includes(relation.name);
+ }
+
+ // forward links
+ for (const relation of note.getRelations()) {
+ if (isIgnoredRelation(relation)) {
+ continue;
+ }
+
+ const targetNote = relation.getTargetNote();
+
+ if (!targetNote || targetNote.isLabelTruthy("excludeFromNoteMap")) {
+ continue;
+ }
+
+ retNoteIds.push(targetNote.noteId);
+
+ for (const noteId of getNeighbors(targetNote, depth - 1)) {
+ retNoteIds.push(noteId);
+ }
+ }
+
+ // backward links
+ for (const relation of note.getTargetRelations()) {
+ if (isIgnoredRelation(relation)) {
+ continue;
+ }
+
+ const sourceNote = relation.getNote();
+
+ if (!sourceNote || sourceNote.isLabelTruthy("excludeFromNoteMap")) {
+ continue;
+ }
+
+ retNoteIds.push(sourceNote.noteId);
+
+ for (const noteId of getNeighbors(sourceNote, depth - 1)) {
+ retNoteIds.push(noteId);
+ }
+ }
+
+ return retNoteIds;
+}
+
+function getLinkMap(req: Request<{ noteId: string }>) {
+ const mapRootNote = becca.getNoteOrThrow(req.params.noteId);
+
+ // if the map root itself has "excludeFromNoteMap" attribute (journal typically) then there wouldn't be anything
+ // to display, so we'll just ignore it
+ const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");
+ let unfilteredNotes;
+
+ const toSet = (data: unknown) => new Set<string>(data instanceof Array ? data : []);
+
+ const excludeRelations = toSet(req.body.excludeRelations);
+ const includeRelations = toSet(req.body.includeRelations);
+
+ if (mapRootNote.type === "search") {
+ // for search notes, we want to consider the direct search results only without the descendants
+ unfilteredNotes = mapRootNote.getSearchResultNotes();
+ } else {
+ unfilteredNotes = mapRootNote.getSubtree({
+ includeArchived: false,
+ resolveSearch: true,
+ includeHidden: mapRootNote.isInHiddenSubtree()
+ }).notes;
+ }
+
+ const noteIds = new Set<string>(unfilteredNotes.filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap")).map((note) => note.noteId));
+
+ if (mapRootNote.type === "search") {
+ noteIds.delete(mapRootNote.noteId);
+ }
+
+ for (const noteId of getNeighbors(mapRootNote, 3)) {
+ noteIds.add(noteId);
+ }
+
+ const noteIdsArray = Array.from(noteIds);
+
+ const notes = noteIdsArray.map((noteId) => {
+ const note = becca.getNoteOrThrow(noteId);
+
+ return [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")];
+ });
+
+ const links = Object.values(becca.attributes)
+ .filter((rel) => {
+ if (rel.type !== "relation" || rel.name === "relationMapLink" || rel.name === "template" || rel.name === "inherit") {
+ return false;
+ } else if (!noteIds.has(rel.noteId) || !noteIds.has(rel.value)) {
+ return false;
+ } else if (rel.name === "imageLink") {
+ const parentNote = becca.getNote(rel.noteId);
+ if (!parentNote) {
+ return false;
+ }
+
+ return !parentNote.getChildNotes().find((childNote) => childNote.noteId === rel.value);
+ } else if (includeRelations.size != 0 && !includeRelations.has(rel.name)) {
+ return false;
+ } else if (excludeRelations.has(rel.name)) {
+ return false;
+ }
+ return true;
+
+ })
+ .map((rel) => ({
+ id: `${rel.noteId}-${rel.name}-${rel.value}`,
+ sourceNoteId: rel.noteId,
+ targetNoteId: rel.value,
+ name: rel.name
+ }));
+
+ return {
+ notes,
+ noteIdToDescendantCountMap: buildDescendantCountMap(noteIdsArray),
+ links
+ };
+}
+
+function getTreeMap(req: Request<{ noteId: string }>) {
+ const mapRootNote = becca.getNoteOrThrow(req.params.noteId);
+ // if the map root itself has "excludeFromNoteMap" (journal typically) then there wouldn't be anything to display,
+ // so we'll just ignore it
+ const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");
+ const subtree = mapRootNote.getSubtree({
+ includeArchived: false,
+ resolveSearch: true,
+ includeHidden: mapRootNote.isInHiddenSubtree()
+ });
+
+ const notes = subtree.notes
+ .filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap"))
+ .filter((note) => {
+ if (note.type !== "image" || note.getChildNotes().length > 0) {
+ return true;
+ }
+
+ const imageLinkRelation = note.getTargetRelations().find((rel) => rel.name === "imageLink");
+
+ if (!imageLinkRelation) {
+ return true;
+ }
+
+ return !note.getParentNotes().find((parentNote) => parentNote.noteId === imageLinkRelation.noteId);
+ })
+ .map((note) => [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")]);
+
+ const noteIds = new Set<string>();
+ notes.forEach(([noteId]) => noteId && noteIds.add(noteId));
+
+ const links: TreeLink[] = [];
+
+ for (const { parentNoteId, childNoteId } of subtree.relationships) {
+ if (!noteIds.has(parentNoteId) || !noteIds.has(childNoteId)) {
+ continue;
+ }
+
+ links.push({
+ sourceNoteId: parentNoteId,
+ targetNoteId: childNoteId
+ });
+ }
+
+ const noteIdToDescendantCountMap = buildDescendantCountMap(Array.from(noteIds));
+
+ updateDescendantCountMapForSearch(noteIdToDescendantCountMap, subtree.relationships);
+
+ return {
+ notes,
+ noteIdToDescendantCountMap,
+ links
+ };
+}
+
+function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<string, number>, relationships: { parentNoteId: string; childNoteId: string }[]) {
+ for (const { parentNoteId, childNoteId } of relationships) {
+ const parentNote = becca.notes[parentNoteId];
+ if (!parentNote || parentNote.type !== "search") {
+ continue;
+ }
+
+ noteIdToDescendantCountMap[parentNote.noteId] = noteIdToDescendantCountMap[parentNoteId] || 0;
+ noteIdToDescendantCountMap[parentNote.noteId] += noteIdToDescendantCountMap[childNoteId] || 1;
+ }
+}
+
+function removeImages(document: HTMLElement) {
+ const images = document.getElementsByTagName("img");
+ for (const image of images) {
+ image.remove();
+ }
+}
+
+const EXCERPT_CHAR_LIMIT = 200;
+type ElementOrText = HTMLElement | TextNode;
+
+export function findExcerpts(sourceNote: BNote, referencedNoteId: string) {
+ const html = sourceNote.getContent();
+ const document = parse(html.toString());
+
+ const excerpts: string[] = [];
+
+ removeImages(document);
+
+ for (const linkEl of document.querySelectorAll("a")) {
+ console.log("Got ", linkEl.innerHTML);
+ const href = linkEl.getAttribute("href");
+
+ if (!href || !href.endsWith(referencedNoteId)) {
+ continue;
+ }
+
+ linkEl.classList.add("backlink-link");
+
+ let centerEl: HTMLElement = linkEl;
+
+ while (centerEl.tagName !== "BODY" && centerEl.parentNode && (centerEl.parentNode?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {
+ centerEl = centerEl.parentNode;
+ }
+
+ const excerptEls: ElementOrText[] = [centerEl];
+ let excerptLength = centerEl.textContent?.length || 0;
+ let left: ElementOrText = centerEl;
+ let right: ElementOrText = centerEl;
+
+ while (excerptLength < EXCERPT_CHAR_LIMIT) {
+ let added = false;
+
+ const prev: HTMLElement | null = left.previousElementSibling;
+
+ if (prev) {
+ const prevText = prev.textContent || "";
+
+ if (prevText.length + excerptLength > EXCERPT_CHAR_LIMIT) {
+ const prefix = prevText.substr(prevText.length - (EXCERPT_CHAR_LIMIT - excerptLength));
+
+ const textNode = new TextNode(`…${prefix}`);
+ excerptEls.unshift(textNode);
+
+ break;
+ }
+
+ left = prev;
+ excerptEls.unshift(left);
+ excerptLength += prevText.length;
+ added = true;
+ }
+
+ const next: HTMLElement | null = right.nextElementSibling;
+
+ if (next) {
+ const nextText = next.textContent;
+
+ if (nextText && nextText.length + excerptLength > EXCERPT_CHAR_LIMIT) {
+ const suffix = nextText.substr(nextText.length - (EXCERPT_CHAR_LIMIT - excerptLength));
+
+ const textNode = new TextNode(`${suffix}…`);
+ excerptEls.push(textNode);
+
+ break;
+ }
+
+ right = next;
+ excerptEls.push(right);
+ excerptLength += nextText?.length || 0;
+ added = true;
+ }
+
+ if (!added) {
+ break;
+ }
+ }
+
+ const excerptWrapper = new HTMLElement("div", {});
+ excerptWrapper.classList.add("ck-content");
+ excerptWrapper.classList.add("backlink-excerpt");
+
+ for (const childEl of excerptEls) {
+ excerptWrapper.appendChild(childEl);
+ }
+
+ excerpts.push(excerptWrapper.outerHTML);
+ }
+ return excerpts;
+}
function getFilteredBacklinks(note: BNote): BAttribute[] {
return (
@@ -13,7 +348,33 @@ function getFilteredBacklinks(note: BNote): BAttribute[] {
);
}
-function getBacklinkCount(req: Request) {
+function getBacklinks(req: Request<{ noteId: string }>): BacklinksResponse {
+ const { noteId } = req.params;
+ const note = becca.getNoteOrThrow(noteId);
+
+ let backlinksWithExcerptCount = 0;
+
+ return getFilteredBacklinks(note).map((backlink) => {
+ const sourceNote = backlink.note;
+
+ if (sourceNote.type !== "text" || backlinksWithExcerptCount > 50) {
+ return {
+ noteId: sourceNote.noteId,
+ relationName: backlink.name
+ } satisfies BacklinksResponse[number];
+ }
+
+ backlinksWithExcerptCount++;
+
+ const excerpts = findExcerpts(sourceNote, noteId);
+ return {
+ noteId: sourceNote.noteId,
+ excerpts
+ } satisfies BacklinksResponse[number];
+ });
+}
+
+function getBacklinkCount(req: Request<{ noteId: string }>): BacklinkCountResponse {
const { noteId } = req.params;
const note = becca.getNoteOrThrow(noteId);
@@ -24,5 +385,8 @@ function getBacklinkCount(req: Request) {
}
export default {
+ getLinkMap,
+ getTreeMap,
+ getBacklinks,
getBacklinkCount
-}
+};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index ed088aa1a6..22feecddeb 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -166,6 +166,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);
apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);
+ apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);
+ apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);
+ apiRoute(GET, "/api/note-map/:noteId/backlinks", noteMapRoute.getBacklinks);
apiRoute(GET, "/api/note-map/:noteId/backlink-count", noteMapRoute.getBacklinkCount);
apiRoute(PST, "/api/recent-notes", recentNotesRoute.addRecentNote);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 631aaa6752..7ab86f9c63 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -772,9 +772,6 @@ importers:
html-to-text:
specifier: 9.0.5
version: 9.0.5
- node-html-parser:
- specifier: 7.1.0
- version: 7.1.0
sucrase:
specifier: 3.35.1
version: 3.35.1
@@ -1716,6 +1713,9 @@ importers:
mime-types:
specifier: 3.0.2
version: 3.0.2
+ node-html-parser:
+ specifier: 7.1.0
+ version: 7.1.0
sanitize-filename:
specifier: 1.6.4
version: 1.6.4
@@ -17665,6 +17665,8 @@ snapshots:
'@ckeditor/ckeditor5-widget': 47.6.1
ckeditor5: 47.6.1
es-toolkit: 1.39.5
+ transitivePeerDependencies:
+ - supports-color
'@ckeditor/[email protected]': {}
@@ -17682,6 +17684,8 @@ snapshots:
'@ckeditor/ckeditor5-widget': 47.6.1
ckeditor5: 47.6.1
es-toolkit: 1.39.5
+ transitivePeerDependencies:
+ - supports-color
'@ckeditor/[email protected]':
dependencies:
@@ -17829,8 +17833,6 @@ snapshots:
'@ckeditor/ckeditor5-ui': 47.6.1
'@ckeditor/ckeditor5-utils': 47.6.1
ckeditor5: 47.6.1
- transitivePeerDependencies:
- - supports-color
'@ckeditor/[email protected]':
dependencies: