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): build the views' image URLs through one helper
Elian Doran25b6e61a029f
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 92830139b2..b98cef9c44 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -27,6 +27,7 @@ import renderText, {postProcessRichContent, renderChildrenList, renderTextContent} from "./content_renderer_text.js";import renderDoc from "./doc_renderer.js";+import { getAttachmentImageUrl, getNoteImageUrl } from "./image_urls.js";import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";import { renderOfficeToHtml } from "./office_renderer.js";import openService from "./open.js";@@ -581,13 +582,11 @@ async function renderCanvasDrawing(}function getImageUrl(entity: FNote | FAttachment) {- const encodedTitle = encodeURIComponent(entity.title);-if (entity instanceof FNote) {- return `api/images/${entity.noteId}/${encodedTitle}?${Math.random()}`;+ return getNoteImageUrl(entity.noteId, entity.title, String(Math.random()));} else if (entity instanceof FAttachment) {- const { attachmentId, utcDateModified } = entity;- return `api/attachments/${attachmentId}/image/${encodedTitle}?${utcDateModified}`;+ const { attachmentId, title, utcDateModified } = entity;+ return getAttachmentImageUrl(attachmentId, title, utcDateModified);}return "";}diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex aa11c62a07..99e400a5ca 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -9,6 +9,7 @@ import { highlightBlockReference } from "./block_reference.js";import { default as content_renderer, type RenderOptions } from "./content_renderer.js";import froca from "./froca.js";import { t } from "./i18n.js";+import { resolveContentImageUrls } from "./image_urls.js";import link from "./link.js";import { applyLinkEmbeds } from "./link_embed.js";import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";@@ -36,7 +37,7 @@ export async function renderTextContent() {const hasContent = content !== undefined && !isHtmlEmpty(content);const $content = $('<div class="ck-content">')- .html(hasContent ? sanitizeNoteContentHtml(content) : "");+ .html(hasContent ? resolveContentImageUrls(sanitizeNoteContentHtml(content)) : "");if (options.block !== undefined && !sliceToBlockReference($content[0], options.block)) {$renderedContent.append($("<p>")diff --git a/apps/client/src/services/image_urls.spec.ts b/apps/client/src/services/image_urls.spec.tsnew file mode 100644index 0000000000..115856bae9--- /dev/null+++ b/apps/client/src/services/image_urls.spec.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it } from "vitest";++import {+ getAttachmentImageUrl, getNoteImageUrl, resolveContentImageUrls, setImageUrlResolver+} from "./image_urls.js";++describe("image URLs", () => {+ afterEach(() => {+ setImageUrlResolver(undefined);+ });++ it("points at the API, unless the resolver finds the image elsewhere", () => {+ expect(getNoteImageUrl("note1", "A b/c", "v=1")).toBe("api/images/note1/A%20b%2Fc?v=1");+ expect(getAttachmentImageUrl("att1", "x.png")).toBe("api/attachments/att1/image/x.png");++ setImageUrlResolver((target) => ("noteId" in target+ ? (target.noteId === "note1" ? "../files/note1.png" : null)+ : `../files/${target.attachmentId}.svg`));+ expect(getNoteImageUrl("note1", "A", "v=1")).toBe("../files/note1.png");+ expect(getNoteImageUrl("note2", "B")).toBe("api/images/note2/B");+ expect(getAttachmentImageUrl("att1", "x.png", "1")).toBe("../files/att1.svg");+ });++ it("points the images a note's HTML embeds where the resolver finds them", () => {+ const html = `<img src="api/images/note1/A?123"><img src="api/images/note2/B">`+ + `<section data-image="api/attachments/att1/image/x.png" data-favicon="https://a/b.ico">`+ + `<img src="../../api/attachments/att2/image/y.svg"><a href="api/images/note1/A">`;+ expect(resolveContentImageUrls(html)).toBe(html);++ setImageUrlResolver((target) => ("noteId" in target+ ? (target.noteId === "note1" ? "files/note1.png" : null)+ : `files/${target.attachmentId}`));+ expect(resolveContentImageUrls(html)).toBe(`<img src="files/note1.png">`+ + `<img src="api/images/note2/B">`+ + `<section data-image="files/att1" data-favicon="https://a/b.ico">`+ + `<img src="files/att2"><a href="api/images/note1/A">`);+ });+});diff --git a/apps/client/src/services/image_urls.ts b/apps/client/src/services/image_urls.tsnew file mode 100644index 0000000000..8d051368e0--- /dev/null+++ b/apps/client/src/services/image_urls.ts@@ -0,0 +1,59 @@+/** What an image URL points at: the image of a note, or an image attachment. */+export type ImageTarget = { noteId: string } | { attachmentId: string };++/** Finds the URL of an image somewhere other than the API, or returns `null` to keep the API's. */+export type ImageUrlResolver = (target: ImageTarget) => string | null;++let resolveImageUrl: ImageUrlResolver | undefined;++/**+ * Sets where the views find images, which only a page hosting them outside the app knows, such as+ * a page of the static export, which holds the images as files.+ */+export function setImageUrlResolver(resolver: ImageUrlResolver | undefined) {+ resolveImageUrl = resolver;+}++/**+ * Returns the URL of the image of the note `noteId`, titled `title`: `api/images/<noteId>/<title>`+ * with `query`, which keeps a browser from showing a cached copy, unless the resolver has another.+ */+export function getNoteImageUrl(noteId: string, title: string, query?: string) {+ return resolveImageUrl?.({ noteId })+ ?? `api/images/${noteId}/${encodeURIComponent(title)}${toQuery(query)}`;+}++/**+ * Returns the URL of the image attachment `attachmentId`, titled `title`:+ * `api/attachments/<attachmentId>/image/<title>` with `query`, unless the resolver has another.+ */+export function getAttachmentImageUrl(attachmentId: string, title: string, query?: string) {+ return resolveImageUrl?.({ attachmentId })+ ?? `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}${toQuery(query)}`;+}++/**+ * Points the images a note's HTML embeds from the API, in `src` and in a link preview's+ * `data-image` and `data-favicon`, where the resolver finds them. Runs on the HTML before it is+ * parsed into the page, which loads an image as soon as it parses its element.+ */+export function resolveContentImageUrls(html: string) {+ if (!resolveImageUrl) {+ return html;+ }++ return html.replace(CONTENT_IMAGE_URL, (match, attribute: string, noteId?: string,+ attachmentId?: string) => {+ const target = noteId ? { noteId } : { attachmentId: attachmentId ?? "" };+ const url = resolveImageUrl?.(target);+ return url ? `${attribute}="${url}"` : match;+ });+}++/** An image of the API in an attribute of a note's HTML, naming a note or an attachment. */+const CONTENT_IMAGE_URL =+ /(src|data-image|data-favicon)="[^"]*?api\/(?:images\/(\w+)\/|attachments\/(\w+)\/image\/)[^"]*"/g;++function toQuery(query: string | undefined) {+ return query === undefined ? "" : `?${query}`;+}diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 303e075acc..f2e0af6c10 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -7,6 +7,7 @@ import { getCachedBlockReferenceLabel, loadBlockReferenceLabel } from "./block_eimport cssClassManager from "./css_class_manager.js";import froca from "./froca.js";import { t } from "./i18n.js";+import { getNoteImageUrl } from "./image_urls.js";import { showError } from "./toast.js";import treeService from "./tree.js";import utils, { isShare } from "./utils.js";@@ -191,10 +192,8 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptioconst note = await froca.getNote(noteId);if (autoConvertToImage && note?.type && ["image", "canvas", "mermaid"].includes(note.type) && viewMode === "default") {- const encodedTitle = encodeURIComponent(linkTitle || "");-return $("<img>")- .attr("src", `api/images/${noteId}/${encodedTitle}?${Math.random()}`)+ .attr("src", getNoteImageUrl(noteId, linkTitle || "", String(Math.random()))).attr("alt", linkTitle || "");}diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 689a3d53e8..9dc34b3006 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -1,6 +1,7 @@import { dayjs, filterAttributeName, isValidAttributeName } from "@triliumnext/commons";import FNote from "../entities/fnote";+import { getNoteImageUrl } from "./image_urls.js";import type { ViewMode, ViewScope } from "./link.js";const SVG_MIME = "image/svg+xml";@@ -677,7 +678,7 @@ function copyHtmlToClipboard(html: string, plainText: string = html) {}export function createImageSrcUrl(note: FNote) {- return `api/images/${note.noteId}/${encodeURIComponent(note.title)}?timestamp=${Date.now()}`;+ return getNoteImageUrl(note.noteId, note.title, `timestamp=${Date.now()}`);}diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 595db4af46..4bb8e12d67 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -7,6 +7,7 @@ import FNote from "../../../entities/fnote";import branches from "../../../services/branches";import froca from "../../../services/froca";import { t } from "../../../services/i18n";+import { getNoteImageUrl } from "../../../services/image_urls";import server from "../../../services/server";import toast from "../../../services/toast";import { fileAccept } from "../../../services/utils";@@ -602,7 +603,7 @@ function useImageMap(note: FNote): ImageMapState {// Absolute, as MapLibre resolves a source's URL against its worker rather than the page.const url = imageNote && new URL(- `api/images/${imageNote.noteId}/${encodeURIComponent(imageNote.title)}?v=${version}`, document.baseURI).href;+ getNoteImageUrl(imageNote.noteId, imageNote.title, `v=${version}`), document.baseURI).href;const size = url ? await measureImage(url) : null;if (!url || !size) {fail("unloadable");diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsxindex 0be8ae4cba..5b7dd3747b 100644--- a/apps/client/src/widgets/type_widgets/Attachment.tsx+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx@@ -22,6 +22,7 @@ import { attachmentRoleLabel } from "../../services/attachment_role_names";import content_renderer, { hasRenderedPreview } from "../../services/content_renderer";import froca from "../../services/froca";import image from "../../services/image";+import { getAttachmentImageUrl } from "../../services/image_urls";import { type ViewScope } from "../../services/link";import options from "../../services/options";import protected_session_holder from "../../services/protected_session_holder";@@ -236,7 +237,7 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view&& attachment.mime === CANVAS_ATTACHMENT_MIME&& (!attachment.isProtected || protected_session_holder.isProtectedSessionAvailable());const rendersItself = isZoomableImage || isPlayableMedia || isEditableDrawing;- const imageSrc = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}?${modified}`;+ const imageSrc = getAttachmentImageUrl(attachment.attachmentId, attachment.title, modified);/** Unmounts whatever the content renderer previously mounted here (a media player), so that replacing* or discarding the content doesn't leak its Preact root — or leave its audio playing. */diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsxindex efe94d90a3..154a6797a6 100644--- a/packages/share-theme/src/content/app_host.tsx+++ b/packages/share-theme/src/content/app_host.tsx@@ -5,6 +5,7 @@ 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 { setImageUrlResolver } from "@triliumnext/client/src/services/image_urls.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";@@ -38,7 +39,7 @@ 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. */+ /** On a page of the static export, the source reading the export's files. */staticSource?: StaticFrocaSource;}@@ -79,11 +80,7 @@ export default function ShareAppHost({ noteId, payload, children }: ShareAppHost}const onClick = (event: MouseEvent) => openNoteLink(event, app);document.addEventListener("click", onClick);- const stopImages = app.staticSource && watchImageUrls(app.staticSource);- return () => {- document.removeEventListener("click", onClick);- stopImages?.();- };+ return () => document.removeEventListener("click", onClick);}, [ app ]);return app && isLoaded && (@@ -101,6 +98,7 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {const staticSource = payload.exportBasePath === undefined? undefined : createStaticFrocaSource(links, payload.exportBasePath);froca.setSource(withRootAnchors(staticSource ?? createShareFrocaSource(links)));+ setImageUrlResolver(staticSource?.getImageUrl);linkContextMenu.setShareLinkResolver((linkedNoteId) => links[linkedNoteId] ?? null);froca.addResp({...anchorAtRoot(rows),@@ -165,47 +163,6 @@ function anchorAtRoot<T extends SubtreeResponse>(rows: T): T {};}-/**- * 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/note_view.tsx b/packages/share-theme/src/content/note_view.tsxindex b7672fab36..38549527bf 100644--- a/packages/share-theme/src/content/note_view.tsx+++ b/packages/share-theme/src/content/note_view.tsx@@ -2,6 +2,7 @@ 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 { getNoteImageUrl } from "@triliumnext/client/src/services/image_urls.js";import type NoteMapWidget 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";@@ -98,7 +99,7 @@ function NoteView({ note }: { note: FNote }) {* of its drawing, in a viewer that takes the page.*/function ImageView({ app: { note } }: { app: HostedApp }) {- const src = `api/images/${note.noteId}/${encodeURIComponent(note.title)}?${note.blobId}`;+ const src = getNoteImageUrl(note.noteId, note.title, note.blobId);return (<ZoomViewer labels={getZoomPanLabels("image_viewer.viewport")} fillsPage><img src={src} alt={note.title} />diff --git a/packages/share-theme/src/content/share_froca_source.spec.ts b/packages/share-theme/src/content/share_froca_source.spec.tsindex 42f7ab5c25..71081a9c38 100644--- a/packages/share-theme/src/content/share_froca_source.spec.ts+++ b/packages/share-theme/src/content/share_froca_source.spec.ts@@ -46,18 +46,17 @@ describe("createStaticFrocaSource", () => {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 () => {+ it("finds the images of the export once it has read its rows", 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();+ expect(source.getImageUrl({ noteId: "image" })).toBeNull();+ await source.loadNotes([]);+ expect(source.getImageUrl({ noteId: "image" })).toBe("data/images/image.png");+ expect(source.getImageUrl({ noteId: "canvas" })).toBe("pages/canvas_svg.svg");+ expect(source.getImageUrl({ attachmentId: "svg" })).toBe("pages/canvas_svg.svg");+ expect(source.getImageUrl({ noteId: "unknown" })).toBeNull();+ expect(source.getImageUrl({ attachmentId: "unknown" })).toBeNull();});it("lists a note's children that are not archived, the one search it answers", async () => {diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex 93761b3228..3915c792e1 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -1,6 +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 type { ImageUrlResolver } from "@triliumnext/client/src/services/image_urls.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. */@@ -65,13 +66,13 @@ interface StaticShareRows extends ShareFrocaRows {noteMaps: Record<string, string>;}-/** A source of froca's notes that also resolves the app's image URLs on a page of the export. */+/** A source of froca's notes that also finds the images 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.+ * The URL of the file of a note's image or of an image attachment, relative to the page, or+ * `null` for one the export does not hold or before the source has read `rows.json`.*/- resolveImageUrl(url: string): Promise<string | null>;+ getImageUrl: ImageUrlResolver;}/**@@ -85,9 +86,13 @@ export function createStaticFrocaSource(links: Record<string, string>,basePath: string): StaticFrocaSource {+ let rows: StaticShareRows | undefined;let rowsPromise: Promise<StaticShareRows> | undefined;const readRows = () => {- rowsPromise ??= getJson<StaticShareRows>(`${basePath}data/rows.json`);+ rowsPromise ??= getJson<StaticShareRows>(`${basePath}data/rows.json`).then((read) => {+ rows = read;+ return read;+ });return rowsPromise;};const resolve = (path: string) => (path ? `${basePath}${path}` : basePath || "./");@@ -146,14 +151,10 @@ export function createStaticFrocaSource(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 ?? ""];+ getImageUrl: (target) => {+ const path = "noteId" in target+ ? rows?.images[target.noteId]+ : rows?.attachmentPaths[target.attachmentId];return path ? resolve(path) : null;}};@@ -162,9 +163,6 @@ export function createStaticFrocaSource(/** 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) {