forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

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