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(share): draw a shared note map note with the app's note map
Elian Dorane25cda78cdcd
diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.tsindex ee01483e7f..6eaf116120 100644--- a/apps/client/src/services/froca-interface.ts+++ b/apps/client/src/services/froca-interface.ts@@ -1,3 +1,5 @@+import type { NoteMapPostResponse } from "@triliumnext/commons";+import type FAttachment from "../entities/fattachment.js";import type { FAttachmentRow } from "../entities/fattachment.js";import type FAttribute from "../entities/fattribute.js";@@ -9,6 +11,12 @@ import type { FBranchRow } from "../entities/fbranch.js";import type FNote from "../entities/fnote.js";import type { FNoteRow } from "../entities/fnote.js";+/** The relations a note map draws or leaves out, by name; an empty `includeRelations` draws all. */+export interface NoteMapFilters {+ excludeRelations: string[];+ includeRelations: string[];+}+/** The rows of notes with their branches and attributes, which `froca.addResp()` takes. */export interface SubtreeResponse {notes: FNoteRow[];@@ -29,6 +37,8 @@ export interface FrocaSource {getBlob(entityType: string, entityId: string): Promise<FBlobRow>;/** The ids of the notes below `ancestorNoteId` that match the search `query`. */searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;+ /** The notes and the links of the note map of `mapRootNoteId`, as a tree or as its relations. */+ getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;}export interface Froca {@@ -49,4 +59,5 @@ export interface Froca {getAttachmentsForNote(noteId: string): Promise<FAttachment[]>;searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;+ getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;}diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex 189a027637..4f8ba7cd10 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -1,11 +1,11 @@-import type { HighlightedTokenInfo } from "@triliumnext/commons";+import type { HighlightedTokenInfo, NoteMapPostResponse } from "@triliumnext/commons";import FAttachment, { type FAttachmentRow } from "../entities/fattachment.js";import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";import FBlob, { type FBlobRow } from "../entities/fblob.js";import FBranch, { type FBranchRow } from "../entities/fbranch.js";import FNote, { type FNoteRow } from "../entities/fnote.js";-import type { Froca, FrocaSource, SubtreeResponse } from "./froca-interface.js";+import type { Froca, FrocaSource, NoteMapFilters, SubtreeResponse } from "./froca-interface.js";import server from "./server.js";import { isPreAuthScreen } from "./utils.js";@@ -403,6 +403,10 @@ class FrocaImpl implements Froca {return this.source.searchNoteIds(query, ancestorNoteId);}+ getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters) {+ return this.source.getNoteMap(mapRootNoteId, mapType, filters);+ }+async getBlob(entityType: string, entityId: string): Promise<FBlob | null> {// I'm not sure why we're not using blobIds directly, it would save us this composite key ...// perhaps one benefit is that we're always requesting the latest blob, not relying on perhaps faulty/slow@@ -439,7 +443,9 @@ const SERVER_SOURCE: FrocaSource = {searchNoteIds: async (query) => {const { default: search } = await import("./search.js");return await search.searchForNoteIds(query);- }+ },+ getNoteMap: (mapRootNoteId, mapType, filters) =>+ server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters)};const froca = new FrocaImpl();diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsxindex 94cc23da9e..120b255021 100644--- a/apps/client/src/widgets/note_map/NoteMap.tsx+++ b/apps/client/src/widgets/note_map/NoteMap.tsx@@ -27,9 +27,13 @@ interface NoteMapProps {note: FNote;widgetMode: NoteMapWidgetMode;parentRef: RefObject<HTMLElement | null>;+ /** The note the map starts from when the note names none, in place of the active note's parent. */+ defaultRootNoteId?: string | null;+ /** Opens a clicked note where the map's host shows notes, in place of the active note context. */+ onOpenNote?: (noteId: string) => void;}-export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {+export default function NoteMap({ note, widgetMode, parentRef, defaultRootNoteId, onOpenNote }: NoteMapProps) {const containerRef = useRef<HTMLDivElement>(null);const styleResolverRef = useRef<HTMLDivElement>(null);const [ mapType, setMapType ] = useMapType(note, widgetMode);@@ -57,7 +61,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {} else if (mapRootIdLabel) {return mapRootIdLabel;}- return appContext.tabManager.getActiveContext()?.parentNoteId ?? null;+ return defaultRootNoteId ?? appContext.tabManager.getActiveContext()?.parentNoteId ?? null;}, [ note ]);@@ -121,6 +125,10 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {graph.onNodeClick((node) => {if (!node.id) return;+ if (onOpenNote) {+ onOpenNote(node.id);+ return;+ }appContext.tabManager.getActiveContext()?.setNote(node.id);// The map always sends the reader to the pane behind it, never to its own host — so a// map shown in the quick-edit popup has to dismiss it, or it would be left covering the@@ -129,7 +137,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {void appContext.triggerEvent("closePopupEditor", {});}).onNodeRightClick((node, e) => {- if (!node.id) return;+ if (!node.id || onOpenNote) return;link_context_menu.openContextMenu(node.id, e);});diff --git a/apps/client/src/widgets/note_map/data.ts b/apps/client/src/widgets/note_map/data.tsindex c7dcf79b76..eb897f8afc 100644--- a/apps/client/src/widgets/note_map/data.ts+++ b/apps/client/src/widgets/note_map/data.ts@@ -1,5 +1,5 @@import { NoteMapLink, NoteMapPostResponse } from "@triliumnext/commons";-import server from "../../services/server";+import froca from "../../services/froca";import { LinkObject, NodeObject } from "force-graph";type MapType = "tree" | "link";@@ -48,9 +48,7 @@ export interface NotesAndRelationsData {* 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 resp = await froca.getNoteMap(mapRootNoteId, mapType, { excludeRelations, includeRelations });const noteIdToSizeMap = calculateNodeSizes(resp, mapType);const links = getGroupedLinks(resp.links);diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsxindex cb4cdb0e00..41b38d5515 100644--- a/packages/share-theme/src/content/app_host.tsx+++ b/packages/share-theme/src/content/app_host.tsx@@ -15,11 +15,15 @@ export interface AppPayload extends ShareFrocaRows {options: Record<string, OptionValue | null>;/** Where the app's assets are, such as the translations its views read. */assetPath: string;+ /** The parent of the note on the share, which the note is shown below. */+ parentNoteId: string | null;}export interface HostedApp {/** The note the page shows, read-only. */note: FNote;+ /** The parent of the note on the share, which the note is shown below. */+ parentNoteId: string | null;/** Opens a note on its shared page, in place of the app's own way. */openNote(noteId: string): void;}@@ -79,6 +83,7 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {return {note,+ parentNoteId: payload.parentNoteId,openNote: (openedNoteId) => {const link = links[openedNoteId];if (link) {diff --git a/packages/share-theme/src/content/note_view.tsx b/packages/share-theme/src/content/note_view.tsxindex ec14467b4a..ac11d88e8f 100644--- a/packages/share-theme/src/content/note_view.tsx+++ b/packages/share-theme/src/content/note_view.tsx@@ -1,12 +1,15 @@+import "@triliumnext/client/src/widgets/type_widgets/NoteMap.css";+import type FNote from "@triliumnext/client/src/entities/fnote.js";import { t } from "@triliumnext/client/src/services/i18n.js";+import NoteMap from "@triliumnext/client/src/widgets/note_map/NoteMap.js";import { TYPE_MAPPINGS, type TypeWidget } from "@triliumnext/client/src/widgets/note_types.js";import { useNoteBlob } from "@triliumnext/client/src/widgets/react/hooks.js";import { RawHtmlBlock } from "@triliumnext/client/src/widgets/react/RawHtml.js";import { render } from "preact";-import { useEffect, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";-import ShareAppHost, { type AppPayload } from "./app_host.js";+import ShareAppHost, { type AppPayload, type HostedApp } from "./app_host.js";import { drawMermaid, loadMermaid, readMermaidTheme } from "./mermaid.js";import { ZoomViewer } from "./zoom_viewer.js";@@ -19,13 +22,14 @@ export default function mountNoteView(container: HTMLElement, payload: AppPayloacontainer.replaceChildren();render(<ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>- {({ note }) => <SharedNoteView note={note} />}+ {(app) => <SharedNoteView app={app} />}</ShareAppHost>,container);}-function SharedNoteView({ note }: { note: FNote }) {+function SharedNoteView({ app }: { app: HostedApp }) {+ const { note } = app;switch (note.type) {case "image":case "canvas":@@ -33,6 +37,8 @@ function SharedNoteView({ note }: { note: FNote }) {return <ImageView note={note} />;case "mermaid":return <MermaidView note={note} />;+ case "noteMap":+ return <NoteMapView app={app} />;default:return <NoteView note={note} />;}@@ -107,6 +113,25 @@ function MermaidView({ note }: { note: FNote }) {);}+/**+ * Draws a note map note's map, from the note's parent on the share unless the note names another+ * root, and opens a clicked note on its shared page.+ */+function NoteMapView({ app }: { app: HostedApp }) {+ const containerRef = useRef<HTMLDivElement>(null);+ return (+ <div ref={containerRef} className="note-detail-note-map">+ <NoteMap+ parentRef={containerRef}+ note={app.note}+ widgetMode="type"+ defaultRootNoteId={app.parentNoteId}+ onOpenNote={app.openNote}+ />+ </div>+ );+}+/** The page's Mermaid theme, which follows the theme switch's class on `<html>`. */function useMermaidTheme() {const [ theme, setTheme ] = useState(readMermaidTheme);diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex a049a3df79..5bf7582e2f 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -26,6 +26,13 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSourconst params = new URLSearchParams({ search: query, ancestorNoteId });const { results } = await getJson<{ results: { noteId: string }[] }>(`api/notes?${params}`);return results.map((result) => result.noteId);+ },+ getNoteMap: (mapRootNoteId, mapType, { excludeRelations, includeRelations }) => {+ const params = new URLSearchParams([+ ...excludeRelations.map((name) => [ "excludeRelation", name ]),+ ...includeRelations.map((name) => [ "includeRelation", name ])+ ]);+ return getJson(`api/note-map/${encodeURIComponent(mapRootNoteId)}/${mapType}?${params}`);}};}diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.tsindex d276715063..d3338b6828 100644--- a/packages/trilium-core/src/routes/api/note_map.ts+++ b/packages/trilium-core/src/routes/api/note_map.ts@@ -99,7 +99,18 @@ function getNeighbors(note: BNote, depth: number): string[] {}function getLinkMap(req: Request<{ noteId: string }>) {- const mapRootNote = becca.getNoteOrThrow(req.params.noteId);+ const toNames = (data: unknown) => (data instanceof Array ? data.map(String) : []);+ return buildLinkMap(becca.getNoteOrThrow(req.params.noteId), {+ excludeRelations: toNames(req.body.excludeRelations),+ includeRelations: toNames(req.body.includeRelations)+ });+}++/**+ * Returns the notes of the link map of `mapRootNote` (its subtree, or a search note's results, and+ * the notes within three relations of it) and the relations between them, which `filters` narrow.+ */+export function buildLinkMap(mapRootNote: BNote, filters: { excludeRelations: string[]; includeRelations: string[] }) {// if the map root itself has "excludeFromNoteMap" attribute (journal typically) then there wouldn't be anything// to display, so we'll just ignore it@@ -111,10 +122,8 @@ function getLinkMap(req: Request<{ noteId: string }>) {const includeArchived = mapRootNote.isArchived;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);+ const excludeRelations = new Set(filters.excludeRelations);+ const includeRelations = new Set(filters.includeRelations);if (mapRootNote.type === "search") {// for search notes, we want to consider the direct search results only without the descendants@@ -182,7 +191,11 @@ function getLinkMap(req: Request<{ noteId: string }>) {}function getTreeMap(req: Request<{ noteId: string }>) {- const mapRootNote = becca.getNoteOrThrow(req.params.noteId);+ return buildTreeMap(becca.getNoteOrThrow(req.params.noteId));+}++/** Returns the notes of the subtree of `mapRootNote` and the branches between them. */+export function buildTreeMap(mapRootNote: BNote) {// if the map root itself has "excludeFromNoteMap" (journal typically) then there wouldn't be anything to display,// so we'll just ignore itconst ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 9d2c90917a..4805405b68 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -511,6 +511,9 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}result.isEmpty = true;} else if (note.type === "webView") {renderWebView(note, result);+ } else if (note.type === "noteMap") {+ result.content = "";+ hostNoteView(result, note);} else if (note.type === "spreadsheet") {renderSpreadsheet(result);hostNoteView(result, note);@@ -946,7 +949,9 @@ function hostInAppView(result: Result, note: SNote, container: string) {...buildFrocaPayload(note),options: Object.fromEntries(SHARED_OPTIONS.map((name) => [ name, options.getOptionOrNull(name) ])),// The app's assets, such as its translations, from a page directly below `/share/`.- assetPath: `../${utils.isDev() ? `${assetUrlFragment}/src` : assetUrlFragment}`+ assetPath: `../${utils.isDev() ? `${assetUrlFragment}/src` : assetUrlFragment}`,+ // The note the app would show the note below, such as the root of a note map note's map.+ parentNoteId: note.getParentBranches()[0]?.parentNoteId ?? null};const json = JSON.stringify(payload).replace(/</g, "\\u003c");result.isAppView = true;diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex 37a48dcc8c..a49c2f9d19 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -2,6 +2,8 @@ import { isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@import ejs from "ejs";import { t } from "i18next";+import becca from "../becca/becca.js";+import { buildLinkMap, buildTreeMap } from "../routes/api/note_map.js";import { getCrypto } from "../services/encryption/crypto.js";import searchService from "../services/search/services/search.js";import SearchContext from "../services/search/search_context.js";@@ -91,6 +93,7 @@ const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {"/share/api/attachments/:attachmentId/all": getSiblingAttachments,"/share/api/attachments/:attachmentId/blob": getAttachmentBlob,"/share/api/tree": loadTree,+ "/share/api/note-map/:noteId/:mapType": getNoteMap,"/share/": getShareRoot,"/share/:shareId": getShareNote};@@ -185,6 +188,39 @@ function loadTree(req: ShareRequest): ShareReply {return jsonReply(200, buildFrocaRows(notes, canAccess));}+/**+ * Answers the note map the app draws of a shared note, as a tree or as its relations, with only the+ * notes a visitor of the share can read and the links between them. The relations to leave out or+ * to keep come as repeated `excludeRelation` and `includeRelation` parameters.+ */+function getNoteMap(req: ShareRequest): ShareReply {+ const mapRoot = becca.getNote(checkNoteAccess(req.params.noteId ?? "", req).noteId);+ const { mapType } = req.params;+ if (!mapRoot || (mapType !== "tree" && mapType !== "link")) {+ return jsonReply(404, { message: `No note map of '${req.params.noteId}'.` });+ }++ const toNames = (value: string | string[] | undefined) => [ value ?? [] ].flat();+ const map = mapType === "tree"+ ? buildTreeMap(mapRoot)+ : buildLinkMap(mapRoot, {+ excludeRelations: toNames(req.query.excludeRelation),+ includeRelations: toNames(req.query.includeRelation)+ });++ const notes = map.notes.filter(([ noteId ]) => {+ const note = shaca.getNote(noteId);+ return !!note && !note.isProtected && hasCredentialAccess(note, req);+ });+ const noteIds = new Set(notes.map(([ noteId ]) => noteId));+ return jsonReply(200, {+ notes,+ links: map.links.filter((link) => noteIds.has(link.sourceNoteId) && noteIds.has(link.targetNoteId)),+ noteIdToDescendantCountMap: Object.fromEntries(Object.entries(map.noteIdToDescendantCountMap)+ .filter(([ noteId ]) => noteIds.has(noteId)))+ });+}+function getNoteAttachments(req: ShareRequest): ShareReply {const note = checkNoteContentAccess(req.params.noteId ?? "", req);return jsonReply(200, note.getAttachments().map(getAttachmentRow));diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.tsindex 88e68df7b6..3fec3b9364 100644--- a/packages/trilium-core/src/share/route_paths.ts+++ b/packages/trilium-core/src/share/route_paths.ts@@ -20,6 +20,7 @@ export const SHARE_ROUTE_PATHS = ["/share/api/attachments/:attachmentId/all","/share/api/attachments/:attachmentId/blob","/share/api/tree",+ "/share/api/note-map/:noteId/:mapType","/share/","/share/:shareId"] as const;