forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

board-stroke-codec.ts219 lines, 7.2 KiBHistoryRawDownload
1import { isDash, type Point, type Stroke, type StrokeDash } from "./draw-stroke";
2
3// The whiteboard backend caps each stroke `payload` at 4096 bytes
4// (board.max_stroke_payload_len, published at GET /limits). A long freehand
5// stroke is split into several segment frames that share one `sid`; the
6// receiver paints each segment as it arrives (consecutive segments overlap by
7// one point so the line stays continuous) and can reassemble the full stroke
8// for history replay.
9export const MAX_STROKE_PAYLOAD_BYTES = 4096;
10
11// A little headroom under the hard cap so we never sit exactly on the byte
12// boundary the server rejects.
13const DEFAULT_MAX_BYTES = MAX_STROKE_PAYLOAD_BYTES - 64;
14
15/** A stroke on the live board, tagged with the `sid` it travelled under. */
16export type BoardStroke = Stroke & { id?: string };
17
18// Wire envelope for one segment of a logical stroke. Coordinates are
19// board-space (device/zoom independent); points travel as [x, y] tuples to
20// keep the payload small.
21export type StrokeSegment = {
22 v: 1;
23 sid: string;
24 seg: number;
25 last: boolean;
26 color: string;
27 width: number;
28 erase: boolean;
29 /** Absent for a solid line, so a solid stroke's payload is unchanged. */
30 dash?: StrokeDash;
31 /**
32 * Erase marker: the sids of earlier strokes this entry removes (Excalidraw's
33 * object eraser). The stroke log is append-only, so a deletion is itself a
34 * logged entry; a marker carries no ink (`pts` is empty).
35 */
36 del?: string[];
37 pts: [number, number][];
38};
39
40const encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
41
42function byteLength(text: string): number {
43 return encoder ? encoder.encode(text).length : text.length;
44}
45
46// Board-space may be fractional; two decimals is plenty of fidelity and keeps
47// the payload compact.
48function round2(n: number): number {
49 return Math.round(n * 100) / 100;
50}
51
52function segmentString(
53 sid: string,
54 seg: number,
55 last: boolean,
56 stroke: Pick<Stroke, "color" | "width" | "erase" | "dash">,
57 pts: [number, number][],
58): string {
59 const envelope: StrokeSegment = {
60 v: 1,
61 sid,
62 seg,
63 last,
64 color: stroke.color,
65 width: stroke.width,
66 erase: stroke.erase,
67 ...(stroke.dash ? { dash: stroke.dash } : {}),
68 pts,
69 };
70 return JSON.stringify(envelope);
71}
72
73/**
74 * Serialize one logical stroke into one or more segment payloads, each under
75 * `maxBytes`. Consecutive segments repeat the previous segment's last point as
76 * their first, so painting them in order leaves no gap. A single point whose
77 * envelope already exceeds the cap is still emitted (a point can't be split).
78 */
79export function encodeStrokeSegments(
80 stroke: Stroke,
81 sid: string,
82 maxBytes: number = DEFAULT_MAX_BYTES,
83): string[] {
84 const tuples: [number, number][] = stroke.points.map((p) => [round2(p.x), round2(p.y)]);
85 if (tuples.length === 0) return [];
86
87 const segments: [number, number][][] = [];
88 let current: [number, number][] = [];
89
90 for (const pt of tuples) {
91 const candidate = [...current, pt];
92 // Not the last segment yet (last flag unknown here), so measure with
93 // last:false — the final re-encode below stamps the real flags.
94 const fits = byteLength(segmentString(sid, segments.length, false, stroke, candidate)) <= maxBytes;
95 if (fits || current.length === 0) {
96 current = candidate;
97 } else {
98 segments.push(current);
99 // Overlap one point for continuity across the segment boundary.
100 current = [current[current.length - 1], pt];
101 }
102 }
103 if (current.length > 0) segments.push(current);
104
105 return segments.map((pts, i) =>
106 segmentString(sid, i, i === segments.length - 1, stroke, pts),
107 );
108}
109
110function isTuple(v: unknown): v is [number, number] {
111 return (
112 Array.isArray(v) &&
113 v.length === 2 &&
114 typeof v[0] === "number" &&
115 typeof v[1] === "number" &&
116 Number.isFinite(v[0]) &&
117 Number.isFinite(v[1])
118 );
119}
120
121/**
122 * Serialize an erase of the strokes `ids` into marker payloads, each under
123 * `maxBytes` (a long sweep can remove more sids than fit in one payload).
124 */
125export function encodeEraseMarkers(ids: string[], sid: string, maxBytes: number = DEFAULT_MAX_BYTES): string[] {
126 const out: string[] = [];
127 const marker = (del: string[], n: number) =>
128 JSON.stringify({ v: 1, sid: `${sid}-${n}`, seg: 0, last: true, color: "", width: 0, erase: true, del, pts: [] } satisfies StrokeSegment);
129 let batch: string[] = [];
130 for (const id of ids) {
131 if (batch.length > 0 && byteLength(marker([...batch, id], out.length)) > maxBytes) {
132 out.push(marker(batch, out.length));
133 batch = [];
134 }
135 batch.push(id);
136 }
137 if (batch.length > 0) out.push(marker(batch, out.length));
138 return out;
139}
140
141/** Parse one segment payload, or null on anything malformed (payloads are untrusted). */
142export function decodeSegment(payload: string | null): StrokeSegment | null {
143 if (!payload) return null;
144 let data: unknown;
145 try {
146 data = JSON.parse(payload);
147 } catch {
148 return null;
149 }
150 if (!data || typeof data !== "object") return null;
151 const s = data as StrokeSegment;
152 if (
153 s.v !== 1 ||
154 typeof s.sid !== "string" ||
155 typeof s.seg !== "number" ||
156 typeof s.last !== "boolean" ||
157 typeof s.color !== "string" ||
158 typeof s.width !== "number" ||
159 typeof s.erase !== "boolean" ||
160 (s.dash !== undefined && !isDash(s.dash)) ||
161 (s.del !== undefined && !(Array.isArray(s.del) && s.del.every((id) => typeof id === "string"))) ||
162 !Array.isArray(s.pts) ||
163 !s.pts.every(isTuple)
164 ) {
165 return null;
166 }
167 return s;
168}
169
170/** One decoded segment as a paintable Stroke (its own points only). */
171export function segmentToStroke(seg: StrokeSegment): Stroke {
172 return {
173 color: seg.color,
174 width: seg.width,
175 erase: seg.erase,
176 ...(seg.dash ? { dash: seg.dash } : {}),
177 points: seg.pts.map(([x, y]) => ({ x, y }) as Point),
178 };
179}
180
181/**
182 * Reassemble full strokes from an ordered list of stroke payloads (e.g. a
183 * history/epoch page). Segments are grouped by `sid` in arrival order; the
184 * overlap point each later segment repeats is dropped so the joined stroke has
185 * no duplicate vertex. Strokes removed by a later erase marker are dropped,
186 * so a replay ends on what the board actually showed. Non-stroke rows (null payloads, clear markers) are
187 * skipped by the caller passing only stroke payloads.
188 */
189export function reassembleStrokes(payloads: (string | null)[]): Stroke[] {
190 const order: string[] = [];
191 const bySid = new Map<string, Stroke>();
192 const deleted = new Set<string>();
193
194 for (const payload of payloads) {
195 const seg = decodeSegment(payload);
196 if (!seg) continue;
197 if (seg.del) {
198 for (const id of seg.del) deleted.add(id);
199 continue;
200 }
201 const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point);
202 const existing = bySid.get(seg.sid);
203 if (!existing) {
204 order.push(seg.sid);
205 bySid.set(seg.sid, {
206 color: seg.color,
207 width: seg.width,
208 erase: seg.erase,
209 ...(seg.dash ? { dash: seg.dash } : {}),
210 points: pts,
211 });
212 } else {
213 // Drop the leading overlap point that duplicates the previous last point.
214 existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts));
215 }
216 }
217
218 return order.filter((sid) => !deleted.has(sid)).map((sid) => bySid.get(sid)!);
219}