@vitavision/stage2d 0.10.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.
@@ -7,7 +7,7 @@
7
7
  * this is the gestures, the handles and the keyboard.
8
8
  */
9
9
 
10
- import { useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
10
+ import { useEffect, useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
11
11
 
12
12
  import type { Point } from "./measureGeometry";
13
13
  import { overlayRole } from "./overlayRole";
@@ -20,17 +20,18 @@ import {
20
20
  rotationHandlePoint,
21
21
  shapeHandleCursor,
22
22
  shapeHandlePoint,
23
+ shapePress,
24
+ SHAPE_HANDLE_PX,
25
+ SHAPE_ROTATE_OFFSET_PX,
26
+ SHAPE_ROTATE_RADIUS_PX,
23
27
  type RotatedShape,
24
28
  } from "./shapeEdit";
29
+ import { POINTER_RADIUS_PX, TOUCH_RADIUS_PX, hitRadiusPx } from "./stage/gesture";
25
30
  import { useStage } from "./stage/ImageStage";
31
+ import { useCoarsePointer } from "./stage/useCoarsePointer";
26
32
  import { useScreenPx } from "./stage/useScreenPx";
27
33
  import { imageViewBox } from "./stage/view";
28
34
 
29
- /** Handle square side, in screen pixels. */
30
- const HANDLE_PX = 9;
31
- /** Rotation handle radius, and its distance past the top side, in screen pixels. */
32
- const ROTATE_RADIUS_PX = 5;
33
- const ROTATE_OFFSET_PX = 24;
34
35
  /** Outline width, in screen pixels. */
35
36
  const STROKE_PX = 1.5;
36
37
  /** The halo under the outline (visual-language §5), in screen pixels on each side. */
@@ -66,17 +67,28 @@ export interface ShapeEditorProps {
66
67
  stroke?: string | undefined;
67
68
  }
68
69
 
69
- type Drag =
70
- | { kind: "move"; from: Point; start: RotatedShape; moved: boolean }
71
- | { kind: "resize"; handle: RoiHandle; start: RotatedShape; moved: boolean }
72
- | { kind: "rotate"; start: RotatedShape; moved: boolean };
70
+ type Drag = (
71
+ | { kind: "move"; from: Point }
72
+ | { kind: "resize"; handle: RoiHandle }
73
+ | { kind: "rotate" }
74
+ ) & { start: RotatedShape; moved: boolean; pointerId: number };
73
75
 
74
76
  /**
75
77
  * An editable rotated rectangle or ellipse inside an `ImageStage`.
76
78
  *
77
79
  * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
78
80
  * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
79
- * `minSize` rather than flipping. The interior moves it.
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.
80
92
  * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
81
93
  * round to 15°.
82
94
  * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
@@ -104,26 +116,74 @@ export function ShapeEditor({
104
116
  }: ShapeEditorProps) {
105
117
  const stage = useStage();
106
118
  const px = useScreenPx();
119
+ const coarse = useCoarsePointer();
107
120
  const dragRef = useRef<Drag | null>(null);
108
121
  const lastRef = useRef<RotatedShape | null>(null);
122
+ const stopWatchRef = useRef<(() => void) | null>(null);
109
123
 
110
124
  const report = (next: RotatedShape) => {
111
125
  lastRef.current = next;
112
126
  onValueChange(next);
113
127
  };
114
128
 
115
- const begin = (event: PointerEvent<SVGElement>, drag: Drag) => {
116
- if (stage.panMode || event.button !== 0) return;
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;
117
159
  event.stopPropagation();
118
160
  event.preventDefault();
119
- event.currentTarget.setPointerCapture(event.pointerId);
120
- dragRef.current = drag;
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" };
121
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
+ }
122
182
  };
123
183
 
124
184
  const onMove = (event: PointerEvent<SVGElement>) => {
125
185
  const drag = dragRef.current;
126
- if (!drag) return;
186
+ if (!drag || drag.pointerId !== event.pointerId) return;
127
187
  event.stopPropagation();
128
188
  const p = stage.toImage({ x: event.clientX, y: event.clientY });
129
189
  drag.moved = true;
@@ -134,12 +194,26 @@ export function ShapeEditor({
134
194
 
135
195
  const onEnd = (event: PointerEvent<SVGElement>) => {
136
196
  const drag = dragRef.current;
137
- if (!drag) return;
197
+ if (!drag || drag.pointerId !== event.pointerId) return;
138
198
  event.stopPropagation();
139
199
  dragRef.current = null;
200
+ stopWatchRef.current?.();
201
+ stopWatchRef.current = null;
140
202
  if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
141
203
  };
142
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
+
143
217
  const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
144
218
  if (!editable || value === null) return;
145
219
  const turn = rotatable && (event.key === "[" || event.key === "]");
@@ -171,8 +245,8 @@ export function ShapeEditor({
171
245
  onCommit?.(next);
172
246
  };
173
247
 
174
- const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX)) } : null;
175
- const handleSize = px(HANDLE_PX);
248
+ const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(SHAPE_ROTATE_OFFSET_PX)) } : null;
249
+ const handleSize = px(SHAPE_HANDLE_PX);
176
250
 
177
251
  return (
178
252
  <svg
@@ -196,6 +270,25 @@ export function ShapeEditor({
196
270
  opacity={0.6}
197
271
  />
198
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
+ )}
199
292
  {editable && value && (
200
293
  <Outline
201
294
  kind={kind}
@@ -206,14 +299,9 @@ export function ShapeEditor({
206
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)}°`}
207
300
  aria-roledescription={kind === "rect" ? "rotated rectangle" : "ellipse"}
208
301
  className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
209
- onPointerDown={(event) =>
210
- begin(event, { kind: "move", from: stage.toImage({ x: event.clientX, y: event.clientY }), start: value, moved: false })
211
- }
212
- onPointerMove={onMove}
213
- onPointerUp={onEnd}
214
- onLostPointerCapture={onEnd}
302
+ strokeWidth={px(2)}
303
+ {...gesture}
215
304
  onKeyDown={onKeyDown}
216
- onDoubleClick={(event) => event.stopPropagation()}
217
305
  />
218
306
  )}
219
307
  {editable && value && rotatable && stem && (
@@ -224,17 +312,13 @@ export function ShapeEditor({
224
312
  data-handle="rotate"
225
313
  cx={stem.to.x}
226
314
  cy={stem.to.y}
227
- r={px(ROTATE_RADIUS_PX)}
315
+ r={px(SHAPE_ROTATE_RADIUS_PX)}
228
316
  fill={stroke}
229
317
  stroke={HALO}
230
318
  strokeWidth={px(1)}
231
319
  className="pointer-events-auto"
232
320
  style={{ cursor: "grab" }}
233
- onPointerDown={(event) => begin(event, { kind: "rotate", start: value, moved: false })}
234
- onPointerMove={onMove}
235
- onPointerUp={onEnd}
236
- onLostPointerCapture={onEnd}
237
- onDoubleClick={(event) => event.stopPropagation()}
321
+ {...gesture}
238
322
  />
239
323
  </>
240
324
  )}
@@ -255,11 +339,7 @@ export function ShapeEditor({
255
339
  strokeWidth={px(1)}
256
340
  className="pointer-events-auto"
257
341
  style={{ cursor: shapeHandleCursor(handle, value.rotation) }}
258
- onPointerDown={(event) => begin(event, { kind: "resize", handle, start: value, moved: false })}
259
- onPointerMove={onMove}
260
- onPointerUp={onEnd}
261
- onLostPointerCapture={onEnd}
262
- onDoubleClick={(event) => event.stopPropagation()}
342
+ {...gesture}
263
343
  />
264
344
  );
265
345
  })}
@@ -265,8 +265,11 @@ export function buildAreaIndex(items: readonly Area[], cell?: number): AreaIndex
265
265
  return { items, bounds, size, cell: side, x0: minX, y0: minY, cols, rows, starts, entries };
266
266
  }
267
267
 
268
- /** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */
269
- function candidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {
268
+ /**
269
+ * The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
270
+ * The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
271
+ */
272
+ export function areaCandidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {
270
273
  const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
271
274
  if (entries.length === 0) return [];
272
275
  const cx0 = Math.max(0, Math.floor((left - x0) / cell));
@@ -306,7 +309,7 @@ export function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit
306
309
  const { items, size } = index;
307
310
  let edge: AreaHit | null = null;
308
311
  let inner: AreaHit | null = null;
309
- for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
312
+ for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
310
313
  const points = items[a]!.points;
311
314
  const distance = distanceToOutline(points, p.x, p.y);
312
315
  const inside = pointInPolygon(points, p.x, p.y);
@@ -337,7 +340,7 @@ export function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {
337
340
  height: Math.abs(rect.height),
338
341
  };
339
342
  const out: AreaId[] = [];
340
- for (const a of candidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {
343
+ for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {
341
344
  if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);
342
345
  }
343
346
  return out;
@@ -0,0 +1,279 @@
1
+ /**
2
+ * A spatial index over many ellipses: which one is under the pointer, and which ones a
3
+ * rubber band touched.
4
+ *
5
+ * The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
6
+ * items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
7
+ * exact tests are in the ellipse's own frame: containment is one quadratic form, and the
8
+ * distance to the outline is the true Euclidean distance (a few Newton steps on the
9
+ * parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
10
+ * round one. It imports neither React nor the DOM.
11
+ *
12
+ * An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
13
+ * outline to draw or to pick.
14
+ */
15
+
16
+ import { areaCandidates, buildAreaIndex, type AreaIndex } from "./areaIndex";
17
+ import type { Point } from "./measureGeometry";
18
+ import type { Rect } from "./stage/view";
19
+
20
+ /** An ellipse's identity. */
21
+ export type EllipseId = string | number;
22
+
23
+ /** One ellipse. */
24
+ export interface Ellipse {
25
+ /** Its identity, unique in the set. */
26
+ id: EllipseId;
27
+ /** Centre x, image pixels. */
28
+ x: number;
29
+ /** Centre y, image pixels. */
30
+ y: number;
31
+ /** Semi-axis along the rotated x axis, image pixels. */
32
+ rx: number;
33
+ /** Semi-axis along the rotated y axis, image pixels. */
34
+ ry: number;
35
+ /** Rotation of the `rx` axis, radians clockwise on screen (y points down). Defaults to 0. */
36
+ angle?: number | undefined;
37
+ }
38
+
39
+ /**
40
+ * An index built by `buildEllipseIndex`. Treat it as opaque and query it with `nearestEllipse`
41
+ * and `ellipsesInRect`; its layout may change.
42
+ */
43
+ export interface EllipseIndex {
44
+ /** The ellipses, in the order given. */
45
+ readonly items: readonly Ellipse[];
46
+ /** The grid over their bounding boxes (an `AreaIndex` of boxes, one per ellipse). */
47
+ readonly grid: AreaIndex;
48
+ /** Per ellipse, its area `π·rx·ry`, used to prefer the smaller of nested ellipses; `NaN` for a degenerate one. */
49
+ readonly size: Float64Array;
50
+ }
51
+
52
+ /** The ellipse `nearestEllipse` picked. */
53
+ export interface EllipseHit {
54
+ /** Its id. */
55
+ id: EllipseId;
56
+ /** Its position in the array the index was built from. */
57
+ index: number;
58
+ /** Whether the query is inside the ellipse. */
59
+ inside: boolean;
60
+ /** The distance from the query to the ellipse's outline, in image pixels (also when inside). */
61
+ distance: number;
62
+ }
63
+
64
+ function usable(e: Ellipse): boolean {
65
+ return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
66
+ }
67
+
68
+ /**
69
+ * The axis-aligned bounding box of an ellipse.
70
+ *
71
+ * @param e - The ellipse.
72
+ * @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
73
+ */
74
+ export function ellipseBounds(e: Ellipse): [number, number, number, number] | null {
75
+ if (!usable(e)) return null;
76
+ const c = Math.cos(e.angle ?? 0);
77
+ const s = Math.sin(e.angle ?? 0);
78
+ const hx = Math.hypot(e.rx * c, e.ry * s);
79
+ const hy = Math.hypot(e.rx * s, e.ry * c);
80
+ return [e.x - hx, e.y - hy, e.x + hx, e.y + hy];
81
+ }
82
+
83
+ /** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
84
+ function toFrame(e: Ellipse, x: number, y: number): Point {
85
+ const c = Math.cos(e.angle ?? 0);
86
+ const s = Math.sin(e.angle ?? 0);
87
+ const dx = x - e.x;
88
+ const dy = y - e.y;
89
+ return { x: c * dx + s * dy, y: -s * dx + c * dy };
90
+ }
91
+
92
+ /**
93
+ * Whether `(x, y)` is inside the ellipse (its outline counts as inside).
94
+ *
95
+ * @param e - The ellipse.
96
+ * @param x - The query's x.
97
+ * @param y - The query's y.
98
+ * @returns `false` for a degenerate ellipse.
99
+ */
100
+ export function pointInEllipse(e: Ellipse, x: number, y: number): boolean {
101
+ if (!usable(e)) return false;
102
+ const p = toFrame(e, x, y);
103
+ return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
104
+ }
105
+
106
+ /** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
107
+ const NEWTON_STEPS = 12;
108
+
109
+ /**
110
+ * The Euclidean distance from `(x, y)` to the outline of an ellipse.
111
+ *
112
+ * The query is folded into the first quadrant of the ellipse's frame and the nearest outline
113
+ * point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
114
+ * better of a coarse scan so a thin ellipse and a query near its centre both converge.
115
+ *
116
+ * @param e - The ellipse.
117
+ * @param x - The query's x.
118
+ * @param y - The query's y.
119
+ * @returns The distance; `Infinity` for a degenerate ellipse.
120
+ */
121
+ export function distanceToEllipse(e: Ellipse, x: number, y: number): number {
122
+ if (!usable(e)) return Infinity;
123
+ const p = toFrame(e, x, y);
124
+ const px = Math.abs(p.x);
125
+ const py = Math.abs(p.y);
126
+ const a = e.rx;
127
+ const b = e.ry;
128
+ const squared = (t: number) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
129
+ // The squared distance can have two local minima in the quadrant (a query near the centre of
130
+ // a thin ellipse), so start from the best of a coarse scan, then polish.
131
+ let t = 0;
132
+ let best = Infinity;
133
+ const SCAN = 16;
134
+ for (let k = 0; k <= SCAN; k++) {
135
+ const candidate = (k / SCAN) * (Math.PI / 2);
136
+ const value = squared(candidate);
137
+ if (value < best) {
138
+ best = value;
139
+ t = candidate;
140
+ }
141
+ }
142
+ for (let i = 0; i < NEWTON_STEPS; i++) {
143
+ const c = Math.cos(t);
144
+ const s = Math.sin(t);
145
+ // f(θ) = d/dθ of half the squared distance; f' by differentiating again.
146
+ const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
147
+ const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
148
+ if (!(Math.abs(df) > 1e-12)) break;
149
+ const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
150
+ if (squared(next) > squared(t)) break; // a step that does not descend is noise
151
+ t = next;
152
+ }
153
+ return Math.sqrt(squared(t));
154
+ }
155
+
156
+ /**
157
+ * An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
158
+ *
159
+ * @param cx - Centre x, image pixels.
160
+ * @param cy - Centre y, image pixels.
161
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
162
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
163
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
164
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
165
+ */
166
+ export function ellipsePath(cx: number, cy: number, rx: number, ry: number, angle = 0): string {
167
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
168
+ const dx = rx * Math.cos(angle);
169
+ const dy = rx * Math.sin(angle);
170
+ const degrees = round((angle * 180) / Math.PI);
171
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
172
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
173
+ }
174
+
175
+ /** Round to 1/1000 of an image pixel. */
176
+ function round(value: number): number {
177
+ return Math.round(value * 1000) / 1000;
178
+ }
179
+
180
+ /**
181
+ * Index a set of ellipses.
182
+ *
183
+ * @param items - The ellipses.
184
+ * @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
185
+ * @returns The index.
186
+ */
187
+ export function buildEllipseIndex(items: readonly Ellipse[], cell?: number): EllipseIndex {
188
+ const size = new Float64Array(items.length).fill(Number.NaN);
189
+ const boxes = items.map((item, i) => {
190
+ const box = ellipseBounds(item);
191
+ if (box === null) return { id: i, points: [] as number[] };
192
+ size[i] = Math.PI * item.rx * item.ry;
193
+ const [x0, y0, x1, y1] = box;
194
+ return { id: i, points: [x0, y0, x1, y0, x1, y1, x0, y1] };
195
+ });
196
+ return { items, grid: buildAreaIndex(boxes, cell), size };
197
+ }
198
+
199
+ /**
200
+ * The ellipse under a point: one whose outline passes within `radius`, or else one that
201
+ * contains it.
202
+ *
203
+ * An outline is the more precise gesture, so it wins: among ellipses whose outline is within
204
+ * `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
205
+ * distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
206
+ * another is picked rather than the outer one, then to the earlier one.
207
+ *
208
+ * @param index - The index.
209
+ * @param p - The query, in image coordinates.
210
+ * @param radius - How far from an outline the query still picks it, in image pixels.
211
+ * @returns The ellipse, or `null`.
212
+ */
213
+ export function nearestEllipse(index: EllipseIndex, p: Point, radius: number): EllipseHit | null {
214
+ if (!(radius >= 0)) return null;
215
+ const { items, size } = index;
216
+ let edge: EllipseHit | null = null;
217
+ let inner: EllipseHit | null = null;
218
+ for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
219
+ const e = items[a]!;
220
+ const distance = distanceToEllipse(e, p.x, p.y);
221
+ const hit: EllipseHit = { id: e.id, index: a, inside: pointInEllipse(e, p.x, p.y), distance };
222
+ if (distance <= radius) {
223
+ if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;
224
+ } else if (hit.inside && (inner === null || size[a]! < size[inner.index]!)) {
225
+ inner = hit;
226
+ }
227
+ }
228
+ return edge ?? inner;
229
+ }
230
+
231
+ /**
232
+ * The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
233
+ * inside the ellipse, or contains it.
234
+ *
235
+ * @param index - The index.
236
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
237
+ * its corners.
238
+ * @returns Their ids, in the order the ellipses were given.
239
+ */
240
+ export function ellipsesInRect(index: EllipseIndex, rect: Rect): EllipseId[] {
241
+ const x0 = Math.min(rect.x, rect.x + rect.width);
242
+ const y0 = Math.min(rect.y, rect.y + rect.height);
243
+ const x1 = Math.max(rect.x, rect.x + rect.width);
244
+ const y1 = Math.max(rect.y, rect.y + rect.height);
245
+ const out: EllipseId[] = [];
246
+ for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
247
+ const e = index.items[a]!;
248
+ if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
249
+ }
250
+ return out;
251
+ }
252
+
253
+ /** Whether the filled ellipse and the rectangle share a point (both convex). */
254
+ function rectMeetsEllipse(e: Ellipse, x0: number, y0: number, x1: number, y1: number): boolean {
255
+ // The rectangle contains the ellipse (its centre is inside), the ellipse contains a corner,
256
+ // or an edge crosses the ellipse with both end points outside it: the three ways two convex
257
+ // shapes meet.
258
+ if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
259
+ const corners: Point[] = [
260
+ { x: x0, y: y0 },
261
+ { x: x1, y: y0 },
262
+ { x: x1, y: y1 },
263
+ { x: x0, y: y1 },
264
+ ];
265
+ if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
266
+ // Minimise the ellipse's quadratic form along each edge, in the ellipse's frame.
267
+ for (let k = 0; k < 4; k++) {
268
+ const a = toFrame(e, corners[k]!.x, corners[k]!.y);
269
+ const b = toFrame(e, corners[(k + 1) % 4]!.x, corners[(k + 1) % 4]!.y);
270
+ const ux = (b.x - a.x) / e.rx;
271
+ const uy = (b.y - a.y) / e.ry;
272
+ const vx = a.x / e.rx;
273
+ const vy = a.y / e.ry;
274
+ const len2 = ux * ux + uy * uy;
275
+ const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
276
+ if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
277
+ }
278
+ return false;
279
+ }
@@ -34,9 +34,11 @@ export interface MarkerShape {
34
34
  * @param y - Centre y, in image coordinates.
35
35
  * @param unit - Image pixels per screen pixel.
36
36
  * @param angle - The item's orientation in radians, `0` when it has none.
37
+ * @param angle2 - The item's second angle in radians, `undefined` when it has none. Most
38
+ * shapes ignore it; a glyph with two axes (a corner's two edge directions) reads it.
37
39
  * @returns Path commands, absolute at the start (`M x y …`) and self-contained.
38
40
  */
39
- path: (x: number, y: number, unit: number, angle: number) => string;
41
+ path: (x: number, y: number, unit: number, angle: number, angle2?: number) => string;
40
42
  }
41
43
 
42
44
  /** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
@@ -15,7 +15,13 @@
15
15
  */
16
16
 
17
17
  import type { Point } from "./measureGeometry";
18
- import type { RoiHandle } from "./roiEdit";
18
+ import { ROI_HANDLES, type RoiHandle } from "./roiEdit";
19
+
20
+ /** Handle square side, in screen pixels. */
21
+ export const SHAPE_HANDLE_PX = 9;
22
+ /** Rotation handle radius, and its distance past the top side, in screen pixels. */
23
+ export const SHAPE_ROTATE_RADIUS_PX = 5;
24
+ export const SHAPE_ROTATE_OFFSET_PX = 24;
19
25
 
20
26
  /** A rotated rectangle, or the ellipse inscribed in one. */
21
27
  export interface RotatedShape {
@@ -230,3 +236,63 @@ export function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilo
230
236
  Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon
231
237
  );
232
238
  }
239
+
240
+ /** What a press on an editable shape does. */
241
+ export type ShapePress = { kind: "resize"; handle: RoiHandle } | { kind: "rotate" } | { kind: "move" };
242
+
243
+ /**
244
+ * How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is
245
+ * a first-order estimate, which is exact on the axes and good to a few percent elsewhere.
246
+ */
247
+ function distanceOutside(shape: RotatedShape, kind: "rect" | "ellipse", p: Point): number {
248
+ const u = toShapeFrame(shape, p);
249
+ const a = Math.max(shape.width / 2, 1e-9);
250
+ const b = Math.max(shape.height / 2, 1e-9);
251
+ if (kind === "rect") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));
252
+ const f = (u.x / a) ** 2 + (u.y / b) ** 2;
253
+ if (f <= 1) return 0;
254
+ const g = Math.hypot(u.x / (a * a), u.y / (b * b));
255
+ return (f - Math.sqrt(f)) / g;
256
+ }
257
+
258
+ /**
259
+ * What a press on an editable shape means, decided once for the whole editor so that a small
260
+ * shape's interior never steals a press meant for its handle.
261
+ *
262
+ * In order:
263
+ * 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen
264
+ * distance from the press is within `radius` plus the handle's half size: resize or rotate.
265
+ * 2. Inside the shape, or within `radius` screen pixels of its outline: move.
266
+ * 3. Otherwise `null`: the press is declined and belongs to whatever is below.
267
+ *
268
+ * @param shape - The shape.
269
+ * @param kind - `"rect"` or `"ellipse"` (the outline differs).
270
+ * @param scale - The view scale: screen pixels per image pixel.
271
+ * @param point - The press, in image coordinates.
272
+ * @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.
273
+ * @param rotatable - Whether the rotation handle exists. Defaults to `true`.
274
+ * @returns The decision, or `null`.
275
+ */
276
+ export function shapePress(
277
+ shape: RotatedShape,
278
+ kind: "rect" | "ellipse",
279
+ scale: number,
280
+ point: Point,
281
+ radius: number,
282
+ rotatable = true,
283
+ ): ShapePress | null {
284
+ const best: { press: ShapePress | null; distance: number } = { press: null, distance: Infinity };
285
+ const consider = (candidate: ShapePress, at: Point, half: number) => {
286
+ const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;
287
+ if (d <= radius + half && d < best.distance) {
288
+ best.press = candidate;
289
+ best.distance = d;
290
+ }
291
+ };
292
+ for (const handle of ROI_HANDLES) consider({ kind: "resize", handle }, shapeHandlePoint(shape, handle), SHAPE_HANDLE_PX / 2);
293
+ if (rotatable) {
294
+ consider({ kind: "rotate" }, rotationHandlePoint(shape, SHAPE_ROTATE_OFFSET_PX / scale), SHAPE_ROTATE_RADIUS_PX);
295
+ }
296
+ if (best.press) return best.press;
297
+ return distanceOutside(shape, kind, point) * scale <= radius ? { kind: "move" } : null;
298
+ }