forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

draw-stroke.ts209 lines, 8.2 KiBHistoryRawDownload
1export type Point = { x: number; y: number };
2export type Stroke = { color: string; width: number; erase: boolean; points: Point[] };
3export type BgKind = "none" | "lines" | "grid";
4/** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */
5export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind; dpr?: number };
6
7/** World px per notebook cell — shared by the live CSS paper and the baked export so both read as the same ruling. */
8export const PAPER_CELL = 24;
9/** Faint blue-gray ruling colour for both the live CSS paper and the baked export. */
10export const PAPER_LINE = "rgba(37, 99, 235, 0.14)";
11
12function isPoint(p: unknown): p is Point {
13 return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number";
14}
15
16/**
17 * Export-box side in world px: finite, positive, and no wider than the largest canvas a
18 * browser will make. A real export was itself rendered through a `w × dpr` canvas (dpr ≥ 1
19 * on any normal display), so nothing legitimate can exceed this — while an unbounded side
20 * both sizes the playback allocation and drives paintPaper's per-cell loop.
21 */
22const MAX_SIDE = 16384;
23
24function isSide(n: unknown): n is number {
25 return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons
26}
27
28function isStroke(s: unknown): s is Stroke {
29 if (!s || typeof s !== "object") return false;
30 const st = s as Stroke;
31 return (
32 typeof st.color === "string" &&
33 typeof st.width === "number" &&
34 typeof st.erase === "boolean" &&
35 Array.isArray(st.points) &&
36 st.points.every(isPoint)
37 );
38}
39
40/**
41 * Parse the JSON embedded in a drawing PNG into a scene, or null on anything
42 * malformed. The input is effectively untrusted (any uploaded `.hzdraw.png`),
43 * so the whole shape is validated before it reaches the renderer.
44 */
45export function parseScene(text: string | null): DrawScene | null {
46 if (!text) return null;
47 let data: unknown;
48 try {
49 data = JSON.parse(text);
50 } catch {
51 return null;
52 }
53 if (!data || typeof data !== "object") return null;
54 const scene = data as DrawScene;
55 if (scene.v !== 1 || !isSide(scene.w) || !isSide(scene.h) || !Array.isArray(scene.strokes)) {
56 return null;
57 }
58 if (!scene.strokes.every(isStroke)) return null;
59 // bg is optional (old drawings lack it); reject only a present-but-bogus value.
60 if (scene.bg !== undefined && scene.bg !== "none" && scene.bg !== "lines" && scene.bg !== "grid") return null;
61 // dpr likewise optional, but it multiplies a canvas allocation on the viewer's machine, so
62 // cap it at 8 — well past any real display (1–3), while browser zoom-out legitimately
63 // exports below 1. NaN/Infinity fail the comparisons.
64 if (scene.dpr !== undefined && !(typeof scene.dpr === "number" && scene.dpr > 0 && scene.dpr <= 8)) return null;
65 return scene;
66}
67
68/**
69 * A parsed scene is only worth replaying if it has ink: a plain photo (parse failed,
70 * null) or an emptied drawing (parsed, zero strokes) both mean "nothing to play", so
71 * ReplayableImage falls back to the static image for either. Pulled out of that
72 * component (which has three call sites of its own) so the decision is unit-testable
73 * without mounting Solid.
74 */
75export function playableScene(parsed: DrawScene | null): DrawScene | null {
76 return parsed && parsed.strokes.length > 0 ? parsed : null;
77}
78
79/**
80 * Tight bounding box over every ink (pen) stroke, padded by its half-width so a
81 * thick line isn't clipped at the edge. Null when there's nothing drawn. Used to
82 * export only the drawn region of an unbounded (pannable) pad instead of the
83 * viewport.
84 */
85export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: number; h: number } | null {
86 let minX = Infinity;
87 let minY = Infinity;
88 let maxX = -Infinity;
89 let maxY = -Infinity;
90 for (const s of strokes) {
91 if (s.erase) continue; // eraser cuts existing ink, adds none — must not expand the export box
92 const r = s.width / 2;
93 for (const p of s.points) {
94 minX = Math.min(minX, p.x - r);
95 minY = Math.min(minY, p.y - r);
96 maxX = Math.max(maxX, p.x + r);
97 maxY = Math.max(maxY, p.y + r);
98 }
99 }
100 if (!Number.isFinite(minX)) return null;
101 return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
102}
103
104/**
105 * World px → device px for one canvas side, shared by the export (`renderBounds`,
106 * baking `scene.w`/`scene.h` at `scene.dpr`) and playback (`onMount`, replaying them at
107 * that same dpr) so the two can't round differently and size the replay canvas
108 * differently on screen than the static image it replaces. Floors at 1: a canvas side
109 * of 0 throws, which a tiny world side at a sub-1 dpr could otherwise round down to.
110 */
111export function canvasPx(worldSide: number, dpr: number): number {
112 return Math.max(1, Math.round(worldSide * dpr));
113}
114
115/**
116 * Split strokes at a reveal cut for order-only playback. Points are counted across
117 * strokes in drawn order; the first `revealCount` are "revealed". `full` = strokes
118 * shown in their entirety, `partial` = the stroke the cut lands inside, truncated to
119 * its revealed points (null when the cut sits on a stroke boundary). `revealCount` is
120 * clamped to [0, total points]; running out of strokes handles the upper bound.
121 */
122export function sliceStrokes(strokes: Stroke[], revealCount: number): { full: Stroke[]; partial: Stroke | null } {
123 let n = Math.max(0, Math.floor(revealCount));
124 const full: Stroke[] = [];
125 for (const s of strokes) {
126 if (n >= s.points.length) {
127 full.push(s);
128 n -= s.points.length;
129 continue;
130 }
131 // cut lands inside this stroke (0 <= n < points.length); n === 0 means it hasn't started
132 return { full, partial: n > 0 ? { ...s, points: s.points.slice(0, n) } : null };
133 }
134 return { full, partial: null };
135}
136
137function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) {
138 // The eraser cuts through the transparent drawing layer rather than painting
139 // over it, so a saved drawing keeps whatever the caller flattens it onto.
140 c.globalCompositeOperation = stroke.erase ? "destination-out" : "source-over";
141 c.strokeStyle = stroke.color;
142 c.fillStyle = stroke.color;
143 c.lineWidth = stroke.width;
144 c.lineCap = "round";
145 c.lineJoin = "round";
146}
147
148/** Replay a finished stroke. Midpoint quadratics so a fast drag reads as a curve, not a polygon. */
149export function paintStroke(c: CanvasRenderingContext2D, stroke: Stroke) {
150 const pts = stroke.points;
151 if (pts.length === 0) return;
152 applyBrush(c, stroke);
153 if (pts.length === 1) {
154 // a tap with no drag still leaves a dot
155 c.beginPath();
156 c.arc(pts[0].x, pts[0].y, stroke.width / 2, 0, Math.PI * 2);
157 c.fill();
158 return;
159 }
160 c.beginPath();
161 c.moveTo(pts[0].x, pts[0].y);
162 for (let i = 1; i < pts.length - 1; i += 1) {
163 c.quadraticCurveTo(pts[i].x, pts[i].y, (pts[i].x + pts[i + 1].x) / 2, (pts[i].y + pts[i + 1].y) / 2);
164 }
165 c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y);
166 c.stroke();
167}
168
169/**
170 * Paint only the newest segment of a stroke still being drawn. Replaying the
171 * whole drawing on every pointermove gets expensive past a few thousand points;
172 * the caller replays once on pointerup to swap in the smoothed version.
173 */
174export function paintTip(c: CanvasRenderingContext2D, stroke: Stroke) {
175 const pts = stroke.points;
176 if (pts.length < 2) {
177 paintStroke(c, stroke);
178 return;
179 }
180 applyBrush(c, stroke);
181 c.beginPath();
182 c.moveTo(pts[pts.length - 2].x, pts[pts.length - 2].y);
183 c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y);
184 c.stroke();
185}
186
187/**
188 * Paint ruled/grid paper across a device-pixel box, meant to sit UNDER the
189 * strokes. `step` is line spacing in device px. No-op for "none". Kept out of the
190 * live redraw() on purpose: the eraser (destination-out) would cut these lines, so
191 * the live pad rules itself with CSS and this only bakes the exported image.
192 */
193export function paintPaper(c: CanvasRenderingContext2D, bg: BgKind, width: number, height: number, step: number) {
194 if (bg === "none" || step <= 0) return;
195 c.strokeStyle = PAPER_LINE;
196 c.lineWidth = 1;
197 c.beginPath();
198 for (let y = step; y < height; y += step) {
199 c.moveTo(0, y);
200 c.lineTo(width, y);
201 }
202 if (bg === "grid") {
203 for (let x = step; x < width; x += step) {
204 c.moveTo(x, 0);
205 c.lineTo(x, height);
206 }
207 }
208 c.stroke();
209}