import type { Workspace } from "../model/model.ts"; import { readOptional, saveDocument } from "./persistence.ts"; import { message } from "./message.ts"; /** A draft is separate from the saved card and uses compare-and-write protection. */ export class DescriptionDraft { private source: string | null = null; private queue: Promise = Promise.resolve(); readonly path: 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`; } 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.")); return value.body; } save(body: string | null): Promise { const write = this.queue.then(async () => { 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; }); this.queue = write.catch(() => {}); return write; } }