// The /board mini-app: a shared whiteboard drawn together in the current chat. // A stroke is a list of points a member drags out with the pen; on release it's // emitted whole as one board.stroke event and folded into the shared drawing — // every device converges on the same picture because the fold is just "append // the stroke", same as todo/poll's list model. The server only ever sees // ciphertext: never a line, a color, or who drew what. // // Relative import (not "/static/apps.js") so the reducer is exercisable in Node // tests while still resolving to /static/apps.js in the browser. import { defineApp, namespace, addItem } from "../apps.js"; import { ICON_PRESENTATION } from "../icons.js"; // One declaration of the app's prefix, reused everywhere: N.ev("stroke") → the // "board.stroke" wire type (used as the `events` keys and in every emit/compare), // N.cls("canvas") → the "board-canvas" CSS class. Change "board" here and every // string below follows — the prefix can't drift. (Inside render/commands the same // helper is on ctx as ctx.ev / ctx.cls.) const N = namespace("board"); // Points are stored in a fixed logical canvas size, not normalized — every // device draws the same picture at the same coordinates regardless of its own // panel width (the DOM canvas is scaled to fit via CSS, pointer positions are // converted back into this space on the way in). const CANVAS_W = 640; const CANVAS_H = 320; const COLORS = ["#2a211b", "#c2410c", "#2c6fb0", "#2f8f5b", "#c9932e"]; const WIDTHS = [3, 6, 12]; const MAX_POINTS_PER_STROKE = 2000; // sanitizePoints turns whatever a hostile or stale client sent into a clean // [[x,y], …] array clamped to the canvas, or null if it's not a usable stroke. // Exported so the fold's validation is directly testable. export function sanitizePoints(points) { if (!Array.isArray(points)) return null; const out = []; for (const p of points) { if (!Array.isArray(p) || p.length !== 2) continue; const [x, y] = p; if (typeof x !== "number" || typeof y !== "number" || !Number.isFinite(x) || !Number.isFinite(y)) continue; out.push([Math.min(CANVAS_W, Math.max(0, x)), Math.min(CANVAS_H, Math.max(0, y))]); if (out.length >= MAX_POINTS_PER_STROKE) break; } return out.length >= 2 ? out : null; } // State is { open, strokes: [{ id, points, color, width }] }. `open` gates the // panel: a shared app renders nothing when empty (see poll.js), but an empty // canvas IS the useful starting state here, so /board explicitly opts a thread // in with board.open. `open` is the ONLY thing that gates visibility — Close // (board.close) flips it back off without touching the drawing, so reopening // with /board picks up right where the group left off; Clear (board.clear) // is the destructive one, wiping strokes but leaving the panel open. export const app = defineApp({ name: "board", title: "Whiteboard", blurb: "Sketch on a whiteboard", // sidebar subtitle before first use (sync w/ native) glyph: "🎨", symbol: "rectangle.on.rectangle", // native chrome: the SF Symbols name iOS/Mac render (docs/icons.md) logo: ICON_PRESENTATION, // Drawing together is the point — the whiteboard lives in a chat (places // model; the ambient panel retired with #405). /board in a group adopts it. places: ["chat"], placeNote: "A whiteboard is for sketching together — it lives in a group chat.", // Unlike poll (which just renders nothing when it has zero polls), an empty // board is still the useful starting state, so it's gated behind an explicit // `open` flag instead. `openEvent` tells the Add-apps flow (groupactions.js) // to fire this the moment the app is added, so the canvas shows up right // away rather than sitting invisible until someone remembers to run /board. openEvent: "board.open", // Optimistic local echo (docs: apps/README.md § Optimistic sends): a finished // stroke folds into state the instant you lift the pen, so the line stays put // instead of vanishing on pen-up and flashing back when the server echoes it. // Safe because every board reducer is idempotent by the event's own id (strokes // via addItem; open/close/clear are self-checked), so the authoritative echo // re-folds onto the same entity rather than duplicating it. optimistic: true, initialState: () => ({ open: false, strokes: [] }), events: { [N.ev("open")]: (s) => (s.open ? s : { ...s, open: true }), [N.ev("close")]: (s) => (s.open ? { ...s, open: false } : s), [N.ev("stroke")]: (s, e) => { const points = sanitizePoints(e.points); if (!e.id || !points) return s; const color = COLORS.includes(e.color) ? e.color : COLORS[0]; const width = WIDTHS.includes(e.width) ? e.width : WIDTHS[1]; return { ...s, strokes: addItem(s.strokes, { id: e.id, points, color, width }) }; }, [N.ev("clear")]: (s) => (s.strokes.length ? { ...s, strokes: [] } : s), }, commands: { // /board opens the whiteboard panel; /board clear wipes it; /board close hides it. "/board": (args, ctx) => { const a = args.trim().toLowerCase(); if (a === "clear") ctx.emit({ type: N.ev("clear") }); else if (a === "close") ctx.emit({ type: N.ev("close") }); else ctx.emit({ type: N.ev("open") }); }, }, // Sidebar presence: opening is worth surfacing, like poll's create; strokes // (and closing) stay quiet — the panel updates live anyway. preview: (e) => (e.type === N.ev("open") ? "🎨 opened the whiteboard" : null), unread: (e) => e.type === N.ev("open"), // This app's CSS travels with it — the framework injects it once. It reads the // theme's CSS variables (var(--accent) etc.) so it follows the chosen theme. styles: ` .board-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } .board-title { font-size: 13px; font-weight: 600; color: var(--ink); } .board-min, .board-close-btn { border: 1px solid var(--border); background: transparent; color: var(--ink); border-radius: 8px; font: inherit; font-size: 12px; padding: 3px 8px; cursor: var(--ui-cursor, pointer); } .board-min { padding: 3px 10px; } .board-wrap.minimized .board-body { display: none; } .board-body { display: flex; flex-direction: column; } .board-toolbar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; } .board-swatch { width: 22px; height: 22px; border-radius: 50%; border: 2px solid transparent; padding: 0; cursor: var(--ui-cursor, pointer); } .board-swatch.selected { border-color: var(--ink); } .board-size { display: flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: 8px; border: 1px solid var(--border); background: transparent; padding: 0; cursor: var(--ui-cursor, pointer); } .board-size.selected { border-color: var(--accent); background: var(--bubble-them); } .board-size-dot { border-radius: 50%; background: var(--ink); display: block; } .board-spacer { flex: 1 1 auto; } .board-clear { border: none; background: transparent; padding: 0; font: inherit; font-size: 12px; color: var(--link); cursor: var(--ui-cursor, pointer); text-decoration: underline; text-underline-offset: 2px; } .board-stage { position: relative; width: 100%; aspect-ratio: ${CANVAS_W} / ${CANVAS_H}; border-radius: 10px; overflow: hidden; border: 1px solid var(--border); background: var(--panel); } .board-base, .board-live { position: absolute; inset: 0; width: 100%; height: 100%; touch-action: none; } .board-live { cursor: crosshair; } `, // Panel surface: renders nothing until someone runs /board (or after /board // close), so the panel collapses like poll's. Incremental: the canvas + toolbar // are built ONCE per thread and kept — rebuilding them on every fold would tear // the DOM out from under anyone mid-stroke the moment another member's line // lands, and would wipe the in-progress local stroke on the overlay canvas. // // #app-surface (the mount every shared app renders into) is ONE persistent // element reused across every thread the host switches to — it's not torn // down and rebuilt per-thread. So a `.board-wrap` built while thread A was // active can still be sitting there when the host later renders thread B. // Two things guard against that: the wrap is removed outright whenever the // CURRENT thread's `open` is false (so a thread that never ran /board can't // show another thread's drawing), and `ctx` — which is fresh every render — // is stashed on the wrap and re-read by the pointer handlers at draw time, so // a stroke always emits into whichever thread is actually active right now, // never whichever thread happened to be active when the wrap was first built. incremental: true, render(state, el, ctx) { const s = state || {}; let wrap = el.querySelector("." + N.cls("wrap")); if (!s.open) { if (wrap) wrap.remove(); return; } if (!wrap) { wrap = buildBoard(); el.appendChild(wrap); } if (wrap.dataset.tid !== ctx.threadId) { wrap.dataset.tid = ctx.threadId; // a different thread's board starts expanded wrap.classList.remove("minimized"); } wrap._ctx = ctx; paintStrokes(wrap.querySelector("." + N.cls("base")), s.strokes || []); }, }); // paintStrokes redraws the committed picture from state — always a full clear // + redraw (simplest correct thing; a session's stroke count is small enough // that this is cheap). The in-progress local stroke lives on a separate // overlay canvas this never touches, so another member's stroke landing // mid-drag can't erase what you're currently drawing. function paintStrokes(canvas, strokes) { const g = canvas.getContext("2d"); g.clearRect(0, 0, canvas.width, canvas.height); for (const stroke of strokes) drawStroke(g, stroke); } function drawStroke(g, stroke) { const pts = stroke.points; if (!pts || pts.length < 2) return; g.strokeStyle = stroke.color; g.lineWidth = stroke.width; g.lineCap = "round"; g.lineJoin = "round"; g.beginPath(); g.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]); g.stroke(); } // buildBoard constructs the header + toolbar + two-canvas stage once per // thread. Color/brush-size choice and the minimized flag are local UI state — // never shared or persisted, exactly like which emoji is "armed" on a picker. // Handlers read `wrap._ctx` (refreshed every render, see above) rather than // closing over a ctx captured at build time, so they always target whichever // thread is actually active when the user actually draws/clears/closes. function buildBoard() { const wrap = document.createElement("div"); wrap.className = N.cls("wrap"); const header = document.createElement("div"); header.className = N.cls("header"); const title = document.createElement("span"); title.className = N.cls("title"); title.textContent = "🎨 Whiteboard"; header.appendChild(title); header.appendChild(Object.assign(document.createElement("div"), { className: N.cls("spacer") })); const minBtn = document.createElement("button"); minBtn.type = "button"; minBtn.className = N.cls("min"); const setMinLabel = () => { const min = wrap.classList.contains("minimized"); minBtn.textContent = min ? "Expand" : "Minimize"; minBtn.setAttribute("aria-label", min ? "Expand whiteboard" : "Minimize whiteboard"); }; minBtn.onclick = () => { wrap.classList.toggle("minimized"); setMinLabel(); }; setMinLabel(); header.appendChild(minBtn); const closeBtn = document.createElement("button"); closeBtn.type = "button"; closeBtn.className = N.cls("close-btn"); closeBtn.textContent = "Close"; closeBtn.setAttribute("aria-label", "Close whiteboard"); // Non-destructive: hides the panel (board.close), but the drawing is still // there — /board reopens it exactly as it was. Nothing to confirm. closeBtn.onclick = () => wrap._ctx.emit({ type: N.ev("close") }); header.appendChild(closeBtn); wrap.appendChild(header); const body = document.createElement("div"); body.className = N.cls("body"); wrap.appendChild(body); const toolbar = document.createElement("div"); toolbar.className = N.cls("toolbar"); let color = COLORS[0]; let width = WIDTHS[1]; const swatches = COLORS.map((c, i) => { const b = document.createElement("button"); b.type = "button"; b.className = N.cls("swatch") + (i === 0 ? " selected" : ""); b.style.background = c; b.setAttribute("aria-label", "Color " + c); b.onclick = () => { color = c; for (const sw of swatches) sw.classList.toggle("selected", sw === b); }; toolbar.appendChild(b); return b; }); const sizeLabels = ["Thin", "Medium", "Thick"]; const sizes = WIDTHS.map((w, i) => { const b = document.createElement("button"); b.type = "button"; b.className = N.cls("size") + (i === 1 ? " selected" : ""); const dot = document.createElement("span"); dot.className = N.cls("size-dot"); dot.style.width = dot.style.height = 4 + i * 4 + "px"; b.appendChild(dot); b.setAttribute("aria-label", sizeLabels[i] + " brush"); b.onclick = () => { width = w; for (const sz of sizes) sz.classList.toggle("selected", sz === b); }; toolbar.appendChild(b); return b; }); toolbar.appendChild(Object.assign(document.createElement("div"), { className: N.cls("spacer") })); const clear = document.createElement("button"); clear.type = "button"; clear.className = N.cls("clear"); clear.textContent = "Clear"; // Two-step inline confirm (see poll.js's Close poll) rather than confirm(): // embedded webviews have no confirm panel, so the dialog would silently // answer false and the click would look dead. clear.onclick = () => { if (!clear.dataset.armed) { clear.dataset.armed = "1"; clear.textContent = "Clear for everyone?"; setTimeout(() => { delete clear.dataset.armed; if (clear.isConnected) clear.textContent = "Clear"; }, 4000); return; } delete clear.dataset.armed; clear.textContent = "Clear"; wrap._ctx.emit({ type: N.ev("clear") }); }; toolbar.appendChild(clear); body.appendChild(toolbar); const stage = document.createElement("div"); stage.className = N.cls("stage"); const base = document.createElement("canvas"); base.className = N.cls("base"); base.width = CANVAS_W; base.height = CANVAS_H; const live = document.createElement("canvas"); live.className = N.cls("live"); live.width = CANVAS_W; live.height = CANVAS_H; stage.append(base, live); body.appendChild(stage); const toCanvasPoint = (ev) => { const rect = live.getBoundingClientRect(); const x = ((ev.clientX - rect.left) / rect.width) * CANVAS_W; const y = ((ev.clientY - rect.top) / rect.height) * CANVAS_H; return [Math.min(CANVAS_W, Math.max(0, x)), Math.min(CANVAS_H, Math.max(0, y))]; }; let drawing = null; // { points, g } while a pointer is down live.addEventListener("pointerdown", (ev) => { live.setPointerCapture(ev.pointerId); const g = live.getContext("2d"); g.strokeStyle = color; g.lineWidth = width; g.lineCap = "round"; g.lineJoin = "round"; const p = toCanvasPoint(ev); g.beginPath(); g.moveTo(p[0], p[1]); drawing = { points: [p], g }; }); live.addEventListener("pointermove", (ev) => { if (!drawing) return; const p = toCanvasPoint(ev); drawing.points.push(p); drawing.g.lineTo(p[0], p[1]); drawing.g.stroke(); }); const finishStroke = () => { if (!drawing) return; const points = drawing.points; drawing = null; live.getContext("2d").clearRect(0, 0, CANVAS_W, CANVAS_H); if (points.length >= 2) wrap._ctx.emit({ type: N.ev("stroke"), id: wrap._ctx.id(), points, color, width }); }; live.addEventListener("pointerup", finishStroke); live.addEventListener("pointercancel", finishStroke); live.addEventListener("pointerleave", (ev) => { if (drawing && ev.buttons === 0) finishStroke(); }); return wrap; }