@vitavision/stage2d 0.12.0 → 0.13.2

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 (43) 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/api/mapValues.ts +1 -4
  7. package/src/components/AreaSet.tsx +32 -9
  8. package/src/components/ContourEditor.tsx +325 -40
  9. package/src/components/DatumEditor.tsx +261 -0
  10. package/src/components/DraftShape.tsx +37 -5
  11. package/src/components/EllipseSet.tsx +3 -3
  12. package/src/components/GridLayer.tsx +8 -3
  13. package/src/components/HeatmapLayer.tsx +1 -1
  14. package/src/components/MaskEditor.tsx +57 -9
  15. package/src/components/MeasureOverlay.tsx +353 -92
  16. package/src/components/PointSet.tsx +23 -12
  17. package/src/components/PolylineSet.tsx +83 -27
  18. package/src/components/RectRoiEditor.tsx +189 -93
  19. package/src/components/ShapeEditor.tsx +25 -10
  20. package/src/components/areaBatching.ts +23 -3
  21. package/src/components/areaIndex.ts +2 -1
  22. package/src/components/contourArc.ts +268 -0
  23. package/src/components/datumEdit.ts +149 -0
  24. package/src/components/labelLod.ts +3 -7
  25. package/src/components/markerShapes.ts +2 -5
  26. package/src/components/measureGeometry.ts +46 -28
  27. package/src/components/measureHit.ts +383 -0
  28. package/src/components/overlayRole.ts +1 -1
  29. package/src/components/pointIndex.ts +14 -5
  30. package/src/components/polylineIndex.ts +3 -3
  31. package/src/components/shapeEdit.ts +38 -5
  32. package/src/components/stage/CompareLayer.tsx +231 -0
  33. package/src/components/stage/ImageLayer.tsx +56 -24
  34. package/src/components/stage/ImageStage.tsx +33 -38
  35. package/src/components/stage/StageSurface.tsx +34 -34
  36. package/src/components/stage/StageToolbar.tsx +35 -37
  37. package/src/components/stage/compareStyle.ts +155 -0
  38. package/src/components/stage/gesture.ts +5 -0
  39. package/src/components/stage/hitTest.ts +19 -0
  40. package/src/components/stage/useStageHitTest.ts +17 -12
  41. package/src/components/stage/view.ts +3 -15
  42. package/src/components/useShapeDrag.ts +2 -4
  43. package/src/index.ts +34 -65
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/stage2d",
3
- "version": "0.12.0",
3
+ "version": "0.13.2",
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.14.0",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -107,10 +107,7 @@ export function valuesAt(plane: ValuePlane, u: number, v: number): number[] {
107
107
  }
108
108
 
109
109
  /** Where a value sits in a range, as a fraction — `null` for a degenerate range. */
110
- export function fractionOf(
111
- value: number,
112
- range: { low: number; high: number } | null | undefined,
113
- ): number | null {
110
+ export function fractionOf(value: number, range: { low: number; high: number } | null | undefined): number | null {
114
111
  if (!range || range.high <= range.low) return null;
115
112
  return (value - range.low) / (range.high - range.low);
116
113
  }
@@ -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,
@@ -245,7 +245,9 @@ export function AreaSet({
245
245
  /** Each region's fill as its own even-odd path, or all of them as one path. */
246
246
  const fillPaths = (batch: AreaBatch, colour: string, tag: string) =>
247
247
  evenOdd ? (
248
- batch.fills!.map((d, k) => <path key={batch.indices[k]} data-fill={tag} d={d} fill={colour} fillOpacity={fillOpacity} fillRule="evenodd" />)
248
+ batch.fills!.map((d, k) => (
249
+ <path key={batch.indices[k]} data-fill={tag} d={d} fill={colour} fillOpacity={fillOpacity} fillRule="evenodd" />
250
+ ))
249
251
  ) : (
250
252
  <path data-fill={tag} d={batch.fills!.join("")} fill={colour} fillOpacity={fillOpacity} />
251
253
  );
@@ -261,7 +263,9 @@ export function AreaSet({
261
263
  <g fill="none" strokeLinecap="round" strokeLinejoin="round">
262
264
  {groups.normal.map((batch) => (
263
265
  <g key={batch.id} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>
264
- {halo && (!separate || batch.d !== "") && <path d={batch.d} stroke={HALO} strokeWidth={widthOf(batch.role, "default") + px(2)} opacity={0.6} />}
266
+ {halo && (!separate || batch.d !== "") && (
267
+ <path d={batch.d} stroke={HALO} strokeWidth={widthOf(batch.role, "default") + px(2)} opacity={0.6} />
268
+ )}
265
269
  {separate && fillPaths(batch, batch.fill ?? strokeOf(batch), batch.key)}
266
270
  {(!separate || batch.d !== "") && (
267
271
  <path
@@ -292,7 +296,11 @@ export function AreaSet({
292
296
  {hoverItem && (
293
297
  <>
294
298
  {halo && (
295
- <path d={areaPath(hoverItem.points)} stroke={HALO} strokeWidth={widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)} />
299
+ <path
300
+ d={areaPath(hoverItem.points)}
301
+ stroke={HALO}
302
+ strokeWidth={widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)}
303
+ />
296
304
  )}
297
305
  <path
298
306
  data-hovered-area=""
@@ -315,9 +323,24 @@ export function AreaSet({
315
323
  ))}
316
324
  </g>
317
325
  {shownLabels.length > 0 && (
318
- <g data-labels="" fontSize={px(11)} className="font-mono" stroke={HALO} strokeWidth={px(3)} paintOrder="stroke" strokeLinejoin="round">
326
+ <g
327
+ data-labels=""
328
+ fontSize={px(11)}
329
+ className="font-mono"
330
+ stroke={HALO}
331
+ strokeWidth={px(3)}
332
+ paintOrder="stroke"
333
+ strokeLinejoin="round"
334
+ >
319
335
  {shownLabels.map((i) => (
320
- <text key={items[i]!.id} x={anchors.xy[2 * i]} y={anchors.xy[2 * i + 1]} fill={LABEL} textAnchor="middle" dominantBaseline="central">
336
+ <text
337
+ key={items[i]!.id}
338
+ x={anchors.xy[2 * i]}
339
+ y={anchors.xy[2 * i + 1]}
340
+ fill={LABEL}
341
+ textAnchor="middle"
342
+ dominantBaseline="central"
343
+ >
321
344
  {items[i]!.label}
322
345
  </text>
323
346
  ))}
@@ -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;
31
82
  }
32
83
 
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 {
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;
95
+ }
96
+
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;
@@ -42,15 +107,60 @@ export function nearestContourSegment(points: Point[], point: Point): number {
42
107
  const dy = b.y - a.y;
43
108
  const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)));
44
109
  const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;
45
- if (d < distance) { distance = d; nearest = i; }
110
+ if (d < distance) {
111
+ distance = d;
112
+ nearest = i;
113
+ }
46
114
  }
47
- return nearest;
115
+ return { index: nearest, distance: Math.sqrt(distance) };
48
116
  }
49
117
 
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) {
118
+ /**
119
+ * Edit contour vertices over an ImageStage using its shared source-image transform.
120
+ *
121
+ * - **Vertices.** Each vertex is a focusable button: drag it (once the pointer has moved
122
+ * 3 screen pixels, so a jittery click edits nothing), nudge it with the arrow keys (Shift for
123
+ * a tenth of a pixel), delete it with Delete or Backspace (a closed contour keeps three
124
+ * vertices, an open one two), or insert one after it with Insert.
125
+ * - **Open or closed.** `closed` (the default) draws a polygon; `closed={false}` an open
126
+ * polyline with no segment from the last vertex back to the first.
127
+ * - **Outline.** The outline takes no presses, so a press on it reaches the layers below, or
128
+ * pans. While `editable` in `"vertex"` mode, the contour answers the stage's hit-test
129
+ * (`STAGE_HIT_PRIORITY.line` by default, segment indices as ids), and a double-click near the
130
+ * outline inserts a vertex on the nearest segment; the stage's double-click to fit does not
131
+ * run then.
132
+ * - **Brush and erase.** In `"brush"` mode a drag pushes the contour with a soft round brush
133
+ * (`deformContour`, from the contour as it was at the press, held inside `bounds`); in
134
+ * `"erase"` mode a drag along the contour previews the stretch it removes, dashed, and the
135
+ * release calls `onErase`. Both start only past the click slop. The vertex handles are
136
+ * hidden in these modes.
137
+ *
138
+ * The SVG carries `data-mode` while editable; the tool surface is `data-tool-surface`, and the
139
+ * stretch an erase would remove is `data-erase-preview`.
140
+ */
141
+ export function ContourEditor({
142
+ points,
143
+ closed = true,
144
+ onChange,
145
+ onCommit,
146
+ editable = false,
147
+ label = "Contour",
148
+ stroke = "var(--signal)",
149
+ bounds,
150
+ layerId,
151
+ priority = STAGE_HIT_PRIORITY.line,
152
+ mode = "vertex",
153
+ brushRadius = 20,
154
+ onErase,
155
+ }: ContourEditorProps) {
52
156
  const stage = useStage();
53
- const draggingRef = useRef<number | null>(null);
157
+ const px = useScreenPx();
158
+ const startDrag = useStageDrag();
159
+ // Where the brush's footprint is drawn: under a hovering mouse or pen, and during a gesture.
160
+ const [footprint, setFootprint] = useState<Point | null>(null);
161
+ // The stretch an erase drag would remove, as arc lengths.
162
+ const [erasing, setErasing] = useState<{ start: number; end: number } | null>(null);
163
+ const draggingRef = useRef<{ index: number; client: Point } | null>(null);
54
164
  const movedRef = useRef(false);
55
165
  const [selected, setSelected] = useState<number | null>(null);
56
166
  const line = points.map((point) => `${point.x},${point.y}`).join(" ");
@@ -76,19 +186,51 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
76
186
  return true;
77
187
  }
78
188
 
189
+ /** Insert `point` (clamped) after vertex `index`, and select it. */
190
+ function insert(index: number, point: Point) {
191
+ onChange([...points.slice(0, index + 1), clamp(point), ...points.slice(index + 1)]);
192
+ setSelected(index + 1);
193
+ onCommit?.();
194
+ }
195
+
196
+ /** The fewest vertices the contour keeps: a closed one is a polygon, an open one a line. */
197
+ const fewest = closed ? 3 : 2;
198
+ // The outline answers the stage's hit-test rather than owning a press target: a press on it
199
+ // goes to whatever is below, and a double-click near it inserts a vertex.
200
+ const active = editable && mode === "vertex" && points.length >= fewest;
201
+ const tool = editable && mode !== "vertex";
202
+ useStageHitLayer({
203
+ layerId,
204
+ priority,
205
+ pick: (point, hitRadius) => {
206
+ if (!active) return null;
207
+ const hit = nearestSegment(points, point, closed);
208
+ return hit.distance <= hitRadius ? { id: hit.index, dist: hit.distance } : null;
209
+ },
210
+ onDoubleClick: active
211
+ ? (id, point) => {
212
+ insert(Number(id), point);
213
+ }
214
+ : undefined,
215
+ });
216
+
79
217
  function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {
80
218
  if (!editable || stage.panMode || event.button !== 0) return;
81
219
  event.stopPropagation();
82
220
  event.currentTarget.setPointerCapture(event.pointerId);
83
- draggingRef.current = index;
221
+ draggingRef.current = { index, client: { x: event.clientX, y: event.clientY } };
84
222
  movedRef.current = false;
85
223
  setSelected(index);
86
224
  }
87
225
 
88
226
  function pointerMove(event: PointerEvent<SVGCircleElement>) {
89
- if (draggingRef.current === null) return;
227
+ const drag = draggingRef.current;
228
+ if (drag === null) return;
90
229
  event.stopPropagation();
91
- if (move(draggingRef.current, stage.toImage({ x: event.clientX, y: event.clientY }))) movedRef.current = true;
230
+ // A jittery click is not an edit: the vertex stays until the pointer leaves the click slop.
231
+ if (!movedRef.current && Math.hypot(event.clientX - drag.client.x, event.clientY - drag.client.y) <= CLICK_SLOP) return;
232
+ movedRef.current = true;
233
+ move(drag.index, stage.toImage({ x: event.clientX, y: event.clientY }));
92
234
  }
93
235
 
94
236
  function pointerUp(event: PointerEvent<SVGCircleElement>) {
@@ -104,48 +246,191 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
104
246
  const p = points[index];
105
247
  if (!p) return;
106
248
  const shift: Record<string, Point> = {
107
- ArrowLeft: { x: -delta, y: 0 }, ArrowRight: { x: delta, y: 0 },
108
- ArrowUp: { x: 0, y: -delta }, ArrowDown: { x: 0, y: delta },
249
+ ArrowLeft: { x: -delta, y: 0 },
250
+ ArrowRight: { x: delta, y: 0 },
251
+ ArrowUp: { x: 0, y: -delta },
252
+ ArrowDown: { x: 0, y: delta },
109
253
  };
110
254
  if (shift[event.key]) {
111
255
  event.preventDefault();
112
256
  event.stopPropagation();
113
257
  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) {
258
+ } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > fewest) {
115
259
  event.preventDefault();
116
260
  event.stopPropagation();
117
261
  onChange(points.filter((_, i) => i !== index));
118
262
  setSelected(null);
119
263
  onCommit?.();
120
- } else if (event.key === "Insert" && points.length >= 3) {
264
+ } else if (event.key === "Insert" && points.length >= fewest) {
121
265
  event.preventDefault();
122
266
  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?.();
267
+ // Midway to the next vertex; past an open contour's last vertex there is none, so midway
268
+ // to the one before it.
269
+ const after = !closed && index === points.length - 1 ? index - 1 : index;
270
+ const a = points[after]!;
271
+ const b = points[(after + 1) % points.length]!;
272
+ insert(after, { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
273
+ }
274
+ }
275
+
276
+ /**
277
+ * A press on the tool surface: a brush push or an erase, from where it landed. Declined (the
278
+ * stage pans) when the brush does not reach the contour.
279
+ */
280
+ function toolDown(event: PointerEvent<SVGRectElement>) {
281
+ if (stage.panMode || event.button !== 0 || points.length === 0) return;
282
+ const from = stage.toImage({ x: event.clientX, y: event.clientY });
283
+ const hit = projectToArc(points, from, closed);
284
+ if (hit.distance > brushRadius) return;
285
+ const client = { x: event.clientX, y: event.clientY };
286
+ const touch = event.pointerType === "touch";
287
+ let moved = false;
288
+ /** Whether the pointer has left the click slop: before that, the press edits nothing. */
289
+ const past = (e: globalThis.PointerEvent) => moved || (moved = Math.hypot(e.clientX - client.x, e.clientY - client.y) > CLICK_SLOP);
290
+ setFootprint(from);
291
+ if (mode === "brush") {
292
+ const snapshot = points;
293
+ let changed = false;
294
+ startDrag(event, {
295
+ onMove: (p, e) => {
296
+ if (!touch) setFootprint(p);
297
+ if (!past(e)) return;
298
+ changed = true;
299
+ onChange(deformContour(snapshot, from, { x: p.x - from.x, y: p.y - from.y }, brushRadius, closed).map(clamp));
300
+ },
301
+ onEnd: () => {
302
+ if (touch) setFootprint(null);
303
+ if (changed) onCommit?.();
304
+ },
305
+ onCancel: () => {
306
+ setFootprint(null);
307
+ if (changed) onChange(snapshot);
308
+ },
309
+ });
310
+ return;
127
311
  }
312
+ const snapshot = points;
313
+ const start = hit.s;
314
+ let range: { start: number; end: number } | null = null;
315
+ startDrag(event, {
316
+ onMove: (p, e) => {
317
+ if (!touch) setFootprint(p);
318
+ if (!past(e)) return;
319
+ range = stretchBetween(snapshot, start, projectToArc(snapshot, p, closed).s, closed);
320
+ setErasing(range);
321
+ },
322
+ onEnd: () => {
323
+ if (touch) setFootprint(null);
324
+ setErasing(null);
325
+ if (range && range.start !== range.end) onErase?.(eraseArc(snapshot, range.start, range.end, closed), range);
326
+ },
327
+ onCancel: () => {
328
+ setFootprint(null);
329
+ setErasing(null);
330
+ },
331
+ });
128
332
  }
129
333
 
334
+ const preview = erasing ? subPath(points, erasing.start, erasing.end, closed) : null;
335
+
130
336
  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
- }} />
337
+ <>
338
+ <svg
339
+ viewBox={imageViewBox(stage.image)}
340
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
341
+ role={editable ? undefined : "img"}
342
+ aria-label={label}
343
+ data-mode={editable ? mode : undefined}
344
+ >
345
+ {tool && (
346
+ <rect
347
+ data-tool-surface=""
348
+ x={-0.5}
349
+ y={-0.5}
350
+ width={stage.image.width}
351
+ height={stage.image.height}
352
+ fill="transparent"
353
+ className="pointer-events-auto"
354
+ style={{ cursor: stage.panMode ? undefined : "crosshair" }}
355
+ onPointerDown={toolDown}
356
+ onPointerMove={(event) => {
357
+ if (event.pointerType !== "touch" && !stage.panMode) setFootprint(stage.toImage({ x: event.clientX, y: event.clientY }));
358
+ }}
359
+ onPointerLeave={() => setFootprint(null)}
360
+ onDoubleClick={(event) => {
361
+ if (!stage.panMode) event.stopPropagation();
362
+ }}
363
+ />
364
+ )}
365
+ {closed ? (
366
+ <polygon points={line} fill="none" stroke={stroke} strokeWidth={hairline} />
367
+ ) : (
368
+ <polyline points={line} fill="none" stroke={stroke} strokeWidth={hairline} strokeLinejoin="round" />
369
+ )}
370
+ {preview && (
371
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
372
+ <polyline points={toAttribute(preview)} stroke={overlayRole("halo")} strokeWidth={px(4)} />
373
+ <polyline
374
+ data-erase-preview=""
375
+ points={toAttribute(preview)}
376
+ stroke={ERASE}
377
+ strokeWidth={px(2.5)}
378
+ strokeDasharray={`${px(6)} ${px(4)}`}
379
+ />
380
+ </g>
381
+ )}
382
+ {editable &&
383
+ mode === "vertex" &&
384
+ points.map((point, index) => (
385
+ // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.
386
+ <circle
387
+ // oxlint-disable-next-line react/no-array-index-key
388
+ key={index}
389
+ cx={point.x}
390
+ cy={point.y}
391
+ r={selected === index ? radius * 1.3 : radius}
392
+ fill="var(--surface)"
393
+ stroke={stroke}
394
+ strokeWidth={hairline}
395
+ className="pointer-events-auto cursor-move"
396
+ tabIndex={0}
397
+ role="button"
398
+ aria-label={`${label} point ${index + 1}`}
399
+ onPointerDown={(event) => pointerDown(event, index)}
400
+ onPointerMove={pointerMove}
401
+ onPointerUp={pointerUp}
402
+ onLostPointerCapture={pointerUp}
403
+ onDoubleClick={(event) => {
404
+ if (!stage.panMode) event.stopPropagation();
405
+ }}
406
+ onKeyDown={(event) => keyDown(event, index)}
407
+ onFocus={() => setSelected(index)}
408
+ />
409
+ ))}
410
+ </svg>
411
+ {tool && footprint && (
412
+ <DraftShape
413
+ shape={{ kind: "brush", x: footprint.x, y: footprint.y, diameter: 2 * brushRadius }}
414
+ stroke={mode === "erase" ? ERASE : undefined}
415
+ />
143
416
  )}
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>
417
+ </>
150
418
  );
151
419
  }
420
+
421
+ /**
422
+ * The stretch from arc length `a` to `b` as `{ start, end }`, running forward. On a closed
423
+ * contour, the shorter way round: a drag back across the first vertex erases the few pixels
424
+ * it covered, not the rest of the contour.
425
+ */
426
+ function stretchBetween(points: readonly Point[], a: number, b: number, closed: boolean): { start: number; end: number } {
427
+ if (!closed) return { start: Math.min(a, b), end: Math.max(a, b) };
428
+ const total = arcLengths(points, true).at(-1) ?? 0;
429
+ if (!(total > 0)) return { start: a, end: b };
430
+ const forward = (((b - a) % total) + total) % total;
431
+ return forward <= total / 2 ? { start: a, end: b } : { start: b, end: a };
432
+ }
433
+
434
+ function toAttribute(points: readonly Point[]): string {
435
+ return points.map((p) => `${p.x},${p.y}`).join(" ");
436
+ }