@vitavision/stage2d 0.11.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 (41) hide show
  1. package/README.md +3 -6
  2. package/dist/index.d.ts +806 -74
  3. package/dist/index.js +6669 -4568
  4. package/dist/index.js.map +1 -1
  5. package/package.json +2 -2
  6. package/src/components/AreaSet.tsx +87 -56
  7. package/src/components/ContourEditor.tsx +297 -39
  8. package/src/components/DatumEditor.tsx +261 -0
  9. package/src/components/DraftShape.tsx +56 -11
  10. package/src/components/EllipseSet.tsx +3 -3
  11. package/src/components/GridLayer.tsx +1 -2
  12. package/src/components/HeatmapLayer.tsx +1 -1
  13. package/src/components/MaskEditor.tsx +22 -9
  14. package/src/components/MeasureOverlay.tsx +320 -89
  15. package/src/components/PointSet.tsx +18 -10
  16. package/src/components/PolylineSet.tsx +81 -17
  17. package/src/components/RectRoiEditor.tsx +193 -88
  18. package/src/components/ShapeEditor.tsx +14 -4
  19. package/src/components/areaBatching.ts +111 -0
  20. package/src/components/contourArc.ts +268 -0
  21. package/src/components/datumEdit.ts +149 -0
  22. package/src/components/labelLod.ts +2 -3
  23. package/src/components/markerShapes.ts +1 -2
  24. package/src/components/measureGeometry.ts +34 -1
  25. package/src/components/measureHit.ts +371 -0
  26. package/src/components/overlayRole.ts +1 -1
  27. package/src/components/pointIndex.ts +2 -3
  28. package/src/components/polylineIndex.ts +3 -3
  29. package/src/components/shapeEdit.ts +38 -5
  30. package/src/components/stage/CompareLayer.tsx +228 -0
  31. package/src/components/stage/ImageLayer.tsx +56 -15
  32. package/src/components/stage/ImageStage.tsx +231 -128
  33. package/src/components/stage/StageSurface.tsx +44 -18
  34. package/src/components/stage/StageToolbar.tsx +26 -8
  35. package/src/components/stage/compareStyle.ts +155 -0
  36. package/src/components/stage/gesture.ts +5 -0
  37. package/src/components/stage/hitTest.ts +19 -0
  38. package/src/components/stage/useStageHitTest.ts +11 -0
  39. package/src/components/stage/view.ts +33 -6
  40. package/src/components/useShapeDrag.ts +2 -4
  41. package/src/index.ts +34 -2
@@ -1,15 +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";
23
+ import type { Rect } from "./stage/view";
8
24
 
9
- /** 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. */
10
29
  export interface ContourEditorProps {
11
- /** 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. */
12
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;
13
38
  /** Receives a complete replacement point list after each edit. */
14
39
  onChange: (points: Point[]) => void;
15
40
  /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */
@@ -20,13 +45,61 @@ export interface ContourEditorProps {
20
45
  label?: string;
21
46
  /** CSS stroke color. */
22
47
  stroke?: string;
48
+ /**
49
+ * The area, in image coordinates, every vertex is kept inside: a drag, a keyboard nudge and
50
+ * an inserted vertex are clamped to it. Defaults to the pixel centres,
51
+ * `{ x: 0, y: 0, width: w - 1, height: h - 1 }`. Pass `{ x: -0.5, y: -0.5, width: w, height: h }`
52
+ * for polygons in the area convention, which may lie exactly on the image border.
53
+ */
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;
23
95
  }
24
96
 
25
- /** Return the index of the closest segment, with the last vertex joined to the first. */
26
- 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 } {
27
99
  let nearest = 0;
28
100
  let distance = Infinity;
29
- 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++) {
30
103
  const a = points[i];
31
104
  const b = points[(i + 1) % points.length];
32
105
  if (!a || !b) continue;
@@ -36,13 +109,55 @@ export function nearestContourSegment(points: Point[], point: Point): number {
36
109
  const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;
37
110
  if (d < distance) { distance = d; nearest = i; }
38
111
  }
39
- return nearest;
112
+ return { index: nearest, distance: Math.sqrt(distance) };
40
113
  }
41
114
 
42
- /** Edit contour vertices over an ImageStage using its shared source-image transform. */
43
- export function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)" }: 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) {
44
153
  const stage = useStage();
45
- 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);
46
161
  const movedRef = useRef(false);
47
162
  const [selected, setSelected] = useState<number | null>(null);
48
163
  const line = points.map((point) => `${point.x},${point.y}`).join(" ");
@@ -50,9 +165,10 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
50
165
  const hairline = stage.imageLength(1.5);
51
166
 
52
167
  function clamp(point: Point): Point {
168
+ const area = bounds ?? { x: 0, y: 0, width: stage.image.width - 1, height: stage.image.height - 1 };
53
169
  return {
54
- x: Math.max(0, Math.min(stage.image.width - 1, point.x)),
55
- y: Math.max(0, Math.min(stage.image.height - 1, point.y)),
170
+ x: Math.max(area.x, Math.min(area.x + area.width, point.x)),
171
+ y: Math.max(area.y, Math.min(area.y + area.height, point.y)),
56
172
  };
57
173
  }
58
174
 
@@ -67,19 +183,51 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
67
183
  return true;
68
184
  }
69
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
+
70
214
  function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {
71
215
  if (!editable || stage.panMode || event.button !== 0) return;
72
216
  event.stopPropagation();
73
217
  event.currentTarget.setPointerCapture(event.pointerId);
74
- draggingRef.current = index;
218
+ draggingRef.current = { index, client: { x: event.clientX, y: event.clientY } };
75
219
  movedRef.current = false;
76
220
  setSelected(index);
77
221
  }
78
222
 
79
223
  function pointerMove(event: PointerEvent<SVGCircleElement>) {
80
- if (draggingRef.current === null) return;
224
+ const drag = draggingRef.current;
225
+ if (drag === null) return;
81
226
  event.stopPropagation();
82
- 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 }));
83
231
  }
84
232
 
85
233
  function pointerUp(event: PointerEvent<SVGCircleElement>) {
@@ -102,41 +250,151 @@ export function ContourEditor({ points, onChange, onCommit, editable = false, la
102
250
  event.preventDefault();
103
251
  event.stopPropagation();
104
252
  if (move(index, { x: p.x + shift[event.key]!.x, y: p.y + shift[event.key]!.y })) onCommit?.();
105
- } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > 3) {
253
+ } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > fewest) {
106
254
  event.preventDefault();
107
255
  event.stopPropagation();
108
256
  onChange(points.filter((_, i) => i !== index));
109
257
  setSelected(null);
110
258
  onCommit?.();
111
- } else if (event.key === "Insert" && points.length >= 3) {
259
+ } else if (event.key === "Insert" && points.length >= fewest) {
112
260
  event.preventDefault();
113
261
  event.stopPropagation();
114
- const next = points[(index + 1) % points.length]!;
115
- onChange([...points.slice(0, index + 1), { x: (p.x + next.x) / 2, y: (p.y + next.y) / 2 }, ...points.slice(index + 1)]);
116
- setSelected(index + 1);
117
- 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 });
118
268
  }
119
269
  }
120
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;
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
+ });
328
+ }
329
+
330
+ const preview = erasing ? subPath(points, erasing.start, erasing.end, closed) : null;
331
+
121
332
  return (
122
- <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}>
123
- <polygon points={line} fill="none" stroke={stroke} strokeWidth={hairline} />
124
- {editable && points.length >= 3 && (
125
- <polygon points={line} fill="none" stroke="transparent" strokeWidth={stage.imageLength(12)} className="pointer-events-auto" onDoubleClick={(event) => {
126
- if (stage.panMode) return;
127
- event.stopPropagation();
128
- const point = clamp(stage.toImage({ x: event.clientX, y: event.clientY }));
129
- const index = nearestContourSegment(points, point);
130
- onChange([...points.slice(0, index + 1), point, ...points.slice(index + 1)]);
131
- setSelected(index + 1);
132
- onCommit?.();
133
- }} />
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} />
134
380
  )}
135
- {editable && points.map((point, index) => (
136
- // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.
137
- // eslint-disable-next-line @eslint-react/no-array-index-key
138
- <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)} />
139
- ))}
140
- </svg>
381
+ </>
141
382
  );
142
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
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * A datum on the image: an origin and the direction of its i axis, moved and turned like an
3
+ * object. The frame a model, a target or a measurement is expressed in.
4
+ *
5
+ * The arithmetic is `datumEdit.ts`; this is the glyph, the gestures and the keyboard.
6
+ */
7
+
8
+ import { useState, type KeyboardEvent, type PointerEvent } from "react";
9
+
10
+ import { cn } from "@vitavision/ui";
11
+ import { DATUM_ARM_PX, DATUM_HANDLE_PX, DATUM_RING_PX, datumAxes, datumPress, moveDatum, rotateDatum, type Datum } from "./datumEdit";
12
+ import { arrowHeadPoints, rotatePoint, type Point } from "./measureGeometry";
13
+ import { overlayRole } from "./overlayRole";
14
+ import { normalizeAngle } from "./shapeEdit";
15
+ import { POINTER_RADIUS_PX, TOUCH_RADIUS_PX, hitRadiusPx } from "./stage/gesture";
16
+ import { useStage } from "./stage/ImageStage";
17
+ import { useStageDrag } from "./stage/StageSurface";
18
+ import { useCoarsePointer } from "./stage/useCoarsePointer";
19
+ import { useScreenPx } from "./stage/useScreenPx";
20
+ import { PIXEL_CENTRE, imageViewBox, type Rect } from "./stage/view";
21
+
22
+ /** Props of `DatumEditor`. */
23
+ export interface DatumEditorProps {
24
+ /** The datum, when the app controls it. `angle` is in radians, clockwise on screen from `+x`. */
25
+ value?: Datum | undefined;
26
+ /** The starting datum when the editor controls it. Defaults to the image's centre, pointing along `+x`. */
27
+ defaultValue?: Datum | undefined;
28
+ /** Called with the datum as it changes: on every move of a drag, and on each key press. */
29
+ onValueChange?: ((value: Datum) => void) | undefined;
30
+ /** Called once a gesture ends (a drag released, a key pressed): the moment to save or re-run. */
31
+ onCommit?: ((value: Datum) => void) | undefined;
32
+ /** Accept moves and turns, by pointer and keyboard. Defaults to `true`. */
33
+ editable?: boolean | undefined;
34
+ /** Show the rotation handle and accept `[` / `]`. Defaults to `true`; off for a datum that must keep its angle. */
35
+ rotatable?: boolean | undefined;
36
+ /** The step a turn rounds to, in radians: while Shift is held, or always with `snapAlways`. Defaults to π/12 (15°); 0 never rounds. */
37
+ angleSnap?: number | undefined;
38
+ /** Round every turn to `angleSnap`, not only while Shift is held. Defaults to `false`. */
39
+ snapAlways?: boolean | undefined;
40
+ /** Round the origin to a grid of this many image pixels as it moves. Defaults to 0: no grid. */
41
+ originSnap?: number | undefined;
42
+ /** The rectangle the origin stays inside, in image coordinates. Defaults to the image. */
43
+ bounds?: Rect | undefined;
44
+ /** The i axis's length in screen pixels; the j axis is half of it. Defaults to 40. */
45
+ armLength?: number | undefined;
46
+ /** The datum's accessible name. Defaults to "Datum". */
47
+ label?: string | undefined;
48
+ /** CSS colour of the glyph. Defaults to the overlay `model` role. */
49
+ stroke?: string | undefined;
50
+ /** Merged onto the `<svg>` with `cn`. */
51
+ className?: string | undefined;
52
+ }
53
+
54
+ const HALO = overlayRole("halo");
55
+ /** How far a press may travel and still be a click, in screen pixels: the stage's own slop. */
56
+ const CLICK_SLOP = 3;
57
+ /** `[` / `]` turn by 1°, 15° with Shift. */
58
+ const KEY_TURN = Math.PI / 180;
59
+ const KEY_TURN_SHIFT = Math.PI / 12;
60
+
61
+ /**
62
+ * An editable datum inside an `ImageStage`: a ring at the origin with its i axis (an arm ending
63
+ * in a rotation handle) and its j axis (half as long, a quarter turn clockwise from i).
64
+ *
65
+ * - **Pointer.** Drag the ring to move the origin; drag the arm or its handle to turn the datum
66
+ * about the origin. A press grabs whichever is nearer, and nothing happens until the pointer
67
+ * has moved 3 px, so a click does not nudge it. Hold Shift to round the angle to `angleSnap`
68
+ * (15°), or set `snapAlways`. `originSnap` rounds the origin to a grid; `bounds` keeps it in.
69
+ * - **Keyboard.** The origin is a focusable button: arrow keys move it one image pixel (ten with
70
+ * Shift; one grid step with `originSnap`), and `[` / `]` turn it by 1° (15° with Shift).
71
+ * - **Rendering.** Every part is a constant size on screen at every zoom, over a halo.
72
+ * - **Panning.** A press away from the glyph, or with the hand tool or space held, still pans.
73
+ *
74
+ * The SVG carries `data-editable`, and `data-dragging` (`origin` or `arm`) during a drag.
75
+ */
76
+ export function DatumEditor({
77
+ value,
78
+ defaultValue,
79
+ onValueChange,
80
+ onCommit,
81
+ editable = true,
82
+ rotatable = true,
83
+ angleSnap = Math.PI / 12,
84
+ snapAlways = false,
85
+ originSnap = 0,
86
+ bounds,
87
+ armLength = DATUM_ARM_PX,
88
+ label = "Datum",
89
+ stroke = overlayRole("model"),
90
+ className,
91
+ }: DatumEditorProps) {
92
+ const stage = useStage();
93
+ const px = useScreenPx();
94
+ const coarse = useCoarsePointer();
95
+ const startDrag = useStageDrag();
96
+ const [own, setOwn] = useState<Datum>(
97
+ () => defaultValue ?? { origin: { x: (stage.image.width - 1) / 2, y: (stage.image.height - 1) / 2 }, angle: 0 },
98
+ );
99
+ const [dragging, setDragging] = useState<"origin" | "arm" | null>(null);
100
+ const datum = value ?? own;
101
+ const area = bounds ?? { x: -PIXEL_CENTRE, y: -PIXEL_CENTRE, width: stage.image.width, height: stage.image.height };
102
+
103
+ const set = (next: Datum) => {
104
+ setOwn(next);
105
+ onValueChange?.(next);
106
+ };
107
+
108
+ const press = (event: PointerEvent<SVGElement>) => {
109
+ if (!editable || stage.panMode) return;
110
+ if (event.pointerType !== "touch" && event.button !== 0) return;
111
+ const at = stage.toImage({ x: event.clientX, y: event.clientY });
112
+ const grab = datumPress(datum, at, stage.view.scale, hitRadiusPx(event.pointerType), { armLength, rotatable });
113
+ if (grab === null) return;
114
+ const start = datum;
115
+ const from = { x: event.clientX, y: event.clientY };
116
+ // Turning follows the pointer's direction from the origin, less where on the arm it grabbed,
117
+ // so the datum does not jump to the pointer when the arm is grabbed a little off its line.
118
+ const offset = Math.atan2(at.y - start.origin.y, at.x - start.origin.x) - start.angle;
119
+ let moved = false;
120
+ let last: Datum | null = null;
121
+ setDragging(grab);
122
+ startDrag(event, {
123
+ claimsTouch: true,
124
+ onMove: (p, e) => {
125
+ if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= CLICK_SLOP) return;
126
+ moved = true;
127
+ if (grab === "origin") {
128
+ last = moveDatum(start, { x: start.origin.x + p.x - at.x, y: start.origin.y + p.y - at.y }, { grid: originSnap, bounds: area });
129
+ } else {
130
+ const turned = rotatePoint(p.x - start.origin.x, p.y - start.origin.y, -offset);
131
+ const to = { x: start.origin.x + turned.x, y: start.origin.y + turned.y };
132
+ last = rotateDatum(start, to, snapAlways || e.shiftKey ? angleSnap : 0);
133
+ }
134
+ set(last);
135
+ },
136
+ onEnd: () => {
137
+ setDragging(null);
138
+ if (moved && last) onCommit?.(last);
139
+ },
140
+ onCancel: () => {
141
+ setDragging(null);
142
+ if (last) set(start);
143
+ },
144
+ });
145
+ };
146
+
147
+ const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
148
+ if (!editable) return;
149
+ let next: Datum | null = null;
150
+ if (rotatable && (event.key === "[" || event.key === "]")) {
151
+ const turn = (event.key === "]" ? 1 : -1) * (event.shiftKey ? KEY_TURN_SHIFT : KEY_TURN);
152
+ next = { origin: datum.origin, angle: normalizeAngle(datum.angle + turn) };
153
+ } else {
154
+ const step = (originSnap > 0 ? originSnap : 1) * (event.shiftKey ? 10 : 1);
155
+ const delta: Record<string, Point> = {
156
+ ArrowLeft: { x: -step, y: 0 },
157
+ ArrowRight: { x: step, y: 0 },
158
+ ArrowUp: { x: 0, y: -step },
159
+ ArrowDown: { x: 0, y: step },
160
+ };
161
+ const d = delta[event.key];
162
+ if (d) next = moveDatum(datum, { x: datum.origin.x + d.x, y: datum.origin.y + d.y }, { grid: originSnap, bounds: area });
163
+ }
164
+ if (next === null) return;
165
+ event.preventDefault();
166
+ event.stopPropagation();
167
+ set(next);
168
+ onCommit?.(next);
169
+ };
170
+
171
+ const ring = px(DATUM_RING_PX);
172
+ const axes = datumAxes(datum, px(armLength));
173
+ const c = Math.cos(datum.angle);
174
+ const s = Math.sin(datum.angle);
175
+ // The axes start at the ring, so the origin itself stays visible.
176
+ const iFrom = { x: datum.origin.x + ring * c, y: datum.origin.y + ring * s };
177
+ const jFrom = { x: datum.origin.x - ring * s, y: datum.origin.y + ring * c };
178
+ const handle = editable && rotatable;
179
+ const head = arrowHeadPoints(axes.i, datum.angle, px(4));
180
+ const headPoints = head.map((p) => `${p.x},${p.y}`).join(" ");
181
+ const degrees = (datum.angle * 180) / Math.PI;
182
+ const band = px(2 * (coarse ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX));
183
+
184
+ return (
185
+ <svg
186
+ viewBox={imageViewBox(stage.image)}
187
+ className={cn("pointer-events-none absolute inset-0 h-full w-full overflow-visible", className)}
188
+ data-editable={editable ? "" : undefined}
189
+ data-dragging={dragging ?? undefined}
190
+ >
191
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round" data-datum="">
192
+ <g stroke={HALO}>
193
+ <circle cx={datum.origin.x} cy={datum.origin.y} r={ring} strokeWidth={px(1.5 + 2)} />
194
+ <line x1={iFrom.x} y1={iFrom.y} x2={axes.i.x} y2={axes.i.y} strokeWidth={px(1.5 + 2)} />
195
+ <line x1={jFrom.x} y1={jFrom.y} x2={axes.j.x} y2={axes.j.y} strokeWidth={px(1 + 2)} />
196
+ {!handle && <polyline points={headPoints} strokeWidth={px(1.5 + 2)} />}
197
+ <circle cx={datum.origin.x} cy={datum.origin.y} r={px(1.5 + 1)} fill={HALO} stroke="none" />
198
+ </g>
199
+ <g stroke={stroke}>
200
+ <circle data-datum-ring="" cx={datum.origin.x} cy={datum.origin.y} r={ring} strokeWidth={px(1.5)} />
201
+ <line data-axis="i" x1={iFrom.x} y1={iFrom.y} x2={axes.i.x} y2={axes.i.y} strokeWidth={px(1.5)} />
202
+ <line data-axis="j" x1={jFrom.x} y1={jFrom.y} x2={axes.j.x} y2={axes.j.y} strokeWidth={px(1)} />
203
+ {!handle && <polyline points={headPoints} strokeWidth={px(1.5)} />}
204
+ <circle cx={datum.origin.x} cy={datum.origin.y} r={px(1.5)} fill={stroke} stroke="none" />
205
+ </g>
206
+ </g>
207
+ {editable && rotatable && (
208
+ // The arm's band: a wide transparent stroke, so a press a few pixels off the arm still turns it.
209
+ <line
210
+ data-datum-arm=""
211
+ x1={iFrom.x}
212
+ y1={iFrom.y}
213
+ x2={axes.i.x}
214
+ y2={axes.i.y}
215
+ stroke="transparent"
216
+ strokeWidth={band}
217
+ aria-hidden
218
+ className="pointer-events-auto"
219
+ style={{ pointerEvents: "stroke", cursor: "grab" }}
220
+ onPointerDown={press}
221
+ />
222
+ )}
223
+ {handle && (
224
+ <circle
225
+ data-handle="rotate"
226
+ cx={axes.i.x}
227
+ cy={axes.i.y}
228
+ r={px(DATUM_HANDLE_PX)}
229
+ fill={stroke}
230
+ stroke={HALO}
231
+ strokeWidth={px(1)}
232
+ className="pointer-events-auto"
233
+ style={{ cursor: "grab" }}
234
+ onPointerDown={press}
235
+ />
236
+ )}
237
+ {editable && (
238
+ <circle
239
+ cx={datum.origin.x}
240
+ cy={datum.origin.y}
241
+ r={ring + band / 2}
242
+ fill="transparent"
243
+ role="button"
244
+ tabIndex={0}
245
+ aria-label={`${label}: origin ${fmt(datum.origin.x)}, ${fmt(datum.origin.y)}, angle ${fmt(degrees)}°`}
246
+ aria-roledescription="datum"
247
+ className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
248
+ strokeWidth={px(2)}
249
+ onPointerDown={press}
250
+ onKeyDown={onKeyDown}
251
+ />
252
+ )}
253
+ </svg>
254
+ );
255
+ }
256
+
257
+ /** A number for the accessible name: to a tenth, without a trailing ".0". */
258
+ function fmt(value: number): string {
259
+ const rounded = Math.round(value * 10) / 10;
260
+ return String(rounded === 0 ? 0 : rounded);
261
+ }