gitflarePublicPartly agent-ready50
cf-durable-whiteboard
Realtime collaborative whiteboard on Cloudflare Durable Objects: presence cursors, WebSocket hibernation, SQLite storage, undo, PNG export.
- LicenseApache-2.0
- LanguageTypeScript
- Last landed
6eb4fbdOct 20, 2026
Keep board zoom and pan stable across reloads
6eb4fbdimport { COLOURS, SIZES, msg, applyOp, shapeId, pushRecent, peopleLabel, initials, isBoardId } from "./protocol.js";import { makeView, loadView, saveView } from "./viewport.js";import { drawBoard } from "./render.js";import { connect } from "./net.js";import { createPointerHandler } from "./pointer.js";import { setupToolbar } from "./toolbar.js";const $ = (i) => document.getElementById(i);const id = location.pathname.split("/")[2] || "";if (!isBoardId(id)) location.replace("/");pushRecent(localStorage, id);$("bid").textContent = id; document.title = `Board ${id} · Durable Whiteboard`;const cv = $("board"), c = cv.getContext("2d");const st = { tool: "pen", colour: COLOURS[0], size: SIZES[1], view: loadView(localStorage, id, innerWidth, innerHeight), shapes: new Map(), peers: new Map(), cursors: new Map(), preview: null, sel: null, space: false, me: null, ready: false, fit: false };let net, raf = 0;const toast = (t) => { const e = $("toast"); e.textContent = t; e.classList.add("show"); setTimeout(() => e.classList.remove("show"), 2200); };const render = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(paint); };function size() { const r = cv.getBoundingClientRect(); cv.width = r.width * devicePixelRatio; cv.height = r.height * devicePixelRatio; render(); }function paint() { const r = cv.getBoundingClientRect(); const list = [...st.shapes.values()]; if (st.preview) list.push(st.preview); drawBoard(c, list, st.view, r.width, r.height, st.sel && st.shapes.get(st.sel.id)); saveView(localStorage, id, st.view); $("zlabel").textContent = Math.round(st.view.k * 100) + "%"; $("empty").hidden = !st.ready || list.length > 0; for (const [uid, cu] of st.cursors) { const p = st.peers.get(uid); if (!p) continue; let el = document.querySelector(`[data-uid="${CSS.escape(uid)}"]`); if (!el) { el = document.createElement("div"); el.className = "cur"; el.dataset.uid = uid; el.textContent = p.name; el.style.background = p.colour; $("cursors").append(el); } el.style.transform = `translate(${cu.x * st.view.k + st.view.x}px,${cu.y * st.view.k + st.view.y}px)`; }}function people() { const all = [...(st.me ? [st.me] : []), ...st.peers.values()]; $("count").textContent = st.ready ? peopleLabel(all.length) : ""; const ul = $("avatars"); ul.textContent = ""; for (const p of all) { const li = document.createElement("li"); li.style.background = p.colour || "#3df0ff"; li.textContent = initials(p.name); li.title = p.name + (p === st.me ? " (you)" : ""); ul.append(li); }}function setState(s) { const el = $("status"); el.dataset.state = s; el.lastElementChild.textContent = { connecting: "Connecting…", live: "Live", reconnecting: "Reconnecting…", closed: "Disconnected" }[s];}function onMessage(m) { if (m.type === "welcome") { st.me = m.you && typeof m.you === "object" ? m.you : { userId: m.you, name: "You", colour: "#3df0ff" }; st.shapes = new Map((m.shapes || []).map((s) => [s.id, s])); st.peers = new Map((m.peers || []).filter((p) => p.userId !== st.me.userId).map((p) => [p.userId, p])); st.ready = true; $("loading").hidden = true; document.querySelectorAll(".cur").forEach((e) => e.remove()); st.cursors.clear(); st.fit = true; } else if (m.type === "op") applyOp(st.shapes, m.op); else if (m.type === "peer-join") { const p = m.peer || m; if (p.userId !== st.me?.userId) st.peers.set(p.userId, p); } else if (m.type === "peer-leave") { st.peers.delete(m.userId); st.cursors.delete(m.userId); document.querySelector(`[data-uid="${CSS.escape(m.userId)}"]`)?.remove(); } else if (m.type === "cursor") st.cursors.set(m.userId, { x: m.x, y: m.y }); else if (m.type === "error") toast(m.message || "Server rejected an action"); if (m.type !== "cursor") people(); render();}const nextZ = () => { let z = 0; for (const s of st.shapes.values()) z = Math.max(z, s.z ?? 0); return z + 1; };const api = { st, render, toast, shapeId, send: (m) => net.send(m), commit(op) { applyOp(st.shapes, op); render(); }, add(s) { s.z = nextZ(); api.commit({ type: "add", shape: s }); net.send(msg.add(s)); }, update(s) { api.commit({ type: "update", shape: s }); net.send(msg.update(s)); }, del(sid) { api.commit({ type: "delete", id: sid }); net.send(msg.del(sid)); },};net = connect(id, { state: setState, message: onMessage });createPointerHandler(cv, api);setupToolbar(api, cv, id);new ResizeObserver(size).observe(cv);setState("connecting");