Keep pasted card images in description drafts

A pasted image arrives while it still loads, so the draft save did not
start. A close of the card then cleared the image data from memory. The
draft kept the text and a reference to an image that RuneStone never
saved.

- A second draft file, <card hex>.images.json, keeps the data of the
  images that only the draft uses.
- Only a save of the description or the card writes image files. Save
  and Cancel empty the draft and its image record, so a discarded draft
  leaves no image file.
- A reopened card restores the images of its draft. The draft saves
  after a pasted image finishes loading. A card save also writes a
  cover image that only the draft has.

New tests: the pmDraftImages smoke test and the description-draft unit
tests.

(cherry picked from commit d9653da579bf8cfc0edd2457f72e658c9fe00fd6)
This commit is contained in:
Knotty Wyvern
2026-10-31 19:58:04 -07:00
parent 3c099e7f49
commit f9bdbe0467
8 changed files with 295 additions and 17 deletions
@@ -0,0 +1,90 @@
// Project Management description drafts with images: an image pasted in an unsaved description survives a close,
// a reopen, and a reload of the card. Save writes the image file. Cancel removes the image data and writes no image file.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, draftPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
const draftImagesPath = id => draftPath(id).replace(/\.json$/, ".images.json");
const json = async (page, path) => JSON.parse(await fileText(page, path) ?? "null");
await runSmoke("features/pmDraftImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const editor = page.locator("dialog.pm-card-editor[open]");
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
const openCard = async title => {
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
};
const closeCard = async () => {
await editor.getByRole("button", { name: "Close card", exact: true }).click();
await editor.waitFor({ state: "detached" });
};
// Paste a 1 by 1 PNG into the description. Returns the image ID of the new reference.
const pasteImage = async name => {
await description.evaluate((element, name) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], name, { type: "image/png" }));
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, name);
const reference = new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await page.waitForFunction(source => new RegExp(source).test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value), reference.source);
return reference.exec(await description.inputValue())[1];
};
// Wait until the gallery thumbnail of `name` shows the decoded image.
const imageLoads = async name => {
await page.waitForFunction(alt => {
const image = document.querySelector(`dialog.pm-card-editor[open] .pm-card-images img[alt="${alt}"]`);
return !!image?.complete && image.naturalWidth > 0;
}, name);
assert.equal(await editor.locator(".pm-card-images .pm-error").allInnerTexts().then(texts => texts.join("")), "");
};
// A pasted image stays with the draft when the card closes. The image folder gets no file yet.
await openCard("Card A");
const first = await pasteImage("dot.png");
await imageLoads("dot.png");
await closeCard();
await waitForFile(page, draftPath("card-a"), new RegExp(`pm-image:${first}`));
assert.match((await json(page, draftImagesPath("card-a"))).images[first], /^data:image\/png;base64,iVBOR/);
assert.equal(await fileText(page, imageFile(first)), undefined, "Only a save writes the image file");
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
// The reopened card restores the draft and shows its image. Save writes the image file and ends the draft.
await openCard("Card A");
await imageLoads("dot.png");
assert.match(await description.inputValue(), new RegExp(`pm-image:${first}`));
await descriptionAction("Save").click();
await waitForFile(page, cardPath("card-a"), new RegExp(`!\\[dot\\.png\\]\\(pm-image:${first}\\)`));
assert.match(await fileText(page, imageFile(first)), /"data":"data:image\/png;base64,iVBOR/);
assert.equal((await json(page, draftPath("card-a"))).body, null);
assert.deepEqual((await json(page, draftImagesPath("card-a"))).images, {});
await closeCard();
await openCard("Card A");
await imageLoads("dot.png");
await closeCard();
// The draft saves after the paste, without another edit, so the image survives a reload of the app.
await openCard("Card B");
const second = await pasteImage("second.png");
await waitForFile(page, draftImagesPath("card-b"), new RegExp(second));
await waitForFile(page, draftPath("card-b"), new RegExp(`pm-image:${second}`));
await page.reload();
await page.locator('[data-tree-rel="note.md"]').waitFor();
await openBoard(page, "Roadmap");
await openCard("Card B");
await imageLoads("second.png");
// Cancel removes the draft and its image data. The image folder gets no file.
await descriptionAction("Cancel").click();
await page.waitForFunction(rel => /"body":null/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-b"));
assert.deepEqual((await json(page, draftImagesPath("card-b"))).images, {});
assert.equal(await fileText(page, imageFile(second)), undefined);
assert.doesNotMatch(await fileText(page, cardPath("card-b")), /pm-image:/);
await closeCard();
console.log("PASS: a draft image survives a close, a reopen, and a reload. Save writes its file. Cancel leaves no image data.");
});
@@ -0,0 +1,108 @@
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
import test from "node:test";
import assert from "node:assert/strict";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { memoryWorkspace } from "./_memory.ts";
const one = "12345678-1234-1234-1234-123456789abc";
const two = "87654321-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
const other = "data:image/gif;base64,R0lGOD==";
/** A workspace that records the path of each write and creation, in order. */
function recorded() {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const writes: string[] = [];
const { write, create } = workspace;
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
return { workspace, writes };
}
test("a draft from an earlier version, without an image record, still loads", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
assert.deepEqual(await reopened.loadImages(), new Map());
await reopened.save("Newer text");
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
});
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
const body = `Text\n${imageMarkdown("a.png", one)}`;
await draft.save(body, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
// A text change does not write the image data again.
await draft.save(`${body}\nMore`, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `${body}\nMore`);
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
// A later save writes the image file from the restored data.
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
});
test("a removed image keeps its data until the text without the reference is saved", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
writes.length = 0;
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
// An image that replaces another one: the record holds both images while the text changes.
writes.length = 0;
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
});
test("a discarded draft keeps no image data and writes no image file", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
writes.length = 0;
await draft.save(null, new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
});
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
await assert.rejects(draft.loadImages(), /description draft is invalid/);
}
workspace.files.delete(draft.imagesPath);
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
await first.loadImages();
await second.loadImages();
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
});
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const pending = new Map([[one, data], [two, other]]);
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
assert.equal(workspace.files.has(imagePath(one)), false);
assert.equal(workspace.files.has(imagePath(two)), true);
});