Keep the frames of pasted GIF, WebP, and AVIF images

A browser puts only the first frame of an image on the clipboard, with
HTML that names the image address.

- Documents and cards download the original of a GIF, WebP, or AVIF
  address. The host commands workspace_save_image_url and
  workspace_download_image read the format from the file contents and
  refuse other data. A failed download keeps the first frame and shows
  a message.
- Copy image in the RuneStone browser keeps the bytes that the page
  loaded. The engine reads them through the DevTools Protocol, so the
  website gets no second request. The new copiedImage command gives
  them in parts below the line limit of the host. A paste uses them
  first.
- An empty dropped image file shows a message. Firefox gives such a
  file when the website refuses its download.

Copy image needs a new browser engine build. Card 0d5c18f7.
This commit is contained in:
Knotty Wyvern
2026-10-31 17:33:08 -07:00
parent 31ce7e73ce
commit 6e1b24e40f
29 changed files with 654 additions and 41 deletions
+5
View File
@@ -88,6 +88,11 @@ function pmCommands(test) {
else workspace.folders.add(rel);
return null;
}),
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
workspace_download_image: ({ url }) => {
if (url.includes("offline")) throw new Error("Cannot reach the image server");
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
+20 -1
View File
@@ -52,9 +52,19 @@ async function startEngine() {
return engine;
}
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
@@ -120,6 +130,15 @@ await runSmoke('browser/interaction', async ({ browser }) => {
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
+52 -1
View File
@@ -28,6 +28,13 @@ await runSmoke("editor/images", async ({ page }) => {
if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64);
},
// The download of a copied web image. The host adds the extension of the downloaded format.
workspace_save_image_url: args => {
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
const rel = args.rel + ".gif";
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
return rel;
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
@@ -196,5 +203,49 @@ await runSmoke("editor/images", async ({ page }) => {
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
// A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
async function pasteWebImage(src) {
await page.locator(".cm-content").evaluate((element, src) => {
const data = new DataTransfer();
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
const writesBefore = await writes();
await pasteWebImage("https://media.example.com/cat.gif?size=large&amp;v=2");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
assert.equal(await writes(), writesBefore);
// When the download fails, the still copy stays.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
assert.equal(await writes(), writesBefore + 1);
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
// An empty file from a browser drag gives a message, not a broken image.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
});
await page.getByText("The image file is empty.", { exact: false }).waitFor();
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
});
+66
View File
@@ -0,0 +1,66 @@
// Project Management card images: a GIF copied in a web browser keeps its original file. A failed download keeps the still copy.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
await runSmoke("features/pmImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
await description.fill("");
// A browser puts a still PNG on the clipboard, with HTML that names the original GIF.
async function pasteWebImage(src) {
await description.evaluate((element, src) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body><!--StartFragment--><img src="${src}"/><!--EndFragment--></body></html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
const reference = name => new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await pasteWebImage("https://media.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.gif\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_download_image").args);
assert.equal(download.url, "https://media.example.com/cat.gif");
// When the download fails, the card gets the still PNG.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.png\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
await editor.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_download_image").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value.match(/!\[image\.gif\]/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.equal(await editor.getByText("The website refused the original image", { exact: false }).count(), 0, "A kept original clears the message");
// An empty file from a browser drag gives a message, not the size limit.
await description.evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }));
});
await editor.getByText("The image file is empty.", { exact: false }).waitFor();
assert.equal(await editor.getByText("Use an image between 1 byte and 50 MiB.").count(), 0);
await editor.locator(".pm-description-actions").getByRole("button", { name: "Save", exact: true }).click();
await waitForFile(page, cardPath("card-a"), /pm-image:.*\n?[\s\S]*pm-image:/);
const body = await fileText(page, cardPath("card-a"));
const gif = reference("image.gif").exec(body)[1], png = reference("image.png").exec(body)[1];
assert.match(await fileText(page, imageFile(gif)), /"data":"data:image\/gif;base64,R0lGOD/);
assert.match(await fileText(page, imageFile(png)), /"data":"data:image\/png;base64,iVBOR/);
console.log("PASS: a pasted web GIF keeps its original file, a copied original needs no download, and failures explain the cause");
});
+47 -1
View File
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { attachmentRel, dataUrlExtension, hasFileDrag, imageFiles, imageInsertion, mayAnimate, pastedImageSource, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { copiedImage, keepCopiedImage } from "../../../src/lib/workspace/copiedImage.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts";
@@ -18,6 +19,51 @@ test("protected file drags and files without MIME metadata are recognized", () =
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
});
test("a copied web image names its original file in the clipboard HTML", () => {
const copy = (src: string) => `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`;
assert.equal(pastedImageSource(copy("https://media.example.com/cat.gif")), "https://media.example.com/cat.gif");
assert.equal(pastedImageSource(copy("https://cdn.example.com/a/b.WEBP?width=200&amp;ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1");
assert.equal(pastedImageSource("<img alt='x' data-src='a.png' src='http://example.com/x.avif'>"), "http://example.com/x.avif");
assert.equal(pastedImageSource("<img src=https://example.com/x.gif>"), "https://example.com/x.gif");
assert.equal(pastedImageSource(copy("https://example.com/photo.jpg")), "https://example.com/photo.jpg");
// Firefox copies the element of the page with all of its attributes.
assert.equal(pastedImageSource('<img id="img" src="https://h.example.net/om/1/x.gif" style="width:640px" onload="update()">'), "https://h.example.net/om/1/x.gif");
// A missing address and other schemes keep the clipboard copy.
assert.equal(pastedImageSource(copy("data:image/gif;base64,R0lGODlh")), undefined);
assert.equal(pastedImageSource(copy("file:///C:/cat.gif")), undefined);
assert.equal(pastedImageSource(copy("cat.gif")), undefined);
assert.equal(pastedImageSource('<img srcset="https://example.com/x.gif 1x">'), undefined);
assert.equal(pastedImageSource(""), undefined);
// A copy of a page part with two images is not a copied image.
assert.equal(pastedImageSource(copy("https://example.com/a.gif") + copy("https://example.com/b.gif")), undefined);
});
test("only formats with frames get a download, and data URLs name their extension", () => {
assert.equal(mayAnimate("https://media.example.com/cat.gif"), true);
assert.equal(mayAnimate("https://cdn.example.com/a/b.WEBP?width=200"), true);
assert.equal(mayAnimate("http://example.com/x.avif"), true);
assert.equal(mayAnimate("https://example.com/photo.jpg"), false);
assert.equal(mayAnimate("https://example.com/image?format=gif"), false);
assert.equal(dataUrlExtension("data:image/gif;base64,R0lGODlh"), "gif");
assert.equal(dataUrlExtension("data:image/jpeg;base64,/9j/"), "jpg");
assert.equal(dataUrlExtension("data:image/webp;base64,UklG"), "webp");
assert.equal(dataUrlExtension("data:image/svg+xml;base64,PHN2Zz4="), undefined);
assert.equal(dataUrlExtension("data:text/html;base64,PGh0bWw+"), undefined);
});
test("a paste uses only the original of the image that the RuneStone browser copied last", async () => {
assert.equal(await copiedImage("https://example.com/a.gif"), undefined);
let finish: (value: string) => void = () => {};
keepCopiedImage("https://example.com/a.gif", new Promise(resolve => { finish = resolve; }));
const waiting = copiedImage("https://example.com/a.gif");
finish("data:image/gif;base64,R0lGODlh");
assert.equal(await waiting, "data:image/gif;base64,R0lGODlh");
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
keepCopiedImage("https://example.com/b.gif", Promise.reject(new Error("engine stopped")));
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
assert.equal(await copiedImage("https://example.com/a.gif"), undefined, "a newer copy replaces the older one");
});
test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");