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.test.ts312 lines, 11.9 KiBHistoryRawDownload
1import { describe, expect, it } from "vitest";
2import { canvasPx, paintPaper, paintStroke, paintTip, parseScene, playableScene, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke";
3
4/** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */
5function stubContext() {
6 const calls: string[] = [];
7 const props: Record<string, unknown> = {};
8 const record =
9 (name: string) =>
10 (...args: unknown[]) => {
11 calls.push(`${name}(${args.join(",")})`);
12 };
13 const c = {
14 calls,
15 props,
16 beginPath: record("beginPath"),
17 moveTo: record("moveTo"),
18 lineTo: record("lineTo"),
19 quadraticCurveTo: record("quadraticCurveTo"),
20 arc: record("arc"),
21 fill: record("fill"),
22 stroke: record("stroke"),
23 // a style setter, not geometry — kept out of `calls` like the other styles
24 setLineDash: (segments: number[]) => {
25 props.lineDash = segments;
26 },
27 };
28 // trap the style assignments so composite mode / width can be asserted too
29 return new Proxy(c, {
30 set(target, key, value) {
31 props[String(key)] = value;
32 return Reflect.set(target, key, value);
33 },
34 }) as unknown as CanvasRenderingContext2D & { calls: string[]; props: Record<string, unknown> };
35}
36
37const stroke = (points: Stroke["points"], over: Partial<Stroke> = {}): Stroke => ({
38 color: "#000",
39 width: 4,
40 erase: false,
41 points,
42 ...over,
43});
44
45describe("paintStroke", () => {
46 it("draws nothing for an empty stroke", () => {
47 const c = stubContext();
48 paintStroke(c, stroke([]));
49 expect(c.calls).toEqual([]);
50 });
51
52 it("fills a dot for a tap with no drag", () => {
53 const c = stubContext();
54 paintStroke(c, stroke([{ x: 10, y: 20 }]));
55 // radius is half the line width, so a tap matches the pen it was drawn with
56 expect(c.calls).toContain(`arc(10,20,2,0,${Math.PI * 2})`);
57 expect(c.calls).toContain("fill()");
58 expect(c.calls).not.toContain("stroke()");
59 });
60
61 it("smooths interior points into quadratics and lands on the last point", () => {
62 const c = stubContext();
63 paintStroke(
64 c,
65 stroke([
66 { x: 0, y: 0 },
67 { x: 10, y: 0 },
68 { x: 20, y: 10 },
69 { x: 30, y: 10 },
70 ]),
71 );
72 expect(c.calls).toEqual([
73 "beginPath()",
74 "moveTo(0,0)",
75 "quadraticCurveTo(10,0,15,5)",
76 "quadraticCurveTo(20,10,25,10)",
77 "lineTo(30,10)",
78 "stroke()",
79 ]);
80 });
81
82 it("cuts through the layer when erasing instead of painting over it", () => {
83 const c = stubContext();
84 paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { erase: true }));
85 expect(c.props.globalCompositeOperation).toBe("destination-out");
86 });
87
88 it("draws a solid line unless the stroke carries a dash pattern", () => {
89 const c = stubContext();
90 paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }]));
91 expect(c.props.lineDash).toEqual([]);
92 paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dashed" }));
93 expect(c.props.lineDash).toEqual([16, 12]);
94 paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { dash: "dotted" }));
95 expect((c.props.lineDash as number[])[0]).toBe(0);
96 });
97
98 it("paints over the layer when not erasing", () => {
99 const c = stubContext();
100 paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }]));
101 expect(c.props.globalCompositeOperation).toBe("source-over");
102 });
103});
104
105describe("paintTip", () => {
106 it("draws only the newest segment, not the whole stroke", () => {
107 const c = stubContext();
108 paintTip(
109 c,
110 stroke([
111 { x: 0, y: 0 },
112 { x: 5, y: 5 },
113 { x: 9, y: 9 },
114 ]),
115 );
116 expect(c.calls).toEqual(["beginPath()", "moveTo(5,5)", "lineTo(9,9)", "stroke()"]);
117 });
118
119 it("falls back to a dot on the first point of a stroke", () => {
120 const c = stubContext();
121 paintTip(c, stroke([{ x: 3, y: 4 }]));
122 expect(c.calls).toContain("fill()");
123 });
124});
125
126describe("parseScene", () => {
127 const scene: DrawScene = { v: 1, w: 100, h: 80, strokes: [stroke([{ x: 1, y: 2 }, { x: 3, y: 4 }])] };
128
129 it("parses a valid scene", () => {
130 expect(parseScene(JSON.stringify(scene))).toEqual(scene);
131 });
132
133 it("keeps a known dash pattern and rejects an unknown one", () => {
134 const dashed = { ...scene, strokes: [{ ...scene.strokes[0], dash: "dotted" }] };
135 expect(parseScene(JSON.stringify(dashed))).toEqual(dashed);
136 expect(parseScene(JSON.stringify({ ...scene, strokes: [{ ...scene.strokes[0], dash: "wavy" }] }))).toBeNull();
137 });
138
139 it("rejects a wrong version", () => {
140 expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull();
141 });
142
143 // w/h size the playback canvas and drive paintPaper's per-cell loop, from a PNG anyone
144 // can upload: a real export can be big, but never non-finite, negative or past MAX_SIDE.
145 it("accepts a large-but-real box, rejects non-finite, non-positive and absurd sides", () => {
146 expect(parseScene(JSON.stringify({ ...scene, w: 8000, h: 16384 }))).not.toBeNull();
147 // 1e999 is valid JSON that parses to Infinity; null is what JSON.stringify makes of NaN.
148 for (const bad of ["1e999", "-1", "0", "1e9", "null", '"10"']) {
149 expect(parseScene(`{"v":1,"w":${bad},"h":10,"strokes":[]}`)).toBeNull();
150 }
151 });
152
153 it("rejects a malformed stroke shape", () => {
154 expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull();
155 });
156
157 it("rejects garbage and null", () => {
158 expect(parseScene("not json")).toBeNull();
159 expect(parseScene(null)).toBeNull();
160 });
161
162 // dpr multiplies the playback canvas allocation, from a PNG anyone can upload: it must
163 // survive the round trip, stay optional for drawings saved before it existed, and never
164 // arrive as something unusable or absurd.
165 it("round-trips dpr, tolerates its absence, rejects bogus or out-of-range ones", () => {
166 expect(parseScene(JSON.stringify({ ...scene, dpr: 2 }))?.dpr).toBe(2);
167 expect(parseScene(JSON.stringify({ ...scene, dpr: 0.5 }))?.dpr).toBe(0.5); // zoomed-out export
168 expect(parseScene(JSON.stringify(scene))?.dpr).toBeUndefined();
169 expect(parseScene(JSON.stringify({ ...scene, dpr: 0 }))).toBeNull();
170 expect(parseScene(JSON.stringify({ ...scene, dpr: "2" }))).toBeNull();
171 expect(parseScene(JSON.stringify({ ...scene, dpr: 1e9 }))).toBeNull(); // tab-killer allocation
172 });
173});
174
175describe("strokesBounds", () => {
176 it("is null with nothing drawn", () => {
177 expect(strokesBounds([])).toBeNull();
178 });
179
180 it("wraps every point and pads by half the stroke width", () => {
181 const b = strokesBounds([
182 stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // half-width 2
183 stroke([{ x: 50, y: 40 }], { width: 10 }), // half-width 5
184 ]);
185 // minX 10-2=8, minY 10-2=8, maxX 50+5=55, maxY 40+5=45
186 expect(b).toEqual({ x: 8, y: 8, w: 47, h: 37 });
187 });
188
189 it("ignores eraser strokes so a far erase doesn't pad the export box", () => {
190 const b = strokesBounds([
191 stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // pen, half-width 2
192 stroke([{ x: 500, y: 500 }], { width: 10, erase: true }), // far eraser — must not count
193 ]);
194 // same box as the pen stroke alone: minX 10-2=8, minY 10-2=8, maxX 30+2=32, maxY 20+2=22
195 expect(b).toEqual({ x: 8, y: 8, w: 24, h: 14 });
196 });
197
198 it("is null when the scene has only eraser strokes", () => {
199 expect(strokesBounds([stroke([{ x: 5, y: 5 }], { erase: true })])).toBeNull();
200 });
201});
202
203describe("sliceStrokes", () => {
204 const a = stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }]); // 3 points
205 const b = stroke([{ x: 5, y: 5 }, { x: 6, y: 6 }, { x: 7, y: 7 }, { x: 8, y: 8 }]); // 4 points
206
207 it("reveals nothing at count 0", () => {
208 expect(sliceStrokes([a, b], 0)).toEqual({ full: [], partial: null });
209 });
210
211 it("reveals every stroke, no partial, at the total point count", () => {
212 expect(sliceStrokes([a, b], 7)).toEqual({ full: [a, b], partial: null });
213 });
214
215 it("clamps past the total to the whole drawing", () => {
216 expect(sliceStrokes([a, b], 999)).toEqual({ full: [a, b], partial: null });
217 });
218
219 it("truncates the stroke the cut lands inside", () => {
220 const { full, partial } = sliceStrokes([a, b], 5); // a whole (3) + first 2 of b
221 expect(full).toEqual([a]);
222 expect(partial).toEqual({ ...b, points: b.points.slice(0, 2) });
223 });
224
225 it("gives no partial when the cut sits on a stroke boundary", () => {
226 expect(sliceStrokes([a, b], 3)).toEqual({ full: [a], partial: null }); // a done, b not started
227 });
228
229 it("handles a single-point stroke on both sides of its one point", () => {
230 const dot = stroke([{ x: 9, y: 9 }]);
231 expect(sliceStrokes([dot], 0)).toEqual({ full: [], partial: null });
232 expect(sliceStrokes([dot], 1)).toEqual({ full: [dot], partial: null });
233 });
234
235 it("is empty for no strokes", () => {
236 expect(sliceStrokes([], 0)).toEqual({ full: [], partial: null });
237 expect(sliceStrokes([], 5)).toEqual({ full: [], partial: null });
238 });
239});
240
241describe("paintPaper", () => {
242 it("draws nothing for none", () => {
243 const c = stubContext();
244 paintPaper(c, "none", 100, 100, 24);
245 expect(c.calls).toEqual([]);
246 });
247
248 it("draws only horizontal rules for lines", () => {
249 const c = stubContext();
250 paintPaper(c, "lines", 100, 100, 24);
251 const moves = c.calls.filter((s) => s.startsWith("moveTo"));
252 expect(moves.length).toBeGreaterThan(0);
253 // every rule starts at the left edge (x=0) — no vertical segments
254 expect(moves.every((s) => s.startsWith("moveTo(0,"))).toBe(true);
255 expect(c.calls).toContain("stroke()");
256 });
257
258 it("draws both horizontal and vertical lines for grid", () => {
259 const c = stubContext();
260 paintPaper(c, "grid", 100, 100, 24);
261 const moves = c.calls.filter((s) => s.startsWith("moveTo"));
262 const horizontal = moves.filter((s) => s.startsWith("moveTo(0,"));
263 const vertical = moves.filter((s) => !s.startsWith("moveTo(0,"));
264 expect(horizontal.length).toBeGreaterThan(0);
265 expect(vertical.length).toBeGreaterThan(0);
266 });
267});
268
269// canvasPx is the one spot both the export (draw-canvas's renderBounds) and playback
270// (drawing-playback's onMount) canvases round a world-px side into device px — if the
271// two ever computed this differently, the replay would render at a different on-screen
272// size than the static <img> it swaps in for.
273describe("canvasPx", () => {
274 it("rounds world px * dpr to the nearest device px across export- and playback-typical dprs", () => {
275 for (const side of [1, 16.5, 100.4, 123.7, 8000]) {
276 for (const dpr of [0.5, 1, 2, 3]) {
277 expect(canvasPx(side, dpr)).toBe(Math.max(1, Math.round(side * dpr)));
278 }
279 }
280 });
281
282 it("floors at 1 device px so a tiny side at a sub-1 dpr never yields a 0-sized canvas", () => {
283 expect(canvasPx(0.5, 0.5)).toBe(1); // 0.25 rounds to 0, which a canvas can't allocate
284 });
285
286 // drawing-playback's onMount resolves `scene.dpr ?? window.devicePixelRatio` before
287 // calling canvasPx — mirrored here since onMount itself needs a real DOM mount, which
288 // this repo has no headless (jsdom-free) way to drive.
289 it("mirrors the playback side's dpr fallback: a scene without dpr uses the viewer's ratio", () => {
290 const viewerRatio = 3;
291 const missingDpr: number | undefined = undefined;
292 const savedDpr: number | undefined = 2;
293 expect(canvasPx(100, missingDpr ?? viewerRatio)).toBe(canvasPx(100, viewerRatio));
294 expect(canvasPx(100, savedDpr ?? viewerRatio)).toBe(canvasPx(100, 2)); // a saved dpr wins over the fallback
295 });
296});
297
298describe("playableScene", () => {
299 const scene: DrawScene = { v: 1, w: 10, h: 10, strokes: [stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }])] };
300
301 it("passes through a scene with at least one stroke — the playback branch", () => {
302 expect(playableScene(scene)).toBe(scene);
303 });
304
305 it("is null for a scene with zero strokes — an emptied drawing falls back to the static image", () => {
306 expect(playableScene({ ...scene, strokes: [] })).toBeNull();
307 });
308
309 it("is null for null — a plain photo with nothing embedded", () => {
310 expect(playableScene(null)).toBeNull();
311 });
312});