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
JavaScript22 lines1.1 KB
import { backoff, parseServer, msg } from "./protocol.js";export function connect(id, h) {  let ws, attempt = 0, timer, closed = false;  const name = localStorage.getItem("wb-name") || (() => { const n = "Guest " + (100 + Math.floor(Math.random() * 900)); localStorage.setItem("wb-name", n); return n; })();  function open() {    h.state(attempt ? "reconnecting" : "connecting");    ws = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws/" + id);    ws.onopen = () => { attempt = 0; ws.send(JSON.stringify(msg.hello(name))); };    ws.onmessage = (e) => { const m = parseServer(e.data); if (m) { if (m.type === "welcome") h.state("live"); h.message(m); } };    ws.onclose = (e) => {      if (closed) return;      if (e.code === 1008) { h.state("closed"); return; }      h.state("reconnecting"); timer = setTimeout(open, backoff(attempt++));    };  }  open();  return {    send(m) { if (ws && ws.readyState === 1) { ws.send(JSON.stringify(m)); return true; } return false; },    close() { closed = true; clearTimeout(timer); ws && ws.close(); },  };}