Skip to content

gitflarePublicPartly agent-ready50

cf-durable-whiteboard

Realtime collaborative whiteboard on Cloudflare Durable Objects: presence cursors, WebSocket hibernation, SQLite storage, undo, PNG export.

Keep board zoom and pan stable across reloads6eb4fbd
TypeScript70 lines2.1 KB
import type { Op, Shape } from "./validate"; export type Shapes = Map<string, Shape>;export const MAX_OPS = 500; /** Apply op to shapes (mutating); returns the inverse op, or null if no-op. */export function applyOp(shapes: Shapes, op: Op): Op | null {  switch (op.type) {    case "add": {      const prev = shapes.get(op.shape.id);      shapes.set(op.shape.id, op.shape);      return prev ? { type: "update", shape: prev } : { type: "delete", id: op.shape.id };    }    case "update": {      const prev = shapes.get(op.shape.id);      if (!prev) return null;      shapes.set(op.shape.id, op.shape);      return { type: "update", shape: prev };    }    case "delete": {      const prev = shapes.get(op.id);      if (!prev) return null;      shapes.delete(op.id);      return { type: "add", shape: prev };    }    case "clear": {      if (shapes.size === 0) return null;      const all = [...shapes.values()];      shapes.clear();      return { type: "batch", ops: all.map((shape) => ({ type: "add" as const, shape })) };    }    case "batch": {      const inv: Op[] = [];      for (const o of op.ops) { const i = applyOp(shapes, o); if (i) inv.unshift(i); }      return inv.length ? { type: "batch", ops: inv } : null;    }  }} export type Entry = { op: Op; inverse: Op }; export class UndoStacks {  private undo = new Map<string, Entry[]>();  private redo = new Map<string, Entry[]>();  private list(m: Map<string, Entry[]>, u: string) {    let l = m.get(u);    if (!l) m.set(u, (l = []));    return l;  }  record(user: string, e: Entry) {    const u = this.list(this.undo, user);    u.push(e);    if (u.length > MAX_OPS) u.shift();    this.redo.set(user, []);  }  /** Pop an undo entry, returns the op to apply (the inverse). */  popUndo(user: string): Entry | null {    const e = this.list(this.undo, user).pop();    if (!e) return null;    this.list(this.redo, user).push(e);    return { op: e.inverse, inverse: e.op };  }  popRedo(user: string): Entry | null {    const e = this.list(this.redo, user).pop();    if (!e) return null;    this.list(this.undo, user).push(e);    return { op: e.op, inverse: e.inverse };  }}