| 1 | // The /board mini-app: a shared whiteboard drawn together in the current chat. |
| 2 | // A stroke is a list of points a member drags out with the pen; on release it's |
| 3 | // emitted whole as one board.stroke event and folded into the shared drawing — |
| 4 | // every device converges on the same picture because the fold is just "append |
| 5 | // the stroke", same as todo/poll's list model. The server only ever sees |
| 6 | // ciphertext: never a line, a color, or who drew what. |
| 7 | // |
| 8 | // Relative import (not "/static/apps.js") so the reducer is exercisable in Node |
| 9 | // tests while still resolving to /static/apps.js in the browser. |
| 10 | import { defineApp, namespace, addItem } from "../apps.js"; |
| 11 | import { ICON_PRESENTATION } from "../icons.js"; |
| 12 | |
| 13 | // One declaration of the app's prefix, reused everywhere: N.ev("stroke") → the |
| 14 | // "board.stroke" wire type (used as the `events` keys and in every emit/compare), |
| 15 | // N.cls("canvas") → the "board-canvas" CSS class. Change "board" here and every |
| 16 | // string below follows — the prefix can't drift. (Inside render/commands the same |
| 17 | // helper is on ctx as ctx.ev / ctx.cls.) |
| 18 | const N = namespace("board"); |
| 19 | |
| 20 | // Points are stored in a fixed logical canvas size, not normalized — every |
| 21 | // device draws the same picture at the same coordinates regardless of its own |
| 22 | // panel width (the DOM canvas is scaled to fit via CSS, pointer positions are |
| 23 | // converted back into this space on the way in). |
| 24 | const CANVAS_W = 640; |
| 25 | const CANVAS_H = 320; |
| 26 | const COLORS = ["#2a211b", "#c2410c", "#2c6fb0", "#2f8f5b", "#c9932e"]; |
| 27 | const WIDTHS = [3, 6, 12]; |
| 28 | const MAX_POINTS_PER_STROKE = 2000; |
| 29 | |
| 30 | // sanitizePoints turns whatever a hostile or stale client sent into a clean |
| 31 | // [[x,y], …] array clamped to the canvas, or null if it's not a usable stroke. |
| 32 | // Exported so the fold's validation is directly testable. |
| 33 | export function sanitizePoints(points) { |
| 34 | if (!Array.isArray(points)) return null; |
| 35 | const out = []; |
| 36 | for (const p of points) { |
| 37 | if (!Array.isArray(p) || p.length !== 2) continue; |
| 38 | const [x, y] = p; |
| 39 | if (typeof x !== "number" || typeof y !== "number" || !Number.isFinite(x) || !Number.isFinite(y)) continue; |
| 40 | out.push([Math.min(CANVAS_W, Math.max(0, x)), Math.min(CANVAS_H, Math.max(0, y))]); |
| 41 | if (out.length >= MAX_POINTS_PER_STROKE) break; |
| 42 | } |
| 43 | return out.length >= 2 ? out : null; |
| 44 | } |
| 45 | |
| 46 | // State is { open, strokes: [{ id, points, color, width }] }. `open` gates the |
| 47 | // panel: a shared app renders nothing when empty (see poll.js), but an empty |
| 48 | // canvas IS the useful starting state here, so /board explicitly opts a thread |
| 49 | // in with board.open. `open` is the ONLY thing that gates visibility — Close |
| 50 | // (board.close) flips it back off without touching the drawing, so reopening |
| 51 | // with /board picks up right where the group left off; Clear (board.clear) |
| 52 | // is the destructive one, wiping strokes but leaving the panel open. |
| 53 | export const app = defineApp({ |
| 54 | name: "board", |
| 55 | title: "Whiteboard", |
| 56 | blurb: "Sketch on a whiteboard", // sidebar subtitle before first use (sync w/ native) |
| 57 | glyph: "🎨", |
| 58 | symbol: "rectangle.on.rectangle", // native chrome: the SF Symbols name iOS/Mac render (docs/icons.md) |
| 59 | logo: ICON_PRESENTATION, |
| 60 | // Drawing together is the point — the whiteboard lives in a chat (places |
| 61 | // model; the ambient panel retired with #405). /board in a group adopts it. |
| 62 | places: ["chat"], |
| 63 | placeNote: "A whiteboard is for sketching together — it lives in a group chat.", |
| 64 | // Unlike poll (which just renders nothing when it has zero polls), an empty |
| 65 | // board is still the useful starting state, so it's gated behind an explicit |
| 66 | // `open` flag instead. `openEvent` tells the Add-apps flow (groupactions.js) |
| 67 | // to fire this the moment the app is added, so the canvas shows up right |
| 68 | // away rather than sitting invisible until someone remembers to run /board. |
| 69 | openEvent: "board.open", |
| 70 | // Optimistic local echo (docs: apps/README.md § Optimistic sends): a finished |
| 71 | // stroke folds into state the instant you lift the pen, so the line stays put |
| 72 | // instead of vanishing on pen-up and flashing back when the server echoes it. |
| 73 | // Safe because every board reducer is idempotent by the event's own id (strokes |
| 74 | // via addItem; open/close/clear are self-checked), so the authoritative echo |
| 75 | // re-folds onto the same entity rather than duplicating it. |
| 76 | optimistic: true, |
| 77 | initialState: () => ({ open: false, strokes: [] }), |
| 78 | events: { |
| 79 | [N.ev("open")]: (s) => (s.open ? s : { ...s, open: true }), |
| 80 | [N.ev("close")]: (s) => (s.open ? { ...s, open: false } : s), |
| 81 | [N.ev("stroke")]: (s, e) => { |
| 82 | const points = sanitizePoints(e.points); |
| 83 | if (!e.id || !points) return s; |
| 84 | const color = COLORS.includes(e.color) ? e.color : COLORS[0]; |
| 85 | const width = WIDTHS.includes(e.width) ? e.width : WIDTHS[1]; |
| 86 | return { ...s, strokes: addItem(s.strokes, { id: e.id, points, color, width }) }; |
| 87 | }, |
| 88 | [N.ev("clear")]: (s) => (s.strokes.length ? { ...s, strokes: [] } : s), |
| 89 | }, |
| 90 | commands: { |
| 91 | // /board opens the whiteboard panel; /board clear wipes it; /board close hides it. |
| 92 | "/board": (args, ctx) => { |
| 93 | const a = args.trim().toLowerCase(); |
| 94 | if (a === "clear") ctx.emit({ type: N.ev("clear") }); |
| 95 | else if (a === "close") ctx.emit({ type: N.ev("close") }); |
| 96 | else ctx.emit({ type: N.ev("open") }); |
| 97 | }, |
| 98 | }, |
| 99 | |
| 100 | // Sidebar presence: opening is worth surfacing, like poll's create; strokes |
| 101 | // (and closing) stay quiet — the panel updates live anyway. |
| 102 | preview: (e) => (e.type === N.ev("open") ? "🎨 opened the whiteboard" : null), |
| 103 | unread: (e) => e.type === N.ev("open"), |
| 104 | |
| 105 | // This app's CSS travels with it — the framework injects it once. It reads the |
| 106 | // theme's CSS variables (var(--accent) etc.) so it follows the chosen theme. |
| 107 | styles: ` |
| 108 | .board-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } |
| 109 | .board-title { font-size: 13px; font-weight: 600; color: var(--ink); } |
| 110 | .board-min, .board-close-btn { |
| 111 | border: 1px solid var(--border); background: transparent; color: var(--ink); |
| 112 | border-radius: 8px; font: inherit; font-size: 12px; padding: 3px 8px; cursor: var(--ui-cursor, pointer); |
| 113 | } |
| 114 | .board-min { padding: 3px 10px; } |
| 115 | .board-wrap.minimized .board-body { display: none; } |
| 116 | .board-body { display: flex; flex-direction: column; } |
| 117 | .board-toolbar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; } |
| 118 | .board-swatch { |
| 119 | width: 22px; height: 22px; border-radius: 50%; border: 2px solid transparent; |
| 120 | padding: 0; cursor: var(--ui-cursor, pointer); |
| 121 | } |
| 122 | .board-swatch.selected { border-color: var(--ink); } |
| 123 | .board-size { |
| 124 | display: flex; align-items: center; justify-content: center; width: 26px; height: 26px; |
| 125 | border-radius: 8px; border: 1px solid var(--border); background: transparent; padding: 0; |
| 126 | cursor: var(--ui-cursor, pointer); |
| 127 | } |
| 128 | .board-size.selected { border-color: var(--accent); background: var(--bubble-them); } |
| 129 | .board-size-dot { border-radius: 50%; background: var(--ink); display: block; } |
| 130 | .board-spacer { flex: 1 1 auto; } |
| 131 | .board-clear { |
| 132 | border: none; background: transparent; padding: 0; font: inherit; font-size: 12px; |
| 133 | color: var(--link); cursor: var(--ui-cursor, pointer); text-decoration: underline; |
| 134 | text-underline-offset: 2px; |
| 135 | } |
| 136 | .board-stage { |
| 137 | position: relative; width: 100%; aspect-ratio: ${CANVAS_W} / ${CANVAS_H}; |
| 138 | border-radius: 10px; overflow: hidden; border: 1px solid var(--border); background: var(--panel); |
| 139 | } |
| 140 | .board-base, .board-live { |
| 141 | position: absolute; inset: 0; width: 100%; height: 100%; touch-action: none; |
| 142 | } |
| 143 | .board-live { cursor: crosshair; } |
| 144 | `, |
| 145 | |
| 146 | // Panel surface: renders nothing until someone runs /board (or after /board |
| 147 | // close), so the panel collapses like poll's. Incremental: the canvas + toolbar |
| 148 | // are built ONCE per thread and kept — rebuilding them on every fold would tear |
| 149 | // the DOM out from under anyone mid-stroke the moment another member's line |
| 150 | // lands, and would wipe the in-progress local stroke on the overlay canvas. |
| 151 | // |
| 152 | // #app-surface (the mount every shared app renders into) is ONE persistent |
| 153 | // element reused across every thread the host switches to — it's not torn |
| 154 | // down and rebuilt per-thread. So a `.board-wrap` built while thread A was |
| 155 | // active can still be sitting there when the host later renders thread B. |
| 156 | // Two things guard against that: the wrap is removed outright whenever the |
| 157 | // CURRENT thread's `open` is false (so a thread that never ran /board can't |
| 158 | // show another thread's drawing), and `ctx` — which is fresh every render — |
| 159 | // is stashed on the wrap and re-read by the pointer handlers at draw time, so |
| 160 | // a stroke always emits into whichever thread is actually active right now, |
| 161 | // never whichever thread happened to be active when the wrap was first built. |
| 162 | incremental: true, |
| 163 | render(state, el, ctx) { |
| 164 | const s = state || {}; |
| 165 | let wrap = el.querySelector("." + N.cls("wrap")); |
| 166 | if (!s.open) { |
| 167 | if (wrap) wrap.remove(); |
| 168 | return; |
| 169 | } |
| 170 | if (!wrap) { |
| 171 | wrap = buildBoard(); |
| 172 | el.appendChild(wrap); |
| 173 | } |
| 174 | if (wrap.dataset.tid !== ctx.threadId) { |
| 175 | wrap.dataset.tid = ctx.threadId; // a different thread's board starts expanded |
| 176 | wrap.classList.remove("minimized"); |
| 177 | } |
| 178 | wrap._ctx = ctx; |
| 179 | paintStrokes(wrap.querySelector("." + N.cls("base")), s.strokes || []); |
| 180 | }, |
| 181 | }); |
| 182 | |
| 183 | // paintStrokes redraws the committed picture from state — always a full clear |
| 184 | // + redraw (simplest correct thing; a session's stroke count is small enough |
| 185 | // that this is cheap). The in-progress local stroke lives on a separate |
| 186 | // overlay canvas this never touches, so another member's stroke landing |
| 187 | // mid-drag can't erase what you're currently drawing. |
| 188 | function paintStrokes(canvas, strokes) { |
| 189 | const g = canvas.getContext("2d"); |
| 190 | g.clearRect(0, 0, canvas.width, canvas.height); |
| 191 | for (const stroke of strokes) drawStroke(g, stroke); |
| 192 | } |
| 193 | |
| 194 | function drawStroke(g, stroke) { |
| 195 | const pts = stroke.points; |
| 196 | if (!pts || pts.length < 2) return; |
| 197 | g.strokeStyle = stroke.color; |
| 198 | g.lineWidth = stroke.width; |
| 199 | g.lineCap = "round"; |
| 200 | g.lineJoin = "round"; |
| 201 | g.beginPath(); |
| 202 | g.moveTo(pts[0][0], pts[0][1]); |
| 203 | for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]); |
| 204 | g.stroke(); |
| 205 | } |
| 206 | |
| 207 | // buildBoard constructs the header + toolbar + two-canvas stage once per |
| 208 | // thread. Color/brush-size choice and the minimized flag are local UI state — |
| 209 | // never shared or persisted, exactly like which emoji is "armed" on a picker. |
| 210 | // Handlers read `wrap._ctx` (refreshed every render, see above) rather than |
| 211 | // closing over a ctx captured at build time, so they always target whichever |
| 212 | // thread is actually active when the user actually draws/clears/closes. |
| 213 | function buildBoard() { |
| 214 | const wrap = document.createElement("div"); |
| 215 | wrap.className = N.cls("wrap"); |
| 216 | |
| 217 | const header = document.createElement("div"); |
| 218 | header.className = N.cls("header"); |
| 219 | const title = document.createElement("span"); |
| 220 | title.className = N.cls("title"); |
| 221 | title.textContent = "🎨 Whiteboard"; |
| 222 | header.appendChild(title); |
| 223 | header.appendChild(Object.assign(document.createElement("div"), { className: N.cls("spacer") })); |
| 224 | |
| 225 | const minBtn = document.createElement("button"); |
| 226 | minBtn.type = "button"; |
| 227 | minBtn.className = N.cls("min"); |
| 228 | const setMinLabel = () => { |
| 229 | const min = wrap.classList.contains("minimized"); |
| 230 | minBtn.textContent = min ? "Expand" : "Minimize"; |
| 231 | minBtn.setAttribute("aria-label", min ? "Expand whiteboard" : "Minimize whiteboard"); |
| 232 | }; |
| 233 | minBtn.onclick = () => { |
| 234 | wrap.classList.toggle("minimized"); |
| 235 | setMinLabel(); |
| 236 | }; |
| 237 | setMinLabel(); |
| 238 | header.appendChild(minBtn); |
| 239 | |
| 240 | const closeBtn = document.createElement("button"); |
| 241 | closeBtn.type = "button"; |
| 242 | closeBtn.className = N.cls("close-btn"); |
| 243 | closeBtn.textContent = "Close"; |
| 244 | closeBtn.setAttribute("aria-label", "Close whiteboard"); |
| 245 | // Non-destructive: hides the panel (board.close), but the drawing is still |
| 246 | // there — /board reopens it exactly as it was. Nothing to confirm. |
| 247 | closeBtn.onclick = () => wrap._ctx.emit({ type: N.ev("close") }); |
| 248 | header.appendChild(closeBtn); |
| 249 | |
| 250 | wrap.appendChild(header); |
| 251 | |
| 252 | const body = document.createElement("div"); |
| 253 | body.className = N.cls("body"); |
| 254 | wrap.appendChild(body); |
| 255 | |
| 256 | const toolbar = document.createElement("div"); |
| 257 | toolbar.className = N.cls("toolbar"); |
| 258 | |
| 259 | let color = COLORS[0]; |
| 260 | let width = WIDTHS[1]; |
| 261 | |
| 262 | const swatches = COLORS.map((c, i) => { |
| 263 | const b = document.createElement("button"); |
| 264 | b.type = "button"; |
| 265 | b.className = N.cls("swatch") + (i === 0 ? " selected" : ""); |
| 266 | b.style.background = c; |
| 267 | b.setAttribute("aria-label", "Color " + c); |
| 268 | b.onclick = () => { |
| 269 | color = c; |
| 270 | for (const sw of swatches) sw.classList.toggle("selected", sw === b); |
| 271 | }; |
| 272 | toolbar.appendChild(b); |
| 273 | return b; |
| 274 | }); |
| 275 | |
| 276 | const sizeLabels = ["Thin", "Medium", "Thick"]; |
| 277 | const sizes = WIDTHS.map((w, i) => { |
| 278 | const b = document.createElement("button"); |
| 279 | b.type = "button"; |
| 280 | b.className = N.cls("size") + (i === 1 ? " selected" : ""); |
| 281 | const dot = document.createElement("span"); |
| 282 | dot.className = N.cls("size-dot"); |
| 283 | dot.style.width = dot.style.height = 4 + i * 4 + "px"; |
| 284 | b.appendChild(dot); |
| 285 | b.setAttribute("aria-label", sizeLabels[i] + " brush"); |
| 286 | b.onclick = () => { |
| 287 | width = w; |
| 288 | for (const sz of sizes) sz.classList.toggle("selected", sz === b); |
| 289 | }; |
| 290 | toolbar.appendChild(b); |
| 291 | return b; |
| 292 | }); |
| 293 | |
| 294 | toolbar.appendChild(Object.assign(document.createElement("div"), { className: N.cls("spacer") })); |
| 295 | |
| 296 | const clear = document.createElement("button"); |
| 297 | clear.type = "button"; |
| 298 | clear.className = N.cls("clear"); |
| 299 | clear.textContent = "Clear"; |
| 300 | // Two-step inline confirm (see poll.js's Close poll) rather than confirm(): |
| 301 | // embedded webviews have no confirm panel, so the dialog would silently |
| 302 | // answer false and the click would look dead. |
| 303 | clear.onclick = () => { |
| 304 | if (!clear.dataset.armed) { |
| 305 | clear.dataset.armed = "1"; |
| 306 | clear.textContent = "Clear for everyone?"; |
| 307 | setTimeout(() => { |
| 308 | delete clear.dataset.armed; |
| 309 | if (clear.isConnected) clear.textContent = "Clear"; |
| 310 | }, 4000); |
| 311 | return; |
| 312 | } |
| 313 | delete clear.dataset.armed; |
| 314 | clear.textContent = "Clear"; |
| 315 | wrap._ctx.emit({ type: N.ev("clear") }); |
| 316 | }; |
| 317 | toolbar.appendChild(clear); |
| 318 | body.appendChild(toolbar); |
| 319 | |
| 320 | const stage = document.createElement("div"); |
| 321 | stage.className = N.cls("stage"); |
| 322 | const base = document.createElement("canvas"); |
| 323 | base.className = N.cls("base"); |
| 324 | base.width = CANVAS_W; |
| 325 | base.height = CANVAS_H; |
| 326 | const live = document.createElement("canvas"); |
| 327 | live.className = N.cls("live"); |
| 328 | live.width = CANVAS_W; |
| 329 | live.height = CANVAS_H; |
| 330 | stage.append(base, live); |
| 331 | body.appendChild(stage); |
| 332 | |
| 333 | const toCanvasPoint = (ev) => { |
| 334 | const rect = live.getBoundingClientRect(); |
| 335 | const x = ((ev.clientX - rect.left) / rect.width) * CANVAS_W; |
| 336 | const y = ((ev.clientY - rect.top) / rect.height) * CANVAS_H; |
| 337 | return [Math.min(CANVAS_W, Math.max(0, x)), Math.min(CANVAS_H, Math.max(0, y))]; |
| 338 | }; |
| 339 | |
| 340 | let drawing = null; // { points, g } while a pointer is down |
| 341 | live.addEventListener("pointerdown", (ev) => { |
| 342 | live.setPointerCapture(ev.pointerId); |
| 343 | const g = live.getContext("2d"); |
| 344 | g.strokeStyle = color; |
| 345 | g.lineWidth = width; |
| 346 | g.lineCap = "round"; |
| 347 | g.lineJoin = "round"; |
| 348 | const p = toCanvasPoint(ev); |
| 349 | g.beginPath(); |
| 350 | g.moveTo(p[0], p[1]); |
| 351 | drawing = { points: [p], g }; |
| 352 | }); |
| 353 | live.addEventListener("pointermove", (ev) => { |
| 354 | if (!drawing) return; |
| 355 | const p = toCanvasPoint(ev); |
| 356 | drawing.points.push(p); |
| 357 | drawing.g.lineTo(p[0], p[1]); |
| 358 | drawing.g.stroke(); |
| 359 | }); |
| 360 | const finishStroke = () => { |
| 361 | if (!drawing) return; |
| 362 | const points = drawing.points; |
| 363 | drawing = null; |
| 364 | live.getContext("2d").clearRect(0, 0, CANVAS_W, CANVAS_H); |
| 365 | if (points.length >= 2) wrap._ctx.emit({ type: N.ev("stroke"), id: wrap._ctx.id(), points, color, width }); |
| 366 | }; |
| 367 | live.addEventListener("pointerup", finishStroke); |
| 368 | live.addEventListener("pointercancel", finishStroke); |
| 369 | live.addEventListener("pointerleave", (ev) => { |
| 370 | if (drawing && ev.buttons === 0) finishStroke(); |
| 371 | }); |
| 372 | |
| 373 | return wrap; |
| 374 | } |
| 375 | |