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): paste a picture copied from another app as the picture itself
Elian Doran728c6f3af633
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex d2248d2663..6a4d5e79db 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -33,6 +33,7 @@ import AutoformatMath from "./plugins/math/autoformat_math.js";import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";import CopyLinkUrlButton from "./plugins/copy_link_url.js";import ImageActions from "./plugins/image_actions.js";+import ClipboardBareImage from "./plugins/clipboard_bare_image.js";import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";import TriliumSnippets from "./plugins/snippets/snippets.js";@@ -91,6 +92,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [CopyLinkUrlButton,ImageActions,ClipboardImageEmbed,+ ClipboardBareImage,TriliumSnippets,];diff --git a/packages/ckeditor5/src/plugins/clipboard_bare_image.spec.ts b/packages/ckeditor5/src/plugins/clipboard_bare_image.spec.tsnew file mode 100644index 0000000000..95a9a17087--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_bare_image.spec.ts@@ -0,0 +1,166 @@+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";+import { ClassicEditor, Essentials, FileRepository, Image, ImageBlock, ImageInline, ImageUpload, Paragraph } from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import ClipboardBareImage, { bareImageFile, isBareImageHtml } from "./clipboard_bare_image.js";++/** What Slack puts on the clipboard for a copied picture: a private URL and nothing else. */+const SLACK_HTML = `<html>+<body>+<!--StartFragment--><img src="https://files.slack.com/files-pri/T017YV03N2V-F08N4H06R8B/image.png" alt="image.png"/><!--EndFragment-->+</body>+</html>`;++/** A mixed selection — text, a mention and a picture — which carries no file to fall back on. */+const GOOGLE_CHAT_HTML = `<html>+<body>+<!--StartFragment--><span><div><span data-name="Elian Doran"><a role="button"><span>@</span><span>Elian Doran</span></a></span>, eu cred ca ceva s-a stricat<br></div><div><div><img src="https://chat.google.com/u/0/api/get_attachment_url?url_type=FIFE_URL&attachment_token=AOo0EEWKpJnS5oUz"></div></div><div>Inainte de merge cu develop aveam ~7 issues<br></div></span><!--EndFragment-->+</body>+</html>`;++function imageFile(name = "image.png", type = "image/png") {+ return new File(["bytes"], name, { type });+}++/**+ * A stand-in for the clipboard `DataTransfer`, carrying whatever flavors a test needs. `types` is+ * here for the sake of upstream's own listener, which reads it whenever this plugin declines and+ * lets the event through.+ */+function clipboard(html: string, files: File[] = []) {+ return {+ types: [...(html ? ["text/html"] : []), ...(files.length ? ["Files"] : [])],+ getData: (type: string) => (type === "text/html" ? html : ""),+ files+ };+}++describe("ClipboardBareImage", () => {++ // --- The rule itself: is the clipboard HTML one picture and nothing else? ---++ describe("isBareImageHtml", () => {+ it("accepts a lone image, however the source wrapped it", () => {+ expect(isBareImageHtml(SLACK_HTML)).toBe(true);+ expect(isBareImageHtml(`<img src="https://ext/a.png">`)).toBe(true);+ // Wrappers are fine — they hold nothing but the image itself.+ expect(isBareImageHtml(`<div><span><img src="https://ext/a.png"></span></div>`)).toBe(true);+ // Chrome writes a charset ahead of the fragment; it carries nothing.+ expect(isBareImageHtml(`<meta charset="utf-8"><img src="https://ext/a.png">`)).toBe(true);+ });++ it("refuses anything carrying text, which is what keeps a Word paste intact", () => {+ // ckeditor/ckeditor5#2830: preferring the clipboard bitmap here would drop the text.+ expect(isBareImageHtml(`<p>see this <img src="https://ext/a.png"></p>`)).toBe(false);+ expect(isBareImageHtml(GOOGLE_CHAT_HTML)).toBe(false);+ });++ it("refuses a fragment that is not exactly one image", () => {+ expect(isBareImageHtml(`<img src="https://ext/a.png"><img src="https://ext/b.png">`)).toBe(false);+ expect(isBareImageHtml(`<p>no pictures at all</p>`)).toBe(false);+ // A sibling element carrying no text is still something more than the picture.+ expect(isBareImageHtml(`<img src="https://ext/a.png"><hr>`)).toBe(false);+ });++ it("leaves images the editor can already resolve to the normal paste path", () => {+ // Self-contained bytes: nothing to gain by preferring the file.+ expect(isBareImageHtml(`<img src="data:image/png;base64,AAAA">`)).toBe(false);+ expect(isBareImageHtml(`<img src="blob:http://localhost/abc">`)).toBe(false);+ // Copied out of Trilium, where the reference beside the payload is the whole point.+ expect(isBareImageHtml(`<img src="data:image/png;base64,AAAA" ${TRILIUM_SRC_ATTRIBUTE}="api/images/n1/p.png">`)).toBe(false);+ });+ });++ describe("bareImageFile", () => {+ it("offers the file that stands in for a bare image", () => {+ const file = imageFile();++ expect(bareImageFile(clipboard(SLACK_HTML, [file]))).toBe(file);+ });++ it("declines when there is no HTML, which upstream already handles", () => {+ expect(bareImageFile(clipboard("", [imageFile()]))).toBeNull();+ });++ it("declines unless exactly one image file is on offer", () => {+ expect(bareImageFile(clipboard(SLACK_HTML, []))).toBeNull();+ // Two files and there is no telling which one the image stands for.+ expect(bareImageFile(clipboard(SLACK_HTML, [imageFile("a.png"), imageFile("b.png")]))).toBeNull();+ // A non-image file is not a candidate at all.+ expect(bareImageFile(clipboard(SLACK_HTML, [new File(["x"], "notes.txt", { type: "text/plain" })]))).toBeNull();+ });++ it("honours the editor's configured upload types", () => {+ const webp = imageFile("a.webp", "image/webp");++ expect(bareImageFile(clipboard(SLACK_HTML, [webp]), ["png", "jpeg"])).toBeNull();+ expect(bareImageFile(clipboard(SLACK_HTML, [webp]), ["png", "webp"])).toBe(webp);+ });++ it("declines when the HTML is more than a picture, even with a file present", () => {+ expect(bareImageFile(clipboard(GOOGLE_CHAT_HTML, [imageFile()]))).toBeNull();+ });+ });++ // --- The wiring: that the rule actually diverts the paste. ---++ describe("plugin", () => {+ let editor: ClassicEditor;+ let createLoader: ReturnType<typeof vi.spyOn>;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Image, ImageBlock, ImageInline, ImageUpload, ClipboardBareImage]);+ // Loader creation is what an upload attempt looks like from the outside.+ createLoader = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");+ editor.setData("<p>start</p>");+ });++ function paste(html: string, files: File[]) {+ const reachedRestOfPipeline = vi.fn();+ // Registered after the plugin's own `high`-priority listener, so it stands in for+ // everything downstream: reached only when the plugin declined the paste. Stopping here+ // keeps the real clipboard pipeline — which a stubbed DataTransfer cannot satisfy — out+ // of the test, while still telling us which way the decision went.+ editor.editing.view.document.on("clipboardInput", (evt) => {+ reachedRestOfPipeline();+ evt.stop();+ }, { priority: "high" });++ editor.editing.view.document.fire("clipboardInput", { dataTransfer: clipboard(html, files), method: "paste" });++ return { reachedRestOfPipeline };+ }++ it("registers under its name and requires image upload", () => {+ expect(editor.plugins.get(ClipboardBareImage)).toBeInstanceOf(ClipboardBareImage);+ expect(ClipboardBareImage.pluginName).toBe("ClipboardBareImage");+ expect(ClipboardBareImage.requires).toContain(ImageUpload);+ });++ it("uploads the clipboard file when the HTML is a bare image, and takes the paste over", () => {+ const file = imageFile();++ const { reachedRestOfPipeline } = paste(SLACK_HTML, [file]);++ expect(createLoader).toHaveBeenCalledTimes(1);+ expect(createLoader).toHaveBeenCalledWith(file);+ // The HTML — and its unreachable URL — never gets inserted.+ expect(reachedRestOfPipeline).not.toHaveBeenCalled();+ });++ it("keeps out of a paste whose HTML carries more than the picture", () => {+ const { reachedRestOfPipeline } = paste(GOOGLE_CHAT_HTML, [imageFile()]);++ expect(createLoader).not.toHaveBeenCalled();+ expect(reachedRestOfPipeline).toHaveBeenCalled();+ });++ it("keeps out of a paste with no file to substitute", () => {+ const { reachedRestOfPipeline } = paste(SLACK_HTML, []);++ expect(createLoader).not.toHaveBeenCalled();+ expect(reachedRestOfPipeline).toHaveBeenCalled();+ });+ });+});diff --git a/packages/ckeditor5/src/plugins/clipboard_bare_image.ts b/packages/ckeditor5/src/plugins/clipboard_bare_image.tsnew file mode 100644index 0000000000..239bea016a--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_bare_image.ts@@ -0,0 +1,138 @@+import { TRILIUM_SRC_ATTRIBUTE } from "@triliumnext/commons";+import { createImageTypeRegExp, ImageUpload, Plugin } from "ckeditor5";+import type { ViewDocumentClipboardInputEvent } from "ckeditor5";++/**+ * The parts of a clipboard `DataTransfer` this plugin reads. Kept structural so the rule below can+ * be exercised without building a real one.+ */+export interface ClipboardImageSource {+ getData(type: string): string;+ files: readonly (File | null)[];+}++/**+ * Elements that carry nothing of their own, so their presence does not stop an image from being the+ * only thing on the clipboard. Chrome routinely writes a `<meta charset>` ahead of the fragment.+ */+const WEIGHTLESS_TAGS = new Set(["META", "STYLE", "LINK", "SCRIPT", "TITLE"]);++/**+ * Makes an image copied from another application paste as the image itself rather than as a broken+ * link to it.+ *+ * Copying a picture in Slack, Google Chat or a browser puts two things on the clipboard: the decoded+ * bytes as a file, and an HTML fragment naming the picture by URL. CKEditor's `ImageUploadEditing`+ * prefers the HTML whenever any is present — deliberately, since a copy from Word carries a bitmap+ * of the selection that must not win over the text (ckeditor/ckeditor5-upload#68). But for a bare+ * image the HTML is the worse of the two: those URLs are usually private to the app that served+ * them (`files.slack.com` answers only to a Slack session cookie), so the note ends up pointing at+ * something neither the server nor the browser can fetch.+ *+ * So the file is preferred over the HTML in exactly one shape — the HTML is a single `<img>` and+ * nothing else, and the clipboard carries exactly one image file. Anything with text in it, or with+ * a second image, keeps the current behavior, which leaves the Word case untouched.+ *+ * A mixed selection of text and pictures carries no file at all — the browser only offers one when+ * the copy *is* a picture — so it cannot be rescued here. Those go on relying on the server+ * fetching the URL after the note is saved (see `image_download.ts`), which works whenever the URL+ * is reachable without the originating app's credentials.+ */+export default class ClipboardBareImage extends Plugin {++ static get requires() {+ return [ImageUpload] as const;+ }++ static get pluginName() {+ return "ClipboardBareImage" as const;+ }++ init() {+ const editor = this.editor;++ // `high`, to get in ahead of `ImageUploadEditing`'s own normal-priority listener — the one+ // that would otherwise hand the paste to the HTML path and never look at the file.+ this.listenTo<ViewDocumentClipboardInputEvent>(+ editor.editing.view.document,+ "clipboardInput",+ (evt, data) => {+ const file = bareImageFile(data.dataTransfer, editor.config.get("image.upload.types"));+ if (!file) {+ return;+ }++ evt.stop();++ editor.model.change((writer) => {+ if (data.targetRanges) {+ writer.setSelection(data.targetRanges.map((range) => editor.editing.mapper.toModelRange(range)));+ }++ editor.execute("uploadImage", { file: [file] });+ });+ },+ { priority: "high" }+ );+ }+}++/**+ * The single image file to paste in place of the clipboard's HTML, or `null` to leave the paste+ * alone. See {@link ClipboardBareImage} for why the shape has to be this narrow.+ */+export function bareImageFile(dataTransfer: ClipboardImageSource, uploadTypes?: string[]): File | null {+ // With no HTML there is nothing to prefer the file over: `ImageUploadEditing` already uploads it.+ if (!dataTransfer.getData("text/html")) {+ return null;+ }++ const pattern = uploadTypes?.length ? createImageTypeRegExp(uploadTypes) : /^image\//;+ const files = dataTransfer.files.filter((file): file is File => !!file && pattern.test(file.type));++ // More than one and there is no telling which belongs to the image; none and there is nothing+ // to offer in the HTML's place.+ if (files.length !== 1) {+ return null;+ }++ return isBareImageHtml(dataTransfer.getData("text/html")) ? files[0] : null;+}++/**+ * Whether the clipboard HTML is one image and nothing besides — no text, no second element standing+ * beside it — and that image is one the editor could not resolve on its own.+ */+export function isBareImageHtml(html: string): boolean {+ const body = new DOMParser().parseFromString(html, "text/html").body;+ if (!body || body.textContent?.trim()) {+ return false;+ }++ const images = body.querySelectorAll("img");+ if (images.length !== 1) {+ return false;+ }++ const image = images[0];+ for (const element of body.querySelectorAll("*")) {+ // Everything else has to be either something wrapping the image or something weightless;+ // an element standing beside it means the clipboard held more than just a picture.+ if (element === image || element.contains(image) || WEIGHTLESS_TAGS.has(element.tagName)) {+ continue;+ }++ return false;+ }++ // An image the editor can already resolve is left to the normal path: a `data:`/`blob:` payload+ // carries its own bytes, and Trilium's own marker means this came from a Trilium copy, where+ // the reference beside it is the point (see the ClipboardImageEmbed plugin).+ if (image.hasAttribute(TRILIUM_SRC_ATTRIBUTE)) {+ return false;+ }++ const src = image.getAttribute("src") ?? "";++ return !src.startsWith("data:") && !src.startsWith("blob:");+}