Skip to content

Build your personal knowledge base with Trilium Notes

link previews: store the card image as a note attachment, not inline base64

Elian Doran86ac262d7479
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 93f9a3679e..49f54f12ae 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import server from "./server.js";
+import { uploadImageAttachment } from "./image_upload.js";
import {
applyLinkEmbeds,
detectEmbedType,
@@ -9,6 +9,13 @@ import {
renderMentionPreview,
safeHostname
} from "./link_embed.js";
+import server from "./server.js";
+
+vi.mock("./image_upload.js", () => ({
+ uploadImageAttachment: vi.fn()
+}));
+
+const uploadImageAttachmentMock = vi.mocked(uploadImageAttachment);
let container: HTMLDivElement | undefined;
@@ -107,6 +114,57 @@ describe("fetchMetadata", () => {
const result = await fetchMetadata("https://blocked.example.com/x");
expect(result.unresolved).toBe(true);
});
+
+ describe("image offload to attachment", () => {
+ const metaWithDataUriImage = {
+ url: "https://example.com",
+ embedType: "opengraph",
+ title: "Title",
+ favicon: "data:image/png;base64,FAV",
+ image: "data:image/jpeg;base64,IMG"
+ };
+
+ it("stores the image as an attachment of the owning note, keeping the favicon inline", async () => {
+ server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
+ uploadImageAttachmentMock.mockResolvedValueOnce("api/attachments/att1/image/image.jpg");
+
+ const result = await fetchMetadata("https://example.com", "note1");
+
+ expect(uploadImageAttachmentMock).toHaveBeenCalledExactlyOnceWith("note1", "data:image/jpeg;base64,IMG");
+ // Only the attachment URL lands in the note content — inlined base64 would count against
+ // the auto-read-only size threshold. The favicon stays inline: it is small and shared
+ // with inline mentions.
+ expect(result.image).toBe("api/attachments/att1/image/image.jpg");
+ expect(result.favicon).toBe("data:image/png;base64,FAV");
+ });
+
+ it("keeps the data URI when the upload fails, so the preview still persists", async () => {
+ server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
+ uploadImageAttachmentMock.mockResolvedValueOnce(null);
+
+ const result = await fetchMetadata("https://example.com", "note1");
+
+ expect(result.image).toBe("data:image/jpeg;base64,IMG");
+ });
+
+ it("does not upload without an owning note, a non-data-URI image, or a missing image", async () => {
+ uploadImageAttachmentMock.mockClear();
+
+ server.post = vi.fn(async () => metaWithDataUriImage) as typeof server.post;
+ const withoutNote = await fetchMetadata("https://example.com");
+ expect(withoutNote.image).toBe("data:image/jpeg;base64,IMG");
+
+ server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: "https://img.example/x.png" })) as typeof server.post;
+ const remoteImage = await fetchMetadata("https://example.com", "note1");
+ expect(remoteImage.image).toBe("https://img.example/x.png");
+
+ server.post = vi.fn(async () => ({ ...metaWithDataUriImage, image: undefined })) as typeof server.post;
+ const noImage = await fetchMetadata("https://example.com", "note1");
+ expect(noImage.image).toBeUndefined();
+
+ expect(uploadImageAttachmentMock).not.toHaveBeenCalled();
+ });
+ });
});
describe("renderEmbedPreview", () => {
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index e233522783..616ac512a2 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -1,10 +1,11 @@
import "../widgets/type_widgets/text/LinkEmbed.css";
-import { type LinkEmbedMetadata, YOUTUBE_REGEX, extractYouTubeVideoId, safeLinkPreviewHref } from "@triliumnext/commons";
+import { extractYouTubeVideoId, type LinkEmbedMetadata, safeLinkPreviewHref, YOUTUBE_REGEX } from "@triliumnext/commons";
import { render } from "preact";
import { useState } from "preact/hooks";
import { t } from "./i18n.js";
+import { uploadImageAttachment } from "./image_upload.js";
import server from "./server.js";
export interface EmbedMetadata {
@@ -31,8 +32,13 @@ export function safeHostname(url: string): string {
/**
* Fetches link metadata from the server. Called once at link creation time.
* The returned metadata is then stored in the note's HTML as data attributes.
+ *
+ * When `ownerNoteId` is given, the preview image is stored as an attachment of that note and only
+ * its `api/attachments/...` URL ends up in the metadata. Inlined as a base64 data URI it would be
+ * 10–140KB of note content per preview — enough for a single card to push the note past the
+ * `autoReadonlySizeText` threshold (32KB by default) and flip it read-only.
*/
-export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
+export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<EmbedMetadata> {
try {
// POSTed rather than passed in the query string: a URL can carry a one-time token or a
// signed signature, and a query string ends up in every access log along the way.
@@ -44,7 +50,7 @@ export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
description: metadata.description,
favicon: metadata.favicon,
siteName: metadata.siteName,
- image: metadata.image,
+ image: await offloadImageToAttachment(metadata.image, ownerNoteId),
unresolved: metadata.unresolved
};
} catch {
@@ -57,6 +63,22 @@ export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
}
}
+/**
+ * Converts a base64 preview image into an attachment of the owning note, returning its
+ * `api/attachments/...` URL — or the data URI unchanged when the upload fails, so the preview
+ * still persists and renders, just at the old inline cost.
+ *
+ * Only the card image is offloaded. The favicon stays inline on purpose: it is a few KB, and it is
+ * carried by inline mentions too, where an attachment per mention would flood the attachment list.
+ */
+async function offloadImageToAttachment(image: string | undefined, ownerNoteId: string | undefined): Promise<string | undefined> {
+ if (!image || !ownerNoteId || !image.startsWith("data:")) {
+ return image;
+ }
+
+ return await uploadImageAttachment(ownerNoteId, image) ?? image;
+}
+
// ---------------------------------------------------------------------------
// Preact components — render previews from stored metadata, no network requests.
// Used by the CKEditor editing downcast (via component interface), the
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 8f2b5b11db..ad2faee5d1 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -44,7 +44,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
// editor-creation time, so the editor must be recreated when it changes.
const [ multilineToolbar ] = useTriliumOptionBool("textNoteEditorMultilineToolbar");
const [ editor, setEditor ] = useState<CKTextEditor>();
- const { parentComponent, ntxId } = useNoteContext();
+ const { parentComponent, ntxId, note } = useNoteContext();
useKeyboardShortcuts("text-detail", containerRef, parentComponent, ntxId);
@@ -151,7 +151,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
await link.loadReferenceLinkTitle($el, href);
},
async fetchLinkMetadata(url: string) {
- return await linkEmbedService.fetchMetadata(url);
+ return await linkEmbedService.fetchMetadata(url, note?.noteId);
},
detectEmbedType(url: string) {
return linkEmbedService.detectEmbedType(url);
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index d855029b11..2e9e914ca1 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -138,7 +138,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
async fetchLinkMetadata(url: string) {
- return await linkEmbedService.fetchMetadata(url);
+ return await linkEmbedService.fetchMetadata(url, note.noteId);
},
detectEmbedType(url: string) {
return linkEmbedService.detectEmbedType(url);
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.ts
index 4ab6a21426..ca46d6ee6d 100644
--- a/apps/server/src/services/notes.spec.ts
+++ b/apps/server/src/services/notes.spec.ts
@@ -113,6 +113,20 @@ describe("checkImageAttachments", () => {
expect(att.save).not.toHaveBeenCalled();
});
+ it("keeps attachments referenced from a link preview's data-image attribute alive", () => {
+ const note = buildNote({ title: "Test", attachments: [{ title: "image.jpg", role: "image", mime: "image/jpeg" }] });
+ mockAttachmentSaves(note);
+ const [att] = note.getAttachments();
+ att.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";
+
+ // A link preview carries its card image in a data attribute, not an <img src>.
+ const content = `<section class="link-embed" data-url="https://example.com"` +
+ ` data-image="api/attachments/${att.attachmentId}/image/image.jpg"></section>`;
+ checkImageAttachments(note, content);
+
+ expect(att.utcDateScheduledForErasureSince).toBeNull();
+ });
+
it("schedules unreferenced attachments for erasure", () => {
const note = buildNote({ title: "Test", attachments: [{ title: "test.png", role: "image", mime: "image/png" }] });
mockAttachmentSaves(note);
diff --git a/packages/trilium-core/src/services/export/single.spec.ts b/packages/trilium-core/src/services/export/single.spec.ts
index 6d3ed65182..d7cf5377b2 100644
--- a/packages/trilium-core/src/services/export/single.spec.ts
+++ b/packages/trilium-core/src/services/export/single.spec.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
-import { mapByNoteType } from "./single.js";
+import { describe, expect, it, vi } from "vitest";
+
+import becca from "../../becca/becca.js";
+import type BAttachment from "../../becca/entities/battachment.js";
import { buildNote } from "../../test/becca_easy_mocking.js";
+import { mapByNoteType } from "./single.js";
describe("Note type mappings", () => {
it("supports mermaid note", () => {
@@ -30,6 +33,29 @@ describe("Note type mappings", () => {
}
});
+ it("inlines a link preview's data-image attachment as base64 in single-note HTML export", () => {
+ // A link preview references its card image attachment from `data-image`, not an <img src>;
+ // the single-file export must inline it the same way to stay self-contained.
+ const note = buildNote({ type: "text", title: "Preview" });
+ const fakeAttachment = {
+ mime: "image/jpeg",
+ getContent: () => new Uint8Array([1, 2, 3])
+ } as unknown as BAttachment;
+ const getAttachment = vi.spyOn(becca, "getAttachment").mockReturnValue(fakeAttachment);
+
+ try {
+ const content = `<section class="link-embed" data-url="https://example.com"`
+ + ` data-image="api/attachments/att1/image/preview.jpg"></section>`;
+ const { payload } = mapByNoteType(note, content, "html");
+
+ expect(getAttachment).toHaveBeenCalledWith("att1");
+ expect(payload).toContain(`data-image="data:image/jpeg;base64,AQID"`);
+ expect(payload).not.toContain("api/attachments");
+ } finally {
+ getAttachment.mockRestore();
+ }
+ });
+
it("exports a spreadsheet note verbatim with a .triliumsheet extension", () => {
// Like canvas/mermaid, single-note spreadsheet export is a lossless raw dump of the stored
// Univer workbook JSON — no conversion (the editor's own CSV/XLSX buttons cover interchange).
diff --git a/packages/trilium-core/src/services/export/single.ts b/packages/trilium-core/src/services/export/single.ts
index dcc1477ce4..b7746fa036 100644
--- a/packages/trilium-core/src/services/export/single.ts
+++ b/packages/trilium-core/src/services/export/single.ts
@@ -135,7 +135,9 @@ function inlineAttachments(content: string) {
return `src="${srcValue}"`;
});
- content = content.replace(/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/?[^"]+"/g, (match, attachmentId) => {
+ // `data-image` is where link previews (section.link-embed) keep their card image reference;
+ // inlining it keeps the exported file self-contained just like an <img> src.
+ content = content.replace(/(src|data-image)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/?[^"]+"/g, (match, attrName, attachmentId) => {
const attachment = becca.getAttachment(attachmentId);
if (!attachment || !attachment.mime.startsWith("image/")) {
return match;
@@ -149,7 +151,7 @@ function inlineAttachments(content: string) {
const base64Content = encodeBase64(attachmentContent);
const srcValue = `data:${attachment.mime};base64,${base64Content}`;
- return `src="${srcValue}"`;
+ return `${attrName}="${srcValue}"`;
});
content = content.replace(/href="[^"]*#root[^"]*attachmentId=([a-zA-Z0-9_]+)\/?"/g, (match, attachmentId) => {
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index e70289035e..b5eea27dcf 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -357,6 +357,31 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
}
});
+ it("rewrites a link preview's data-image reference to the exported attachment file", async () => {
+ // A link preview stores its card image as an attachment referenced from `data-image`
+ // (not an <img src>), so the attribute must be rewritten to the exported attachment
+ // file just like an image src. The markdown export keeps the preview's raw HTML, so
+ // the same rewrite must land there too.
+ const { note } = createNote("root", { title: "LinkPreviewHost", content: "" });
+ getContext().init(() => {
+ const attachment = note.saveAttachment({ role: "image", mime: "image/jpeg", title: "preview.jpg", content: "jpeg-bytes" });
+ note.setContent(`<section class="link-embed" data-url="https://example.com" data-embed-type="opengraph"` +
+ ` data-title="Example" data-image="api/attachments/${attachment.attachmentId}/image/preview.jpg"></section>`);
+ });
+
+ for (const format of ["html", "markdown"] as const) {
+ const { entries } = await exportSubtree(note.getParentBranches()[0], format);
+ const rootMeta = parseMeta(entries).files[0];
+
+ const attFileName = (rootMeta.attachments ?? [])[0]?.dataFileName ?? "";
+ expect(entries[attFileName], format).toBeDefined();
+
+ const exported = entries[rootMeta.dataFileName ?? ""].toString("utf-8");
+ expect(exported, format).toContain(`data-image="${attFileName}"`);
+ expect(exported, format).not.toContain("api/attachments");
+ }
+ });
+
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 daa978528c..eeecc88d0b 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -274,10 +274,12 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
return url ? `src="${url}"` : match;
});
- content = content.replace(/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, targetAttachmentId) => {
+ // `data-image` is where link previews (section.link-embed / span.link-mention) keep their
+ // card image reference; it points at the exported attachment file just like an <img> src.
+ content = content.replace(/(src|data-image)="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, attrName, targetAttachmentId) => {
const url = findAttachment(targetAttachmentId);
- return url ? `src="${url}"` : match;
+ return url ? `${attrName}="${url}"` : match;
});
content = content.replace(/href="[^"]*#root[^"]*attachmentId=([a-zA-Z0-9_]+)\/?"/g, (match, targetAttachmentId) => {
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 20b7cb0142..6492fd20a7 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -461,6 +461,9 @@ export function checkImageAttachments(note: BNote, content: string) {
: [
// <img src="api/attachments/{id}/image/...">
/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
+ // Link previews reference their card image from a data attribute, not an <img>:
+ // <section class="link-embed" data-image="api/attachments/{id}/image/...">
+ /data-image="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
// <a href="...attachmentId={id}">
/href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g
];