From f9bdbe0467ad8d9ad67ed34cee6411300cd2599f Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Sat, 31 Oct 2026 19:58:00 -0700 Subject: [PATCH] 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, .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) --- docs/development.md | 2 + docs/guides/project-management.md | 1 + .../features/pm/storage/description-draft.ts | 55 ++++++++- src/lib/features/pm/storage/images.ts | 9 +- src/lib/features/pm/ui/images-ui.ts | 23 +++- src/lib/features/pm/ui/ui.ts | 24 ++-- tests/smoke/features/pmDraftImages.smoke.mjs | 90 +++++++++++++++ .../features/pm/description-draft.spec.ts | 108 ++++++++++++++++++ 8 files changed, 295 insertions(+), 17 deletions(-) create mode 100644 tests/smoke/features/pmDraftImages.smoke.mjs create mode 100644 tests/unit/features/pm/description-draft.spec.ts diff --git a/docs/development.md b/docs/development.md index cd67ee6..1aa45f3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -232,6 +232,8 @@ Git, Background, Terminal, PDF Viewer, and Project Management are native feature - `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code. - Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command. - Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it. +- Project Management deletes no files. A description draft is `.runestone/pm/drafts/.json`. The data of its unsaved images is in `.images.json` in the same folder. Thus a text change does not write the images again. + Only a save of the description or the card writes `.runestone/pm/images/.json`. **Save** and **Cancel** of the description replace the draft and its image record with empty records. As a result, a discarded draft leaves no image file. - `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`. - The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code. - The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin. diff --git a/docs/guides/project-management.md b/docs/guides/project-management.md index cb53123..fbeda3b 100644 --- a/docs/guides/project-management.md +++ b/docs/guides/project-management.md @@ -52,6 +52,7 @@ A card can be on more than one board, with a different list on each board. The card details have the title, the labels, and the description in Markdown. A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker. +An image that you paste or drop into a draft stays with the draft. **Save** adds the image to the card. **Cancel** removes it. Board and list changes save at once. Other fields save when you close the card details. ### Card details diff --git a/src/lib/features/pm/storage/description-draft.ts b/src/lib/features/pm/storage/description-draft.ts index 73cc2e7..9e261ed 100644 --- a/src/lib/features/pm/storage/description-draft.ts +++ b/src/lib/features/pm/storage/description-draft.ts @@ -1,34 +1,77 @@ import type { Workspace } from "../model/model.ts"; import { readOptional, saveDocument } from "./persistence.ts"; import { message } from "./message.ts"; +import { imagePath, parseImage } from "./images.ts"; -/** A draft is separate from the saved card and uses compare-and-write protection. */ +const invalidDraft = () => new Error(message("The description draft is invalid. Preserve it before recovery.")); +const sameImages = (a: ReadonlyMap, b: ReadonlyMap) => + a.size === b.size && [...a].every(([id, data]) => b.get(id) === data); + +/** + * A draft is separate from the saved card and uses compare-and-write protection. + * A second file keeps the data of the images that only the draft uses. Thus a text change does not write the images again. + * The image folder gets an image only from a save of the description or the card. A discarded draft keeps an empty image record, so no image file stays behind. + */ export class DescriptionDraft { private source: string | null = null; + private imageSource: string | null = null; + private images: ReadonlyMap = new Map(); private queue: Promise = Promise.resolve(); readonly path: string; + readonly imagesPath: string; private workspace: Workspace; constructor(workspace: Workspace, id: string) { this.workspace = workspace; const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join(""); this.path = `.runestone/pm/drafts/${key}.json`; + this.imagesPath = `.runestone/pm/drafts/${key}.images.json`; } async load(): Promise { this.source = await readOptional(this.workspace, this.path); if (this.source === null) return null; const value = JSON.parse(this.source); if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string")) - throw new Error(message("The description draft is invalid. Preserve it before recovery.")); + throw invalidDraft(); return value.body; } - save(body: string | null): Promise { + /** The image data of the draft, by image ID. A draft of an earlier version has no image record. Call this before `save`. */ + async loadImages(): Promise> { + this.images = new Map(); + this.imageSource = await readOptional(this.workspace, this.imagesPath); + if (this.imageSource === null) return new Map(); + const value = JSON.parse(this.imageSource); + if (value?.schema !== 1 || typeof value.images !== "object" || value.images === null || Array.isArray(value.images)) + throw invalidDraft(); + const images = new Map(); + for (const [id, data] of Object.entries(value.images)) { + try { imagePath(id); images.set(id, parseImage(JSON.stringify({ schema: 1, data }))); } + catch { throw invalidDraft(); } + } + this.images = images; + return new Map(images); + } + /** Save the text of the draft and the data of the images that only the draft uses. A `null` body discards the draft and its images. */ + save(body: string | null, images: ReadonlyMap = new Map()): Promise { const write = this.queue.then(async () => { + const next = body === null ? new Map() : images; + // Keep the old and the new image data until the text is saved, so that each saved reference has its data. + await this.saveImages(new Map([...this.images, ...next])); const source = JSON.stringify({ schema: 1, body }) + "\n"; - if (source === this.source || (body === null && this.source === null)) return; - await saveDocument(this.workspace, this.path, source, this.source); - this.source = source; + if (source !== this.source && !(body === null && this.source === null)) { + await saveDocument(this.workspace, this.path, source, this.source); + this.source = source; + } + await this.saveImages(next); }); this.queue = write.catch(() => {}); return write; } + private async saveImages(images: ReadonlyMap) { + if (sameImages(images, this.images) || (!images.size && this.imageSource === null)) return; + const sorted = [...images].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); + const source = JSON.stringify({ schema: 1, images: Object.fromEntries(sorted) }) + "\n"; + await saveDocument(this.workspace, this.imagesPath, source, this.imageSource); + this.imageSource = source; + this.images = new Map(images); + } } diff --git a/src/lib/features/pm/storage/images.ts b/src/lib/features/pm/storage/images.ts index 52ea91c..4aed01a 100644 --- a/src/lib/features/pm/storage/images.ts +++ b/src/lib/features/pm/storage/images.ts @@ -51,13 +51,16 @@ export function parseImage(source: string): string { throw new Error(message("The saved image is invalid or exceeds 50 MiB.")); return value.data; } +/** Write the pending images that `body`, `attachments`, or `ids` refer to. Returns the IDs of the written images. */ export async function saveImages( workspace: Workspace, body: string, - pending: Map, + pending: ReadonlyMap, attachments: TaskFields["attachments"] = [], + ids: string[] = [], ) { - for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) { + const saved: string[] = []; + for (const id of new Set([...[...imageReferences(body), ...attachments].map((image) => image.id), ...ids])) { const data = pending.get(id); if (!data) continue; const source = JSON.stringify({ schema: 1, data }) + "\n"; @@ -66,5 +69,7 @@ export async function saveImages( // Retrying a failed card save reuses its complete image files. const previous = await workspace.readOptional?.(path); if (previous !== source) await saveDocument(workspace, path, source, null); + saved.push(id); } + return saved; } diff --git a/src/lib/features/pm/ui/images-ui.ts b/src/lib/features/pm/ui/images-ui.ts index 114b68b..1794623 100644 --- a/src/lib/features/pm/ui/images-ui.ts +++ b/src/lib/features/pm/ui/images-ui.ts @@ -369,7 +369,26 @@ export function createCardImages( saving = value; updateControls(); }, - save: (body: string) => saveImages(workspace, body, pending, attachments), + /** Write the images of `body`, of the attachments, and of `ids`, for example the card cover. */ + async save(body: string, ids: string[] = []) { + for (const id of await saveImages(workspace, body, pending, attachments, ids)) { + // The image file now holds the data, so the description draft does not keep it. + const data = pending.get(id); + if (!data) continue; + loaded.set(id, Promise.resolve(data)); + pending.delete(id); + } + }, + /** The data of the unsaved images that `body` refers to. The description draft keeps it. */ + draftImages: (body: string) => new Map(imageReferences(body).flatMap(ref => { + const data = pending.get(ref.id); + return data ? [[ref.id, data] as const] : []; + })), + /** Add the image data of a restored description draft, and show the images of the restored text. */ + restore(images: ReadonlyMap) { + for (const [id, data] of images) if (!pending.has(id)) pending.set(id, data); + void render(); + }, dispose() { disposed = true; clearTimeout(idleTimer); @@ -377,7 +396,7 @@ export function createCardImages( viewerObserver = undefined; viewer?.remove(); viewer = undefined; revision++; - pending.clear(); + // Keep the pending image data. A draft save that is in progress after a close still needs it. loaded.clear(); description.removeEventListener("paste", paste); description.removeEventListener("input", render); diff --git a/src/lib/features/pm/ui/ui.ts b/src/lib/features/pm/ui/ui.ts index a87ba00..0c7bd5b 100644 --- a/src/lib/features/pm/ui/ui.ts +++ b/src/lib/features/pm/ui/ui.ts @@ -1051,7 +1051,11 @@ export function mountPM( description, (name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"), (name, action) => iconButton(name, "close", action), - (loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); }, + (loading) => { + save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); + // The input event of a pasted image comes while the image loads. Save the draft after the load. + if (!loading) scheduleDraft(); + }, task?.attachments, ); const formattingIcons: Record = { @@ -1064,9 +1068,10 @@ export function mountPM( let descriptionSaving = false; let draftTimer: ReturnType | undefined; let draftEdited = false; - const draftReady = draft?.load().then(body => { + const draftReady = draft && Promise.all([draft.load(), draft.loadImages()]).then(([body, draftImages]) => { if (body !== null && !draftEdited && dialog.isConnected) { descriptionEditor.restoreDraft(body); + images.restore(draftImages); updateDescriptionBadge(task!.id, body !== task!.body); } }); @@ -1074,8 +1079,13 @@ export function mountPM( clearTimeout(draftTimer); await draftReady; if (!draft || !task) return; - await images.save(description.value); - await draft.save(description.value === task.body ? null : description.value); + const body = description.value; + // The draft keeps the data of its unsaved images. The image files come only with a save of the description or the card. + await draft.save(body === task.body ? null : body, images.draftImages(body)); + }; + const scheduleDraft = () => { + clearTimeout(draftTimer); + if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300); }; const reportDraftError = (reason: unknown) => { error.textContent = errorText(reason); }; void draftReady?.catch(reportDraftError); @@ -1113,8 +1123,7 @@ export function mountPM( description.addEventListener("input", () => { draftEdited = true; if (task) updateDescriptionBadge(task.id, description.value !== task.body); - clearTimeout(draftTimer); - if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300); + scheduleDraft(); }); const useSharedChoices = sharedChoice; const updateChoice = sharedChoices.update; @@ -1549,7 +1558,8 @@ export function mountPM( const ok = await perform( async () => { await flushDraft(); - await images.save(body); + // The cover can be an image that only the description draft has. + await images.save(body, cover.value ? [cover.value] : []); const existingIds = new Set(store.tasks.map(candidate => candidate.id)); await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged)) ? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body }) diff --git a/tests/smoke/features/pmDraftImages.smoke.mjs b/tests/smoke/features/pmDraftImages.smoke.mjs new file mode 100644 index 0000000..e3e428a --- /dev/null +++ b/tests/smoke/features/pmDraftImages.smoke.mjs @@ -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."); +}); diff --git a/tests/unit/features/pm/description-draft.spec.ts b/tests/unit/features/pm/description-draft.spec.ts new file mode 100644 index 0000000..39e5ed8 --- /dev/null +++ b/tests/unit/features/pm/description-draft.spec.ts @@ -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); +});