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
text editor/add a copy/download commands for images
Adorian Doran2ba602b42060
diff --git a/apps/client/src/menus/image_context_menu.ts b/apps/client/src/menus/image_context_menu.tsindex de8bf306a3..298f7364db 100644--- a/apps/client/src/menus/image_context_menu.ts+++ b/apps/client/src/menus/image_context_menu.ts@@ -33,19 +33,13 @@ function setupContextMenu($image: JQuery<HTMLElement>) {if (command === "copyImageReferenceToClipboard") {imageService.copyImageReferenceToClipboard($image);} else if (command === "copyImageToClipboard") {- try {- const src = $image.attr("src");- if (!src) {- console.error("Missing src");- return;- }-- const response = await fetch(src);- const buffer = new Uint8Array(await response.arrayBuffer());- window.electronApi?.clipboard.copyImageToClipboard(buffer);- } catch (error) {- console.error("Failed to copy image to clipboard:", error);+ const src = $image.attr("src");+ if (!src) {+ console.error("Missing src");+ return;}++ await imageService.copyImageToClipboard(src);} else {throw new Error(`Unrecognized command '${command}'`);}diff --git a/apps/client/src/services/image.spec.ts b/apps/client/src/services/image.spec.tsindex 37af54f635..cff97d5c5f 100644--- a/apps/client/src/services/image.spec.ts+++ b/apps/client/src/services/image.spec.ts@@ -1,9 +1,16 @@import $ from "jquery";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import imageService, { copyImageReferenceToClipboard } from "./image.js";+import imageService, { copyImageReferenceToClipboard, downloadImage, getFileNameFromSrc, getImageDownloadUrl, isImageCopySupported } from "./image.js";+import open from "./open.js";import * as toastModule from "./toast.js";import toastService from "./toast.js";+import utils from "./utils.js";++vi.mock("./utils.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./utils.js")>();+ return { ...actual, default: { ...actual.default, isElectron: vi.fn(() => false) } };+});describe("copyImageReferenceToClipboard", () => {let execCommandSpy: ReturnType<typeof vi.fn>;@@ -92,3 +99,82 @@ describe("copyImageReferenceToClipboard", () => {expect(imageService.copyImageReferenceToClipboard).toBe(copyImageReferenceToClipboard);});});++describe("getImageDownloadUrl", () => {+ it("maps note and attachment image URLs to their download endpoints", () => {+ expect(getImageDownloadUrl("api/images/abc123/My%20Image.png")).toBe("api/notes/abc123/download");+ expect(getImageDownloadUrl("api/attachments/att456/image/photo.jpg")).toBe("api/attachments/att456/download");+ });++ it("matches absolute URLs and ignores the query string", () => {+ expect(getImageDownloadUrl("http://localhost:8080/api/images/abc123/x.png?ts=1")).toBe("api/notes/abc123/download");+ });++ it("returns null for sources that aren't note/attachment images", () => {+ expect(getImageDownloadUrl("data:image/png;base64,AAAA")).toBeNull();+ expect(getImageDownloadUrl("https://example.com/cat.png")).toBeNull();+ });+});++describe("getFileNameFromSrc", () => {+ it("uses the decoded last path segment and strips the query", () => {+ expect(getFileNameFromSrc("api/images/abc/My%20Image.png?ts=1")).toBe("My Image.png");+ });++ it("appends an extension from the MIME type when the name has none", () => {+ expect(getFileNameFromSrc("api/images/abc/screenshot", "image/png")).toBe("screenshot.png");+ });++ it("keeps an existing extension and falls back to 'image' for an empty segment", () => {+ expect(getFileNameFromSrc("api/images/abc/photo.jpg", "image/jpeg")).toBe("photo.jpg");+ expect(getFileNameFromSrc("api/images/abc/", "image/png")).toBe("image.png");+ });+});++describe("isImageCopySupported", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("is always supported in Electron, regardless of secure context", () => {+ vi.mocked(utils.isElectron).mockReturnValue(true);+ vi.stubGlobal("isSecureContext", false);+ expect(isImageCopySupported()).toBe(true);+ });++ it("is supported in a secure browser context exposing the Clipboard API", () => {+ vi.mocked(utils.isElectron).mockReturnValue(false);+ vi.stubGlobal("isSecureContext", true);+ vi.stubGlobal("ClipboardItem", class {});+ vi.stubGlobal("navigator", { clipboard: { write: vi.fn() } });+ expect(isImageCopySupported()).toBe(true);+ });++ it("is unsupported on a non-secure origin", () => {+ vi.mocked(utils.isElectron).mockReturnValue(false);+ vi.stubGlobal("isSecureContext", false);+ vi.stubGlobal("ClipboardItem", class {});+ vi.stubGlobal("navigator", { clipboard: { write: vi.fn() } });+ expect(isImageCopySupported()).toBe(false);+ });++ it("is unsupported when the Clipboard API is missing", () => {+ vi.mocked(utils.isElectron).mockReturnValue(false);+ vi.stubGlobal("isSecureContext", true);+ vi.stubGlobal("ClipboardItem", undefined);+ vi.stubGlobal("navigator", { clipboard: undefined });+ expect(isImageCopySupported()).toBe(false);+ });+});++describe("downloadImage", () => {+ it("downloads via the resolved download endpoint instead of the inline image URL", async () => {+ vi.mocked(utils.isElectron).mockReturnValue(false);+ const downloadSpy = vi.spyOn(open, "download").mockImplementation(() => {});++ await downloadImage("api/images/abc123/My%20Image.png");++ expect(downloadSpy).toHaveBeenCalledWith("api/notes/abc123/download");+ downloadSpy.mockRestore();+ });+});diff --git a/apps/client/src/services/image.ts b/apps/client/src/services/image.tsindex ca0d816c5d..6a462d41dc 100644--- a/apps/client/src/services/image.ts+++ b/apps/client/src/services/image.ts@@ -1,5 +1,129 @@import { t } from "./i18n.js";+import open, { getUrlForDownload } from "./open.js";import toastService, { showError } from "./toast.js";+import utils from "./utils.js";++/**+ * Whether copying the raw image to the clipboard is supported in the current environment.+ *+ * Electron has a native clipboard bridge. Browsers expose `ClipboardItem` and+ * `navigator.clipboard.write()` only in secure contexts (HTTPS or localhost) — which Trilium+ * isn't guaranteed to run under — so we feature-detect both rather than assume from the+ * protocol. When unsupported, the browser's own context menu still offers a "Copy image" entry.+ */+export function isImageCopySupported() {+ if (utils.isElectron()) {+ return true;+ }++ return window.isSecureContext && typeof ClipboardItem !== "undefined" && typeof navigator.clipboard?.write === "function";+}++/** Copies the actual image (not a reference to it) to the system clipboard. */+export async function copyImageToClipboard(src: string) {+ try {+ if (utils.isElectron()) {+ const blob = await (await fetch(src)).blob();+ const buffer = new Uint8Array(await blob.arrayBuffer());+ window.electronApi?.clipboard.copyImageToClipboard(buffer);+ } else {+ // The Web Clipboard API reliably accepts only PNG, so render the image to PNG through+ // an <img> + canvas. The browser's own image decoder handles every format it can+ // display (JPEG, WebP, GIF, SVG, …), whereas createImageBitmap rejects some of them.+ // A concrete Blob is written (not a Promise), which Firefox needs.+ const pngBlob = await renderImageToPng(src);+ await navigator.clipboard.write([new ClipboardItem({ "image/png": pngBlob })]);+ }++ toastService.showMessage(t("image.image-copied-to-clipboard"));+ } catch (e) {+ logError(`Failed to copy image to clipboard: ${e}`);+ showError(t("image.cannot-copy-image"));+ }+}++/** Downloads the image to the user's device. */+export async function downloadImage(src: string) {+ // Prefer the note/attachment download endpoint: it responds with `Content-Disposition:+ // attachment`, so the browser saves the file (with a correct name) instead of opening it in a+ // new tab, and it works synchronously — without relying on a transient user activation that an+ // `await` would consume (which is why a fetch-then-anchor download silently does nothing).+ const downloadUrl = getImageDownloadUrl(src);+ if (downloadUrl) {+ open.download(getUrlForDownload(downloadUrl));+ return;+ }++ // Fallback for other sources (e.g. data: URLs): fetch into a blob and save via an object URL.+ try {+ const blob = await (await fetch(src)).blob();+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = getFileNameFromSrc(src, blob.type);+ document.body.appendChild(link);+ link.click();+ link.remove();+ // Defer revocation so the in-flight download isn't cancelled.+ setTimeout(() => URL.revokeObjectURL(url), 10_000);+ } catch (e) {+ logError(`Failed to download image: ${e}`);+ showError(t("image.cannot-download"));+ }+}++/** Maps an embedded image's `src` to the download endpoint of its backing note or attachment. */+export function getImageDownloadUrl(src: string) {+ const noteMatch = src.match(/(?:^|\/)api\/images\/([^/?#]+)\//);+ if (noteMatch) {+ return `api/notes/${noteMatch[1]}/download`;+ }++ const attachmentMatch = src.match(/(?:^|\/)api\/attachments\/([^/?#]+)\/image\//);+ if (attachmentMatch) {+ return `api/attachments/${attachmentMatch[1]}/download`;+ }++ return null;+}++async function renderImageToPng(src: string) {+ // Decode through an <img> element — the browser's full image decoder, which handles every+ // format it can display — rather than createImageBitmap, which rejects some formats (e.g. SVG).+ const image = new Image();+ image.src = src;+ await image.decode();++ const canvas = document.createElement("canvas");+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext("2d");+ if (!context || !canvas.width || !canvas.height) {+ throw new Error("The image has no drawable dimensions.");+ }+ context.drawImage(image, 0, 0);++ return await new Promise<Blob>((resolve, reject) => {+ canvas.toBlob((result) => (result ? resolve(result) : reject(new Error("The image could not be encoded as PNG."))), "image/png");+ });+}++export function getFileNameFromSrc(src: string, mimeType?: string) {+ // Image URLs look like `api/images/<noteId>/<title>` — use the last path segment as the name.+ const path = src.split("?")[0];+ const lastSegment = path.substring(path.lastIndexOf("/") + 1);+ let name = decodeURIComponent(lastSegment) || "image";++ // Ensure an extension, since a blob: URL carries none: derive it from the MIME type.+ if (mimeType && !name.includes(".")) {+ const extension = mimeType.split("/")[1];+ if (extension) {+ name += `.${extension}`;+ }+ }++ return name;+}export function copyImageReferenceToClipboard($imageWrapper: JQuery<HTMLElement>) {try {@@ -34,5 +158,8 @@ function selectImage(element: HTMLElement | undefined) {}export default {- copyImageReferenceToClipboard+ copyImageReferenceToClipboard,+ copyImageToClipboard,+ downloadImage,+ isImageCopySupported};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex d40bd91161..604c7a6ebb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2005,7 +2005,12 @@},"image": {"copied-to-clipboard": "A reference to the image has been copied to clipboard. This can be pasted in any text note.",- "cannot-copy": "Could not copy the image reference to clipboard."+ "cannot-copy": "Could not copy the image reference to clipboard.",+ "copy-to-clipboard": "Copy image to clipboard",+ "download": "Download image",+ "image-copied-to-clipboard": "The image has been copied to clipboard.",+ "cannot-copy-image": "Could not copy the image to clipboard.",+ "cannot-download": "Could not download the image."},"clipboard": {"cut": "Note(s) have been cut into clipboard.",diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 9dd74809a2..7f7e1ab280 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -4,6 +4,7 @@ import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, MIME_TYPE_AUTO, normalizeMimimport { copyTextWithToast } from "../../../services/clipboard_ext.js";import { t } from "../../../services/i18n.js";+import imageService from "../../../services/image.js";import { getMermaidConfig } from "../../../services/mermaid.js";import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";@@ -187,6 +188,16 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi// The app's i18n translate function, so plugins can resolve Trilium translation keys.(config as Record<string, unknown>).translate = (key: string, params?: Record<string, unknown>) => t(key, params);+ // Image toolbar actions (copy / download), handled by the ImageActions plugin. The copy+ // button is only added where copying the raw image is supported (Electron or a secure+ // context); elsewhere the browser's own context menu still offers a "Copy image" entry.+ (config as Record<string, unknown>).imageActions = {+ copyToClipboard: (src: string) => imageService.copyImageToClipboard(src),+ download: (src: string) => imageService.downloadImage(src)+ };+ const imageToolbar = (config.image as { toolbar: (string | object)[] }).toolbar;+ imageToolbar.push("|", ...(imageService.isImageCopySupported() ? ["copyImageToClipboard"] : []), "downloadImage");+// Set up content language.const { contentLanguage } = opts;if (contentLanguage) {diff --git a/packages/ckeditor5/src/icons/download.svg b/packages/ckeditor5/src/icons/download.svgnew file mode 100644index 0000000000..3607f3162d--- /dev/null+++ b/packages/ckeditor5/src/icons/download.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="fill: rgba(0, 0, 0, 1);transform: ;msFilter:;"><path d="M12 16l4-5h-3V4h-2v7H8z"></path><path d="M20 18H4v-7H2v7c0 1.103.897 2 2 2h16c1.103 0 2-.897 2-2v-7h-2v7z"></path></svg>diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 01c8c91a84..cdbf4710cf 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -24,6 +24,7 @@ import { Collapsible } from "@triliumnext/ckeditor5-collapsible";import { Footnotes } from "@triliumnext/ckeditor5-footnotes";import { Math, AutoformatMath } from "@triliumnext/ckeditor5-math";import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";+import ImageActions from "./plugins/image_actions.js";// import "@triliumnext/ckeditor5-mermaid/index.css";// import "@triliumnext/ckeditor5-admonition/index.css";@@ -72,6 +73,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [LinkEmbedToolbar,TodoListMultistate,CopyAnchorLinkButton,+ ImageActions,];/**diff --git a/packages/ckeditor5/src/plugins/image_actions.ts b/packages/ckeditor5/src/plugins/image_actions.tsnew file mode 100644index 0000000000..d25d01b5da--- /dev/null+++ b/packages/ckeditor5/src/plugins/image_actions.ts@@ -0,0 +1,84 @@+import { ButtonView, Command, type Editor, ImageUtils, Plugin } from "ckeditor5";+import copyIcon from "../icons/copy.svg?raw";+import downloadIcon from "../icons/download.svg?raw";++/**+ * Callbacks injected by the host application (see the editor's `imageActions` config) that+ * perform the actual platform-specific work. The plugin only resolves the selected image's+ * `src` and hands it over — the clipboard/download mechanics live in the client.+ */+interface ImageActionsConfig {+ copyToClipboard?: (src: string) => void;+ download?: (src: string) => void;+}++type ImageAction = keyof ImageActionsConfig;++/**+ * Adds "copy to clipboard" and "download" buttons to the image balloon toolbar. The buttons+ * are thin wrappers: they look up the selected image's source and delegate to the callbacks+ * provided in the `imageActions` editor config.+ */+export default class ImageActions extends Plugin {++ static get requires() {+ return [ImageUtils] as const;+ }++ init() {+ this._registerButton("copyImageToClipboard", "image.copy-to-clipboard", copyIcon, "copyToClipboard");+ this._registerButton("downloadImage", "image.download", downloadIcon, "download");+ }++ private _registerButton(name: string, labelKey: string, icon: string, action: ImageAction) {+ const editor = this.editor;+ editor.commands.add(name, new ImageActionCommand(editor, action));++ editor.ui.componentFactory.add(name, (locale) => {+ const button = new ButtonView(locale);+ button.set({+ label: this._translate(labelKey),+ icon,+ tooltip: true+ });+ button.bind("isEnabled").to(editor.commands.get(name)!, "isEnabled");+ this.listenTo(button, "execute", () => editor.execute(name));+ return button;+ });+ }++ private _translate(key: string) {+ const translate = this.editor.config.get("translate") as ((key: string) => string) | undefined;+ return translate ? translate(key) : key;+ }++}++class ImageActionCommand extends Command {++ constructor(editor: Editor, private readonly action: ImageAction) {+ super(editor);+ }++ override refresh() {+ this.isEnabled = !!this._getSelectedImageSrc();+ }++ override execute() {+ const src = this._getSelectedImageSrc();+ if (!src) {+ return;+ }++ const config = this.editor.config.get("imageActions") as ImageActionsConfig | undefined;+ config?.[this.action]?.(src);+ }++ private _getSelectedImageSrc() {+ const imageUtils = this.editor.plugins.get(ImageUtils);+ const imageElement = imageUtils.getClosestSelectedImageElement(this.editor.model.document.selection);+ const src = imageElement?.getAttribute("src");+ return typeof src === "string" ? src : null;+ }++}