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(editor): embed images on copy so notes paste into external apps
Elian Doran96fadcba250b
diff --git a/apps/client/src/services/image.ts b/apps/client/src/services/image.tsindex bc57d86d37..a2d594c58e 100644--- a/apps/client/src/services/image.ts+++ b/apps/client/src/services/image.ts@@ -175,9 +175,80 @@ function selectImage(element: HTMLElement | undefined) {selection?.addRange(range);}+/**+ * Largest data: URI (in characters) we put on the clipboard for a single embedded image. Beyond+ * this the image is left as an internal reference (the previous behavior) so the clipboard isn't+ * bloated by a huge photo. A base64 data URI is ~1.37x the encoded byte size.+ */+const MAX_EMBED_DATA_URL_LENGTH = 12_000_000;++/**+ * 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}.+ *+ * 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+ * photos, but the only option that doesn't block the clipboard write). A cross-origin image would+ * taint the canvas and make `toDataURL` throw; internal images are same-origin, so that's only a+ * defensive catch.+ */+export function embedReferenceImageAsDataUrl(src: string): string | null {+ if (!getImageDownloadUrl(src)) {+ return null; // not an internal note/attachment image — leave it untouched+ }++ const image = findLoadedImage(src);+ if (!image) {+ return null;+ }++ try {+ const canvas = document.createElement("canvas");+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext("2d");+ if (!context || !canvas.width || !canvas.height) {+ return null;+ }+ context.drawImage(image, 0, 0);++ 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;+ } catch {+ return null; // e.g. a tainted canvas — fall back to the reference+ }+}++/** 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)) {+ if (image.getAttribute("src") === src && image.complete && image.naturalWidth > 0) {+ return image;+ }+ }+ return null;+}++/** Pick an output encoding from the source extension so photos stay JPEG instead of bloating to PNG. */+function inferEncodeMimeType(src: string): string {+ const path = src.split(/[?#]/)[0].toLowerCase();+ if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {+ return "image/jpeg";+ }+ if (path.endsWith(".webp")) {+ return "image/webp";+ }+ return "image/png";+}+export default {copyImageReferenceToClipboard,copyImageToClipboard,downloadImage,+ embedReferenceImageAsDataUrl,isImageCopySupported};diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex bfbbe7cdce..824cfa999b 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -199,6 +199,14 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConficonst imageToolbar = (config.image as { toolbar: (string | object)[] }).toolbar;imageToolbar.push("|", ...(imageService.isImageCopySupported() ? ["copyImageToClipboard"] : []), "downloadImage");+ // 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 = {+ enabled: options.get("clipboardImageEmbedEnabled") === "true",+ embedImage: (src: string) => imageService.embedReferenceImageAsDataUrl(src)+ };+// Set up content language.const { contentLanguage } = opts;if (contentLanguage) {diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 3084b9ff1f..5c89cc823b 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -26,6 +26,7 @@ import { Math, AutoformatMath } from "@triliumnext/ckeditor5-math";import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";import CopyLinkUrlButton from "./plugins/copy_link_url.js";import ImageActions from "./plugins/image_actions.js";+import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";// import "@triliumnext/ckeditor5-mermaid/index.css";// import "@triliumnext/ckeditor5-admonition/index.css";@@ -80,6 +81,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [CopyAnchorLinkButton,CopyLinkUrlButton,ImageActions,+ ClipboardImageEmbed,];/**diff --git a/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts b/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.tsnew file mode 100644index 0000000000..604fcc4ace--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_image_embed.spec.ts@@ -0,0 +1,230 @@+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";++/** A representative internal image reference and the data: URI a resolver would hand back. */+const REFERENCE = "api/images/noteId123/photo.png";+const DATA_URI = "data:image/png;base64,AAAA";++/** A minimal stand-in for the view DataTransfer that records what the serializer writes to it. */+function recordingDataTransfer() {+ const store: Record<string, string> = {};+ return {+ store,+ setData: (type: string, data: string) => { store[type] = data; },+ getData: (type: string) => store[type] ?? ""+ };+}++describe("ClipboardImageEmbed", () => {++ // --- The pure view-fragment transforms (the business logic). ---++ describe("embedClipboardImageReferences", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph]);+ });++ function embed(html: string, embedImage: (src: string) => string | null): string {+ const fragment = editor.data.processor.toView(html) as ViewDocumentFragment;+ embedClipboardImageReferences(editor.editing.view, fragment, embedImage);+ return editor.data.processor.toData(fragment);+ }++ it("rewrites an internal image to a data: URI and stashes the original reference", () => {+ const result = embed(`<img src="${REFERENCE}">`, () => DATA_URI);++ expect(result).toContain(`src="${DATA_URI}"`);+ expect(result).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);+ });++ it("leaves an image untouched when the resolver declines it (returns null)", () => {+ const result = embed(`<img src="https://example.com/x.png">`, () => null);++ expect(result).toContain(`src="https://example.com/x.png"`);+ expect(result).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });++ it("is idempotent: an already-embedded image is not re-encoded", () => {+ const embedImage = vi.fn(() => DATA_URI);++ const result = embed(`<img src="${DATA_URI}" ${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}">`, embedImage);++ expect(embedImage).not.toHaveBeenCalled();+ expect(result).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);+ });++ it("skips an image without a src attribute", () => {+ const embedImage = vi.fn(() => DATA_URI);++ const result = embed(`<img alt="no source">`, embedImage);++ expect(embedImage).not.toHaveBeenCalled();+ expect(result).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });++ it("embeds only the images the resolver accepts within a mixed fragment", () => {+ const embedImage = (src: string) => (src === REFERENCE ? DATA_URI : null);++ const result = embed(`<p>text</p><img src="${REFERENCE}"><img src="https://ext/y.png">`, embedImage);++ expect(result).toContain(`src="${DATA_URI}"`);+ expect(result).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);+ expect(result).toContain(`src="https://ext/y.png"`);+ });++ it("does nothing (and never calls the resolver) for a fragment with no images", () => {+ const embedImage = vi.fn(() => DATA_URI);++ const result = embed(`<p>just text</p>`, embedImage);++ expect(embedImage).not.toHaveBeenCalled();+ expect(result).toBe(`<p>just text</p>`);+ });+ });++ describe("restoreClipboardImageReferences", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph]);+ });++ function restore(html: string): string {+ const fragment = editor.data.processor.toView(html) as ViewDocumentFragment;+ restoreClipboardImageReferences(editor.editing.view, fragment);+ return editor.data.processor.toData(fragment);+ }++ it("restores the src from the marker and drops the marker attribute", () => {+ const result = restore(`<img src="${DATA_URI}" ${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}">`);++ expect(result).toContain(`src="${REFERENCE}"`);+ expect(result).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ expect(result).not.toContain("data:image");+ });++ it("leaves an image without the marker untouched", () => {+ const result = restore(`<img src="${DATA_URI}">`);++ expect(result).toContain(`src="${DATA_URI}"`);+ });++ it("is the inverse of embedding (round-trips back to the original reference)", () => {+ const embedded = (() => {+ const fragment = editor.data.processor.toView(`<img src="${REFERENCE}">`) as ViewDocumentFragment;+ embedClipboardImageReferences(editor.editing.view, fragment, () => DATA_URI);+ return editor.data.processor.toData(fragment);+ })();++ expect(restore(embedded)).toContain(`src="${REFERENCE}"`);+ expect(restore(embedded)).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });+ });++ // --- The plugin wiring: that the transforms run on the real clipboard pipeline events. ---++ describe("plugin", () => {+ it("registers under its name and requires the clipboard pipeline", async () => {+ const editor = await createTestEditor([Essentials, Paragraph, ClipboardImageEmbed]);++ expect(editor.plugins.get(ClipboardImageEmbed)).toBeInstanceOf(ClipboardImageEmbed);+ expect(ClipboardImageEmbed.pluginName).toBe("ClipboardImageEmbed");+ expect(ClipboardImageEmbed.requires).toContain(ClipboardPipeline);+ });++ describe("on copy (clipboardOutput)", () => {+ async function copy(html: string, clipboardImageEmbed?: Record<string, unknown>): Promise<string> {+ const editor = await createTestEditor(+ [Essentials, Paragraph, Image, ImageBlock, ImageInline, ClipboardImageEmbed],+ clipboardImageEmbed ? { clipboardImageEmbed } : {}+ );+ const dataTransfer = recordingDataTransfer();+ const content = editor.data.processor.toView(html) as ViewDocumentFragment;++ editor.editing.view.document.fire("clipboardOutput", { dataTransfer, content, method: "copy" });++ return dataTransfer.getData("text/html");+ }++ it("embeds internal images in the serialized clipboard HTML", async () => {+ const html = await copy(`<figure class="image"><img src="${REFERENCE}"></figure>`, {+ enabled: true,+ embedImage: () => DATA_URI+ });++ expect(html).toContain(`src="${DATA_URI}"`);+ expect(html).toContain(`${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}"`);+ });++ it("does not embed when the kill-switch option is disabled", async () => {+ const html = await copy(`<figure class="image"><img src="${REFERENCE}"></figure>`, {+ enabled: false,+ embedImage: () => DATA_URI+ });++ expect(html).toContain(`src="${REFERENCE}"`);+ expect(html).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });++ it("does not embed when no resolver is configured", async () => {+ const html = await copy(`<figure class="image"><img src="${REFERENCE}"></figure>`, { enabled: true });++ expect(html).toContain(`src="${REFERENCE}"`);+ expect(html).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });++ it("does not embed when the feature is not configured at all", async () => {+ const html = await copy(`<figure class="image"><img src="${REFERENCE}"></figure>`);++ expect(html).toContain(`src="${REFERENCE}"`);+ expect(html).not.toContain(TRILIUM_SRC_ATTRIBUTE);+ });+ });++ describe("on paste (inputTransformation)", () => {+ let editor: ClassicEditor;+ let fileRepository: FileRepository;+ let createLoader: ReturnType<typeof vi.spyOn>;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Image, ImageBlock, ImageInline, ImageUpload, ClipboardImageEmbed]);+ fileRepository = editor.plugins.get(FileRepository);+ // Spy on loader creation: ImageUploadEditing calls it for every "local" (data:/blob:)+ // image it decides to upload, so it is the precise signal for "an upload was attempted".+ createLoader = vi.spyOn(fileRepository, "createLoader");+ editor.setData("<p>start</p>");+ });++ function paste(html: string) {+ const content = editor.data.processor.toView(html) as ViewDocumentFragment;+ editor.plugins.get(ClipboardPipeline).fire("inputTransformation", {+ content,+ dataTransfer: recordingDataTransfer(),+ method: "paste"+ });+ }++ it("restores the reference and never uploads the embedded copy", () => {+ paste(`<img src="${DATA_URI}" ${TRILIUM_SRC_ATTRIBUTE}="${REFERENCE}">`);++ expect(createLoader).not.toHaveBeenCalled();+ const data = editor.getData();+ expect(data).toContain(REFERENCE);+ expect(data).not.toContain("data:image");+ });++ it("still uploads a genuine external data: image (no marker), so normal paste is unaffected", () => {+ paste(`<img src="${DATA_URI}">`);++ // ImageUploadEditing's upload path is live; only our marked embeds are diverted.+ expect(createLoader).toHaveBeenCalled();+ });+ });+ });+});diff --git a/packages/ckeditor5/src/plugins/clipboard_image_embed.ts b/packages/ckeditor5/src/plugins/clipboard_image_embed.tsnew file mode 100644index 0000000000..297db5a3d9--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_image_embed.ts@@ -0,0 +1,140 @@+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).+ *+ * `embedImage` is given an image `src` and returns a self-contained `data:` URI to embed, or+ * `null` to leave the image untouched (non-internal images, images not yet loaded, or ones over a+ * size cap). The DOM/canvas work lives in the client so this plugin stays platform-agnostic and+ * unit-testable with a stub resolver.+ */+export interface ClipboardImageEmbedConfig {+ enabled?: boolean;+ embedImage?: (src: string) => string | null;+}++/**+ * Makes copying (or dragging out) note content paste correctly into EXTERNAL applications — email+ * clients, word processors — by embedding internal images as `data:` URIs on the clipboard, while+ * keeping internal Trilium→Trilium paste reference-based so no duplicate images are created.+ *+ * - On copy/cut/drag-out (`clipboardOutput`, before the default serializer) each internal image's+ * `src` is rewritten to a `data:` URI, with the original reference stashed in+ * {@link TRILIUM_SRC_ATTRIBUTE} (see {@link embedClipboardImageReferences}).+ * - On paste/drop (`inputTransformation`, before CKEditor's `ImageUploadEditing` would upload the+ * `data:` URI as a brand-new attachment) the reference is restored from that attribute, so the+ * embedded copy is dropped and the note keeps pointing at the original image (see+ * {@link restoreClipboardImageReferences}).+ */+export default class ClipboardImageEmbed extends Plugin {++ static get requires() {+ return [ClipboardPipeline] as const;+ }++ static get pluginName() {+ return "ClipboardImageEmbed" as const;+ }++ init() {+ const editor = this.editor;++ // Embed internal images as data: URIs on the way out (copy / cut / drag-out). Runs before+ // the default `low`-priority serializer so the serialized clipboard HTML carries the URIs.+ this.listenTo<ViewDocumentClipboardOutputEvent>(+ editor.editing.view.document,+ "clipboardOutput",+ (_evt, data) => this._embedImages(data),+ { priority: "high" }+ );++ // Restore references on the way in (paste / drop), before `ImageUploadEditing`'s+ // normal-priority `inputTransformation` listener would otherwise upload the data: URI.+ this.listenTo<ClipboardInputTransformationEvent>(+ editor.plugins.get(ClipboardPipeline),+ "inputTransformation",+ (_evt, data) => this._restoreImages(data),+ { priority: "high" }+ );+ }++ private _embedImages(data: ViewDocumentClipboardOutputEventData) {+ const config = this.editor.config.get("clipboardImageEmbed") as ClipboardImageEmbedConfig | undefined;+ if (!config?.enabled || !config.embedImage) {+ return;+ }++ embedClipboardImageReferences(this.editor.editing.view, data.content, config.embedImage);+ }++ private _restoreImages(data: ClipboardInputTransformationData) {+ restoreClipboardImageReferences(this.editor.editing.view, data.content);+ }+}++/**+ * Rewrite each internal image in a clipboard view fragment to a self-contained `data:` URI,+ * stashing the original reference in {@link TRILIUM_SRC_ATTRIBUTE}. Images that `embedImage`+ * declines (returns `null`), images without a `src`, and images that are already embedded are+ * left untouched, so the pass is idempotent.+ */+export function embedClipboardImageReferences(view: EditingView, fragment: ViewDocumentFragment, embedImage: (src: string) => string | null) {+ forEachImage(view, fragment, (writer, image) => {+ const src = image.getAttribute("src");+ if (typeof src !== "string" || image.hasAttribute(TRILIUM_SRC_ATTRIBUTE)) {+ return;+ }++ const dataUri = embedImage(src);+ if (!dataUri) {+ return;+ }++ writer.setAttribute("src", dataUri, image);+ writer.setAttribute(TRILIUM_SRC_ATTRIBUTE, src, image);+ });+}++/**+ * Inverse of {@link embedClipboardImageReferences}: for every image carrying a+ * {@link TRILIUM_SRC_ATTRIBUTE}, restore its `src` to that internal reference and drop the+ * attribute (and the embedded `data:` URI with it). Images without the marker are left untouched.+ */+export function restoreClipboardImageReferences(view: EditingView, fragment: ViewDocumentFragment) {+ forEachImage(view, fragment, (writer, image) => {+ const reference = image.getAttribute(TRILIUM_SRC_ATTRIBUTE);+ if (typeof reference !== "string") {+ return;+ }++ writer.setAttribute("src", reference, image);+ writer.removeAttribute(TRILIUM_SRC_ATTRIBUTE, image);+ });+}++/** Invoke `callback` for each `<img>` in the fragment, sharing a single upcast writer. */+function forEachImage(view: EditingView, fragment: ViewDocumentFragment, callback: (writer: UpcastWriter, image: ViewElement) => void) {+ const images: ViewElement[] = [];+ for (const { item } of view.createRangeIn(fragment)) {+ if (item.is("element", "img")) {+ images.push(item);+ }+ }+ if (!images.length) {+ return;+ }++ const writer = new UpcastWriter(view.document);+ for (const image of images) {+ callback(writer, image);+ }+}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex a812302d6b..19e34df1cf 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -186,6 +186,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActitextNoteCompletionEnabled: boolean;/** Whether keyboard auto-completion for editing commands is triggered when typing `/`. */textNoteSlashCommandsEnabled: boolean;+ /** Whether copying note content embeds internal images as data: URIs so they paste into external apps (internal paste stays reference-based). Hidden kill-switch. */+ clipboardImageEmbedEnabled: boolean;backgroundEffects: boolean;newLayout: boolean;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 5d3ba8a51c..0beaf54617 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -110,6 +110,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["textNoteEmojiCompletionEnabled","textNoteCompletionEnabled","textNoteSlashCommandsEnabled",+ "clipboardImageEmbedEnabled","includeNoteDefaultBoxSize","layoutOrientation","backgroundEffects",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex c8624e03c9..a0d986b1a2 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -242,6 +242,7 @@ const defaultOptions: DefaultOption[] = [{ name: "textNoteEmojiCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteSlashCommandsEnabled", value: "true", isSynced: true },+ { name: "clipboardImageEmbedEnabled", value: "true", isSynced: true },{ name: "includeNoteDefaultBoxSize", value: "medium", isSynced: true },// HTML import configuration