@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
@@ -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
+ }
@@ -4,9 +4,9 @@
4
4
  *
5
5
  * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
6
6
  * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
7
- * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
7
+ * appearance into a handful of `<path>`s Strokes stay screen-sized.
8
8
  * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
9
- * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
9
+ * DOM; `pickable={false}` leaves a decorative layer out of it.
10
10
  */
11
11
 
12
12
  import { useMemo, useState } from "react";
@@ -136,7 +136,7 @@ interface Batch {
136
136
  *
137
137
  * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
138
138
  * the stroke is a screen constant.
139
- * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
139
+ * - **States**: 1.5 screen px (1 for `model` and `structure`), hover
140
140
  * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
141
141
  * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
142
142
  * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
@@ -3,8 +3,7 @@
3
3
  * column edges between neighbours, and optional `(i, j)` labels.
4
4
  *
5
5
  * Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of
6
- * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1
7
- * and 4). Edges are not picked: a person points at a corner.
6
+ * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths. Edges are not picked: a person points at a corner.
8
7
  */
9
8
 
10
9
  import { useMemo } from "react";
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.
3
3
  *
4
- * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an
4
+ * A heatmap is a raster, not vector geometry : it is rendered once into an
5
5
  * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage
6
6
  * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel
7
7
  * map costs one element. It takes no pointer events; to read the numbers under the pointer, use