Something went wrong. Try again.
r/place on the atmosphere, targeting cloudflare's free tier
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// Live canvas updates over a WebSocket, reconnecting with backoff.
import { type CanvasConfig, decodeMessage, type Pixel } from "../shared/protocol.ts";import { canvasPath } from "../shared/routes.ts";
export interface FeedHandlers { onConfig(config: CanvasConfig): void; onSnapshot(pixels: Uint8Array): void; onDiff(pixels: Pixel[]): void; onConnection(connected: boolean): void;}
const MAX_BACKOFF_MS = 30_000;
// Returns a function that closes the feed for good.export function connectFeed(canvasUri: string, handlers: FeedHandlers): () => void { const scheme = location.protocol === "https:" ? "wss" : "ws"; const url = `${scheme}://${location.host}${canvasPath(canvasUri, "ws")}`; let backoff = 1000; let stopped = false; let ws: WebSocket;
const open = () => { ws = new WebSocket(url); ws.binaryType = "arraybuffer"; // Decoding is async; chain it so messages are handled in arrival order. let queue = Promise.resolve(); // Diffs can race ahead of the snapshot; hold them until it lands. let early: Pixel[] | null = [];
ws.onopen = () => { backoff = 1000; handlers.onConnection(true); }; ws.onmessage = (event) => { queue = queue.then(async () => { const msg = await decodeMessage(event.data); if (msg.type === "config") handlers.onConfig(msg.config); else if (msg.type === "snapshot") { handlers.onSnapshot(msg.pixels); if (early?.length) handlers.onDiff(early); early = null; } else if (early) early.push(...msg.pixels); else handlers.onDiff(msg.pixels); }); }; ws.onclose = () => { handlers.onConnection(false); if (stopped) return; setTimeout(open, backoff); backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); }; };
open(); return () => { stopped = true; ws.close(); };}