Skip to content

Build your personal knowledge base with Trilium Notes

fix(export): resolve embedded mermaid/canvas images to their rendered attachment

Elian Doranead69de35e2a
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index fc0e7570ec..e70289035e 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -323,6 +323,40 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
expect(Buffer.compare(entries[attFileName], binaryContent)).toBe(0);
});
+ it("resolves embedded mermaid/canvas images to their rendered image attachment", async () => {
+ // A mermaid/canvas note is not an image itself: `api/images/<noteId>` serves its
+ // generated `*-export.svg` attachment. An <img> embedding such a note must therefore
+ // resolve to that attachment, not to the note's own data file (the mermaid source or,
+ // in the share export, the note's HTML page).
+ const cases = [
+ { type: "mermaid", mime: "text/mermaid", content: "flowchart TD\n A --> B", attachment: "mermaid-export.svg" },
+ { type: "canvas", mime: "application/json", content: "{}", attachment: "canvas-export.svg" }
+ ] as const;
+
+ for (const { type, mime, content, attachment } of cases) {
+ const hostTitle = `${type}Host`;
+ const { note: host } = createNote("root", { title: hostTitle, content: "" });
+ const { note: diagram } = createNote(host.noteId, { title: "Diagram", type, mime, content });
+
+ getContext().init(() => {
+ diagram.saveAttachment({ role: "image", mime: "image/svg+xml", title: attachment, content: "<svg/>" });
+ host.setContent(`<p><img src="api/images/${diagram.noteId}/Diagram"></p>`);
+ });
+
+ const { entries } = await exportSubtree(host.getParentBranches()[0], "html");
+ const rootMeta = parseMeta(entries).files[0];
+ const exported = entries[rootMeta.dataFileName ?? ""].toString("utf-8");
+
+ // The SVG really is in the archive, next to the diagram note's own data file.
+ const svgPath = `${hostTitle}/Diagram_${attachment}`;
+ expect(entries[svgPath], svgPath).toBeDefined();
+
+ expect(exported, type).toContain(`src="${svgPath}"`);
+ // ...and not at the diagram note's data file, which no browser can render as an image.
+ expect(exported, type).not.toMatch(/src="[^"]*Diagram\.(txt|json|html)"/);
+ }
+ });
+
it("pipes the archive to the response before appending any content", async () => {
// Memory efficiency: the archive must start streaming to the response
// before note/attachment content is appended, so blobs drain to the
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index 2d743be86e..59cd76e0aa 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -6,6 +6,7 @@ import becca from "../../becca/becca.js";
import BBranch from "../../becca/entities/bbranch.js";
import type BNote from "../../becca/entities/bnote.js";
import dateUtils from "../utils/date.js";
+import { getImageAttachmentTitle } from "../image_attachments.js";
import { getLog } from "../log.js";
import protectedSessionService from "../protected_session.js";
import TaskContext from "../task_context.js";
@@ -210,7 +211,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
return meta as NoteMeta;
}
- function getNoteTargetUrl(targetNoteId: string, sourceMeta: NoteMeta): string | null {
+ function getNoteTargetUrl(targetNoteId: string, sourceMeta: NoteMeta, fileNameOverride?: string): string | null {
const targetMeta = noteIdToMeta[targetNoteId];
if (!targetMeta || !targetMeta.notePath || !sourceMeta.notePath) {
@@ -242,14 +243,31 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
const meta = noteIdToMeta[targetPath[targetPath.length - 1]];
// link can target note which is only "folder-note" and as such, will not have a file in an export
- url += encodeURIComponent(meta.dataFileName || meta.dirFileName || "");
+ url += encodeURIComponent(fileNameOverride ?? (meta.dataFileName || meta.dirFileName || ""));
return url;
}
+ /**
+ * Resolves an `api/images/<noteId>` embed to the file that actually holds the image. For a
+ * mermaid or canvas note that is the exported `*-export.svg` attachment sitting next to the
+ * note's data file, not the data file itself — which holds the diagram source, or the note's
+ * own HTML page in a share export, and renders as a broken image.
+ */
+ function getEmbeddedImageUrl(targetNoteId: string, sourceMeta: NoteMeta): string | null {
+ const targetMeta = noteIdToMeta[targetNoteId];
+ const attachmentTitle = getImageAttachmentTitle(targetMeta?.type);
+ const attachmentMeta = attachmentTitle
+ ? (targetMeta.attachments || []).find((attMeta) => attMeta.title === attachmentTitle)
+ : undefined;
+
+ // Falls back to the note's own data file when the attachment was never generated.
+ return getNoteTargetUrl(targetNoteId, sourceMeta, attachmentMeta?.dataFileName);
+ }
+
function rewriteLinks(content: string, noteMeta: NoteMeta): string {
content = content.replace(/src="[^"]*api\/images\/([a-zA-Z0-9_]+)\/[^"]*"/g, (match, targetNoteId) => {
- const url = getNoteTargetUrl(targetNoteId, noteMeta);
+ const url = getEmbeddedImageUrl(targetNoteId, noteMeta);
return url ? `src="${url}"` : match;
});
diff --git a/packages/trilium-core/src/services/image_attachments.ts b/packages/trilium-core/src/services/image_attachments.ts
new file mode 100644
index 0000000000..44fb9d4a0b
--- /dev/null
+++ b/packages/trilium-core/src/services/image_attachments.ts
@@ -0,0 +1,21 @@
+import { NoteType } from "@triliumnext/commons";
+
+/**
+ * Note types that can be embedded as an image but are not images themselves: `api/images/<noteId>`
+ * serves a generated attachment for them rather than the note's own content. Kept in sync with the
+ * routes that serve those attachments (`routes/api/image.ts` and the share `routes.ts`).
+ */
+const NOTE_TYPE_TO_IMAGE_ATTACHMENT_TITLE: Partial<Record<NoteType, string>> = {
+ canvas: "canvas-export.svg",
+ mermaid: "mermaid-export.svg",
+ mindMap: "mindmap-export.svg",
+ spreadsheet: "spreadsheet-export.png"
+};
+
+/**
+ * The title of the attachment holding the rendered image of the given note type, or `undefined`
+ * if notes of that type are served as images directly.
+ */
+export function getImageAttachmentTitle(type: NoteType | null | undefined): string | undefined {
+ return type ? NOTE_TYPE_TO_IMAGE_ATTACHMENT_TITLE[type] : undefined;
+}
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.ts
index 3e319c2653..e1a65b256e 100644
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@ -192,6 +192,57 @@ describe("processNoteContent", () => {
expect(content).not.toContain("Markdown Note_image.jpg");
});
+ it("restores an embedded mermaid diagram as a note reference, not as a raw attachment", async () => {
+ // The export points the <img> at the mermaid note's generated `mermaid-export.svg`.
+ // On the way back in that has to resolve to `api/images/<noteId>` — which re-renders the
+ // diagram and keeps the #imageLink to the mermaid note — rather than to the raw attachment,
+ // which would freeze the live diagram into a static image owned by nobody.
+ const metaFile = {
+ formatVersion: 2,
+ appVersion: "0.0.0",
+ files: [{
+ noteId: "mermaidHost1",
+ title: "MermaidHost",
+ type: "text",
+ mime: "text/html",
+ format: "html",
+ dataFileName: "MermaidHost.html",
+ dirFileName: "MermaidHost",
+ attachments: [],
+ children: [{
+ noteId: "mermaidDiag1",
+ title: "Diagram",
+ type: "mermaid",
+ mime: "text/mermaid",
+ dataFileName: "Diagram.txt",
+ attachments: [{
+ attachmentId: "mermSvg1",
+ title: "mermaid-export.svg",
+ role: "image",
+ mime: "image/svg+xml",
+ position: 10,
+ dataFileName: "Diagram_mermaid-export.svg"
+ }]
+ }]
+ }]
+ };
+
+ const zipBuffer = await createZipBuffer({
+ "!!!meta.json": JSON.stringify(metaFile),
+ "MermaidHost.html": `<p><img src="MermaidHost/Diagram_mermaid-export.svg"></p>`,
+ "MermaidHost/Diagram.txt": "flowchart TD\n A --> B",
+ "MermaidHost/Diagram_mermaid-export.svg": "<svg/>"
+ });
+
+ const { importedNote } = await testImportBuffer(zipBuffer);
+ const diagram = importedNote.getChildNotes()[0];
+ expect(diagram.type).toBe("mermaid");
+
+ const content = importedNote.getContent() as string;
+ expect(content).toContain(`src="api/images/${diagram.noteId}/`);
+ expect(content).not.toContain("api/attachments/");
+ });
+
it("imports a CSV entry as an editable spreadsheet note", async () => {
const zipBuffer = await createZipBuffer({ "csv_import_sample.csv": "a,b\r\n1,2" });
const { rootNote } = await testImportBuffer(zipBuffer, "import-csv", { spreadsheetImportedAsSpreadsheet: true });
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.ts
index c5850a9486..2b0a8e4364 100644
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@ -8,6 +8,7 @@ import BAttribute from "../../becca/entities/battribute.js";
import BBranch from "../../becca/entities/bbranch.js";
import type BNote from "../../becca/entities/bnote.js";
import attributeService from "../../services/attributes.js";
+import { getImageAttachmentTitle } from "../../services/image_attachments.js";
import { getLog } from "../../services/log.js";
import noteService from "../../services/notes.js";
import { getNoteTitle, newEntityId, removeFileExtension, unescapeHtml } from "../../services/utils/index.js";
@@ -341,7 +342,12 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
return {
attachmentId: getNewAttachmentId(attachmentMeta.attachmentId),
attachmentTitle: attachmentMeta.title,
- noteId: getNewNoteId(noteMeta.noteId)
+ noteId: getNewNoteId(noteMeta.noteId),
+ // The rendered image of a mermaid/canvas note, which the export writes out as a
+ // sibling file. An <img> aimed at it belongs back on `api/images/<noteId>`: that
+ // keeps the embed tied to the live diagram instead of freezing it into a copy of
+ // the exported picture.
+ isRenderedNoteImage: getImageAttachmentTitle(noteMeta.type) === attachmentMeta.title
};
}
// don't check for noteMeta since it's not mandatory for notes
@@ -391,7 +397,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
const target = getEntityIdFromRelativeUrl(url, filePath);
- if (target.attachmentId) {
+ if (target.attachmentId && !target.isRenderedNoteImage) {
return `src="api/attachments/${target.attachmentId}/image/${basename(url)}"`;
} else if (target.noteId) {
return `src="api/images/${target.noteId}/${basename(url)}"`;
@@ -494,7 +500,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
const target = getEntityIdFromRelativeUrl(url, filePath);
- if (target.attachmentId) {
+ if (target.attachmentId && !target.isRenderedNoteImage) {
return `![${alt}](api/attachments/${target.attachmentId}/image/${encodeURIComponent(target.attachmentTitle || "image")})`;
} else if (target.noteId) {
return `![${alt}](api/images/${target.noteId}/${basename(url)})`;