feat(workspace): integrate persisted canvas, element editing and session renewal

This commit is contained in:
2026-11-06 12:50:43 +08:00
parent 45e78f2e43
commit 373582906d
36 changed files with 1028 additions and 193 deletions
+77
View File
@@ -0,0 +1,77 @@
import { decodeCanvas, type CanvasDocument } from "./canvas.ts";
export type CanvasSnapshot = { version: number; document: CanvasDocument };
export type CanvasRequest = <T>(path: string, options?: RequestInit) => Promise<T>;
export type SyncState = { status: "saved" | "saving" | "error"; version: number; error?: string };
export function canvasPath(workspace: string, board: string) {
return `workspaces/${encodeURIComponent(workspace)}/materials/${encodeURIComponent(board)}/canvas`;
}
export function canvasPayload(document: CanvasDocument) {
const clean = decodeCanvas(JSON.stringify(document));
return { ...clean, nodes: clean.nodes.map(({ id, type, position, width, height, data }) => ({ id, type, position, ...(width !== undefined ? { width, height } : {}), data })) };
}
export function canvasFingerprint(document: CanvasDocument) {
return JSON.stringify(canvasPayload(document), (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value);
}
export function decodeSnapshot(value: CanvasSnapshot): CanvasSnapshot {
if (!Number.isSafeInteger(value?.version) || value.version < 1) throw new Error("invalid_canvas_snapshot");
return { version: value.version, document: decodeCanvas(JSON.stringify(value.document)) };
}
/** One writer per board. Coalesce pending snapshots; stop on any rejected write. */
export class CanvasSync {
version: number;
saved: string;
error = "";
private pending: CanvasDocument | null = null;
private running: Promise<void> | null = null;
private request: CanvasRequest;
private path: string;
private notify: (state: SyncState) => void;
constructor(request: CanvasRequest, path: string, initial: CanvasSnapshot, notify: (state: SyncState) => void) {
this.request = request; this.path = path; this.version = initial.version;
this.saved = canvasFingerprint(initial.document); this.notify = notify;
}
enqueue(document: CanvasDocument): Promise<void> {
this.pending = document;
if (this.error) return Promise.resolve();
if (!this.running) this.running = Promise.resolve().then(() => this.drain()).finally(() => { this.running = null; if (this.pending && !this.error) void this.enqueue(this.pending); });
return this.running;
}
retry() { this.error = ""; return this.pending ? this.enqueue(this.pending) : Promise.resolve(); }
private async drain() {
while (this.pending) {
const document = this.pending; this.pending = null;
this.notify({ status: "saving", version: this.version });
try {
const fingerprint = canvasFingerprint(document);
if (fingerprint === this.saved) { this.notify({ status: "saved", version: this.version }); continue; }
const body = JSON.stringify({ document: canvasPayload(document) });
if (new TextEncoder().encode(body).length > 5 * 1024 * 1024) throw new Error("canvas_too_large");
const result = await this.request<{ version: number }>(this.path, { method: "PATCH", headers: { "If-Match": `"${this.version}"` }, body });
if (!Number.isSafeInteger(result?.version) || result.version !== this.version + 1) throw new Error("invalid_canvas_snapshot");
this.version = result.version; this.saved = fingerprint;
this.notify({ status: "saved", version: this.version });
} catch (error) {
this.pending ||= document;
this.error = error instanceof Error ? error.message : "request_failed";
this.notify({ status: "error", version: this.version, error: this.error });
return;
}
}
}
}
export function readLocalRecovery(storage: Pick<Storage, "getItem">, key: string, snapshot?: CanvasSnapshot): CanvasDocument | null {
const record = storage.getItem(key + ":recovery");
if (record) {
const value = JSON.parse(record);
const doc = decodeCanvas(JSON.stringify(value.document));
if (!snapshot || (value.dirty && canvasFingerprint(doc) !== canvasFingerprint(snapshot.document))) return doc;
return null;
}
const legacy = storage.getItem(key);
if (!legacy) return null;
const doc = decodeCanvas(legacy);
return !snapshot || canvasFingerprint(doc) !== canvasFingerprint(snapshot.document) ? doc : null;
}