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 relation map note with the app's relation map
Elian Doranf85e189d72a2
diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.tsindex 6eaf116120..2a629cd669 100644--- a/apps/client/src/services/froca-interface.ts+++ b/apps/client/src/services/froca-interface.ts@@ -1,4 +1,4 @@-import type { NoteMapPostResponse } from "@triliumnext/commons";+import type { NoteMapPostResponse, RelationMapPostResponse } from "@triliumnext/commons";import type FAttachment from "../entities/fattachment.js";import type { FAttachmentRow } from "../entities/fattachment.js";@@ -39,6 +39,8 @@ export interface FrocaSource {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>;+ /** The relations the relation map note `relationMapNoteId` draws between the notes `noteIds`. */+ getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;}export interface Froca {@@ -60,4 +62,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>;+ getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;}diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex 4f8ba7cd10..8ae2dc5c77 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -1,4 +1,4 @@-import type { HighlightedTokenInfo, NoteMapPostResponse } from "@triliumnext/commons";+import type { HighlightedTokenInfo, NoteMapPostResponse, RelationMapPostResponse } from "@triliumnext/commons";import FAttachment, { type FAttachmentRow } from "../entities/fattachment.js";import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";@@ -407,6 +407,10 @@ class FrocaImpl implements Froca {return this.source.getNoteMap(mapRootNoteId, mapType, filters);}+ getRelationMap(relationMapNoteId: string, noteIds: string[]) {+ return this.source.getRelationMap(relationMapNoteId, noteIds);+ }+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@@ -445,7 +449,9 @@ const SERVER_SOURCE: FrocaSource = {return await search.searchForNoteIds(query);},getNoteMap: (mapRootNoteId, mapType, filters) =>- server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters)+ server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters),+ getRelationMap: (relationMapNoteId, noteIds) =>+ server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId })};const froca = new FrocaImpl();diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex c81872f1d7..88131f06e3 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -29,7 +29,7 @@ import SpacedUpdate, { type StateCallback } from "../../services/spaced_update";import { getEffectiveThemeStyle } from "../../services/theme";import toast, { ToastOptions } from "../../services/toast";import tree from "../../services/tree";-import utils, { getErrorMessage, randomString, reloadFrontendApp } from "../../services/utils";+import utils, { getErrorMessage, isShare, randomString, reloadFrontendApp } from "../../services/utils";import ws from "../../services/ws";import BasicWidget, { ReactWrappedWidget } from "../basic_widget";import NoteContextAwareWidget from "../note_context_aware_widget";@@ -148,8 +148,9 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, on}, [ note, getData ]);const commit = useCallback(async (data: SavedData | undefined) => {- // for read only notes, or if note is not yet available (e.g. lazy creation)- if (data === undefined || !note || note.type !== noteType) return;+ // for read only notes, or if note is not yet available (e.g. lazy creation); a visitor of a+ // shared page cannot save+ if (data === undefined || !note || note.type !== noteType || isShare) return;protected_session_holder.touchProtectedSessionIfNecessary(note);diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsxindex cb3e40cd79..110a2420bb 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx@@ -13,7 +13,6 @@ import { t } from "../../../services/i18n";import { goToLinkExt } from "../../../services/link";import note_create from "../../../services/note_create";import { pasteNotes } from "../../../services/note_paste";-import server from "../../../services/server";import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";import toast from "../../../services/toast";import { isMobile } from "../../../services/utils";@@ -33,7 +32,12 @@ import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";import RelationNamePopover, { useRelationNamePrompt } from "./RelationNamePopover";import { CLICK_TOLERANCE, fitTransform, getMousePosition, idToNoteId, noteIdToId, revealOffset } from "./utils";-export default function RelationMap({ note, noteContext, ntxId }: TypeWidgetProps) {+interface RelationMapProps extends TypeWidgetProps {+ /** Opens a clicked note where the map's host shows notes, in place of the note pane and a tab. */+ onOpenNote?: (noteId: string) => void;+}++export default function RelationMap({ note, noteContext, ntxId, onOpenNote }: RelationMapProps) {const [ data, setData ] = useState<MapData>();// The same read-only the note's own bar of actions read while the + stood there.const [ isReadOnly ] = useNoteLabelBoolean(note, "readOnly");@@ -115,9 +119,9 @@ export default function RelationMap({ note, noteContext, ntxId }: TypeWidgetPropconst clickProps = useCanvasClicks({placing: placement.placing,onPlace: placement.placeAt,- onSelectNote: (noteId) => setSelection({ noteId }),+ onSelectNote: (noteId) => (onOpenNote ? onOpenNote(noteId) : setSelection({ noteId })),onClickEmpty: () => paneRef.current?.close(),- onOpenNote: openNoteFromBox+ onOpenNote: (noteId, e) => (onOpenNote ? onOpenNote(noteId) : openNoteFromBox(noteId, e))});const dragProps = useNoteDragging({ containerRef, mapApiRef, getScale });const paste = useMapPaste({ note, isReadOnly, viewport, containerRef, mapApiRef, getScale });@@ -357,7 +361,7 @@ function useRelationData(noteId: string, mapData: MapData | undefined, mapApiRefif (!noteIds || !api) return;let isCurrent = true;- server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId: noteId }).then((data) => {+ froca.getRelationMap(noteId, noteIds).then((data) => {if (!isCurrent) return;const relations = pairInverseRelations(data.relations, data.inverseRelations);diff --git a/packages/share-theme/src/content/note_view.tsx b/packages/share-theme/src/content/note_view.tsxindex ac11d88e8f..daedc2934b 100644--- a/packages/share-theme/src/content/note_view.tsx+++ b/packages/share-theme/src/content/note_view.tsx@@ -9,6 +9,7 @@ import { RawHtmlBlock } from "@triliumnext/client/src/widgets/react/RawHtml.js";import { render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";+import type RelationMapWidget from "@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js";import ShareAppHost, { type AppPayload, type HostedApp } from "./app_host.js";import { drawMermaid, loadMermaid, readMermaidTheme } from "./mermaid.js";import { ZoomViewer } from "./zoom_viewer.js";@@ -39,6 +40,8 @@ function SharedNoteView({ app }: { app: HostedApp }) {return <MermaidView note={note} />;case "noteMap":return <NoteMapView app={app} />;+ case "relationMap":+ return <RelationMapView app={app} />;default:return <NoteView note={note} />;}@@ -132,6 +135,30 @@ function NoteMapView({ app }: { app: HostedApp }) {);}+/** Draws a relation map note's map, and opens a clicked note on its shared page. */+function RelationMapView({ app }: { app: HostedApp }) {+ const [ RelationMap, setRelationMap ] = useState<typeof RelationMapWidget>();++ useEffect(() => {+ import("@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js")+ .then(({ default: widget }) => setRelationMap(() => widget));+ }, []);++ return RelationMap && (+ <div className="note-detail-relation-map">+ <RelationMap+ note={app.note}+ viewScope={undefined}+ ntxId={null}+ parentComponent={undefined}+ noteContext={undefined}+ isVisible+ 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 5bf7582e2f..dd33d0c02e 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -33,7 +33,10 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSour...includeRelations.map((name) => [ "includeRelation", name ])]);return getJson(`api/note-map/${encodeURIComponent(mapRootNoteId)}/${mapType}?${params}`);- }+ },+ // The share reads the notes from the map's own content, so a visitor cannot name others.+ getRelationMap: (relationMapNoteId) =>+ getJson(`api/relation-map/${encodeURIComponent(relationMapNoteId)}`)};}diff --git a/packages/trilium-core/src/routes/api/relation-map.ts b/packages/trilium-core/src/routes/api/relation-map.tsindex 04f73d0de1..94038c93fa 100644--- a/packages/trilium-core/src/routes/api/relation-map.ts+++ b/packages/trilium-core/src/routes/api/relation-map.ts@@ -1,11 +1,24 @@import type { Request } from "../../http_interface";import becca from "../../becca/becca.js";+import type BNote from "../../becca/entities/bnote.js";import { RelationMapPostResponse } from "@triliumnext/commons";import { getSql } from "../../services/sql/index.js";function getRelationMap(req: Request) {const { relationMapNoteId, noteIds } = req.body;+ if (!Array.isArray(noteIds) || noteIds.length === 0) {+ return buildRelationMap(null, []);+ }++ return buildRelationMap(becca.getNoteOrThrow(relationMapNoteId), noteIds);+}+/**+ * Returns the titles of the notes among `noteIds`, the relations between them that+ * `relationMapNote` shows (by its `#displayRelations` and `#hideRelations`) and the inverse of+ * each relation the notes define.+ */+export function buildRelationMap(relationMapNote: BNote | null, noteIds: string[]) {const resp: RelationMapPostResponse = {// noteId => titlenoteTitles: {},@@ -16,14 +29,12 @@ function getRelationMap(req: Request) {}};- if (!Array.isArray(noteIds) || noteIds.length === 0) {+ if (!relationMapNote || noteIds.length === 0) {return resp;}const questionMarks = noteIds.map((_noteId) => "?").join(",");- const relationMapNote = becca.getNoteOrThrow(relationMapNoteId);-const displayRelationsVal = relationMapNote.getLabelValue("displayRelations");const displayRelations = !displayRelationsVal ? [] : displayRelationsVal.split(",").map((token) => token.trim());diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex b385c5e8a7..4731bc7667 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1712,7 +1712,11 @@ describe("content_renderer pages", () => {expect(parse(String(spreadsheet.content)).querySelector(".share-note-view[data-note-id=sheetNote] > p")?.textContent).toBe("Empty spreadsheet.");- expect(render({ type: "relationMap", content: "{}" }).content)+ const relationMap = render({ id: "relationMapNote", type: "relationMap", content: "{}" });+ expect(relationMap.isAppView).toBe(true);+ expect(parse(String(relationMap.content))+ .querySelector(".share-note-view[data-note-id=relationMapNote]")?.innerHTML).toBe("");+ expect(render({ type: "render", content: "" }).content).toBe(`<p>${t("content_renderer.note-cannot-be-displayed")}</p>`);});diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 4805405b68..5ccf847b85 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -511,7 +511,7 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}result.isEmpty = true;} else if (note.type === "webView") {renderWebView(note, result);- } else if (note.type === "noteMap") {+ } else if (note.type === "noteMap" || note.type === "relationMap") {result.content = "";hostNoteView(result, note);} else if (note.type === "spreadsheet") {diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex a49c2f9d19..8713e86284 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -4,6 +4,7 @@ import { t } from "i18next";import becca from "../becca/becca.js";import { buildLinkMap, buildTreeMap } from "../routes/api/note_map.js";+import { buildRelationMap } from "../routes/api/relation-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";@@ -94,6 +95,7 @@ const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {"/share/api/attachments/:attachmentId/blob": getAttachmentBlob,"/share/api/tree": loadTree,"/share/api/note-map/:noteId/:mapType": getNoteMap,+ "/share/api/relation-map/:noteId": getRelationMap,"/share/": getShareRoot,"/share/:shareId": getShareNote};@@ -221,6 +223,31 @@ function getNoteMap(req: ShareRequest): ShareReply {});}+/**+ * Answers the relations a shared relation map note draws between the notes placed on it, of which+ * only those a visitor of the share can read. The notes are read from the map's own content.+ */+function getRelationMap(req: ShareRequest): ShareReply {+ const mapNote = checkNoteContentAccess(req.params.noteId ?? "", req);+ const placedNoteIds = readPlacedNoteIds(mapNote.getContent());+ const noteIds = placedNoteIds.filter((noteId) => {+ const note = shaca.getNote(noteId);+ return !!note && !note.isProtected && hasCredentialAccess(note, req);+ });++ return jsonReply(200, buildRelationMap(becca.getNote(mapNote.noteId), noteIds));+}++/** Returns the IDs of the notes a relation map's content places on the map. */+function readPlacedNoteIds(content: string | Uint8Array | null | undefined) {+ try {+ const data = JSON.parse(typeof content === "string" ? content : "") as { notes?: { noteId?: unknown }[] };+ return (data.notes ?? []).map((entry) => entry.noteId).filter((noteId) => typeof noteId === "string");+ } catch {+ return [];+ }+}+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 3fec3b9364..3748e4a07f 100644--- a/packages/trilium-core/src/share/route_paths.ts+++ b/packages/trilium-core/src/share/route_paths.ts@@ -21,6 +21,7 @@ export const SHARE_ROUTE_PATHS = ["/share/api/attachments/:attachmentId/blob","/share/api/tree","/share/api/note-map/:noteId/:mapType",+ "/share/api/relation-map/:noteId","/share/","/share/:shareId"] as const;