@vitavision/stage2d 0.10.0 → 0.12.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. */
@@ -102,6 +127,16 @@ function toImage(view, p) {
102
127
  function insideImage(p, image) {
103
128
  return p.x >= -.5 && p.y >= -.5 && p.x < image.width - .5 && p.y < image.height - .5;
104
129
  }
130
+ /**
131
+ * An image coordinate held to the image's extent, `[-0.5, w - 0.5] x [-0.5, h - 0.5]` in the
132
+ * pixel-centre convention: the point on the frame's edge nearest to `p`.
133
+ */
134
+ function clampToImage(p, image) {
135
+ return {
136
+ x: Math.min(image.width - PIXEL_CENTRE, Math.max(-.5, p.x)),
137
+ y: Math.min(image.height - PIXEL_CENTRE, Math.max(-.5, p.y))
138
+ };
139
+ }
105
140
  /** A length in image pixels that covers `css` screen pixels at this view. */
106
141
  function imageLengthFor(view, css) {
107
142
  return view.scale > 0 ? css / view.scale : css;
@@ -129,20 +164,26 @@ function scaleRange(box, image, options = {}) {
129
164
  /**
130
165
  * Keep the view legal: scale inside its range, and the image never dragged off screen.
131
166
  *
132
- * An axis where the scaled image is smaller than the viewport is centred rather than left
133
- * where a drag put it — free-floating pixels in a grey field is a way to be lost with no
134
- * visible handle to get back. An axis where it is larger is held so the viewport stays
135
- * covered.
167
+ * With the default `panBounds: "cover"`, an axis where the scaled image is smaller than the
168
+ * viewport is centred rather than left where a drag put it — free-floating pixels in a grey
169
+ * field is a way to be lost with no visible handle to get back — and an axis where it is
170
+ * larger is held so the viewport stays covered. With `"center"`, each axis only keeps some
171
+ * image point at or past the viewport's centre.
136
172
  */
137
173
  function clampView(view, box, image, options = {}) {
138
174
  const [min, max] = scaleRange(box, image, options);
139
175
  const scale = clamp$2(view.scale, min, max);
176
+ const axis = options.panBounds === "center" ? centreAxis : clampAxis;
140
177
  return {
141
178
  scale,
142
- tx: clampAxis(view.tx, box.width, image.width * scale),
143
- ty: clampAxis(view.ty, box.height, image.height * scale)
179
+ tx: axis(view.tx, box.width, image.width * scale),
180
+ ty: axis(view.ty, box.height, image.height * scale)
144
181
  };
145
182
  }
183
+ /** `"center"` bounds: the content's far edge may come to the centre, and its near edge too. */
184
+ function centreAxis(t, boxLength, contentLength) {
185
+ return clamp$2(t, boxLength / 2 - contentLength, boxLength / 2);
186
+ }
146
187
  function clampAxis(t, boxLength, contentLength) {
147
188
  if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
148
189
  return clamp$2(t, boxLength - contentLength, 0);
@@ -176,9 +217,9 @@ function frameRect(box, image, rect, pad = .15) {
176
217
  * that was *fit* re-fits instead, because fit is a relationship to the viewport rather than
177
218
  * a particular pair of numbers.
178
219
  */
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);
220
+ function preserveCenter(view, from, to, image, options = {}, fit = {}) {
221
+ if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);
222
+ if (isFit(view, from, image, fit)) return fitView(to, image, fit);
182
223
  const centre = toImage(view, {
183
224
  x: from.width / 2,
184
225
  y: from.height / 2
@@ -215,6 +256,15 @@ function formatScale(scale) {
215
256
  function clamp$2(value, low, high) {
216
257
  return Math.min(high, Math.max(low, value));
217
258
  }
259
+ /**
260
+ * The hit-test tolerance for a pointer, in screen pixels.
261
+ *
262
+ * @param pointerType - `PointerEvent.pointerType`.
263
+ * @returns 12 for `"touch"`, 6 otherwise.
264
+ */
265
+ function hitRadiusPx(pointerType) {
266
+ return pointerType === "touch" ? 12 : 6;
267
+ }
218
268
  const BUTTON_CODE = {
219
269
  left: 0,
220
270
  middle: 1,
@@ -389,11 +439,19 @@ function createHitRegistry() {
389
439
  * with the image.
390
440
  */
391
441
  const WHEEL_SENSITIVITY = .0015;
442
+ /**
443
+ * How long after the last view change the stage box keeps `will-change: transform`.
444
+ *
445
+ * The hint keeps a pan on the compositor (without it every overlay path is repainted each
446
+ * frame: 130 ms against 17 ms with 4,000 corners in view under software raster), but Chromium
447
+ * then keeps the layer at the raster scale it had when the hint was applied, so the stage
448
+ * would stay blurry after a zoom. Measured in `willChange.browser.test.ts`: always on, the
449
+ * edge of a zoomed image ramps over 6 px and a 1 px line smears to 10; cleared once the view
450
+ * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.
451
+ */
452
+ const MOVING_SETTLE_MS = 150;
392
453
  /** How far a press may travel and still count as a click rather than a pan. */
393
454
  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
455
  /** The view before the viewport has been measured — nothing is on screen yet. */
398
456
  const UNMEASURED_VIEW = {
399
457
  scale: 1,
@@ -417,12 +475,17 @@ function useStage() {
417
475
  * size, so an overlay drawn in image coordinates stays registered with the photograph at
418
476
  * any zoom and window size. Layers read the transform through `useStage`.
419
477
  *
478
+ * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while
479
+ * the view changes and for 150 ms after, so a pan stays on the compositor and the layer
480
+ * re-rasterises sharp once the view settles.
481
+ *
420
482
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
421
483
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
422
484
  * or absent.
423
485
  */
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 }) {
486
+ 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
487
  const viewportRef = useRef(null);
488
+ const boxRef = useRef(null);
426
489
  const [box, setBox] = useState({
427
490
  width: 0,
428
491
  height: 0
@@ -434,24 +497,41 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
434
497
  const [panning, setPanning] = useState(false);
435
498
  const [spaceHeld, setSpaceHeld] = useState(false);
436
499
  const panMode = panTool || spaceHeld;
500
+ const fitOpts = useMemo(() => ({
501
+ padding: fitOptions?.padding,
502
+ upscale: fitOptions?.upscale
503
+ }), [fitOptions?.padding, fitOptions?.upscale]);
504
+ const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW), [
505
+ view,
506
+ box,
507
+ image,
508
+ opening,
509
+ fitOpts
510
+ ]);
437
511
  const latestRef = useRef({
438
512
  view,
513
+ effective: UNMEASURED_VIEW,
439
514
  box,
440
515
  image,
441
516
  clamp,
442
517
  onView,
443
- opening
518
+ opening,
519
+ fitOpts
444
520
  });
445
521
  useLayoutEffect(() => {
446
522
  latestRef.current = {
447
523
  view,
524
+ effective,
448
525
  box,
449
526
  image,
450
527
  clamp,
451
528
  onView,
452
- opening
529
+ opening,
530
+ fitOpts
453
531
  };
454
532
  });
533
+ /** Whether the opening view of the current `null` view has been reported. */
534
+ const openedRef = useRef(false);
455
535
  /** The view to come back to when a double-click leaves fit. */
456
536
  const previousRef = useRef(null);
457
537
  const dragRef = useRef(null);
@@ -462,16 +542,50 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
462
542
  /** The registry the stage's layers answer hit-tests through. */
463
543
  const [hits] = useState(() => createHitRegistry());
464
544
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
465
- const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW), [
545
+ useEffect(() => {
546
+ const element = boxRef.current;
547
+ if (!element) return;
548
+ element.style.willChange = "transform";
549
+ element.dataset["moving"] = "";
550
+ const timer = setTimeout(() => {
551
+ element.style.willChange = "";
552
+ delete element.dataset["moving"];
553
+ }, MOVING_SETTLE_MS);
554
+ return () => clearTimeout(timer);
555
+ }, [
556
+ effective.scale,
557
+ effective.tx,
558
+ effective.ty
559
+ ]);
560
+ /** Report a view with its cause and the viewport it was made for (the measured one by default). */
561
+ const emit = useCallback((next, cause, box) => {
562
+ const { box: b, onView: report } = latestRef.current;
563
+ report(next, {
564
+ cause,
565
+ box: box ?? b
566
+ });
567
+ }, []);
568
+ const commit = useCallback((next, cause = "command") => {
569
+ const { box: b, image: i, clamp: c } = latestRef.current;
570
+ emit(b.width > 0 ? clampView(next, b, i, c) : next, cause);
571
+ }, [emit]);
572
+ useEffect(() => {
573
+ if (view !== null) {
574
+ openedRef.current = false;
575
+ return;
576
+ }
577
+ if (box.width > 0 && !openedRef.current) {
578
+ openedRef.current = true;
579
+ emit(openingView(opening, box, image, fitOpts), "measure");
580
+ }
581
+ }, [
466
582
  view,
467
583
  box,
468
584
  image,
469
- opening
585
+ opening,
586
+ fitOpts,
587
+ emit
470
588
  ]);
471
- const commit = useCallback((next) => {
472
- const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
473
- report(b.width > 0 ? clampView(next, b, i, c) : next);
474
- }, []);
475
589
  const attachViewport = useCallback((element) => {
476
590
  viewportRef.current = element;
477
591
  if (!element) return;
@@ -485,10 +599,12 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
485
599
  };
486
600
  measuredRef.current = next;
487
601
  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));
490
- else if (!(current.width > 0)) report(clampView(v, next, i, c));
491
- else report(preserveCenter(v, current, next, i, c));
602
+ const { view: v, image: i, clamp: c, opening: o, fitOpts: f } = latestRef.current;
603
+ if (v === null) {
604
+ openedRef.current = true;
605
+ emit(openingView(o, next, i, f), "measure", next);
606
+ } else if (!(current.width > 0)) emit(clampView(v, next, i, c), "measure", next);
607
+ else emit(preserveCenter(v, current, next, i, c, f), "measure", next);
492
608
  };
493
609
  measure(contentSize(element));
494
610
  const observer = new ResizeObserver((entries) => {
@@ -498,15 +614,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
498
614
  observer.observe(element);
499
615
  const onWheel = (event) => {
500
616
  event.preventDefault();
501
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
502
- if (v === null || !(b.width > 0)) return;
617
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
618
+ if (!(b.width > 0)) return;
503
619
  const origin = viewportOrigin(element);
504
620
  const [min, max] = scaleRange(b, i, c);
505
621
  const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
506
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, v.scale * factor)), {
622
+ const scale = Math.min(max, Math.max(min, v.scale * factor));
623
+ const anchor = {
507
624
  x: event.clientX - origin.x,
508
625
  y: event.clientY - origin.y
509
- }), b, i, c));
626
+ };
627
+ emit(clampView(zoomAbout(v, scale, anchor), b, i, c), "gesture");
510
628
  };
511
629
  element.addEventListener("wheel", onWheel, { passive: false });
512
630
  return () => {
@@ -514,7 +632,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
514
632
  element.removeEventListener("wheel", onWheel);
515
633
  viewportRef.current = null;
516
634
  };
517
- }, []);
635
+ }, [emit]);
518
636
  useEffect(() => {
519
637
  if (!shortcuts) return;
520
638
  const down = (event) => {
@@ -535,8 +653,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
535
653
  }, [shortcuts]);
536
654
  const clientToImage = useCallback((p) => {
537
655
  const element = viewportRef.current;
538
- const { view: v } = latestRef.current;
539
- if (!element || v === null) return {
656
+ const { view: held, effective: v, box: b } = latestRef.current;
657
+ if (!element || held === null && !(b.width > 0)) return {
540
658
  x: 0,
541
659
  y: 0
542
660
  };
@@ -548,8 +666,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
548
666
  }, []);
549
667
  const imageToClient = useCallback((p) => {
550
668
  const element = viewportRef.current;
551
- const { view: v } = latestRef.current;
552
- if (!element || v === null) return {
669
+ const { view: held, effective: v, box: b } = latestRef.current;
670
+ if (!element || held === null && !(b.width > 0)) return {
553
671
  x: 0,
554
672
  y: 0
555
673
  };
@@ -560,16 +678,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
560
678
  y: local.y + origin.y
561
679
  };
562
680
  }, []);
563
- const fit = useCallback(() => {
564
- const { box: b, image: i, view: v, onView: report } = latestRef.current;
681
+ const fitBy = useCallback((cause) => {
682
+ const { box: b, image: i, view: v, fitOpts: f } = latestRef.current;
565
683
  if (!(b.width > 0)) return;
566
- if (v !== null && !isFit(v, b, i)) previousRef.current = v;
567
- report(fitView(b, i));
568
- }, []);
569
- const zoomTo = useCallback((scale, anchor) => {
570
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
684
+ if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
685
+ emit(fitView(b, i, f), cause);
686
+ }, [emit]);
687
+ const fit = useCallback(() => fitBy("command"), [fitBy]);
688
+ const zoomBy = useCallback((cause, scale, anchor) => {
689
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
571
690
  const element = viewportRef.current;
572
- if (v === null || !(b.width > 0) || !element) return;
691
+ if (!(b.width > 0) || !element) return;
573
692
  const origin = viewportOrigin(element);
574
693
  const local = anchor ? {
575
694
  x: anchor.x - origin.x,
@@ -579,13 +698,14 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
579
698
  y: b.height / 2
580
699
  };
581
700
  const [min, max] = scaleRange(b, i, c);
582
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
583
- }, []);
701
+ emit(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c), cause);
702
+ }, [emit]);
703
+ const zoomTo = useCallback((scale, anchor) => zoomBy("command", scale, anchor), [zoomBy]);
584
704
  const frame = useCallback((rect, pad) => {
585
- const { box: b, image: i, onView: report } = latestRef.current;
705
+ const { box: b, image: i } = latestRef.current;
586
706
  if (!(b.width > 0)) return;
587
- report(frameRect(b, i, rect, pad));
588
- }, []);
707
+ emit(frameRect(b, i, rect, pad), "command");
708
+ }, [emit]);
589
709
  useImperativeHandle(ref, () => ({
590
710
  frame,
591
711
  fit,
@@ -595,7 +715,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
595
715
  fit,
596
716
  zoomTo
597
717
  ]);
598
- const atFit = box.width > 0 && isFit(effective, box, image);
718
+ const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);
599
719
  const context = useMemo(() => ({
600
720
  view: effective,
601
721
  setView: commit,
@@ -626,7 +746,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
626
746
  panMode
627
747
  ]);
628
748
  /** 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);
749
+ const hitRadius = (event) => imageLengthFor(effective, hitRadiusPx(event.pointerType));
630
750
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
631
751
  const routePress = (event) => hits.routePress(clientToImage({
632
752
  x: event.clientX,
@@ -681,14 +801,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
681
801
  scale: effective.scale,
682
802
  tx: origin.tx + dx,
683
803
  ty: origin.ty + dy
684
- });
804
+ }, "gesture");
685
805
  };
686
806
  const endDrag = (event) => {
687
807
  const origin = dragRef.current;
688
808
  if (origin?.touch) return;
689
809
  dragRef.current = null;
690
810
  setPanning(false);
691
- if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
811
+ if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event, clientToImage({
812
+ x: event.clientX,
813
+ y: event.clientY
814
+ }));
692
815
  };
693
816
  const touchDown = (event) => {
694
817
  const touches = touchesRef.current;
@@ -747,7 +870,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
747
870
  commit(pinchView(pinch.view, pinch.distance, pinch.centre, Math.hypot(a.x - b.x, a.y - b.y), {
748
871
  x: mid.x - origin.x,
749
872
  y: mid.y - origin.y
750
- }, scaleRange(box, image, clamp)));
873
+ }, scaleRange(box, image, clamp)), "gesture");
751
874
  return;
752
875
  }
753
876
  const drag = dragRef.current;
@@ -763,7 +886,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
763
886
  scale: effective.scale,
764
887
  tx: drag.tx + dx,
765
888
  ty: drag.ty + dy
766
- });
889
+ }, "gesture");
767
890
  };
768
891
  const touchEnd = (event, cancelled) => {
769
892
  const touches = touchesRef.current;
@@ -791,21 +914,24 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
791
914
  dragRef.current = null;
792
915
  setPanning(false);
793
916
  if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
794
- if (!routePress(event)) onBackgroundClick?.(event);
917
+ if (!routePress(event)) onBackgroundClick?.(event, clientToImage({
918
+ x: event.clientX,
919
+ y: event.clientY
920
+ }));
795
921
  };
796
922
  const onDoubleClick = (event) => {
797
923
  if (!doubleClickFit || !(box.width > 0)) return;
798
924
  if (atFit) {
799
925
  const restore = previousRef.current;
800
- if (restore) onView(clampView(restore, box, image, clamp));
801
- else zoomTo(1, {
926
+ if (restore) emit(clampView(restore, box, image, clamp), "gesture");
927
+ else zoomBy("gesture", 1, {
802
928
  x: event.clientX,
803
929
  y: event.clientY
804
930
  });
805
931
  return;
806
932
  }
807
933
  previousRef.current = effective;
808
- onView(fitView(box, image));
934
+ emit(fitView(box, image, fitOpts), "gesture");
809
935
  };
810
936
  const onKeyDown = (event) => {
811
937
  if (!shortcuts || isTypingTarget(event.target)) return;
@@ -814,45 +940,45 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
814
940
  switch (event.key) {
815
941
  case "+":
816
942
  case "=":
817
- zoomTo(Math.min(max, effective.scale * 1.5));
943
+ zoomBy("key", Math.min(max, effective.scale * 1.5));
818
944
  break;
819
945
  case "-":
820
946
  case "_":
821
- zoomTo(Math.max(min, effective.scale / 1.5));
947
+ zoomBy("key", Math.max(min, effective.scale / 1.5));
822
948
  break;
823
949
  case "0":
824
- fit();
950
+ fitBy("key");
825
951
  break;
826
952
  case "1":
827
- zoomTo(1);
953
+ zoomBy("key", 1);
828
954
  break;
829
955
  case "ArrowLeft":
830
956
  if (!panKeys) return;
831
957
  commit({
832
958
  ...effective,
833
959
  tx: effective.tx + nudge
834
- });
960
+ }, "key");
835
961
  break;
836
962
  case "ArrowRight":
837
963
  if (!panKeys) return;
838
964
  commit({
839
965
  ...effective,
840
966
  tx: effective.tx - nudge
841
- });
967
+ }, "key");
842
968
  break;
843
969
  case "ArrowUp":
844
970
  if (!panKeys) return;
845
971
  commit({
846
972
  ...effective,
847
973
  ty: effective.ty + nudge
848
- });
974
+ }, "key");
849
975
  break;
850
976
  case "ArrowDown":
851
977
  if (!panKeys) return;
852
978
  commit({
853
979
  ...effective,
854
980
  ty: effective.ty - nudge
855
- });
981
+ }, "key");
856
982
  break;
857
983
  default: return;
858
984
  }
@@ -886,6 +1012,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
886
1012
  onKeyDown,
887
1013
  children: [
888
1014
  /* @__PURE__ */ jsx("div", {
1015
+ ref: boxRef,
889
1016
  "data-stage": true,
890
1017
  className: "absolute top-0 left-0 origin-top-left",
891
1018
  style: {
@@ -916,8 +1043,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
916
1043
  });
917
1044
  }
918
1045
  /** 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);
1046
+ function openingView(opening, box, image, fit) {
1047
+ return opening === "fit" ? fitView(box, image, fit) : initialView(box, image, fit);
921
1048
  }
922
1049
  function hoverPoint(event, element, view, image) {
923
1050
  if (!element) return null;
@@ -1091,6 +1218,64 @@ function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onLoad, onError, cl
1091
1218
  })] });
1092
1219
  }
1093
1220
  //#endregion
1221
+ //#region src/components/stage/touchWatch.ts
1222
+ /**
1223
+ * Watching a touch without claiming it.
1224
+ *
1225
+ * A layer that claims a touch (`stopPropagation` plus pointer capture) takes it from the stage,
1226
+ * so a second finger can no longer pinch and a drag can no longer pan. A layer that only wants
1227
+ * to know whether the touch was a tap leaves the press alone and follows its pointer on
1228
+ * `window`, where the moves and the release arrive whoever captured the pointer.
1229
+ */
1230
+ /**
1231
+ * Follow one touch on `window` until it lifts. A second touch landing, or `pointercancel`,
1232
+ * cancels the watch and leaves the touches to the stage.
1233
+ *
1234
+ * @param origin - The `pointerdown` of the touch.
1235
+ * @param watch - What to report.
1236
+ * @returns A function that cancels the watch (calling `onCancel`); a no-op once it has ended.
1237
+ */
1238
+ function watchTouch(origin, watch) {
1239
+ const id = origin.pointerId;
1240
+ let moved = false;
1241
+ let done = false;
1242
+ const travel = (e) => Math.hypot(e.clientX - origin.clientX, e.clientY - origin.clientY);
1243
+ const stop = () => {
1244
+ done = true;
1245
+ window.removeEventListener("pointermove", move);
1246
+ window.removeEventListener("pointerup", up);
1247
+ window.removeEventListener("pointercancel", cancelEvent);
1248
+ window.removeEventListener("pointerdown", other);
1249
+ };
1250
+ const cancel = () => {
1251
+ if (done) return;
1252
+ stop();
1253
+ watch.onCancel?.();
1254
+ };
1255
+ function move(e) {
1256
+ if (e.pointerId !== id) return;
1257
+ if (!moved && travel(e) > 3) moved = true;
1258
+ if (moved) watch.onMove?.(e);
1259
+ }
1260
+ function up(e) {
1261
+ if (e.pointerId !== id) return;
1262
+ stop();
1263
+ if (!moved && travel(e) > 3) moved = true;
1264
+ watch.onEnd(e, moved, isTap(moved ? Infinity : travel(e), e.timeStamp - origin.timeStamp));
1265
+ }
1266
+ function cancelEvent(e) {
1267
+ if (e.pointerId === id) cancel();
1268
+ }
1269
+ function other(e) {
1270
+ if (e.pointerId !== id && e.pointerType === "touch") cancel();
1271
+ }
1272
+ window.addEventListener("pointermove", move);
1273
+ window.addEventListener("pointerup", up);
1274
+ window.addEventListener("pointercancel", cancelEvent);
1275
+ window.addEventListener("pointerdown", other);
1276
+ return cancel;
1277
+ }
1278
+ //#endregion
1094
1279
  //#region src/components/stage/StageSurface.tsx
1095
1280
  /**
1096
1281
  * The stage's tool model: one place that decides what a press on the image means.
@@ -1166,55 +1351,138 @@ function useStageDrag() {
1166
1351
  * that have their own small targets (handles, strokes). Each press is offered to `onPress`
1167
1352
  * unless the hand tool or a held space bar make it a pan; a declined press pans.
1168
1353
  *
1169
- * The surface draws nothing. It carries `data-dragging` while a drag it started is in
1170
- * flight.
1354
+ * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on
1355
+ * `window`, so the stage does not pan from it.
1356
+ *
1357
+ * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface
1358
+ * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)
1359
+ * and a second finger still pinches. The drag then sees:
1360
+ * - `onMove`, only once the finger has left the tap slop;
1361
+ * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;
1362
+ * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).
1363
+ *
1364
+ * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
1365
+ *
1366
+ * With `extent="viewport"` the surface also takes presses in the margin around the image, and
1367
+ * clamps every reported point to the image.
1368
+ *
1369
+ * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
1171
1370
  */
1172
- function StageSurface({ onPress, cursor, onHover }) {
1371
+ function StageSurface({ onPress, cursor, onHover, onDoubleClick, extent = "image" }) {
1173
1372
  const stage = useStage();
1174
1373
  const start = useStageDrag();
1175
1374
  const [dragging, setDragging] = useState(false);
1375
+ const watchRef = useRef(null);
1376
+ useEffect(() => () => watchRef.current?.(), []);
1377
+ const viewport = extent === "viewport";
1378
+ const pointAt = (client) => {
1379
+ const p = stage.toImage(client);
1380
+ return viewport ? clampToImage(p, stage.image) : p;
1381
+ };
1382
+ const target = (() => {
1383
+ const { image, view, box } = stage;
1384
+ if (!viewport || !(box.width > 0)) return {
1385
+ x: -.5,
1386
+ y: -.5,
1387
+ width: image.width,
1388
+ height: image.height
1389
+ };
1390
+ const a = toImage(view, {
1391
+ x: 0,
1392
+ y: 0
1393
+ });
1394
+ const b = toImage(view, {
1395
+ x: box.width,
1396
+ y: box.height
1397
+ });
1398
+ return {
1399
+ x: a.x,
1400
+ y: a.y,
1401
+ width: b.x - a.x,
1402
+ height: b.y - a.y
1403
+ };
1404
+ })();
1176
1405
  const onPointerDown = (event) => {
1177
- if (event.button !== 0 || stage.panMode) return;
1406
+ const touch = event.pointerType === "touch";
1407
+ if (stage.panMode || !touch && event.button !== 0) return;
1408
+ if (touch && watchRef.current) return;
1409
+ const client = {
1410
+ x: event.clientX,
1411
+ y: event.clientY
1412
+ };
1178
1413
  const drag = onPress({
1179
- point: stage.toImage({
1180
- x: event.clientX,
1181
- y: event.clientY
1182
- }),
1414
+ point: pointAt(client),
1415
+ client,
1416
+ touch,
1417
+ radius: hitRadiusPx(event.pointerType),
1183
1418
  shiftKey: event.shiftKey,
1184
1419
  altKey: event.altKey,
1185
1420
  metaKey: event.metaKey || event.ctrlKey
1186
1421
  });
1187
1422
  if (!drag) return;
1423
+ const finish = () => setDragging(false);
1188
1424
  setDragging(true);
1425
+ if (touch && !drag.claimsTouch) {
1426
+ const release = () => {
1427
+ watchRef.current = null;
1428
+ finish();
1429
+ };
1430
+ watchRef.current = watchTouch(event, {
1431
+ onMove: (e) => drag.onMove?.(pointAt({
1432
+ x: e.clientX,
1433
+ y: e.clientY
1434
+ }), e),
1435
+ onEnd: (e, moved) => {
1436
+ release();
1437
+ drag.onEnd?.(pointAt({
1438
+ x: e.clientX,
1439
+ y: e.clientY
1440
+ }), e, moved);
1441
+ },
1442
+ onCancel: () => {
1443
+ release();
1444
+ drag.onCancel?.();
1445
+ }
1446
+ });
1447
+ return;
1448
+ }
1189
1449
  start(event, {
1190
- onMove: drag.onMove,
1450
+ onMove: drag.onMove && ((point, e) => drag.onMove?.(viewport ? clampToImage(point, stage.image) : point, e)),
1191
1451
  onEnd: (point, e, moved) => {
1192
- setDragging(false);
1193
- drag.onEnd?.(point, e, moved);
1452
+ finish();
1453
+ drag.onEnd?.(viewport ? clampToImage(point, stage.image) : point, e, moved);
1194
1454
  },
1195
1455
  onCancel: () => {
1196
- setDragging(false);
1456
+ finish();
1197
1457
  drag.onCancel?.();
1198
1458
  }
1199
1459
  });
1200
1460
  };
1201
1461
  return /* @__PURE__ */ jsx("svg", {
1202
1462
  viewBox: imageViewBox(stage.image),
1203
- className: "pointer-events-none absolute inset-0 h-full w-full",
1463
+ className: cn("pointer-events-none absolute inset-0 h-full w-full", viewport && "overflow-visible"),
1204
1464
  "data-dragging": dragging ? "" : void 0,
1205
1465
  "aria-hidden": true,
1206
1466
  children: /* @__PURE__ */ jsx("rect", {
1207
1467
  "data-stage-surface": "",
1208
- x: -.5,
1209
- y: -.5,
1210
- width: stage.image.width,
1211
- height: stage.image.height,
1468
+ x: target.x,
1469
+ y: target.y,
1470
+ width: target.width,
1471
+ height: target.height,
1212
1472
  fill: "transparent",
1213
1473
  className: "pointer-events-auto",
1214
1474
  style: { cursor: stage.panMode ? void 0 : cursor },
1215
1475
  onPointerDown,
1216
1476
  onPointerMove: (event) => {
1217
- if (!dragging) onHover?.(stage.toImage({
1477
+ if (!dragging && event.pointerType !== "touch") onHover?.(pointAt({
1478
+ x: event.clientX,
1479
+ y: event.clientY
1480
+ }));
1481
+ },
1482
+ onDoubleClick: (event) => {
1483
+ if (!onDoubleClick) return;
1484
+ event.stopPropagation();
1485
+ onDoubleClick(pointAt({
1218
1486
  x: event.clientX,
1219
1487
  y: event.clientY
1220
1488
  }));
@@ -2548,7 +2816,7 @@ function nearestContourSegment(points, point) {
2548
2816
  return nearest;
2549
2817
  }
2550
2818
  /** Edit contour vertices over an ImageStage using its shared source-image transform. */
2551
- function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)" }) {
2819
+ function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)", bounds }) {
2552
2820
  const stage = useStage();
2553
2821
  const draggingRef = useRef(null);
2554
2822
  const movedRef = useRef(false);
@@ -2557,9 +2825,15 @@ function ContourEditor({ points, onChange, onCommit, editable = false, label = "
2557
2825
  const radius = stage.imageLength(5);
2558
2826
  const hairline = stage.imageLength(1.5);
2559
2827
  function clamp(point) {
2828
+ const area = bounds ?? {
2829
+ x: 0,
2830
+ y: 0,
2831
+ width: stage.image.width - 1,
2832
+ height: stage.image.height - 1
2833
+ };
2560
2834
  return {
2561
- x: Math.max(0, Math.min(stage.image.width - 1, point.x)),
2562
- y: Math.max(0, Math.min(stage.image.height - 1, point.y))
2835
+ x: Math.max(area.x, Math.min(area.x + area.width, point.x)),
2836
+ y: Math.max(area.y, Math.min(area.y + area.height, point.y))
2563
2837
  };
2564
2838
  }
2565
2839
  /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */
@@ -2859,10 +3133,10 @@ function clamp(value, low, high) {
2859
3133
  * inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.
2860
3134
  */
2861
3135
  /** Handle square side, in screen pixels. */
2862
- const HANDLE_PX$1 = 9;
3136
+ const HANDLE_PX = 9;
2863
3137
  /** Outline width, in screen pixels. */
2864
3138
  const STROKE_PX$2 = 1.5;
2865
- const HALO$6 = overlayRole("halo");
3139
+ const HALO$7 = overlayRole("halo");
2866
3140
  /**
2867
3141
  * An editable axis-aligned region inside an `ImageStage`.
2868
3142
  *
@@ -2880,8 +3154,8 @@ const HALO$6 = overlayRole("halo");
2880
3154
  function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw = false, bounds, minSize = 4, label = "Region", stroke = overlayRole("selection") }) {
2881
3155
  const stage = useStage();
2882
3156
  const area = bounds ?? {
2883
- x: 0,
2884
- y: 0,
3157
+ x: -.5,
3158
+ y: -.5,
2885
3159
  width: stage.image.width,
2886
3160
  height: stage.image.height
2887
3161
  };
@@ -2973,7 +3247,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2973
3247
  width: shown.width,
2974
3248
  height: shown.height,
2975
3249
  fill: "none",
2976
- stroke: HALO$6,
3250
+ stroke: HALO$7,
2977
3251
  strokeWidth: px(3.5)
2978
3252
  }), /* @__PURE__ */ jsx("rect", {
2979
3253
  x: shown.x,
@@ -3041,7 +3315,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3041
3315
  }),
3042
3316
  editable && value && !drawing && ROI_HANDLES.map((handle) => {
3043
3317
  const centre = roiHandlePoint(value, handle);
3044
- const size = px(HANDLE_PX$1);
3318
+ const size = px(HANDLE_PX);
3045
3319
  return /* @__PURE__ */ jsx("rect", {
3046
3320
  "data-handle": handle,
3047
3321
  x: centre.x - size / 2,
@@ -3049,7 +3323,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3049
3323
  width: size,
3050
3324
  height: size,
3051
3325
  fill: stroke,
3052
- stroke: HALO$6,
3326
+ stroke: HALO$7,
3053
3327
  strokeWidth: px(1),
3054
3328
  className: "pointer-events-auto",
3055
3329
  style: { cursor: ROI_HANDLE_CURSOR[handle] },
@@ -3089,7 +3363,7 @@ function fmt$1(value) {
3089
3363
  * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
3090
3364
  * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
3091
3365
  */
3092
- const HALO$5 = overlayRole("halo");
3366
+ const HALO$6 = overlayRole("halo");
3093
3367
  /** The most points drawn as dots at once; past this the dots are noise and a cost. */
3094
3368
  const MAX_VERTEX_DOTS = 5e3;
3095
3369
  /**
@@ -3103,12 +3377,17 @@ const MAX_VERTEX_DOTS = 5e3;
3103
3377
  * - **Halo.** Every line has a halo, so it holds on any image.
3104
3378
  * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.
3105
3379
  * - **Panning.** The hand tool and a held space bar still pan.
3380
+ * - **Tools.** Without a handler (or with `interactive={false}`) the layer takes no presses
3381
+ * and only answers `useStageHitTest`, so a draw tool's surface below receives them.
3106
3382
  *
3107
3383
  * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
3108
3384
  */
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 }) {
3385
+ 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
3386
  const stage = useStage();
3111
3387
  const startDrag = useStageDrag();
3388
+ const watchRef = useRef(null);
3389
+ useEffect(() => () => watchRef.current?.(), []);
3390
+ const takesPresses = interactive ?? (onItemPress !== void 0 || onSelect !== void 0 || onHover !== void 0 || onHoverChange !== void 0 || marquee);
3112
3391
  const px = useScreenPx();
3113
3392
  const { hitTestAll } = useStageHitTest();
3114
3393
  const index = useMemo(() => buildPolylineIndex(items), [items]);
@@ -3222,7 +3501,9 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3222
3501
  });
3223
3502
  };
3224
3503
  const onLinePointerDown = (event) => {
3225
- if (stage.panMode || event.button !== 0) return;
3504
+ const touch = event.pointerType === "touch";
3505
+ if (stage.panMode || !touch && event.button !== 0) return;
3506
+ if (touch && watchRef.current) return;
3226
3507
  if (event.shiftKey || marquee) {
3227
3508
  sweep(event);
3228
3509
  return;
@@ -3234,6 +3515,21 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3234
3515
  y: event.clientY
3235
3516
  });
3236
3517
  if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
3518
+ if (touch && !marquee) {
3519
+ const additive = event.metaKey || event.ctrlKey;
3520
+ watchRef.current = watchTouch(event, {
3521
+ onEnd: (_e, _moved, tap) => {
3522
+ watchRef.current = null;
3523
+ if (!tap) return;
3524
+ onItemPress?.(id, event);
3525
+ onSelect?.([id], additive ? "toggle" : "replace");
3526
+ },
3527
+ onCancel: () => {
3528
+ watchRef.current = null;
3529
+ }
3530
+ });
3531
+ return;
3532
+ }
3237
3533
  event.stopPropagation();
3238
3534
  onItemPress?.(id, event);
3239
3535
  onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
@@ -3247,7 +3543,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3247
3543
  "data-hovered": hoverId ?? void 0,
3248
3544
  "data-sweeping": band ? "" : void 0,
3249
3545
  children: [
3250
- marquee && /* @__PURE__ */ jsx("rect", {
3546
+ takesPresses && marquee && /* @__PURE__ */ jsx("rect", {
3251
3547
  "data-marquee-surface": "",
3252
3548
  x: -.5,
3253
3549
  y: -.5,
@@ -3267,7 +3563,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3267
3563
  children: [
3268
3564
  /* @__PURE__ */ jsx("path", {
3269
3565
  d: groups.hit,
3270
- stroke: HALO$5,
3566
+ stroke: HALO$6,
3271
3567
  strokeWidth: px(3.5),
3272
3568
  opacity: .6
3273
3569
  }),
@@ -3280,7 +3576,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3280
3576
  }, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
3281
3577
  groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3282
3578
  d: groups.selected,
3283
- stroke: HALO$5,
3579
+ stroke: HALO$6,
3284
3580
  strokeWidth: px(4.5)
3285
3581
  }), /* @__PURE__ */ jsx("path", {
3286
3582
  "data-selected-lines": "",
@@ -3290,7 +3586,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3290
3586
  })] }),
3291
3587
  hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3292
3588
  d: hoverPath,
3293
- stroke: HALO$5,
3589
+ stroke: HALO$6,
3294
3590
  strokeWidth: px(4)
3295
3591
  }), /* @__PURE__ */ jsx("path", {
3296
3592
  "data-hovered-line": "",
@@ -3304,7 +3600,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3304
3600
  stroke: selectionStroke,
3305
3601
  strokeWidth: px(3)
3306
3602
  }),
3307
- /* @__PURE__ */ jsx("path", {
3603
+ takesPresses && /* @__PURE__ */ jsx("path", {
3308
3604
  "data-hit": "",
3309
3605
  d: groups.hit,
3310
3606
  stroke: "transparent",
@@ -3315,7 +3611,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3315
3611
  },
3316
3612
  onPointerDown: onLinePointerDown,
3317
3613
  onPointerMove: (event) => {
3318
- if (!band) setHover(pickAt(event));
3614
+ if (!band && event.pointerType !== "touch") setHover(pickAt(event));
3319
3615
  },
3320
3616
  onPointerLeave: () => setHover(null)
3321
3617
  })
@@ -3732,7 +4028,7 @@ function useLabelIndices({ enabled, xy, labelled, forced }) {
3732
4028
  * Many points over the image, hoverable and selectable: detected corners, ring centres,
3733
4029
  * keypoints, labelled landmarks.
3734
4030
  *
3735
- * Drawn as a handful of batched paths, one per (state, style, marker kind), never one element
4031
+ * Drawn as a handful of batched paths, one per (state, style, colour, marker kind), never one element
3736
4032
  * per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the
3737
4033
  * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
3738
4034
  * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
@@ -3741,7 +4037,7 @@ function useLabelIndices({ enabled, xy, labelled, forced }) {
3741
4037
  const CULL_ABOVE = 3e3;
3742
4038
  /** How much bigger than a marker its selection ring is, in screen pixels. */
3743
4039
  const RING_GAP = 4;
3744
- const HALO$4 = overlayRole("halo");
4040
+ const HALO$5 = overlayRole("halo");
3745
4041
  const LABEL$1 = overlayRole("label");
3746
4042
  /**
3747
4043
  * A selectable set of points inside an `ImageStage`.
@@ -3808,6 +4104,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3808
4104
  key,
3809
4105
  shape,
3810
4106
  role: "selection",
4107
+ color: void 0,
3811
4108
  dim: false,
3812
4109
  indices: [],
3813
4110
  cache: null
@@ -3819,13 +4116,15 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3819
4116
  }
3820
4117
  const role = item.role ?? shape.role ?? "feature";
3821
4118
  const dim = isDimmed(item.id);
3822
- const key = `${dim ? 1 : 0}|${role}|${kindName}`;
4119
+ const color = item.color || void 0;
4120
+ const key = `${dim ? 1 : 0}|${role}|${kindName}${color ? `|${color}` : ""}`;
3823
4121
  let batch = normal.get(key);
3824
4122
  if (!batch) {
3825
4123
  batch = {
3826
4124
  key,
3827
4125
  shape,
3828
4126
  role,
4127
+ color,
3829
4128
  dim,
3830
4129
  indices: [],
3831
4130
  cache: null
@@ -3860,7 +4159,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3860
4159
  const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
3861
4160
  const build = (batches) => batches.map((batch) => ({
3862
4161
  batch,
3863
- d: batchPath(batch, items, unit, cull, cullKey)
4162
+ d: batchPath$1(batch, items, unit, cull, cullKey)
3864
4163
  }));
3865
4164
  const paths = {
3866
4165
  normal: build(groups.normal),
@@ -3917,25 +4216,25 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3917
4216
  children: [
3918
4217
  halo && paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3919
4218
  d,
3920
- stroke: HALO$4,
4219
+ stroke: HALO$5,
3921
4220
  strokeWidth: widthOf(batch.shape, batch.role, "default") + px(2),
3922
4221
  opacity: .6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)
3923
4222
  }, `halo|${batch.key}`)),
3924
4223
  paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3925
4224
  "data-batch": batch.key,
3926
4225
  d,
3927
- stroke: overlayRole(batch.role),
4226
+ stroke: batch.color ?? overlayRole(batch.role),
3928
4227
  strokeWidth: widthOf(batch.shape, batch.role, "default"),
3929
4228
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1
3930
4229
  }, batch.key)),
3931
4230
  halo && paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3932
4231
  d,
3933
- stroke: HALO$4,
4232
+ stroke: HALO$5,
3934
4233
  strokeWidth: widthOf(batch.shape, batch.role, "selected") + px(2)
3935
4234
  }, `halo|selected|${batch.key}`)),
3936
4235
  halo && paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3937
4236
  d,
3938
- stroke: HALO$4,
4237
+ stroke: HALO$5,
3939
4238
  strokeWidth: ringWidth + px(2)
3940
4239
  }, `halo|${batch.key}`)),
3941
4240
  paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
@@ -3951,13 +4250,13 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3951
4250
  strokeWidth: ringWidth
3952
4251
  }, batch.key)),
3953
4252
  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,
4253
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
4254
+ stroke: HALO$5,
3956
4255
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)
3957
4256
  }), /* @__PURE__ */ jsx("path", {
3958
4257
  "data-hovered-point": "",
3959
- d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
3960
- stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
4258
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
4259
+ stroke: hoverSelected ? selectionStroke : hoverItem?.color || overlayRole(hoverRole),
3961
4260
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
3962
4261
  })] })
3963
4262
  ]
@@ -3965,7 +4264,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3965
4264
  "data-labels": "",
3966
4265
  fontSize: px(11),
3967
4266
  className: "font-mono",
3968
- stroke: HALO$4,
4267
+ stroke: HALO$5,
3969
4268
  strokeWidth: px(3),
3970
4269
  paintOrder: "stroke",
3971
4270
  strokeLinejoin: "round",
@@ -3986,7 +4285,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3986
4285
  * The path data of a batch, generated again only when what it depends on changed: nothing
3987
4286
  * for a disc marker, the zoom and the window for an outline.
3988
4287
  */
3989
- function batchPath(batch, items, unit, cull, cullKey) {
4288
+ function batchPath$1(batch, items, unit, cull, cullKey) {
3990
4289
  const disc = batch.shape.paint === "disc";
3991
4290
  const key = disc ? "" : `${unit}|${cullKey}`;
3992
4291
  if (batch.cache?.key === key) return batch.cache.d;
@@ -3995,7 +4294,7 @@ function batchPath(batch, items, unit, cull, cullKey) {
3995
4294
  for (const i of batch.indices) {
3996
4295
  const item = items[i];
3997
4296
  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);
4297
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0, item.angle2);
3999
4298
  }
4000
4299
  batch.cache = {
4001
4300
  key,
@@ -4238,8 +4537,11 @@ function buildAreaIndex(items, cell) {
4238
4537
  entries
4239
4538
  };
4240
4539
  }
4241
- /** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */
4242
- function candidates(index, left, top, right, bottom) {
4540
+ /**
4541
+ * The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
4542
+ * The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
4543
+ */
4544
+ function areaCandidates(index, left, top, right, bottom) {
4243
4545
  const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
4244
4546
  if (entries.length === 0) return [];
4245
4547
  const cx0 = Math.max(0, Math.floor((left - x0) / cell));
@@ -4276,7 +4578,7 @@ function nearestArea(index, p, radius) {
4276
4578
  const { items, size } = index;
4277
4579
  let edge = null;
4278
4580
  let inner = null;
4279
- for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4581
+ for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4280
4582
  const points = items[a].points;
4281
4583
  const distance = distanceToOutline(points, p.x, p.y);
4282
4584
  const inside = pointInPolygon(points, p.x, p.y);
@@ -4309,7 +4611,7 @@ function areasInRect(index, rect) {
4309
4611
  height: Math.abs(rect.height)
4310
4612
  };
4311
4613
  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);
4614
+ 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
4615
  return out;
4314
4616
  }
4315
4617
  function polygonTouchesRect(points, rect) {
@@ -4329,17 +4631,103 @@ function polygonTouchesRect(points, rect) {
4329
4631
  return pointInPolygon(points, rect.x, rect.y);
4330
4632
  }
4331
4633
  //#endregion
4634
+ //#region src/components/areaBatching.ts
4635
+ /**
4636
+ * How `AreaSet` groups its regions into batched paths: by appearance (state, role, colours),
4637
+ * either one batch per appearance or consecutive runs in item order. Pure, so the keys are
4638
+ * unit-tested without a DOM (ADR-0004 rule 1).
4639
+ */
4640
+ /**
4641
+ * The appearance key of an item. Without a custom colour it is `dim|role`, as before colours
4642
+ * existed; a custom colour appends the outline and fill it was given.
4643
+ *
4644
+ * @param dim - Whether the item is dimmed.
4645
+ * @param role - The item's role.
4646
+ * @param stroke - The outline colour, if any.
4647
+ * @param fill - The fill colour, if any.
4648
+ * @returns The key.
4649
+ */
4650
+ function areaBatchKey(dim, role, stroke, fill) {
4651
+ const base = `${dim ? 1 : 0}|${role}`;
4652
+ return stroke || fill ? `${base}|${stroke ?? ""}|${fill ?? ""}` : base;
4653
+ }
4654
+ /**
4655
+ * Groups items into batches. Selected items go to `picked` (drawn on top in the selection
4656
+ * colour), unless `selectionFill` is `"item"`: then they stay in their batch for the fill and
4657
+ * `picked` carries only their outlines.
4658
+ *
4659
+ * @param items - The regions.
4660
+ * @param options - What decides the grouping.
4661
+ * @returns The appearance batches in paint order, and the selected overlay.
4662
+ */
4663
+ function batchAreas(items, options) {
4664
+ const { role, stroke, paintOrder, fillRule, selectionFill, selected, isDimmed } = options;
4665
+ const keepSelected = selectionFill === "item";
4666
+ const separate = fillRule === "evenodd" || keepSelected;
4667
+ const byKey = /* @__PURE__ */ new Map();
4668
+ const runs = [];
4669
+ const picked = {
4670
+ key: "selected",
4671
+ id: "selected",
4672
+ role: "selection",
4673
+ stroke: void 0,
4674
+ fill: void 0,
4675
+ dim: false,
4676
+ indices: [],
4677
+ d: "",
4678
+ fills: fillRule === "evenodd" && !keepSelected ? [] : null
4679
+ };
4680
+ items.forEach((item, i) => {
4681
+ const isSelected = selected.has(item.id);
4682
+ if (isSelected) {
4683
+ const d = areaPath(item.points);
4684
+ picked.indices.push(i);
4685
+ picked.d += d;
4686
+ picked.fills?.push(d);
4687
+ if (!keepSelected) return;
4688
+ }
4689
+ const itemRole = item.role ?? role;
4690
+ const itemStroke = item.stroke ?? stroke;
4691
+ const dim = isDimmed(item.id);
4692
+ const key = areaBatchKey(dim, itemRole, itemStroke, item.fill);
4693
+ let batch = paintOrder === "items" ? runs[runs.length - 1] : byKey.get(key);
4694
+ if (!batch || batch.key !== key) {
4695
+ batch = {
4696
+ key,
4697
+ id: paintOrder === "items" ? `${key}#${runs.length}` : key,
4698
+ role: itemRole,
4699
+ stroke: itemStroke,
4700
+ fill: item.fill,
4701
+ dim,
4702
+ indices: [],
4703
+ d: "",
4704
+ fills: separate ? [] : null
4705
+ };
4706
+ byKey.set(key, batch);
4707
+ runs.push(batch);
4708
+ }
4709
+ const d = areaPath(item.points);
4710
+ batch.indices.push(i);
4711
+ batch.fills?.push(d);
4712
+ if (!(isSelected && keepSelected)) batch.d += d;
4713
+ });
4714
+ return {
4715
+ normal: runs,
4716
+ picked: picked.indices.length > 0 ? picked : null
4717
+ };
4718
+ }
4719
+ //#endregion
4332
4720
  //#region src/components/AreaSet.tsx
4333
4721
  /**
4334
4722
  * Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,
4335
4723
  * region annotations, defect outlines.
4336
4724
  *
4337
- * Drawn as a handful of batched paths, one per (state, role), each outline with its 12 % fill
4725
+ * Drawn as a handful of batched paths, one per (state, role, colours), each outline with its 12 % fill
4338
4726
  * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the
4339
4727
  * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
4340
4728
  * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
4341
4729
  */
4342
- const HALO$3 = overlayRole("halo");
4730
+ const HALO$4 = overlayRole("halo");
4343
4731
  const LABEL = overlayRole("label");
4344
4732
  /** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */
4345
4733
  const FILL_OPACITY = .12;
@@ -4348,7 +4736,8 @@ const TICK_PX = 8;
4348
4736
  /**
4349
4737
  * A selectable set of closed regions inside an `ImageStage`.
4350
4738
  *
4351
- * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default).
4739
+ * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default) or its own
4740
+ * `stroke` / `fill` colours (`fillOpacity`, `fillRule`, `paintOrder` and `selectionFill` tune the fill).
4352
4741
  * Rings are wound alike before they are batched, so overlapping regions never cut a hole in
4353
4742
  * each other.
4354
4743
  * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and
@@ -4362,7 +4751,7 @@ const TICK_PX = 8;
4362
4751
  *
4363
4752
  * The SVG carries `data-hovered` (the hovered id).
4364
4753
  */
4365
- function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, labels = true, firstVertexTick = false, halo = true, selectionStroke = overlayRole("selection"), layerId, priority = STAGE_HIT_PRIORITY.area, label = "Areas" }) {
4754
+ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, labels = true, firstVertexTick = false, stroke, fillOpacity = FILL_OPACITY, fillRule = "nonzero", paintOrder = "appearance", selectionFill = "selection", halo = true, selectionStroke = overlayRole("selection"), layerId, priority = STAGE_HIT_PRIORITY.area, label = "Areas" }) {
4366
4755
  const stage = useStage();
4367
4756
  const px = useScreenPx();
4368
4757
  const unit = px(1);
@@ -4392,53 +4781,35 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4392
4781
  },
4393
4782
  onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
4394
4783
  });
4395
- const groups = useMemo(() => {
4396
- const normal = /* @__PURE__ */ new Map();
4397
- const picked = {
4398
- key: "selected",
4399
- role: "selection",
4400
- dim: false,
4401
- indices: [],
4402
- d: ""
4403
- };
4404
- items.forEach((item, i) => {
4405
- if (selectedSet.has(item.id)) {
4406
- picked.indices.push(i);
4407
- picked.d += areaPath(item.points);
4408
- return;
4409
- }
4410
- const itemRole = item.role ?? role;
4411
- const dim = isDimmed(item.id);
4412
- const key = `${dim ? 1 : 0}|${itemRole}`;
4413
- let batch = normal.get(key);
4414
- if (!batch) {
4415
- batch = {
4416
- key,
4417
- role: itemRole,
4418
- dim,
4419
- indices: [],
4420
- d: ""
4421
- };
4422
- normal.set(key, batch);
4423
- }
4424
- batch.indices.push(i);
4425
- batch.d += areaPath(item.points);
4426
- });
4427
- return {
4428
- normal: [...normal.values()],
4429
- picked: picked.indices.length > 0 ? picked : null
4430
- };
4431
- }, [
4784
+ const groups = useMemo(() => batchAreas(items, {
4785
+ role,
4786
+ stroke,
4787
+ paintOrder,
4788
+ fillRule,
4789
+ selectionFill,
4790
+ selected: selectedSet,
4791
+ isDimmed
4792
+ }), [
4432
4793
  items,
4433
4794
  role,
4795
+ stroke,
4796
+ paintOrder,
4797
+ fillRule,
4798
+ selectionFill,
4434
4799
  selectedSet,
4435
4800
  isDimmed
4436
4801
  ]);
4802
+ const keepFill = selectionFill === "item";
4803
+ const evenOdd = fillRule === "evenodd";
4804
+ const separate = evenOdd || keepFill;
4437
4805
  const ticks = useMemo(() => {
4438
4806
  if (!firstVertexTick) return [];
4439
4807
  return (groups.picked ? [...groups.normal, groups.picked] : groups.normal).map((batch) => {
4440
4808
  let d = "";
4441
- for (const i of batch.indices) d += tickPath(items[i].points, TICK_PX * unit);
4809
+ for (const i of batch.indices) {
4810
+ if (keepFill && batch !== groups.picked && selectedSet.has(items[i].id)) continue;
4811
+ d += tickPath(items[i].points, TICK_PX * unit);
4812
+ }
4442
4813
  return {
4443
4814
  batch,
4444
4815
  d
@@ -4448,11 +4819,14 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4448
4819
  firstVertexTick,
4449
4820
  groups,
4450
4821
  items,
4451
- unit
4822
+ unit,
4823
+ keepFill,
4824
+ selectedSet
4452
4825
  ]);
4453
4826
  const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
4454
4827
  const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
4455
4828
  const hoverRole = hoverItem?.role ?? role;
4829
+ const hoverStroke = hoverItem ? hoverItem.stroke ?? stroke ?? overlayRole(hoverRole) : void 0;
4456
4830
  const anchors = useMemo(() => {
4457
4831
  const xy = new Float64Array(items.length * 2);
4458
4832
  const labelled = [];
@@ -4491,6 +4865,20 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4491
4865
  const thin = itemRole === "model" || itemRole === "structure";
4492
4866
  return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
4493
4867
  };
4868
+ const strokeOf = (batch) => batch.stroke ?? overlayRole(batch.role);
4869
+ /** Each region's fill as its own even-odd path, or all of them as one path. */
4870
+ const fillPaths = (batch, colour, tag) => evenOdd ? batch.fills.map((d, k) => /* @__PURE__ */ jsx("path", {
4871
+ "data-fill": tag,
4872
+ d,
4873
+ fill: colour,
4874
+ fillOpacity,
4875
+ fillRule: "evenodd"
4876
+ }, batch.indices[k])) : /* @__PURE__ */ jsx("path", {
4877
+ "data-fill": tag,
4878
+ d: batch.fills.join(""),
4879
+ fill: colour,
4880
+ fillOpacity
4881
+ });
4494
4882
  return /* @__PURE__ */ jsxs("svg", {
4495
4883
  viewBox: imageViewBox(stage.image),
4496
4884
  className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
@@ -4504,62 +4892,70 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4504
4892
  children: [
4505
4893
  groups.normal.map((batch) => /* @__PURE__ */ jsxs("g", {
4506
4894
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4507
- children: [halo && /* @__PURE__ */ jsx("path", {
4508
- d: batch.d,
4509
- stroke: HALO$3,
4510
- strokeWidth: widthOf(batch.role, "default") + px(2),
4511
- opacity: .6
4512
- }), /* @__PURE__ */ jsx("path", {
4513
- "data-batch": batch.key,
4514
- d: batch.d,
4515
- fill: overlayRole(batch.role),
4516
- fillOpacity: FILL_OPACITY,
4517
- stroke: overlayRole(batch.role),
4518
- strokeWidth: widthOf(batch.role, "default")
4519
- })]
4520
- }, batch.key)),
4521
- groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4522
- d: groups.picked.d,
4523
- stroke: HALO$3,
4524
- strokeWidth: widthOf("selection", "selected") + px(2)
4525
- }), /* @__PURE__ */ jsx("path", {
4526
- "data-selected-areas": "",
4527
- d: groups.picked.d,
4528
- fill: selectionStroke,
4529
- fillOpacity: FILL_OPACITY,
4530
- stroke: selectionStroke,
4531
- strokeWidth: widthOf("selection", "selected")
4532
- })] }),
4895
+ children: [
4896
+ halo && (!separate || batch.d !== "") && /* @__PURE__ */ jsx("path", {
4897
+ d: batch.d,
4898
+ stroke: HALO$4,
4899
+ strokeWidth: widthOf(batch.role, "default") + px(2),
4900
+ opacity: .6
4901
+ }),
4902
+ separate && fillPaths(batch, batch.fill ?? strokeOf(batch), batch.key),
4903
+ (!separate || batch.d !== "") && /* @__PURE__ */ jsx("path", {
4904
+ "data-batch": batch.key,
4905
+ d: batch.d,
4906
+ fill: separate ? void 0 : batch.fill ?? strokeOf(batch),
4907
+ fillOpacity: separate ? void 0 : fillOpacity,
4908
+ stroke: strokeOf(batch),
4909
+ strokeWidth: widthOf(batch.role, "default")
4910
+ })
4911
+ ]
4912
+ }, batch.id)),
4913
+ groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [
4914
+ halo && /* @__PURE__ */ jsx("path", {
4915
+ d: groups.picked.d,
4916
+ stroke: HALO$4,
4917
+ strokeWidth: widthOf("selection", "selected") + px(2)
4918
+ }),
4919
+ evenOdd && !keepFill && fillPaths(groups.picked, selectionStroke, "selected"),
4920
+ /* @__PURE__ */ jsx("path", {
4921
+ "data-selected-areas": "",
4922
+ d: groups.picked.d,
4923
+ fill: evenOdd || keepFill ? void 0 : selectionStroke,
4924
+ fillOpacity: evenOdd || keepFill ? void 0 : fillOpacity,
4925
+ stroke: selectionStroke,
4926
+ strokeWidth: widthOf("selection", "selected")
4927
+ })
4928
+ ] }),
4533
4929
  hoverItem && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4534
4930
  d: areaPath(hoverItem.points),
4535
- stroke: HALO$3,
4931
+ stroke: HALO$4,
4536
4932
  strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)
4537
4933
  }), /* @__PURE__ */ jsx("path", {
4538
4934
  "data-hovered-area": "",
4539
4935
  d: areaPath(hoverItem.points),
4540
- stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
4936
+ stroke: hoverSelected ? selectionStroke : hoverStroke,
4541
4937
  strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover")
4542
4938
  })] }),
4543
4939
  ticks.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
4544
4940
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4545
4941
  children: [halo && /* @__PURE__ */ jsx("path", {
4546
4942
  d,
4547
- stroke: HALO$3,
4943
+ stroke: HALO$4,
4548
4944
  strokeWidth: px(OVERLAY_STATE_WIDTH.selected + 2),
4549
4945
  opacity: .6
4550
4946
  }), /* @__PURE__ */ jsx("path", {
4551
4947
  "data-ticks": batch.key,
4552
4948
  d,
4553
- stroke: batch === groups.picked ? selectionStroke : overlayRole(batch.role),
4949
+ stroke: batch === groups.picked ? selectionStroke : strokeOf(batch),
4554
4950
  strokeWidth: px(OVERLAY_STATE_WIDTH.selected)
4555
4951
  })]
4556
- }, `tick|${batch.key}`))
4952
+ }, `tick|${batch.id}`))
4557
4953
  ]
4558
4954
  }), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
4559
4955
  "data-labels": "",
4560
4956
  fontSize: px(11),
4561
4957
  className: "font-mono",
4562
- stroke: HALO$3,
4958
+ stroke: HALO$4,
4563
4959
  strokeWidth: px(3),
4564
4960
  paintOrder: "stroke",
4565
4961
  strokeLinejoin: "round",
@@ -4589,45 +4985,508 @@ function tickPath(points, length) {
4589
4985
  return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1e3) / 1e3} ${Math.round((y + (c.y - y) * k) * 1e3) / 1e3}`;
4590
4986
  }
4591
4987
  //#endregion
4592
- //#region src/components/gridEdges.ts
4593
- /** Indices past this magnitude are not hashed (the key must stay an exact integer). */
4594
- const LIMIT = 2 ** 25;
4595
- function key(i, j) {
4596
- return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
4988
+ //#region src/components/ellipseIndex.ts
4989
+ /**
4990
+ * A spatial index over many ellipses: which one is under the pointer, and which ones a
4991
+ * rubber band touched.
4992
+ *
4993
+ * The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
4994
+ * items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
4995
+ * exact tests are in the ellipse's own frame: containment is one quadratic form, and the
4996
+ * distance to the outline is the true Euclidean distance (a few Newton steps on the
4997
+ * parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
4998
+ * round one. It imports neither React nor the DOM.
4999
+ *
5000
+ * An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
5001
+ * outline to draw or to pick.
5002
+ */
5003
+ function usable(e) {
5004
+ return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
4597
5005
  }
4598
5006
  /**
4599
- * The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
4600
- * axis.
5007
+ * The axis-aligned bounding box of an ellipse.
4601
5008
  *
4602
- * @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
4603
- * integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
4604
- * first one is the lattice's node there.
4605
- * @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
5009
+ * @param e - The ellipse.
5010
+ * @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
4606
5011
  */
4607
- function latticeEdges(nodes) {
4608
- const at = /* @__PURE__ */ new Map();
4609
- const valid = (n) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
4610
- for (let p = 0; p < nodes.length; p++) {
4611
- const node = nodes[p];
4612
- if (!valid(node)) continue;
4613
- const k = key(node.i, node.j);
4614
- if (!at.has(k)) at.set(k, p);
4615
- }
4616
- const edges = [];
4617
- for (let p = 0; p < nodes.length; p++) {
4618
- const node = nodes[p];
4619
- if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
4620
- if (node.i + 1 < LIMIT) {
4621
- const q = at.get(key(node.i + 1, node.j));
4622
- if (q !== void 0) edges.push({
4623
- a: p,
4624
- b: q,
4625
- axis: "i"
4626
- });
4627
- }
4628
- if (node.j + 1 < LIMIT) {
4629
- const q = at.get(key(node.i, node.j + 1));
4630
- if (q !== void 0) edges.push({
5012
+ function ellipseBounds(e) {
5013
+ if (!usable(e)) return null;
5014
+ const c = Math.cos(e.angle ?? 0);
5015
+ const s = Math.sin(e.angle ?? 0);
5016
+ const hx = Math.hypot(e.rx * c, e.ry * s);
5017
+ const hy = Math.hypot(e.rx * s, e.ry * c);
5018
+ return [
5019
+ e.x - hx,
5020
+ e.y - hy,
5021
+ e.x + hx,
5022
+ e.y + hy
5023
+ ];
5024
+ }
5025
+ /** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
5026
+ function toFrame(e, x, y) {
5027
+ const c = Math.cos(e.angle ?? 0);
5028
+ const s = Math.sin(e.angle ?? 0);
5029
+ const dx = x - e.x;
5030
+ const dy = y - e.y;
5031
+ return {
5032
+ x: c * dx + s * dy,
5033
+ y: -s * dx + c * dy
5034
+ };
5035
+ }
5036
+ /**
5037
+ * Whether `(x, y)` is inside the ellipse (its outline counts as inside).
5038
+ *
5039
+ * @param e - The ellipse.
5040
+ * @param x - The query's x.
5041
+ * @param y - The query's y.
5042
+ * @returns `false` for a degenerate ellipse.
5043
+ */
5044
+ function pointInEllipse(e, x, y) {
5045
+ if (!usable(e)) return false;
5046
+ const p = toFrame(e, x, y);
5047
+ return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
5048
+ }
5049
+ /** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
5050
+ const NEWTON_STEPS = 12;
5051
+ /**
5052
+ * The Euclidean distance from `(x, y)` to the outline of an ellipse.
5053
+ *
5054
+ * The query is folded into the first quadrant of the ellipse's frame and the nearest outline
5055
+ * point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
5056
+ * better of a coarse scan so a thin ellipse and a query near its centre both converge.
5057
+ *
5058
+ * @param e - The ellipse.
5059
+ * @param x - The query's x.
5060
+ * @param y - The query's y.
5061
+ * @returns The distance; `Infinity` for a degenerate ellipse.
5062
+ */
5063
+ function distanceToEllipse(e, x, y) {
5064
+ if (!usable(e)) return Infinity;
5065
+ const p = toFrame(e, x, y);
5066
+ const px = Math.abs(p.x);
5067
+ const py = Math.abs(p.y);
5068
+ const a = e.rx;
5069
+ const b = e.ry;
5070
+ const squared = (t) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
5071
+ let t = 0;
5072
+ let best = Infinity;
5073
+ const SCAN = 16;
5074
+ for (let k = 0; k <= SCAN; k++) {
5075
+ const candidate = k / SCAN * (Math.PI / 2);
5076
+ const value = squared(candidate);
5077
+ if (value < best) {
5078
+ best = value;
5079
+ t = candidate;
5080
+ }
5081
+ }
5082
+ for (let i = 0; i < NEWTON_STEPS; i++) {
5083
+ const c = Math.cos(t);
5084
+ const s = Math.sin(t);
5085
+ const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
5086
+ const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
5087
+ if (!(Math.abs(df) > 1e-12)) break;
5088
+ const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
5089
+ if (squared(next) > squared(t)) break;
5090
+ t = next;
5091
+ }
5092
+ return Math.sqrt(squared(t));
5093
+ }
5094
+ /**
5095
+ * An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
5096
+ *
5097
+ * @param cx - Centre x, image pixels.
5098
+ * @param cy - Centre y, image pixels.
5099
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
5100
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
5101
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
5102
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
5103
+ */
5104
+ function ellipsePath(cx, cy, rx, ry, angle = 0) {
5105
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
5106
+ const dx = rx * Math.cos(angle);
5107
+ const dy = rx * Math.sin(angle);
5108
+ const degrees = round(angle * 180 / Math.PI);
5109
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
5110
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
5111
+ }
5112
+ /** Round to 1/1000 of an image pixel. */
5113
+ function round(value) {
5114
+ return Math.round(value * 1e3) / 1e3;
5115
+ }
5116
+ /**
5117
+ * Index a set of ellipses.
5118
+ *
5119
+ * @param items - The ellipses.
5120
+ * @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
5121
+ * @returns The index.
5122
+ */
5123
+ function buildEllipseIndex(items, cell) {
5124
+ const size = new Float64Array(items.length).fill(NaN);
5125
+ return {
5126
+ items,
5127
+ grid: buildAreaIndex(items.map((item, i) => {
5128
+ const box = ellipseBounds(item);
5129
+ if (box === null) return {
5130
+ id: i,
5131
+ points: []
5132
+ };
5133
+ size[i] = Math.PI * item.rx * item.ry;
5134
+ const [x0, y0, x1, y1] = box;
5135
+ return {
5136
+ id: i,
5137
+ points: [
5138
+ x0,
5139
+ y0,
5140
+ x1,
5141
+ y0,
5142
+ x1,
5143
+ y1,
5144
+ x0,
5145
+ y1
5146
+ ]
5147
+ };
5148
+ }), cell),
5149
+ size
5150
+ };
5151
+ }
5152
+ /**
5153
+ * The ellipse under a point: one whose outline passes within `radius`, or else one that
5154
+ * contains it.
5155
+ *
5156
+ * An outline is the more precise gesture, so it wins: among ellipses whose outline is within
5157
+ * `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
5158
+ * distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
5159
+ * another is picked rather than the outer one, then to the earlier one.
5160
+ *
5161
+ * @param index - The index.
5162
+ * @param p - The query, in image coordinates.
5163
+ * @param radius - How far from an outline the query still picks it, in image pixels.
5164
+ * @returns The ellipse, or `null`.
5165
+ */
5166
+ function nearestEllipse(index, p, radius) {
5167
+ if (!(radius >= 0)) return null;
5168
+ const { items, size } = index;
5169
+ let edge = null;
5170
+ let inner = null;
5171
+ for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
5172
+ const e = items[a];
5173
+ const distance = distanceToEllipse(e, p.x, p.y);
5174
+ const hit = {
5175
+ id: e.id,
5176
+ index: a,
5177
+ inside: pointInEllipse(e, p.x, p.y),
5178
+ distance
5179
+ };
5180
+ if (distance <= radius) {
5181
+ if (edge === null || distance < edge.distance || distance === edge.distance && size[a] < size[edge.index]) edge = hit;
5182
+ } else if (hit.inside && (inner === null || size[a] < size[inner.index])) inner = hit;
5183
+ }
5184
+ return edge ?? inner;
5185
+ }
5186
+ /**
5187
+ * The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
5188
+ * inside the ellipse, or contains it.
5189
+ *
5190
+ * @param index - The index.
5191
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
5192
+ * its corners.
5193
+ * @returns Their ids, in the order the ellipses were given.
5194
+ */
5195
+ function ellipsesInRect(index, rect) {
5196
+ const x0 = Math.min(rect.x, rect.x + rect.width);
5197
+ const y0 = Math.min(rect.y, rect.y + rect.height);
5198
+ const x1 = Math.max(rect.x, rect.x + rect.width);
5199
+ const y1 = Math.max(rect.y, rect.y + rect.height);
5200
+ const out = [];
5201
+ for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
5202
+ const e = index.items[a];
5203
+ if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
5204
+ }
5205
+ return out;
5206
+ }
5207
+ /** Whether the filled ellipse and the rectangle share a point (both convex). */
5208
+ function rectMeetsEllipse(e, x0, y0, x1, y1) {
5209
+ if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
5210
+ const corners = [
5211
+ {
5212
+ x: x0,
5213
+ y: y0
5214
+ },
5215
+ {
5216
+ x: x1,
5217
+ y: y0
5218
+ },
5219
+ {
5220
+ x: x1,
5221
+ y: y1
5222
+ },
5223
+ {
5224
+ x: x0,
5225
+ y: y1
5226
+ }
5227
+ ];
5228
+ if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
5229
+ for (let k = 0; k < 4; k++) {
5230
+ const a = toFrame(e, corners[k].x, corners[k].y);
5231
+ const b = toFrame(e, corners[(k + 1) % 4].x, corners[(k + 1) % 4].y);
5232
+ const ux = (b.x - a.x) / e.rx;
5233
+ const uy = (b.y - a.y) / e.ry;
5234
+ const vx = a.x / e.rx;
5235
+ const vy = a.y / e.ry;
5236
+ const len2 = ux * ux + uy * uy;
5237
+ const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
5238
+ if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
5239
+ }
5240
+ return false;
5241
+ }
5242
+ //#endregion
5243
+ //#region src/components/EllipseSet.tsx
5244
+ /**
5245
+ * Many ellipses over the image whose size is data, hoverable and selectable: fitted ring
5246
+ * edges, edge-bit dots, drawn ellipse annotations.
5247
+ *
5248
+ * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
5249
+ * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
5250
+ * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
5251
+ * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
5252
+ * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
5253
+ */
5254
+ const HALO$3 = overlayRole("halo");
5255
+ /** The outline of an item, its semi-axes raised to `floor` image pixels. */
5256
+ function outlineOf(item, floor) {
5257
+ return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);
5258
+ }
5259
+ /** The concatenated outlines of the items at `indices`. */
5260
+ function batchPath(items, indices, floor) {
5261
+ let d = "";
5262
+ for (const i of indices) d += outlineOf(items[i], floor);
5263
+ return d;
5264
+ }
5265
+ /**
5266
+ * The layer's entry in the stage's hit registry: a component, not a hook call in
5267
+ * `EllipseSet`, so `pickable={false}` really unregisters it. Renders nothing.
5268
+ */
5269
+ function EllipseHits({ index, layerId, priority, onHover, onPress }) {
5270
+ useStageHitLayer({
5271
+ layerId,
5272
+ priority,
5273
+ pick: (point, radius) => {
5274
+ const hit = nearestEllipse(index, point, radius);
5275
+ return hit ? {
5276
+ id: hit.id,
5277
+ dist: hit.inside ? 0 : hit.distance
5278
+ } : null;
5279
+ },
5280
+ onHover,
5281
+ onPress: onPress ? (id, event) => onPress(id, event) : void 0
5282
+ });
5283
+ return null;
5284
+ }
5285
+ /**
5286
+ * A batched set of ellipses inside an `ImageStage`.
5287
+ *
5288
+ * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
5289
+ * the stroke is a screen constant.
5290
+ * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
5291
+ * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
5292
+ * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
5293
+ * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
5294
+ * an outline picks that ellipse, else the smallest ellipse containing the point.
5295
+ * `onHoverChange` and `onItemPress` here, and `useStageHitTest` for an app that arbitrates
5296
+ * between layers. `pickable={false}` turns it off.
5297
+ *
5298
+ * The SVG carries `data-ellipses` (the count) and `data-hovered` (the hovered id).
5299
+ */
5300
+ 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 }) {
5301
+ const stage = useStage();
5302
+ const px = useScreenPx();
5303
+ const unit = px(1);
5304
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
5305
+ const isDimmed = useMemo(() => {
5306
+ if (typeof dimmed === "function") return dimmed;
5307
+ const set = new Set(dimmed ?? []);
5308
+ return (id) => set.has(id);
5309
+ }, [dimmed]);
5310
+ const index = useMemo(() => pickable ? buildEllipseIndex(items) : null, [items, pickable]);
5311
+ const [ownHover, setOwnHover] = useState(null);
5312
+ const hoverId = hoveredId !== void 0 ? hoveredId : pickable ? ownHover : null;
5313
+ const batches = useMemo(() => {
5314
+ const normal = /* @__PURE__ */ new Map();
5315
+ const picked = {
5316
+ key: "selected",
5317
+ role: "selection",
5318
+ dashed: false,
5319
+ opacity: 1,
5320
+ dim: false,
5321
+ indices: []
5322
+ };
5323
+ items.forEach((item, i) => {
5324
+ if (selectedSet.has(item.id)) {
5325
+ picked.indices.push(i);
5326
+ return;
5327
+ }
5328
+ const itemRole = item.role ?? role;
5329
+ const dashed = item.dashed ?? false;
5330
+ const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;
5331
+ const dim = isDimmed(item.id);
5332
+ const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? "dashed" : "solid"}|${opacity}`;
5333
+ let batch = normal.get(key);
5334
+ if (!batch) {
5335
+ batch = {
5336
+ key,
5337
+ role: itemRole,
5338
+ dashed,
5339
+ opacity,
5340
+ dim,
5341
+ indices: []
5342
+ };
5343
+ normal.set(key, batch);
5344
+ }
5345
+ batch.indices.push(i);
5346
+ });
5347
+ return {
5348
+ normal: [...normal.values()],
5349
+ picked: picked.indices.length > 0 ? picked : null
5350
+ };
5351
+ }, [
5352
+ items,
5353
+ role,
5354
+ selectedSet,
5355
+ isDimmed
5356
+ ]);
5357
+ const floor = minRadius !== void 0 ? minRadius * unit : 0;
5358
+ const normalPaths = useMemo(() => batches.normal.map((batch) => ({
5359
+ batch,
5360
+ d: batchPath(items, batch.indices, floor)
5361
+ })), [
5362
+ batches,
5363
+ items,
5364
+ floor
5365
+ ]);
5366
+ const pickedPath = useMemo(() => batches.picked ? batchPath(items, batches.picked.indices, floor) : "", [
5367
+ batches,
5368
+ items,
5369
+ floor
5370
+ ]);
5371
+ const hoverPositions = [];
5372
+ if (hoverId !== null) items.forEach((item, i) => {
5373
+ if (item.id === hoverId) hoverPositions.push(i);
5374
+ });
5375
+ const hoverSelected = hoverId !== null && selectedSet.has(hoverId);
5376
+ const widthOf = (itemRole, state) => {
5377
+ const thin = itemRole === "model" || itemRole === "structure";
5378
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
5379
+ };
5380
+ const dash = `${px(4)} ${px(3)}`;
5381
+ return /* @__PURE__ */ jsxs("svg", {
5382
+ viewBox: imageViewBox(stage.image),
5383
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
5384
+ ...label !== void 0 ? {
5385
+ role: "img",
5386
+ "aria-label": label
5387
+ } : { "aria-hidden": true },
5388
+ "data-ellipses": items.length,
5389
+ "data-hovered": hoverId ?? void 0,
5390
+ children: [index && /* @__PURE__ */ jsx(EllipseHits, {
5391
+ index,
5392
+ layerId,
5393
+ priority,
5394
+ onHover: (id) => {
5395
+ setOwnHover(id);
5396
+ onHoverChange?.(id);
5397
+ },
5398
+ onPress: onItemPress
5399
+ }), /* @__PURE__ */ jsxs("g", {
5400
+ fill: "none",
5401
+ strokeLinecap: "round",
5402
+ strokeLinejoin: "round",
5403
+ children: [
5404
+ normalPaths.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
5405
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
5406
+ children: [halo && /* @__PURE__ */ jsx("path", {
5407
+ d,
5408
+ stroke: HALO$3,
5409
+ strokeWidth: widthOf(batch.role, "default") + px(2),
5410
+ strokeDasharray: batch.dashed ? dash : void 0,
5411
+ opacity: .6 * batch.opacity
5412
+ }), /* @__PURE__ */ jsx("path", {
5413
+ "data-batch": batch.key,
5414
+ d,
5415
+ stroke: overlayRole(batch.role),
5416
+ strokeWidth: widthOf(batch.role, "default"),
5417
+ strokeDasharray: batch.dashed ? dash : void 0,
5418
+ opacity: batch.opacity
5419
+ })]
5420
+ }, batch.key)),
5421
+ batches.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
5422
+ d: pickedPath,
5423
+ stroke: HALO$3,
5424
+ strokeWidth: widthOf("selection", "selected") + px(2)
5425
+ }), /* @__PURE__ */ jsx("path", {
5426
+ "data-selected-ellipses": "",
5427
+ d: pickedPath,
5428
+ stroke: selectionStroke,
5429
+ strokeWidth: widthOf("selection", "selected")
5430
+ })] }),
5431
+ hoverPositions.map((position) => {
5432
+ const item = items[position];
5433
+ const itemRole = item.role ?? role;
5434
+ const state = hoverSelected ? "selected" : "hover";
5435
+ return /* @__PURE__ */ jsxs("g", { children: [halo && /* @__PURE__ */ jsx("path", {
5436
+ d: outlineOf(item, floor),
5437
+ stroke: HALO$3,
5438
+ strokeWidth: widthOf(itemRole, state) + px(2)
5439
+ }), /* @__PURE__ */ jsx("path", {
5440
+ "data-hovered-ellipse": "",
5441
+ d: outlineOf(item, floor),
5442
+ stroke: hoverSelected ? selectionStroke : overlayRole(itemRole),
5443
+ strokeWidth: widthOf(itemRole, state)
5444
+ })] }, position);
5445
+ })
5446
+ ]
5447
+ })]
5448
+ });
5449
+ }
5450
+ //#endregion
5451
+ //#region src/components/gridEdges.ts
5452
+ /** Indices past this magnitude are not hashed (the key must stay an exact integer). */
5453
+ const LIMIT = 2 ** 25;
5454
+ function key(i, j) {
5455
+ return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
5456
+ }
5457
+ /**
5458
+ * The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
5459
+ * axis.
5460
+ *
5461
+ * @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
5462
+ * integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
5463
+ * first one is the lattice's node there.
5464
+ * @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
5465
+ */
5466
+ function latticeEdges(nodes) {
5467
+ const at = /* @__PURE__ */ new Map();
5468
+ const valid = (n) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
5469
+ for (let p = 0; p < nodes.length; p++) {
5470
+ const node = nodes[p];
5471
+ if (!valid(node)) continue;
5472
+ const k = key(node.i, node.j);
5473
+ if (!at.has(k)) at.set(k, p);
5474
+ }
5475
+ const edges = [];
5476
+ for (let p = 0; p < nodes.length; p++) {
5477
+ const node = nodes[p];
5478
+ if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
5479
+ if (node.i + 1 < LIMIT) {
5480
+ const q = at.get(key(node.i + 1, node.j));
5481
+ if (q !== void 0) edges.push({
5482
+ a: p,
5483
+ b: q,
5484
+ axis: "i"
5485
+ });
5486
+ }
5487
+ if (node.j + 1 < LIMIT) {
5488
+ const q = at.get(key(node.i, node.j + 1));
5489
+ if (q !== void 0) edges.push({
4631
5490
  a: p,
4632
5491
  b: q,
4633
5492
  axis: "j"
@@ -4967,8 +5826,6 @@ function colourPlane(plane, colormap, range, channel) {
4967
5826
  height: plane.height
4968
5827
  };
4969
5828
  }
4970
- //#endregion
4971
- //#region src/components/shapeEdit.ts
4972
5829
  /**
4973
5830
  * A point of image space in the shape's own frame: origin at its centre, axes along its sides.
4974
5831
  *
@@ -5186,6 +6043,83 @@ function sameShape(a, b, epsilon = 1e-6) {
5186
6043
  if (a === null || b === null) return a === b;
5187
6044
  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
6045
  }
6046
+ /**
6047
+ * How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is
6048
+ * a first-order estimate, which is exact on the axes and good to a few percent elsewhere.
6049
+ */
6050
+ function distanceOutside(shape, kind, p) {
6051
+ const u = toShapeFrame(shape, p);
6052
+ const a = Math.max(shape.width / 2, 1e-9);
6053
+ const b = Math.max(shape.height / 2, 1e-9);
6054
+ if (kind === "rect") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));
6055
+ const f = (u.x / a) ** 2 + (u.y / b) ** 2;
6056
+ if (f <= 1) return 0;
6057
+ const g = Math.hypot(u.x / (a * a), u.y / (b * b));
6058
+ return (f - Math.sqrt(f)) / g;
6059
+ }
6060
+ /**
6061
+ * What a press on an editable shape means, decided once for the whole editor so that a small
6062
+ * shape's interior never steals a press meant for its handle.
6063
+ *
6064
+ * In order:
6065
+ * 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen
6066
+ * distance from the press is within `radius` plus the handle's half size: resize or rotate.
6067
+ * 2. Inside the shape, or within `radius` screen pixels of its outline: move.
6068
+ * 3. Otherwise `null`: the press is declined and belongs to whatever is below.
6069
+ *
6070
+ * @param shape - The shape.
6071
+ * @param kind - `"rect"` or `"ellipse"` (the outline differs).
6072
+ * @param scale - The view scale: screen pixels per image pixel.
6073
+ * @param point - The press, in image coordinates.
6074
+ * @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.
6075
+ * @param rotatable - Whether the rotation handle exists. Defaults to `true`.
6076
+ * @returns The decision, or `null`.
6077
+ */
6078
+ function shapePress(shape, kind, scale, point, radius, rotatable = true) {
6079
+ const best = {
6080
+ press: null,
6081
+ distance: Infinity
6082
+ };
6083
+ const consider = (candidate, at, half) => {
6084
+ const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;
6085
+ if (d <= radius + half && d < best.distance) {
6086
+ best.press = candidate;
6087
+ best.distance = d;
6088
+ }
6089
+ };
6090
+ for (const handle of ROI_HANDLES) consider({
6091
+ kind: "resize",
6092
+ handle
6093
+ }, shapeHandlePoint(shape, handle), 9 / 2);
6094
+ if (rotatable) consider({ kind: "rotate" }, rotationHandlePoint(shape, 24 / scale), 5);
6095
+ if (best.press) return best.press;
6096
+ return distanceOutside(shape, kind, point) * scale <= radius ? { kind: "move" } : null;
6097
+ }
6098
+ //#endregion
6099
+ //#region src/components/stage/useCoarsePointer.ts
6100
+ /**
6101
+ * Whether the device's primary pointer is coarse (a finger), for sizing a press target that
6102
+ * must exist before any pointer event says which pointer is coming.
6103
+ */
6104
+ const QUERY = "(pointer: coarse)";
6105
+ function mediaList() {
6106
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(QUERY) : null;
6107
+ }
6108
+ function subscribe(onChange) {
6109
+ const list = mediaList();
6110
+ list?.addEventListener("change", onChange);
6111
+ return () => list?.removeEventListener("change", onChange);
6112
+ }
6113
+ const snapshot = () => mediaList()?.matches ?? false;
6114
+ /**
6115
+ * Whether `(pointer: coarse)` matches: the primary pointer is a finger. `false` on the server
6116
+ * and wherever `matchMedia` is missing.
6117
+ *
6118
+ * @returns `true` on a touch-first device.
6119
+ */
6120
+ function useCoarsePointer() {
6121
+ return useSyncExternalStore(subscribe, snapshot, () => false);
6122
+ }
5189
6123
  //#endregion
5190
6124
  //#region src/components/ShapeEditor.tsx
5191
6125
  /**
@@ -5196,11 +6130,6 @@ function sameShape(a, b, epsilon = 1e-6) {
5196
6130
  * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
5197
6131
  * this is the gestures, the handles and the keyboard.
5198
6132
  */
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
6133
  /** Outline width, in screen pixels. */
5205
6134
  const STROKE_PX$1 = 1.5;
5206
6135
  /** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
@@ -5212,7 +6141,17 @@ const HALO$1 = overlayRole("halo");
5212
6141
  *
5213
6142
  * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
5214
6143
  * 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.
6144
+ * `minSize` rather than flipping. The interior moves it, and so does the band along its
6145
+ * outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin
6146
+ * or rotated shape is grabbed. The band is as wide as the device's primary pointer needs
6147
+ * (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to
6148
+ * 12 px outside the outline reaches the layers below instead of the editor.
6149
+ * - **Press order.** One decision serves every part of the editor: the nearest handle first,
6150
+ * then the interior or outline band (move), then nothing. A small shape's interior does not
6151
+ * steal a press meant for a handle, and a press that hits none of them is not claimed, so
6152
+ * it reaches whatever is below, or the stage.
6153
+ * - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit
6154
+ * cancels it (the shape reverts, nothing is committed) and is left to the stage.
5216
6155
  * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
5217
6156
  * round to 15°.
5218
6157
  * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
@@ -5230,23 +6169,78 @@ const HALO$1 = overlayRole("halo");
5230
6169
  function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, rotatable = true, minSize = 5, label = "Shape", stroke = overlayRole("selection") }) {
5231
6170
  const stage = useStage();
5232
6171
  const px = useScreenPx();
6172
+ const coarse = useCoarsePointer();
5233
6173
  const dragRef = useRef(null);
5234
6174
  const lastRef = useRef(null);
6175
+ const stopWatchRef = useRef(null);
5235
6176
  const report = (next) => {
5236
6177
  lastRef.current = next;
5237
6178
  onValueChange(next);
5238
6179
  };
5239
- const begin = (event, drag) => {
5240
- if (stage.panMode || event.button !== 0) return;
6180
+ /** Abandon an edit in flight: the shape reverts and nothing is committed. */
6181
+ const cancelEdit = () => {
6182
+ const drag = dragRef.current;
6183
+ dragRef.current = null;
6184
+ stopWatchRef.current?.();
6185
+ stopWatchRef.current = null;
6186
+ if (drag && lastRef.current) onValueChange(drag.start);
6187
+ lastRef.current = null;
6188
+ };
6189
+ useEffect(() => () => stopWatchRef.current?.(), []);
6190
+ /**
6191
+ * The one press decision for the whole editor: every target (the interior, the outline
6192
+ * band, a handle) comes here, and the nearest handle wins over the interior. A declined
6193
+ * press is not claimed and bubbles to the stage.
6194
+ */
6195
+ const press = (event) => {
6196
+ if (!value || stage.panMode) return;
6197
+ const touch = event.pointerType === "touch";
6198
+ if (!touch && event.button !== 0) return;
6199
+ if (dragRef.current) {
6200
+ if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();
6201
+ return;
6202
+ }
6203
+ const at = stage.toImage({
6204
+ x: event.clientX,
6205
+ y: event.clientY
6206
+ });
6207
+ const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);
6208
+ if (!decision) return;
5241
6209
  event.stopPropagation();
5242
6210
  event.preventDefault();
5243
- event.currentTarget.setPointerCapture(event.pointerId);
5244
- dragRef.current = drag;
6211
+ try {
6212
+ event.currentTarget.setPointerCapture(event.pointerId);
6213
+ } catch {}
6214
+ const base = {
6215
+ start: value,
6216
+ moved: false,
6217
+ pointerId: event.pointerId
6218
+ };
6219
+ dragRef.current = decision.kind === "move" ? {
6220
+ ...base,
6221
+ kind: "move",
6222
+ from: at
6223
+ } : decision.kind === "resize" ? {
6224
+ ...base,
6225
+ kind: "resize",
6226
+ handle: decision.handle
6227
+ } : {
6228
+ ...base,
6229
+ kind: "rotate"
6230
+ };
5245
6231
  lastRef.current = null;
6232
+ if (touch) {
6233
+ const id = event.pointerId;
6234
+ const other = (e) => {
6235
+ if (e.pointerId !== id && e.pointerType === "touch") cancelEdit();
6236
+ };
6237
+ window.addEventListener("pointerdown", other);
6238
+ stopWatchRef.current = () => window.removeEventListener("pointerdown", other);
6239
+ }
5246
6240
  };
5247
6241
  const onMove = (event) => {
5248
6242
  const drag = dragRef.current;
5249
- if (!drag) return;
6243
+ if (!drag || drag.pointerId !== event.pointerId) return;
5250
6244
  event.stopPropagation();
5251
6245
  const p = stage.toImage({
5252
6246
  x: event.clientX,
@@ -5259,11 +6253,24 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5259
6253
  };
5260
6254
  const onEnd = (event) => {
5261
6255
  const drag = dragRef.current;
5262
- if (!drag) return;
6256
+ if (!drag || drag.pointerId !== event.pointerId) return;
5263
6257
  event.stopPropagation();
5264
6258
  dragRef.current = null;
6259
+ stopWatchRef.current?.();
6260
+ stopWatchRef.current = null;
5265
6261
  if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
5266
6262
  };
6263
+ /** The handlers every target of the editor shares. */
6264
+ const gesture = {
6265
+ onPointerDown: press,
6266
+ onPointerMove: onMove,
6267
+ onPointerUp: onEnd,
6268
+ onPointerCancel: (event) => {
6269
+ if (dragRef.current?.pointerId === event.pointerId) cancelEdit();
6270
+ },
6271
+ onLostPointerCapture: onEnd,
6272
+ onDoubleClick: (event) => event.stopPropagation()
6273
+ };
5267
6274
  const onKeyDown = (event) => {
5268
6275
  if (!editable || value === null) return;
5269
6276
  if (rotatable && (event.key === "[" || event.key === "]")) {
@@ -5309,9 +6316,9 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5309
6316
  };
5310
6317
  const stem = value ? {
5311
6318
  from: shapeHandlePoint(value, "n"),
5312
- to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX))
6319
+ to: rotationHandlePoint(value, px(24))
5313
6320
  } : null;
5314
- const handleSize = px(HANDLE_PX);
6321
+ const handleSize = px(9);
5315
6322
  return /* @__PURE__ */ jsxs("svg", {
5316
6323
  viewBox: imageViewBox(stage.image),
5317
6324
  className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
@@ -5345,6 +6352,19 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5345
6352
  strokeDasharray: `${px(4)} ${px(3)}`,
5346
6353
  opacity: .6
5347
6354
  }),
6355
+ editable && value && /* @__PURE__ */ jsx(Outline, {
6356
+ kind,
6357
+ shape: value,
6358
+ "data-shape-band": "",
6359
+ fill: "none",
6360
+ stroke: "transparent",
6361
+ strokeWidth: px(2 * (coarse ? 12 : 6)),
6362
+ strokeLinejoin: "round",
6363
+ "aria-hidden": true,
6364
+ className: "pointer-events-auto cursor-move",
6365
+ style: { pointerEvents: "stroke" },
6366
+ ...gesture
6367
+ }),
5348
6368
  editable && value && /* @__PURE__ */ jsx(Outline, {
5349
6369
  kind,
5350
6370
  shape: value,
@@ -5354,20 +6374,9 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5354
6374
  "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
6375
  "aria-roledescription": kind === "rect" ? "rotated rectangle" : "ellipse",
5356
6376
  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()
6377
+ strokeWidth: px(2),
6378
+ ...gesture,
6379
+ onKeyDown
5371
6380
  }),
5372
6381
  editable && value && rotatable && stem && /* @__PURE__ */ jsxs(Fragment, { children: [
5373
6382
  /* @__PURE__ */ jsx("line", {
@@ -5390,21 +6399,13 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5390
6399
  "data-handle": "rotate",
5391
6400
  cx: stem.to.x,
5392
6401
  cy: stem.to.y,
5393
- r: px(ROTATE_RADIUS_PX),
6402
+ r: px(5),
5394
6403
  fill: stroke,
5395
6404
  stroke: HALO$1,
5396
6405
  strokeWidth: px(1),
5397
6406
  className: "pointer-events-auto",
5398
6407
  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()
6408
+ ...gesture
5408
6409
  })
5409
6410
  ] }),
5410
6411
  editable && value && ROI_HANDLES.map((handle) => {
@@ -5420,16 +6421,7 @@ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, ro
5420
6421
  strokeWidth: px(1),
5421
6422
  className: "pointer-events-auto",
5422
6423
  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()
6424
+ ...gesture
5433
6425
  }, handle);
5434
6426
  })
5435
6427
  ]
@@ -5483,15 +6475,20 @@ const VERTEX_PX = 6;
5483
6475
  * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by
5484
6476
  * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline
5485
6477
  * or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also
5486
- * shows, fainter, the segment that would close it. It takes no pointer events and is hidden
6478
+ * shows, fainter, the segment that would close it; with `closing` the first vertex gets a
6479
+ * ring and that segment turns solid and full strength: "click here to close". A `stroke`
6480
+ * (brush trail) is a translucent band of its own width with round caps and joins and no
6481
+ * dashes, and a `brush` is a footprint ring: a dark ring under a light one, so it reads on
6482
+ * any image. `points` may be a typed-array view that changes identity every move: the draft
6483
+ * is rebuilt in one O(n) pass per render, with no per-vertex elements. It takes no pointer events and is hidden
5487
6484
  * from assistive technology: it is transient feedback for a gesture.
5488
6485
  *
5489
6486
  * The SVG carries `data-draft` (the shape's kind).
5490
6487
  */
5491
- function DraftShape({ shape, role = "selection", halo = true }) {
6488
+ function DraftShape({ shape, role = "selection", stroke, halo = true }) {
5492
6489
  const stage = useStage();
5493
6490
  const px = useScreenPx();
5494
- const colour = overlayRole(role);
6491
+ const colour = stroke ?? overlayRole(role);
5495
6492
  const dash = `${px(DASH)} ${px(GAP)}`;
5496
6493
  const width = px(STROKE_PX);
5497
6494
  const parts = shape ? draftParts(shape, px(1)) : null;
@@ -5524,13 +6521,40 @@ function DraftShape({ shape, role = "selection", halo = true }) {
5524
6521
  strokeWidth: width,
5525
6522
  strokeDasharray: dash
5526
6523
  }),
6524
+ parts.trail && /* @__PURE__ */ jsx("path", {
6525
+ "data-draft-stroke": "",
6526
+ d: parts.trail.d,
6527
+ stroke: colour,
6528
+ strokeWidth: Math.max(parts.trail.width, px(1)),
6529
+ opacity: .4
6530
+ }),
6531
+ parts.footprint && halo && /* @__PURE__ */ jsx("path", {
6532
+ d: parts.footprint,
6533
+ stroke: HALO,
6534
+ strokeWidth: px(3.5),
6535
+ opacity: .6
6536
+ }),
6537
+ parts.footprint && /* @__PURE__ */ jsx("path", {
6538
+ "data-draft-brush": "",
6539
+ d: parts.footprint,
6540
+ stroke: colour,
6541
+ strokeWidth: px(1.5)
6542
+ }),
5527
6543
  parts.closing && /* @__PURE__ */ jsx("path", {
5528
6544
  "data-draft-closing": "",
5529
6545
  d: parts.closing,
5530
6546
  stroke: colour,
5531
- strokeWidth: px(1),
5532
- strokeDasharray: dash,
5533
- opacity: .5
6547
+ strokeWidth: parts.armed ? width : px(1),
6548
+ strokeDasharray: parts.armed ? void 0 : dash,
6549
+ opacity: parts.armed ? 1 : .5
6550
+ }),
6551
+ parts.first && /* @__PURE__ */ jsx("path", {
6552
+ "data-draft-first": "",
6553
+ d: parts.first,
6554
+ stroke: colour,
6555
+ strokeWidth: width,
6556
+ fill: colour,
6557
+ fillOpacity: .35
5534
6558
  }),
5535
6559
  parts.vertices && /* @__PURE__ */ jsx("path", {
5536
6560
  "data-draft-vertices": "",
@@ -5542,43 +6566,62 @@ function DraftShape({ shape, role = "selection", halo = true }) {
5542
6566
  })
5543
6567
  });
5544
6568
  }
6569
+ const NONE = {
6570
+ outline: null,
6571
+ region: false,
6572
+ closing: null,
6573
+ vertices: null,
6574
+ armed: false,
6575
+ first: null,
6576
+ trail: null,
6577
+ footprint: null
6578
+ };
5545
6579
  /** An ellipse with the given centre and radii as two arcs. */
5546
- function ellipsePath(cx, cy, rx, ry) {
6580
+ function ellipsePath$1(cx, cy, rx, ry) {
5547
6581
  return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
5548
6582
  }
5549
6583
  function draftParts(shape, unit) {
5550
6584
  switch (shape.kind) {
5551
6585
  case "point": return {
5552
- outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit),
5553
- region: false,
5554
- closing: null,
6586
+ ...NONE,
6587
+ outline: ellipsePath$1(shape.x, shape.y, 8 * unit, 8 * unit),
5555
6588
  vertices: `M${shape.x} ${shape.y}h0`
5556
6589
  };
5557
6590
  case "line": return {
5558
- outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`,
5559
- region: false,
5560
- closing: null,
5561
- vertices: null
6591
+ ...NONE,
6592
+ outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`
5562
6593
  };
5563
6594
  case "rect":
5564
6595
  case "ellipse": {
5565
6596
  const box = rectFromCorners(shape.from, shape.to);
6597
+ const 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);
6598
+ return {
6599
+ ...NONE,
6600
+ outline,
6601
+ region: true
6602
+ };
6603
+ }
6604
+ case "brush": return {
6605
+ ...NONE,
6606
+ footprint: ellipsePath$1(shape.x, shape.y, Math.max(shape.diameter, 2 * unit) / 2, Math.max(shape.diameter, 2 * unit) / 2)
6607
+ };
6608
+ case "stroke": {
6609
+ const n = Math.floor(shape.points.length / 2);
6610
+ if (n === 0) return NONE;
6611
+ let d = "";
6612
+ for (let i = 0; i < n; i++) d += `${i === 0 ? "M" : "L"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;
5566
6613
  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),
5568
- region: true,
5569
- closing: null,
5570
- vertices: null
6614
+ ...NONE,
6615
+ trail: {
6616
+ d: n === 1 ? `${d}h0` : d,
6617
+ width: shape.width
6618
+ }
5571
6619
  };
5572
6620
  }
5573
6621
  case "polyline":
5574
6622
  case "polygon": {
5575
6623
  const n = Math.floor(shape.points.length / 2);
5576
- if (n === 0) return {
5577
- outline: null,
5578
- region: false,
5579
- closing: null,
5580
- vertices: null
5581
- };
6624
+ if (n === 0) return NONE;
5582
6625
  let outline = "";
5583
6626
  let vertices = "";
5584
6627
  for (let i = 0; i < n; i++) {
@@ -5587,11 +6630,18 @@ function draftParts(shape, unit) {
5587
6630
  }
5588
6631
  if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;
5589
6632
  const polygon = shape.kind === "polygon";
6633
+ const armed = polygon && shape.closing === true && n >= 2;
6634
+ let closing = null;
6635
+ if (armed) closing = `M${shape.points[2 * n - 2]} ${shape.points[2 * n - 1]}L${shape.points[0]} ${shape.points[1]}`;
6636
+ else if (polygon && shape.cursor) closing = `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}`;
5590
6637
  return {
6638
+ ...NONE,
5591
6639
  outline,
5592
6640
  region: polygon && n + (shape.cursor ? 1 : 0) >= 3,
5593
- closing: polygon && shape.cursor ? `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}` : null,
5594
- vertices
6641
+ closing,
6642
+ vertices,
6643
+ armed,
6644
+ first: armed ? ellipsePath$1(shape.points[0], shape.points[1], 5 * unit, 5 * unit) : null
5595
6645
  };
5596
6646
  }
5597
6647
  }
@@ -5738,7 +6788,11 @@ function paintMask(mask, width, height, from, to, radius, value) {
5738
6788
  }
5739
6789
  return next;
5740
6790
  }
5741
- /** Render and edit a binary raster mask within the enclosing ImageStage. */
6791
+ /**
6792
+ * Render and edit a binary raster mask within the enclosing ImageStage. While editing, a
6793
+ * `DraftShape` brush footprint (a circle of the brush's diameter) follows the mouse or pen
6794
+ * pointer, and the keyboard brush while the layer has keyboard focus.
6795
+ */
5742
6796
  function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = "paint", label = "Mask brush", color = [
5743
6797
  0,
5744
6798
  190,
@@ -5751,6 +6805,7 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5751
6805
  const lastRef = useRef(null);
5752
6806
  const cursorRef = useRef(null);
5753
6807
  const [brush, setBrush] = useState(null);
6808
+ const [hover, setHover] = useState(null);
5754
6809
  function cursor() {
5755
6810
  return cursorRef.current ?? {
5756
6811
  x: Math.floor(stage.image.width / 2),
@@ -5787,15 +6842,26 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5787
6842
  lastRef.current = point;
5788
6843
  cursorRef.current = point;
5789
6844
  setBrush(null);
6845
+ if (event.pointerType !== "touch") setHover(point);
5790
6846
  apply(point, point);
5791
6847
  }
5792
6848
  function move(event) {
5793
- if (!lastRef.current) return;
6849
+ if (!lastRef.current) {
6850
+ if (editable && !stage.panMode && event.pointerType !== "touch") {
6851
+ setHover(stage.toImage({
6852
+ x: event.clientX,
6853
+ y: event.clientY
6854
+ }));
6855
+ setBrush(null);
6856
+ }
6857
+ return;
6858
+ }
5794
6859
  event.stopPropagation();
5795
6860
  const point = stage.toImage({
5796
6861
  x: event.clientX,
5797
6862
  y: event.clientY
5798
6863
  });
6864
+ if (event.pointerType !== "touch") setHover(point);
5799
6865
  apply(lastRef.current, point);
5800
6866
  lastRef.current = point;
5801
6867
  cursorRef.current = point;
@@ -5804,6 +6870,7 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5804
6870
  if (!lastRef.current) return;
5805
6871
  event.stopPropagation();
5806
6872
  lastRef.current = null;
6873
+ if (event.pointerType === "touch") setHover(null);
5807
6874
  onCommit?.();
5808
6875
  }
5809
6876
  function keyDown(event) {
@@ -5835,12 +6902,14 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5835
6902
  y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y))
5836
6903
  };
5837
6904
  setBrush(cursorRef.current);
6905
+ setHover(null);
5838
6906
  } else if (event.key === "Enter") {
5839
6907
  event.preventDefault();
5840
6908
  event.stopPropagation();
5841
6909
  const at = cursor();
5842
6910
  draftRef.current = mask;
5843
6911
  setBrush(at);
6912
+ setHover(null);
5844
6913
  apply(at, at);
5845
6914
  onCommit?.();
5846
6915
  }
@@ -5867,22 +6936,21 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
5867
6936
  },
5868
6937
  onKeyDown: keyDown,
5869
6938
  onFocus: focus,
5870
- onBlur: () => setBrush(null)
5871
- }), brush && /* @__PURE__ */ jsx("svg", {
5872
- viewBox: imageViewBox(stage.image),
5873
- className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
5874
- "aria-hidden": "true",
5875
- children: /* @__PURE__ */ jsx("circle", {
5876
- cx: brush.x,
5877
- cy: brush.y,
5878
- r: Math.max(.75, brushRadius),
5879
- fill: "none",
5880
- stroke: "var(--signal)",
5881
- strokeWidth: stage.imageLength(1.5)
5882
- })
6939
+ onBlur: () => setBrush(null),
6940
+ onPointerLeave: () => {
6941
+ if (!lastRef.current) setHover(null);
6942
+ }
6943
+ }), (hover ?? brush) && editable && /* @__PURE__ */ jsx(DraftShape, {
6944
+ shape: {
6945
+ kind: "brush",
6946
+ x: (hover ?? brush).x,
6947
+ y: (hover ?? brush).y,
6948
+ diameter: 2 * Math.max(.75, brushRadius)
6949
+ },
6950
+ stroke: "var(--signal)"
5883
6951
  })] });
5884
6952
  }
5885
6953
  //#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 };
6954
+ 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, clampToImage, 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
6955
 
5888
6956
  //# sourceMappingURL=index.js.map