@widgetic/canvas 0.5.14 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,701 @@
1
+ /**
2
+ * @file strokeShapeSnap.ts
3
+ * @description Turn a hand-drawn freehand stroke into the shape it was meant to be.
4
+ *
5
+ * The Draw tool uses Fabric's `PencilBrush`, so a "shape" the user tries to draw
6
+ * arrives as a wobbly polyline — dozens of sampled points, corners that overshoot,
7
+ * edges that bow. This module measures that polyline and decides whether it is a
8
+ * clean enough instance of a shape the canvas can actually build.
9
+ *
10
+ * **Geometry belongs in code.** JEV cannot see a stroke: it judges text, and the
11
+ * only thing that could be said to it in text is a *measurement* of the stroke,
12
+ * which code has to compute anyway. So the pipeline is:
13
+ *
14
+ * 1. measure the stroke here, deterministically (closed? how many corners? how
15
+ * circular? how far off axis? aspect ratio?) — 0ms, no network;
16
+ * 2. gate every shape the canvas can build through the conditions it *cannot*
17
+ * be — a shape whose gate fails is never offered to anyone, so nothing
18
+ * impossible can be chosen;
19
+ * 3. rank the survivors by how well they match, and a decisive winner is
20
+ * applied immediately with no model call;
21
+ * 4. only when the survivors are ambiguous (a near-square, an oval that is
22
+ * almost a circle) does the caller escalate to JEV, which is exactly the
23
+ * closed-set choice with a confidence gate it is good at — and which can
24
+ * only ever replace a wrong *snap* with the stroke left as drawn.
25
+ *
26
+ * Everything here is pure: it takes command data and points, never a Fabric
27
+ * object, so it can be tested with `npm test` and reused by any caller that can
28
+ * produce a polyline.
29
+ */
30
+ /**
31
+ * The feature flag for this whole behaviour, as requested for the experiment:
32
+ * `true` means a recognized stroke is replaced by the clean shape, `false` means
33
+ * every stroke stays exactly as it was drawn. One line to roll back.
34
+ */
35
+ export const CANVAS_SHAPE_SNAP_ENABLED = true;
36
+ export const CANVAS_SNAP_SHAPES = [
37
+ 'rect',
38
+ 'circle',
39
+ 'oval',
40
+ 'triangle',
41
+ 'diamond',
42
+ 'hexagon'
43
+ ];
44
+ /** How each candidate is described when the roster is shown to JEV. */
45
+ export const CANVAS_SNAP_SHAPE_LABELS = {
46
+ rect: 'rectangle or square',
47
+ circle: 'circle',
48
+ oval: 'oval (ellipse)',
49
+ triangle: 'triangle',
50
+ diamond: 'diamond (a square turned 45°)',
51
+ hexagon: 'hexagon'
52
+ };
53
+ /**
54
+ * A decisive winner needs a solid score *and* a lead over the runner-up. Below
55
+ * either bar the caller escalates to JEV instead of snapping on a coin flip.
56
+ */
57
+ export const STROKE_SNAP_MIN_SCORE = 0.78;
58
+ export const STROKE_SNAP_MIN_MARGIN = 0.12;
59
+ /** Ends closer than this fraction of the diagonal count as a closed shape. */
60
+ const CLOSED_GAP_RATIO = 0.25;
61
+ /** A turn this far from straight counts as a corner. */
62
+ const CORNER_TURN_RAD = Math.PI / 4;
63
+ /**
64
+ * Corner detection runs on the resampled ring, in units of samples: the turn at
65
+ * a point is measured between the directions `CORNER_HALF_WINDOW` samples either
66
+ * side of it, and the outline must be *flat* for `CORNER_FLAT_WINDOW` samples
67
+ * beyond that before the turn counts.
68
+ *
69
+ * The flatness condition is what keeps a curve from reading as corners. The ends
70
+ * of a 2:1 oval bend almost as sharply as a rectangle's corner if you only look
71
+ * at the local turn; what makes them different is that a rectangle is straight
72
+ * on both sides of its corner and an oval never is.
73
+ */
74
+ const CORNER_HALF_WINDOW = 3;
75
+ const CORNER_FLAT_WINDOW = 5;
76
+ /** Corners within this many samples of each other are one corner, not two. */
77
+ const CORNER_MERGE_SAMPLES = 6;
78
+ /** A direction within this many radians of an axis counts as axis-aligned. */
79
+ const AXIS_TOLERANCE_RAD = Math.PI / 9;
80
+ /** Uniform arc-length samples taken before measuring — decoupled from draw speed. */
81
+ const RESAMPLE_COUNT = 96;
82
+ // ── Path disassembly ────────────────────────────────────────────────────────
83
+ /**
84
+ * Flatten path commands into a polyline.
85
+ *
86
+ * Fabric's `PencilBrush` emits `M` followed by a run of quadratic curves whose
87
+ * control point is the sampled pointer and whose endpoint is the midpoint of the
88
+ * next segment, so the curves must be sampled rather than read as endpoints.
89
+ * `L`, `H`, `V` and `Z` are handled too, which makes this usable on any path the
90
+ * canvas holds — including the clean shapes themselves.
91
+ */
92
+ export function flattenPathCommands(commands, samplesPerCurve = 10) {
93
+ const points = [];
94
+ let cursor = { x: 0, y: 0 };
95
+ let subpathStart = { x: 0, y: 0 };
96
+ const push = (point) => {
97
+ const last = points[points.length - 1];
98
+ if (!last || Math.abs(last.x - point.x) > 1e-6 || Math.abs(last.y - point.y) > 1e-6) {
99
+ points.push(point);
100
+ }
101
+ };
102
+ for (const command of commands) {
103
+ const op = String(command[0] ?? '').toUpperCase();
104
+ const n = (i) => Number(command[i]) || 0;
105
+ switch (op) {
106
+ case 'M':
107
+ cursor = { x: n(1), y: n(2) };
108
+ subpathStart = { ...cursor };
109
+ push(cursor);
110
+ break;
111
+ case 'L':
112
+ cursor = { x: n(1), y: n(2) };
113
+ push(cursor);
114
+ break;
115
+ case 'H':
116
+ cursor = { x: n(1), y: cursor.y };
117
+ push(cursor);
118
+ break;
119
+ case 'V':
120
+ cursor = { x: cursor.x, y: n(1) };
121
+ push(cursor);
122
+ break;
123
+ case 'Q': {
124
+ const control = { x: n(1), y: n(2) };
125
+ const end = { x: n(3), y: n(4) };
126
+ for (let i = 1; i <= samplesPerCurve; i++) {
127
+ push(quadraticPoint(cursor, control, end, i / samplesPerCurve));
128
+ }
129
+ cursor = end;
130
+ break;
131
+ }
132
+ case 'C': {
133
+ const c1 = { x: n(1), y: n(2) };
134
+ const c2 = { x: n(3), y: n(4) };
135
+ const end = { x: n(5), y: n(6) };
136
+ for (let i = 1; i <= samplesPerCurve; i++) {
137
+ push(cubicPoint(cursor, c1, c2, end, i / samplesPerCurve));
138
+ }
139
+ cursor = end;
140
+ break;
141
+ }
142
+ case 'Z':
143
+ cursor = { ...subpathStart };
144
+ push(cursor);
145
+ break;
146
+ default:
147
+ break;
148
+ }
149
+ }
150
+ return points;
151
+ }
152
+ function quadraticPoint(p0, p1, p2, t) {
153
+ const u = 1 - t;
154
+ return {
155
+ x: u * u * p0.x + 2 * u * t * p1.x + t * t * p2.x,
156
+ y: u * u * p0.y + 2 * u * t * p1.y + t * t * p2.y
157
+ };
158
+ }
159
+ function cubicPoint(p0, p1, p2, p3, t) {
160
+ const u = 1 - t;
161
+ return {
162
+ x: u ** 3 * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t ** 3 * p3.x,
163
+ y: u ** 3 * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t ** 3 * p3.y
164
+ };
165
+ }
166
+ // ── Resampling and simplification ───────────────────────────────────────────
167
+ /** Uniform arc-length resample, so fast and slow strokes are measured the same. */
168
+ export function resample(points, count = RESAMPLE_COUNT) {
169
+ if (points.length < 2)
170
+ return points.map((p) => ({ ...p }));
171
+ const cumulative = [0];
172
+ for (let i = 1; i < points.length; i++) {
173
+ cumulative.push(cumulative[i - 1] + distance(points[i - 1], points[i]));
174
+ }
175
+ const total = cumulative[cumulative.length - 1];
176
+ if (total <= 0)
177
+ return points.map((p) => ({ ...p }));
178
+ const step = total / (count - 1);
179
+ const out = [{ ...points[0] }];
180
+ let segment = 0;
181
+ for (let i = 1; i < count - 1; i++) {
182
+ const target = i * step;
183
+ while (segment < cumulative.length - 2 && cumulative[segment + 1] < target)
184
+ segment++;
185
+ const spanStart = cumulative[segment];
186
+ const spanLength = cumulative[segment + 1] - spanStart;
187
+ const t = spanLength > 0 ? (target - spanStart) / spanLength : 0;
188
+ out.push({
189
+ x: points[segment].x + (points[segment + 1].x - points[segment].x) * t,
190
+ y: points[segment].y + (points[segment + 1].y - points[segment].y) * t
191
+ });
192
+ }
193
+ out.push({ ...points[points.length - 1] });
194
+ return out;
195
+ }
196
+ /** Ramer–Douglas–Peucker — the vertices a human would name as the corners. */
197
+ export function simplify(points, tolerance) {
198
+ if (points.length <= 2)
199
+ return points.map((p) => ({ ...p }));
200
+ const keep = new Array(points.length).fill(false);
201
+ keep[0] = true;
202
+ keep[points.length - 1] = true;
203
+ const stack = [[0, points.length - 1]];
204
+ while (stack.length > 0) {
205
+ const [first, last] = stack.pop();
206
+ let worst = -1;
207
+ let worstDistance = tolerance;
208
+ for (let i = first + 1; i < last; i++) {
209
+ const d = perpendicularDistance(points[i], points[first], points[last]);
210
+ if (d > worstDistance) {
211
+ worst = i;
212
+ worstDistance = d;
213
+ }
214
+ }
215
+ if (worst > 0) {
216
+ keep[worst] = true;
217
+ stack.push([first, worst], [worst, last]);
218
+ }
219
+ }
220
+ return points.filter((_, i) => keep[i]).map((p) => ({ ...p }));
221
+ }
222
+ // ── Measurement ─────────────────────────────────────────────────────────────
223
+ export function measureStroke(rawPoints) {
224
+ if (rawPoints.length < 3)
225
+ return null;
226
+ const points = resample(rawPoints);
227
+ const bounds = boundingBox(points);
228
+ const diagonal = Math.hypot(bounds.width, bounds.height);
229
+ if (diagonal <= 0)
230
+ return null;
231
+ // Simplify with a tolerance proportional to the stroke, so the same drawing
232
+ // at any zoom yields the same vertices — this is the edge direction set that
233
+ // axis alignment and tilt are read from.
234
+ const simplified = simplify(points, Math.max(1.5, diagonal * 0.025));
235
+ const gap = distance(points[0], points[points.length - 1]);
236
+ const gapRatio = gap / diagonal;
237
+ const closed = gapRatio <= CLOSED_GAP_RATIO;
238
+ const corners = detectCorners(points, closed, diagonal);
239
+ const perimeter = pathLength(points);
240
+ const area = Math.abs(polygonArea(points));
241
+ return {
242
+ pointCount: points.length,
243
+ closed,
244
+ gapRatio: round(gapRatio),
245
+ vertexCount: simplified.length,
246
+ cornerCount: corners.count,
247
+ cornerSharpness: round(corners.maxSharpness),
248
+ aspectRatio: round(Math.max(bounds.width, bounds.height) / Math.max(1e-6, Math.min(bounds.width, bounds.height))),
249
+ straightness: round(straightness(points)),
250
+ circularity: round(perimeter > 0 ? Math.min(1, (4 * Math.PI * area) / (perimeter * perimeter)) : 0),
251
+ axisAlignment: round(axisAlignment(simplified)),
252
+ axisTilt: round(axisTilt(simplified)),
253
+ radialUniformity: round(radialUniformity(points)),
254
+ bounds
255
+ };
256
+ }
257
+ /**
258
+ * Corners, and how sharp the sharpest one is.
259
+ *
260
+ * A sample is a corner when the outline turns sharply there *and* runs straight
261
+ * on both sides of it. When the stroke closes, the ring wraps, so the joint
262
+ * between the first and last samples is a candidate like any other — that is
263
+ * where a rectangle drawn in one motion starts and ends, and missing it would
264
+ * score a rectangle as a triangle. Detections closer together than
265
+ * `CORNER_MERGE_SAMPLES` are one corner, which is what stops a corner that
266
+ * straddles the joint from being counted twice.
267
+ */
268
+ function detectCorners(ring, closed, diagonal) {
269
+ const count = ring.length;
270
+ if (count < 2 * CORNER_HALF_WINDOW + 3)
271
+ return { count: 0, maxSharpness: 0 };
272
+ const flatnessTolerance = diagonal * 0.02;
273
+ const at = (index) => ring[closed ? (index + count) % count : index];
274
+ const inRange = (index) => closed || (index >= 0 && index < count);
275
+ const candidates = [];
276
+ for (let i = 0; i < count; i++) {
277
+ const start = i - CORNER_HALF_WINDOW;
278
+ const end = i + CORNER_HALF_WINDOW;
279
+ if (!inRange(start) || !inRange(end))
280
+ continue;
281
+ const turn = turnAngle(at(start), at(i), at(end));
282
+ if (turn < CORNER_TURN_RAD)
283
+ continue;
284
+ const before = i - CORNER_HALF_WINDOW - CORNER_FLAT_WINDOW;
285
+ const after = i + CORNER_HALF_WINDOW + CORNER_FLAT_WINDOW;
286
+ if (!inRange(before) || !inRange(after))
287
+ continue;
288
+ if (!segmentIsFlat(ring, closed, before, i, flatnessTolerance))
289
+ continue;
290
+ if (!segmentIsFlat(ring, closed, i, after, flatnessTolerance))
291
+ continue;
292
+ // 45° of turn is a corner; a right angle is a hard one.
293
+ candidates.push({
294
+ index: i,
295
+ sharpness: Math.min(1, (turn - CORNER_TURN_RAD) / (Math.PI / 2 - CORNER_TURN_RAD))
296
+ });
297
+ }
298
+ const merged = mergeAdjacentCorners(candidates, count, closed);
299
+ return {
300
+ count: merged.length,
301
+ maxSharpness: merged.length > 0 ? Math.max(...merged.map((c) => c.sharpness)) : 0
302
+ };
303
+ }
304
+ /** One corner per cluster, keeping the sharpest reading in it. */
305
+ function mergeAdjacentCorners(candidates, ringLength, closed) {
306
+ if (candidates.length === 0)
307
+ return [];
308
+ const sorted = [...candidates].sort((a, b) => a.index - b.index);
309
+ const merged = [];
310
+ for (const candidate of sorted) {
311
+ const last = merged[merged.length - 1];
312
+ if (last && candidate.index - last.index <= CORNER_MERGE_SAMPLES) {
313
+ if (candidate.sharpness > last.sharpness)
314
+ merged[merged.length - 1] = candidate;
315
+ continue;
316
+ }
317
+ merged.push(candidate);
318
+ }
319
+ // The ring's first and last clusters can be the same corner either side of
320
+ // the joint.
321
+ if (closed && merged.length > 1) {
322
+ const first = merged[0];
323
+ const last = merged[merged.length - 1];
324
+ if (ringLength - last.index + first.index <= CORNER_MERGE_SAMPLES) {
325
+ if (first.sharpness >= last.sharpness)
326
+ merged.pop();
327
+ else
328
+ merged.shift();
329
+ }
330
+ }
331
+ return merged;
332
+ }
333
+ /** Whether the ring samples between two indices stay on their own chord. */
334
+ function segmentIsFlat(ring, closed, from, to, tolerance) {
335
+ const length = ring.length;
336
+ const start = ring[closed ? ((from % length) + length) % length : from];
337
+ const end = ring[closed ? ((to % length) + length) % length : to];
338
+ if (!start || !end)
339
+ return false;
340
+ const steps = Math.abs(to - from);
341
+ for (let step = 1; step < steps; step++) {
342
+ const index = closed ? (((from + step) % length) + length) % length : from + step;
343
+ const point = ring[index];
344
+ if (!point)
345
+ return false;
346
+ if (perpendicularDistance(point, start, end) > tolerance)
347
+ return false;
348
+ }
349
+ return true;
350
+ }
351
+ /** How far the stroke drifts sideways from the straight chord between its ends. */
352
+ function straightness(points) {
353
+ const start = points[0];
354
+ const end = points[points.length - 1];
355
+ const chord = distance(start, end);
356
+ if (chord <= 1e-6)
357
+ return 0;
358
+ let worst = 0;
359
+ for (const point of points)
360
+ worst = Math.max(worst, perpendicularDistance(point, start, end));
361
+ // A quarter of the chord of sideways drift is already decidedly not a line.
362
+ return clamp01(1 - worst / chord / 0.25);
363
+ }
364
+ /** Share of the outline running within `AXIS_TOLERANCE_RAD` of horizontal or vertical. */
365
+ function axisAlignment(simplified) {
366
+ let aligned = 0;
367
+ let total = 0;
368
+ for (let i = 1; i < simplified.length; i++) {
369
+ const dx = simplified[i].x - simplified[i - 1].x;
370
+ const dy = simplified[i].y - simplified[i - 1].y;
371
+ const length = Math.hypot(dx, dy);
372
+ if (length <= 1e-6)
373
+ continue;
374
+ total += length;
375
+ const angle = Math.atan2(Math.abs(dy), Math.abs(dx));
376
+ const offAxis = Math.min(angle, Math.abs(Math.PI / 2 - angle));
377
+ if (offAxis <= AXIS_TOLERANCE_RAD)
378
+ aligned += length;
379
+ }
380
+ return total > 0 ? aligned / total : 0;
381
+ }
382
+ /**
383
+ * How far the outline's edges are from the axes overall: 0 when they run along
384
+ * the axes, 1 when they run along the diagonals.
385
+ *
386
+ * This is what separates a *diamond* from a *rotated rectangle* and what keeps a
387
+ * rectangle drawn on a tilt from being snapped to an upright one. Edge
388
+ * directions are folded to a 90° period (a rectangle's vertical edges are the
389
+ * same axis as its horizontal ones), averaged as a circular mean, and reported
390
+ * as the distance from that axis over the 45° maximum.
391
+ */
392
+ function axisTilt(simplified) {
393
+ let sin = 0;
394
+ let cos = 0;
395
+ let total = 0;
396
+ for (let i = 1; i < simplified.length; i++) {
397
+ const dx = simplified[i].x - simplified[i - 1].x;
398
+ const dy = simplified[i].y - simplified[i - 1].y;
399
+ const length = Math.hypot(dx, dy);
400
+ if (length <= 1e-6)
401
+ continue;
402
+ const angle = Math.atan2(dy, dx);
403
+ sin += Math.sin(angle * 4) * length;
404
+ cos += Math.cos(angle * 4) * length;
405
+ total += length;
406
+ }
407
+ if (total <= 0)
408
+ return 0;
409
+ // Back out of the ×4 folding: the result is an axis direction in [0, π/2).
410
+ let axis = Math.atan2(sin / total, cos / total) / 4;
411
+ if (axis < 0)
412
+ axis += Math.PI / 2;
413
+ const offAxis = Math.min(axis, Math.PI / 2 - axis);
414
+ return clamp01(offAxis / (Math.PI / 4));
415
+ }
416
+ /** 1 when every boundary point is equidistant from the centroid, 0 when very uneven. */
417
+ function radialUniformity(points) {
418
+ const centre = centroid(points);
419
+ const radii = points.map((p) => distance(p, centre));
420
+ const mean = radii.reduce((a, b) => a + b, 0) / radii.length;
421
+ if (mean <= 1e-6)
422
+ return 0;
423
+ const variance = radii.reduce((sum, r) => sum + (r - mean) ** 2, 0) / radii.length;
424
+ // A rectangle's radii vary enough to reach ~0.88; a circle stays at ~1.
425
+ return clamp01(1 - Math.sqrt(variance) / mean);
426
+ }
427
+ /**
428
+ * What each shape should measure like, as ranges rather than thresholds, so one
429
+ * function scores every candidate and a slightly-loose drawing still scores
430
+ * well on the features it does satisfy.
431
+ */
432
+ const SHAPE_PROFILES = {
433
+ rect: {
434
+ corners: [3.5, 4.5],
435
+ circularity: [0, 0.85],
436
+ axisAlignment: [0.75, 1],
437
+ axisTilt: [0, 0.25],
438
+ aspect: null,
439
+ minCornerSharpness: 0.35
440
+ },
441
+ circle: {
442
+ corners: [0, 2],
443
+ circularity: [0.9, 1],
444
+ axisAlignment: [0, 1],
445
+ axisTilt: null,
446
+ aspect: [0.9, 1.1],
447
+ minCornerSharpness: 0
448
+ },
449
+ oval: {
450
+ corners: [0, 2],
451
+ circularity: [0.55, 0.93],
452
+ axisAlignment: [0, 1],
453
+ axisTilt: null,
454
+ aspect: [1.2, 6],
455
+ minCornerSharpness: 0
456
+ },
457
+ triangle: {
458
+ corners: [2.5, 3.5],
459
+ circularity: [0, 0.8],
460
+ axisAlignment: [0, 0.9],
461
+ axisTilt: null,
462
+ aspect: null,
463
+ minCornerSharpness: 0.3
464
+ },
465
+ diamond: {
466
+ corners: [3.5, 5],
467
+ circularity: [0.5, 0.9],
468
+ axisAlignment: [0, 0.35],
469
+ axisTilt: [0.85, 1],
470
+ aspect: [0.6, 1.7],
471
+ minCornerSharpness: 0.35
472
+ },
473
+ hexagon: {
474
+ corners: [5.5, 6.5],
475
+ circularity: [0.7, 0.93],
476
+ axisAlignment: [0.2, 1],
477
+ axisTilt: null,
478
+ aspect: [0.6, 1.7],
479
+ minCornerSharpness: 0.3
480
+ }
481
+ };
482
+ /**
483
+ * The conditions under which a shape is *impossible*, whatever the style of
484
+ * drawing — a stroke with six corners is not a triangle, and a stroke whose
485
+ * edges run along the diagonals is not an upright rectangle. A shape that fails
486
+ * its gate is not scored, not ranked, and never offered to JEV, so no part of
487
+ * this pipeline can propose a shape the drawing plainly is not.
488
+ *
489
+ * These are deliberately looser than the scoring ranges: the gates decide
490
+ * eligibility, the scores decide confidence. A stroke that passes no gate has no
491
+ * candidates at all, and the caller leaves it exactly as drawn.
492
+ */
493
+ const SHAPE_GATES = {
494
+ rect: (m, closedish) => closedish && m.cornerCount >= 3 && m.cornerCount <= 5 && m.axisTilt <= 0.25,
495
+ triangle: (m, closedish) => closedish && m.cornerCount === 3 && m.straightness < 0.55,
496
+ // A diamond is a square turned 45°, so its edges run along the diagonals.
497
+ // The bar is high on purpose: a quad tilted 30° is neither an upright
498
+ // rectangle nor a diamond, and snapping it to either would look wrong.
499
+ diamond: (m, closedish) => closedish && m.cornerCount >= 4 && m.cornerCount <= 5 && m.axisTilt >= 0.8,
500
+ hexagon: (m, closedish) => closedish && m.cornerCount >= 5 && m.cornerCount <= 8,
501
+ circle: (m, closedish) => closedish && m.cornerCount <= 2 && m.aspectRatio <= 1.16,
502
+ oval: (m, closedish) => closedish && m.cornerCount <= 2 && m.aspectRatio >= 1.14
503
+ };
504
+ /** Feature weights — corners and roundness discriminate more than shape drift. */
505
+ const FEATURE_WEIGHTS = {
506
+ closed: 1.6,
507
+ corners: 2,
508
+ circularity: 1.6,
509
+ axisAlignment: 1.4,
510
+ axisTilt: 1.4,
511
+ aspect: 1.6,
512
+ cornerSharpness: 1
513
+ };
514
+ /**
515
+ * The shapes this stroke could still plausibly be, best first.
516
+ *
517
+ * Empty means "not a shape the canvas can build" — a line, a scribble, a
518
+ * signature, a check mark, a tilted quad — and the caller must leave the drawing
519
+ * untouched. The returned list doubles as the roster for the JEV escalation, so
520
+ * JEV is only ever asked to choose between shapes the stroke could actually be.
521
+ */
522
+ export function rankSnapShapes(measurements) {
523
+ // Nothing closed *and* nothing cornered is not an outline at all.
524
+ const closedish = measurements.closed || measurements.gapRatio <= 0.5;
525
+ if (!closedish && measurements.cornerCount < 3)
526
+ return [];
527
+ return CANVAS_SNAP_SHAPES.filter((shape) => SHAPE_GATES[shape](measurements, closedish))
528
+ .map((shape) => ({
529
+ shape,
530
+ score: round(scoreShape(measurements, SHAPE_PROFILES[shape], measurements.closed))
531
+ }))
532
+ .sort((a, b) => b.score - a.score || a.shape.localeCompare(b.shape));
533
+ }
534
+ function scoreShape(measurements, profile, closed) {
535
+ // A closed shape drawn with a visible gap is still that shape, just less
536
+ // certainly.
537
+ const closedMatch = closed
538
+ ? 1
539
+ : clamp01(1 - (measurements.gapRatio - CLOSED_GAP_RATIO) / 0.5) * 0.5;
540
+ const cornerMatch = measurements.cornerCount >= profile.corners[0] && measurements.cornerCount <= profile.corners[1]
541
+ ? 1
542
+ : clamp01(1 - rangeDistance(measurements.cornerCount, profile.corners) / 1.5);
543
+ const sharpnessMatch = profile.minCornerSharpness > 0
544
+ ? clamp01(1 - Math.max(0, profile.minCornerSharpness - measurements.cornerSharpness) / 0.5)
545
+ : 1;
546
+ const weighted = [
547
+ [closedMatch, FEATURE_WEIGHTS.closed],
548
+ // Circularity is the sharpest circle/oval discriminator, so it is
549
+ // satisfied instead of graded: a perfect circle is nothing like an oval.
550
+ [
551
+ rangeSatisfaction(measurements.circularity, profile.circularity, 0.06),
552
+ FEATURE_WEIGHTS.circularity
553
+ ],
554
+ [
555
+ rangeSatisfaction(measurements.axisAlignment, profile.axisAlignment, 0.3),
556
+ FEATURE_WEIGHTS.axisAlignment
557
+ ],
558
+ [
559
+ profile.axisTilt ? rangeSatisfaction(measurements.axisTilt, profile.axisTilt, 0.3) : 1,
560
+ FEATURE_WEIGHTS.axisTilt
561
+ ],
562
+ [
563
+ profile.aspect ? rangeSatisfaction(measurements.aspectRatio, profile.aspect, 0.45) : 1,
564
+ FEATURE_WEIGHTS.aspect
565
+ ],
566
+ [cornerMatch, FEATURE_WEIGHTS.corners],
567
+ [sharpnessMatch, FEATURE_WEIGHTS.cornerSharpness]
568
+ ];
569
+ const totalWeight = weighted.reduce((sum, [, weight]) => sum + weight, 0);
570
+ return clamp01(weighted.reduce((sum, [value, weight]) => sum + value * weight, 0) / totalWeight);
571
+ }
572
+ /**
573
+ * The winner when it is decisive — a solid score *and* a clear lead over the
574
+ * runner-up. `null` means "ask JEV", or, when there is no JEV to ask, leave the
575
+ * stroke as drawn.
576
+ */
577
+ export function confidentSnapShape(rankings) {
578
+ const [best, runnerUp] = rankings;
579
+ if (!best || best.score < STROKE_SNAP_MIN_SCORE)
580
+ return null;
581
+ if (runnerUp && best.score - runnerUp.score < STROKE_SNAP_MIN_MARGIN)
582
+ return null;
583
+ return best;
584
+ }
585
+ /**
586
+ * Where the clean shape goes: exactly the stroke's bounds.
587
+ *
588
+ * Three shapes refuse to stretch, because stretching them would change which
589
+ * shape they are: a circle whose bounds are 2:1 is an oval, and the library
590
+ * shapes are square-designed symbols. Those get the smaller side, centred on the
591
+ * stroke — the same thing the toolbar does when `lockAspectRatio` is set.
592
+ *
593
+ * Rotation is deliberately not applied: the replacement is upright, which is
594
+ * what the toolbar would have given the user, and strokes tilted far enough to
595
+ * matter never reach here (see `SHAPE_GATES`).
596
+ */
597
+ export function planSnapPlacement(shape, bounds) {
598
+ if (shape === 'circle' || shape === 'diamond' || shape === 'hexagon') {
599
+ const side = Math.max(1, Math.min(bounds.width, bounds.height));
600
+ return {
601
+ bounds: {
602
+ left: bounds.left + (bounds.width - side) / 2,
603
+ top: bounds.top + (bounds.height - side) / 2,
604
+ width: side,
605
+ height: side
606
+ },
607
+ forcedSide: side
608
+ };
609
+ }
610
+ return { bounds };
611
+ }
612
+ // ── Small geometry helpers ──────────────────────────────────────────────────
613
+ function distance(a, b) {
614
+ return Math.hypot(a.x - b.x, a.y - b.y);
615
+ }
616
+ function centroid(points) {
617
+ let x = 0;
618
+ let y = 0;
619
+ for (const point of points) {
620
+ x += point.x;
621
+ y += point.y;
622
+ }
623
+ return { x: x / points.length, y: y / points.length };
624
+ }
625
+ function boundingBox(points) {
626
+ let minX = Infinity;
627
+ let minY = Infinity;
628
+ let maxX = -Infinity;
629
+ let maxY = -Infinity;
630
+ for (const point of points) {
631
+ if (point.x < minX)
632
+ minX = point.x;
633
+ if (point.y < minY)
634
+ minY = point.y;
635
+ if (point.x > maxX)
636
+ maxX = point.x;
637
+ if (point.y > maxY)
638
+ maxY = point.y;
639
+ }
640
+ return { left: minX, top: minY, width: maxX - minX, height: maxY - minY };
641
+ }
642
+ function pathLength(points) {
643
+ let total = 0;
644
+ for (let i = 1; i < points.length; i++)
645
+ total += distance(points[i - 1], points[i]);
646
+ return total;
647
+ }
648
+ /** Signed area of the point ring. */
649
+ function polygonArea(points) {
650
+ let area = 0;
651
+ for (let i = 0; i < points.length; i++) {
652
+ const a = points[i];
653
+ const b = points[(i + 1) % points.length];
654
+ area += a.x * b.y - b.x * a.y;
655
+ }
656
+ return area / 2;
657
+ }
658
+ /** Shortest distance from a point to the segment `a`–`b`. */
659
+ function perpendicularDistance(point, a, b) {
660
+ const dx = b.x - a.x;
661
+ const dy = b.y - a.y;
662
+ const lengthSquared = dx * dx + dy * dy;
663
+ if (lengthSquared <= 1e-12)
664
+ return distance(point, a);
665
+ const t = clamp01(((point.x - a.x) * dx + (point.y - a.y) * dy) / lengthSquared);
666
+ return distance(point, { x: a.x + t * dx, y: a.y + t * dy });
667
+ }
668
+ /**
669
+ * How far the path turns at `current`, in radians — 0 when the path continues
670
+ * straight through it, 45° for a hexagon's vertex, 90° for a rectangle's corner.
671
+ */
672
+ function turnAngle(previous, current, next) {
673
+ const a = { x: current.x - previous.x, y: current.y - previous.y };
674
+ const b = { x: next.x - current.x, y: next.y - current.y };
675
+ const lengthA = Math.hypot(a.x, a.y);
676
+ const lengthB = Math.hypot(b.x, b.y);
677
+ if (lengthA <= 1e-6 || lengthB <= 1e-6)
678
+ return 0;
679
+ const cosine = clampUnit((a.x * b.x + a.y * b.y) / (lengthA * lengthB));
680
+ return Math.acos(cosine);
681
+ }
682
+ /** 1 inside the range, decaying linearly outside it over `tolerance`. */
683
+ function rangeSatisfaction(value, range, tolerance) {
684
+ return clamp01(1 - rangeDistance(value, range) / tolerance);
685
+ }
686
+ function rangeDistance(value, range) {
687
+ if (value < range[0])
688
+ return range[0] - value;
689
+ if (value > range[1])
690
+ return value - range[1];
691
+ return 0;
692
+ }
693
+ function clamp01(value) {
694
+ return Math.min(1, Math.max(0, value));
695
+ }
696
+ function clampUnit(value) {
697
+ return Math.min(1, Math.max(-1, value));
698
+ }
699
+ function round(value) {
700
+ return Math.round(value * 1000) / 1000;
701
+ }