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): read the static export's app view data from its files
Elian Doran90509d2afffd
diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsxindex e338af69ae..efe94d90a3 100644--- a/packages/share-theme/src/content/app_host.tsx+++ b/packages/share-theme/src/content/app_host.tsx@@ -4,13 +4,16 @@ import TabManager from "@triliumnext/client/src/components/tab_manager.js";import type FNote from "@triliumnext/client/src/entities/fnote.js";import linkContextMenu from "@triliumnext/client/src/menus/link_context_menu.js";import froca from "@triliumnext/client/src/services/froca.js";+import type { FrocaSource, SubtreeResponse } from "@triliumnext/client/src/services/froca-interface.js";import { parseNavigationStateFromUrl } from "@triliumnext/client/src/services/link.js";import options, { type OptionValue } from "@triliumnext/client/src/services/options.js";import { ParentComponent } from "@triliumnext/client/src/widgets/react/react_utils.js";import type { ComponentChildren } from "preact";import { useLayoutEffect, useState } from "preact/hooks";-import { createShareFrocaSource, type ShareFrocaRows } from "./share_froca_source.js";+import {+ createShareFrocaSource, createStaticFrocaSource, type ShareFrocaRows, type StaticFrocaSource+} from "./share_froca_source.js";/** What core embeds next to an app view on a shared page. */export interface AppPayload extends ShareFrocaRows {@@ -19,6 +22,11 @@ export interface AppPayload extends ShareFrocaRows {assetPath: string;/** The parent of the note on the share, which the note is shown below. */parentNoteId: string | null;+ /**+ * On a page of the static export, the path of the export's root from the page, such as+ * `../`, under which the notes the views read are files instead of the share's API.+ */+ exportBasePath?: string;}export interface HostedApp {@@ -30,6 +38,8 @@ export interface HostedApp {openNote(noteId: string): void;/** Whether the note has a shared page to open. */hasLink(noteId: string): boolean;+ /** On a page of the static export, the source that resolves the views' image URLs. */+ staticSource?: StaticFrocaSource;}interface ShareAppHostProps {@@ -42,12 +52,20 @@ interface ShareAppHostProps {* Hosts app views on a shared page: fills `options` and froca from `payload`, has froca read any* other note from the share, marks the note `#readOnly` so the views leave out their editing* controls, starts the part of `appContext` the views rely on and mounts them under a component of- * their own, as the app mounts every view. A click on a link into the note tree the views render,+ * their own, as the app mounts every view. On a page of the static export, froca first takes every+ * note of the export, so a collection a view draws has its children. A click on a link into the note tree the views render,* which the app's link handler opens in the app, opens the note's shared page.*/export default function ShareAppHost({ noteId, payload, children }: ShareAppHostProps) {const [ app ] = useState(() => loadPayload(noteId, payload));const [ component ] = useState(() => new Component());+ const [ isLoaded, setLoaded ] = useState(!app?.staticSource);++ useLayoutEffect(() => {+ if (app?.staticSource) {+ void froca.reloadNotes([ app.note.noteId ]).then(() => setLoaded(true));+ }+ }, [ app ]);useLayoutEffect(() => {startAppContext();@@ -61,10 +79,14 @@ export default function ShareAppHost({ noteId, payload, children }: ShareAppHost}const onClick = (event: MouseEvent) => openNoteLink(event, app);document.addEventListener("click", onClick);- return () => document.removeEventListener("click", onClick);+ const stopImages = app.staticSource && watchImageUrls(app.staticSource);+ return () => {+ document.removeEventListener("click", onClick);+ stopImages?.();+ };}, [ app ]);- return app && (+ return app && isLoaded && (<ParentComponent.Provider value={component}>{children(app)}</ParentComponent.Provider>@@ -76,10 +98,12 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {options.load(Object.fromEntries(Object.entries(optionValues).flatMap(([ name, value ]) => (value === null ? [] : [ [ name, value ] ]))));- froca.setSource(createShareFrocaSource(links));+ const staticSource = payload.exportBasePath === undefined+ ? undefined : createStaticFrocaSource(links, payload.exportBasePath);+ froca.setSource(withRootAnchors(staticSource ?? createShareFrocaSource(links)));linkContextMenu.setShareLinkResolver((linkedNoteId) => links[linkedNoteId] ?? null);froca.addResp({- ...rows,+ ...anchorAtRoot(rows),attributes: [ ...rows.attributes, {attributeId: `${noteId}-share-readOnly`,noteId,@@ -105,10 +129,83 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {window.location.href = link;}},- hasLink: (linkedNoteId) => !!links[linkedNoteId]+ hasLink: (linkedNoteId) => !!links[linkedNoteId],+ staticSource};}+/** Has `source` answer every note it loads with {@link anchorAtRoot}. */+function withRootAnchors(source: FrocaSource): FrocaSource {+ return { ...source, loadNotes: async (noteIds) => anchorAtRoot(await source.loadNotes(noteIds)) };+}++/**+ * Places each note of `rows` that has no parent among them below a stand-in `root`, which a+ * page holds none of, so that each note has a path, which a collection a view draws needs to mount.+ * The built-in templates, such as `_template_calendar`, stay outside the tree.+ */+function anchorAtRoot<T extends SubtreeResponse>(rows: T): T {+ const childNoteIds = new Set(rows.branches.map((branch) => branch.noteId));+ const orphans = rows.notes.filter((note) =>+ !childNoteIds.has(note.noteId) && note.noteId !== "root" && !note.noteId.startsWith("_"));+ const rootRows = froca.getNoteFromCache("root") ? [] : [ {+ noteId: "root", title: "root", isProtected: false, type: "text" as const,+ mime: "text/html", blobId: ""+ } ];+ return {+ ...rows,+ notes: [ ...rootRows, ...rows.notes ],+ branches: [ ...rows.branches, ...orphans.map((note) => ({+ branchId: `root_${note.noteId}`,+ noteId: note.noteId,+ parentNoteId: "root",+ notePosition: 0,+ fromSearchNote: false+ })) ]+ };+}++/**+ * Points the images the views draw in `#content` from the app's API, such as a card's+ * `api/images/<noteId>/…`, at their files in the static export, as they are added or changed.+ * Returns the function that stops watching.+ */+function watchImageUrls(source: StaticFrocaSource) {+ const root = document.getElementById("content") ?? document.body;+ const update = async (image: HTMLImageElement) => {+ const src = image.getAttribute("src");+ const resolved = src ? await source.resolveImageUrl(src) : null;+ if (resolved && image.getAttribute("src") === src) {+ image.setAttribute("src", resolved);+ }+ };+ const updateWithin = (node: Node) => {+ if (node instanceof HTMLImageElement) {+ void update(node);+ } else if (node instanceof Element) {+ for (const image of node.querySelectorAll("img")) {+ void update(image);+ }+ }+ };++ const observer = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ if (mutation.type === "attributes") {+ updateWithin(mutation.target);+ }+ for (const node of mutation.addedNodes) {+ updateWithin(node);+ }+ }+ });+ observer.observe(root, {+ childList: true, subtree: true, attributes: true, attributeFilter: [ "src" ]+ });+ updateWithin(root);+ return () => observer.disconnect();+}+/*** Opens the shared page of the note a clicked link into the note tree names, such as a table's* `.reference-link[data-href="#root/…"]` cell. A link to a note the share does not hold is left alone.diff --git a/packages/share-theme/src/content/share_froca_source.spec.ts b/packages/share-theme/src/content/share_froca_source.spec.tsnew file mode 100644index 0000000000..42f7ab5c25--- /dev/null+++ b/packages/share-theme/src/content/share_froca_source.spec.ts@@ -0,0 +1,121 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { createStaticFrocaSource } from "./share_froca_source.js";++describe("createStaticFrocaSource", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("answers froca from the files of the static export, relative to the page", async () => {+ const fetch = stubFiles({+ "../data/rows.json": ROWS,+ "../data/blobs/notes/event.json": { content: "<p>Event</p>" },+ "../data/note-map/0.json": { notes: [ [ "filtered" ] ] },+ "../data/note-map/1.json": { notes: [ [ "plain" ] ] },+ "../data/relation-map/relations.json": { noteTitles: { event: "Event" } },+ "../data/script/script.json": { script: "run()" }+ });+ const links: Record<string, string> = {};+ const source = createStaticFrocaSource(links, "../");++ expect(await source.loadNotes([ "event" ])).toEqual({+ notes: ROWS.notes, branches: ROWS.branches, attributes: ROWS.attributes+ });+ expect(links).toEqual({ siteRoot: "../", event: "../pages/event.html" });+ expect(await source.getAttachments("canvas")).toEqual([ SVG ]);+ expect(await source.getAttachments("event")).toEqual([]);+ expect(await source.getSiblingAttachments("svg")).toEqual([ SVG ]);+ await expect(source.getSiblingAttachments("gone")).rejects.toThrow("no attachment 'gone'");+ expect(await source.getBlob("notes", "event")).toEqual({ content: "<p>Event</p>" });++ const filters = { excludeRelations: [ "template" ], includeRelations: [] };+ expect(await source.getNoteMap("site", "link", filters))+ .toEqual({ notes: [ [ "filtered" ] ] });+ expect(await source.getNoteMap("site", "link",+ { excludeRelations: [ "other" ], includeRelations: [] }))+ .toEqual({ notes: [ [ "filtered" ] ] });+ expect(await source.getNoteMap("site", "tree", filters))+ .toEqual({ notes: [ [ "plain" ] ] });+ expect(await source.getNoteMap("elsewhere", "tree", filters))+ .toEqual({ notes: [], links: [], noteIdToDescendantCountMap: {} });+ expect(await source.getRelationMap("relations", []))+ .toEqual({ noteTitles: { event: "Event" } });+ expect(await source.getScriptBundle("script")).toEqual({ script: "run()" });+ expect(await source.getScriptBundle("missing")).toBeUndefined();+ expect(fetch.mock.calls.filter(([ url ]) => url === "../data/rows.json")).toHaveLength(1);+ });++ it("resolves the image URLs of the app's API to the export's files", async () => {+ stubFiles({ "data/rows.json": ROWS });+ const source = createStaticFrocaSource({}, "");++ expect(await source.resolveImageUrl("api/images/image/Photo.png?123"))+ .toBe("data/images/image.png");+ expect(await source.resolveImageUrl("http://host/page/api/images/canvas/x"))+ .toBe("pages/canvas_svg.svg");+ expect(await source.resolveImageUrl("api/attachments/svg/image/a.svg"))+ .toBe("pages/canvas_svg.svg");+ expect(await source.resolveImageUrl("api/images/unknown/x")).toBeNull();+ expect(await source.resolveImageUrl("pages/photo.png")).toBeNull();+ });++ it("lists a note's children that are not archived, the one search it answers", async () => {+ stubFiles({ "data/rows.json": {+ ...ROWS,+ branches: [+ { branchId: "a", noteId: "open", parentNoteId: "board" },+ { branchId: "b", noteId: "archived", parentNoteId: "board" },+ { branchId: "c", noteId: "elsewhere", parentNoteId: "other" }+ ],+ attributes: [+ { noteId: "archived", type: "label", name: "archived", value: "" },+ { noteId: "open", type: "relation", name: "archived", value: "x" }+ ]+ } });+ const source = createStaticFrocaSource({}, "");++ expect(await source.searchNoteIds("note.parents.noteId=\"board\" #!archived", "board"))+ .toEqual([ "open" ]);+ });++ it("finds nothing and keeps nothing it is asked to search or save", async () => {+ const source = createStaticFrocaSource({}, "");++ expect(await source.searchNoteIds("#a", "root")).toEqual([]);+ expect(await source.searchInSubtree("#a", "root"))+ .toEqual({ searchResultNoteIds: [], highlightedTokens: [], error: null });+ expect(await source.lintSearch("#a")).toEqual({ error: null });+ expect(await source.getAttributeNames("label", "a")).toEqual([]);+ await expect(source.saveAttachment("note", {+ role: "viewConfig", title: "config.json", mime: "application/json", content: "{}",+ position: 0+ })).resolves.toBeUndefined();+ await expect(source.removeAttachment("attachment")).resolves.toBeUndefined();+ });+});++const SVG = { attachmentId: "svg", ownerId: "canvas", title: "canvas-export.svg" };++const ROWS = {+ notes: [ { noteId: "event", title: "Event" } ],+ branches: [ { branchId: "site_event", noteId: "event", parentNoteId: "siteRoot" } ],+ attributes: [],+ links: { siteRoot: "", event: "pages/event.html" },+ attachments: { canvas: [ SVG ] },+ attachmentPaths: { svg: "pages/canvas_svg.svg" },+ images: { image: "data/images/image.png", canvas: "pages/canvas_svg.svg" },+ noteMaps: {+ "site/link?exclude=template": "data/note-map/0.json",+ "site/tree?": "data/note-map/1.json"+ }+};++/** Has `fetch` answer each of `files` by its URL with its JSON, and anything else with a 404. */+function stubFiles(files: Record<string, unknown>) {+ const fetch = vi.fn(async (url: string) => (url in files+ ? new Response(JSON.stringify(files[url]))+ : new Response("", { status: 404, statusText: "Not Found" })));+ vi.stubGlobal("fetch", fetch);+ return fetch;+}diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex 69fe7a28f9..93761b3228 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -1,4 +1,7 @@+import type { FAttachmentRow } from "@triliumnext/client/src/entities/fattachment.js";+import type { Bundle } from "@triliumnext/client/src/services/bundle.js";import type { FrocaSource, SubtreeResponse } from "@triliumnext/client/src/services/froca-interface.js";+import { getNoteMapDataKey } from "@triliumnext/commons/src/lib/share_hosting.js";/** Rows of notes as the share answers them, with the share link of each note. */export interface ShareFrocaRows extends SubtreeResponse {@@ -51,6 +54,117 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSour};}+/**+ * The data the static export writes into `data/rows.json`: the rows of every note it holds, each+ * note's link and the paths of its files, relative to the export's root.+ */+interface StaticShareRows extends ShareFrocaRows {+ attachments: Record<string, FAttachmentRow[]>;+ attachmentPaths: Record<string, string>;+ images: Record<string, string>;+ noteMaps: Record<string, string>;+}++/** A source of froca's notes that also resolves the app's image URLs on a page of the export. */+export interface StaticFrocaSource extends FrocaSource {+ /**+ * The URL of the file of an `api/images/<noteId>/…` or `api/attachments/<id>/image/…` URL,+ * relative to the page, or `null` for another URL or a file the export does not hold.+ */+ resolveImageUrl(url: string): Promise<string | null>;+}++/**+ * Reads the notes, attachments and blobs froca lacks from the files the static export writes+ * under `data/`, `basePath` being the export's root from the page, and records the link of each+ * note it loads in `links`. A view cannot search or change notes there: a search finds nothing, but+ * for the one listing a note's children that are not archived, and a save holds only while the page+ * is open.+ */+export function createStaticFrocaSource(+ links: Record<string, string>,+ basePath: string+): StaticFrocaSource {+ let rowsPromise: Promise<StaticShareRows> | undefined;+ const readRows = () => {+ rowsPromise ??= getJson<StaticShareRows>(`${basePath}data/rows.json`);+ return rowsPromise;+ };+ const resolve = (path: string) => (path ? `${basePath}${path}` : basePath || "./");+ const readData = <T>(path: string) => getJson<T>(`${basePath}data/${path}`);++ return {+ loadNotes: async () => {+ const { notes, branches, attributes, links: rootLinks } = await readRows();+ for (const [ noteId, link ] of Object.entries(rootLinks)) {+ links[noteId] = resolve(link);+ }+ return { notes, branches, attributes };+ },+ getSiblingAttachments: async (attachmentId) => {+ const siblings = Object.values((await readRows()).attachments).find((attachments) =>+ attachments.some((attachment) => attachment.attachmentId === attachmentId));+ if (!siblings) {+ throw new Error(`The export holds no attachment '${attachmentId}'.`);+ }+ return siblings;+ },+ getAttachments: async (noteId) => (await readRows()).attachments[noteId] ?? [],+ getBlob: (entityType, entityId) =>+ readData(`blobs/${entityType}/${encodeURIComponent(entityId)}.json`),+ searchNoteIds: async (query) => {+ const parentNoteId = UNARCHIVED_CHILDREN.exec(query)?.[1];+ if (!parentNoteId) {+ return [];+ }+ const { branches, attributes } = await readRows();+ const archived = new Set(attributes+ .filter((attribute) => attribute.type === "label" && attribute.name === "archived")+ .map((attribute) => attribute.noteId));+ return branches+ .filter((branch) => branch.parentNoteId === parentNoteId)+ .filter((branch) => !archived.has(branch.noteId))+ .map((branch) => branch.noteId);+ },+ saveAttachment: async () => {},+ removeAttachment: async () => {},+ searchInSubtree: async () => ({+ searchResultNoteIds: [], highlightedTokens: [], error: null+ }),+ getAttributeNames: async () => [],+ lintSearch: async () => ({ error: null }),+ getNoteMap: async (mapRootNoteId, mapType, filters) => {+ const { noteMaps } = await readRows();+ const prefix = `${mapRootNoteId}/${mapType}?`;+ const path = noteMaps[getNoteMapDataKey(mapRootNoteId, mapType, filters)]+ ?? Object.entries(noteMaps).find(([ key ]) => key.startsWith(prefix))?.[1];+ return path+ ? await getJson(resolve(path))+ : { notes: [], links: [], noteIdToDescendantCountMap: {} };+ },+ getRelationMap: (relationMapNoteId) =>+ readData(`relation-map/${encodeURIComponent(relationMapNoteId)}.json`),+ getScriptBundle: (noteId) =>+ readData<Bundle>(`script/${encodeURIComponent(noteId)}.json`).catch(() => undefined),+ resolveImageUrl: async (url) => {+ const match = IMAGE_URL.exec(url);+ if (!match) {+ return null;+ }+ const [ , noteId, attachmentId ] = match;+ const { images, attachmentPaths } = await readRows();+ const path = noteId ? images[noteId] : attachmentPaths[attachmentId ?? ""];+ return path ? resolve(path) : null;+ }+ };+}++/** The search `FNote.getChildNoteIdsWithArchiveFiltering()` lists a note's children with. */+const UNARCHIVED_CHILDREN = /^note\.parents\.noteId="(\w+)" #!archived$/;++/** An image URL of the app's API, naming a note's image or an image attachment. */+const IMAGE_URL = /(?:^|\/)api\/(?:images\/(\w+)\/|attachments\/(\w+)\/image\/)/;+async function getJson<T>(url: string): Promise<T> {const response = await fetch(url);if (!response.ok) {diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex a959647cdd..540120804a 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1756,6 +1756,7 @@ describe("content_renderer pages", () => {const payload = JSON.parse(page.querySelector("script.share-froca")?.textContent ?? "{}");expect(payload.notes.map((note: { noteId: string }) => note.noteId)).toEqual([ "lockedBoard", "openCard" ]);expect(payload.attributes.map((attribute: { name: string }) => attribute.name)).toEqual([ "viewType" ]);+ expect("exportBasePath" in payload).toBe(false);});it("lists the subpages of a collection whose template makes it a list", () => {@@ -1955,6 +1956,7 @@ describe("content_renderer pages", () => {expect(payload.branches.map((row: { noteId: string }) => row.noteId)).toStrictEqual([ "hostEvent" ]);expect(payload.assetPath).toBe("../assets");+ expect(payload.exportBasePath).toBe("../");// Without the export's links, a page keeps the content rendered for it.const staticPage = parse(String(renderNoteForExport(calendar, branch, "../", [], [])));diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 184f3d8abe..e263afbb6c 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -998,7 +998,9 @@ function hostInAppView(? `${exportHosting.basePath}assets`: `../${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+ parentNoteId: note.getParentBranches()[0]?.parentNoteId ?? null,+ // On a page of the export, the views read their notes from the files under `data/`.+ exportBasePath: exportHosting?.basePath};const json = JSON.stringify(payload).replace(/</g, "\\u003c");result.isAppView = true;