forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

board-stroke-codec.ts172 lines, 5.3 KiBHistoryRawDownload
1import type { Point, Stroke } 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// Wire envelope for one segment of a logical stroke. Coordinates are
16// board-space (device/zoom independent); points travel as [x, y] tuples to
17// keep the payload small.
18export type StrokeSegment = {
19 v: 1;
20 sid: string;
21 seg: number;
22 last: boolean;
23 color: string;
24 width: number;
25 erase: boolean;
26 pts: [number, number][];
27};
28
29const encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
30
31function byteLength(text: string): number {
32 return encoder ? encoder.encode(text).length : text.length;
33}
34
35// Board-space may be fractional; two decimals is plenty of fidelity and keeps
36// the payload compact.
37function round2(n: number): number {
38 return Math.round(n * 100) / 100;
39}
40
41function segmentString(
42 sid: string,
43 seg: number,
44 last: boolean,
45 stroke: Pick<Stroke, "color" | "width" | "erase">,
46 pts: [number, number][],
47): string {
48 const envelope: StrokeSegment = {
49 v: 1,
50 sid,
51 seg,
52 last,
53 color: stroke.color,
54 width: stroke.width,
55 erase: stroke.erase,
56 pts,
57 };
58 return JSON.stringify(envelope);
59}
60
61/**
62 * Serialize one logical stroke into one or more segment payloads, each under
63 * `maxBytes`. Consecutive segments repeat the previous segment's last point as
64 * their first, so painting them in order leaves no gap. A single point whose
65 * envelope already exceeds the cap is still emitted (a point can't be split).
66 */
67export function encodeStrokeSegments(
68 stroke: Stroke,
69 sid: string,
70 maxBytes: number = DEFAULT_MAX_BYTES,
71): string[] {
72 const tuples: [number, number][] = stroke.points.map((p) => [round2(p.x), round2(p.y)]);
73 if (tuples.length === 0) return [];
74
75 const segments: [number, number][][] = [];
76 let current: [number, number][] = [];
77
78 for (const pt of tuples) {
79 const candidate = [...current, pt];
80 // Not the last segment yet (last flag unknown here), so measure with
81 // last:false — the final re-encode below stamps the real flags.
82 const fits = byteLength(segmentString(sid, segments.length, false, stroke, candidate)) <= maxBytes;
83 if (fits || current.length === 0) {
84 current = candidate;
85 } else {
86 segments.push(current);
87 // Overlap one point for continuity across the segment boundary.
88 current = [current[current.length - 1], pt];
89 }
90 }
91 if (current.length > 0) segments.push(current);
92
93 return segments.map((pts, i) =>
94 segmentString(sid, i, i === segments.length - 1, stroke, pts),
95 );
96}
97
98function isTuple(v: unknown): v is [number, number] {
99 return (
100 Array.isArray(v) &&
101 v.length === 2 &&
102 typeof v[0] === "number" &&
103 typeof v[1] === "number" &&
104 Number.isFinite(v[0]) &&
105 Number.isFinite(v[1])
106 );
107}
108
109/** Parse one segment payload, or null on anything malformed (payloads are untrusted). */
110export function decodeSegment(payload: string | null): StrokeSegment | null {
111 if (!payload) return null;
112 let data: unknown;
113 try {
114 data = JSON.parse(payload);
115 } catch {
116 return null;
117 }
118 if (!data || typeof data !== "object") return null;
119 const s = data as StrokeSegment;
120 if (
121 s.v !== 1 ||
122 typeof s.sid !== "string" ||
123 typeof s.seg !== "number" ||
124 typeof s.last !== "boolean" ||
125 typeof s.color !== "string" ||
126 typeof s.width !== "number" ||
127 typeof s.erase !== "boolean" ||
128 !Array.isArray(s.pts) ||
129 !s.pts.every(isTuple)
130 ) {
131 return null;
132 }
133 return s;
134}
135
136/** One decoded segment as a paintable Stroke (its own points only). */
137export function segmentToStroke(seg: StrokeSegment): Stroke {
138 return {
139 color: seg.color,
140 width: seg.width,
141 erase: seg.erase,
142 points: seg.pts.map(([x, y]) => ({ x, y }) as Point),
143 };
144}
145
146/**
147 * Reassemble full strokes from an ordered list of stroke payloads (e.g. a
148 * history/epoch page). Segments are grouped by `sid` in arrival order; the
149 * overlap point each later segment repeats is dropped so the joined stroke has
150 * no duplicate vertex. Non-stroke rows (null payloads, clear markers) are
151 * skipped by the caller passing only stroke payloads.
152 */
153export function reassembleStrokes(payloads: (string | null)[]): Stroke[] {
154 const order: string[] = [];
155 const bySid = new Map<string, Stroke>();
156
157 for (const payload of payloads) {
158 const seg = decodeSegment(payload);
159 if (!seg) continue;
160 const pts = seg.pts.map(([x, y]) => ({ x, y }) as Point);
161 const existing = bySid.get(seg.sid);
162 if (!existing) {
163 order.push(seg.sid);
164 bySid.set(seg.sid, { color: seg.color, width: seg.width, erase: seg.erase, points: pts });
165 } else {
166 // Drop the leading overlap point that duplicates the previous last point.
167 existing.points.push(...(seg.seg > 0 ? pts.slice(1) : pts));
168 }
169 }
170
171 return order.map((sid) => bySid.get(sid)!);
172}