@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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, use, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
1
+ import { createContext, use, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { DropdownMenu, Kbd, MenuCheckboxItem, MenuLabel, Tooltip, cn, focusRing, toneColor } from "@vitavision/ui";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  import { Layers, Maximize2, Minus, Plus, Scan } from "lucide-react";
@@ -54,18 +54,43 @@ const SCALE_LADDER = [
54
54
  const SCALE_EPSILON = .001;
55
55
  /** Absolute tolerance for "is this the same offset", in CSS pixels. */
56
56
  const OFFSET_EPSILON = .5;
57
- /** The scale at which the whole image is just visible inside `box`. */
58
- function fitScale(box, image) {
57
+ /**
58
+ * The scale at which the whole image is just visible inside `box`.
59
+ *
60
+ * @param box - The viewport, in CSS pixels.
61
+ * @param image - The image, in image pixels.
62
+ * @param options - A margin and an upscale cap; the defaults fill the box edge to edge.
63
+ * @returns CSS pixels per image pixel; `1` for a degenerate box or image.
64
+ */
65
+ function fitScale(box, image, options = {}) {
59
66
  if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;
60
- return Math.min(box.width / image.width, box.height / image.height);
67
+ const pad = Math.max(0, options.padding ?? 0);
68
+ const room = box.width > 2 * pad && box.height > 2 * pad ? pad : 0;
69
+ const scale = Math.min((box.width - 2 * room) / image.width, (box.height - 2 * room) / image.height);
70
+ return options.upscale === false ? Math.min(1, scale) : scale;
61
71
  }
62
- /** Fit, centred — the view a viewer opens at and the one `0` returns to. */
63
- function fitView(box, image) {
64
- return centred(fitScale(box, image), box, image);
72
+ /**
73
+ * Fit, centred: the view a viewer opens at and the one `0` returns to.
74
+ *
75
+ * @param box - The viewport, in CSS pixels.
76
+ * @param image - The image, in image pixels.
77
+ * @param options - A margin and an upscale cap; see `FitOptions`.
78
+ * @returns The view.
79
+ */
80
+ function fitView(box, image, options = {}) {
81
+ return centred(fitScale(box, image, options), box, image);
65
82
  }
66
- /** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */
67
- function initialView(box, image) {
68
- return centred(Math.min(1, fitScale(box, image)), box, image);
83
+ /**
84
+ * The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view.
85
+ *
86
+ * @param box - The viewport, in CSS pixels.
87
+ * @param image - The image, in image pixels.
88
+ * @param options - Only `padding` matters here (the image must fit inside the margin to open
89
+ * at 1:1, and "otherwise fit" is the padded fit); it never magnifies, so `upscale` is moot.
90
+ * @returns The view.
91
+ */
92
+ function initialView(box, image, options = {}) {
93
+ return centred(Math.min(1, fitScale(box, image, { padding: options.padding })), box, image);
69
94
  }
70
95
  function centred(scale, box, image) {
71
96
  return {
@@ -74,9 +99,9 @@ function centred(scale, box, image) {
74
99
  ty: (box.height - image.height * scale) / 2
75
100
  };
76
101
  }
77
- /** Whether `view` is (indistinguishably) the fit view for this box and image. */
78
- function isFit(view, box, image) {
79
- const fit = fitView(box, image);
102
+ /** Whether `view` is (indistinguishably) the fit view for this box, image and `FitOptions`. */
103
+ function isFit(view, box, image, options = {}) {
104
+ const fit = fitView(box, image, options);
80
105
  return Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON && Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON && Math.abs(view.ty - fit.ty) <= OFFSET_EPSILON;
81
106
  }
82
107
  /** Where the **centre of** image pixel `p` lands in the viewport. */
@@ -176,9 +201,9 @@ function frameRect(box, image, rect, pad = .15) {
176
201
  * that was *fit* re-fits instead, because fit is a relationship to the viewport rather than
177
202
  * a particular pair of numbers.
178
203
  */
179
- function preserveCenter(view, from, to, image, options = {}) {
180
- if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);
181
- if (isFit(view, from, image)) return fitView(to, image);
204
+ function preserveCenter(view, from, to, image, options = {}, fit = {}) {
205
+ if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);
206
+ if (isFit(view, from, image, fit)) return fitView(to, image, fit);
182
207
  const centre = toImage(view, {
183
208
  x: from.width / 2,
184
209
  y: from.height / 2
@@ -215,6 +240,15 @@ function formatScale(scale) {
215
240
  function clamp$2(value, low, high) {
216
241
  return Math.min(high, Math.max(low, value));
217
242
  }
243
+ /**
244
+ * The hit-test tolerance for a pointer, in screen pixels.
245
+ *
246
+ * @param pointerType - `PointerEvent.pointerType`.
247
+ * @returns 12 for `"touch"`, 6 otherwise.
248
+ */
249
+ function hitRadiusPx(pointerType) {
250
+ return pointerType === "touch" ? 12 : 6;
251
+ }
218
252
  const BUTTON_CODE = {
219
253
  left: 0,
220
254
  middle: 1,
@@ -389,11 +423,19 @@ function createHitRegistry() {
389
423
  * with the image.
390
424
  */
391
425
  const WHEEL_SENSITIVITY = .0015;
426
+ /**
427
+ * How long after the last view change the stage box keeps `will-change: transform`.
428
+ *
429
+ * The hint keeps a pan on the compositor (without it every overlay path is repainted each
430
+ * frame: 130 ms against 17 ms with 4,000 corners in view under software raster), but Chromium
431
+ * then keeps the layer at the raster scale it had when the hint was applied, so the stage
432
+ * would stay blurry after a zoom. Measured in `willChange.browser.test.ts`: always on, the
433
+ * edge of a zoomed image ramps over 6 px and a 1 px line smears to 10; cleared once the view
434
+ * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.
435
+ */
436
+ const MOVING_SETTLE_MS = 150;
392
437
  /** How far a press may travel and still count as a click rather than a pan. */
393
438
  const CLICK_SLOP$1 = 3;
394
- /** The pointer's tolerance for hover and presses, in screen pixels: a mouse, and a fingertip. */
395
- const POINTER_RADIUS = 6;
396
- const TOUCH_RADIUS = 12;
397
439
  /** The view before the viewport has been measured — nothing is on screen yet. */
398
440
  const UNMEASURED_VIEW = {
399
441
  scale: 1,
@@ -417,12 +459,17 @@ function useStage() {
417
459
  * size, so an overlay drawn in image coordinates stays registered with the photograph at
418
460
  * any zoom and window size. Layers read the transform through `useStage`.
419
461
  *
462
+ * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while
463
+ * the view changes and for 150 ms after, so a pan stays on the compositor and the layer
464
+ * re-rasterises sharp once the view settles.
465
+ *
420
466
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
421
467
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
422
468
  * or absent.
423
469
  */
424
- function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, panButton, doubleClickFit = true, touchPan = "one-finger", className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", ref }) {
470
+ function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, panButton, doubleClickFit = true, touchPan = "one-finger", className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", fit: fitOptions, ref }) {
425
471
  const viewportRef = useRef(null);
472
+ const boxRef = useRef(null);
426
473
  const [box, setBox] = useState({
427
474
  width: 0,
428
475
  height: 0
@@ -434,13 +481,18 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
434
481
  const [panning, setPanning] = useState(false);
435
482
  const [spaceHeld, setSpaceHeld] = useState(false);
436
483
  const panMode = panTool || spaceHeld;
484
+ const fitOpts = useMemo(() => ({
485
+ padding: fitOptions?.padding,
486
+ upscale: fitOptions?.upscale
487
+ }), [fitOptions?.padding, fitOptions?.upscale]);
437
488
  const latestRef = useRef({
438
489
  view,
439
490
  box,
440
491
  image,
441
492
  clamp,
442
493
  onView,
443
- opening
494
+ opening,
495
+ fitOpts
444
496
  });
445
497
  useLayoutEffect(() => {
446
498
  latestRef.current = {
@@ -449,7 +501,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
449
501
  image,
450
502
  clamp,
451
503
  onView,
452
- opening
504
+ opening,
505
+ fitOpts
453
506
  };
454
507
  });
455
508
  /** The view to come back to when a double-click leaves fit. */
@@ -462,11 +515,27 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
462
515
  /** The registry the stage's layers answer hit-tests through. */
463
516
  const [hits] = useState(() => createHitRegistry());
464
517
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
465
- const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW), [
518
+ const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW), [
466
519
  view,
467
520
  box,
468
521
  image,
469
- opening
522
+ opening,
523
+ fitOpts
524
+ ]);
525
+ useEffect(() => {
526
+ const element = boxRef.current;
527
+ if (!element) return;
528
+ element.style.willChange = "transform";
529
+ element.dataset["moving"] = "";
530
+ const timer = setTimeout(() => {
531
+ element.style.willChange = "";
532
+ delete element.dataset["moving"];
533
+ }, MOVING_SETTLE_MS);
534
+ return () => clearTimeout(timer);
535
+ }, [
536
+ effective.scale,
537
+ effective.tx,
538
+ effective.ty
470
539
  ]);
471
540
  const commit = useCallback((next) => {
472
541
  const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
@@ -485,10 +554,10 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
485
554
  };
486
555
  measuredRef.current = next;
487
556
  setBox(next);
488
- const { view: v, image: i, clamp: c, onView: report, opening: o } = latestRef.current;
489
- if (v === null) report(openingView(o, next, i));
557
+ const { view: v, image: i, clamp: c, onView: report, opening: o, fitOpts: f } = latestRef.current;
558
+ if (v === null) report(openingView(o, next, i, f));
490
559
  else if (!(current.width > 0)) report(clampView(v, next, i, c));
491
- else report(preserveCenter(v, current, next, i, c));
560
+ else report(preserveCenter(v, current, next, i, c, f));
492
561
  };
493
562
  measure(contentSize(element));
494
563
  const observer = new ResizeObserver((entries) => {
@@ -561,10 +630,10 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
561
630
  };
562
631
  }, []);
563
632
  const fit = useCallback(() => {
564
- const { box: b, image: i, view: v, onView: report } = latestRef.current;
633
+ const { box: b, image: i, view: v, onView: report, fitOpts: f } = latestRef.current;
565
634
  if (!(b.width > 0)) return;
566
- if (v !== null && !isFit(v, b, i)) previousRef.current = v;
567
- report(fitView(b, i));
635
+ if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
636
+ report(fitView(b, i, f));
568
637
  }, []);
569
638
  const zoomTo = useCallback((scale, anchor) => {
570
639
  const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
@@ -595,7 +664,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
595
664
  fit,
596
665
  zoomTo
597
666
  ]);
598
- const atFit = box.width > 0 && isFit(effective, box, image);
667
+ const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);
599
668
  const context = useMemo(() => ({
600
669
  view: effective,
601
670
  setView: commit,
@@ -626,7 +695,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
626
695
  panMode
627
696
  ]);
628
697
  /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */
629
- const hitRadius = (event) => imageLengthFor(effective, event.pointerType === "touch" ? TOUCH_RADIUS : POINTER_RADIUS);
698
+ const hitRadius = (event) => imageLengthFor(effective, hitRadiusPx(event.pointerType));
630
699
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
631
700
  const routePress = (event) => hits.routePress(clientToImage({
632
701
  x: event.clientX,
@@ -805,7 +874,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
805
874
  return;
806
875
  }
807
876
  previousRef.current = effective;
808
- onView(fitView(box, image));
877
+ onView(fitView(box, image, fitOpts));
809
878
  };
810
879
  const onKeyDown = (event) => {
811
880
  if (!shortcuts || isTypingTarget(event.target)) return;
@@ -886,6 +955,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
886
955
  onKeyDown,
887
956
  children: [
888
957
  /* @__PURE__ */ jsx("div", {
958
+ ref: boxRef,
889
959
  "data-stage": true,
890
960
  className: "absolute top-0 left-0 origin-top-left",
891
961
  style: {
@@ -916,8 +986,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
916
986
  });
917
987
  }
918
988
  /** The view a `null` view opens at, by the `initialView` policy. */
919
- function openingView(opening, box, image) {
920
- return opening === "fit" ? fitView(box, image) : initialView(box, image);
989
+ function openingView(opening, box, image, fit) {
990
+ return opening === "fit" ? fitView(box, image, fit) : initialView(box, image, fit);
921
991
  }
922
992
  function hoverPoint(event, element, view, image) {
923
993
  if (!element) return null;
@@ -1091,6 +1161,64 @@ function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onLoad, onError, cl
1091
1161
  })] });
1092
1162
  }
1093
1163
  //#endregion
1164
+ //#region src/components/stage/touchWatch.ts
1165
+ /**
1166
+ * Watching a touch without claiming it.
1167
+ *
1168
+ * A layer that claims a touch (`stopPropagation` plus pointer capture) takes it from the stage,
1169
+ * so a second finger can no longer pinch and a drag can no longer pan. A layer that only wants
1170
+ * to know whether the touch was a tap leaves the press alone and follows its pointer on
1171
+ * `window`, where the moves and the release arrive whoever captured the pointer.
1172
+ */
1173
+ /**
1174
+ * Follow one touch on `window` until it lifts. A second touch landing, or `pointercancel`,
1175
+ * cancels the watch and leaves the touches to the stage.
1176
+ *
1177
+ * @param origin - The `pointerdown` of the touch.
1178
+ * @param watch - What to report.
1179
+ * @returns A function that cancels the watch (calling `onCancel`); a no-op once it has ended.
1180
+ */
1181
+ function watchTouch(origin, watch) {
1182
+ const id = origin.pointerId;
1183
+ let moved = false;
1184
+ let done = false;
1185
+ const travel = (e) => Math.hypot(e.clientX - origin.clientX, e.clientY - origin.clientY);
1186
+ const stop = () => {
1187
+ done = true;
1188
+ window.removeEventListener("pointermove", move);
1189
+ window.removeEventListener("pointerup", up);
1190
+ window.removeEventListener("pointercancel", cancelEvent);
1191
+ window.removeEventListener("pointerdown", other);
1192
+ };
1193
+ const cancel = () => {
1194
+ if (done) return;
1195
+ stop();
1196
+ watch.onCancel?.();
1197
+ };
1198
+ function move(e) {
1199
+ if (e.pointerId !== id) return;
1200
+ if (!moved && travel(e) > 3) moved = true;
1201
+ if (moved) watch.onMove?.(e);
1202
+ }
1203
+ function up(e) {
1204
+ if (e.pointerId !== id) return;
1205
+ stop();
1206
+ if (!moved && travel(e) > 3) moved = true;
1207
+ watch.onEnd(e, moved, isTap(moved ? Infinity : travel(e), e.timeStamp - origin.timeStamp));
1208
+ }
1209
+ function cancelEvent(e) {
1210
+ if (e.pointerId === id) cancel();
1211
+ }
1212
+ function other(e) {
1213
+ if (e.pointerId !== id && e.pointerType === "touch") cancel();
1214
+ }
1215
+ window.addEventListener("pointermove", move);
1216
+ window.addEventListener("pointerup", up);
1217
+ window.addEventListener("pointercancel", cancelEvent);
1218
+ window.addEventListener("pointerdown", other);
1219
+ return cancel;
1220
+ }
1221
+ //#endregion
1094
1222
  //#region src/components/stage/StageSurface.tsx
1095
1223
  /**
1096
1224
  * The stage's tool model: one place that decides what a press on the image means.
@@ -1166,34 +1294,78 @@ function useStageDrag() {
1166
1294
  * that have their own small targets (handles, strokes). Each press is offered to `onPress`
1167
1295
  * unless the hand tool or a held space bar make it a pan; a declined press pans.
1168
1296
  *
1169
- * The surface draws nothing. It carries `data-dragging` while a drag it started is in
1170
- * flight.
1297
+ * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on
1298
+ * `window`, so the stage does not pan from it.
1299
+ *
1300
+ * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface
1301
+ * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)
1302
+ * and a second finger still pinches. The drag then sees:
1303
+ * - `onMove`, only once the finger has left the tap slop;
1304
+ * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;
1305
+ * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).
1306
+ *
1307
+ * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
1308
+ *
1309
+ * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
1171
1310
  */
1172
- function StageSurface({ onPress, cursor, onHover }) {
1311
+ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1173
1312
  const stage = useStage();
1174
1313
  const start = useStageDrag();
1175
1314
  const [dragging, setDragging] = useState(false);
1315
+ const watchRef = useRef(null);
1316
+ useEffect(() => () => watchRef.current?.(), []);
1176
1317
  const onPointerDown = (event) => {
1177
- if (event.button !== 0 || stage.panMode) return;
1318
+ const touch = event.pointerType === "touch";
1319
+ if (stage.panMode || !touch && event.button !== 0) return;
1320
+ if (touch && watchRef.current) return;
1321
+ const client = {
1322
+ x: event.clientX,
1323
+ y: event.clientY
1324
+ };
1178
1325
  const drag = onPress({
1179
- point: stage.toImage({
1180
- x: event.clientX,
1181
- y: event.clientY
1182
- }),
1326
+ point: stage.toImage(client),
1327
+ client,
1328
+ touch,
1329
+ radius: hitRadiusPx(event.pointerType),
1183
1330
  shiftKey: event.shiftKey,
1184
1331
  altKey: event.altKey,
1185
1332
  metaKey: event.metaKey || event.ctrlKey
1186
1333
  });
1187
1334
  if (!drag) return;
1335
+ const finish = () => setDragging(false);
1188
1336
  setDragging(true);
1337
+ if (touch && !drag.claimsTouch) {
1338
+ const release = () => {
1339
+ watchRef.current = null;
1340
+ finish();
1341
+ };
1342
+ watchRef.current = watchTouch(event, {
1343
+ onMove: (e) => drag.onMove?.(stage.toImage({
1344
+ x: e.clientX,
1345
+ y: e.clientY
1346
+ }), e),
1347
+ onEnd: (e, moved) => {
1348
+ release();
1349
+ drag.onEnd?.(stage.toImage({
1350
+ x: e.clientX,
1351
+ y: e.clientY
1352
+ }), e, moved);
1353
+ },
1354
+ onCancel: () => {
1355
+ release();
1356
+ drag.onCancel?.();
1357
+ }
1358
+ });
1359
+ return;
1360
+ }
1189
1361
  start(event, {
1190
1362
  onMove: drag.onMove,
1191
1363
  onEnd: (point, e, moved) => {
1192
- setDragging(false);
1364
+ finish();
1193
1365
  drag.onEnd?.(point, e, moved);
1194
1366
  },
1195
1367
  onCancel: () => {
1196
- setDragging(false);
1368
+ finish();
1197
1369
  drag.onCancel?.();
1198
1370
  }
1199
1371
  });
@@ -1214,7 +1386,15 @@ function StageSurface({ onPress, cursor, onHover }) {
1214
1386
  style: { cursor: stage.panMode ? void 0 : cursor },
1215
1387
  onPointerDown,
1216
1388
  onPointerMove: (event) => {
1217
- if (!dragging) onHover?.(stage.toImage({
1389
+ if (!dragging && event.pointerType !== "touch") onHover?.(stage.toImage({
1390
+ x: event.clientX,
1391
+ y: event.clientY
1392
+ }));
1393
+ },
1394
+ onDoubleClick: (event) => {
1395
+ if (!onDoubleClick) return;
1396
+ event.stopPropagation();
1397
+ onDoubleClick(stage.toImage({
1218
1398
  x: event.clientX,
1219
1399
  y: event.clientY
1220
1400
  }));
@@ -2859,10 +3039,10 @@ function clamp(value, low, high) {
2859
3039
  * inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.
2860
3040
  */
2861
3041
  /** Handle square side, in screen pixels. */
2862
- const HANDLE_PX$1 = 9;
3042
+ const HANDLE_PX = 9;
2863
3043
  /** Outline width, in screen pixels. */
2864
3044
  const STROKE_PX$2 = 1.5;
2865
- const HALO$6 = overlayRole("halo");
3045
+ const HALO$7 = overlayRole("halo");
2866
3046
  /**
2867
3047
  * An editable axis-aligned region inside an `ImageStage`.
2868
3048
  *
@@ -2973,7 +3153,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2973
3153
  width: shown.width,
2974
3154
  height: shown.height,
2975
3155
  fill: "none",
2976
- stroke: HALO$6,
3156
+ stroke: HALO$7,
2977
3157
  strokeWidth: px(3.5)
2978
3158
  }), /* @__PURE__ */ jsx("rect", {
2979
3159
  x: shown.x,
@@ -3041,7 +3221,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3041
3221
  }),
3042
3222
  editable && value && !drawing && ROI_HANDLES.map((handle) => {
3043
3223
  const centre = roiHandlePoint(value, handle);
3044
- const size = px(HANDLE_PX$1);
3224
+ const size = px(HANDLE_PX);
3045
3225
  return /* @__PURE__ */ jsx("rect", {
3046
3226
  "data-handle": handle,
3047
3227
  x: centre.x - size / 2,
@@ -3049,7 +3229,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3049
3229
  width: size,
3050
3230
  height: size,
3051
3231
  fill: stroke,
3052
- stroke: HALO$6,
3232
+ stroke: HALO$7,
3053
3233
  strokeWidth: px(1),
3054
3234
  className: "pointer-events-auto",
3055
3235
  style: { cursor: ROI_HANDLE_CURSOR[handle] },
@@ -3089,7 +3269,7 @@ function fmt$1(value) {
3089
3269
  * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
3090
3270
  * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
3091
3271
  */
3092
- const HALO$5 = overlayRole("halo");
3272
+ const HALO$6 = overlayRole("halo");
3093
3273
  /** The most points drawn as dots at once; past this the dots are noise and a cost. */
3094
3274
  const MAX_VERTEX_DOTS = 5e3;
3095
3275
  /**
@@ -3103,12 +3283,17 @@ const MAX_VERTEX_DOTS = 5e3;
3103
3283
  * - **Halo.** Every line has a halo, so it holds on any image.
3104
3284
  * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.
3105
3285
  * - **Panning.** The hand tool and a held space bar still pan.
3286
+ * - **Tools.** Without a handler (or with `interactive={false}`) the layer takes no presses
3287
+ * and only answers `useStageHitTest`, so a draw tool's surface below receives them.
3106
3288
  *
3107
3289
  * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
3108
3290
  */
3109
- function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange, onItemPress, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines", layerId, priority = STAGE_HIT_PRIORITY.line }) {
3291
+ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange, onItemPress, onSelect, marquee = false, interactive, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines", layerId, priority = STAGE_HIT_PRIORITY.line }) {
3110
3292
  const stage = useStage();
3111
3293
  const startDrag = useStageDrag();
3294
+ const watchRef = useRef(null);
3295
+ useEffect(() => () => watchRef.current?.(), []);
3296
+ const takesPresses = interactive ?? (onItemPress !== void 0 || onSelect !== void 0 || onHover !== void 0 || onHoverChange !== void 0 || marquee);
3112
3297
  const px = useScreenPx();
3113
3298
  const { hitTestAll } = useStageHitTest();
3114
3299
  const index = useMemo(() => buildPolylineIndex(items), [items]);
@@ -3222,7 +3407,9 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3222
3407
  });
3223
3408
  };
3224
3409
  const onLinePointerDown = (event) => {
3225
- if (stage.panMode || event.button !== 0) return;
3410
+ const touch = event.pointerType === "touch";
3411
+ if (stage.panMode || !touch && event.button !== 0) return;
3412
+ if (touch && watchRef.current) return;
3226
3413
  if (event.shiftKey || marquee) {
3227
3414
  sweep(event);
3228
3415
  return;
@@ -3234,6 +3421,21 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3234
3421
  y: event.clientY
3235
3422
  });
3236
3423
  if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
3424
+ if (touch && !marquee) {
3425
+ const additive = event.metaKey || event.ctrlKey;
3426
+ watchRef.current = watchTouch(event, {
3427
+ onEnd: (_e, _moved, tap) => {
3428
+ watchRef.current = null;
3429
+ if (!tap) return;
3430
+ onItemPress?.(id, event);
3431
+ onSelect?.([id], additive ? "toggle" : "replace");
3432
+ },
3433
+ onCancel: () => {
3434
+ watchRef.current = null;
3435
+ }
3436
+ });
3437
+ return;
3438
+ }
3237
3439
  event.stopPropagation();
3238
3440
  onItemPress?.(id, event);
3239
3441
  onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
@@ -3247,7 +3449,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3247
3449
  "data-hovered": hoverId ?? void 0,
3248
3450
  "data-sweeping": band ? "" : void 0,
3249
3451
  children: [
3250
- marquee && /* @__PURE__ */ jsx("rect", {
3452
+ takesPresses && marquee && /* @__PURE__ */ jsx("rect", {
3251
3453
  "data-marquee-surface": "",
3252
3454
  x: -.5,
3253
3455
  y: -.5,
@@ -3267,7 +3469,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3267
3469
  children: [
3268
3470
  /* @__PURE__ */ jsx("path", {
3269
3471
  d: groups.hit,
3270
- stroke: HALO$5,
3472
+ stroke: HALO$6,
3271
3473
  strokeWidth: px(3.5),
3272
3474
  opacity: .6
3273
3475
  }),
@@ -3280,7 +3482,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3280
3482
  }, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
3281
3483
  groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3282
3484
  d: groups.selected,
3283
- stroke: HALO$5,
3485
+ stroke: HALO$6,
3284
3486
  strokeWidth: px(4.5)
3285
3487
  }), /* @__PURE__ */ jsx("path", {
3286
3488
  "data-selected-lines": "",
@@ -3290,7 +3492,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3290
3492
  })] }),
3291
3493
  hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3292
3494
  d: hoverPath,
3293
- stroke: HALO$5,
3495
+ stroke: HALO$6,
3294
3496
  strokeWidth: px(4)
3295
3497
  }), /* @__PURE__ */ jsx("path", {
3296
3498
  "data-hovered-line": "",
@@ -3304,7 +3506,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3304
3506
  stroke: selectionStroke,
3305
3507
  strokeWidth: px(3)
3306
3508
  }),
3307
- /* @__PURE__ */ jsx("path", {
3509
+ takesPresses && /* @__PURE__ */ jsx("path", {
3308
3510
  "data-hit": "",
3309
3511
  d: groups.hit,
3310
3512
  stroke: "transparent",
@@ -3315,7 +3517,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3315
3517
  },
3316
3518
  onPointerDown: onLinePointerDown,
3317
3519
  onPointerMove: (event) => {
3318
- if (!band) setHover(pickAt(event));
3520
+ if (!band && event.pointerType !== "touch") setHover(pickAt(event));
3319
3521
  },
3320
3522
  onPointerLeave: () => setHover(null)
3321
3523
  })
@@ -3741,7 +3943,7 @@ function useLabelIndices({ enabled, xy, labelled, forced }) {
3741
3943
  const CULL_ABOVE = 3e3;
3742
3944
  /** How much bigger than a marker its selection ring is, in screen pixels. */
3743
3945
  const RING_GAP = 4;
3744
- const HALO$4 = overlayRole("halo");
3946
+ const HALO$5 = overlayRole("halo");
3745
3947
  const LABEL$1 = overlayRole("label");
3746
3948
  /**
3747
3949
  * A selectable set of points inside an `ImageStage`.
@@ -3860,7 +4062,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3860
4062
  const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
3861
4063
  const build = (batches) => batches.map((batch) => ({
3862
4064
  batch,
3863
- d: batchPath(batch, items, unit, cull, cullKey)
4065
+ d: batchPath$1(batch, items, unit, cull, cullKey)
3864
4066
  }));
3865
4067
  const paths = {
3866
4068
  normal: build(groups.normal),
@@ -3917,7 +4119,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3917
4119
  children: [
3918
4120
  halo && paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3919
4121
  d,
3920
- stroke: HALO$4,
4122
+ stroke: HALO$5,
3921
4123
  strokeWidth: widthOf(batch.shape, batch.role, "default") + px(2),
3922
4124
  opacity: .6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)
3923
4125
  }, `halo|${batch.key}`)),
@@ -3930,12 +4132,12 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3930
4132
  }, batch.key)),
3931
4133
  halo && paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3932
4134
  d,
3933
- stroke: HALO$4,
4135
+ stroke: HALO$5,
3934
4136
  strokeWidth: widthOf(batch.shape, batch.role, "selected") + px(2)
3935
4137
  }, `halo|selected|${batch.key}`)),
3936
4138
  halo && paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3937
4139
  d,
3938
- stroke: HALO$4,
4140
+ stroke: HALO$5,
3939
4141
  strokeWidth: ringWidth + px(2)
3940
4142
  }, `halo|${batch.key}`)),
3941
4143
  paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
@@ -3951,12 +4153,12 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3951
4153
  strokeWidth: ringWidth
3952
4154
  }, batch.key)),
3953
4155
  hoverItem && hoverShape && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
3954
- d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
3955
- stroke: HALO$4,
4156
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
4157
+ stroke: HALO$5,
3956
4158
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)
3957
4159
  }), /* @__PURE__ */ jsx("path", {
3958
4160
  "data-hovered-point": "",
3959
- d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
4161
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
3960
4162
  stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
3961
4163
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
3962
4164
  })] })
@@ -3965,7 +4167,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3965
4167
  "data-labels": "",
3966
4168
  fontSize: px(11),
3967
4169
  className: "font-mono",
3968
- stroke: HALO$4,
4170
+ stroke: HALO$5,
3969
4171
  strokeWidth: px(3),
3970
4172
  paintOrder: "stroke",
3971
4173
  strokeLinejoin: "round",
@@ -3986,7 +4188,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3986
4188
  * The path data of a batch, generated again only when what it depends on changed: nothing
3987
4189
  * for a disc marker, the zoom and the window for an outline.
3988
4190
  */
3989
- function batchPath(batch, items, unit, cull, cullKey) {
4191
+ function batchPath$1(batch, items, unit, cull, cullKey) {
3990
4192
  const disc = batch.shape.paint === "disc";
3991
4193
  const key = disc ? "" : `${unit}|${cullKey}`;
3992
4194
  if (batch.cache?.key === key) return batch.cache.d;
@@ -3995,7 +4197,7 @@ function batchPath(batch, items, unit, cull, cullKey) {
3995
4197
  for (const i of batch.indices) {
3996
4198
  const item = items[i];
3997
4199
  if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;
3998
- d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);
4200
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0, item.angle2);
3999
4201
  }
4000
4202
  batch.cache = {
4001
4203
  key,
@@ -4238,8 +4440,11 @@ function buildAreaIndex(items, cell) {
4238
4440
  entries
4239
4441
  };
4240
4442
  }
4241
- /** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */
4242
- function candidates(index, left, top, right, bottom) {
4443
+ /**
4444
+ * The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
4445
+ * The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
4446
+ */
4447
+ function areaCandidates(index, left, top, right, bottom) {
4243
4448
  const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
4244
4449
  if (entries.length === 0) return [];
4245
4450
  const cx0 = Math.max(0, Math.floor((left - x0) / cell));
@@ -4276,7 +4481,7 @@ function nearestArea(index, p, radius) {
4276
4481
  const { items, size } = index;
4277
4482
  let edge = null;
4278
4483
  let inner = null;
4279
- for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4484
+ for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4280
4485
  const points = items[a].points;
4281
4486
  const distance = distanceToOutline(points, p.x, p.y);
4282
4487
  const inside = pointInPolygon(points, p.x, p.y);
@@ -4309,7 +4514,7 @@ function areasInRect(index, rect) {
4309
4514
  height: Math.abs(rect.height)
4310
4515
  };
4311
4516
  const out = [];
4312
- for (const a of candidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) if (polygonTouchesRect(index.items[a].points, box)) out.push(index.items[a].id);
4517
+ for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) if (polygonTouchesRect(index.items[a].points, box)) out.push(index.items[a].id);
4313
4518
  return out;
4314
4519
  }
4315
4520
  function polygonTouchesRect(points, rect) {
@@ -4339,7 +4544,7 @@ function polygonTouchesRect(points, rect) {
4339
4544
  * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
4340
4545
  * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
4341
4546
  */
4342
- const HALO$3 = overlayRole("halo");
4547
+ const HALO$4 = overlayRole("halo");
4343
4548
  const LABEL = overlayRole("label");
4344
4549
  /** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */
4345
4550
  const FILL_OPACITY = .12;
@@ -4506,7 +4711,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4506
4711
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4507
4712
  children: [halo && /* @__PURE__ */ jsx("path", {
4508
4713
  d: batch.d,
4509
- stroke: HALO$3,
4714
+ stroke: HALO$4,
4510
4715
  strokeWidth: widthOf(batch.role, "default") + px(2),
4511
4716
  opacity: .6
4512
4717
  }), /* @__PURE__ */ jsx("path", {
@@ -4520,7 +4725,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4520
4725
  }, batch.key)),
4521
4726
  groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4522
4727
  d: groups.picked.d,
4523
- stroke: HALO$3,
4728
+ stroke: HALO$4,
4524
4729
  strokeWidth: widthOf("selection", "selected") + px(2)
4525
4730
  }), /* @__PURE__ */ jsx("path", {
4526
4731
  "data-selected-areas": "",
@@ -4532,7 +4737,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4532
4737
  })] }),
4533
4738
  hoverItem && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4534
4739
  d: areaPath(hoverItem.points),
4535
- stroke: HALO$3,
4740
+ stroke: HALO$4,
4536
4741
  strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)
4537
4742
  }), /* @__PURE__ */ jsx("path", {
4538
4743
  "data-hovered-area": "",
@@ -4544,7 +4749,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4544
4749
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4545
4750
  children: [halo && /* @__PURE__ */ jsx("path", {
4546
4751
  d,
4547
- stroke: HALO$3,
4752
+ stroke: HALO$4,
4548
4753
  strokeWidth: px(OVERLAY_STATE_WIDTH.selected + 2),
4549
4754
  opacity: .6
4550
4755
  }), /* @__PURE__ */ jsx("path", {
@@ -4559,7 +4764,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4559
4764
  "data-labels": "",
4560
4765
  fontSize: px(11),
4561
4766
  className: "font-mono",
4562
- stroke: HALO$3,
4767
+ stroke: HALO$4,
4563
4768
  strokeWidth: px(3),
4564
4769
  paintOrder: "stroke",
4565
4770
  strokeLinejoin: "round",
@@ -4589,6 +4794,469 @@ function tickPath(points, length) {
4589
4794
  return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1e3) / 1e3} ${Math.round((y + (c.y - y) * k) * 1e3) / 1e3}`;
4590
4795
  }
4591
4796
  //#endregion
4797
+ //#region src/components/ellipseIndex.ts
4798
+ /**
4799
+ * A spatial index over many ellipses: which one is under the pointer, and which ones a
4800
+ * rubber band touched.
4801
+ *
4802
+ * The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
4803
+ * items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
4804
+ * exact tests are in the ellipse's own frame: containment is one quadratic form, and the
4805
+ * distance to the outline is the true Euclidean distance (a few Newton steps on the
4806
+ * parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
4807
+ * round one. It imports neither React nor the DOM.
4808
+ *
4809
+ * An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
4810
+ * outline to draw or to pick.
4811
+ */
4812
+ function usable(e) {
4813
+ return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
4814
+ }
4815
+ /**
4816
+ * The axis-aligned bounding box of an ellipse.
4817
+ *
4818
+ * @param e - The ellipse.
4819
+ * @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
4820
+ */
4821
+ function ellipseBounds(e) {
4822
+ if (!usable(e)) return null;
4823
+ const c = Math.cos(e.angle ?? 0);
4824
+ const s = Math.sin(e.angle ?? 0);
4825
+ const hx = Math.hypot(e.rx * c, e.ry * s);
4826
+ const hy = Math.hypot(e.rx * s, e.ry * c);
4827
+ return [
4828
+ e.x - hx,
4829
+ e.y - hy,
4830
+ e.x + hx,
4831
+ e.y + hy
4832
+ ];
4833
+ }
4834
+ /** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
4835
+ function toFrame(e, x, y) {
4836
+ const c = Math.cos(e.angle ?? 0);
4837
+ const s = Math.sin(e.angle ?? 0);
4838
+ const dx = x - e.x;
4839
+ const dy = y - e.y;
4840
+ return {
4841
+ x: c * dx + s * dy,
4842
+ y: -s * dx + c * dy
4843
+ };
4844
+ }
4845
+ /**
4846
+ * Whether `(x, y)` is inside the ellipse (its outline counts as inside).
4847
+ *
4848
+ * @param e - The ellipse.
4849
+ * @param x - The query's x.
4850
+ * @param y - The query's y.
4851
+ * @returns `false` for a degenerate ellipse.
4852
+ */
4853
+ function pointInEllipse(e, x, y) {
4854
+ if (!usable(e)) return false;
4855
+ const p = toFrame(e, x, y);
4856
+ return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
4857
+ }
4858
+ /** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
4859
+ const NEWTON_STEPS = 12;
4860
+ /**
4861
+ * The Euclidean distance from `(x, y)` to the outline of an ellipse.
4862
+ *
4863
+ * The query is folded into the first quadrant of the ellipse's frame and the nearest outline
4864
+ * point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
4865
+ * better of a coarse scan so a thin ellipse and a query near its centre both converge.
4866
+ *
4867
+ * @param e - The ellipse.
4868
+ * @param x - The query's x.
4869
+ * @param y - The query's y.
4870
+ * @returns The distance; `Infinity` for a degenerate ellipse.
4871
+ */
4872
+ function distanceToEllipse(e, x, y) {
4873
+ if (!usable(e)) return Infinity;
4874
+ const p = toFrame(e, x, y);
4875
+ const px = Math.abs(p.x);
4876
+ const py = Math.abs(p.y);
4877
+ const a = e.rx;
4878
+ const b = e.ry;
4879
+ const squared = (t) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
4880
+ let t = 0;
4881
+ let best = Infinity;
4882
+ const SCAN = 16;
4883
+ for (let k = 0; k <= SCAN; k++) {
4884
+ const candidate = k / SCAN * (Math.PI / 2);
4885
+ const value = squared(candidate);
4886
+ if (value < best) {
4887
+ best = value;
4888
+ t = candidate;
4889
+ }
4890
+ }
4891
+ for (let i = 0; i < NEWTON_STEPS; i++) {
4892
+ const c = Math.cos(t);
4893
+ const s = Math.sin(t);
4894
+ const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
4895
+ const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
4896
+ if (!(Math.abs(df) > 1e-12)) break;
4897
+ const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
4898
+ if (squared(next) > squared(t)) break;
4899
+ t = next;
4900
+ }
4901
+ return Math.sqrt(squared(t));
4902
+ }
4903
+ /**
4904
+ * An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
4905
+ *
4906
+ * @param cx - Centre x, image pixels.
4907
+ * @param cy - Centre y, image pixels.
4908
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
4909
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
4910
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
4911
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
4912
+ */
4913
+ function ellipsePath(cx, cy, rx, ry, angle = 0) {
4914
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
4915
+ const dx = rx * Math.cos(angle);
4916
+ const dy = rx * Math.sin(angle);
4917
+ const degrees = round(angle * 180 / Math.PI);
4918
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
4919
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
4920
+ }
4921
+ /** Round to 1/1000 of an image pixel. */
4922
+ function round(value) {
4923
+ return Math.round(value * 1e3) / 1e3;
4924
+ }
4925
+ /**
4926
+ * Index a set of ellipses.
4927
+ *
4928
+ * @param items - The ellipses.
4929
+ * @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
4930
+ * @returns The index.
4931
+ */
4932
+ function buildEllipseIndex(items, cell) {
4933
+ const size = new Float64Array(items.length).fill(NaN);
4934
+ return {
4935
+ items,
4936
+ grid: buildAreaIndex(items.map((item, i) => {
4937
+ const box = ellipseBounds(item);
4938
+ if (box === null) return {
4939
+ id: i,
4940
+ points: []
4941
+ };
4942
+ size[i] = Math.PI * item.rx * item.ry;
4943
+ const [x0, y0, x1, y1] = box;
4944
+ return {
4945
+ id: i,
4946
+ points: [
4947
+ x0,
4948
+ y0,
4949
+ x1,
4950
+ y0,
4951
+ x1,
4952
+ y1,
4953
+ x0,
4954
+ y1
4955
+ ]
4956
+ };
4957
+ }), cell),
4958
+ size
4959
+ };
4960
+ }
4961
+ /**
4962
+ * The ellipse under a point: one whose outline passes within `radius`, or else one that
4963
+ * contains it.
4964
+ *
4965
+ * An outline is the more precise gesture, so it wins: among ellipses whose outline is within
4966
+ * `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
4967
+ * distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
4968
+ * another is picked rather than the outer one, then to the earlier one.
4969
+ *
4970
+ * @param index - The index.
4971
+ * @param p - The query, in image coordinates.
4972
+ * @param radius - How far from an outline the query still picks it, in image pixels.
4973
+ * @returns The ellipse, or `null`.
4974
+ */
4975
+ function nearestEllipse(index, p, radius) {
4976
+ if (!(radius >= 0)) return null;
4977
+ const { items, size } = index;
4978
+ let edge = null;
4979
+ let inner = null;
4980
+ for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4981
+ const e = items[a];
4982
+ const distance = distanceToEllipse(e, p.x, p.y);
4983
+ const hit = {
4984
+ id: e.id,
4985
+ index: a,
4986
+ inside: pointInEllipse(e, p.x, p.y),
4987
+ distance
4988
+ };
4989
+ if (distance <= radius) {
4990
+ if (edge === null || distance < edge.distance || distance === edge.distance && size[a] < size[edge.index]) edge = hit;
4991
+ } else if (hit.inside && (inner === null || size[a] < size[inner.index])) inner = hit;
4992
+ }
4993
+ return edge ?? inner;
4994
+ }
4995
+ /**
4996
+ * The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
4997
+ * inside the ellipse, or contains it.
4998
+ *
4999
+ * @param index - The index.
5000
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
5001
+ * its corners.
5002
+ * @returns Their ids, in the order the ellipses were given.
5003
+ */
5004
+ function ellipsesInRect(index, rect) {
5005
+ const x0 = Math.min(rect.x, rect.x + rect.width);
5006
+ const y0 = Math.min(rect.y, rect.y + rect.height);
5007
+ const x1 = Math.max(rect.x, rect.x + rect.width);
5008
+ const y1 = Math.max(rect.y, rect.y + rect.height);
5009
+ const out = [];
5010
+ for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
5011
+ const e = index.items[a];
5012
+ if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
5013
+ }
5014
+ return out;
5015
+ }
5016
+ /** Whether the filled ellipse and the rectangle share a point (both convex). */
5017
+ function rectMeetsEllipse(e, x0, y0, x1, y1) {
5018
+ if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
5019
+ const corners = [
5020
+ {
5021
+ x: x0,
5022
+ y: y0
5023
+ },
5024
+ {
5025
+ x: x1,
5026
+ y: y0
5027
+ },
5028
+ {
5029
+ x: x1,
5030
+ y: y1
5031
+ },
5032
+ {
5033
+ x: x0,
5034
+ y: y1
5035
+ }
5036
+ ];
5037
+ if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
5038
+ for (let k = 0; k < 4; k++) {
5039
+ const a = toFrame(e, corners[k].x, corners[k].y);
5040
+ const b = toFrame(e, corners[(k + 1) % 4].x, corners[(k + 1) % 4].y);
5041
+ const ux = (b.x - a.x) / e.rx;
5042
+ const uy = (b.y - a.y) / e.ry;
5043
+ const vx = a.x / e.rx;
5044
+ const vy = a.y / e.ry;
5045
+ const len2 = ux * ux + uy * uy;
5046
+ const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
5047
+ if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
5048
+ }
5049
+ return false;
5050
+ }
5051
+ //#endregion
5052
+ //#region src/components/EllipseSet.tsx
5053
+ /**
5054
+ * Many ellipses over the image whose size is data, hoverable and selectable: fitted ring
5055
+ * edges, edge-bit dots, drawn ellipse annotations.
5056
+ *
5057
+ * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
5058
+ * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
5059
+ * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
5060
+ * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
5061
+ * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
5062
+ */
5063
+ const HALO$3 = overlayRole("halo");
5064
+ /** The outline of an item, its semi-axes raised to `floor` image pixels. */
5065
+ function outlineOf(item, floor) {
5066
+ return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);
5067
+ }
5068
+ /** The concatenated outlines of the items at `indices`. */
5069
+ function batchPath(items, indices, floor) {
5070
+ let d = "";
5071
+ for (const i of indices) d += outlineOf(items[i], floor);
5072
+ return d;
5073
+ }
5074
+ /**
5075
+ * The layer's entry in the stage's hit registry: a component, not a hook call in
5076
+ * `EllipseSet`, so `pickable={false}` really unregisters it. Renders nothing.
5077
+ */
5078
+ function EllipseHits({ index, layerId, priority, onHover, onPress }) {
5079
+ useStageHitLayer({
5080
+ layerId,
5081
+ priority,
5082
+ pick: (point, radius) => {
5083
+ const hit = nearestEllipse(index, point, radius);
5084
+ return hit ? {
5085
+ id: hit.id,
5086
+ dist: hit.inside ? 0 : hit.distance
5087
+ } : null;
5088
+ },
5089
+ onHover,
5090
+ onPress: onPress ? (id, event) => onPress(id, event) : void 0
5091
+ });
5092
+ return null;
5093
+ }
5094
+ /**
5095
+ * A batched set of ellipses inside an `ImageStage`.
5096
+ *
5097
+ * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
5098
+ * the stroke is a screen constant.
5099
+ * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
5100
+ * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
5101
+ * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
5102
+ * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
5103
+ * an outline picks that ellipse, else the smallest ellipse containing the point.
5104
+ * `onHoverChange` and `onItemPress` here, and `useStageHitTest` for an app that arbitrates
5105
+ * between layers. `pickable={false}` turns it off.
5106
+ *
5107
+ * The SVG carries `data-ellipses` (the count) and `data-hovered` (the hovered id).
5108
+ */
5109
+ function EllipseSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, pickable = true, layerId, priority = STAGE_HIT_PRIORITY.area, halo = true, minRadius, selectionStroke = overlayRole("selection"), label }) {
5110
+ const stage = useStage();
5111
+ const px = useScreenPx();
5112
+ const unit = px(1);
5113
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
5114
+ const isDimmed = useMemo(() => {
5115
+ if (typeof dimmed === "function") return dimmed;
5116
+ const set = new Set(dimmed ?? []);
5117
+ return (id) => set.has(id);
5118
+ }, [dimmed]);
5119
+ const index = useMemo(() => pickable ? buildEllipseIndex(items) : null, [items, pickable]);
5120
+ const [ownHover, setOwnHover] = useState(null);
5121
+ const hoverId = hoveredId !== void 0 ? hoveredId : pickable ? ownHover : null;
5122
+ const batches = useMemo(() => {
5123
+ const normal = /* @__PURE__ */ new Map();
5124
+ const picked = {
5125
+ key: "selected",
5126
+ role: "selection",
5127
+ dashed: false,
5128
+ opacity: 1,
5129
+ dim: false,
5130
+ indices: []
5131
+ };
5132
+ items.forEach((item, i) => {
5133
+ if (selectedSet.has(item.id)) {
5134
+ picked.indices.push(i);
5135
+ return;
5136
+ }
5137
+ const itemRole = item.role ?? role;
5138
+ const dashed = item.dashed ?? false;
5139
+ const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;
5140
+ const dim = isDimmed(item.id);
5141
+ const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? "dashed" : "solid"}|${opacity}`;
5142
+ let batch = normal.get(key);
5143
+ if (!batch) {
5144
+ batch = {
5145
+ key,
5146
+ role: itemRole,
5147
+ dashed,
5148
+ opacity,
5149
+ dim,
5150
+ indices: []
5151
+ };
5152
+ normal.set(key, batch);
5153
+ }
5154
+ batch.indices.push(i);
5155
+ });
5156
+ return {
5157
+ normal: [...normal.values()],
5158
+ picked: picked.indices.length > 0 ? picked : null
5159
+ };
5160
+ }, [
5161
+ items,
5162
+ role,
5163
+ selectedSet,
5164
+ isDimmed
5165
+ ]);
5166
+ const floor = minRadius !== void 0 ? minRadius * unit : 0;
5167
+ const normalPaths = useMemo(() => batches.normal.map((batch) => ({
5168
+ batch,
5169
+ d: batchPath(items, batch.indices, floor)
5170
+ })), [
5171
+ batches,
5172
+ items,
5173
+ floor
5174
+ ]);
5175
+ const pickedPath = useMemo(() => batches.picked ? batchPath(items, batches.picked.indices, floor) : "", [
5176
+ batches,
5177
+ items,
5178
+ floor
5179
+ ]);
5180
+ const hoverPositions = [];
5181
+ if (hoverId !== null) items.forEach((item, i) => {
5182
+ if (item.id === hoverId) hoverPositions.push(i);
5183
+ });
5184
+ const hoverSelected = hoverId !== null && selectedSet.has(hoverId);
5185
+ const widthOf = (itemRole, state) => {
5186
+ const thin = itemRole === "model" || itemRole === "structure";
5187
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
5188
+ };
5189
+ const dash = `${px(4)} ${px(3)}`;
5190
+ return /* @__PURE__ */ jsxs("svg", {
5191
+ viewBox: imageViewBox(stage.image),
5192
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
5193
+ ...label !== void 0 ? {
5194
+ role: "img",
5195
+ "aria-label": label
5196
+ } : { "aria-hidden": true },
5197
+ "data-ellipses": items.length,
5198
+ "data-hovered": hoverId ?? void 0,
5199
+ children: [index && /* @__PURE__ */ jsx(EllipseHits, {
5200
+ index,
5201
+ layerId,
5202
+ priority,
5203
+ onHover: (id) => {
5204
+ setOwnHover(id);
5205
+ onHoverChange?.(id);
5206
+ },
5207
+ onPress: onItemPress
5208
+ }), /* @__PURE__ */ jsxs("g", {
5209
+ fill: "none",
5210
+ strokeLinecap: "round",
5211
+ strokeLinejoin: "round",
5212
+ children: [
5213
+ normalPaths.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
5214
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
5215
+ children: [halo && /* @__PURE__ */ jsx("path", {
5216
+ d,
5217
+ stroke: HALO$3,
5218
+ strokeWidth: widthOf(batch.role, "default") + px(2),
5219
+ strokeDasharray: batch.dashed ? dash : void 0,
5220
+ opacity: .6 * batch.opacity
5221
+ }), /* @__PURE__ */ jsx("path", {
5222
+ "data-batch": batch.key,
5223
+ d,
5224
+ stroke: overlayRole(batch.role),
5225
+ strokeWidth: widthOf(batch.role, "default"),
5226
+ strokeDasharray: batch.dashed ? dash : void 0,
5227
+ opacity: batch.opacity
5228
+ })]
5229
+ }, batch.key)),
5230
+ batches.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
5231
+ d: pickedPath,
5232
+ stroke: HALO$3,
5233
+ strokeWidth: widthOf("selection", "selected") + px(2)
5234
+ }), /* @__PURE__ */ jsx("path", {
5235
+ "data-selected-ellipses": "",
5236
+ d: pickedPath,
5237
+ stroke: selectionStroke,
5238
+ strokeWidth: widthOf("selection", "selected")
5239
+ })] }),
5240
+ hoverPositions.map((position) => {
5241
+ const item = items[position];
5242
+ const itemRole = item.role ?? role;
5243
+ const state = hoverSelected ? "selected" : "hover";
5244
+ return /* @__PURE__ */ jsxs("g", { children: [halo && /* @__PURE__ */ jsx("path", {
5245
+ d: outlineOf(item, floor),
5246
+ stroke: HALO$3,
5247
+ strokeWidth: widthOf(itemRole, state) + px(2)
5248
+ }), /* @__PURE__ */ jsx("path", {
5249
+ "data-hovered-ellipse": "",
5250
+ d: outlineOf(item, floor),
5251
+ stroke: hoverSelected ? selectionStroke : overlayRole(itemRole),
5252
+ strokeWidth: widthOf(itemRole, state)
5253
+ })] }, position);
5254
+ })
5255
+ ]
5256
+ })]
5257
+ });
5258
+ }
5259
+ //#endregion
4592
5260
  //#region src/components/gridEdges.ts
4593
5261
  /** Indices past this magnitude are not hashed (the key must stay an exact integer). */
4594
5262
  const LIMIT = 2 ** 25;
@@ -4967,8 +5635,6 @@ function colourPlane(plane, colormap, range, channel) {
4967
5635
  height: plane.height
4968
5636
  };
4969
5637
  }
4970
- //#endregion
4971
- //#region src/components/shapeEdit.ts
4972
5638
  /**
4973
5639
  * A point of image space in the shape's own frame: origin at its centre, axes along its sides.
4974
5640
  *
@@ -5186,6 +5852,83 @@ function sameShape(a, b, epsilon = 1e-6) {
5186
5852
  if (a === null || b === null) return a === b;
5187
5853
  return Math.abs(a.cx - b.cx) < epsilon && Math.abs(a.cy - b.cy) < epsilon && Math.abs(a.width - b.width) < epsilon && Math.abs(a.height - b.height) < epsilon && Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon;
5188
5854
  }
5855
+ /**
5856
+ * How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is
5857
+ * a first-order estimate, which is exact on the axes and good to a few percent elsewhere.
5858
+ */
5859
+ function distanceOutside(shape, kind, p) {
5860
+ const u = toShapeFrame(shape, p);
5861
+ const a = Math.max(shape.width / 2, 1e-9);
5862
+ const b = Math.max(shape.height / 2, 1e-9);
5863
+ if (kind === "rect") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));
5864
+ const f = (u.x / a) ** 2 + (u.y / b) ** 2;
5865
+ if (f <= 1) return 0;
5866
+ const g = Math.hypot(u.x / (a * a), u.y / (b * b));
5867
+ return (f - Math.sqrt(f)) / g;
5868
+ }
5869
+ /**
5870
+ * What a press on an editable shape means, decided once for the whole editor so that a small
5871
+ * shape's interior never steals a press meant for its handle.
5872
+ *
5873
+ * In order:
5874
+ * 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen
5875
+ * distance from the press is within `radius` plus the handle's half size: resize or rotate.
5876
+ * 2. Inside the shape, or within `radius` screen pixels of its outline: move.
5877
+ * 3. Otherwise `null`: the press is declined and belongs to whatever is below.
5878
+ *
5879
+ * @param shape - The shape.
5880
+ * @param kind - `"rect"` or `"ellipse"` (the outline differs).
5881
+ * @param scale - The view scale: screen pixels per image pixel.
5882
+ * @param point - The press, in image coordinates.
5883
+ * @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.
5884
+ * @param rotatable - Whether the rotation handle exists. Defaults to `true`.
5885
+ * @returns The decision, or `null`.
5886
+ */
5887
+ function shapePress(shape, kind, scale, point, radius, rotatable = true) {
5888
+ const best = {
5889
+ press: null,
5890
+ distance: Infinity
5891
+ };
5892
+ const consider = (candidate, at, half) => {
5893
+ const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;
5894
+ if (d <= radius + half && d < best.distance) {
5895
+ best.press = candidate;
5896
+ best.distance = d;
5897
+ }
5898
+ };
5899
+ for (const handle of ROI_HANDLES) consider({
5900
+ kind: "resize",
5901
+ handle
5902
+ }, shapeHandlePoint(shape, handle), 9 / 2);
5903
+ if (rotatable) consider({ kind: "rotate" }, rotationHandlePoint(shape, 24 / scale), 5);
5904
+ if (best.press) return best.press;
5905
+ return distanceOutside(shape, kind, point) * scale <= radius ? { kind: "move" } : null;
5906
+ }
5907
+ //#endregion
5908
+ //#region src/components/stage/useCoarsePointer.ts
5909
+ /**
5910
+ * Whether the device's primary pointer is coarse (a finger), for sizing a press target that
5911
+ * must exist before any pointer event says which pointer is coming.
5912
+ */
5913
+ const QUERY = "(pointer: coarse)";
5914
+ function mediaList() {
5915
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(QUERY) : null;
5916
+ }
5917
+ function subscribe(onChange) {
5918
+ const list = mediaList();
5919
+ list?.addEventListener("change", onChange);
5920
+ return () => list?.removeEventListener("change", onChange);
5921
+ }
5922
+ const snapshot = () => mediaList()?.matches ?? false;
5923
+ /**
5924
+ * Whether `(pointer: coarse)` matches: the primary pointer is a finger. `false` on the server
5925
+ * and wherever `matchMedia` is missing.
5926
+ *
5927
+ * @returns `true` on a touch-first device.
5928
+ */
5929
+ function useCoarsePointer() {
5930
+ return useSyncExternalStore(subscribe, snapshot, () => false);
5931
+ }
5189
5932
  //#endregion
5190
5933
  //#region src/components/ShapeEditor.tsx
5191
5934
  /**
@@ -5196,11 +5939,6 @@ function sameShape(a, b, epsilon = 1e-6) {
5196
5939
  * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
5197
5940
  * this is the gestures, the handles and the keyboard.
5198
5941
  */
5199
- /** Handle square side, in screen pixels. */
5200
- const HANDLE_PX = 9;
5201
- /** Rotation handle radius, and its distance past the top side, in screen pixels. */
5202
- const ROTATE_RADIUS_PX = 5;
5203
- const ROTATE_OFFSET_PX = 24;
5204
5942
  /** Outline width, in screen pixels. */
5205
5943
  const STROKE_PX$1 = 1.5;
5206
5944
  /** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
@@ -5212,7 +5950,17 @@ const HALO$1 = overlayRole("halo");
5212
5950
  *
5213
5951
  * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
5214
5952
  * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
5215
- * `minSize` rather than flipping. The interior moves it.
5953
+ * `minSize` rather than flipping. The interior moves it, and so does the band along its
5954
+ * outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin
5955
+ * or rotated shape is grabbed. The band is as wide as the device's primary pointer needs
5956
+ * (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to
5957
+ * 12 px outside the outline reaches the layers below instead of the editor.
5958
+ * - **Press order.** One decision serves every part of the editor: the nearest handle first,
5959
+ * then the interior or outline band (move), then nothing. A small shape's interior does not
5960
+ * steal a press meant for a handle, and a press that hits none of them is not claimed, so
5961
+ * it reaches whatever is below, or the stage.
5962
+ * - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit
5963
+ * cancels it (the shape reverts, nothing is committed) and is left to the stage.
5216
5964
  * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
5217
5965
  * round to 15°.
5218
5966
  * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
@@ -5230,23 +5978,78 @@ const HALO$1 = overlayRole("halo");
5230
5978
  function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, rotatable = true, minSize = 5, label = "Shape", stroke = overlayRole("selection") }) {
5231
5979
  const stage = useStage();
5232
5980
  const px = useScreenPx();
5981
+ const coarse = useCoarsePointer();
5233
5982
  const dragRef = useRef(null);
5234
5983
  const lastRef = useRef(null);
5984
+ const stopWatchRef = useRef(null);
5235
5985
  const report = (next) => {
5236
5986
  lastRef.current = next;
5237
5987
  onValueChange(next);
5238
5988
  };
5239
- const begin = (event, drag) => {
5240
- if (stage.panMode || event.button !== 0) return;
5989
+ /** Abandon an edit in flight: the shape reverts and nothing is committed. */
5990
+ const cancelEdit = () => {
5991
+ const drag = dragRef.current;
5992
+ dragRef.current = null;
5993
+ stopWatchRef.current?.();
5994
+ stopWatchRef.current = null;
5995
+ if (drag && lastRef.current) onValueChange(drag.start);
5996
+ lastRef.current = null;
5997
+ };
5998
+ useEffect(() => () => stopWatchRef.current?.(), []);
5999
+ /**
6000
+ * The one press decision for the whole editor: every target (the interior, the outline
6001
+ * band, a handle) comes here, and the nearest handle wins over the interior. A declined
6002
+ * press is not claimed and bubbles to the stage.
6003
+ */
6004
+ const press = (event) => {
6005
+ if (!value || stage.panMode) return;
6006
+ const touch = event.pointerType === "touch";
6007
+ if (!touch && event.button !== 0) return;
6008
+ if (dragRef.current) {
6009
+ if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();
6010
+ return;
6011
+ }
6012
+ const at = stage.toImage({
6013
+ x: event.clientX,
6014
+ y: event.clientY
6015
+ });
6016
+ const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);
6017
+ if (!decision) return;
5241
6018
  event.stopPropagation();
5242
6019
  event.preventDefault();
5243
- event.currentTarget.setPointerCapture(event.pointerId);
5244
- dragRef.current = drag;
6020
+ try {
6021
+ event.currentTarget.setPointerCapture(event.pointerId);
6022
+ } catch {}
6023
+ const base = {
6024
+ start: value,
6025
+ moved: false,
6026
+ pointerId: event.pointerId
6027
+ };
6028
+ dragRef.current = decision.kind === "move" ? {
6029
+ ...base,
6030
+ kind: "move",
6031
+ from: at
6032
+ } : decision.kind === "resize" ? {
6033
+ ...base,
6034
+ kind: "resize",
6035
+ handle: decision.handle
6036
+ } : {
6037
+ ...base,
6038
+ kind: "rotate"
6039
+ };
5245
6040
  lastRef.current = null;
6041
+ if (touch) {
6042
+ const id = event.pointerId;
6043
+ const other = (e) => {
6044
+ if (e.pointerId !== id && e.pointerType === "touch") cancelEdit();
6045
+ };
6046
+ window.addEventListener("pointerdown", other);
6047
+ stopWatchRef.current = () => window.removeEventListener("pointerdown", other);
6048
+ }
5246
6049
  };
5247
6050
  const onMove = (event) => {
5248
6051
  const drag = dragRef.current;
5249
- if (!drag) return;
6052
+ if (!drag || drag.pointerId !== event.pointerId) return;
5250
6053
  event.stopPropagation();
5251
6054
  const p = stage.toImage({
5252
6055
  x: event.clientX,
@@ -5259,11 +6062,24 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5259
6062
  };
5260
6063
  const onEnd = (event) => {
5261
6064
  const drag = dragRef.current;
5262
- if (!drag) return;
6065
+ if (!drag || drag.pointerId !== event.pointerId) return;
5263
6066
  event.stopPropagation();
5264
6067
  dragRef.current = null;
6068
+ stopWatchRef.current?.();
6069
+ stopWatchRef.current = null;
5265
6070
  if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
5266
6071
  };
6072
+ /** The handlers every target of the editor shares. */
6073
+ const gesture = {
6074
+ onPointerDown: press,
6075
+ onPointerMove: onMove,
6076
+ onPointerUp: onEnd,
6077
+ onPointerCancel: (event) => {
6078
+ if (dragRef.current?.pointerId === event.pointerId) cancelEdit();
6079
+ },
6080
+ onLostPointerCapture: onEnd,
6081
+ onDoubleClick: (event) => event.stopPropagation()
6082
+ };
5267
6083
  const onKeyDown = (event) => {
5268
6084
  if (!editable || value === null) return;
5269
6085
  if (rotatable && (event.key === "[" || event.key === "]")) {
@@ -5309,9 +6125,9 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5309
6125
  };
5310
6126
  const stem = value ? {
5311
6127
  from: shapeHandlePoint(value, "n"),
5312
- to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX))
6128
+ to: rotationHandlePoint(value, px(24))
5313
6129
  } : null;
5314
- const handleSize = px(HANDLE_PX);
6130
+ const handleSize = px(9);
5315
6131
  return /* @__PURE__ */ jsxs("svg", {
5316
6132
  viewBox: imageViewBox(stage.image),
5317
6133
  className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
@@ -5345,6 +6161,19 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5345
6161
  strokeDasharray: `${px(4)} ${px(3)}`,
5346
6162
  opacity: .6
5347
6163
  }),
6164
+ editable && value && /* @__PURE__ */ jsx(Outline, {
6165
+ kind,
6166
+ shape: value,
6167
+ "data-shape-band": "",
6168
+ fill: "none",
6169
+ stroke: "transparent",
6170
+ strokeWidth: px(2 * (coarse ? 12 : 6)),
6171
+ strokeLinejoin: "round",
6172
+ "aria-hidden": true,
6173
+ className: "pointer-events-auto cursor-move",
6174
+ style: { pointerEvents: "stroke" },
6175
+ ...gesture
6176
+ }),
5348
6177
  editable && value && /* @__PURE__ */ jsx(Outline, {
5349
6178
  kind,
5350
6179
  shape: value,
@@ -5354,20 +6183,9 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5354
6183
  "aria-label": `${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt(value.rotation * 180 / Math.PI)}°`,
5355
6184
  "aria-roledescription": kind === "rect" ? "rotated rectangle" : "ellipse",
5356
6185
  className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
5357
- onPointerDown: (event) => begin(event, {
5358
- kind: "move",
5359
- from: stage.toImage({
5360
- x: event.clientX,
5361
- y: event.clientY
5362
- }),
5363
- start: value,
5364
- moved: false
5365
- }),
5366
- onPointerMove: onMove,
5367
- onPointerUp: onEnd,
5368
- onLostPointerCapture: onEnd,
5369
- onKeyDown,
5370
- onDoubleClick: (event) => event.stopPropagation()
6186
+ strokeWidth: px(2),
6187
+ ...gesture,
6188
+ onKeyDown
5371
6189
  }),
5372
6190
  editable && value && rotatable && stem && /* @__PURE__ */ jsxs(Fragment, { children: [
5373
6191
  /* @__PURE__ */ jsx("line", {
@@ -5390,21 +6208,13 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5390
6208
  "data-handle": "rotate",
5391
6209
  cx: stem.to.x,
5392
6210
  cy: stem.to.y,
5393
- r: px(ROTATE_RADIUS_PX),
6211
+ r: px(5),
5394
6212
  fill: stroke,
5395
6213
  stroke: HALO$1,
5396
6214
  strokeWidth: px(1),
5397
6215
  className: "pointer-events-auto",
5398
6216
  style: { cursor: "grab" },
5399
- onPointerDown: (event) => begin(event, {
5400
- kind: "rotate",
5401
- start: value,
5402
- moved: false
5403
- }),
5404
- onPointerMove: onMove,
5405
- onPointerUp: onEnd,
5406
- onLostPointerCapture: onEnd,
5407
- onDoubleClick: (event) => event.stopPropagation()
6217
+ ...gesture
5408
6218
  })
5409
6219
  ] }),
5410
6220
  editable && value && ROI_HANDLES.map((handle) => {
@@ -5420,16 +6230,7 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5420
6230
  strokeWidth: px(1),
5421
6231
  className: "pointer-events-auto",
5422
6232
  style: { cursor: shapeHandleCursor(handle, value.rotation) },
5423
- onPointerDown: (event) => begin(event, {
5424
- kind: "resize",
5425
- handle,
5426
- start: value,
5427
- moved: false
5428
- }),
5429
- onPointerMove: onMove,
5430
- onPointerUp: onEnd,
5431
- onLostPointerCapture: onEnd,
5432
- onDoubleClick: (event) => event.stopPropagation()
6233
+ ...gesture
5433
6234
  }, handle);
5434
6235
  })
5435
6236
  ]
@@ -5543,13 +6344,13 @@ function DraftShape({ shape, role = "selection", halo = true }) {
5543
6344
  });
5544
6345
  }
5545
6346
  /** An ellipse with the given centre and radii as two arcs. */
5546
- function ellipsePath(cx, cy, rx, ry) {
6347
+ function ellipsePath$1(cx, cy, rx, ry) {
5547
6348
  return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
5548
6349
  }
5549
6350
  function draftParts(shape, unit) {
5550
6351
  switch (shape.kind) {
5551
6352
  case "point": return {
5552
- outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit),
6353
+ outline: ellipsePath$1(shape.x, shape.y, 8 * unit, 8 * unit),
5553
6354
  region: false,
5554
6355
  closing: null,
5555
6356
  vertices: `M${shape.x} ${shape.y}h0`
@@ -5564,7 +6365,7 @@ function draftParts(shape, unit) {
5564
6365
  case "ellipse": {
5565
6366
  const box = rectFromCorners(shape.from, shape.to);
5566
6367
  return {
5567
- outline: shape.kind === "rect" ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z` : ellipsePath(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2),
6368
+ outline: shape.kind === "rect" ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z` : ellipsePath$1(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2),
5568
6369
  region: true,
5569
6370
  closing: null,
5570
6371
  vertices: null
@@ -5883,6 +6684,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5883
6684
  })] });
5884
6685
  }
5885
6686
  //#endregion
5886
- export { AreaSet, ContourEditor, DraftShape, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestPoint, nearestPolyline, normalizeAngle, overlayRole, paintMask, planeRange, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
6687
+ export { AreaSet, ContourEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestPoint, nearestPolyline, normalizeAngle, overlayRole, paintMask, planeRange, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
5887
6688
 
5888
6689
  //# sourceMappingURL=index.js.map