@vitavision/stage2d 0.12.0 → 0.13.0

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.
Files changed (38) hide show
  1. package/README.md +3 -6
  2. package/dist/index.d.ts +669 -57
  3. package/dist/index.js +5455 -3621
  4. package/dist/index.js.map +1 -1
  5. package/package.json +2 -2
  6. package/src/components/AreaSet.tsx +4 -4
  7. package/src/components/ContourEditor.tsx +286 -37
  8. package/src/components/DatumEditor.tsx +261 -0
  9. package/src/components/EllipseSet.tsx +3 -3
  10. package/src/components/GridLayer.tsx +1 -2
  11. package/src/components/HeatmapLayer.tsx +1 -1
  12. package/src/components/MeasureOverlay.tsx +320 -89
  13. package/src/components/PointSet.tsx +4 -4
  14. package/src/components/PolylineSet.tsx +81 -17
  15. package/src/components/RectRoiEditor.tsx +188 -84
  16. package/src/components/ShapeEditor.tsx +14 -4
  17. package/src/components/areaBatching.ts +1 -1
  18. package/src/components/contourArc.ts +268 -0
  19. package/src/components/datumEdit.ts +149 -0
  20. package/src/components/labelLod.ts +2 -3
  21. package/src/components/markerShapes.ts +1 -2
  22. package/src/components/measureGeometry.ts +34 -1
  23. package/src/components/measureHit.ts +371 -0
  24. package/src/components/overlayRole.ts +1 -1
  25. package/src/components/pointIndex.ts +2 -3
  26. package/src/components/polylineIndex.ts +3 -3
  27. package/src/components/shapeEdit.ts +38 -5
  28. package/src/components/stage/CompareLayer.tsx +228 -0
  29. package/src/components/stage/ImageLayer.tsx +56 -15
  30. package/src/components/stage/ImageStage.tsx +29 -8
  31. package/src/components/stage/StageSurface.tsx +1 -4
  32. package/src/components/stage/StageToolbar.tsx +26 -8
  33. package/src/components/stage/compareStyle.ts +155 -0
  34. package/src/components/stage/gesture.ts +5 -0
  35. package/src/components/stage/hitTest.ts +19 -0
  36. package/src/components/stage/useStageHitTest.ts +11 -0
  37. package/src/components/useShapeDrag.ts +2 -4
  38. package/src/index.ts +32 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/stage2d",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "The vitavision 2D image stage: view transform, zoom/pan, layered overlays, measurement.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.11.0",
49
+ "@vitavision/ui": "^0.12.0",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -3,9 +3,9 @@
3
3
  * region annotations, defect outlines.
4
4
  *
5
5
  * Drawn as a handful of batched paths, one per (state, role, colours), each outline with its 12 % fill
6
- * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the
7
- * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
8
- * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
6
+ * in one element; the pointer is resolved by `nearestArea` through the
7
+ * stage's hit registry, never by the DOM; strokes and labels are sized in screen
8
+ * pixels. A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
9
9
  */
10
10
 
11
11
  import { useMemo, useState } from "react";
@@ -119,7 +119,7 @@ const TICK_PX = 8;
119
119
  * `stroke` / `fill` colours (`fillOpacity`, `fillRule`, `paintOrder` and `selectionFill` tune the fill).
120
120
  * Rings are wound alike before they are batched, so overlapping regions never cut a hole in
121
121
  * each other.
122
- * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and
122
+ * - **States**: default 1.5 screen px (1 for `model` and
123
123
  * `structure`), hover 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every
124
124
  * outline has a halo. A region has no ring: its outline at 2.5 px is the mark.
125
125
  * - **Labels** at the centre of a region, only where regions are at least 24 screen px apart,
@@ -1,16 +1,40 @@
1
- /** Reusable source-image contour overlay and vertex editor for ImageStage. */
1
+ /**
2
+ * Reusable source-image contour overlay and vertex editor for ImageStage.
3
+ *
4
+ * The outline itself takes no pointer events: a press on it reaches whatever is below, and
5
+ * the stage pans from it when nothing is. The editor answers the stage's hit-test instead
6
+ * (nearest segment), which is how a double-click on the outline inserts a vertex without a
7
+ * wide transparent band intercepting every press near the line.
8
+ */
2
9
 
3
10
  import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
4
11
 
12
+ import { arcLengths, deformContour, eraseArc, projectToArc, subPath } from "./contourArc";
13
+ import { DraftShape } from "./DraftShape";
14
+ import { overlayRole } from "./overlayRole";
5
15
  import { imageViewBox } from "./stage/view";
6
16
  import { useStage } from "./stage/ImageStage";
17
+ import { CLICK_SLOP } from "./stage/gesture";
18
+ import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
19
+ import { useStageDrag } from "./stage/StageSurface";
20
+ import { useStageHitLayer } from "./stage/useStageHitTest";
21
+ import { useScreenPx } from "./stage/useScreenPx";
7
22
  import type { Point } from "./measureGeometry";
8
23
  import type { Rect } from "./stage/view";
9
24
 
10
- /** An ordered, closed contour drawn in source-image pixel-center coordinates. */
25
+ /** The colour of an erase: its footprint and the stretch it would remove. */
26
+ const ERASE = "var(--defect)";
27
+
28
+ /** An ordered contour, closed or open, drawn in source-image pixel-center coordinates. */
11
29
  export interface ContourEditorProps {
12
- /** Ordered vertices; the final vertex connects back to the first. */
30
+ /** Ordered vertices; on a closed contour the final vertex connects back to the first. */
13
31
  points: Point[];
32
+ /**
33
+ * Whether the last vertex joins the first. Defaults to `true`, a closed polygon; `false`
34
+ * draws an open polyline (a centreline, an edge piece), which keeps at least two vertices
35
+ * where a closed contour keeps three.
36
+ */
37
+ closed?: boolean | undefined;
14
38
  /** Receives a complete replacement point list after each edit. */
15
39
  onChange: (points: Point[]) => void;
16
40
  /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */
@@ -28,13 +52,54 @@ export interface ContourEditorProps {
28
52
  * for polygons in the area convention, which may lie exactly on the image border.
29
53
  */
30
54
  bounds?: Rect | undefined;
55
+ /** The id hit-tests report for this contour, whose items are segment indices. Defaults to a generated one. */
56
+ layerId?: string | undefined;
57
+ /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.line`. */
58
+ priority?: number | undefined;
59
+ /**
60
+ * What a press does while `editable`:
61
+ * - `"vertex"` (the default): vertices are dragged, nudged, inserted and deleted.
62
+ * - `"brush"`: a drag pushes the contour with a soft round brush of `brushRadius`, centred
63
+ * where the press landed; `onChange` follows the drag and `onCommit` ends it.
64
+ * - `"erase"`: a drag along the contour marks a stretch of it, and the release reports what
65
+ * is left through `onErase`.
66
+ *
67
+ * In `"brush"` and `"erase"` the editor covers the image with its own press target
68
+ * (`data-tool-surface`) and shows the brush's footprint under the pointer; a press whose
69
+ * brush does not reach the contour is declined, so the stage pans.
70
+ */
71
+ mode?: "vertex" | "brush" | "erase" | undefined;
72
+ /** The brush's radius in `"brush"` and `"erase"` mode, in image pixels. Defaults to 20. */
73
+ brushRadius?: number | undefined;
74
+ /**
75
+ * Called when an erase drag is released, with the pieces of the contour that are left (each
76
+ * an open polyline, see `eraseArc`) and the erased stretch as arc lengths: from `start`
77
+ * forward to `end`, past the first vertex of a closed contour when `start > end`. The editor
78
+ * does not change `points` itself. Erasing a stretch of a closed contour leaves **one open
79
+ * piece**: to keep editing it, pass it back as `points` with `closed={false}`.
80
+ */
81
+ onErase?: ((pieces: Point[][], range: { start: number; end: number }) => void) | undefined;
82
+ }
83
+
84
+ /**
85
+ * The index of the segment closest to `point`: segment `i` runs from vertex `i` to the next.
86
+ *
87
+ * @param points - The contour's vertices.
88
+ * @param point - The point, in image coordinates.
89
+ * @param closed - Whether the last vertex joins the first, which adds the closing segment
90
+ * (index `points.length - 1`). Defaults to `true`.
91
+ * @returns The segment's index; 0 for a contour with no segment.
92
+ */
93
+ export function nearestContourSegment(points: Point[], point: Point, closed = true): number {
94
+ return nearestSegment(points, point, closed).index;
31
95
  }
32
96
 
33
- /** Return the index of the closest segment, with the last vertex joined to the first. */
34
- export function nearestContourSegment(points: Point[], point: Point): number {
97
+ /** The closest segment and its distance from `point`. */
98
+ function nearestSegment(points: Point[], point: Point, closed: boolean): { index: number; distance: number } {
35
99
  let nearest = 0;
36
100
  let distance = Infinity;
37
- for (let i = 0; i < points.length; i++) {
101
+ const segments = closed ? points.length : points.length - 1;
102
+ for (let i = 0; i < segments; i++) {
38
103
  const a = points[i];
39
104
  const b = points[(i + 1) % points.length];
40
105
  if (!a || !b) continue;
@@ -44,13 +109,55 @@ export function nearestContourSegment(points: Point[], point: Point): number {
44
109
  const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;
45
110
  if (d < distance) { distance = d; nearest = i; }
46
111
  }
47
- return nearest;
112
+ return { index: nearest, distance: Math.sqrt(distance) };
48
113
  }
49
114
 
50
- /** Edit contour vertices over an ImageStage using its shared source-image transform. */
51
- export function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)", bounds }: ContourEditorProps) {
115
+ /**
116
+ * Edit contour vertices over an ImageStage using its shared source-image transform.
117
+ *
118
+ * - **Vertices.** Each vertex is a focusable button: drag it (once the pointer has moved
119
+ * 3 screen pixels, so a jittery click edits nothing), nudge it with the arrow keys (Shift for
120
+ * a tenth of a pixel), delete it with Delete or Backspace (a closed contour keeps three
121
+ * vertices, an open one two), or insert one after it with Insert.
122
+ * - **Open or closed.** `closed` (the default) draws a polygon; `closed={false}` an open
123
+ * polyline with no segment from the last vertex back to the first.
124
+ * - **Outline.** The outline takes no presses, so a press on it reaches the layers below, or
125
+ * pans. While `editable` in `"vertex"` mode, the contour answers the stage's hit-test
126
+ * (`STAGE_HIT_PRIORITY.line` by default, segment indices as ids), and a double-click near the
127
+ * outline inserts a vertex on the nearest segment; the stage's double-click to fit does not
128
+ * run then.
129
+ * - **Brush and erase.** In `"brush"` mode a drag pushes the contour with a soft round brush
130
+ * (`deformContour`, from the contour as it was at the press, held inside `bounds`); in
131
+ * `"erase"` mode a drag along the contour previews the stretch it removes, dashed, and the
132
+ * release calls `onErase`. Both start only past the click slop. The vertex handles are
133
+ * hidden in these modes.
134
+ *
135
+ * The SVG carries `data-mode` while editable; the tool surface is `data-tool-surface`, and the
136
+ * stretch an erase would remove is `data-erase-preview`.
137
+ */
138
+ export function ContourEditor({
139
+ points,
140
+ closed = true,
141
+ onChange,
142
+ onCommit,
143
+ editable = false,
144
+ label = "Contour",
145
+ stroke = "var(--signal)",
146
+ bounds,
147
+ layerId,
148
+ priority = STAGE_HIT_PRIORITY.line,
149
+ mode = "vertex",
150
+ brushRadius = 20,
151
+ onErase,
152
+ }: ContourEditorProps) {
52
153
  const stage = useStage();
53
- const draggingRef = useRef<number | null>(null);
154
+ const px = useScreenPx();
155
+ const startDrag = useStageDrag();
156
+ // Where the brush's footprint is drawn: under a hovering mouse or pen, and during a gesture.
157
+ const [footprint, setFootprint] = useState<Point | null>(null);
158
+ // The stretch an erase drag would remove, as arc lengths.
159
+ const [erasing, setErasing] = useState<{ start: number; end: number } | null>(null);
160
+ const draggingRef = useRef<{ index: number; client: Point } | null>(null);
54
161
  const movedRef = useRef(false);
55
162
  const [selected, setSelected] = useState<number | null>(null);
56
163
  const line = points.map((point) => `${point.x},${point.y}`).join(" ");
@@ -76,19 +183,51 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
76
183
  return true;
77
184
  }
78
185
 
186
+ /** Insert `point` (clamped) after vertex `index`, and select it. */
187
+ function insert(index: number, point: Point) {
188
+ onChange([...points.slice(0, index + 1), clamp(point), ...points.slice(index + 1)]);
189
+ setSelected(index + 1);
190
+ onCommit?.();
191
+ }
192
+
193
+ /** The fewest vertices the contour keeps: a closed one is a polygon, an open one a line. */
194
+ const fewest = closed ? 3 : 2;
195
+ // The outline answers the stage's hit-test rather than owning a press target: a press on it
196
+ // goes to whatever is below, and a double-click near it inserts a vertex.
197
+ const active = editable && mode === "vertex" && points.length >= fewest;
198
+ const tool = editable && mode !== "vertex";
199
+ useStageHitLayer({
200
+ layerId,
201
+ priority,
202
+ pick: (point, hitRadius) => {
203
+ if (!active) return null;
204
+ const hit = nearestSegment(points, point, closed);
205
+ return hit.distance <= hitRadius ? { id: hit.index, dist: hit.distance } : null;
206
+ },
207
+ onDoubleClick: active
208
+ ? (id, point) => {
209
+ insert(Number(id), point);
210
+ }
211
+ : undefined,
212
+ });
213
+
79
214
  function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {
80
215
  if (!editable || stage.panMode || event.button !== 0) return;
81
216
  event.stopPropagation();
82
217
  event.currentTarget.setPointerCapture(event.pointerId);
83
- draggingRef.current = index;
218
+ draggingRef.current = { index, client: { x: event.clientX, y: event.clientY } };
84
219
  movedRef.current = false;
85
220
  setSelected(index);
86
221
  }
87
222
 
88
223
  function pointerMove(event: PointerEvent<SVGCircleElement>) {
89
- if (draggingRef.current === null) return;
224
+ const drag = draggingRef.current;
225
+ if (drag === null) return;
90
226
  event.stopPropagation();
91
- if (move(draggingRef.current, stage.toImage({ x: event.clientX, y: event.clientY }))) movedRef.current = true;
227
+ // A jittery click is not an edit: the vertex stays until the pointer leaves the click slop.
228
+ if (!movedRef.current && Math.hypot(event.clientX - drag.client.x, event.clientY - drag.client.y) <= CLICK_SLOP) return;
229
+ movedRef.current = true;
230
+ move(drag.index, stage.toImage({ x: event.clientX, y: event.clientY }));
92
231
  }
93
232
 
94
233
  function pointerUp(event: PointerEvent<SVGCircleElement>) {
@@ -111,41 +250,151 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
111
250
  event.preventDefault();
112
251
  event.stopPropagation();
113
252
  if (move(index, { x: p.x + shift[event.key]!.x, y: p.y + shift[event.key]!.y })) onCommit?.();
114
- } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > 3) {
253
+ } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > fewest) {
115
254
  event.preventDefault();
116
255
  event.stopPropagation();
117
256
  onChange(points.filter((_, i) => i !== index));
118
257
  setSelected(null);
119
258
  onCommit?.();
120
- } else if (event.key === "Insert" && points.length >= 3) {
259
+ } else if (event.key === "Insert" && points.length >= fewest) {
121
260
  event.preventDefault();
122
261
  event.stopPropagation();
123
- const next = points[(index + 1) % points.length]!;
124
- onChange([...points.slice(0, index + 1), { x: (p.x + next.x) / 2, y: (p.y + next.y) / 2 }, ...points.slice(index + 1)]);
125
- setSelected(index + 1);
126
- onCommit?.();
262
+ // Midway to the next vertex; past an open contour's last vertex there is none, so midway
263
+ // to the one before it.
264
+ const after = !closed && index === points.length - 1 ? index - 1 : index;
265
+ const a = points[after]!;
266
+ const b = points[(after + 1) % points.length]!;
267
+ insert(after, { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
268
+ }
269
+ }
270
+
271
+ /**
272
+ * A press on the tool surface: a brush push or an erase, from where it landed. Declined (the
273
+ * stage pans) when the brush does not reach the contour.
274
+ */
275
+ function toolDown(event: PointerEvent<SVGRectElement>) {
276
+ if (stage.panMode || event.button !== 0 || points.length === 0) return;
277
+ const from = stage.toImage({ x: event.clientX, y: event.clientY });
278
+ const hit = projectToArc(points, from, closed);
279
+ if (hit.distance > brushRadius) return;
280
+ const client = { x: event.clientX, y: event.clientY };
281
+ const touch = event.pointerType === "touch";
282
+ let moved = false;
283
+ /** Whether the pointer has left the click slop: before that, the press edits nothing. */
284
+ const past = (e: globalThis.PointerEvent) =>
285
+ moved || (moved = Math.hypot(e.clientX - client.x, e.clientY - client.y) > CLICK_SLOP);
286
+ setFootprint(from);
287
+ if (mode === "brush") {
288
+ const snapshot = points;
289
+ let changed = false;
290
+ startDrag(event, {
291
+ onMove: (p, e) => {
292
+ if (!touch) setFootprint(p);
293
+ if (!past(e)) return;
294
+ changed = true;
295
+ onChange(deformContour(snapshot, from, { x: p.x - from.x, y: p.y - from.y }, brushRadius, closed).map(clamp));
296
+ },
297
+ onEnd: () => {
298
+ if (touch) setFootprint(null);
299
+ if (changed) onCommit?.();
300
+ },
301
+ onCancel: () => {
302
+ setFootprint(null);
303
+ if (changed) onChange(snapshot);
304
+ },
305
+ });
306
+ return;
127
307
  }
308
+ const snapshot = points;
309
+ const start = hit.s;
310
+ let range: { start: number; end: number } | null = null;
311
+ startDrag(event, {
312
+ onMove: (p, e) => {
313
+ if (!touch) setFootprint(p);
314
+ if (!past(e)) return;
315
+ range = stretchBetween(snapshot, start, projectToArc(snapshot, p, closed).s, closed);
316
+ setErasing(range);
317
+ },
318
+ onEnd: () => {
319
+ if (touch) setFootprint(null);
320
+ setErasing(null);
321
+ if (range && range.start !== range.end) onErase?.(eraseArc(snapshot, range.start, range.end, closed), range);
322
+ },
323
+ onCancel: () => {
324
+ setFootprint(null);
325
+ setErasing(null);
326
+ },
327
+ });
128
328
  }
129
329
 
330
+ const preview = erasing ? subPath(points, erasing.start, erasing.end, closed) : null;
331
+
130
332
  return (
131
- <svg viewBox={imageViewBox(stage.image)} className="pointer-events-none absolute inset-0 h-full w-full overflow-visible" role={editable ? undefined : "img"} aria-label={label}>
132
- <polygon points={line} fill="none" stroke={stroke} strokeWidth={hairline} />
133
- {editable && points.length >= 3 && (
134
- <polygon points={line} fill="none" stroke="transparent" strokeWidth={stage.imageLength(12)} className="pointer-events-auto" onDoubleClick={(event) => {
135
- if (stage.panMode) return;
136
- event.stopPropagation();
137
- const point = clamp(stage.toImage({ x: event.clientX, y: event.clientY }));
138
- const index = nearestContourSegment(points, point);
139
- onChange([...points.slice(0, index + 1), point, ...points.slice(index + 1)]);
140
- setSelected(index + 1);
141
- onCommit?.();
142
- }} />
333
+ <>
334
+ <svg
335
+ viewBox={imageViewBox(stage.image)}
336
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
337
+ role={editable ? undefined : "img"}
338
+ aria-label={label}
339
+ data-mode={editable ? mode : undefined}
340
+ >
341
+ {tool && (
342
+ <rect
343
+ data-tool-surface=""
344
+ x={-0.5}
345
+ y={-0.5}
346
+ width={stage.image.width}
347
+ height={stage.image.height}
348
+ fill="transparent"
349
+ className="pointer-events-auto"
350
+ style={{ cursor: stage.panMode ? undefined : "crosshair" }}
351
+ onPointerDown={toolDown}
352
+ onPointerMove={(event) => {
353
+ if (event.pointerType !== "touch" && !stage.panMode) setFootprint(stage.toImage({ x: event.clientX, y: event.clientY }));
354
+ }}
355
+ onPointerLeave={() => setFootprint(null)}
356
+ onDoubleClick={(event) => {
357
+ if (!stage.panMode) event.stopPropagation();
358
+ }}
359
+ />
360
+ )}
361
+ {closed ? (
362
+ <polygon points={line} fill="none" stroke={stroke} strokeWidth={hairline} />
363
+ ) : (
364
+ <polyline points={line} fill="none" stroke={stroke} strokeWidth={hairline} strokeLinejoin="round" />
365
+ )}
366
+ {preview && (
367
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
368
+ <polyline points={toAttribute(preview)} stroke={overlayRole("halo")} strokeWidth={px(4)} />
369
+ <polyline data-erase-preview="" points={toAttribute(preview)} stroke={ERASE} strokeWidth={px(2.5)} strokeDasharray={`${px(6)} ${px(4)}`} />
370
+ </g>
371
+ )}
372
+ {editable && mode === "vertex" && points.map((point, index) => (
373
+ // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.
374
+ // eslint-disable-next-line @eslint-react/no-array-index-key
375
+ <circle key={index} cx={point.x} cy={point.y} r={selected === index ? radius * 1.3 : radius} fill="var(--surface)" stroke={stroke} strokeWidth={hairline} className="pointer-events-auto cursor-move" tabIndex={0} role="button" aria-label={`${label} point ${index + 1}`} onPointerDown={(event) => pointerDown(event, index)} onPointerMove={pointerMove} onPointerUp={pointerUp} onLostPointerCapture={pointerUp} onDoubleClick={(event) => { if (!stage.panMode) event.stopPropagation(); }} onKeyDown={(event) => keyDown(event, index)} onFocus={() => setSelected(index)} />
376
+ ))}
377
+ </svg>
378
+ {tool && footprint && (
379
+ <DraftShape shape={{ kind: "brush", x: footprint.x, y: footprint.y, diameter: 2 * brushRadius }} stroke={mode === "erase" ? ERASE : undefined} />
143
380
  )}
144
- {editable && points.map((point, index) => (
145
- // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.
146
- // eslint-disable-next-line @eslint-react/no-array-index-key
147
- <circle key={index} cx={point.x} cy={point.y} r={selected === index ? radius * 1.3 : radius} fill="var(--surface)" stroke={stroke} strokeWidth={hairline} className="pointer-events-auto cursor-move" tabIndex={0} role="button" aria-label={`${label} point ${index + 1}`} onPointerDown={(event) => pointerDown(event, index)} onPointerMove={pointerMove} onPointerUp={pointerUp} onLostPointerCapture={pointerUp} onDoubleClick={(event) => { if (!stage.panMode) event.stopPropagation(); }} onKeyDown={(event) => keyDown(event, index)} onFocus={() => setSelected(index)} />
148
- ))}
149
- </svg>
381
+ </>
150
382
  );
151
383
  }
384
+
385
+ /**
386
+ * The stretch from arc length `a` to `b` as `{ start, end }`, running forward. On a closed
387
+ * contour, the shorter way round: a drag back across the first vertex erases the few pixels
388
+ * it covered, not the rest of the contour.
389
+ */
390
+ function stretchBetween(points: readonly Point[], a: number, b: number, closed: boolean): { start: number; end: number } {
391
+ if (!closed) return { start: Math.min(a, b), end: Math.max(a, b) };
392
+ const total = arcLengths(points, true).at(-1) ?? 0;
393
+ if (!(total > 0)) return { start: a, end: b };
394
+ const forward = (((b - a) % total) + total) % total;
395
+ return forward <= total / 2 ? { start: a, end: b } : { start: b, end: a };
396
+ }
397
+
398
+ function toAttribute(points: readonly Point[]): string {
399
+ return points.map((p) => `${p.x},${p.y}`).join(" ");
400
+ }