@vitavision/stage2d 0.7.2 → 0.8.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,7 +1,7 @@
1
- import { createContext, use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
- import { cn, focusRing, toneColor } from "@vitavision/ui";
1
+ import { createContext, use, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { DropdownMenu, Kbd, MenuCheckboxItem, MenuLabel, Tooltip, cn, focusRing, toneColor } from "@vitavision/ui";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
- import { Maximize2, Minus, Plus, Scan } from "lucide-react";
4
+ import { Layers, Maximize2, Minus, Plus, Scan } from "lucide-react";
5
5
  //#region src/components/stage/view.ts
6
6
  /**
7
7
  * The offset between the two pixel conventions: an image coordinate `i` sits at CSS
@@ -136,7 +136,7 @@ function scaleRange(box, image, options = {}) {
136
136
  */
137
137
  function clampView(view, box, image, options = {}) {
138
138
  const [min, max] = scaleRange(box, image, options);
139
- const scale = clamp$1(view.scale, min, max);
139
+ const scale = clamp$2(view.scale, min, max);
140
140
  return {
141
141
  scale,
142
142
  tx: clampAxis(view.tx, box.width, image.width * scale),
@@ -145,7 +145,7 @@ function clampView(view, box, image, options = {}) {
145
145
  }
146
146
  function clampAxis(t, boxLength, contentLength) {
147
147
  if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
148
- return clamp$1(t, boxLength - contentLength, 0);
148
+ return clamp$2(t, boxLength - contentLength, 0);
149
149
  }
150
150
  /**
151
151
  * The view that puts `rect` (image coordinates) on screen with a margin around it.
@@ -195,9 +195,15 @@ function preserveCenter(view, from, to, image, options = {}) {
195
195
  */
196
196
  function steppedScale(scale, direction, min, max) {
197
197
  const ladder = SCALE_LADDER.filter((s) => s >= min - 1e-9 && s <= max + 1e-9);
198
- const candidates = ladder.length > 0 ? ladder : [clamp$1(scale, min, max)];
199
- if (direction > 0) return candidates.find((s) => s > scale * 1.001) ?? Math.min(max, Math.max(scale, candidates[candidates.length - 1]));
200
- return [...candidates].reverse().find((s) => s < scale * .999) ?? Math.max(min, Math.min(scale, candidates[0]));
198
+ const candidates = ladder.length > 0 ? ladder : [clamp$2(scale, min, max)];
199
+ if (direction > 0) {
200
+ const next = candidates.find((s) => s > scale * 1.001);
201
+ if (next === void 0) return scale < max * .999 ? max : Math.min(max, scale);
202
+ return next;
203
+ }
204
+ const previous = [...candidates].reverse().find((s) => s < scale * .999);
205
+ if (previous === void 0) return scale > min * 1.001 ? min : Math.max(min, scale);
206
+ return previous;
201
207
  }
202
208
  /** `0.5` → `"50%"`, `1` → `"100%"`, `0.0833` → `"8%"`. */
203
209
  function formatScale(scale) {
@@ -206,7 +212,7 @@ function formatScale(scale) {
206
212
  if (percent >= 10) return `${Math.round(percent)}%`;
207
213
  return `${percent.toFixed(1)}%`;
208
214
  }
209
- function clamp$1(value, low, high) {
215
+ function clamp$2(value, low, high) {
210
216
  return Math.min(high, Math.max(low, value));
211
217
  }
212
218
  //#endregion
@@ -239,7 +245,7 @@ function clamp$1(value, low, high) {
239
245
  */
240
246
  const WHEEL_SENSITIVITY = .0015;
241
247
  /** How far a press may travel and still count as a click rather than a pan. */
242
- const CLICK_SLOP = 3;
248
+ const CLICK_SLOP$1 = 3;
243
249
  /** The view before the viewport has been measured — nothing is on screen yet. */
244
250
  const UNMEASURED_VIEW = {
245
251
  scale: 1,
@@ -267,7 +273,7 @@ function useStage() {
267
273
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
268
274
  * or absent.
269
275
  */
270
- function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas" }) {
276
+ function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", ref }) {
271
277
  const viewportRef = useRef(null);
272
278
  const [box, setBox] = useState({
273
279
  width: 0,
@@ -285,7 +291,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
285
291
  box,
286
292
  image,
287
293
  clamp,
288
- onView
294
+ onView,
295
+ opening
289
296
  });
290
297
  useLayoutEffect(() => {
291
298
  latestRef.current = {
@@ -293,16 +300,18 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
293
300
  box,
294
301
  image,
295
302
  clamp,
296
- onView
303
+ onView,
304
+ opening
297
305
  };
298
306
  });
299
307
  /** The view to come back to when a double-click leaves fit. */
300
308
  const previousRef = useRef(null);
301
309
  const dragRef = useRef(null);
302
- const effective = useMemo(() => view ?? (box.width > 0 ? initialView(box, image) : UNMEASURED_VIEW), [
310
+ const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW), [
303
311
  view,
304
312
  box,
305
- image
313
+ image,
314
+ opening
306
315
  ]);
307
316
  const commit = useCallback((next) => {
308
317
  const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
@@ -321,8 +330,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
321
330
  };
322
331
  measuredRef.current = next;
323
332
  setBox(next);
324
- const { view: v, image: i, clamp: c, onView: report } = latestRef.current;
325
- if (v === null) report(initialView(next, i));
333
+ const { view: v, image: i, clamp: c, onView: report, opening: o } = latestRef.current;
334
+ if (v === null) report(openingView(o, next, i));
326
335
  else if (!(current.width > 0)) report(clampView(v, next, i, c));
327
336
  else report(preserveCenter(v, current, next, i, c));
328
337
  };
@@ -422,6 +431,15 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
422
431
  if (!(b.width > 0)) return;
423
432
  report(frameRect(b, i, rect, pad));
424
433
  }, []);
434
+ useImperativeHandle(ref, () => ({
435
+ frame,
436
+ fit,
437
+ zoomTo
438
+ }), [
439
+ frame,
440
+ fit,
441
+ zoomTo
442
+ ]);
425
443
  const atFit = box.width > 0 && isFit(effective, box, image);
426
444
  const context = useMemo(() => ({
427
445
  view: effective,
@@ -473,7 +491,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
473
491
  }
474
492
  const dx = event.clientX - origin.x;
475
493
  const dy = event.clientY - origin.y;
476
- if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;
494
+ if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP$1) return;
477
495
  origin.moved = true;
478
496
  onHover?.(null);
479
497
  commit({
@@ -564,7 +582,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
564
582
  "data-fit": atFit ? "" : void 0,
565
583
  "data-panning": panning ? "" : void 0,
566
584
  "data-pan-mode": panMode ? "" : void 0,
567
- className: cn("relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
585
+ className: cn("@container/stage relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
568
586
  onPointerDown,
569
587
  onPointerMove,
570
588
  onPointerUp: endDrag,
@@ -589,12 +607,13 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
589
607
  children: banner
590
608
  }),
591
609
  (toolbar || readout) && /* @__PURE__ */ jsxs("div", {
592
- className: "pointer-events-none absolute inset-x-2 bottom-2 z-10 flex items-end justify-between gap-2",
610
+ className: "pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2",
593
611
  children: [/* @__PURE__ */ jsx("div", {
594
- className: "pointer-events-auto shrink-0",
612
+ className: "pointer-events-auto max-w-full shrink-0",
595
613
  children: toolbar
596
614
  }), /* @__PURE__ */ jsx("div", {
597
- className: "min-w-0 truncate",
615
+ "data-readout-slot": "",
616
+ className: "max-w-full min-w-0 truncate",
598
617
  children: readout
599
618
  })]
600
619
  })
@@ -602,6 +621,10 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
602
621
  })
603
622
  });
604
623
  }
624
+ /** The view a `null` view opens at, by the `initialView` policy. */
625
+ function openingView(opening, box, image) {
626
+ return opening === "fit" ? fitView(box, image) : initialView(box, image);
627
+ }
605
628
  function hoverPoint(event, element, view, image) {
606
629
  if (!element) return null;
607
630
  const origin = viewportOrigin(element);
@@ -640,6 +663,203 @@ function isTypingTarget(target) {
640
663
  return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
641
664
  }
642
665
  //#endregion
666
+ //#region src/components/stage/ImageLayer.tsx
667
+ /**
668
+ * The photograph, as a stage layer.
669
+ *
670
+ * The stage is laid out at the image's own pixel size, so the photograph is drawn at its
671
+ * natural size, with no `object-fit` letterbox for an overlay to disagree with.
672
+ *
673
+ * Two things every viewer of a large frame ends up doing by hand, done once here:
674
+ *
675
+ * - **A preview tier, then the full image.** A downscaled preview loads fast and is enough
676
+ * until it would be magnified — until the screen shows more pixels than it has. Past that
677
+ * point the full image is requested, and it stays once loaded, so zooming back out does
678
+ * not swap back. The preview stays underneath while the full image loads, so the frame
679
+ * never goes blank.
680
+ * - **Pixelated past a zoom.** Above about 4× the browser's smoothing paints detail the
681
+ * sensor never recorded; on a metrology bench the sensor's own samples are what is worth
682
+ * looking at.
683
+ */
684
+ /**
685
+ * The photograph at its natural size inside an `ImageStage`, with an optional preview tier
686
+ * and pixelated rendering past `pixelatedAbove`. It takes no pointer events, so presses reach
687
+ * the stage and the layers above.
688
+ *
689
+ * Each image carries `data-tier` (`preview` or `full`); the full image carries `data-loaded`
690
+ * once it has loaded, and both carry `data-pixelated` while pixelated.
691
+ */
692
+ function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onLoad, onError, className }) {
693
+ const stage = useStage();
694
+ const scale = stage.view.scale;
695
+ const measured = stage.box.width > 0;
696
+ const needsFull = preview === void 0 || measured && scale * stage.image.width > preview.width;
697
+ const [requested, setRequested] = useState(needsFull ? src : null);
698
+ if (needsFull && requested !== src) setRequested(src);
699
+ const [loaded, setLoaded] = useState(null);
700
+ const showFull = requested === src;
701
+ const fullReady = loaded === src;
702
+ const pixelated = scale >= pixelatedAbove;
703
+ const shared = cn("pointer-events-none absolute inset-0 h-full w-full select-none", className);
704
+ const rendering = pixelated ? "pixelated" : void 0;
705
+ return /* @__PURE__ */ jsxs(Fragment, { children: [preview && !fullReady && /* @__PURE__ */ jsx("img", {
706
+ src: preview.src,
707
+ alt: showFull ? "" : alt,
708
+ "aria-hidden": showFull ? true : void 0,
709
+ draggable: false,
710
+ "data-tier": "preview",
711
+ "data-pixelated": pixelated ? "" : void 0,
712
+ className: shared,
713
+ style: { imageRendering: rendering }
714
+ }), showFull && /* @__PURE__ */ jsx("img", {
715
+ src,
716
+ alt,
717
+ draggable: false,
718
+ "data-tier": "full",
719
+ "data-loaded": fullReady ? "" : void 0,
720
+ "data-pixelated": pixelated ? "" : void 0,
721
+ onLoad: () => {
722
+ setLoaded(src);
723
+ onLoad?.();
724
+ },
725
+ onError: () => onError?.(),
726
+ className: cn(shared, preview && !fullReady && "opacity-0"),
727
+ style: { imageRendering: rendering }
728
+ })] });
729
+ }
730
+ //#endregion
731
+ //#region src/components/stage/StageSurface.tsx
732
+ /**
733
+ * The stage's tool model: one place that decides what a press on the image means.
734
+ *
735
+ * Several layers usually want a full-frame target: one to draw a region, one to sweep a
736
+ * selection, one to place a point. Only the topmost element under the pointer receives a press,
737
+ * so two full-frame targets are one that always wins and one that never fires. Apps that grew
738
+ * such layers one by one found this out the hard way.
739
+ *
740
+ * The rule here is one surface per stage, under the layers' own small targets (a handle, a
741
+ * stroke). It asks the app what a press means, in priority order, and a press the app declines
742
+ * bubbles to the stage, which pans.
743
+ *
744
+ * Drags listen on `window`, not on the pressed element. `setPointerCapture` routes every later
745
+ * event to that one element, so a drag begun on a handle sent its moves to the handle, never
746
+ * to the surface that held the move logic. Listening at the window also lets a drag survive
747
+ * the pointer leaving the canvas, which is what dragging a corner outward does.
748
+ */
749
+ /** How far a press may travel and still be a click, in screen pixels. */
750
+ const CLICK_SLOP = 3;
751
+ /**
752
+ * Start a drag from a press on any element inside an `ImageStage`.
753
+ *
754
+ * The press is claimed: propagation stops, so the stage does not pan. Later moves and the
755
+ * release are read from `window` and converted to image coordinates. Call it from a
756
+ * `pointerdown` handler.
757
+ *
758
+ * @returns `start(event, drag)`.
759
+ */
760
+ function useStageDrag() {
761
+ const { toImage } = useStage();
762
+ const cleanupRef = useRef(null);
763
+ useEffect(() => () => cleanupRef.current?.(), []);
764
+ return useCallback((event, drag) => {
765
+ event.stopPropagation();
766
+ event.preventDefault();
767
+ cleanupRef.current?.();
768
+ const from = {
769
+ x: event.clientX,
770
+ y: event.clientY
771
+ };
772
+ let moved = false;
773
+ const at = (e) => toImage({
774
+ x: e.clientX,
775
+ y: e.clientY
776
+ });
777
+ const move = (e) => {
778
+ if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP) moved = true;
779
+ drag.onMove?.(at(e), e);
780
+ };
781
+ const up = (e) => {
782
+ stop();
783
+ drag.onEnd?.(at(e), e, moved);
784
+ };
785
+ const cancel = () => {
786
+ stop();
787
+ drag.onCancel?.();
788
+ };
789
+ const stop = () => {
790
+ window.removeEventListener("pointermove", move);
791
+ window.removeEventListener("pointerup", up);
792
+ window.removeEventListener("pointercancel", cancel);
793
+ cleanupRef.current = null;
794
+ };
795
+ window.addEventListener("pointermove", move);
796
+ window.addEventListener("pointerup", up);
797
+ window.addEventListener("pointercancel", cancel);
798
+ cleanupRef.current = cancel;
799
+ }, [toImage]);
800
+ }
801
+ /**
802
+ * The stage's one full-frame press target. Put it inside an `ImageStage`, below the layers
803
+ * that have their own small targets (handles, strokes). Each press is offered to `onPress`
804
+ * unless the hand tool or a held space bar make it a pan; a declined press pans.
805
+ *
806
+ * The surface draws nothing. It carries `data-dragging` while a drag it started is in
807
+ * flight.
808
+ */
809
+ function StageSurface({ onPress, cursor, onHover }) {
810
+ const stage = useStage();
811
+ const start = useStageDrag();
812
+ const [dragging, setDragging] = useState(false);
813
+ const onPointerDown = (event) => {
814
+ if (event.button !== 0 || stage.panMode) return;
815
+ const drag = onPress({
816
+ point: stage.toImage({
817
+ x: event.clientX,
818
+ y: event.clientY
819
+ }),
820
+ shiftKey: event.shiftKey,
821
+ altKey: event.altKey,
822
+ metaKey: event.metaKey || event.ctrlKey
823
+ });
824
+ if (!drag) return;
825
+ setDragging(true);
826
+ start(event, {
827
+ onMove: drag.onMove,
828
+ onEnd: (point, e, moved) => {
829
+ setDragging(false);
830
+ drag.onEnd?.(point, e, moved);
831
+ },
832
+ onCancel: () => {
833
+ setDragging(false);
834
+ drag.onCancel?.();
835
+ }
836
+ });
837
+ };
838
+ return /* @__PURE__ */ jsx("svg", {
839
+ viewBox: imageViewBox(stage.image),
840
+ className: "pointer-events-none absolute inset-0 h-full w-full",
841
+ "data-dragging": dragging ? "" : void 0,
842
+ "aria-hidden": true,
843
+ children: /* @__PURE__ */ jsx("rect", {
844
+ "data-stage-surface": "",
845
+ x: -.5,
846
+ y: -.5,
847
+ width: stage.image.width,
848
+ height: stage.image.height,
849
+ fill: "transparent",
850
+ className: "pointer-events-auto",
851
+ style: { cursor: stage.panMode ? void 0 : cursor },
852
+ onPointerDown,
853
+ onPointerMove: (event) => {
854
+ if (!dragging) onHover?.(stage.toImage({
855
+ x: event.clientX,
856
+ y: event.clientY
857
+ }));
858
+ }
859
+ })
860
+ });
861
+ }
862
+ //#endregion
643
863
  //#region src/components/stage/StageToolbar.tsx
644
864
  /**
645
865
  * The viewer's own controls, floating over the image rather than filed in a side panel.
@@ -669,6 +889,9 @@ const PRESETS = [
669
889
  *
670
890
  * The bar carries `data-fit` while the view is fit; the percentage button carries
671
891
  * `data-state="open"` or `"closed"` for its menu.
892
+ *
893
+ * On a canvas narrower than 30rem, zoom out, zoom in and 100% collapse: the percentage menu
894
+ * and the `+` / `-` / `1` keys still reach them, so the app's own groups keep their room.
672
895
  */
673
896
  function StageToolbar({ children, className }) {
674
897
  const stage = useStage();
@@ -694,6 +917,7 @@ function StageToolbar({ children, className }) {
694
917
  label: "Zoom out",
695
918
  onClick: () => step(-1),
696
919
  disabled: stage.view.scale <= min + 1e-9,
920
+ className: "@max-[30rem]/stage:hidden",
697
921
  children: /* @__PURE__ */ jsx(Minus, {
698
922
  className: "size-4",
699
923
  "aria-hidden": true
@@ -734,6 +958,7 @@ function StageToolbar({ children, className }) {
734
958
  label: "Zoom in",
735
959
  onClick: () => step(1),
736
960
  disabled: stage.view.scale >= Math.min(max, 32) - 1e-9,
961
+ className: "@max-[30rem]/stage:hidden",
737
962
  children: /* @__PURE__ */ jsx(Plus, {
738
963
  className: "size-4",
739
964
  "aria-hidden": true
@@ -751,6 +976,7 @@ function StageToolbar({ children, className }) {
751
976
  }),
752
977
  /* @__PURE__ */ jsx(StageButton, {
753
978
  label: "Actual size (100%)",
979
+ className: "@max-[30rem]/stage:hidden",
754
980
  onClick: () => stage.zoomTo(1),
755
981
  pressed: !stage.isFit && Math.abs(stage.view.scale - 1) < 1e-6,
756
982
  children: /* @__PURE__ */ jsx(Scan, {
@@ -766,18 +992,64 @@ function StageToolbar({ children, className }) {
766
992
  * The bar's own button shape, exported so app groups match it exactly. An icon button
767
993
  * named by `label`; a toggle when `pressed` is given, exposed as `aria-pressed` and
768
994
  * `data-state="on"` or `"off"`. Other button props (and `ref`) are passed through.
995
+ *
996
+ * Its tooltip is the native `title` (the label), or with `hint` / `shortcut` the ui
997
+ * `Tooltip`: the label, the hint, and the shortcut as a key cap.
769
998
  */
770
- function StageButton({ label, pressed, className, children, ...props }) {
771
- return /* @__PURE__ */ jsx("button", {
999
+ function StageButton({ label, pressed, hint, shortcut, className, children, ...props }) {
1000
+ const rich = hint !== void 0 || shortcut !== void 0;
1001
+ const button = /* @__PURE__ */ jsx("button", {
772
1002
  ...props,
773
1003
  type: "button",
774
- title: label,
1004
+ title: rich ? void 0 : label,
775
1005
  "aria-label": label,
1006
+ "aria-keyshortcuts": shortcut,
776
1007
  "aria-pressed": pressed,
777
1008
  "data-state": pressed === void 0 ? void 0 : pressed ? "on" : "off",
778
1009
  className: cn("grid size-7 place-items-center rounded-control text-fg-muted transition-colors", "hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40", pressed && "bg-signal/15 text-signal", focusRing, className),
779
1010
  children
780
1011
  });
1012
+ if (!rich) return button;
1013
+ return /* @__PURE__ */ jsx(Tooltip, {
1014
+ content: /* @__PURE__ */ jsxs("span", {
1015
+ className: "flex items-center gap-2",
1016
+ children: [/* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("span", {
1017
+ className: "font-medium",
1018
+ children: label
1019
+ }), hint !== void 0 && /* @__PURE__ */ jsx("span", {
1020
+ className: "block text-fg-muted",
1021
+ children: hint
1022
+ })] }), shortcut && /* @__PURE__ */ jsx(Kbd, { children: shortcut })]
1023
+ }),
1024
+ children: button
1025
+ });
1026
+ }
1027
+ /**
1028
+ * A `StageButton`-shaped trigger opening a menu of layer toggles, for `StageToolbar`'s
1029
+ * children. Each layer is a `menuitemcheckbox`; toggling one keeps the menu open for the
1030
+ * next. The trigger shows as pressed while any layer is hidden, so a canvas missing a layer
1031
+ * says so before the menu is opened.
1032
+ */
1033
+ function StageLayersMenu({ layers, onVisibleChange, label = "Layers" }) {
1034
+ const hidden = layers.some((layer) => !layer.visible && !layer.disabled);
1035
+ return /* @__PURE__ */ jsxs(DropdownMenu, {
1036
+ side: "top",
1037
+ trigger: /* @__PURE__ */ jsx(StageButton, {
1038
+ label,
1039
+ pressed: hidden,
1040
+ children: /* @__PURE__ */ jsx(Layers, {
1041
+ className: "size-4",
1042
+ "aria-hidden": true
1043
+ })
1044
+ }),
1045
+ children: [/* @__PURE__ */ jsx(MenuLabel, { children: label }), layers.map((layer) => /* @__PURE__ */ jsx(MenuCheckboxItem, {
1046
+ checked: layer.visible,
1047
+ onCheckedChange: (visible) => onVisibleChange(layer.id, visible),
1048
+ disabled: layer.disabled,
1049
+ shortcut: layer.shortcut,
1050
+ children: layer.label
1051
+ }, layer.id))]
1052
+ });
781
1053
  }
782
1054
  /** A thin vertical rule between groups of `StageButton`s. Decorative (`aria-hidden`). */
783
1055
  function StageToolbarDivider({ className }) {
@@ -875,7 +1147,7 @@ const FULL_TIER_ZOOM = 2;
875
1147
  * `t' = p − (p − t)·z'/z`, with `p` measured from the centre.
876
1148
  */
877
1149
  function zoomAt(view, pointer, rect, factor) {
878
- const zoom = clamp(view.zoom * factor, 1, 12);
1150
+ const zoom = clamp$1(view.zoom * factor, 1, 12);
879
1151
  if (zoom === 1) return RESET_VIEW;
880
1152
  const px = pointer.x - rect.left - rect.width / 2;
881
1153
  const py = pointer.y - rect.top - rect.height / 2;
@@ -917,9 +1189,9 @@ function contentUnder(view, pointer, rect) {
917
1189
  */
918
1190
  function nativeZoomFor(sourceWidth, boxWidth) {
919
1191
  if (!(sourceWidth > 0) || !(boxWidth > 0)) return 2;
920
- return clamp(sourceWidth / boxWidth, 1, 12);
1192
+ return clamp$1(sourceWidth / boxWidth, 1, 12);
921
1193
  }
922
- function clamp(value, low, high) {
1194
+ function clamp$1(value, low, high) {
923
1195
  return Math.min(high, Math.max(low, value));
924
1196
  }
925
1197
  /**
@@ -1340,17 +1612,296 @@ function dimensionGeometry(x1, y1, x2, y2, offset) {
1340
1612
  };
1341
1613
  }
1342
1614
  //#endregion
1615
+ //#region src/components/overlayRole.ts
1616
+ /** The roles, in the order the spec lists them. */
1617
+ const OVERLAY_ROLES = [
1618
+ "feature",
1619
+ "model",
1620
+ "structure",
1621
+ "selection",
1622
+ "label",
1623
+ "halo"
1624
+ ];
1625
+ /**
1626
+ * The CSS paint for a role: a `var(--stage-…)` reference defined by `@vitavision/stage2d/styles.css`.
1627
+ *
1628
+ * @param role - The role.
1629
+ * @returns A CSS value usable as an SVG `stroke` or `fill`.
1630
+ */
1631
+ function overlayRole(role) {
1632
+ return `var(--stage-${role})`;
1633
+ }
1634
+ /** Screen-pixel stroke widths for each state, before the stage's scale is applied. */
1635
+ const OVERLAY_STATE_WIDTH = {
1636
+ default: 1.5,
1637
+ hover: 2,
1638
+ selected: 2.5,
1639
+ dimmed: 1.5
1640
+ };
1641
+ /** Opacity for each state. */
1642
+ const OVERLAY_STATE_OPACITY = {
1643
+ default: 1,
1644
+ hover: 1,
1645
+ selected: 1,
1646
+ dimmed: .35
1647
+ };
1648
+ //#endregion
1649
+ //#region src/components/polylineIndex.ts
1650
+ /**
1651
+ * The number of segments of a polyline.
1652
+ *
1653
+ * @param points - Flat points.
1654
+ * @param closed - Whether the last point joins the first.
1655
+ * @returns The segment count.
1656
+ */
1657
+ function segmentCount(points, closed) {
1658
+ const n = Math.floor(points.length / 2);
1659
+ if (n < 2) return n === 1 ? 1 : 0;
1660
+ return closed ? n : n - 1;
1661
+ }
1662
+ /** The start and end of segment `s` (a single point is its own segment). */
1663
+ function segment(points, s) {
1664
+ const n = Math.floor(points.length / 2);
1665
+ const b = n === 1 ? 0 : (s + 1) % n;
1666
+ return [
1667
+ points[2 * s],
1668
+ points[2 * s + 1],
1669
+ points[2 * b],
1670
+ points[2 * b + 1]
1671
+ ];
1672
+ }
1673
+ /**
1674
+ * Index a set of polylines.
1675
+ *
1676
+ * @param items - The polylines.
1677
+ * @param cell - The grid cell side in image pixels. Defaults to 32: a few segments per cell
1678
+ * at contour densities, and a pointer's search radius spans one or two cells.
1679
+ * @returns The index.
1680
+ */
1681
+ function buildPolylineIndex(items, cell = 32) {
1682
+ let minX = Infinity;
1683
+ let minY = Infinity;
1684
+ let maxX = -Infinity;
1685
+ let maxY = -Infinity;
1686
+ for (const item of items) {
1687
+ const p = item.points;
1688
+ for (let i = 0; i + 1 < p.length; i += 2) {
1689
+ const x = p[i];
1690
+ const y = p[i + 1];
1691
+ if (x < minX) minX = x;
1692
+ if (x > maxX) maxX = x;
1693
+ if (y < minY) minY = y;
1694
+ if (y > maxY) maxY = y;
1695
+ }
1696
+ }
1697
+ if (!(maxX >= minX)) return {
1698
+ items,
1699
+ cell,
1700
+ x0: 0,
1701
+ y0: 0,
1702
+ cols: 1,
1703
+ rows: 1,
1704
+ starts: /* @__PURE__ */ new Uint32Array(2),
1705
+ segs: /* @__PURE__ */ new Uint32Array(0)
1706
+ };
1707
+ const cols = Math.max(1, Math.ceil((maxX - minX) / cell) + 1);
1708
+ const rows = Math.max(1, Math.ceil((maxY - minY) / cell) + 1);
1709
+ const cellX = (x) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell)));
1710
+ const cellY = (y) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell)));
1711
+ const counts = new Uint32Array(cols * rows + 1);
1712
+ const visit = (fn) => {
1713
+ items.forEach((item, index) => {
1714
+ const closed = item.closed === true;
1715
+ const count = segmentCount(item.points, closed);
1716
+ for (let s = 0; s < count; s++) {
1717
+ const [ax, ay, bx, by] = segment(item.points, s);
1718
+ const cx0 = cellX(Math.min(ax, bx));
1719
+ const cx1 = cellX(Math.max(ax, bx));
1720
+ const cy0 = cellY(Math.min(ay, by));
1721
+ const cy1 = cellY(Math.max(ay, by));
1722
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, index, s);
1723
+ }
1724
+ });
1725
+ };
1726
+ visit((c) => counts[c + 1]++);
1727
+ for (let c = 0; c < cols * rows; c++) counts[c + 1] += counts[c];
1728
+ const starts = counts;
1729
+ const fill = starts.slice(0, cols * rows);
1730
+ const segs = new Uint32Array(starts[cols * rows] * 2);
1731
+ visit((c, item, s) => {
1732
+ const k = fill[c]++;
1733
+ segs[2 * k] = item;
1734
+ segs[2 * k + 1] = s;
1735
+ });
1736
+ return {
1737
+ items,
1738
+ cell,
1739
+ x0: minX,
1740
+ y0: minY,
1741
+ cols,
1742
+ rows,
1743
+ starts,
1744
+ segs
1745
+ };
1746
+ }
1747
+ /**
1748
+ * The polyline nearest to `p` within `radius`, or `null`.
1749
+ *
1750
+ * @param index - The index.
1751
+ * @param p - The point, in image coordinates.
1752
+ * @param radius - The search radius, in image pixels.
1753
+ * @returns The nearest polyline, the closest point on it and the distance; ties go to the
1754
+ * earlier polyline, so the result does not depend on cell order.
1755
+ */
1756
+ function nearestPolyline(index, p, radius) {
1757
+ const { items, cell, x0, y0, cols, rows, starts, segs } = index;
1758
+ const cx0 = Math.max(0, Math.floor((p.x - radius - x0) / cell));
1759
+ const cx1 = Math.min(cols - 1, Math.floor((p.x + radius - x0) / cell));
1760
+ const cy0 = Math.max(0, Math.floor((p.y - radius - y0) / cell));
1761
+ const cy1 = Math.min(rows - 1, Math.floor((p.y + radius - y0) / cell));
1762
+ let best = null;
1763
+ let bestItem = Infinity;
1764
+ let bestD = radius * radius;
1765
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
1766
+ const c = cy * cols + cx;
1767
+ for (let k = starts[c]; k < starts[c + 1]; k++) {
1768
+ const itemIndex = segs[2 * k];
1769
+ const item = items[itemIndex];
1770
+ const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]);
1771
+ const q = closestOnSegment(p, ax, ay, bx, by);
1772
+ const d = (q.x - p.x) ** 2 + (q.y - p.y) ** 2;
1773
+ if (d < bestD || d === bestD && itemIndex < bestItem) {
1774
+ bestD = d;
1775
+ bestItem = itemIndex;
1776
+ best = {
1777
+ id: item.id,
1778
+ point: q,
1779
+ distance: Math.sqrt(d)
1780
+ };
1781
+ }
1782
+ }
1783
+ }
1784
+ return best;
1785
+ }
1786
+ /**
1787
+ * The polylines with any part inside `rect`, in the order they were given.
1788
+ *
1789
+ * Any part, not any vertex: a long straight contour crossing a rubber band has no vertex
1790
+ * inside it and is still what the band was aimed at.
1791
+ *
1792
+ * @param index - The index.
1793
+ * @param rect - The band, in image coordinates.
1794
+ * @returns Their ids.
1795
+ */
1796
+ function polylinesInRect(index, rect) {
1797
+ const { items, cell, x0, y0, cols, rows, starts, segs } = index;
1798
+ const hit = new Uint8Array(items.length);
1799
+ const cx0 = Math.max(0, Math.floor((rect.x - x0) / cell));
1800
+ const cx1 = Math.min(cols - 1, Math.floor((rect.x + rect.width - x0) / cell));
1801
+ const cy0 = Math.max(0, Math.floor((rect.y - y0) / cell));
1802
+ const cy1 = Math.min(rows - 1, Math.floor((rect.y + rect.height - y0) / cell));
1803
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
1804
+ const c = cy * cols + cx;
1805
+ for (let k = starts[c]; k < starts[c + 1]; k++) {
1806
+ const itemIndex = segs[2 * k];
1807
+ if (hit[itemIndex]) continue;
1808
+ const item = items[itemIndex];
1809
+ const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]);
1810
+ if (segmentTouchesRect(ax, ay, bx, by, rect)) hit[itemIndex] = 1;
1811
+ }
1812
+ }
1813
+ const ids = [];
1814
+ items.forEach((item, i) => {
1815
+ if (hit[i]) ids.push(item.id);
1816
+ });
1817
+ return ids;
1818
+ }
1819
+ /**
1820
+ * A polyline as an SVG path (`M … L … Z`).
1821
+ *
1822
+ * @param points - Flat points.
1823
+ * @param closed - Whether to close it.
1824
+ * @returns The path data; `""` with no points.
1825
+ */
1826
+ function polylinePath(points, closed = false) {
1827
+ if (points.length < 2) return "";
1828
+ let d = `M${points[0]} ${points[1]}`;
1829
+ if (points.length < 4) return `${d}L${points[0]} ${points[1]}`;
1830
+ for (let i = 2; i + 1 < points.length; i += 2) d += `L${points[i]} ${points[i + 1]}`;
1831
+ return closed ? `${d}Z` : d;
1832
+ }
1833
+ /**
1834
+ * The bounding box of flat points.
1835
+ *
1836
+ * @param points - Flat points.
1837
+ * @returns The box, or `null` without points.
1838
+ */
1839
+ function polylineBounds(points) {
1840
+ if (points.length < 2) return null;
1841
+ let minX = Infinity;
1842
+ let minY = Infinity;
1843
+ let maxX = -Infinity;
1844
+ let maxY = -Infinity;
1845
+ for (let i = 0; i + 1 < points.length; i += 2) {
1846
+ const x = points[i];
1847
+ const y = points[i + 1];
1848
+ if (x < minX) minX = x;
1849
+ if (x > maxX) maxX = x;
1850
+ if (y < minY) minY = y;
1851
+ if (y > maxY) maxY = y;
1852
+ }
1853
+ return {
1854
+ x: minX,
1855
+ y: minY,
1856
+ width: maxX - minX,
1857
+ height: maxY - minY
1858
+ };
1859
+ }
1860
+ function closestOnSegment(p, ax, ay, bx, by) {
1861
+ const dx = bx - ax;
1862
+ const dy = by - ay;
1863
+ const len2 = dx * dx + dy * dy;
1864
+ const t = len2 > 0 ? Math.max(0, Math.min(1, ((p.x - ax) * dx + (p.y - ay) * dy) / len2)) : 0;
1865
+ return {
1866
+ x: ax + t * dx,
1867
+ y: ay + t * dy
1868
+ };
1869
+ }
1870
+ /** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
1871
+ function segmentTouchesRect(ax, ay, bx, by, r) {
1872
+ const xmin = r.x;
1873
+ const xmax = r.x + r.width;
1874
+ const ymin = r.y;
1875
+ const ymax = r.y + r.height;
1876
+ let t0 = 0;
1877
+ let t1 = 1;
1878
+ const dx = bx - ax;
1879
+ const dy = by - ay;
1880
+ const clip = (p, q) => {
1881
+ if (p === 0) return q >= 0;
1882
+ const t = q / p;
1883
+ if (p < 0) {
1884
+ if (t > t1) return false;
1885
+ if (t > t0) t0 = t;
1886
+ } else {
1887
+ if (t < t0) return false;
1888
+ if (t < t1) t1 = t;
1889
+ }
1890
+ return true;
1891
+ };
1892
+ return clip(-dx, ax - xmin) && clip(dx, xmax - ax) && clip(-dy, ay - ymin) && clip(dy, ymax - ay);
1893
+ }
1894
+ //#endregion
1343
1895
  //#region src/components/MeasureOverlay.tsx
1344
1896
  /**
1345
1897
  * A vector overlay layer for measurement primitives, drawn in source-image pixel
1346
1898
  * coordinates.
1347
1899
  *
1348
- * Meant to sit as one of the transformed children inside `ZoomPanCanvas`, alongside the
1349
- * image itself and any raster layers (a mask, a false-colour value plane). Because the
1350
- * whole stack is transformed together (see `ZoomPanCanvas`'s own docs), a caliper box
1351
- * drawn here stays registered with the pixel it measures at any zoom or pan — the overlay
1352
- * never touches the DOM to find out where it is; it is told, in `nativeWidth` ×
1353
- * `nativeHeight` pixel coordinates, via `primitives`.
1900
+ * Meant to sit as one of the layers inside `ImageStage`, alongside the image itself and any
1901
+ * raster layers (a mask, a false-colour value plane). Because the whole stack is transformed
1902
+ * together, a caliper box drawn here stays registered with the pixel it measures at any zoom
1903
+ * or pan. The overlay never touches the DOM to find out where it is; it is told, in
1904
+ * `nativeWidth` × `nativeHeight` pixel coordinates, via `primitives`.
1354
1905
  *
1355
1906
  * This component holds **no app state**: no fetch, no selection, no hover tracking. It is a
1356
1907
  * pure function of its props, on purpose — the app decides what a "caliper box" or a
@@ -1364,12 +1915,17 @@ const DEFAULT_POINT_RADIUS = 3;
1364
1915
  const DEFAULT_CROSS_SIZE = 5;
1365
1916
  const DEFAULT_DIMENSION_OFFSET = 16;
1366
1917
  /**
1367
- * A vector overlay of measurement primitives — points, segments, circles, arcs, caliper
1368
- * boxes, dimensions — drawn in source-image pixel coordinates.
1918
+ * A vector overlay of measurement primitives — points, segments, polylines, circles, arcs,
1919
+ * caliper boxes, dimensions — drawn in source-image pixel coordinates.
1369
1920
  *
1370
1921
  * Place it as a layer inside `ImageStage` so it moves with the image. It is a pure function
1371
1922
  * of its props and decorative to assistive technology (`aria-hidden`), so a result drawn
1372
1923
  * only here must also be stated in text.
1924
+ *
1925
+ * A primitive's colour is its `role` (overlay grammar) if given, else its verdict `tone`.
1926
+ * Its `state` follows the overlay grammar: `hover` thickens it, `selected` thickens it and
1927
+ * rings it in the selection colour, and `dimmed` fades it. Each primitive is a `<g>` carrying
1928
+ * `data-kind`, plus `data-id` and `data-state` when given.
1373
1929
  */
1374
1930
  function MeasureOverlay({ nativeWidth, nativeHeight, primitives, strokeScale, className }) {
1375
1931
  const hairline = strokeWidthFor(strokeScale, 1);
@@ -1384,17 +1940,39 @@ function MeasureOverlay({ nativeWidth, nativeHeight, primitives, strokeScale, cl
1384
1940
  }),
1385
1941
  preserveAspectRatio: "none",
1386
1942
  className: cn("pointer-events-none absolute inset-0 h-full w-full overflow-visible", className),
1387
- children: primitives.map((primitive, index) => /* @__PURE__ */ jsx(Primitive, {
1388
- primitive,
1389
- hairline,
1390
- thick,
1391
- labelSize,
1392
- strokeScale
1393
- }, index))
1943
+ children: primitives.map((primitive, index) => {
1944
+ const state = primitive.state ?? "default";
1945
+ const colour = primitive.role ? overlayRole(primitive.role) : toneColor(primitive.tone);
1946
+ const widen = state === "hover" ? 2 / 1.5 : state === "selected" ? 2.5 / 1.5 : 1;
1947
+ return /* @__PURE__ */ jsxs("g", {
1948
+ "data-kind": primitive.kind,
1949
+ "data-id": primitive.id,
1950
+ "data-state": primitive.state,
1951
+ opacity: OVERLAY_STATE_OPACITY[state] === 1 ? void 0 : OVERLAY_STATE_OPACITY[state],
1952
+ children: [state === "selected" && /* @__PURE__ */ jsx("g", {
1953
+ opacity: .6,
1954
+ children: /* @__PURE__ */ jsx(Primitive, {
1955
+ primitive,
1956
+ colour: overlayRole("selection"),
1957
+ hairline: hairline * widen + strokeWidthFor(strokeScale, 3),
1958
+ thick: thick * widen + strokeWidthFor(strokeScale, 3),
1959
+ labelSize: 0,
1960
+ strokeScale,
1961
+ ring: true
1962
+ })
1963
+ }), /* @__PURE__ */ jsx(Primitive, {
1964
+ primitive,
1965
+ colour,
1966
+ hairline: hairline * widen,
1967
+ thick: thick * widen,
1968
+ labelSize,
1969
+ strokeScale
1970
+ })]
1971
+ }, index);
1972
+ })
1394
1973
  });
1395
1974
  }
1396
- function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
1397
- const colour = toneColor(primitive.tone);
1975
+ function Primitive({ primitive, colour, hairline, thick, labelSize, strokeScale, ring = false }) {
1398
1976
  switch (primitive.kind) {
1399
1977
  case "point": {
1400
1978
  if (primitive.cross) {
@@ -1426,7 +2004,7 @@ function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
1426
2004
  ]
1427
2005
  });
1428
2006
  }
1429
- const radius = strokeWidthFor(strokeScale, primitive.radius ?? DEFAULT_POINT_RADIUS);
2007
+ const radius = strokeWidthFor(strokeScale, (primitive.radius ?? DEFAULT_POINT_RADIUS) + (ring ? 2 : 0));
1430
2008
  return /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("circle", {
1431
2009
  cx: primitive.x,
1432
2010
  cy: primitive.y,
@@ -1453,8 +2031,8 @@ function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
1453
2031
  cx: primitive.cx,
1454
2032
  cy: primitive.cy,
1455
2033
  r: primitive.r,
1456
- fill: primitive.filled ? colour : "none",
1457
- stroke: primitive.filled ? "none" : colour,
2034
+ fill: primitive.filled && !ring ? colour : "none",
2035
+ stroke: primitive.filled && !ring ? "none" : colour,
1458
2036
  strokeWidth: hairline
1459
2037
  });
1460
2038
  case "arc": return /* @__PURE__ */ jsx("path", {
@@ -1497,6 +2075,21 @@ function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
1497
2075
  })
1498
2076
  ] });
1499
2077
  }
2078
+ case "polyline": return /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("path", {
2079
+ d: polylinePath(primitive.points, primitive.closed === true),
2080
+ fill: "none",
2081
+ stroke: colour,
2082
+ strokeWidth: hairline,
2083
+ strokeLinecap: "round",
2084
+ strokeLinejoin: "round",
2085
+ strokeDasharray: primitive.dashed ? `${hairline * 4} ${hairline * 3}` : void 0
2086
+ }), primitive.points.length >= 2 && /* @__PURE__ */ jsx(Label, {
2087
+ x: primitive.points[0],
2088
+ y: primitive.points[1] - strokeWidthFor(strokeScale, 4),
2089
+ text: primitive.label,
2090
+ colour,
2091
+ size: labelSize
2092
+ })] });
1500
2093
  case "dimension": {
1501
2094
  const offset = primitive.offset ?? DEFAULT_DIMENSION_OFFSET;
1502
2095
  const geometry = dimensionGeometry(primitive.x1, primitive.y1, primitive.x2, primitive.y2, offset);
@@ -1542,7 +2135,7 @@ function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
1542
2135
  }
1543
2136
  }
1544
2137
  function Label({ x, y, text, colour, size }) {
1545
- if (!text) return null;
2138
+ if (!text || !(size > 0)) return null;
1546
2139
  return /* @__PURE__ */ jsx("text", {
1547
2140
  x,
1548
2141
  y,
@@ -1554,6 +2147,21 @@ function Label({ x, y, text, colour, size }) {
1554
2147
  });
1555
2148
  }
1556
2149
  //#endregion
2150
+ //#region src/components/stage/useScreenPx.ts
2151
+ /**
2152
+ * Screen-constant geometry for a layer inside an `ImageStage`.
2153
+ */
2154
+ /**
2155
+ * A function from screen pixels to image pixels at the current zoom. A stroke, handle or
2156
+ * label drawn `px(1.5)` wide stays 1.5 screen pixels at every zoom (the overlay grammar's
2157
+ * rule).
2158
+ *
2159
+ * @returns `px(css)`.
2160
+ */
2161
+ function useScreenPx() {
2162
+ return useStage().imageLength;
2163
+ }
2164
+ //#endregion
1557
2165
  //#region src/components/ContourEditor.tsx
1558
2166
  /** Reusable source-image contour overlay and vertex editor for ImageStage. */
1559
2167
  /** Return the index of the closest segment, with the last vertex joined to the first. */
@@ -1734,6 +2342,624 @@ function ContourEditor({ points, onChange, onCommit, editable = false, label = "
1734
2342
  });
1735
2343
  }
1736
2344
  //#endregion
2345
+ //#region src/components/roiEdit.ts
2346
+ /** The eight handles, clockwise from the top-left corner. */
2347
+ const ROI_HANDLES = [
2348
+ "nw",
2349
+ "n",
2350
+ "ne",
2351
+ "e",
2352
+ "se",
2353
+ "s",
2354
+ "sw",
2355
+ "w"
2356
+ ];
2357
+ /** The CSS resize cursor for each handle, so the affordance is legible before the press. */
2358
+ const ROI_HANDLE_CURSOR = {
2359
+ nw: "nwse-resize",
2360
+ n: "ns-resize",
2361
+ ne: "nesw-resize",
2362
+ e: "ew-resize",
2363
+ se: "nwse-resize",
2364
+ s: "ns-resize",
2365
+ sw: "nesw-resize",
2366
+ w: "ew-resize"
2367
+ };
2368
+ /**
2369
+ * Where a handle sits.
2370
+ *
2371
+ * @param rect - The region.
2372
+ * @param handle - The handle.
2373
+ * @returns The handle's centre.
2374
+ */
2375
+ function roiHandlePoint(rect, handle) {
2376
+ const { x, y, width: w, height: h } = rect;
2377
+ const cx = x + w / 2;
2378
+ const cy = y + h / 2;
2379
+ return {
2380
+ x: handle.includes("w") ? x : handle.includes("e") ? x + w : cx,
2381
+ y: handle.includes("n") ? y : handle.includes("s") ? y + h : cy
2382
+ };
2383
+ }
2384
+ /**
2385
+ * The box spanned by two corners, with positive width and height whichever way it was
2386
+ * dragged.
2387
+ *
2388
+ * @param a - One corner.
2389
+ * @param b - The opposite corner.
2390
+ * @returns The normalised box.
2391
+ */
2392
+ function rectFromCorners(a, b) {
2393
+ return {
2394
+ x: Math.min(a.x, b.x),
2395
+ y: Math.min(a.y, b.y),
2396
+ width: Math.abs(b.x - a.x),
2397
+ height: Math.abs(b.y - a.y)
2398
+ };
2399
+ }
2400
+ /**
2401
+ * A box held inside `bounds`, and no smaller than `minSize` on either side, unless `bounds`
2402
+ * itself is smaller.
2403
+ *
2404
+ * @param rect - The box.
2405
+ * @param bounds - The area it must stay in.
2406
+ * @param minSize - The smallest side.
2407
+ * @returns The clamped box.
2408
+ */
2409
+ function clampRect(rect, bounds, minSize) {
2410
+ const width = Math.min(Math.max(rect.width, minSize), bounds.width);
2411
+ const height = Math.min(Math.max(rect.height, minSize), bounds.height);
2412
+ return {
2413
+ x: clamp(rect.x, bounds.x, bounds.x + bounds.width - width),
2414
+ y: clamp(rect.y, bounds.y, bounds.y + bounds.height - height),
2415
+ width,
2416
+ height
2417
+ };
2418
+ }
2419
+ /**
2420
+ * Drag a handle to `to`.
2421
+ *
2422
+ * The dragged edge follows the pointer and the opposite edge stays put, which is what makes
2423
+ * a handle feel attached to the corner it is drawn on. Dragging an edge through its opposite
2424
+ * flips the box instead of clamping it to zero: a clamp leaves the pointer moving and the box
2425
+ * not, which reads as the drag having died.
2426
+ *
2427
+ * @param rect - The box before the drag.
2428
+ * @param handle - The handle being dragged.
2429
+ * @param to - The pointer, in image coordinates.
2430
+ * @param bounds - The area the box must stay in.
2431
+ * @param minSize - The smallest side.
2432
+ * @returns The resized box.
2433
+ */
2434
+ function resizeRect(rect, handle, to, bounds, minSize) {
2435
+ let left = rect.x;
2436
+ let top = rect.y;
2437
+ let right = rect.x + rect.width;
2438
+ let bottom = rect.y + rect.height;
2439
+ const px = clamp(to.x, bounds.x, bounds.x + bounds.width);
2440
+ const py = clamp(to.y, bounds.y, bounds.y + bounds.height);
2441
+ if (handle.includes("w")) left = px;
2442
+ if (handle.includes("e")) right = px;
2443
+ if (handle.includes("n")) top = py;
2444
+ if (handle.includes("s")) bottom = py;
2445
+ return clampRect(rectFromCorners({
2446
+ x: left,
2447
+ y: top
2448
+ }, {
2449
+ x: right,
2450
+ y: bottom
2451
+ }), bounds, minSize);
2452
+ }
2453
+ /**
2454
+ * Move the whole box, held inside `bounds` without changing its size.
2455
+ *
2456
+ * @param rect - The box.
2457
+ * @param dx - Horizontal shift.
2458
+ * @param dy - Vertical shift.
2459
+ * @param bounds - The area it must stay in.
2460
+ * @returns The moved box.
2461
+ */
2462
+ function moveRect(rect, dx, dy, bounds) {
2463
+ return {
2464
+ x: clamp(rect.x + dx, bounds.x, Math.max(bounds.x, bounds.x + bounds.width - rect.width)),
2465
+ y: clamp(rect.y + dy, bounds.y, Math.max(bounds.y, bounds.y + bounds.height - rect.height)),
2466
+ width: rect.width,
2467
+ height: rect.height
2468
+ };
2469
+ }
2470
+ /**
2471
+ * Whether two boxes are the same, to within `epsilon`. Useful for telling whether a region
2472
+ * still matches the one a result was computed for.
2473
+ *
2474
+ * @param a - A box, or `null`.
2475
+ * @param b - A box, or `null`.
2476
+ * @param epsilon - The tolerance. Defaults to 1e-6.
2477
+ * @returns `true` for two equal boxes, or two `null`s.
2478
+ */
2479
+ function sameRect(a, b, epsilon = 1e-6) {
2480
+ if (a === null || b === null) return a === b;
2481
+ return Math.abs(a.x - b.x) < epsilon && Math.abs(a.y - b.y) < epsilon && Math.abs(a.width - b.width) < epsilon && Math.abs(a.height - b.height) < epsilon;
2482
+ }
2483
+ function clamp(value, low, high) {
2484
+ return Math.min(high, Math.max(low, value));
2485
+ }
2486
+ //#endregion
2487
+ //#region src/components/RectRoiEditor.tsx
2488
+ /**
2489
+ * A region of interest as an object rather than a gesture: drawn, moved and resized on the
2490
+ * image, kept inside it.
2491
+ *
2492
+ * Its predecessors in the apps could only draw a *new* box: every press started again from a
2493
+ * corner, so a box that was nearly right had to be redrawn, and one drawn at fit could not
2494
+ * be refined by zooming in first. Here the box has eight handles and an interior, and it lives
2495
+ * inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.
2496
+ */
2497
+ /** Handle square side, in screen pixels. */
2498
+ const HANDLE_PX = 9;
2499
+ /** Outline width, in screen pixels. */
2500
+ const STROKE_PX = 1.5;
2501
+ const HALO$1 = overlayRole("halo");
2502
+ /**
2503
+ * An editable axis-aligned region inside an `ImageStage`.
2504
+ *
2505
+ * - **Handles.** The eight handles resize the region, and the interior moves it. A handle
2506
+ * dragged through the opposite edge flips the box.
2507
+ * - **Drawing.** With `draw`, a drag elsewhere on the image draws a new region.
2508
+ * - **Keyboard.** The region is focusable: arrow keys move it by one image pixel (ten with
2509
+ * Shift), and with Alt they grow or shrink it from the bottom-right corner.
2510
+ * - **Limits.** The region stays inside `bounds` and never gets smaller than `minSize`.
2511
+ * - **Rendering.** Handles and the outline are a constant size on screen at every zoom.
2512
+ * - **Panning.** A press with the hand tool, or with space held, still pans.
2513
+ *
2514
+ * The SVG carries `data-editable` and `data-drawing` (while a draw is in progress).
2515
+ */
2516
+ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw = false, bounds, minSize = 4, label = "Region", stroke = overlayRole("selection") }) {
2517
+ const stage = useStage();
2518
+ const area = bounds ?? {
2519
+ x: 0,
2520
+ y: 0,
2521
+ width: stage.image.width,
2522
+ height: stage.image.height
2523
+ };
2524
+ const dragRef = useRef(null);
2525
+ const lastRef = useRef(null);
2526
+ const [drawing, setDrawing] = useState(null);
2527
+ const px = useScreenPx();
2528
+ const shown = drawing ?? value;
2529
+ const report = (next) => {
2530
+ lastRef.current = next;
2531
+ onValueChange(next);
2532
+ };
2533
+ const begin = (event, drag) => {
2534
+ if (stage.panMode || event.button !== 0) return;
2535
+ event.stopPropagation();
2536
+ event.preventDefault();
2537
+ event.currentTarget.setPointerCapture(event.pointerId);
2538
+ dragRef.current = drag;
2539
+ lastRef.current = null;
2540
+ };
2541
+ const onMove = (event) => {
2542
+ const drag = dragRef.current;
2543
+ if (!drag) return;
2544
+ event.stopPropagation();
2545
+ const p = stage.toImage({
2546
+ x: event.clientX,
2547
+ y: event.clientY
2548
+ });
2549
+ drag.moved = true;
2550
+ if (drag.kind === "move") report(moveRect(drag.start, p.x - drag.from.x, p.y - drag.from.y, area));
2551
+ else if (drag.kind === "resize") report(resizeRect(drag.start, drag.handle, p, area, minSize));
2552
+ else {
2553
+ const drawn = clampRect(rectFromCorners(clampPoint(drag.from, area), clampPoint(p, area)), area, 0);
2554
+ lastRef.current = drawn;
2555
+ setDrawing(drawn);
2556
+ }
2557
+ };
2558
+ const onEnd = (event) => {
2559
+ const drag = dragRef.current;
2560
+ if (!drag) return;
2561
+ event.stopPropagation();
2562
+ dragRef.current = null;
2563
+ if (drag.kind === "draw") {
2564
+ const drawn = lastRef.current;
2565
+ setDrawing(null);
2566
+ if (drawn && drawn.width >= minSize && drawn.height >= minSize) {
2567
+ onValueChange(drawn);
2568
+ onCommit?.(drawn);
2569
+ }
2570
+ return;
2571
+ }
2572
+ if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
2573
+ };
2574
+ const onKeyDown = (event) => {
2575
+ if (!editable || value === null) return;
2576
+ const step = event.shiftKey ? 10 : 1;
2577
+ const d = {
2578
+ ArrowLeft: {
2579
+ x: -step,
2580
+ y: 0
2581
+ },
2582
+ ArrowRight: {
2583
+ x: step,
2584
+ y: 0
2585
+ },
2586
+ ArrowUp: {
2587
+ x: 0,
2588
+ y: -step
2589
+ },
2590
+ ArrowDown: {
2591
+ x: 0,
2592
+ y: step
2593
+ }
2594
+ }[event.key];
2595
+ if (!d) return;
2596
+ event.preventDefault();
2597
+ event.stopPropagation();
2598
+ const next = event.altKey ? clampRect({
2599
+ ...value,
2600
+ width: value.width + d.x,
2601
+ height: value.height + d.y
2602
+ }, area, minSize) : moveRect(value, d.x, d.y, area);
2603
+ onValueChange(next);
2604
+ onCommit?.(next);
2605
+ };
2606
+ const outline = shown && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("rect", {
2607
+ x: shown.x,
2608
+ y: shown.y,
2609
+ width: shown.width,
2610
+ height: shown.height,
2611
+ fill: "none",
2612
+ stroke: HALO$1,
2613
+ strokeWidth: px(3.5)
2614
+ }), /* @__PURE__ */ jsx("rect", {
2615
+ x: shown.x,
2616
+ y: shown.y,
2617
+ width: shown.width,
2618
+ height: shown.height,
2619
+ fill: stroke,
2620
+ fillOpacity: .06,
2621
+ stroke,
2622
+ strokeWidth: px(STROKE_PX),
2623
+ strokeDasharray: `${px(6)} ${px(4)}`
2624
+ })] });
2625
+ return /* @__PURE__ */ jsxs("svg", {
2626
+ viewBox: imageViewBox(stage.image),
2627
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
2628
+ "data-editable": editable ? "" : void 0,
2629
+ "data-drawing": drawing ? "" : void 0,
2630
+ children: [
2631
+ draw && editable && /* @__PURE__ */ jsx("rect", {
2632
+ "data-draw-surface": "",
2633
+ x: area.x,
2634
+ y: area.y,
2635
+ width: area.width,
2636
+ height: area.height,
2637
+ fill: "transparent",
2638
+ className: "pointer-events-auto cursor-crosshair",
2639
+ onPointerDown: (event) => begin(event, {
2640
+ kind: "draw",
2641
+ from: stage.toImage({
2642
+ x: event.clientX,
2643
+ y: event.clientY
2644
+ }),
2645
+ moved: false
2646
+ }),
2647
+ onPointerMove: onMove,
2648
+ onPointerUp: onEnd,
2649
+ onLostPointerCapture: onEnd
2650
+ }),
2651
+ outline,
2652
+ editable && value && !drawing && /* @__PURE__ */ jsx("rect", {
2653
+ x: value.x,
2654
+ y: value.y,
2655
+ width: value.width,
2656
+ height: value.height,
2657
+ fill: "transparent",
2658
+ role: "button",
2659
+ tabIndex: 0,
2660
+ "aria-label": `${label}: ${fmt(value.x)}, ${fmt(value.y)}, ${fmt(value.width)} × ${fmt(value.height)} px`,
2661
+ "aria-roledescription": "region",
2662
+ className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
2663
+ onPointerDown: (event) => begin(event, {
2664
+ kind: "move",
2665
+ from: stage.toImage({
2666
+ x: event.clientX,
2667
+ y: event.clientY
2668
+ }),
2669
+ start: value,
2670
+ moved: false
2671
+ }),
2672
+ onPointerMove: onMove,
2673
+ onPointerUp: onEnd,
2674
+ onLostPointerCapture: onEnd,
2675
+ onKeyDown,
2676
+ onDoubleClick: (event) => event.stopPropagation()
2677
+ }),
2678
+ editable && value && !drawing && ROI_HANDLES.map((handle) => {
2679
+ const centre = roiHandlePoint(value, handle);
2680
+ const size = px(HANDLE_PX);
2681
+ return /* @__PURE__ */ jsx("rect", {
2682
+ "data-handle": handle,
2683
+ x: centre.x - size / 2,
2684
+ y: centre.y - size / 2,
2685
+ width: size,
2686
+ height: size,
2687
+ fill: stroke,
2688
+ stroke: HALO$1,
2689
+ strokeWidth: px(1),
2690
+ className: "pointer-events-auto",
2691
+ style: { cursor: ROI_HANDLE_CURSOR[handle] },
2692
+ onPointerDown: (event) => begin(event, {
2693
+ kind: "resize",
2694
+ handle,
2695
+ start: value,
2696
+ moved: false
2697
+ }),
2698
+ onPointerMove: onMove,
2699
+ onPointerUp: onEnd,
2700
+ onLostPointerCapture: onEnd,
2701
+ onDoubleClick: (event) => event.stopPropagation()
2702
+ }, handle);
2703
+ })
2704
+ ]
2705
+ });
2706
+ }
2707
+ function clampPoint(p, area) {
2708
+ return {
2709
+ x: Math.min(area.x + area.width, Math.max(area.x, p.x)),
2710
+ y: Math.min(area.y + area.height, Math.max(area.y, p.y))
2711
+ };
2712
+ }
2713
+ function fmt(value) {
2714
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
2715
+ }
2716
+ //#endregion
2717
+ //#region src/components/PolylineSet.tsx
2718
+ /**
2719
+ * Many polylines over the image, selectable: contours a model may be built from, a
2720
+ * document's segments, a batch's matches.
2721
+ *
2722
+ * Drawn as a handful of batched paths, one per state and colour, not one element per line. The
2723
+ * L0-3 benchmark shows the per-element form failing the 2 ms hit-test gate at scale, while the
2724
+ * batched form plus a spatial index passes on every candidate engine
2725
+ * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
2726
+ * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
2727
+ */
2728
+ const HALO = overlayRole("halo");
2729
+ /** The most points drawn as dots at once; past this the dots are noise and a cost. */
2730
+ const MAX_VERTEX_DOTS = 5e3;
2731
+ /**
2732
+ * A selectable set of polylines inside an `ImageStage`.
2733
+ *
2734
+ * - **States**, from visual-language §5:
2735
+ * - default 1.5 screen px;
2736
+ * - hover 2 px;
2737
+ * - selected 2.5 px in `selectionStroke`;
2738
+ * - dimmed at 35 % opacity.
2739
+ * - **Halo.** Every line has a halo, so it holds on any image.
2740
+ * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.
2741
+ * - **Panning.** The hand tool and a held space bar still pan.
2742
+ *
2743
+ * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
2744
+ */
2745
+ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines" }) {
2746
+ const stage = useStage();
2747
+ const startDrag = useStageDrag();
2748
+ const px = useScreenPx();
2749
+ const index = useMemo(() => buildPolylineIndex(items), [items]);
2750
+ const selectedSet = useMemo(() => new Set(selected ?? []), [selected]);
2751
+ const dimmedSet = useMemo(() => new Set(dimmed ?? []), [dimmed]);
2752
+ const byId = useMemo(() => new Map(items.map((item) => [item.id, item])), [items]);
2753
+ const [ownHover, setOwnHover] = useState(null);
2754
+ const hoverId = hovered !== void 0 ? hovered : ownHover;
2755
+ const [band, setBand] = useState(null);
2756
+ const groups = useMemo(() => {
2757
+ const map = /* @__PURE__ */ new Map();
2758
+ const hitParts = [];
2759
+ for (const item of items) {
2760
+ const d = polylinePath(item.points, item.closed === true);
2761
+ if (d === "") continue;
2762
+ hitParts.push(d);
2763
+ if (selectedSet.has(item.id)) continue;
2764
+ const colour = item.stroke ?? stroke;
2765
+ const dashed = item.dashed === true;
2766
+ const dim = dimmedSet.has(item.id);
2767
+ const key = `${dim ? 1 : 0}|${dashed ? 1 : 0}|${colour}`;
2768
+ let group = map.get(key);
2769
+ if (!group) {
2770
+ group = {
2771
+ d: [],
2772
+ stroke: colour,
2773
+ dashed,
2774
+ dim
2775
+ };
2776
+ map.set(key, group);
2777
+ }
2778
+ group.d.push(d);
2779
+ }
2780
+ const selectedPath = items.filter((item) => selectedSet.has(item.id)).map((item) => polylinePath(item.points, item.closed === true)).join("");
2781
+ return {
2782
+ batches: [...map.values()].map((g) => ({
2783
+ ...g,
2784
+ path: g.d.join("")
2785
+ })),
2786
+ hit: hitParts.join(""),
2787
+ selected: selectedPath
2788
+ };
2789
+ }, [
2790
+ items,
2791
+ selectedSet,
2792
+ dimmedSet,
2793
+ stroke
2794
+ ]);
2795
+ const hoverItem = hoverId !== null ? byId.get(hoverId) : void 0;
2796
+ const hoverPath = hoverItem ? polylinePath(hoverItem.points, hoverItem.closed === true) : "";
2797
+ const dots = useMemo(() => {
2798
+ if (stage.view.scale < vertexScale) return "";
2799
+ const shown = [];
2800
+ if (hoverItem) shown.push(hoverItem);
2801
+ for (const item of items) if (selectedSet.has(item.id) && item !== hoverItem) shown.push(item);
2802
+ let d = "";
2803
+ let count = 0;
2804
+ for (const item of shown) {
2805
+ const p = item.points;
2806
+ for (let i = 0; i + 1 < p.length && count < MAX_VERTEX_DOTS; i += 2, count++) d += `M${p[i]} ${p[i + 1]}h0`;
2807
+ }
2808
+ return d;
2809
+ }, [
2810
+ stage.view.scale,
2811
+ vertexScale,
2812
+ hoverItem,
2813
+ items,
2814
+ selectedSet
2815
+ ]);
2816
+ const pickAt = (event) => nearestPolyline(index, stage.toImage({
2817
+ x: event.clientX,
2818
+ y: event.clientY
2819
+ }), px(hitWidth / 2))?.id ?? null;
2820
+ const setHover = (id) => {
2821
+ if (id === hoverId) return;
2822
+ setOwnHover(id);
2823
+ onHover?.(id);
2824
+ };
2825
+ const sweep = (event) => {
2826
+ const from = stage.toImage({
2827
+ x: event.clientX,
2828
+ y: event.clientY
2829
+ });
2830
+ const additive = event.metaKey || event.ctrlKey;
2831
+ setBand({
2832
+ x: from.x,
2833
+ y: from.y,
2834
+ width: 0,
2835
+ height: 0
2836
+ });
2837
+ setHover(null);
2838
+ startDrag(event, {
2839
+ onMove: (p) => setBand(boxBetween(from, p)),
2840
+ onEnd: (p) => {
2841
+ setBand(null);
2842
+ onSelect?.(polylinesInRect(index, boxBetween(from, p)), additive ? "add" : "replace");
2843
+ },
2844
+ onCancel: () => setBand(null)
2845
+ });
2846
+ };
2847
+ const onLinePointerDown = (event) => {
2848
+ if (stage.panMode || event.button !== 0) return;
2849
+ if (event.shiftKey || marquee) {
2850
+ sweep(event);
2851
+ return;
2852
+ }
2853
+ const id = pickAt(event);
2854
+ if (id === null) return;
2855
+ event.stopPropagation();
2856
+ onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
2857
+ };
2858
+ const hairline = px(1.5);
2859
+ return /* @__PURE__ */ jsxs("svg", {
2860
+ viewBox: imageViewBox(stage.image),
2861
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
2862
+ role: "img",
2863
+ "aria-label": `${label}: ${items.length} ${items.length === 1 ? "line" : "lines"}, ${selectedSet.size} selected`,
2864
+ "data-hovered": hoverId ?? void 0,
2865
+ "data-sweeping": band ? "" : void 0,
2866
+ children: [
2867
+ marquee && /* @__PURE__ */ jsx("rect", {
2868
+ "data-marquee-surface": "",
2869
+ x: -.5,
2870
+ y: -.5,
2871
+ width: stage.image.width,
2872
+ height: stage.image.height,
2873
+ fill: "transparent",
2874
+ className: "pointer-events-auto cursor-crosshair",
2875
+ onPointerDown: (event) => {
2876
+ if (stage.panMode || event.button !== 0) return;
2877
+ sweep(event);
2878
+ }
2879
+ }),
2880
+ /* @__PURE__ */ jsxs("g", {
2881
+ fill: "none",
2882
+ strokeLinecap: "round",
2883
+ strokeLinejoin: "round",
2884
+ children: [
2885
+ /* @__PURE__ */ jsx("path", {
2886
+ d: groups.hit,
2887
+ stroke: HALO,
2888
+ strokeWidth: px(3.5),
2889
+ opacity: .6
2890
+ }),
2891
+ groups.batches.map((batch) => /* @__PURE__ */ jsx("path", {
2892
+ d: batch.path,
2893
+ stroke: batch.stroke,
2894
+ strokeWidth: hairline,
2895
+ strokeDasharray: batch.dashed ? `${px(4)} ${px(4)}` : void 0,
2896
+ opacity: batch.dim ? .35 : 1
2897
+ }, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
2898
+ groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
2899
+ d: groups.selected,
2900
+ stroke: HALO,
2901
+ strokeWidth: px(4.5)
2902
+ }), /* @__PURE__ */ jsx("path", {
2903
+ "data-selected-lines": "",
2904
+ d: groups.selected,
2905
+ stroke: selectionStroke,
2906
+ strokeWidth: px(2.5)
2907
+ })] }),
2908
+ hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
2909
+ d: hoverPath,
2910
+ stroke: HALO,
2911
+ strokeWidth: px(4)
2912
+ }), /* @__PURE__ */ jsx("path", {
2913
+ "data-hovered-line": "",
2914
+ d: hoverPath,
2915
+ stroke: hoverItem && selectedSet.has(hoverItem.id) ? selectionStroke : hoverItem?.stroke ?? stroke,
2916
+ strokeWidth: px(hoverItem && selectedSet.has(hoverItem.id) ? 2.5 : 2)
2917
+ })] }),
2918
+ dots && /* @__PURE__ */ jsx("path", {
2919
+ "data-points": "",
2920
+ d: dots,
2921
+ stroke: selectionStroke,
2922
+ strokeWidth: px(3)
2923
+ }),
2924
+ /* @__PURE__ */ jsx("path", {
2925
+ "data-hit": "",
2926
+ d: groups.hit,
2927
+ stroke: "transparent",
2928
+ strokeWidth: px(hitWidth),
2929
+ style: {
2930
+ pointerEvents: "stroke",
2931
+ cursor: stage.panMode ? void 0 : marquee ? "crosshair" : "pointer"
2932
+ },
2933
+ onPointerDown: onLinePointerDown,
2934
+ onPointerMove: (event) => {
2935
+ if (!band) setHover(pickAt(event));
2936
+ },
2937
+ onPointerLeave: () => setHover(null)
2938
+ })
2939
+ ]
2940
+ }),
2941
+ band && /* @__PURE__ */ jsx("rect", {
2942
+ x: band.x,
2943
+ y: band.y,
2944
+ width: band.width,
2945
+ height: band.height,
2946
+ fill: selectionStroke,
2947
+ fillOpacity: .12,
2948
+ stroke: selectionStroke,
2949
+ strokeWidth: px(1)
2950
+ })
2951
+ ]
2952
+ });
2953
+ }
2954
+ function boxBetween(a, b) {
2955
+ return {
2956
+ x: Math.min(a.x, b.x),
2957
+ y: Math.min(a.y, b.y),
2958
+ width: Math.abs(b.x - a.x),
2959
+ height: Math.abs(b.y - a.y)
2960
+ };
2961
+ }
2962
+ //#endregion
1737
2963
  //#region src/components/MaskEditor.tsx
1738
2964
  /** A source-pixel raster mask layer with a small paint/erase brush. */
1739
2965
  /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
@@ -1910,6 +3136,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
1910
3136
  })] });
1911
3137
  }
1912
3138
  //#endregion
1913
- export { ContourEditor, FULL_TIER_ZOOM, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MaskEditor, MeasureOverlay, PIXEL_CENTRE, PlaneFormatError, RESET_VIEW, StageButton, StageReadout, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, caliperArrow, caliperCorners, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, nativeZoomFor, nearestContourSegment, paintMask, polygonPath, preserveCenter, rotatePoint, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useStage, valueAt, valuesAt, zoomAbout, zoomAt };
3139
+ export { ContourEditor, FULL_TIER_ZOOM, ImageLayer, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, buildPolylineIndex, caliperArrow, caliperCorners, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, moveRect, nativeZoomFor, nearestContourSegment, nearestPolyline, overlayRole, paintMask, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rectFromCorners, resizeRect, roiHandlePoint, rotatePoint, sameRect, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useScreenPx, useStage, useStageDrag, valueAt, valuesAt, zoomAbout, zoomAt };
1914
3140
 
1915
3141
  //# sourceMappingURL=index.js.map