import type { OpenBuffer, TreeEntry } from "./types"; export type DocumentIO = { read: (path: string) => Promise; write: (path: string, contents: string, expected: string) => Promise; image: (path: string) => Promise; kind: (path: string) => "image" | "text"; chrome: (path: string) => OpenBuffer["chrome"]; }; /** One workspace's documents. UI components never own the saved baseline. */ export class Documents { buffers: OpenBuffer[] = []; activePath: string | null = null; private opening = new Map>(); private saving = new Map>(); private selection = 0; private refreshVersion = 0; private disposed = false; private io: DocumentIO; private changed: () => void; constructor(io: DocumentIO, changed: () => void) { this.io = io; this.changed = changed; } dispose() { this.disposed = true; this.selection++; this.refreshVersion++; } get dirty() { return this.buffers.some(b => b.contents !== b.saved); } get active() { return this.buffers.find(b => b.relPath === this.activePath); } private emit() { if (!this.disposed) this.changed(); } select(path: string) { this.selection++; if (this.buffers.some(b => b.relPath === path)) { this.activePath = path; this.emit(); } } newTab() { if (this.disposed) return; this.selection++; const id = crypto.randomUUID(); // Empty tabs have an identity but no corresponding workspace file. const relPath = `empty:${id}`; this.buffers.push({ id, relPath, name: "New tab", kind: "empty", imageUrl: null, contents: "", saved: "", chrome: "Writing", chromeOverride: null, }); this.activePath = relPath; this.emit(); } importTab(buffer: OpenBuffer) { if (this.disposed || this.buffers.some(tab => tab.relPath === buffer.relPath)) return false; this.buffers = this.buffers.filter(tab => tab.kind !== "empty"); this.buffers.push({ ...buffer, id: crypto.randomUUID(), tabId: undefined }); this.select(buffer.relPath); return true; } async open(entry: TreeEntry, target: "current" | "new" | "background" = "new") { const request = target === "background" ? this.selection : ++this.selection; const previous = target !== "background" && (target === "current" || this.active?.kind === "empty") ? this.active : undefined; const alreadyOpen = this.buffers.some(b => b.relPath === entry.rel_path); if (!this.buffers.some(b => b.relPath === entry.rel_path)) { let pending = this.opening.get(entry.rel_path); if (!pending) { pending = (async () => { const kind = this.io.kind(entry.rel_path); const value = await (kind === "image" ? this.io.image(entry.rel_path) : this.io.read(entry.rel_path)); if (this.disposed) return; this.buffers.push({ id: crypto.randomUUID(), relPath: entry.rel_path, name: entry.name, kind, imageUrl: kind === "image" ? value : null, contents: kind === "text" ? value : "", saved: kind === "text" ? value : "", chrome: this.io.chrome(entry.rel_path), chromeOverride: null, }); this.emit(); })(); this.opening.set(entry.rel_path, pending); } try { await pending; } finally { this.opening.delete(entry.rel_path); } } if (target !== "background" && !this.disposed && request === this.selection) { // Replace only after a successful read, and never discard edits or disk conflicts. if (!alreadyOpen && previous && !previous.pinned && previous.contents === previous.saved && previous.diskContents === undefined && !previous.diskError) { const index = this.buffers.indexOf(previous); const opened = this.buffers.find(b => b.relPath === entry.rel_path); if (index !== -1 && opened) { opened.tabId = previous.tabId ?? previous.id; this.buffers = this.buffers.filter(b => b !== opened); this.buffers.splice(this.buffers.indexOf(previous), 1, opened); } } this.activePath = entry.rel_path; this.emit(); } } edit(id: string, contents: string) { const buffer = this.buffers.find(b => b.id === id); if (buffer?.kind === "text") { buffer.contents = contents; this.emit(); } } setChrome(chrome: OpenBuffer["chrome"]) { if (this.active) { this.active.chromeOverride = chrome; this.emit(); } } close(path: string) { this.selection++; const index = this.buffers.findIndex(b => b.relPath === path); this.buffers = this.buffers.filter(b => b.relPath !== path); if (this.activePath === path) this.activePath = (this.buffers[index] ?? this.buffers[index - 1])?.relPath ?? null; this.emit(); } togglePin(path: string) { if (this.disposed) return; const buffer = this.buffers.find(b => b.relPath === path); if (!buffer) return; buffer.pinned = !buffer.pinned; this.emit(); } move(path: string, to: number) { if (this.disposed || !Number.isInteger(to)) return; const from = this.buffers.findIndex(b => b.relPath === path); if (from < 0) return; const index = Math.max(0, Math.min(to, this.buffers.length - 1)); if (from === index) return; const [buffer] = this.buffers.splice(from, 1); this.buffers.splice(index, 0, buffer); this.emit(); } rename(from: string, to: string) { for (const b of this.buffers) { if (b.kind === "empty") continue; if (b.relPath === from || b.relPath.startsWith(`${from}/`)) { const next = to + b.relPath.slice(from.length); if (this.activePath === b.relPath) this.activePath = next; b.relPath = next; b.name = next.split("/").pop()!; b.chrome = this.io.chrome(next); } } this.emit(); } save(id: string): Promise { const prior = this.saving.get(id) ?? Promise.resolve(); const pending = prior.then(() => this.write(id)); this.saving.set(id, pending); return pending.finally(() => { if (this.saving.get(id) === pending) this.saving.delete(id); }); } async autosave() { const saved: string[] = []; const failed: { path: string; error: unknown }[] = []; if (this.disposed) return { saved, failed }; await Promise.all(this.buffers.map(async b => { if (b.kind !== "text" || b.contents === b.saved || this.saving.has(b.id) || b.diskContents !== undefined || b.diskError) return; const path = b.relPath; try { await this.save(b.id); saved.push(path); } catch (error) { failed.push({ path, error }); } })); return { saved, failed }; } private async write(id: string) { // Serialize saves of a document, and capture the exact text being written. // Typing while disk I/O is pending must still leave the document dirty. if (this.disposed) return; const b = this.buffers.find(b => b.id === id); if (!b || b.kind !== "text") return; if (b.diskContents !== undefined || b.diskError) throw new Error("Resolve the disk changes before saving."); if (b.contents === b.saved) return; const contents = b.contents; const path = b.relPath; await this.io.write(path, contents, b.saved).then(() => { b.saved = contents; if (b.diskContents === contents) b.diskContents = undefined; this.emit(); }); } async refresh() { const version = ++this.refreshVersion; await Promise.all(this.buffers.map(async b => { if (b.kind === "empty" || this.saving.has(b.id)) return; const baseline = b.saved; const path = b.relPath; try { const disk = await (b.kind === "image" ? this.io.image(path) : this.io.read(path)); if (this.disposed || version !== this.refreshVersion || !this.buffers.includes(b) || b.relPath !== path || this.saving.has(b.id) || b.saved !== baseline) return; b.diskError = null; if (b.kind === "image") { b.imageUrl = disk; return; } if (disk === b.saved) { b.diskContents = undefined; return; } if (b.contents === b.saved || b.contents === disk) { b.contents = disk; b.saved = disk; b.diskContents = undefined; } else { b.diskContents = disk; } } catch (error) { if (!this.disposed && version === this.refreshVersion && this.buffers.includes(b) && b.relPath === path && b.saved === baseline && !this.saving.has(b.id)) { b.diskError = `File unavailable on disk. Your buffer is preserved. ${String(error)}`; } } })); this.emit(); } resolve(id: string, useDisk: boolean) { const b = this.buffers.find(b => b.id === id); if (!b || b.diskContents == null) return; if (useDisk) b.contents = b.diskContents; b.saved = b.diskContents; b.diskContents = undefined; this.emit(); } }