Skip to content

Build your personal knowledge base with Trilium Notes

feat(editor): embed images when copying rendered note content too

Elian Dorand6166cc28f7a
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.ts
index 6b2dd7ac4b..fddd23ee90 100644
--- a/apps/client/src/desktop.ts
+++ b/apps/client/src/desktop.ts
@@ -5,6 +5,7 @@ import type { ElectronWindowApi } from "@triliumnext/commons";
import appContext, { type CommandNames } from "./components/app_context.js";
import electronContextMenu from "./menus/electron_context_menu.js";
import bundleService from "./services/bundle.js";
+import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
import { t } from "./services/i18n.js";
import { syncNativeWindowWithTheme } from "./services/native_window.js";
@@ -42,6 +43,8 @@ noteTooltipService.setupGlobalTooltip();
noteAutocompleteService.init();
+setupClipboardImageEmbed();
+
if (utils.isElectron()) {
electronContextMenu.setupContextMenu();
}
diff --git a/apps/client/src/mobile.ts b/apps/client/src/mobile.ts
index ed84fa3706..de219db93d 100644
--- a/apps/client/src/mobile.ts
+++ b/apps/client/src/mobile.ts
@@ -1,6 +1,7 @@
import "autocomplete.js/index_jquery.js";
import appContext from "./components/app_context.js";
+import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
import noteAutocompleteService from "./services/note_autocomplete.js";
@@ -10,6 +11,8 @@ await appContext.earlyInit();
noteAutocompleteService.init();
+setupClipboardImageEmbed();
+
// A dynamic import is required for layouts since they initialize components which require translations.
const MobileLayout = (await import("./layouts/mobile_layout.js")).default;
diff --git a/apps/client/src/services/clipboard_image_embed.spec.ts b/apps/client/src/services/clipboard_image_embed.spec.ts
new file mode 100644
index 0000000000..aa714c9af1
--- /dev/null
+++ b/apps/client/src/services/clipboard_image_embed.spec.ts
@@ -0,0 +1,221 @@
+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { setupClipboardImageEmbed } from "./clipboard_image_embed.js";
+import { embedReferenceImageAsDataUrl, resetImageEmbedBudget } from "./image.js";
+import options from "./options.js";
+
+vi.mock("./image.js", () => ({
+ embedReferenceImageAsDataUrl: vi.fn(),
+ resetImageEmbedBudget: vi.fn()
+}));
+
+vi.mock("./options.js", () => ({
+ default: { get: vi.fn() }
+}));
+
+/** A representative internal image reference and the data: URI the canvas resolver hands back. */
+const REFERENCE = "api/images/noteId123/photo.png";
+const DATA_URI = "data:image/png;base64,AAAA";
+
+describe("clipboard image embed", () => {
+
+ beforeAll(() => {
+ // Registered once: the listeners live on `document` for the lifetime of the app, and
+ // re-registering per test would serve each payload several times over.
+ setupClipboardImageEmbed();
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(options.get).mockReturnValue("true");
+ vi.mocked(embedReferenceImageAsDataUrl).mockReturnValue(DATA_URI);
+ });
+
+ afterEach(() => {
+ // Restores any spy a single test installed (e.g. on `getSelection`) without touching the
+ // module mocks above, which are not spies.
+ vi.restoreAllMocks();
+ });
+
+ describe("on copy", () => {
+ it("embeds an internal image, stashes the reference and takes over the payload", () => {
+ renderAndSelect(`<div class="ck-content"><p>before <img src="${REFERENCE}"> after</p></div>`);
+
+ const { store, defaultPrevented } = fireClipboardEvent("copy");
+
+ expect(store["text/html"]).toContain(`src="${DATA_URI}"`);
+ expect(store["text/html"]).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);
+ // The plain-text flavor still carries what the browser would have written.
+ expect(store["text/plain"]).toBe("before after");
+ expect(defaultPrevented).toBe(true);
+ expect(embedReferenceImageAsDataUrl).toHaveBeenCalledWith(REFERENCE);
+ });
+
+ it("re-wraps the ancestor context so a selection inside a list still pastes as a list", () => {
+ const container = render(`<div class="ck-content"><ul><li><p>item <img src="${REFERENCE}"></p></li></ul></div>`);
+ selectContentsOf(container.querySelector("p") as HTMLElement);
+
+ const { store } = fireClipboardEvent("copy");
+
+ // cloneContents() alone would yield the bare paragraph contents, losing <ul>/<li>.
+ expect(store["text/html"]).toBe(`<ul><li><p>item <img src="${DATA_URI}" ${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"></p></li></ul>`);
+ });
+
+ it("leaves the event alone when nothing in the selection can be embedded", () => {
+ vi.mocked(embedReferenceImageAsDataUrl).mockReturnValue(null);
+ renderAndSelect(`<div class="ck-content"><p>text <img src="https://example.com/x.png"></p></div>`);
+
+ const { store, defaultPrevented } = fireClipboardEvent("copy");
+
+ // Falling through to the browser's own (higher-fidelity) serialization.
+ expect(store).toEqual({});
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("stays out of the text editor, which serves its own payload", () => {
+ renderAndSelect(`<div class="ck-editor__editable ck-content"><p>text <img src="${REFERENCE}"></p></div>`);
+
+ const { store, defaultPrevented } = fireClipboardEvent("copy");
+
+ expect(store).toEqual({});
+ expect(defaultPrevented).toBe(false);
+ expect(embedReferenceImageAsDataUrl).not.toHaveBeenCalled();
+ });
+
+ it("ignores a selection outside rendered note content", () => {
+ renderAndSelect(`<div class="tree"><p>a tree item <img src="${REFERENCE}"></p></div>`);
+
+ const { store } = fireClipboardEvent("copy");
+
+ expect(store).toEqual({});
+ expect(embedReferenceImageAsDataUrl).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when the kill-switch option is disabled", () => {
+ vi.mocked(options.get).mockReturnValue("false");
+ renderAndSelect(`<div class="ck-content"><p>text <img src="${REFERENCE}"></p></div>`);
+
+ const { store } = fireClipboardEvent("copy");
+
+ expect(store).toEqual({});
+ expect(embedReferenceImageAsDataUrl).not.toHaveBeenCalled();
+ });
+
+ it("skips an image that already carries the marker, so the pass is idempotent", () => {
+ renderAndSelect(`<div class="ck-content"><p><img src="${DATA_URI}" ${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"></p></div>`);
+
+ const { store, defaultPrevented } = fireClipboardEvent("copy");
+
+ expect(embedReferenceImageAsDataUrl).not.toHaveBeenCalled();
+ expect(store).toEqual({});
+ expect(defaultPrevented).toBe(false);
+ });
+ });
+
+ describe("on dragstart", () => {
+ it("embeds a dragged image without cancelling the drag", () => {
+ const container = render(`<div class="ck-content"><p><img src="${REFERENCE}"></p></div>`);
+ const image = container.querySelector("img") as HTMLImageElement;
+
+ const { store, defaultPrevented } = fireDragStart(image);
+
+ expect(store["text/html"]).toContain(`src="${DATA_URI}"`);
+ expect(store["text/html"]).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);
+ // preventDefault() here would abort the drag outright.
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("does not embed an image dragged from outside note content", () => {
+ const container = render(`<div class="tree"><img src="${REFERENCE}"></div>`);
+
+ const { store } = fireDragStart(container.querySelector("img") as HTMLImageElement);
+
+ expect(store).toEqual({});
+ });
+
+ it("never substitutes the current selection for an image it declined to embed", () => {
+ // An image dragged out of the editor is the editor's business. The selection live at
+ // that moment belongs to unrelated content, so falling back to it would put the wrong
+ // note's content into the drag.
+ document.body.innerHTML = `
+ <div class="ck-content"><p>unrelated <img src="${REFERENCE}"></p></div>
+ <div class="ck-editor__editable ck-content"><p><img src="${REFERENCE}" id="dragged"></p></div>`;
+ selectContentsOf(document.querySelector(".ck-content") as HTMLElement);
+
+ const { store } = fireDragStart(document.querySelector("#dragged") as HTMLImageElement);
+
+ expect(store).toEqual({});
+ });
+ });
+
+ it("hands a multi-range selection back to the browser rather than copying only part of it", () => {
+ const container = render(`<div class="ck-content"><p id="a">one <img src="${REFERENCE}"></p><p id="b">two</p></div>`);
+ selectContentsOf(container.querySelector("#a") as HTMLElement);
+ // Only Firefox actually builds these (Ctrl+drag); Chrome — and happy-dom with it — keeps a
+ // single range, so the second one has to be simulated to exercise the guard at all. The
+ // guard returns before reading anything else off the selection.
+ vi.spyOn(window, "getSelection").mockReturnValue({ isCollapsed: false, rangeCount: 2 } as unknown as Selection);
+
+ const { store, defaultPrevented } = fireClipboardEvent("copy");
+
+ expect(store).toEqual({});
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("resets the shared embed budget for every copy, cut and drag, including ones it does not serve", () => {
+ // The editor consumes the same budget, so the reset has to happen even when this listener
+ // hands the payload back — otherwise a previous copy's spend would carry over into it.
+ renderAndSelect(`<div class="ck-editor__editable ck-content"><p><img src="${REFERENCE}"></p></div>`);
+
+ fireClipboardEvent("copy");
+ fireClipboardEvent("cut");
+ fireDragStart(document.querySelector("img") as HTMLImageElement);
+
+ expect(resetImageEmbedBudget).toHaveBeenCalledTimes(3);
+ });
+});
+
+function render(html: string) {
+ document.body.innerHTML = html;
+ return document.body.firstElementChild as HTMLElement;
+}
+
+function renderAndSelect(html: string) {
+ selectContentsOf(render(html));
+}
+
+function selectContentsOf(node: Node) {
+ const range = document.createRange();
+ range.selectNodeContents(node);
+
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+}
+
+/** Dispatch a copy/cut carrying a recording `clipboardData`, and report what was written to it. */
+function fireClipboardEvent(type: "copy" | "cut") {
+ const store: Record<string, string> = {};
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", {
+ value: { setData: (name: string, data: string) => { store[name] = data; } }
+ });
+
+ document.dispatchEvent(event);
+
+ return { store, defaultPrevented: event.defaultPrevented };
+}
+
+/** Dispatch a dragstart from `target` carrying a recording `dataTransfer`. */
+function fireDragStart(target: HTMLElement) {
+ const store: Record<string, string> = {};
+ const event = new Event("dragstart", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "dataTransfer", {
+ value: { setData: (name: string, data: string) => { store[name] = data; } }
+ });
+
+ target.dispatchEvent(event);
+
+ return { store, defaultPrevented: event.defaultPrevented };
+}
diff --git a/apps/client/src/services/clipboard_image_embed.ts b/apps/client/src/services/clipboard_image_embed.ts
new file mode 100644
index 0000000000..df72e5b143
--- /dev/null
+++ b/apps/client/src/services/clipboard_image_embed.ts
@@ -0,0 +1,192 @@
+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";
+
+import { embedReferenceImageAsDataUrl, resetImageEmbedBudget } from "./image.js";
+import options from "./options.js";
+
+/**
+ * Class shared by every surface that renders note content: read-only text notes, revision previews
+ * and diffs, doc/help notes, Office file previews, canvas note embeddables, and anything rendered
+ * through `content_renderer` (tooltips, included notes, collection previews).
+ */
+const CONTENT_SELECTOR = ".ck-content";
+
+/**
+ * CKEditor's editable carries `.ck-content` too, but its own `ClipboardImageEmbed` plugin has a
+ * better hook there: CKEditor's clipboard serializer reconstructs ancestor context and understands
+ * widget boundaries, which the range-based serialization below only approximates. So it is skipped.
+ */
+const EDITOR_SELECTOR = ".ck-editor__editable";
+
+/**
+ * Embeds internal images as self-contained `data:` URIs whenever *rendered* note content is copied
+ * or dragged out, so it pastes into external applications (email clients, word processors) with the
+ * images intact rather than as `api/images/...` references those applications cannot resolve.
+ *
+ * This is the application-level counterpart to the CKEditor `ClipboardImageEmbed` plugin, which
+ * covers the text editor only — leaving every read-only surface (notably long notes, which switch
+ * to read-only automatically) still copying bare references. Both halves write
+ * {@link TRILIUM_SRC_ATTRIBUTE} next to the embedded URI, so pasting back into a Trilium note
+ * restores the original reference instead of uploading a duplicate.
+ *
+ * When a selection contains nothing embeddable — the common case — the events are left entirely
+ * alone and the browser's own (higher-fidelity) serialization is used.
+ */
+export function setupClipboardImageEmbed() {
+ document.addEventListener("copy", onCopy, { capture: true });
+ document.addEventListener("dragstart", onDragStart, { capture: true });
+ // A cut only ever originates inside the editor, which serializes its own payload — but the
+ // embed budget is shared with it, so it still has to start fresh here.
+ document.addEventListener("cut", () => resetImageEmbedBudget(), { capture: true });
+}
+
+function onCopy(e: ClipboardEvent) {
+ // Reset first and unconditionally: this capture listener runs before the editor's own handler,
+ // so an editor copy is budgeted by the same allowance even though it is served below.
+ resetImageEmbedBudget();
+
+ if (!e.clipboardData || !isEnabled()) {
+ return;
+ }
+
+ const payload = embedSelection();
+ if (!payload) {
+ return;
+ }
+
+ e.clipboardData.setData("text/html", payload.html);
+ e.clipboardData.setData("text/plain", payload.text);
+ e.preventDefault();
+}
+
+function onDragStart(e: DragEvent) {
+ resetImageEmbedBudget();
+
+ if (!e.dataTransfer || !isEnabled()) {
+ return;
+ }
+
+ // Dragging an image itself carries no selection, so that case is built from the element — and
+ // must never fall through to the selection, which at that moment belongs to unrelated content.
+ const payload = e.target instanceof HTMLImageElement
+ ? (contentRootFor(e.target) ? embedImageElement(e.target) : null)
+ : embedSelection();
+ if (!payload) {
+ return;
+ }
+
+ // No `preventDefault()` here — that would cancel the drag. Re-setting the types replaces what
+ // the browser put in the drag data store, leaving the other flavors untouched.
+ e.dataTransfer.setData("text/html", payload.html);
+ e.dataTransfer.setData("text/plain", payload.text);
+}
+
+function isEnabled() {
+ return options.get("clipboardImageEmbedEnabled") === "true";
+}
+
+/** The clipboard payload for the current selection, or `null` when there is nothing to embed. */
+function embedSelection() {
+ const selection = window.getSelection();
+ // Only a single range is serialized below, so a multi-range selection (Firefox allows one to be
+ // built with Ctrl+drag) is handed back to the browser rather than silently copying part of it.
+ if (!selection || selection.isCollapsed || selection.rangeCount !== 1) {
+ return null;
+ }
+
+ const range = selection.getRangeAt(0);
+ const root = contentRootFor(range.commonAncestorContainer);
+ if (!root) {
+ return null;
+ }
+
+ const fragment = range.cloneContents();
+ if (!embedImagesIn(fragment)) {
+ return null;
+ }
+
+ return { html: serialize(fragment, range.commonAncestorContainer, root), text: selection.toString() };
+}
+
+/** The clipboard payload for a single dragged image, or `null` when it cannot be embedded. */
+function embedImageElement(image: HTMLImageElement) {
+ const fragment = document.createDocumentFragment();
+ fragment.appendChild(image.cloneNode(true));
+ if (!embedImagesIn(fragment)) {
+ return null;
+ }
+
+ return { html: serialize(fragment), text: image.src };
+}
+
+/**
+ * Rewrite every internal image in the fragment to a `data:` URI, stashing the reference it replaces
+ * in {@link TRILIUM_SRC_ATTRIBUTE}. Returns whether anything was embedded, so a selection of plain
+ * text (or of images the resolver declined) can be left to the browser untouched.
+ */
+function embedImagesIn(fragment: DocumentFragment) {
+ let embedded = false;
+
+ for (const image of fragment.querySelectorAll("img")) {
+ const src = image.getAttribute("src");
+ if (!src || image.hasAttribute(TRILIUM_SRC_ATTRIBUTE)) {
+ continue;
+ }
+
+ const dataUrl = embedReferenceImageAsDataUrl(src);
+ if (!dataUrl) {
+ continue;
+ }
+
+ image.setAttribute("src", dataUrl);
+ image.setAttribute(TRILIUM_SRC_ATTRIBUTE, src);
+ embedded = true;
+ }
+
+ return embedded;
+}
+
+/**
+ * Serialize a cloned range to clipboard HTML. `cloneContents()` returns only the nodes inside the
+ * range — unlike the browser's own serializer it drops the enclosing context, so a selection made
+ * inside a list or table would otherwise paste as bare paragraphs. Re-wrapping the fragment in the
+ * ancestors between the selection and the note content root puts that structure back.
+ */
+function serialize(fragment: DocumentFragment, from?: Node, root?: HTMLElement) {
+ let container = document.createElement("div");
+ container.appendChild(fragment);
+
+ if (from && root) {
+ for (const ancestor of ancestorsBetween(from, root)) {
+ const wrapper = ancestor.cloneNode(false) as HTMLElement;
+ wrapper.append(...container.childNodes);
+ container = document.createElement("div");
+ container.appendChild(wrapper);
+ }
+ }
+
+ return container.innerHTML;
+}
+
+/** The elements from `node` up to (but excluding) `root`, innermost first. */
+function ancestorsBetween(node: Node, root: HTMLElement) {
+ const ancestors: Element[] = [];
+
+ let current = node instanceof Element ? node : node.parentElement;
+ while (current && current !== root) {
+ ancestors.push(current);
+ current = current.parentElement;
+ }
+
+ return ancestors;
+}
+
+/**
+ * The note-content container holding `node`, or `null` when it is somewhere else entirely (the tree,
+ * a code editor, a plain input) or inside the text editor, which serves itself.
+ */
+function contentRootFor(node: Node | null) {
+ const element = node instanceof Element ? node : node?.parentElement;
+ const root = element?.closest<HTMLElement>(CONTENT_SELECTOR);
+
+ return root && !root.closest(EDITOR_SELECTOR) ? root : null;
+}
diff --git a/apps/client/src/services/image.spec.ts b/apps/client/src/services/image.spec.ts
index 3413ad6740..c1ada360d2 100644
--- a/apps/client/src/services/image.spec.ts
+++ b/apps/client/src/services/image.spec.ts
@@ -1,7 +1,7 @@
import $ from "jquery";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import imageService, { copyImageReferenceToClipboard, copyImageToClipboard, downloadImage, getFileNameFromSrc, getImageDownloadUrl, isImageCopySupported } from "./image.js";
+import imageService, { copyImageReferenceToClipboard, copyImageToClipboard, downloadImage, embedReferenceImageAsDataUrl, getFileNameFromSrc, getImageDownloadUrl, isImageCopySupported, resetImageEmbedBudget } from "./image.js";
import open from "./open.js";
import * as toastModule from "./toast.js";
import toastService from "./toast.js";
@@ -320,6 +320,124 @@ describe("copyImageToClipboard", () => {
});
});
+describe("embedReferenceImageAsDataUrl", () => {
+ const REFERENCE = "api/images/noteId123/photo.png";
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ resetImageEmbedBudget();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("re-encodes a loaded internal image through a canvas sized to the image", () => {
+ appendLoadedImage(REFERENCE, 640, 480);
+ const drawImage = vi.fn();
+ const toDataURL = vi.fn(() => "data:image/png;base64,AAAA");
+ stubCanvasFactory({ getContext: () => ({ drawImage }), toDataURL });
+
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBe("data:image/png;base64,AAAA");
+ expect(drawImage).toHaveBeenCalledTimes(1);
+ // PNG is encoded losslessly, so no quality argument is passed for it.
+ expect(toDataURL).toHaveBeenCalledWith("image/png", undefined);
+ });
+
+ it("infers the output encoding from the source extension so photos do not bloat to PNG", () => {
+ const toDataURL = vi.fn(() => "data:x");
+ stubCanvasFactory({ toDataURL });
+
+ for (const [src, expected] of [["a/b/p.jpg", "image/jpeg"], ["a/b/p.JPEG", "image/jpeg"], ["a/b/p.webp", "image/webp"], ["a/b/p.gif", "image/png"]] as const) {
+ const reference = `api/images/noteId/${src}`;
+ appendLoadedImage(reference, 10, 10);
+
+ embedReferenceImageAsDataUrl(reference);
+
+ expect(toDataURL).toHaveBeenLastCalledWith(expected, expected === "image/png" ? undefined : 0.92);
+ }
+ });
+
+ it("ignores a query string when inferring the encoding, since image URLs carry cache-busters", () => {
+ const reference = "api/images/noteId/photo.jpg?timestamp=123";
+ appendLoadedImage(reference, 10, 10);
+ const toDataURL = vi.fn(() => "data:x");
+ stubCanvasFactory({ toDataURL });
+
+ embedReferenceImageAsDataUrl(reference);
+
+ expect(toDataURL).toHaveBeenLastCalledWith("image/jpeg", 0.92);
+ });
+
+ it("declines anything that is not an internal note or attachment image", () => {
+ const toDataURL = vi.fn(() => "data:x");
+ stubCanvasFactory({ toDataURL });
+
+ expect(embedReferenceImageAsDataUrl("https://example.com/cat.png")).toBeNull();
+ expect(embedReferenceImageAsDataUrl("data:image/png;base64,AAAA")).toBeNull();
+ // No canvas work is attempted for an image that was never a candidate.
+ expect(toDataURL).not.toHaveBeenCalled();
+ });
+
+ it("declines an image that is absent from the document or has not finished loading", () => {
+ stubCanvasFactory({});
+
+ // Nothing rendered at all.
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+
+ // Present, but still loading — encoding it now would yield a blank canvas.
+ appendLoadedImage(REFERENCE, 0, 0);
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+ });
+
+ it("declines when the canvas cannot be drawn to or the encoder throws on a tainted canvas", () => {
+ appendLoadedImage(REFERENCE, 10, 10);
+
+ stubCanvasFactory({ getContext: () => null });
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+
+ vi.restoreAllMocks();
+ stubCanvasFactory({ toDataURL: () => { throw new Error("tainted canvas"); } });
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+ });
+
+ it("declines a single image larger than the per-image cap, falling back to the reference", () => {
+ appendLoadedImage(REFERENCE, 10, 10);
+ const oversized = "d".repeat(12_000_001);
+ stubCanvasFactory({ toDataURL: () => oversized });
+
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+ });
+
+ it("spends a budget shared across one copy, and starts fresh once it is reset", () => {
+ appendLoadedImage(REFERENCE, 10, 10);
+ // Under the 12M per-image cap, so each call is individually acceptable; the 32M total is
+ // what stops the third. One string instance is reused, so this stays cheap.
+ const large = "d".repeat(11_000_000);
+ stubCanvasFactory({ toDataURL: () => large });
+
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBe(large);
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBe(large);
+ // 22M spent, 10M left — this one would overrun, so it stays a reference instead.
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBeNull();
+
+ resetImageEmbedBudget();
+ expect(embedReferenceImageAsDataUrl(REFERENCE)).toBe(large);
+ });
+});
+
+/** A rendered, fully-decoded `<img>`, which is what the synchronous canvas re-encode requires. */
+function appendLoadedImage(src: string, naturalWidth: number, naturalHeight: number) {
+ const image = document.createElement("img");
+ image.setAttribute("src", src);
+ Object.defineProperty(image, "complete", { value: naturalWidth > 0 });
+ Object.defineProperty(image, "naturalWidth", { value: naturalWidth });
+ Object.defineProperty(image, "naturalHeight", { value: naturalHeight });
+ document.body.appendChild(image);
+
+ return image;
+}
+
/** happy-dom's `Image` reports `naturalWidth` 0 and can't decode, so stub a drawable one. */
function stubDrawableImage() {
vi.stubGlobal("Image", class {
@@ -336,13 +454,18 @@ function stubDrawableImage() {
* Spies on `document.createElement` so that a "canvas" tag returns a fake canvas with controllable
* `getContext`/`toBlob`; every other tag delegates to the real factory.
*/
-function stubCanvasFactory(overrides: { getContext?: () => unknown; toBlob?: (cb: (b: Blob | null) => void) => void }) {
+function stubCanvasFactory(overrides: {
+ getContext?: () => unknown;
+ toBlob?: (cb: (b: Blob | null) => void) => void;
+ toDataURL?: (type?: string, quality?: number) => string;
+}) {
const realCreateElement = document.createElement.bind(document);
const fakeCanvas = {
width: 0,
height: 0,
getContext: overrides.getContext ?? (() => ({ drawImage: vi.fn() })),
- toBlob: overrides.toBlob ?? ((cb: (b: Blob | null) => void) => cb(new Blob(["x"], { type: "image/png" })))
+ toBlob: overrides.toBlob ?? ((cb: (b: Blob | null) => void) => cb(new Blob(["x"], { type: "image/png" }))),
+ toDataURL: overrides.toDataURL ?? (() => "data:image/png;base64,AAAA")
};
vi.spyOn(document, "createElement").mockImplementation((tagName: string, options?: ElementCreationOptions) =>
tagName === "canvas" ? (fakeCanvas as unknown as HTMLElement) : realCreateElement(tagName, options)
diff --git a/apps/client/src/services/image.ts b/apps/client/src/services/image.ts
index 4c9195ec00..3cefe48593 100644
--- a/apps/client/src/services/image.ts
+++ b/apps/client/src/services/image.ts
@@ -187,12 +187,30 @@ function selectImage(element: HTMLElement | undefined) {
*/
const MAX_EMBED_DATA_URL_LENGTH = 12_000_000;
+/**
+ * Largest total embedded payload (in characters) for a single copy. The per-image cap above bounds
+ * one photo; this bounds a whole selection, so that `Ctrl+A` on an image-heavy note can't build a
+ * clipboard payload so large the browser refuses to write it — which would turn a working copy into
+ * a silently failing one. Images past the budget stay references, i.e. the previous behavior.
+ */
+const MAX_EMBED_TOTAL_LENGTH = 32_000_000;
+
+let remainingEmbedBudget = MAX_EMBED_TOTAL_LENGTH;
+
+/**
+ * Start a fresh {@link MAX_EMBED_TOTAL_LENGTH} budget. Called for every copy/cut/drag before any
+ * embedding runs, so the budget spans one clipboard operation rather than the session.
+ */
+export function resetImageEmbedBudget() {
+ remainingEmbedBudget = MAX_EMBED_TOTAL_LENGTH;
+}
+
/**
* Synchronously render an already-loaded internal image to a self-contained `data:` URI so the
* clipboard image-embed plugin can inline it for pasting into external applications. Returns
* `null` (leave the image as a reference) when the `src` isn't an internal note/attachment image,
* the image hasn't finished loading, it can't be drawn, or the result would exceed
- * {@link MAX_EMBED_DATA_URL_LENGTH}.
+ * {@link MAX_EMBED_DATA_URL_LENGTH} or what is left of {@link MAX_EMBED_TOTAL_LENGTH}.
*
* Must stay synchronous: it runs inside the browser's `copy`/`dragstart` event, which cannot
* await — ruling out `fetch()`. So the decoded `<img>` is re-encoded through a canvas (lossy for
@@ -222,7 +240,12 @@ export function embedReferenceImageAsDataUrl(src: string): string | null {
const mimeType = inferEncodeMimeType(src);
const dataUrl = canvas.toDataURL(mimeType, mimeType === "image/png" ? undefined : 0.92);
- return dataUrl.length <= MAX_EMBED_DATA_URL_LENGTH ? dataUrl : null;
+ if (dataUrl.length > MAX_EMBED_DATA_URL_LENGTH || dataUrl.length > remainingEmbedBudget) {
+ return null;
+ }
+
+ remainingEmbedBudget -= dataUrl.length;
+ return dataUrl;
} catch {
return null; // e.g. a tainted canvas — fall back to the reference
}
@@ -230,7 +253,7 @@ export function embedReferenceImageAsDataUrl(src: string): string | null {
/** Find a fully-loaded `<img>` currently in the document whose raw `src` attribute matches. */
function findLoadedImage(src: string): HTMLImageElement | null {
- for (const image of Array.from(document.images)) {
+ for (const image of document.querySelectorAll("img")) {
if (image.getAttribute("src") === src && image.complete && image.naturalWidth > 0) {
return image;
}
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index b4e86e2a7b..74088dcebe 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -229,7 +229,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
// Embed internal images as data: URIs when content is copied out to external apps, while
// keeping internal Trilium paste reference-based (see the ClipboardImageEmbed plugin). The
// resolver does the synchronous canvas encoding; the hidden option is a kill-switch.
- (config as Record<string, unknown>).clipboardImageEmbed = {
+ config.clipboardImageEmbed = {
enabled: options.get("clipboardImageEmbedEnabled") === "true",
embedImage: (src: string) => imageService.embedReferenceImageAsDataUrl(src)
};
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index be5082d929..1e11d752a6 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -5,11 +5,13 @@ import "ckeditor5/ckeditor5.css";
import "./theme/blockquote.css";
import "./theme/code_block_toolbar.css";
import "./theme/link_embed_form.css";
+import type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";
import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";
export { default as EditorWatchdog } from "./custom_watchdog";
export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";
export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
+export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
@@ -85,6 +87,7 @@ declare module "ckeditor5" {
},
clipboard?: {
copy(text: string): void;
- }
+ },
+ clipboardImageEmbed?: ClipboardImageEmbedConfig
}
}
diff --git a/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts b/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts
index 604fcc4ace..2c2ac67941 100644
--- a/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts
@@ -1,9 +1,10 @@
+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";
import { ClassicEditor, ClipboardPipeline, Essentials, FileRepository, Image, ImageBlock, ImageInline, ImageUpload, Paragraph } from "ckeditor5";
import type { ViewDocumentFragment } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
-import ClipboardImageEmbed, { embedClipboardImageReferences, restoreClipboardImageReferences, TRILIUM_SRC_ATTRIBUTE } from "./clipboard_image_embed.js";
+import ClipboardImageEmbed, { embedClipboardImageReferences, restoreClipboardImageReferences } from "./clipboard_image_embed.js";
/** A representative internal image reference and the data: URI a resolver would hand back. */
const REFERENCE = "api/images/noteId123/photo.png";
diff --git a/packages/ckeditor5/src/plugins/clipboard_image_embed.ts b/packages/ckeditor5/src/plugins/clipboard_image_embed.ts
index 297db5a3d9..f0cd8442d7 100644
--- a/packages/ckeditor5/src/plugins/clipboard_image_embed.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_image_embed.ts
@@ -1,14 +1,7 @@
+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";
import { ClipboardPipeline, Plugin, UpcastWriter } from "ckeditor5";
import type { ClipboardInputTransformationData, ClipboardInputTransformationEvent, EditingView, ViewDocumentClipboardOutputEvent, ViewDocumentClipboardOutputEventData, ViewDocumentFragment, ViewElement } from "ckeditor5";
-/**
- * View attribute that carries the original internal image reference (e.g.
- * `api/images/<noteId>/...`) next to the embedded `data:` URI on the clipboard. External
- * applications read the `src` (the self-contained data URI); Trilium's own paste handler reads
- * this attribute to restore the reference, so an internal copy/paste never duplicates the image.
- */
-export const TRILIUM_SRC_ATTRIBUTE = "data-trilium-src";
-
/**
* Configuration injected by the host application (see the editor's `clipboardImageEmbed` config).
*
diff --git a/packages/commons/src/lib/shared_constants.ts b/packages/commons/src/lib/shared_constants.ts
index e7600a812c..b2e625c95b 100644
--- a/packages/commons/src/lib/shared_constants.ts
+++ b/packages/commons/src/lib/shared_constants.ts
@@ -57,6 +57,17 @@ export const WEBVIEW_SESSION_PARTITION = "persist:webview";
// sync. Other platforms default to 0 (no limit). See `syncMaxBlobContentSize`.
export const MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE = 20 * 1024 * 1024;
+// Attribute carrying the original internal image reference (`api/images/<noteId>/…`) alongside the
+// embedded `data:` URI Trilium writes to the clipboard when note content is copied out. External
+// applications read `src` — the self-contained data URI — and ignore this; Trilium's own paste
+// handler reads it to restore the reference, so an internal copy/paste keeps pointing at the
+// original image instead of uploading a duplicate.
+//
+// Shared because the two halves live in different packages: the client writes it when copying
+// rendered note content (read-only notes, revisions, previews), and the CKEditor plugin both writes
+// it when copying from the editor and restores it on paste.
+export const TRILIUM_SRC_ATTRIBUTE = "data-trilium-src";
+
// blobId of genuinely empty content, i.e. hashedBlobId(""). A blob row that carries empty content
// but a *different* blobId is a sync stub: its real content was withheld by the sync server because
// it exceeded the client's `syncMaxBlobContentSize`. Because `blobId` is content-derived, this