@vitavision/stage2d 0.9.0 → 0.11.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.
@@ -0,0 +1,370 @@
1
+ /**
2
+ * A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own
3
+ * frame, and turned from a rotation handle, on the image.
4
+ *
5
+ * The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which
6
+ * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
7
+ * this is the gestures, the handles and the keyboard.
8
+ */
9
+
10
+ import { useEffect, useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
11
+
12
+ import type { Point } from "./measureGeometry";
13
+ import { overlayRole } from "./overlayRole";
14
+ import { ROI_HANDLES, type RoiHandle } from "./roiEdit";
15
+ import {
16
+ fromShapeFrame,
17
+ moveShape,
18
+ resizeShape,
19
+ rotateShape,
20
+ rotationHandlePoint,
21
+ shapeHandleCursor,
22
+ shapeHandlePoint,
23
+ shapePress,
24
+ SHAPE_HANDLE_PX,
25
+ SHAPE_ROTATE_OFFSET_PX,
26
+ SHAPE_ROTATE_RADIUS_PX,
27
+ type RotatedShape,
28
+ } from "./shapeEdit";
29
+ import { POINTER_RADIUS_PX, TOUCH_RADIUS_PX, hitRadiusPx } from "./stage/gesture";
30
+ import { useStage } from "./stage/ImageStage";
31
+ import { useCoarsePointer } from "./stage/useCoarsePointer";
32
+ import { useScreenPx } from "./stage/useScreenPx";
33
+ import { imageViewBox } from "./stage/view";
34
+
35
+ /** Outline width, in screen pixels. */
36
+ const STROKE_PX = 1.5;
37
+ /** The halo under the outline (visual-language §5), in screen pixels on each side. */
38
+ const HALO_PX = 1;
39
+ /** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
40
+ const SNAP = Math.PI / 12;
41
+ const KEY_TURN = Math.PI / 180;
42
+ const HALO = overlayRole("halo");
43
+
44
+ /** Props of `ShapeEditor`. */
45
+ export interface ShapeEditorProps {
46
+ /** `"rect"` draws a rotated rectangle, `"ellipse"` the ellipse inscribed in it. */
47
+ kind: "rect" | "ellipse";
48
+ /**
49
+ * The shape in image coordinates, or `null` for none. `rotation` is in **radians, clockwise
50
+ * on screen**, so a value in degrees (Konva's, say) is `degrees * Math.PI / 180`. An
51
+ * ellipse's `width` and `height` are its full axes, `2 · radiusX` and `2 · radiusY`.
52
+ */
53
+ value: RotatedShape | null;
54
+ /** Called with the shape as it changes: on every move of a drag, and on each key nudge. */
55
+ onValueChange: (value: RotatedShape) => void;
56
+ /** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */
57
+ onCommit?: ((value: RotatedShape) => void) | undefined;
58
+ /** Show handles and accept moves, resizes and rotations. Defaults to `true`. */
59
+ editable?: boolean | undefined;
60
+ /** Show the rotation handle and accept `[` / `]`. Defaults to `true`; off for a shape that must stay level. */
61
+ rotatable?: boolean | undefined;
62
+ /** The smallest extent on either axis, in image pixels. Defaults to 5. */
63
+ minSize?: number | undefined;
64
+ /** The shape's accessible name. Defaults to "Shape". */
65
+ label?: string | undefined;
66
+ /** CSS colour of the outline and handles. Defaults to the overlay `selection` role. */
67
+ stroke?: string | undefined;
68
+ }
69
+
70
+ type Drag = (
71
+ | { kind: "move"; from: Point }
72
+ | { kind: "resize"; handle: RoiHandle }
73
+ | { kind: "rotate" }
74
+ ) & { start: RotatedShape; moved: boolean; pointerId: number };
75
+
76
+ /**
77
+ * An editable rotated rectangle or ellipse inside an `ImageStage`.
78
+ *
79
+ * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
80
+ * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
81
+ * `minSize` rather than flipping. The interior moves it, and so does the band along its
82
+ * outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin
83
+ * or rotated shape is grabbed. The band is as wide as the device's primary pointer needs
84
+ * (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to
85
+ * 12 px outside the outline reaches the layers below instead of the editor.
86
+ * - **Press order.** One decision serves every part of the editor: the nearest handle first,
87
+ * then the interior or outline band (move), then nothing. A small shape's interior does not
88
+ * steal a press meant for a handle, and a press that hits none of them is not claimed, so
89
+ * it reaches whatever is below, or the stage.
90
+ * - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit
91
+ * cancels it (the shape reverts, nothing is committed) and is left to the stage.
92
+ * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
93
+ * round to 15°.
94
+ * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
95
+ * with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`
96
+ * turn it by 1° (15° with Shift).
97
+ * - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an
98
+ * ellipse also shows its bounding box, where the handles are.
99
+ * - **Panning.** A press with the hand tool, or with space held, still pans.
100
+ *
101
+ * It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does
102
+ * not keep the shape inside the image.
103
+ *
104
+ * The SVG carries `data-editable`; the outline carries `data-shape`.
105
+ */
106
+ export function ShapeEditor({
107
+ kind,
108
+ value,
109
+ onValueChange,
110
+ onCommit,
111
+ editable = true,
112
+ rotatable = true,
113
+ minSize = 5,
114
+ label = "Shape",
115
+ stroke = overlayRole("selection"),
116
+ }: ShapeEditorProps) {
117
+ const stage = useStage();
118
+ const px = useScreenPx();
119
+ const coarse = useCoarsePointer();
120
+ const dragRef = useRef<Drag | null>(null);
121
+ const lastRef = useRef<RotatedShape | null>(null);
122
+ const stopWatchRef = useRef<(() => void) | null>(null);
123
+
124
+ const report = (next: RotatedShape) => {
125
+ lastRef.current = next;
126
+ onValueChange(next);
127
+ };
128
+
129
+ /** Abandon an edit in flight: the shape reverts and nothing is committed. */
130
+ const cancelEdit = () => {
131
+ const drag = dragRef.current;
132
+ dragRef.current = null;
133
+ stopWatchRef.current?.();
134
+ stopWatchRef.current = null;
135
+ if (drag && lastRef.current) onValueChange(drag.start);
136
+ lastRef.current = null;
137
+ };
138
+
139
+ // An edit still in flight when the editor goes away is cancelled, not left listening.
140
+ useEffect(() => () => stopWatchRef.current?.(), []);
141
+
142
+ /**
143
+ * The one press decision for the whole editor: every target (the interior, the outline
144
+ * band, a handle) comes here, and the nearest handle wins over the interior. A declined
145
+ * press is not claimed and bubbles to the stage.
146
+ */
147
+ const press = (event: PointerEvent<SVGElement>) => {
148
+ if (!value || stage.panMode) return;
149
+ const touch = event.pointerType === "touch";
150
+ if (!touch && event.button !== 0) return;
151
+ // A second finger while an edit is in flight cancels it (a pinch, not an edit), unclaimed.
152
+ if (dragRef.current) {
153
+ if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();
154
+ return;
155
+ }
156
+ const at = stage.toImage({ x: event.clientX, y: event.clientY });
157
+ const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);
158
+ if (!decision) return;
159
+ event.stopPropagation();
160
+ event.preventDefault();
161
+ try {
162
+ event.currentTarget.setPointerCapture(event.pointerId);
163
+ } catch {
164
+ // The pointer ended before this handler ran; the edit still follows the events the editor receives.
165
+ }
166
+ const base = { start: value, moved: false, pointerId: event.pointerId };
167
+ dragRef.current =
168
+ decision.kind === "move"
169
+ ? { ...base, kind: "move", from: at }
170
+ : decision.kind === "resize"
171
+ ? { ...base, kind: "resize", handle: decision.handle }
172
+ : { ...base, kind: "rotate" };
173
+ lastRef.current = null;
174
+ if (touch) {
175
+ const id = event.pointerId;
176
+ const other = (e: globalThis.PointerEvent) => {
177
+ if (e.pointerId !== id && e.pointerType === "touch") cancelEdit();
178
+ };
179
+ window.addEventListener("pointerdown", other);
180
+ stopWatchRef.current = () => window.removeEventListener("pointerdown", other);
181
+ }
182
+ };
183
+
184
+ const onMove = (event: PointerEvent<SVGElement>) => {
185
+ const drag = dragRef.current;
186
+ if (!drag || drag.pointerId !== event.pointerId) return;
187
+ event.stopPropagation();
188
+ const p = stage.toImage({ x: event.clientX, y: event.clientY });
189
+ drag.moved = true;
190
+ if (drag.kind === "move") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));
191
+ else if (drag.kind === "resize") report(resizeShape(drag.start, drag.handle, p, minSize));
192
+ else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));
193
+ };
194
+
195
+ const onEnd = (event: PointerEvent<SVGElement>) => {
196
+ const drag = dragRef.current;
197
+ if (!drag || drag.pointerId !== event.pointerId) return;
198
+ event.stopPropagation();
199
+ dragRef.current = null;
200
+ stopWatchRef.current?.();
201
+ stopWatchRef.current = null;
202
+ if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
203
+ };
204
+
205
+ /** The handlers every target of the editor shares. */
206
+ const gesture = {
207
+ onPointerDown: press,
208
+ onPointerMove: onMove,
209
+ onPointerUp: onEnd,
210
+ onPointerCancel: (event: PointerEvent<SVGElement>) => {
211
+ if (dragRef.current?.pointerId === event.pointerId) cancelEdit();
212
+ },
213
+ onLostPointerCapture: onEnd,
214
+ onDoubleClick: (event: { stopPropagation: () => void }) => event.stopPropagation(),
215
+ };
216
+
217
+ const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
218
+ if (!editable || value === null) return;
219
+ const turn = rotatable && (event.key === "[" || event.key === "]");
220
+ if (turn) {
221
+ event.preventDefault();
222
+ event.stopPropagation();
223
+ const angle = (event.key === "]" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);
224
+ const next = { ...value, rotation: value.rotation + angle };
225
+ onValueChange(next);
226
+ onCommit?.(next);
227
+ return;
228
+ }
229
+ const step = event.shiftKey ? 10 : 1;
230
+ const delta: Record<string, Point> = {
231
+ ArrowLeft: { x: -step, y: 0 },
232
+ ArrowRight: { x: step, y: 0 },
233
+ ArrowUp: { x: 0, y: -step },
234
+ ArrowDown: { x: 0, y: step },
235
+ };
236
+ const d = delta[event.key];
237
+ if (!d) return;
238
+ event.preventDefault();
239
+ event.stopPropagation();
240
+ // Alt grows from the top-left corner, along the shape's own axes, as `RectRoiEditor` does.
241
+ const next = event.altKey
242
+ ? resizeShape(value, "se", fromShapeFrame(value, { x: value.width / 2 + d.x, y: value.height / 2 + d.y }), minSize)
243
+ : moveShape(value, d.x, d.y);
244
+ onValueChange(next);
245
+ onCommit?.(next);
246
+ };
247
+
248
+ const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(SHAPE_ROTATE_OFFSET_PX)) } : null;
249
+ const handleSize = px(SHAPE_HANDLE_PX);
250
+
251
+ return (
252
+ <svg
253
+ viewBox={imageViewBox(stage.image)}
254
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
255
+ data-editable={editable ? "" : undefined}
256
+ >
257
+ {value && <Outline kind={kind} shape={value} fill="none" stroke={HALO} strokeWidth={px(STROKE_PX + 2 * HALO_PX)} />}
258
+ {value && <Outline kind={kind} shape={value} data-shape={kind} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(STROKE_PX)} />}
259
+ {kind === "ellipse" && value && (
260
+ <rect
261
+ x={value.cx - value.width / 2}
262
+ y={value.cy - value.height / 2}
263
+ width={value.width}
264
+ height={value.height}
265
+ transform={turned(value)}
266
+ fill="none"
267
+ stroke={stroke}
268
+ strokeWidth={px(1)}
269
+ strokeDasharray={`${px(4)} ${px(3)}`}
270
+ opacity={0.6}
271
+ />
272
+ )}
273
+ {editable && value && (
274
+ // The outline band: a wide transparent stroke, so a press a few pixels outside the
275
+ // outline still reaches the editor. Sized for the device's primary pointer (a finger's
276
+ // 12 px on a touch-first device, a mouse's 6 px otherwise) so a mouse press just
277
+ // outside the outline reaches the layers below. `press` decides with the event's own pointer.
278
+ <Outline
279
+ kind={kind}
280
+ shape={value}
281
+ data-shape-band=""
282
+ fill="none"
283
+ stroke="transparent"
284
+ strokeWidth={px(2 * (coarse ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX))}
285
+ strokeLinejoin="round"
286
+ aria-hidden
287
+ className="pointer-events-auto cursor-move"
288
+ style={{ pointerEvents: "stroke" }}
289
+ {...gesture}
290
+ />
291
+ )}
292
+ {editable && value && (
293
+ <Outline
294
+ kind={kind}
295
+ shape={value}
296
+ fill="transparent"
297
+ role="button"
298
+ tabIndex={0}
299
+ aria-label={`${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt((value.rotation * 180) / Math.PI)}°`}
300
+ aria-roledescription={kind === "rect" ? "rotated rectangle" : "ellipse"}
301
+ className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
302
+ strokeWidth={px(2)}
303
+ {...gesture}
304
+ onKeyDown={onKeyDown}
305
+ />
306
+ )}
307
+ {editable && value && rotatable && stem && (
308
+ <>
309
+ <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={HALO} strokeWidth={px(1 + 2 * HALO_PX)} />
310
+ <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={stroke} strokeWidth={px(1)} />
311
+ <circle
312
+ data-handle="rotate"
313
+ cx={stem.to.x}
314
+ cy={stem.to.y}
315
+ r={px(SHAPE_ROTATE_RADIUS_PX)}
316
+ fill={stroke}
317
+ stroke={HALO}
318
+ strokeWidth={px(1)}
319
+ className="pointer-events-auto"
320
+ style={{ cursor: "grab" }}
321
+ {...gesture}
322
+ />
323
+ </>
324
+ )}
325
+ {editable &&
326
+ value &&
327
+ ROI_HANDLES.map((handle) => {
328
+ const centre = shapeHandlePoint(value, handle);
329
+ return (
330
+ <rect
331
+ key={handle}
332
+ data-handle={handle}
333
+ x={centre.x - handleSize / 2}
334
+ y={centre.y - handleSize / 2}
335
+ width={handleSize}
336
+ height={handleSize}
337
+ fill={stroke}
338
+ stroke={HALO}
339
+ strokeWidth={px(1)}
340
+ className="pointer-events-auto"
341
+ style={{ cursor: shapeHandleCursor(handle, value.rotation) }}
342
+ {...gesture}
343
+ />
344
+ );
345
+ })}
346
+ </svg>
347
+ );
348
+ }
349
+
350
+ /** What the outline element takes: any SVG attribute, and `data-*`. */
351
+ type OutlineProps = Omit<SVGProps<SVGElement>, "ref"> & Record<`data-${string}`, string>;
352
+
353
+ /** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */
354
+ function Outline({ kind, shape, ...rest }: OutlineProps & { kind: "rect" | "ellipse"; shape: RotatedShape }) {
355
+ const transform = turned(shape);
356
+ return kind === "rect" ? (
357
+ <rect x={shape.cx - shape.width / 2} y={shape.cy - shape.height / 2} width={shape.width} height={shape.height} transform={transform} {...rest} />
358
+ ) : (
359
+ <ellipse cx={shape.cx} cy={shape.cy} rx={shape.width / 2} ry={shape.height / 2} transform={transform} {...rest} />
360
+ );
361
+ }
362
+
363
+ /** The SVG transform that turns a shape drawn level about its centre. */
364
+ function turned(shape: RotatedShape): string {
365
+ return `rotate(${(shape.rotation * 180) / Math.PI} ${shape.cx} ${shape.cy})`;
366
+ }
367
+
368
+ function fmt(value: number): string {
369
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
370
+ }