@vitavision/stage2d 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, use, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
1
+ import { createContext, use, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { DropdownMenu, Kbd, MenuCheckboxItem, MenuLabel, Tooltip, cn, focusRing, toneColor } from "@vitavision/ui";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  import { Layers, Maximize2, Minus, Plus, Scan } from "lucide-react";
@@ -54,18 +54,43 @@ const SCALE_LADDER = [
54
54
  const SCALE_EPSILON = .001;
55
55
  /** Absolute tolerance for "is this the same offset", in CSS pixels. */
56
56
  const OFFSET_EPSILON = .5;
57
- /** The scale at which the whole image is just visible inside `box`. */
58
- function fitScale(box, image) {
57
+ /**
58
+ * The scale at which the whole image is just visible inside `box`.
59
+ *
60
+ * @param box - The viewport, in CSS pixels.
61
+ * @param image - The image, in image pixels.
62
+ * @param options - A margin and an upscale cap; the defaults fill the box edge to edge.
63
+ * @returns CSS pixels per image pixel; `1` for a degenerate box or image.
64
+ */
65
+ function fitScale(box, image, options = {}) {
59
66
  if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;
60
- return Math.min(box.width / image.width, box.height / image.height);
67
+ const pad = Math.max(0, options.padding ?? 0);
68
+ const room = box.width > 2 * pad && box.height > 2 * pad ? pad : 0;
69
+ const scale = Math.min((box.width - 2 * room) / image.width, (box.height - 2 * room) / image.height);
70
+ return options.upscale === false ? Math.min(1, scale) : scale;
61
71
  }
62
- /** Fit, centred — the view a viewer opens at and the one `0` returns to. */
63
- function fitView(box, image) {
64
- return centred(fitScale(box, image), box, image);
72
+ /**
73
+ * Fit, centred: the view a viewer opens at and the one `0` returns to.
74
+ *
75
+ * @param box - The viewport, in CSS pixels.
76
+ * @param image - The image, in image pixels.
77
+ * @param options - A margin and an upscale cap; see `FitOptions`.
78
+ * @returns The view.
79
+ */
80
+ function fitView(box, image, options = {}) {
81
+ return centred(fitScale(box, image, options), box, image);
65
82
  }
66
- /** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */
67
- function initialView(box, image) {
68
- return centred(Math.min(1, fitScale(box, image)), box, image);
83
+ /**
84
+ * The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view.
85
+ *
86
+ * @param box - The viewport, in CSS pixels.
87
+ * @param image - The image, in image pixels.
88
+ * @param options - Only `padding` matters here (the image must fit inside the margin to open
89
+ * at 1:1, and "otherwise fit" is the padded fit); it never magnifies, so `upscale` is moot.
90
+ * @returns The view.
91
+ */
92
+ function initialView(box, image, options = {}) {
93
+ return centred(Math.min(1, fitScale(box, image, { padding: options.padding })), box, image);
69
94
  }
70
95
  function centred(scale, box, image) {
71
96
  return {
@@ -74,9 +99,9 @@ function centred(scale, box, image) {
74
99
  ty: (box.height - image.height * scale) / 2
75
100
  };
76
101
  }
77
- /** Whether `view` is (indistinguishably) the fit view for this box and image. */
78
- function isFit(view, box, image) {
79
- const fit = fitView(box, image);
102
+ /** Whether `view` is (indistinguishably) the fit view for this box, image and `FitOptions`. */
103
+ function isFit(view, box, image, options = {}) {
104
+ const fit = fitView(box, image, options);
80
105
  return Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON && Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON && Math.abs(view.ty - fit.ty) <= OFFSET_EPSILON;
81
106
  }
82
107
  /** Where the **centre of** image pixel `p` lands in the viewport. */
@@ -176,9 +201,9 @@ function frameRect(box, image, rect, pad = .15) {
176
201
  * that was *fit* re-fits instead, because fit is a relationship to the viewport rather than
177
202
  * a particular pair of numbers.
178
203
  */
179
- function preserveCenter(view, from, to, image, options = {}) {
180
- if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);
181
- if (isFit(view, from, image)) return fitView(to, image);
204
+ function preserveCenter(view, from, to, image, options = {}, fit = {}) {
205
+ if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);
206
+ if (isFit(view, from, image, fit)) return fitView(to, image, fit);
182
207
  const centre = toImage(view, {
183
208
  x: from.width / 2,
184
209
  y: from.height / 2
@@ -215,6 +240,15 @@ function formatScale(scale) {
215
240
  function clamp$2(value, low, high) {
216
241
  return Math.min(high, Math.max(low, value));
217
242
  }
243
+ /**
244
+ * The hit-test tolerance for a pointer, in screen pixels.
245
+ *
246
+ * @param pointerType - `PointerEvent.pointerType`.
247
+ * @returns 12 for `"touch"`, 6 otherwise.
248
+ */
249
+ function hitRadiusPx(pointerType) {
250
+ return pointerType === "touch" ? 12 : 6;
251
+ }
218
252
  const BUTTON_CODE = {
219
253
  left: 0,
220
254
  middle: 1,
@@ -389,11 +423,19 @@ function createHitRegistry() {
389
423
  * with the image.
390
424
  */
391
425
  const WHEEL_SENSITIVITY = .0015;
426
+ /**
427
+ * How long after the last view change the stage box keeps `will-change: transform`.
428
+ *
429
+ * The hint keeps a pan on the compositor (without it every overlay path is repainted each
430
+ * frame: 130 ms against 17 ms with 4,000 corners in view under software raster), but Chromium
431
+ * then keeps the layer at the raster scale it had when the hint was applied, so the stage
432
+ * would stay blurry after a zoom. Measured in `willChange.browser.test.ts`: always on, the
433
+ * edge of a zoomed image ramps over 6 px and a 1 px line smears to 10; cleared once the view
434
+ * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.
435
+ */
436
+ const MOVING_SETTLE_MS = 150;
392
437
  /** How far a press may travel and still count as a click rather than a pan. */
393
438
  const CLICK_SLOP$1 = 3;
394
- /** The pointer's tolerance for hover and presses, in screen pixels: a mouse, and a fingertip. */
395
- const POINTER_RADIUS = 6;
396
- const TOUCH_RADIUS = 12;
397
439
  /** The view before the viewport has been measured — nothing is on screen yet. */
398
440
  const UNMEASURED_VIEW = {
399
441
  scale: 1,
@@ -417,12 +459,17 @@ function useStage() {
417
459
  * size, so an overlay drawn in image coordinates stays registered with the photograph at
418
460
  * any zoom and window size. Layers read the transform through `useStage`.
419
461
  *
462
+ * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while
463
+ * the view changes and for 150 ms after, so a pan stays on the compositor and the layer
464
+ * re-rasterises sharp once the view settles.
465
+ *
420
466
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
421
467
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
422
468
  * or absent.
423
469
  */
424
- function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, panButton, doubleClickFit = true, touchPan = "one-finger", className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", ref }) {
470
+ function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, panButton, doubleClickFit = true, touchPan = "one-finger", className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", fit: fitOptions, ref }) {
425
471
  const viewportRef = useRef(null);
472
+ const boxRef = useRef(null);
426
473
  const [box, setBox] = useState({
427
474
  width: 0,
428
475
  height: 0
@@ -434,13 +481,18 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
434
481
  const [panning, setPanning] = useState(false);
435
482
  const [spaceHeld, setSpaceHeld] = useState(false);
436
483
  const panMode = panTool || spaceHeld;
484
+ const fitOpts = useMemo(() => ({
485
+ padding: fitOptions?.padding,
486
+ upscale: fitOptions?.upscale
487
+ }), [fitOptions?.padding, fitOptions?.upscale]);
437
488
  const latestRef = useRef({
438
489
  view,
439
490
  box,
440
491
  image,
441
492
  clamp,
442
493
  onView,
443
- opening
494
+ opening,
495
+ fitOpts
444
496
  });
445
497
  useLayoutEffect(() => {
446
498
  latestRef.current = {
@@ -449,7 +501,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
449
501
  image,
450
502
  clamp,
451
503
  onView,
452
- opening
504
+ opening,
505
+ fitOpts
453
506
  };
454
507
  });
455
508
  /** The view to come back to when a double-click leaves fit. */
@@ -462,11 +515,27 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
462
515
  /** The registry the stage's layers answer hit-tests through. */
463
516
  const [hits] = useState(() => createHitRegistry());
464
517
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
465
- const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW), [
518
+ const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW), [
466
519
  view,
467
520
  box,
468
521
  image,
469
- opening
522
+ opening,
523
+ fitOpts
524
+ ]);
525
+ useEffect(() => {
526
+ const element = boxRef.current;
527
+ if (!element) return;
528
+ element.style.willChange = "transform";
529
+ element.dataset["moving"] = "";
530
+ const timer = setTimeout(() => {
531
+ element.style.willChange = "";
532
+ delete element.dataset["moving"];
533
+ }, MOVING_SETTLE_MS);
534
+ return () => clearTimeout(timer);
535
+ }, [
536
+ effective.scale,
537
+ effective.tx,
538
+ effective.ty
470
539
  ]);
471
540
  const commit = useCallback((next) => {
472
541
  const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
@@ -485,10 +554,10 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
485
554
  };
486
555
  measuredRef.current = next;
487
556
  setBox(next);
488
- const { view: v, image: i, clamp: c, onView: report, opening: o } = latestRef.current;
489
- if (v === null) report(openingView(o, next, i));
557
+ const { view: v, image: i, clamp: c, onView: report, opening: o, fitOpts: f } = latestRef.current;
558
+ if (v === null) report(openingView(o, next, i, f));
490
559
  else if (!(current.width > 0)) report(clampView(v, next, i, c));
491
- else report(preserveCenter(v, current, next, i, c));
560
+ else report(preserveCenter(v, current, next, i, c, f));
492
561
  };
493
562
  measure(contentSize(element));
494
563
  const observer = new ResizeObserver((entries) => {
@@ -561,10 +630,10 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
561
630
  };
562
631
  }, []);
563
632
  const fit = useCallback(() => {
564
- const { box: b, image: i, view: v, onView: report } = latestRef.current;
633
+ const { box: b, image: i, view: v, onView: report, fitOpts: f } = latestRef.current;
565
634
  if (!(b.width > 0)) return;
566
- if (v !== null && !isFit(v, b, i)) previousRef.current = v;
567
- report(fitView(b, i));
635
+ if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
636
+ report(fitView(b, i, f));
568
637
  }, []);
569
638
  const zoomTo = useCallback((scale, anchor) => {
570
639
  const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
@@ -595,7 +664,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
595
664
  fit,
596
665
  zoomTo
597
666
  ]);
598
- const atFit = box.width > 0 && isFit(effective, box, image);
667
+ const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);
599
668
  const context = useMemo(() => ({
600
669
  view: effective,
601
670
  setView: commit,
@@ -626,7 +695,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
626
695
  panMode
627
696
  ]);
628
697
  /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */
629
- const hitRadius = (event) => imageLengthFor(effective, event.pointerType === "touch" ? TOUCH_RADIUS : POINTER_RADIUS);
698
+ const hitRadius = (event) => imageLengthFor(effective, hitRadiusPx(event.pointerType));
630
699
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
631
700
  const routePress = (event) => hits.routePress(clientToImage({
632
701
  x: event.clientX,
@@ -805,7 +874,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
805
874
  return;
806
875
  }
807
876
  previousRef.current = effective;
808
- onView(fitView(box, image));
877
+ onView(fitView(box, image, fitOpts));
809
878
  };
810
879
  const onKeyDown = (event) => {
811
880
  if (!shortcuts || isTypingTarget(event.target)) return;
@@ -886,6 +955,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
886
955
  onKeyDown,
887
956
  children: [
888
957
  /* @__PURE__ */ jsx("div", {
958
+ ref: boxRef,
889
959
  "data-stage": true,
890
960
  className: "absolute top-0 left-0 origin-top-left",
891
961
  style: {
@@ -916,8 +986,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
916
986
  });
917
987
  }
918
988
  /** The view a `null` view opens at, by the `initialView` policy. */
919
- function openingView(opening, box, image) {
920
- return opening === "fit" ? fitView(box, image) : initialView(box, image);
989
+ function openingView(opening, box, image, fit) {
990
+ return opening === "fit" ? fitView(box, image, fit) : initialView(box, image, fit);
921
991
  }
922
992
  function hoverPoint(event, element, view, image) {
923
993
  if (!element) return null;
@@ -1091,6 +1161,64 @@ function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onLoad, onError, cl
1091
1161
  })] });
1092
1162
  }
1093
1163
  //#endregion
1164
+ //#region src/components/stage/touchWatch.ts
1165
+ /**
1166
+ * Watching a touch without claiming it.
1167
+ *
1168
+ * A layer that claims a touch (`stopPropagation` plus pointer capture) takes it from the stage,
1169
+ * so a second finger can no longer pinch and a drag can no longer pan. A layer that only wants
1170
+ * to know whether the touch was a tap leaves the press alone and follows its pointer on
1171
+ * `window`, where the moves and the release arrive whoever captured the pointer.
1172
+ */
1173
+ /**
1174
+ * Follow one touch on `window` until it lifts. A second touch landing, or `pointercancel`,
1175
+ * cancels the watch and leaves the touches to the stage.
1176
+ *
1177
+ * @param origin - The `pointerdown` of the touch.
1178
+ * @param watch - What to report.
1179
+ * @returns A function that cancels the watch (calling `onCancel`); a no-op once it has ended.
1180
+ */
1181
+ function watchTouch(origin, watch) {
1182
+ const id = origin.pointerId;
1183
+ let moved = false;
1184
+ let done = false;
1185
+ const travel = (e) => Math.hypot(e.clientX - origin.clientX, e.clientY - origin.clientY);
1186
+ const stop = () => {
1187
+ done = true;
1188
+ window.removeEventListener("pointermove", move);
1189
+ window.removeEventListener("pointerup", up);
1190
+ window.removeEventListener("pointercancel", cancelEvent);
1191
+ window.removeEventListener("pointerdown", other);
1192
+ };
1193
+ const cancel = () => {
1194
+ if (done) return;
1195
+ stop();
1196
+ watch.onCancel?.();
1197
+ };
1198
+ function move(e) {
1199
+ if (e.pointerId !== id) return;
1200
+ if (!moved && travel(e) > 3) moved = true;
1201
+ if (moved) watch.onMove?.(e);
1202
+ }
1203
+ function up(e) {
1204
+ if (e.pointerId !== id) return;
1205
+ stop();
1206
+ if (!moved && travel(e) > 3) moved = true;
1207
+ watch.onEnd(e, moved, isTap(moved ? Infinity : travel(e), e.timeStamp - origin.timeStamp));
1208
+ }
1209
+ function cancelEvent(e) {
1210
+ if (e.pointerId === id) cancel();
1211
+ }
1212
+ function other(e) {
1213
+ if (e.pointerId !== id && e.pointerType === "touch") cancel();
1214
+ }
1215
+ window.addEventListener("pointermove", move);
1216
+ window.addEventListener("pointerup", up);
1217
+ window.addEventListener("pointercancel", cancelEvent);
1218
+ window.addEventListener("pointerdown", other);
1219
+ return cancel;
1220
+ }
1221
+ //#endregion
1094
1222
  //#region src/components/stage/StageSurface.tsx
1095
1223
  /**
1096
1224
  * The stage's tool model: one place that decides what a press on the image means.
@@ -1166,34 +1294,78 @@ function useStageDrag() {
1166
1294
  * that have their own small targets (handles, strokes). Each press is offered to `onPress`
1167
1295
  * unless the hand tool or a held space bar make it a pan; a declined press pans.
1168
1296
  *
1169
- * The surface draws nothing. It carries `data-dragging` while a drag it started is in
1170
- * flight.
1297
+ * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on
1298
+ * `window`, so the stage does not pan from it.
1299
+ *
1300
+ * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface
1301
+ * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)
1302
+ * and a second finger still pinches. The drag then sees:
1303
+ * - `onMove`, only once the finger has left the tap slop;
1304
+ * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;
1305
+ * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).
1306
+ *
1307
+ * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
1308
+ *
1309
+ * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
1171
1310
  */
1172
- function StageSurface({ onPress, cursor, onHover }) {
1311
+ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1173
1312
  const stage = useStage();
1174
1313
  const start = useStageDrag();
1175
1314
  const [dragging, setDragging] = useState(false);
1315
+ const watchRef = useRef(null);
1316
+ useEffect(() => () => watchRef.current?.(), []);
1176
1317
  const onPointerDown = (event) => {
1177
- if (event.button !== 0 || stage.panMode) return;
1318
+ const touch = event.pointerType === "touch";
1319
+ if (stage.panMode || !touch && event.button !== 0) return;
1320
+ if (touch && watchRef.current) return;
1321
+ const client = {
1322
+ x: event.clientX,
1323
+ y: event.clientY
1324
+ };
1178
1325
  const drag = onPress({
1179
- point: stage.toImage({
1180
- x: event.clientX,
1181
- y: event.clientY
1182
- }),
1326
+ point: stage.toImage(client),
1327
+ client,
1328
+ touch,
1329
+ radius: hitRadiusPx(event.pointerType),
1183
1330
  shiftKey: event.shiftKey,
1184
1331
  altKey: event.altKey,
1185
1332
  metaKey: event.metaKey || event.ctrlKey
1186
1333
  });
1187
1334
  if (!drag) return;
1335
+ const finish = () => setDragging(false);
1188
1336
  setDragging(true);
1337
+ if (touch && !drag.claimsTouch) {
1338
+ const release = () => {
1339
+ watchRef.current = null;
1340
+ finish();
1341
+ };
1342
+ watchRef.current = watchTouch(event, {
1343
+ onMove: (e) => drag.onMove?.(stage.toImage({
1344
+ x: e.clientX,
1345
+ y: e.clientY
1346
+ }), e),
1347
+ onEnd: (e, moved) => {
1348
+ release();
1349
+ drag.onEnd?.(stage.toImage({
1350
+ x: e.clientX,
1351
+ y: e.clientY
1352
+ }), e, moved);
1353
+ },
1354
+ onCancel: () => {
1355
+ release();
1356
+ drag.onCancel?.();
1357
+ }
1358
+ });
1359
+ return;
1360
+ }
1189
1361
  start(event, {
1190
1362
  onMove: drag.onMove,
1191
1363
  onEnd: (point, e, moved) => {
1192
- setDragging(false);
1364
+ finish();
1193
1365
  drag.onEnd?.(point, e, moved);
1194
1366
  },
1195
1367
  onCancel: () => {
1196
- setDragging(false);
1368
+ finish();
1197
1369
  drag.onCancel?.();
1198
1370
  }
1199
1371
  });
@@ -1214,7 +1386,15 @@ function StageSurface({ onPress, cursor, onHover }) {
1214
1386
  style: { cursor: stage.panMode ? void 0 : cursor },
1215
1387
  onPointerDown,
1216
1388
  onPointerMove: (event) => {
1217
- if (!dragging) onHover?.(stage.toImage({
1389
+ if (!dragging && event.pointerType !== "touch") onHover?.(stage.toImage({
1390
+ x: event.clientX,
1391
+ y: event.clientY
1392
+ }));
1393
+ },
1394
+ onDoubleClick: (event) => {
1395
+ if (!onDoubleClick) return;
1396
+ event.stopPropagation();
1397
+ onDoubleClick(stage.toImage({
1218
1398
  x: event.clientX,
1219
1399
  y: event.clientY
1220
1400
  }));
@@ -2220,6 +2400,7 @@ function polylineBounds(points) {
2220
2400
  height: maxY - minY
2221
2401
  };
2222
2402
  }
2403
+ /** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */
2223
2404
  function closestOnSegment(p, ax, ay, bx, by) {
2224
2405
  const dx = bx - ax;
2225
2406
  const dy = by - ay;
@@ -2230,7 +2411,7 @@ function closestOnSegment(p, ax, ay, bx, by) {
2230
2411
  y: ay + t * dy
2231
2412
  };
2232
2413
  }
2233
- /** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
2414
+ /** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). Shared with `areaIndex.ts`. */
2234
2415
  function segmentTouchesRect(ax, ay, bx, by, r) {
2235
2416
  const xmin = r.x;
2236
2417
  const xmax = r.x + r.width;
@@ -2860,8 +3041,8 @@ function clamp(value, low, high) {
2860
3041
  /** Handle square side, in screen pixels. */
2861
3042
  const HANDLE_PX = 9;
2862
3043
  /** Outline width, in screen pixels. */
2863
- const STROKE_PX = 1.5;
2864
- const HALO$2 = overlayRole("halo");
3044
+ const STROKE_PX$2 = 1.5;
3045
+ const HALO$7 = overlayRole("halo");
2865
3046
  /**
2866
3047
  * An editable axis-aligned region inside an `ImageStage`.
2867
3048
  *
@@ -2972,7 +3153,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2972
3153
  width: shown.width,
2973
3154
  height: shown.height,
2974
3155
  fill: "none",
2975
- stroke: HALO$2,
3156
+ stroke: HALO$7,
2976
3157
  strokeWidth: px(3.5)
2977
3158
  }), /* @__PURE__ */ jsx("rect", {
2978
3159
  x: shown.x,
@@ -2982,7 +3163,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2982
3163
  fill: stroke,
2983
3164
  fillOpacity: .06,
2984
3165
  stroke,
2985
- strokeWidth: px(STROKE_PX),
3166
+ strokeWidth: px(STROKE_PX$2),
2986
3167
  strokeDasharray: `${px(6)} ${px(4)}`
2987
3168
  })] });
2988
3169
  return /* @__PURE__ */ jsxs("svg", {
@@ -3020,7 +3201,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3020
3201
  fill: "transparent",
3021
3202
  role: "button",
3022
3203
  tabIndex: 0,
3023
- "aria-label": `${label}: ${fmt(value.x)}, ${fmt(value.y)}, ${fmt(value.width)} × ${fmt(value.height)} px`,
3204
+ "aria-label": `${label}: ${fmt$1(value.x)}, ${fmt$1(value.y)}, ${fmt$1(value.width)} × ${fmt$1(value.height)} px`,
3024
3205
  "aria-roledescription": "region",
3025
3206
  className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
3026
3207
  onPointerDown: (event) => begin(event, {
@@ -3048,7 +3229,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
3048
3229
  width: size,
3049
3230
  height: size,
3050
3231
  fill: stroke,
3051
- stroke: HALO$2,
3232
+ stroke: HALO$7,
3052
3233
  strokeWidth: px(1),
3053
3234
  className: "pointer-events-auto",
3054
3235
  style: { cursor: ROI_HANDLE_CURSOR[handle] },
@@ -3073,7 +3254,7 @@ function clampPoint(p, area) {
3073
3254
  y: Math.min(area.y + area.height, Math.max(area.y, p.y))
3074
3255
  };
3075
3256
  }
3076
- function fmt(value) {
3257
+ function fmt$1(value) {
3077
3258
  return Number.isInteger(value) ? String(value) : value.toFixed(1);
3078
3259
  }
3079
3260
  //#endregion
@@ -3088,7 +3269,7 @@ function fmt(value) {
3088
3269
  * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
3089
3270
  * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
3090
3271
  */
3091
- const HALO$1 = overlayRole("halo");
3272
+ const HALO$6 = overlayRole("halo");
3092
3273
  /** The most points drawn as dots at once; past this the dots are noise and a cost. */
3093
3274
  const MAX_VERTEX_DOTS = 5e3;
3094
3275
  /**
@@ -3102,12 +3283,17 @@ const MAX_VERTEX_DOTS = 5e3;
3102
3283
  * - **Halo.** Every line has a halo, so it holds on any image.
3103
3284
  * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.
3104
3285
  * - **Panning.** The hand tool and a held space bar still pan.
3286
+ * - **Tools.** Without a handler (or with `interactive={false}`) the layer takes no presses
3287
+ * and only answers `useStageHitTest`, so a draw tool's surface below receives them.
3105
3288
  *
3106
3289
  * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
3107
3290
  */
3108
- function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange, onItemPress, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines", layerId, priority = STAGE_HIT_PRIORITY.line }) {
3291
+ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange, onItemPress, onSelect, marquee = false, interactive, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines", layerId, priority = STAGE_HIT_PRIORITY.line }) {
3109
3292
  const stage = useStage();
3110
3293
  const startDrag = useStageDrag();
3294
+ const watchRef = useRef(null);
3295
+ useEffect(() => () => watchRef.current?.(), []);
3296
+ const takesPresses = interactive ?? (onItemPress !== void 0 || onSelect !== void 0 || onHover !== void 0 || onHoverChange !== void 0 || marquee);
3111
3297
  const px = useScreenPx();
3112
3298
  const { hitTestAll } = useStageHitTest();
3113
3299
  const index = useMemo(() => buildPolylineIndex(items), [items]);
@@ -3221,7 +3407,9 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3221
3407
  });
3222
3408
  };
3223
3409
  const onLinePointerDown = (event) => {
3224
- if (stage.panMode || event.button !== 0) return;
3410
+ const touch = event.pointerType === "touch";
3411
+ if (stage.panMode || !touch && event.button !== 0) return;
3412
+ if (touch && watchRef.current) return;
3225
3413
  if (event.shiftKey || marquee) {
3226
3414
  sweep(event);
3227
3415
  return;
@@ -3233,6 +3421,21 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3233
3421
  y: event.clientY
3234
3422
  });
3235
3423
  if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
3424
+ if (touch && !marquee) {
3425
+ const additive = event.metaKey || event.ctrlKey;
3426
+ watchRef.current = watchTouch(event, {
3427
+ onEnd: (_e, _moved, tap) => {
3428
+ watchRef.current = null;
3429
+ if (!tap) return;
3430
+ onItemPress?.(id, event);
3431
+ onSelect?.([id], additive ? "toggle" : "replace");
3432
+ },
3433
+ onCancel: () => {
3434
+ watchRef.current = null;
3435
+ }
3436
+ });
3437
+ return;
3438
+ }
3236
3439
  event.stopPropagation();
3237
3440
  onItemPress?.(id, event);
3238
3441
  onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
@@ -3246,7 +3449,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3246
3449
  "data-hovered": hoverId ?? void 0,
3247
3450
  "data-sweeping": band ? "" : void 0,
3248
3451
  children: [
3249
- marquee && /* @__PURE__ */ jsx("rect", {
3452
+ takesPresses && marquee && /* @__PURE__ */ jsx("rect", {
3250
3453
  "data-marquee-surface": "",
3251
3454
  x: -.5,
3252
3455
  y: -.5,
@@ -3266,7 +3469,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3266
3469
  children: [
3267
3470
  /* @__PURE__ */ jsx("path", {
3268
3471
  d: groups.hit,
3269
- stroke: HALO$1,
3472
+ stroke: HALO$6,
3270
3473
  strokeWidth: px(3.5),
3271
3474
  opacity: .6
3272
3475
  }),
@@ -3279,7 +3482,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3279
3482
  }, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
3280
3483
  groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3281
3484
  d: groups.selected,
3282
- stroke: HALO$1,
3485
+ stroke: HALO$6,
3283
3486
  strokeWidth: px(4.5)
3284
3487
  }), /* @__PURE__ */ jsx("path", {
3285
3488
  "data-selected-lines": "",
@@ -3289,7 +3492,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3289
3492
  })] }),
3290
3493
  hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
3291
3494
  d: hoverPath,
3292
- stroke: HALO$1,
3495
+ stroke: HALO$6,
3293
3496
  strokeWidth: px(4)
3294
3497
  }), /* @__PURE__ */ jsx("path", {
3295
3498
  "data-hovered-line": "",
@@ -3303,7 +3506,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3303
3506
  stroke: selectionStroke,
3304
3507
  strokeWidth: px(3)
3305
3508
  }),
3306
- /* @__PURE__ */ jsx("path", {
3509
+ takesPresses && /* @__PURE__ */ jsx("path", {
3307
3510
  "data-hit": "",
3308
3511
  d: groups.hit,
3309
3512
  stroke: "transparent",
@@ -3314,7 +3517,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
3314
3517
  },
3315
3518
  onPointerDown: onLinePointerDown,
3316
3519
  onPointerMove: (event) => {
3317
- if (!band) setHover(pickAt(event));
3520
+ if (!band && event.pointerType !== "touch") setHover(pickAt(event));
3318
3521
  },
3319
3522
  onPointerLeave: () => setHover(null)
3320
3523
  })
@@ -3417,7 +3620,7 @@ const MARKER_SHAPES = {
3417
3620
  //#endregion
3418
3621
  //#region src/components/pointIndex.ts
3419
3622
  /** The most grid cells an index allocates, whatever the cell side asks for. */
3420
- const MAX_CELLS = 4e6;
3623
+ const MAX_CELLS$1 = 4e6;
3421
3624
  /**
3422
3625
  * Index a set of points.
3423
3626
  *
@@ -3467,7 +3670,7 @@ function buildPointIndex(xy, options = {}) {
3467
3670
  const width = maxX - minX;
3468
3671
  const height = maxY - minY;
3469
3672
  let cell = options.cell ?? Math.min(256, Math.max(4, Math.sqrt(Math.max(width, 1) * Math.max(height, 1) * 2 / live)));
3470
- while ((Math.floor(width / cell) + 1) * (Math.floor(height / cell) + 1) > MAX_CELLS) cell *= 2;
3673
+ while ((Math.floor(width / cell) + 1) * (Math.floor(height / cell) + 1) > MAX_CELLS$1) cell *= 2;
3471
3674
  const cols = Math.floor(width / cell) + 1;
3472
3675
  const rows = Math.floor(height / cell) + 1;
3473
3676
  const cellOf = new Int32Array(count).fill(-1);
@@ -3659,6 +3862,72 @@ function isLive(xy, i) {
3659
3862
  function* range(n) {
3660
3863
  for (let i = 0; i < n; i++) yield i;
3661
3864
  }
3865
+ /** The image-space rectangle on screen, or `null` before the viewport is measured. */
3866
+ function visibleRect(view, box) {
3867
+ if (!(box.width > 0) || !(view.scale > 0)) return null;
3868
+ return {
3869
+ x: -view.tx / view.scale,
3870
+ y: -view.ty / view.scale,
3871
+ width: box.width / view.scale,
3872
+ height: box.height / view.scale
3873
+ };
3874
+ }
3875
+ /**
3876
+ * Choose the labels to draw.
3877
+ *
3878
+ * @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).
3879
+ * @param forced - Anchors that always carry a label: the hovered and the selected.
3880
+ * @param inView - Whether an anchor is inside the viewport.
3881
+ * @returns The anchor indices to label: the forced ones first (at most 50), then the spaced
3882
+ * ones, 200 in all.
3883
+ */
3884
+ function pickLabelIndices(spaced, forced, inView) {
3885
+ const shown = /* @__PURE__ */ new Set();
3886
+ for (const i of forced) {
3887
+ if (shown.size >= 50) break;
3888
+ if (i >= 0 && inView(i)) shown.add(i);
3889
+ }
3890
+ for (const i of spaced) {
3891
+ if (shown.size >= 200) break;
3892
+ if (inView(i)) shown.add(i);
3893
+ }
3894
+ return [...shown];
3895
+ }
3896
+ /**
3897
+ * The anchors to label at the stage's current zoom and viewport. The spacing depends on the
3898
+ * zoom only, so panning does not reshuffle which anchors carry a label.
3899
+ *
3900
+ * @param anchors - See `LabelAnchors`.
3901
+ * @returns Anchor indices.
3902
+ */
3903
+ function useLabelIndices({ enabled, xy, labelled, forced }) {
3904
+ const stage = useStage();
3905
+ const spacing = 24 * useScreenPx()(1);
3906
+ const spaced = useMemo(() => enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : [], [
3907
+ enabled,
3908
+ labelled,
3909
+ xy,
3910
+ spacing
3911
+ ]);
3912
+ return useMemo(() => {
3913
+ if (!enabled || spaced.length === 0 && forced.length === 0) return [];
3914
+ const view = visibleRect(stage.view, stage.box);
3915
+ const inView = (i) => {
3916
+ if (view === null) return true;
3917
+ const x = xy[2 * i];
3918
+ const y = xy[2 * i + 1];
3919
+ return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;
3920
+ };
3921
+ return pickLabelIndices(spaced, forced, inView);
3922
+ }, [
3923
+ enabled,
3924
+ spaced,
3925
+ forced,
3926
+ xy,
3927
+ stage.view,
3928
+ stage.box
3929
+ ]);
3930
+ }
3662
3931
  //#endregion
3663
3932
  //#region src/components/PointSet.tsx
3664
3933
  /**
@@ -3670,18 +3939,12 @@ function* range(n) {
3670
3939
  * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
3671
3940
  * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
3672
3941
  */
3673
- /** Labels need this much room between points, in screen pixels (overlay grammar §5). */
3674
- const LABEL_SPACING = 24;
3675
- /** The most label elements drawn at once. */
3676
- const MAX_LABELS = 200;
3677
- /** The most hovered-or-selected labels forced on regardless of spacing. */
3678
- const MAX_FORCED_LABELS = 50;
3679
3942
  /** Past this many points, outlines are generated for the visible part only. */
3680
3943
  const CULL_ABOVE = 3e3;
3681
3944
  /** How much bigger than a marker its selection ring is, in screen pixels. */
3682
3945
  const RING_GAP = 4;
3683
- const HALO = overlayRole("halo");
3684
- const LABEL = overlayRole("label");
3946
+ const HALO$5 = overlayRole("halo");
3947
+ const LABEL$1 = overlayRole("label");
3685
3948
  /**
3686
3949
  * A selectable set of points inside an `ImageStage`.
3687
3950
  *
@@ -3799,7 +4062,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3799
4062
  const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
3800
4063
  const build = (batches) => batches.map((batch) => ({
3801
4064
  batch,
3802
- d: batchPath(batch, items, unit, cull, cullKey)
4065
+ d: batchPath$1(batch, items, unit, cull, cullKey)
3803
4066
  }));
3804
4067
  const paths = {
3805
4068
  normal: build(groups.normal),
@@ -3817,41 +4080,26 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3817
4080
  });
3818
4081
  return list;
3819
4082
  }, [items]);
3820
- const spacing = LABEL_SPACING * unit;
3821
- const spaced = useMemo(() => labels && labelled.length > 0 ? thinPoints(index.xy, spacing, labelled) : [], [
3822
- labels,
3823
- labelled,
3824
- index,
3825
- spacing
3826
- ]);
3827
- const shownLabels = useMemo(() => {
3828
- if (!labels || spaced.length === 0 && !hoverItem?.label && selectedSet.size === 0) return [];
3829
- const view = visibleRect(stage.view, stage.box);
3830
- const inView = (i) => {
3831
- const item = items[i];
3832
- return view === null || item.x >= view.x && item.x <= view.x + view.width && item.y >= view.y && item.y <= view.y + view.height;
3833
- };
3834
- const shown = /* @__PURE__ */ new Set();
3835
- const forced = [...hoverItem ? [positionOf.get(hoverItem.id)] : [], ...[...selectedSet].map((id) => positionOf.get(id) ?? -1)];
3836
- for (const i of forced) {
3837
- if (shown.size >= MAX_FORCED_LABELS) break;
3838
- if (i >= 0 && items[i].label && inView(i)) shown.add(i);
3839
- }
3840
- for (const i of spaced) {
3841
- if (shown.size >= MAX_LABELS) break;
3842
- if (inView(i)) shown.add(i);
4083
+ const forced = useMemo(() => {
4084
+ const list = [];
4085
+ if (hoverItem?.label) list.push(positionOf.get(hoverItem.id));
4086
+ for (const id of selectedSet) {
4087
+ const i = positionOf.get(id);
4088
+ if (i !== void 0 && items[i].label) list.push(i);
3843
4089
  }
3844
- return [...shown];
4090
+ return list;
3845
4091
  }, [
3846
- labels,
3847
- spaced,
3848
- items,
3849
4092
  hoverItem,
3850
4093
  selectedSet,
3851
4094
  positionOf,
3852
- stage.view,
3853
- stage.box
4095
+ items
3854
4096
  ]);
4097
+ const shownLabels = useLabelIndices({
4098
+ enabled: labels,
4099
+ xy: index.xy,
4100
+ labelled,
4101
+ forced
4102
+ });
3855
4103
  const widthOf = (shape, role, state) => {
3856
4104
  const thin = role === "model" || role === "structure";
3857
4105
  const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0);
@@ -3871,7 +4119,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3871
4119
  children: [
3872
4120
  halo && paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3873
4121
  d,
3874
- stroke: HALO,
4122
+ stroke: HALO$5,
3875
4123
  strokeWidth: widthOf(batch.shape, batch.role, "default") + px(2),
3876
4124
  opacity: .6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)
3877
4125
  }, `halo|${batch.key}`)),
@@ -3884,12 +4132,12 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3884
4132
  }, batch.key)),
3885
4133
  halo && paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3886
4134
  d,
3887
- stroke: HALO,
4135
+ stroke: HALO$5,
3888
4136
  strokeWidth: widthOf(batch.shape, batch.role, "selected") + px(2)
3889
4137
  }, `halo|selected|${batch.key}`)),
3890
4138
  halo && paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3891
4139
  d,
3892
- stroke: HALO,
4140
+ stroke: HALO$5,
3893
4141
  strokeWidth: ringWidth + px(2)
3894
4142
  }, `halo|${batch.key}`)),
3895
4143
  paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
@@ -3905,12 +4153,12 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3905
4153
  strokeWidth: ringWidth
3906
4154
  }, batch.key)),
3907
4155
  hoverItem && hoverShape && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
3908
- d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
3909
- stroke: HALO,
4156
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
4157
+ stroke: HALO$5,
3910
4158
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)
3911
4159
  }), /* @__PURE__ */ jsx("path", {
3912
4160
  "data-hovered-point": "",
3913
- d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
4161
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
3914
4162
  stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
3915
4163
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
3916
4164
  })] })
@@ -3919,7 +4167,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3919
4167
  "data-labels": "",
3920
4168
  fontSize: px(11),
3921
4169
  className: "font-mono",
3922
- stroke: HALO,
4170
+ stroke: HALO$5,
3923
4171
  strokeWidth: px(3),
3924
4172
  paintOrder: "stroke",
3925
4173
  strokeLinejoin: "round",
@@ -3928,7 +4176,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3928
4176
  return /* @__PURE__ */ jsx("text", {
3929
4177
  x: item.x + px(6),
3930
4178
  y: item.y - px(5),
3931
- fill: LABEL,
4179
+ fill: LABEL$1,
3932
4180
  dominantBaseline: "text-after-edge",
3933
4181
  children: item.label
3934
4182
  }, item.id);
@@ -3940,7 +4188,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
3940
4188
  * The path data of a batch, generated again only when what it depends on changed: nothing
3941
4189
  * for a disc marker, the zoom and the window for an outline.
3942
4190
  */
3943
- function batchPath(batch, items, unit, cull, cullKey) {
4191
+ function batchPath$1(batch, items, unit, cull, cullKey) {
3944
4192
  const disc = batch.shape.paint === "disc";
3945
4193
  const key = disc ? "" : `${unit}|${cullKey}`;
3946
4194
  if (batch.cache?.key === key) return batch.cache.d;
@@ -3949,7 +4197,7 @@ function batchPath(batch, items, unit, cull, cullKey) {
3949
4197
  for (const i of batch.indices) {
3950
4198
  const item = items[i];
3951
4199
  if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;
3952
- d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);
4200
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0, item.angle2);
3953
4201
  }
3954
4202
  batch.cache = {
3955
4203
  key,
@@ -3957,16 +4205,6 @@ function batchPath(batch, items, unit, cull, cullKey) {
3957
4205
  };
3958
4206
  return d;
3959
4207
  }
3960
- /** The image-space rectangle on screen, or `null` before the viewport is measured. */
3961
- function visibleRect(view, box) {
3962
- if (!(box.width > 0) || !(view.scale > 0)) return null;
3963
- return {
3964
- x: -view.tx / view.scale,
3965
- y: -view.ty / view.scale,
3966
- width: box.width / view.scale,
3967
- height: box.height / view.scale
3968
- };
3969
- }
3970
4208
  /**
3971
4209
  * The window outlines are generated for: the viewport plus half a viewport on every side,
3972
4210
  * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
@@ -3989,6 +4227,2287 @@ function cullWindow(view, box, count) {
3989
4227
  };
3990
4228
  }
3991
4229
  //#endregion
4230
+ //#region src/components/areaIndex.ts
4231
+ /** The most grid cells an index allocates, and the most area-to-cell entries. */
4232
+ const MAX_CELLS = 4e6;
4233
+ const MAX_ENTRIES = 8e6;
4234
+ function vertexCount(points) {
4235
+ return Math.floor(points.length / 2);
4236
+ }
4237
+ /**
4238
+ * Whether `(x, y)` is inside the polygon, by the even-odd rule.
4239
+ *
4240
+ * @param points - Flat ring, implicitly closed.
4241
+ * @param x - The query's x.
4242
+ * @param y - The query's y.
4243
+ * @returns `false` for a ring with fewer than three vertices. A point exactly on the outline
4244
+ * may be either; `nearestArea` treats the outline separately.
4245
+ */
4246
+ function pointInPolygon(points, x, y) {
4247
+ const n = vertexCount(points);
4248
+ if (n < 3) return false;
4249
+ let inside = false;
4250
+ for (let i = 0, j = n - 1; i < n; j = i++) {
4251
+ const xi = points[2 * i];
4252
+ const yi = points[2 * i + 1];
4253
+ const xj = points[2 * j];
4254
+ const yj = points[2 * j + 1];
4255
+ if (yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) inside = !inside;
4256
+ }
4257
+ return inside;
4258
+ }
4259
+ /**
4260
+ * The distance from `(x, y)` to the outline of a polygon (its closing edge included).
4261
+ *
4262
+ * @param points - Flat ring, implicitly closed.
4263
+ * @param x - The query's x.
4264
+ * @param y - The query's y.
4265
+ * @returns The distance; `Infinity` for an empty ring.
4266
+ */
4267
+ function distanceToOutline(points, x, y) {
4268
+ const n = vertexCount(points);
4269
+ if (n === 0) return Infinity;
4270
+ const p = {
4271
+ x,
4272
+ y
4273
+ };
4274
+ let best = Infinity;
4275
+ const edges = n === 1 ? 1 : n === 2 ? 1 : n;
4276
+ for (let i = 0; i < edges; i++) {
4277
+ const j = n === 1 ? 0 : (i + 1) % n;
4278
+ const q = closestOnSegment(p, points[2 * i], points[2 * i + 1], points[2 * j], points[2 * j + 1]);
4279
+ const d = Math.hypot(q.x - x, q.y - y);
4280
+ if (d < best) best = d;
4281
+ }
4282
+ return best;
4283
+ }
4284
+ /**
4285
+ * The unsigned area of a polygon (shoelace).
4286
+ *
4287
+ * @param points - Flat ring, implicitly closed.
4288
+ * @returns The area; `0` for fewer than three vertices.
4289
+ */
4290
+ function polygonArea(points) {
4291
+ const n = vertexCount(points);
4292
+ if (n < 3) return 0;
4293
+ let sum = 0;
4294
+ for (let i = 0, j = n - 1; i < n; j = i++) sum += points[2 * j] * points[2 * i + 1] - points[2 * i] * points[2 * j + 1];
4295
+ return Math.abs(sum) / 2;
4296
+ }
4297
+ /**
4298
+ * A polygon as an SVG path (`M … L … Z`) from its first vertex, wound the same way whatever the
4299
+ * input's winding.
4300
+ * A batched path of overlapping polygons filled with the nonzero rule would otherwise cut a
4301
+ * hole where a clockwise ring overlaps an anticlockwise one.
4302
+ *
4303
+ * @param points - Flat ring.
4304
+ * @returns Path data; `""` with no vertices.
4305
+ */
4306
+ function areaPath(points) {
4307
+ const n = vertexCount(points);
4308
+ if (n === 0) return "";
4309
+ let signed = 0;
4310
+ for (let i = 0, j = n - 1; i < n; j = i++) signed += points[2 * j] * points[2 * i + 1] - points[2 * i] * points[2 * j + 1];
4311
+ const reversed = signed < 0;
4312
+ const at = (k) => reversed ? (n - k) % n : k;
4313
+ let d = `M${points[2 * at(0)]} ${points[2 * at(0) + 1]}`;
4314
+ if (n === 1) return `${d}h0`;
4315
+ for (let k = 1; k < n; k++) d += `L${points[2 * at(k)]} ${points[2 * at(k) + 1]}`;
4316
+ return `${d}Z`;
4317
+ }
4318
+ /**
4319
+ * The centre a label is drawn at: the mean of the vertices.
4320
+ *
4321
+ * @param points - Flat ring.
4322
+ * @returns The mean, or `null` for an empty ring.
4323
+ */
4324
+ function areaCentre(points) {
4325
+ const n = vertexCount(points);
4326
+ if (n === 0) return null;
4327
+ let sx = 0;
4328
+ let sy = 0;
4329
+ for (let i = 0; i < n; i++) {
4330
+ sx += points[2 * i];
4331
+ sy += points[2 * i + 1];
4332
+ }
4333
+ return {
4334
+ x: sx / n,
4335
+ y: sy / n
4336
+ };
4337
+ }
4338
+ /**
4339
+ * Index a set of polygons.
4340
+ *
4341
+ * @param items - The polygons.
4342
+ * @param cell - The grid cell side in image pixels. Defaults to the median of the polygons'
4343
+ * larger bounding-box sides, within `[8, 256]`, doubled if the grid would be huge.
4344
+ * @returns The index.
4345
+ */
4346
+ function buildAreaIndex(items, cell) {
4347
+ const count = items.length;
4348
+ const bounds = new Float64Array(count * 4).fill(NaN);
4349
+ const size = new Float64Array(count);
4350
+ let minX = Infinity;
4351
+ let minY = Infinity;
4352
+ let maxX = -Infinity;
4353
+ let maxY = -Infinity;
4354
+ const sides = [];
4355
+ items.forEach((item, a) => {
4356
+ const p = item.points;
4357
+ let x0 = Infinity;
4358
+ let y0 = Infinity;
4359
+ let x1 = -Infinity;
4360
+ let y1 = -Infinity;
4361
+ for (let i = 0; i + 1 < p.length; i += 2) {
4362
+ const x = p[i];
4363
+ const y = p[i + 1];
4364
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
4365
+ if (x < x0) x0 = x;
4366
+ if (x > x1) x1 = x;
4367
+ if (y < y0) y0 = y;
4368
+ if (y > y1) y1 = y;
4369
+ }
4370
+ if (!(x1 >= x0)) return;
4371
+ bounds[4 * a] = x0;
4372
+ bounds[4 * a + 1] = y0;
4373
+ bounds[4 * a + 2] = x1;
4374
+ bounds[4 * a + 3] = y1;
4375
+ size[a] = polygonArea(p);
4376
+ minX = Math.min(minX, x0);
4377
+ minY = Math.min(minY, y0);
4378
+ maxX = Math.max(maxX, x1);
4379
+ maxY = Math.max(maxY, y1);
4380
+ sides.push(Math.max(x1 - x0, y1 - y0));
4381
+ });
4382
+ if (sides.length === 0) return {
4383
+ items,
4384
+ bounds,
4385
+ size,
4386
+ cell: 1,
4387
+ x0: 0,
4388
+ y0: 0,
4389
+ cols: 1,
4390
+ rows: 1,
4391
+ starts: /* @__PURE__ */ new Uint32Array(2),
4392
+ entries: /* @__PURE__ */ new Uint32Array(0)
4393
+ };
4394
+ sides.sort((a, b) => a - b);
4395
+ let side = cell ?? Math.min(256, Math.max(8, sides[sides.length >> 1]));
4396
+ const width = maxX - minX;
4397
+ const height = maxY - minY;
4398
+ const cellsAt = (s) => (Math.floor(width / s) + 1) * (Math.floor(height / s) + 1);
4399
+ const entriesAt = (s) => {
4400
+ let total = 0;
4401
+ for (let a = 0; a < count; a++) {
4402
+ if (Number.isNaN(bounds[4 * a])) continue;
4403
+ total += (Math.floor((bounds[4 * a + 2] - bounds[4 * a]) / s) + 1) * (Math.floor((bounds[4 * a + 3] - bounds[4 * a + 1]) / s) + 1);
4404
+ }
4405
+ return total;
4406
+ };
4407
+ while (cellsAt(side) > MAX_CELLS || entriesAt(side) > MAX_ENTRIES) side *= 2;
4408
+ const cols = Math.floor(width / side) + 1;
4409
+ const rows = Math.floor(height / side) + 1;
4410
+ const cellX = (x) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / side)));
4411
+ const cellY = (y) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / side)));
4412
+ const starts = new Uint32Array(cols * rows + 1);
4413
+ const visit = (fn) => {
4414
+ for (let a = 0; a < count; a++) {
4415
+ if (Number.isNaN(bounds[4 * a])) continue;
4416
+ const cx0 = cellX(bounds[4 * a]);
4417
+ const cx1 = cellX(bounds[4 * a + 2]);
4418
+ const cy0 = cellY(bounds[4 * a + 1]);
4419
+ const cy1 = cellY(bounds[4 * a + 3]);
4420
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, a);
4421
+ }
4422
+ };
4423
+ visit((c) => starts[c + 1]++);
4424
+ for (let c = 0; c < cols * rows; c++) starts[c + 1] += starts[c];
4425
+ const fill = starts.slice(0, cols * rows);
4426
+ const entries = new Uint32Array(starts[cols * rows]);
4427
+ visit((c, a) => {
4428
+ entries[fill[c]++] = a;
4429
+ });
4430
+ return {
4431
+ items,
4432
+ bounds,
4433
+ size,
4434
+ cell: side,
4435
+ x0: minX,
4436
+ y0: minY,
4437
+ cols,
4438
+ rows,
4439
+ starts,
4440
+ entries
4441
+ };
4442
+ }
4443
+ /**
4444
+ * The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
4445
+ * The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
4446
+ */
4447
+ function areaCandidates(index, left, top, right, bottom) {
4448
+ const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
4449
+ if (entries.length === 0) return [];
4450
+ const cx0 = Math.max(0, Math.floor((left - x0) / cell));
4451
+ const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
4452
+ const cy0 = Math.max(0, Math.floor((top - y0) / cell));
4453
+ const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
4454
+ const seen = /* @__PURE__ */ new Set();
4455
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
4456
+ const c = cy * cols + cx;
4457
+ for (let k = starts[c]; k < starts[c + 1]; k++) {
4458
+ const a = entries[k];
4459
+ if (seen.has(a)) continue;
4460
+ if (bounds[4 * a] <= right && bounds[4 * a + 2] >= left && bounds[4 * a + 1] <= bottom && bounds[4 * a + 3] >= top) seen.add(a);
4461
+ }
4462
+ }
4463
+ return [...seen].sort((a, b) => a - b);
4464
+ }
4465
+ /**
4466
+ * The area under a point: one whose outline passes within `radius`, or else one that contains it.
4467
+ *
4468
+ * An outline is the more precise gesture, so it wins: among areas whose outline is within
4469
+ * `radius` the nearest is picked, and only without one the containing area. Ties (equal
4470
+ * distance, or several containing areas) go to the smaller area, so a quad drawn inside a
4471
+ * region is picked rather than the region, then to the earlier one. The result does not depend
4472
+ * on cell order.
4473
+ *
4474
+ * @param index - The index.
4475
+ * @param p - The query, in image coordinates.
4476
+ * @param radius - How far from an outline the query still picks it, in image pixels.
4477
+ * @returns The area, or `null`.
4478
+ */
4479
+ function nearestArea(index, p, radius) {
4480
+ if (!(radius >= 0)) return null;
4481
+ const { items, size } = index;
4482
+ let edge = null;
4483
+ let inner = null;
4484
+ for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4485
+ const points = items[a].points;
4486
+ const distance = distanceToOutline(points, p.x, p.y);
4487
+ const inside = pointInPolygon(points, p.x, p.y);
4488
+ const hit = {
4489
+ id: items[a].id,
4490
+ index: a,
4491
+ inside,
4492
+ distance
4493
+ };
4494
+ if (distance <= radius) {
4495
+ if (edge === null || distance < edge.distance || distance === edge.distance && size[a] < size[edge.index]) edge = hit;
4496
+ } else if (inside && (inner === null || size[a] < size[inner.index])) inner = hit;
4497
+ }
4498
+ return edge ?? inner;
4499
+ }
4500
+ /**
4501
+ * The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole
4502
+ * rectangle lying inside the polygon.
4503
+ *
4504
+ * @param index - The index.
4505
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
4506
+ * its corners.
4507
+ * @returns Their ids, in the order the areas were given.
4508
+ */
4509
+ function areasInRect(index, rect) {
4510
+ const box = {
4511
+ x: Math.min(rect.x, rect.x + rect.width),
4512
+ y: Math.min(rect.y, rect.y + rect.height),
4513
+ width: Math.abs(rect.width),
4514
+ height: Math.abs(rect.height)
4515
+ };
4516
+ const out = [];
4517
+ for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) if (polygonTouchesRect(index.items[a].points, box)) out.push(index.items[a].id);
4518
+ return out;
4519
+ }
4520
+ function polygonTouchesRect(points, rect) {
4521
+ const n = vertexCount(points);
4522
+ const right = rect.x + rect.width;
4523
+ const bottom = rect.y + rect.height;
4524
+ for (let i = 0; i < n; i++) {
4525
+ const x = points[2 * i];
4526
+ const y = points[2 * i + 1];
4527
+ if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;
4528
+ }
4529
+ const edges = n < 2 ? 0 : n === 2 ? 1 : n;
4530
+ for (let i = 0; i < edges; i++) {
4531
+ const j = (i + 1) % n;
4532
+ if (segmentTouchesRect(points[2 * i], points[2 * i + 1], points[2 * j], points[2 * j + 1], rect)) return true;
4533
+ }
4534
+ return pointInPolygon(points, rect.x, rect.y);
4535
+ }
4536
+ //#endregion
4537
+ //#region src/components/AreaSet.tsx
4538
+ /**
4539
+ * Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,
4540
+ * region annotations, defect outlines.
4541
+ *
4542
+ * Drawn as a handful of batched paths, one per (state, role), each outline with its 12 % fill
4543
+ * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the
4544
+ * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
4545
+ * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
4546
+ */
4547
+ const HALO$4 = overlayRole("halo");
4548
+ const LABEL = overlayRole("label");
4549
+ /** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */
4550
+ const FILL_OPACITY = .12;
4551
+ /** How long the first-vertex tick is, in screen pixels, at most. */
4552
+ const TICK_PX = 8;
4553
+ /**
4554
+ * A selectable set of closed regions inside an `ImageStage`.
4555
+ *
4556
+ * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default).
4557
+ * Rings are wound alike before they are batched, so overlapping regions never cut a hole in
4558
+ * each other.
4559
+ * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and
4560
+ * `structure`), hover 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every
4561
+ * outline has a halo. A region has no ring: its outline at 2.5 px is the mark.
4562
+ * - **Labels** at the centre of a region, only where regions are at least 24 screen px apart,
4563
+ * at most 200 at a time. The hovered and selected regions always carry theirs.
4564
+ * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
4565
+ * an outline picks that region, else the smallest region containing the point. `onHoverChange`
4566
+ * and `onItemPress` here, and `useStageHitTest` for an app that arbitrates between layers.
4567
+ *
4568
+ * The SVG carries `data-hovered` (the hovered id).
4569
+ */
4570
+ 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" }) {
4571
+ const stage = useStage();
4572
+ const px = useScreenPx();
4573
+ const unit = px(1);
4574
+ const index = useMemo(() => buildAreaIndex(items), [items]);
4575
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
4576
+ const isDimmed = useMemo(() => {
4577
+ if (typeof dimmed === "function") return dimmed;
4578
+ const set = new Set(dimmed ?? []);
4579
+ return (id) => set.has(id);
4580
+ }, [dimmed]);
4581
+ const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
4582
+ const [ownHover, setOwnHover] = useState(null);
4583
+ const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
4584
+ useStageHitLayer({
4585
+ layerId,
4586
+ priority,
4587
+ pick: (point, radius) => {
4588
+ const hit = nearestArea(index, point, radius);
4589
+ return hit ? {
4590
+ id: hit.id,
4591
+ dist: hit.inside ? 0 : hit.distance
4592
+ } : null;
4593
+ },
4594
+ onHover: (id) => {
4595
+ setOwnHover(id);
4596
+ onHoverChange?.(id);
4597
+ },
4598
+ onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
4599
+ });
4600
+ const groups = useMemo(() => {
4601
+ const normal = /* @__PURE__ */ new Map();
4602
+ const picked = {
4603
+ key: "selected",
4604
+ role: "selection",
4605
+ dim: false,
4606
+ indices: [],
4607
+ d: ""
4608
+ };
4609
+ items.forEach((item, i) => {
4610
+ if (selectedSet.has(item.id)) {
4611
+ picked.indices.push(i);
4612
+ picked.d += areaPath(item.points);
4613
+ return;
4614
+ }
4615
+ const itemRole = item.role ?? role;
4616
+ const dim = isDimmed(item.id);
4617
+ const key = `${dim ? 1 : 0}|${itemRole}`;
4618
+ let batch = normal.get(key);
4619
+ if (!batch) {
4620
+ batch = {
4621
+ key,
4622
+ role: itemRole,
4623
+ dim,
4624
+ indices: [],
4625
+ d: ""
4626
+ };
4627
+ normal.set(key, batch);
4628
+ }
4629
+ batch.indices.push(i);
4630
+ batch.d += areaPath(item.points);
4631
+ });
4632
+ return {
4633
+ normal: [...normal.values()],
4634
+ picked: picked.indices.length > 0 ? picked : null
4635
+ };
4636
+ }, [
4637
+ items,
4638
+ role,
4639
+ selectedSet,
4640
+ isDimmed
4641
+ ]);
4642
+ const ticks = useMemo(() => {
4643
+ if (!firstVertexTick) return [];
4644
+ return (groups.picked ? [...groups.normal, groups.picked] : groups.normal).map((batch) => {
4645
+ let d = "";
4646
+ for (const i of batch.indices) d += tickPath(items[i].points, TICK_PX * unit);
4647
+ return {
4648
+ batch,
4649
+ d
4650
+ };
4651
+ });
4652
+ }, [
4653
+ firstVertexTick,
4654
+ groups,
4655
+ items,
4656
+ unit
4657
+ ]);
4658
+ const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
4659
+ const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
4660
+ const hoverRole = hoverItem?.role ?? role;
4661
+ const anchors = useMemo(() => {
4662
+ const xy = new Float64Array(items.length * 2);
4663
+ const labelled = [];
4664
+ items.forEach((item, i) => {
4665
+ const c = areaCentre(item.points);
4666
+ xy[2 * i] = c?.x ?? NaN;
4667
+ xy[2 * i + 1] = c?.y ?? NaN;
4668
+ if (item.label) labelled.push(i);
4669
+ });
4670
+ return {
4671
+ xy,
4672
+ labelled
4673
+ };
4674
+ }, [items]);
4675
+ const forced = useMemo(() => {
4676
+ const list = [];
4677
+ if (hoverItem?.label) list.push(positionOf.get(hoverItem.id));
4678
+ for (const id of selectedSet) {
4679
+ const i = positionOf.get(id);
4680
+ if (i !== void 0 && items[i].label) list.push(i);
4681
+ }
4682
+ return list;
4683
+ }, [
4684
+ hoverItem,
4685
+ selectedSet,
4686
+ positionOf,
4687
+ items
4688
+ ]);
4689
+ const shownLabels = useLabelIndices({
4690
+ enabled: labels,
4691
+ xy: anchors.xy,
4692
+ labelled: anchors.labelled,
4693
+ forced
4694
+ });
4695
+ const widthOf = (itemRole, state) => {
4696
+ const thin = itemRole === "model" || itemRole === "structure";
4697
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
4698
+ };
4699
+ return /* @__PURE__ */ jsxs("svg", {
4700
+ viewBox: imageViewBox(stage.image),
4701
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
4702
+ role: "img",
4703
+ "aria-label": `${label}: ${items.length} ${items.length === 1 ? "area" : "areas"}, ${selectedSet.size} selected`,
4704
+ "data-hovered": hoverId ?? void 0,
4705
+ children: [/* @__PURE__ */ jsxs("g", {
4706
+ fill: "none",
4707
+ strokeLinecap: "round",
4708
+ strokeLinejoin: "round",
4709
+ children: [
4710
+ groups.normal.map((batch) => /* @__PURE__ */ jsxs("g", {
4711
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4712
+ children: [halo && /* @__PURE__ */ jsx("path", {
4713
+ d: batch.d,
4714
+ stroke: HALO$4,
4715
+ strokeWidth: widthOf(batch.role, "default") + px(2),
4716
+ opacity: .6
4717
+ }), /* @__PURE__ */ jsx("path", {
4718
+ "data-batch": batch.key,
4719
+ d: batch.d,
4720
+ fill: overlayRole(batch.role),
4721
+ fillOpacity: FILL_OPACITY,
4722
+ stroke: overlayRole(batch.role),
4723
+ strokeWidth: widthOf(batch.role, "default")
4724
+ })]
4725
+ }, batch.key)),
4726
+ groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4727
+ d: groups.picked.d,
4728
+ stroke: HALO$4,
4729
+ strokeWidth: widthOf("selection", "selected") + px(2)
4730
+ }), /* @__PURE__ */ jsx("path", {
4731
+ "data-selected-areas": "",
4732
+ d: groups.picked.d,
4733
+ fill: selectionStroke,
4734
+ fillOpacity: FILL_OPACITY,
4735
+ stroke: selectionStroke,
4736
+ strokeWidth: widthOf("selection", "selected")
4737
+ })] }),
4738
+ hoverItem && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4739
+ d: areaPath(hoverItem.points),
4740
+ stroke: HALO$4,
4741
+ strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)
4742
+ }), /* @__PURE__ */ jsx("path", {
4743
+ "data-hovered-area": "",
4744
+ d: areaPath(hoverItem.points),
4745
+ stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
4746
+ strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover")
4747
+ })] }),
4748
+ ticks.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
4749
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4750
+ children: [halo && /* @__PURE__ */ jsx("path", {
4751
+ d,
4752
+ stroke: HALO$4,
4753
+ strokeWidth: px(OVERLAY_STATE_WIDTH.selected + 2),
4754
+ opacity: .6
4755
+ }), /* @__PURE__ */ jsx("path", {
4756
+ "data-ticks": batch.key,
4757
+ d,
4758
+ stroke: batch === groups.picked ? selectionStroke : overlayRole(batch.role),
4759
+ strokeWidth: px(OVERLAY_STATE_WIDTH.selected)
4760
+ })]
4761
+ }, `tick|${batch.key}`))
4762
+ ]
4763
+ }), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
4764
+ "data-labels": "",
4765
+ fontSize: px(11),
4766
+ className: "font-mono",
4767
+ stroke: HALO$4,
4768
+ strokeWidth: px(3),
4769
+ paintOrder: "stroke",
4770
+ strokeLinejoin: "round",
4771
+ children: shownLabels.map((i) => /* @__PURE__ */ jsx("text", {
4772
+ x: anchors.xy[2 * i],
4773
+ y: anchors.xy[2 * i + 1],
4774
+ fill: LABEL,
4775
+ textAnchor: "middle",
4776
+ dominantBaseline: "central",
4777
+ children: items[i].label
4778
+ }, items[i].id))
4779
+ })]
4780
+ });
4781
+ }
4782
+ /**
4783
+ * The first-vertex tick of a ring: a segment from vertex 0 towards the ring's centre, at most
4784
+ * `length` long and at most 45 % of the way there, so a small quad's tick stays inside it.
4785
+ */
4786
+ function tickPath(points, length) {
4787
+ const c = areaCentre(points);
4788
+ if (c === null || points.length < 4) return "";
4789
+ const x = points[0];
4790
+ const y = points[1];
4791
+ const dist = Math.hypot(c.x - x, c.y - y);
4792
+ if (!(dist > 0)) return "";
4793
+ const k = Math.min(length, .45 * dist) / dist;
4794
+ return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1e3) / 1e3} ${Math.round((y + (c.y - y) * k) * 1e3) / 1e3}`;
4795
+ }
4796
+ //#endregion
4797
+ //#region src/components/ellipseIndex.ts
4798
+ /**
4799
+ * A spatial index over many ellipses: which one is under the pointer, and which ones a
4800
+ * rubber band touched.
4801
+ *
4802
+ * The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
4803
+ * items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
4804
+ * exact tests are in the ellipse's own frame: containment is one quadratic form, and the
4805
+ * distance to the outline is the true Euclidean distance (a few Newton steps on the
4806
+ * parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
4807
+ * round one. It imports neither React nor the DOM.
4808
+ *
4809
+ * An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
4810
+ * outline to draw or to pick.
4811
+ */
4812
+ function usable(e) {
4813
+ return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
4814
+ }
4815
+ /**
4816
+ * The axis-aligned bounding box of an ellipse.
4817
+ *
4818
+ * @param e - The ellipse.
4819
+ * @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
4820
+ */
4821
+ function ellipseBounds(e) {
4822
+ if (!usable(e)) return null;
4823
+ const c = Math.cos(e.angle ?? 0);
4824
+ const s = Math.sin(e.angle ?? 0);
4825
+ const hx = Math.hypot(e.rx * c, e.ry * s);
4826
+ const hy = Math.hypot(e.rx * s, e.ry * c);
4827
+ return [
4828
+ e.x - hx,
4829
+ e.y - hy,
4830
+ e.x + hx,
4831
+ e.y + hy
4832
+ ];
4833
+ }
4834
+ /** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
4835
+ function toFrame(e, x, y) {
4836
+ const c = Math.cos(e.angle ?? 0);
4837
+ const s = Math.sin(e.angle ?? 0);
4838
+ const dx = x - e.x;
4839
+ const dy = y - e.y;
4840
+ return {
4841
+ x: c * dx + s * dy,
4842
+ y: -s * dx + c * dy
4843
+ };
4844
+ }
4845
+ /**
4846
+ * Whether `(x, y)` is inside the ellipse (its outline counts as inside).
4847
+ *
4848
+ * @param e - The ellipse.
4849
+ * @param x - The query's x.
4850
+ * @param y - The query's y.
4851
+ * @returns `false` for a degenerate ellipse.
4852
+ */
4853
+ function pointInEllipse(e, x, y) {
4854
+ if (!usable(e)) return false;
4855
+ const p = toFrame(e, x, y);
4856
+ return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
4857
+ }
4858
+ /** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
4859
+ const NEWTON_STEPS = 12;
4860
+ /**
4861
+ * The Euclidean distance from `(x, y)` to the outline of an ellipse.
4862
+ *
4863
+ * The query is folded into the first quadrant of the ellipse's frame and the nearest outline
4864
+ * point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
4865
+ * better of a coarse scan so a thin ellipse and a query near its centre both converge.
4866
+ *
4867
+ * @param e - The ellipse.
4868
+ * @param x - The query's x.
4869
+ * @param y - The query's y.
4870
+ * @returns The distance; `Infinity` for a degenerate ellipse.
4871
+ */
4872
+ function distanceToEllipse(e, x, y) {
4873
+ if (!usable(e)) return Infinity;
4874
+ const p = toFrame(e, x, y);
4875
+ const px = Math.abs(p.x);
4876
+ const py = Math.abs(p.y);
4877
+ const a = e.rx;
4878
+ const b = e.ry;
4879
+ const squared = (t) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
4880
+ let t = 0;
4881
+ let best = Infinity;
4882
+ const SCAN = 16;
4883
+ for (let k = 0; k <= SCAN; k++) {
4884
+ const candidate = k / SCAN * (Math.PI / 2);
4885
+ const value = squared(candidate);
4886
+ if (value < best) {
4887
+ best = value;
4888
+ t = candidate;
4889
+ }
4890
+ }
4891
+ for (let i = 0; i < NEWTON_STEPS; i++) {
4892
+ const c = Math.cos(t);
4893
+ const s = Math.sin(t);
4894
+ const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
4895
+ const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
4896
+ if (!(Math.abs(df) > 1e-12)) break;
4897
+ const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
4898
+ if (squared(next) > squared(t)) break;
4899
+ t = next;
4900
+ }
4901
+ return Math.sqrt(squared(t));
4902
+ }
4903
+ /**
4904
+ * An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
4905
+ *
4906
+ * @param cx - Centre x, image pixels.
4907
+ * @param cy - Centre y, image pixels.
4908
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
4909
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
4910
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
4911
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
4912
+ */
4913
+ function ellipsePath(cx, cy, rx, ry, angle = 0) {
4914
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
4915
+ const dx = rx * Math.cos(angle);
4916
+ const dy = rx * Math.sin(angle);
4917
+ const degrees = round(angle * 180 / Math.PI);
4918
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
4919
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
4920
+ }
4921
+ /** Round to 1/1000 of an image pixel. */
4922
+ function round(value) {
4923
+ return Math.round(value * 1e3) / 1e3;
4924
+ }
4925
+ /**
4926
+ * Index a set of ellipses.
4927
+ *
4928
+ * @param items - The ellipses.
4929
+ * @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
4930
+ * @returns The index.
4931
+ */
4932
+ function buildEllipseIndex(items, cell) {
4933
+ const size = new Float64Array(items.length).fill(NaN);
4934
+ return {
4935
+ items,
4936
+ grid: buildAreaIndex(items.map((item, i) => {
4937
+ const box = ellipseBounds(item);
4938
+ if (box === null) return {
4939
+ id: i,
4940
+ points: []
4941
+ };
4942
+ size[i] = Math.PI * item.rx * item.ry;
4943
+ const [x0, y0, x1, y1] = box;
4944
+ return {
4945
+ id: i,
4946
+ points: [
4947
+ x0,
4948
+ y0,
4949
+ x1,
4950
+ y0,
4951
+ x1,
4952
+ y1,
4953
+ x0,
4954
+ y1
4955
+ ]
4956
+ };
4957
+ }), cell),
4958
+ size
4959
+ };
4960
+ }
4961
+ /**
4962
+ * The ellipse under a point: one whose outline passes within `radius`, or else one that
4963
+ * contains it.
4964
+ *
4965
+ * An outline is the more precise gesture, so it wins: among ellipses whose outline is within
4966
+ * `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
4967
+ * distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
4968
+ * another is picked rather than the outer one, then to the earlier one.
4969
+ *
4970
+ * @param index - The index.
4971
+ * @param p - The query, in image coordinates.
4972
+ * @param radius - How far from an outline the query still picks it, in image pixels.
4973
+ * @returns The ellipse, or `null`.
4974
+ */
4975
+ function nearestEllipse(index, p, radius) {
4976
+ if (!(radius >= 0)) return null;
4977
+ const { items, size } = index;
4978
+ let edge = null;
4979
+ let inner = null;
4980
+ for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
4981
+ const e = items[a];
4982
+ const distance = distanceToEllipse(e, p.x, p.y);
4983
+ const hit = {
4984
+ id: e.id,
4985
+ index: a,
4986
+ inside: pointInEllipse(e, p.x, p.y),
4987
+ distance
4988
+ };
4989
+ if (distance <= radius) {
4990
+ if (edge === null || distance < edge.distance || distance === edge.distance && size[a] < size[edge.index]) edge = hit;
4991
+ } else if (hit.inside && (inner === null || size[a] < size[inner.index])) inner = hit;
4992
+ }
4993
+ return edge ?? inner;
4994
+ }
4995
+ /**
4996
+ * The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
4997
+ * inside the ellipse, or contains it.
4998
+ *
4999
+ * @param index - The index.
5000
+ * @param rect - The band, in image coordinates. A negative extent is read as the box between
5001
+ * its corners.
5002
+ * @returns Their ids, in the order the ellipses were given.
5003
+ */
5004
+ function ellipsesInRect(index, rect) {
5005
+ const x0 = Math.min(rect.x, rect.x + rect.width);
5006
+ const y0 = Math.min(rect.y, rect.y + rect.height);
5007
+ const x1 = Math.max(rect.x, rect.x + rect.width);
5008
+ const y1 = Math.max(rect.y, rect.y + rect.height);
5009
+ const out = [];
5010
+ for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
5011
+ const e = index.items[a];
5012
+ if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
5013
+ }
5014
+ return out;
5015
+ }
5016
+ /** Whether the filled ellipse and the rectangle share a point (both convex). */
5017
+ function rectMeetsEllipse(e, x0, y0, x1, y1) {
5018
+ if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
5019
+ const corners = [
5020
+ {
5021
+ x: x0,
5022
+ y: y0
5023
+ },
5024
+ {
5025
+ x: x1,
5026
+ y: y0
5027
+ },
5028
+ {
5029
+ x: x1,
5030
+ y: y1
5031
+ },
5032
+ {
5033
+ x: x0,
5034
+ y: y1
5035
+ }
5036
+ ];
5037
+ if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
5038
+ for (let k = 0; k < 4; k++) {
5039
+ const a = toFrame(e, corners[k].x, corners[k].y);
5040
+ const b = toFrame(e, corners[(k + 1) % 4].x, corners[(k + 1) % 4].y);
5041
+ const ux = (b.x - a.x) / e.rx;
5042
+ const uy = (b.y - a.y) / e.ry;
5043
+ const vx = a.x / e.rx;
5044
+ const vy = a.y / e.ry;
5045
+ const len2 = ux * ux + uy * uy;
5046
+ const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
5047
+ if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
5048
+ }
5049
+ return false;
5050
+ }
5051
+ //#endregion
5052
+ //#region src/components/EllipseSet.tsx
5053
+ /**
5054
+ * Many ellipses over the image whose size is data, hoverable and selectable: fitted ring
5055
+ * edges, edge-bit dots, drawn ellipse annotations.
5056
+ *
5057
+ * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
5058
+ * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
5059
+ * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
5060
+ * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
5061
+ * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
5062
+ */
5063
+ const HALO$3 = overlayRole("halo");
5064
+ /** The outline of an item, its semi-axes raised to `floor` image pixels. */
5065
+ function outlineOf(item, floor) {
5066
+ return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);
5067
+ }
5068
+ /** The concatenated outlines of the items at `indices`. */
5069
+ function batchPath(items, indices, floor) {
5070
+ let d = "";
5071
+ for (const i of indices) d += outlineOf(items[i], floor);
5072
+ return d;
5073
+ }
5074
+ /**
5075
+ * The layer's entry in the stage's hit registry: a component, not a hook call in
5076
+ * `EllipseSet`, so `pickable={false}` really unregisters it. Renders nothing.
5077
+ */
5078
+ function EllipseHits({ index, layerId, priority, onHover, onPress }) {
5079
+ useStageHitLayer({
5080
+ layerId,
5081
+ priority,
5082
+ pick: (point, radius) => {
5083
+ const hit = nearestEllipse(index, point, radius);
5084
+ return hit ? {
5085
+ id: hit.id,
5086
+ dist: hit.inside ? 0 : hit.distance
5087
+ } : null;
5088
+ },
5089
+ onHover,
5090
+ onPress: onPress ? (id, event) => onPress(id, event) : void 0
5091
+ });
5092
+ return null;
5093
+ }
5094
+ /**
5095
+ * A batched set of ellipses inside an `ImageStage`.
5096
+ *
5097
+ * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
5098
+ * the stroke is a screen constant.
5099
+ * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
5100
+ * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
5101
+ * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
5102
+ * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
5103
+ * an outline picks that ellipse, else the smallest ellipse containing the point.
5104
+ * `onHoverChange` and `onItemPress` here, and `useStageHitTest` for an app that arbitrates
5105
+ * between layers. `pickable={false}` turns it off.
5106
+ *
5107
+ * The SVG carries `data-ellipses` (the count) and `data-hovered` (the hovered id).
5108
+ */
5109
+ function EllipseSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, pickable = true, layerId, priority = STAGE_HIT_PRIORITY.area, halo = true, minRadius, selectionStroke = overlayRole("selection"), label }) {
5110
+ const stage = useStage();
5111
+ const px = useScreenPx();
5112
+ const unit = px(1);
5113
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
5114
+ const isDimmed = useMemo(() => {
5115
+ if (typeof dimmed === "function") return dimmed;
5116
+ const set = new Set(dimmed ?? []);
5117
+ return (id) => set.has(id);
5118
+ }, [dimmed]);
5119
+ const index = useMemo(() => pickable ? buildEllipseIndex(items) : null, [items, pickable]);
5120
+ const [ownHover, setOwnHover] = useState(null);
5121
+ const hoverId = hoveredId !== void 0 ? hoveredId : pickable ? ownHover : null;
5122
+ const batches = useMemo(() => {
5123
+ const normal = /* @__PURE__ */ new Map();
5124
+ const picked = {
5125
+ key: "selected",
5126
+ role: "selection",
5127
+ dashed: false,
5128
+ opacity: 1,
5129
+ dim: false,
5130
+ indices: []
5131
+ };
5132
+ items.forEach((item, i) => {
5133
+ if (selectedSet.has(item.id)) {
5134
+ picked.indices.push(i);
5135
+ return;
5136
+ }
5137
+ const itemRole = item.role ?? role;
5138
+ const dashed = item.dashed ?? false;
5139
+ const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;
5140
+ const dim = isDimmed(item.id);
5141
+ const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? "dashed" : "solid"}|${opacity}`;
5142
+ let batch = normal.get(key);
5143
+ if (!batch) {
5144
+ batch = {
5145
+ key,
5146
+ role: itemRole,
5147
+ dashed,
5148
+ opacity,
5149
+ dim,
5150
+ indices: []
5151
+ };
5152
+ normal.set(key, batch);
5153
+ }
5154
+ batch.indices.push(i);
5155
+ });
5156
+ return {
5157
+ normal: [...normal.values()],
5158
+ picked: picked.indices.length > 0 ? picked : null
5159
+ };
5160
+ }, [
5161
+ items,
5162
+ role,
5163
+ selectedSet,
5164
+ isDimmed
5165
+ ]);
5166
+ const floor = minRadius !== void 0 ? minRadius * unit : 0;
5167
+ const normalPaths = useMemo(() => batches.normal.map((batch) => ({
5168
+ batch,
5169
+ d: batchPath(items, batch.indices, floor)
5170
+ })), [
5171
+ batches,
5172
+ items,
5173
+ floor
5174
+ ]);
5175
+ const pickedPath = useMemo(() => batches.picked ? batchPath(items, batches.picked.indices, floor) : "", [
5176
+ batches,
5177
+ items,
5178
+ floor
5179
+ ]);
5180
+ const hoverPositions = [];
5181
+ if (hoverId !== null) items.forEach((item, i) => {
5182
+ if (item.id === hoverId) hoverPositions.push(i);
5183
+ });
5184
+ const hoverSelected = hoverId !== null && selectedSet.has(hoverId);
5185
+ const widthOf = (itemRole, state) => {
5186
+ const thin = itemRole === "model" || itemRole === "structure";
5187
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
5188
+ };
5189
+ const dash = `${px(4)} ${px(3)}`;
5190
+ return /* @__PURE__ */ jsxs("svg", {
5191
+ viewBox: imageViewBox(stage.image),
5192
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
5193
+ ...label !== void 0 ? {
5194
+ role: "img",
5195
+ "aria-label": label
5196
+ } : { "aria-hidden": true },
5197
+ "data-ellipses": items.length,
5198
+ "data-hovered": hoverId ?? void 0,
5199
+ children: [index && /* @__PURE__ */ jsx(EllipseHits, {
5200
+ index,
5201
+ layerId,
5202
+ priority,
5203
+ onHover: (id) => {
5204
+ setOwnHover(id);
5205
+ onHoverChange?.(id);
5206
+ },
5207
+ onPress: onItemPress
5208
+ }), /* @__PURE__ */ jsxs("g", {
5209
+ fill: "none",
5210
+ strokeLinecap: "round",
5211
+ strokeLinejoin: "round",
5212
+ children: [
5213
+ normalPaths.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
5214
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
5215
+ children: [halo && /* @__PURE__ */ jsx("path", {
5216
+ d,
5217
+ stroke: HALO$3,
5218
+ strokeWidth: widthOf(batch.role, "default") + px(2),
5219
+ strokeDasharray: batch.dashed ? dash : void 0,
5220
+ opacity: .6 * batch.opacity
5221
+ }), /* @__PURE__ */ jsx("path", {
5222
+ "data-batch": batch.key,
5223
+ d,
5224
+ stroke: overlayRole(batch.role),
5225
+ strokeWidth: widthOf(batch.role, "default"),
5226
+ strokeDasharray: batch.dashed ? dash : void 0,
5227
+ opacity: batch.opacity
5228
+ })]
5229
+ }, batch.key)),
5230
+ batches.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
5231
+ d: pickedPath,
5232
+ stroke: HALO$3,
5233
+ strokeWidth: widthOf("selection", "selected") + px(2)
5234
+ }), /* @__PURE__ */ jsx("path", {
5235
+ "data-selected-ellipses": "",
5236
+ d: pickedPath,
5237
+ stroke: selectionStroke,
5238
+ strokeWidth: widthOf("selection", "selected")
5239
+ })] }),
5240
+ hoverPositions.map((position) => {
5241
+ const item = items[position];
5242
+ const itemRole = item.role ?? role;
5243
+ const state = hoverSelected ? "selected" : "hover";
5244
+ return /* @__PURE__ */ jsxs("g", { children: [halo && /* @__PURE__ */ jsx("path", {
5245
+ d: outlineOf(item, floor),
5246
+ stroke: HALO$3,
5247
+ strokeWidth: widthOf(itemRole, state) + px(2)
5248
+ }), /* @__PURE__ */ jsx("path", {
5249
+ "data-hovered-ellipse": "",
5250
+ d: outlineOf(item, floor),
5251
+ stroke: hoverSelected ? selectionStroke : overlayRole(itemRole),
5252
+ strokeWidth: widthOf(itemRole, state)
5253
+ })] }, position);
5254
+ })
5255
+ ]
5256
+ })]
5257
+ });
5258
+ }
5259
+ //#endregion
5260
+ //#region src/components/gridEdges.ts
5261
+ /** Indices past this magnitude are not hashed (the key must stay an exact integer). */
5262
+ const LIMIT = 2 ** 25;
5263
+ function key(i, j) {
5264
+ return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
5265
+ }
5266
+ /**
5267
+ * The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
5268
+ * axis.
5269
+ *
5270
+ * @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
5271
+ * integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
5272
+ * first one is the lattice's node there.
5273
+ * @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
5274
+ */
5275
+ function latticeEdges(nodes) {
5276
+ const at = /* @__PURE__ */ new Map();
5277
+ const valid = (n) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
5278
+ for (let p = 0; p < nodes.length; p++) {
5279
+ const node = nodes[p];
5280
+ if (!valid(node)) continue;
5281
+ const k = key(node.i, node.j);
5282
+ if (!at.has(k)) at.set(k, p);
5283
+ }
5284
+ const edges = [];
5285
+ for (let p = 0; p < nodes.length; p++) {
5286
+ const node = nodes[p];
5287
+ if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
5288
+ if (node.i + 1 < LIMIT) {
5289
+ const q = at.get(key(node.i + 1, node.j));
5290
+ if (q !== void 0) edges.push({
5291
+ a: p,
5292
+ b: q,
5293
+ axis: "i"
5294
+ });
5295
+ }
5296
+ if (node.j + 1 < LIMIT) {
5297
+ const q = at.get(key(node.i, node.j + 1));
5298
+ if (q !== void 0) edges.push({
5299
+ a: p,
5300
+ b: q,
5301
+ axis: "j"
5302
+ });
5303
+ }
5304
+ }
5305
+ return edges;
5306
+ }
5307
+ //#endregion
5308
+ //#region src/components/GridLayer.tsx
5309
+ /**
5310
+ * A detected lattice over the image: the corners of a calibration board with the row and
5311
+ * column edges between neighbours, and optional `(i, j)` labels.
5312
+ *
5313
+ * Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of
5314
+ * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1
5315
+ * and 4). Edges are not picked: a person points at a corner.
5316
+ */
5317
+ const HALO$2 = overlayRole("halo");
5318
+ /** A style with its defaults filled in. */
5319
+ function edgeStyle(style) {
5320
+ return {
5321
+ role: style?.role ?? "structure",
5322
+ dashed: style?.dashed ?? false,
5323
+ visible: style?.visible ?? true
5324
+ };
5325
+ }
5326
+ /**
5327
+ * A detected lattice inside an `ImageStage`.
5328
+ *
5329
+ * - **Nodes** are a `PointSet`: `plus` markers by default, picked through the point index at
5330
+ * point priority, with `onHoverChange`, `onItemPress`, selection (with ring) and dimming.
5331
+ * - **Edges** join `(i, j)` to `(i + 1, j)` and to `(i, j + 1)` where both nodes exist
5332
+ * (`latticeEdges`), in one path per axis and dimming, below the nodes. They are `structure`
5333
+ * role by default, 1 screen px with a halo; `edges` restyles each axis.
5334
+ * - **Labels** are the nodes' own `label`s, or with `indexLabels` their `i,j`, only where nodes
5335
+ * are at least 24 screen px apart.
5336
+ *
5337
+ * The edges' SVG carries `data-edges`; the nodes' is the `PointSet`'s.
5338
+ */
5339
+ function GridLayer({ nodes, edges, kind = "plus", markers, indexLabels = false, labels = true, hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, halo = true, selectionStroke, layerId, priority = STAGE_HIT_PRIORITY.point, label = "Grid" }) {
5340
+ const stage = useStage();
5341
+ const px = useScreenPx();
5342
+ const styles = {
5343
+ i: edgeStyle(edges?.i),
5344
+ j: edgeStyle(edges?.j)
5345
+ };
5346
+ const isDimmed = useMemo(() => {
5347
+ if (typeof dimmed === "function") return dimmed;
5348
+ const set = new Set(dimmed ?? []);
5349
+ return (id) => set.has(id);
5350
+ }, [dimmed]);
5351
+ const batches = useMemo(() => {
5352
+ const map = /* @__PURE__ */ new Map();
5353
+ for (const edge of latticeEdges(nodes)) {
5354
+ const a = nodes[edge.a];
5355
+ const b = nodes[edge.b];
5356
+ if (!Number.isFinite(a.x + a.y + b.x + b.y)) continue;
5357
+ const dim = isDimmed(a.id) && isDimmed(b.id);
5358
+ const k = `${edge.axis}|${dim ? 1 : 0}`;
5359
+ let batch = map.get(k);
5360
+ if (!batch) {
5361
+ batch = {
5362
+ key: k,
5363
+ axis: edge.axis,
5364
+ dim,
5365
+ d: ""
5366
+ };
5367
+ map.set(k, batch);
5368
+ }
5369
+ batch.d += `M${a.x} ${a.y}L${b.x} ${b.y}`;
5370
+ }
5371
+ return [...map.values()];
5372
+ }, [nodes, isDimmed]);
5373
+ const items = useMemo(() => indexLabels ? nodes.map((node) => node.label ? node : {
5374
+ ...node,
5375
+ label: `${node.i},${node.j}`
5376
+ }) : nodes, [nodes, indexLabels]);
5377
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("svg", {
5378
+ viewBox: imageViewBox(stage.image),
5379
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
5380
+ "data-edges": "",
5381
+ "aria-hidden": true,
5382
+ children: /* @__PURE__ */ jsx("g", {
5383
+ fill: "none",
5384
+ strokeLinecap: "round",
5385
+ strokeLinejoin: "round",
5386
+ children: batches.filter((batch) => styles[batch.axis].visible).map((batch) => {
5387
+ const style = styles[batch.axis];
5388
+ const thin = style.role === "model" || style.role === "structure";
5389
+ const width = px(OVERLAY_STATE_WIDTH.default - (thin ? .5 : 0));
5390
+ const dash = style.dashed ? `${px(4)} ${px(3)}` : void 0;
5391
+ return /* @__PURE__ */ jsxs("g", {
5392
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
5393
+ children: [halo && /* @__PURE__ */ jsx("path", {
5394
+ d: batch.d,
5395
+ stroke: HALO$2,
5396
+ strokeWidth: width + px(2),
5397
+ opacity: .6
5398
+ }), /* @__PURE__ */ jsx("path", {
5399
+ "data-edge-batch": batch.key,
5400
+ d: batch.d,
5401
+ stroke: overlayRole(style.role),
5402
+ strokeWidth: width,
5403
+ strokeDasharray: dash
5404
+ })]
5405
+ }, batch.key);
5406
+ })
5407
+ })
5408
+ }), /* @__PURE__ */ jsx(PointSet, {
5409
+ items,
5410
+ kind,
5411
+ markers,
5412
+ hoveredId,
5413
+ onHoverChange,
5414
+ selectedIds,
5415
+ dimmed,
5416
+ onItemPress,
5417
+ labels,
5418
+ halo,
5419
+ selectionStroke,
5420
+ layerId,
5421
+ priority,
5422
+ label
5423
+ })] });
5424
+ }
5425
+ //#endregion
5426
+ //#region src/components/heatmapRaster.ts
5427
+ /** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */
5428
+ const STEPS = 256;
5429
+ /**
5430
+ * The extent of a plane's finite values.
5431
+ *
5432
+ * @param plane - The plane.
5433
+ * @param channel - Which of its channels. Defaults to the first.
5434
+ * @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.
5435
+ */
5436
+ function planeRange(plane, channel = 0) {
5437
+ if (!(channel >= 0 && channel < plane.channels)) return null;
5438
+ const size = plane.width * plane.height;
5439
+ const offset = channel * size;
5440
+ let low = Infinity;
5441
+ let high = -Infinity;
5442
+ for (let k = 0; k < size; k++) {
5443
+ const v = plane.values[offset + k];
5444
+ if (!Number.isFinite(v)) continue;
5445
+ if (v < low) low = v;
5446
+ if (v > high) high = v;
5447
+ }
5448
+ return low <= high ? {
5449
+ low,
5450
+ high
5451
+ } : null;
5452
+ }
5453
+ /**
5454
+ * Colour a plane through a colour map.
5455
+ *
5456
+ * Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered
5457
+ * pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range
5458
+ * (`high <= low`) draws every pixel in the map's first colour.
5459
+ *
5460
+ * @param plane - The plane.
5461
+ * @param colormap - The colour map; sampled at 256 positions.
5462
+ * @param range - What the map spans. Defaults to the extent of the channel's finite values.
5463
+ * @param channel - Which channel to draw. Defaults to the first.
5464
+ * @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.
5465
+ */
5466
+ function rasterizePlane(plane, colormap, range, channel = 0) {
5467
+ const size = plane.width * plane.height;
5468
+ const out = new Uint8ClampedArray(size * 4);
5469
+ if (!(channel >= 0 && channel < plane.channels)) return out;
5470
+ const { low, high } = range ?? planeRange(plane, channel) ?? {
5471
+ low: 0,
5472
+ high: 0
5473
+ };
5474
+ const lut = new Uint8ClampedArray(STEPS * 3);
5475
+ for (let s = 0; s < STEPS; s++) {
5476
+ const [r, g, b] = colormap(s / 255);
5477
+ lut[3 * s] = r;
5478
+ lut[3 * s + 1] = g;
5479
+ lut[3 * s + 2] = b;
5480
+ }
5481
+ const scale = high > low ? 255 / (high - low) : 0;
5482
+ const offset = channel * size;
5483
+ for (let k = 0; k < size; k++) {
5484
+ const v = plane.values[offset + k];
5485
+ if (!Number.isFinite(v)) continue;
5486
+ const s = Math.min(255, Math.max(0, Math.round((v - low) * scale)));
5487
+ out[4 * k] = lut[3 * s];
5488
+ out[4 * k + 1] = lut[3 * s + 1];
5489
+ out[4 * k + 2] = lut[3 * s + 2];
5490
+ out[4 * k + 3] = 255;
5491
+ }
5492
+ return out;
5493
+ }
5494
+ //#endregion
5495
+ //#region src/components/HeatmapLayer.tsx
5496
+ /**
5497
+ * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.
5498
+ *
5499
+ * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an
5500
+ * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage
5501
+ * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel
5502
+ * map costs one element. It takes no pointer events; to read the numbers under the pointer, use
5503
+ * `valueAt` on the plane.
5504
+ */
5505
+ /**
5506
+ * A heatmap inside an `ImageStage`: a scalar field coloured through a colour map, or an RGBA
5507
+ * buffer, placed over the image (default) or any rectangle of it.
5508
+ *
5509
+ * - **Rasterised in an effect**, once per change of its data, into an offscreen canvas and an
5510
+ * object URL that is revoked when replaced and on unmount. Server rendering draws nothing.
5511
+ * - **Pixelated** from 4 CSS pixels per heatmap pixel, like `ImageLayer`, so the cells of a
5512
+ * coarse map are not smoothed into a blur.
5513
+ * - **Stacking:** it is drawn where it is placed among the stage's children. Before the
5514
+ * overlays it sits under them; the image layer goes before it.
5515
+ * - **Input:** none. It takes no pointer events, so presses reach the layers above and the stage.
5516
+ *
5517
+ * The image carries `data-heatmap`, `data-pixelated` while pixelated, and `data-ready`.
5518
+ */
5519
+ function HeatmapLayer(props) {
5520
+ const { opacity = 1, visible = true, rect, pixelatedAbove = 4, alt = "", onReady, onError, className } = props;
5521
+ const stage = useStage();
5522
+ const [raster, setRaster] = useState(null);
5523
+ const [ready, setReady] = useState(false);
5524
+ const urlRef = useRef(null);
5525
+ const callbacksRef = useRef({
5526
+ onReady,
5527
+ onError
5528
+ });
5529
+ useEffect(() => {
5530
+ callbacksRef.current = {
5531
+ onReady,
5532
+ onError
5533
+ };
5534
+ });
5535
+ const { rgba, width, height, plane, colormap, channel } = props;
5536
+ const rangeLow = props.range?.low;
5537
+ const rangeHigh = props.range?.high;
5538
+ useEffect(() => {
5539
+ if (!visible) return;
5540
+ let cancelled = false;
5541
+ const source = rgba ? wrapRgba(rgba, width, height) : plane && colormap ? colourPlane(plane, colormap, rangeLow === void 0 || rangeHigh === void 0 ? void 0 : {
5542
+ low: rangeLow,
5543
+ high: rangeHigh
5544
+ }, channel) : null;
5545
+ const canvas = document.createElement("canvas");
5546
+ const context = source ? (canvas.width = source.width, canvas.height = source.height, canvas.getContext("2d")) : null;
5547
+ if (!source || !context) {
5548
+ callbacksRef.current.onError?.();
5549
+ return;
5550
+ }
5551
+ const { width: w, height: h } = source;
5552
+ context.putImageData(new ImageData(source.pixels, w, h), 0, 0);
5553
+ canvas.toBlob((blob) => {
5554
+ if (cancelled) return;
5555
+ if (!blob) {
5556
+ callbacksRef.current.onError?.();
5557
+ return;
5558
+ }
5559
+ const previous = urlRef.current;
5560
+ const url = URL.createObjectURL(blob);
5561
+ urlRef.current = url;
5562
+ setReady(false);
5563
+ setRaster({
5564
+ url,
5565
+ width: w,
5566
+ height: h
5567
+ });
5568
+ if (previous) URL.revokeObjectURL(previous);
5569
+ });
5570
+ return () => {
5571
+ cancelled = true;
5572
+ };
5573
+ }, [
5574
+ visible,
5575
+ rgba,
5576
+ width,
5577
+ height,
5578
+ plane,
5579
+ colormap,
5580
+ rangeLow,
5581
+ rangeHigh,
5582
+ channel
5583
+ ]);
5584
+ useEffect(() => () => {
5585
+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);
5586
+ urlRef.current = null;
5587
+ }, []);
5588
+ if (!visible || raster === null) return null;
5589
+ const box = rect ?? {
5590
+ x: -.5,
5591
+ y: -.5,
5592
+ width: stage.image.width,
5593
+ height: stage.image.height
5594
+ };
5595
+ const pixelated = stage.view.scale * box.width / raster.width >= pixelatedAbove;
5596
+ return /* @__PURE__ */ jsx("img", {
5597
+ src: raster.url,
5598
+ alt,
5599
+ draggable: false,
5600
+ "data-heatmap": "",
5601
+ "data-ready": ready ? "" : void 0,
5602
+ "data-pixelated": pixelated ? "" : void 0,
5603
+ onLoad: () => {
5604
+ setReady(true);
5605
+ callbacksRef.current.onReady?.();
5606
+ },
5607
+ className: cn("pointer-events-none absolute max-w-none select-none", className),
5608
+ style: {
5609
+ left: box.x + PIXEL_CENTRE,
5610
+ top: box.y + PIXEL_CENTRE,
5611
+ width: box.width,
5612
+ height: box.height,
5613
+ opacity,
5614
+ pointerEvents: "none",
5615
+ imageRendering: pixelated ? "pixelated" : void 0
5616
+ }
5617
+ });
5618
+ }
5619
+ /** The first `width · height · 4` bytes of an RGBA buffer, read in place; `null` if it is too short or empty. */
5620
+ function wrapRgba(rgba, width, height) {
5621
+ const length = width * height * 4;
5622
+ if (!(length > 0) || rgba.length < length) return null;
5623
+ return {
5624
+ pixels: new Uint8ClampedArray(rgba.buffer, rgba.byteOffset, length),
5625
+ width,
5626
+ height
5627
+ };
5628
+ }
5629
+ /** A plane through a colour map; `null` for an empty plane. */
5630
+ function colourPlane(plane, colormap, range, channel) {
5631
+ if (!(plane.width > 0 && plane.height > 0)) return null;
5632
+ return {
5633
+ pixels: rasterizePlane(plane, colormap, range, channel),
5634
+ width: plane.width,
5635
+ height: plane.height
5636
+ };
5637
+ }
5638
+ /**
5639
+ * A point of image space in the shape's own frame: origin at its centre, axes along its sides.
5640
+ *
5641
+ * @param shape - The shape.
5642
+ * @param p - A point in image coordinates.
5643
+ * @returns The point relative to the shape.
5644
+ */
5645
+ function toShapeFrame(shape, p) {
5646
+ const c = Math.cos(shape.rotation);
5647
+ const s = Math.sin(shape.rotation);
5648
+ const dx = p.x - shape.cx;
5649
+ const dy = p.y - shape.cy;
5650
+ return {
5651
+ x: c * dx + s * dy,
5652
+ y: -s * dx + c * dy
5653
+ };
5654
+ }
5655
+ /**
5656
+ * A point of the shape's own frame in image space; the inverse of `toShapeFrame`.
5657
+ *
5658
+ * @param shape - The shape.
5659
+ * @param p - A point relative to the shape.
5660
+ * @returns The point in image coordinates.
5661
+ */
5662
+ function fromShapeFrame(shape, p) {
5663
+ const c = Math.cos(shape.rotation);
5664
+ const s = Math.sin(shape.rotation);
5665
+ return {
5666
+ x: shape.cx + c * p.x - s * p.y,
5667
+ y: shape.cy + s * p.x + c * p.y
5668
+ };
5669
+ }
5670
+ /** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */
5671
+ function handleDirection(handle) {
5672
+ return {
5673
+ x: handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0,
5674
+ y: handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0
5675
+ };
5676
+ }
5677
+ /**
5678
+ * Where a handle sits: a corner or the middle of a side, turned with the shape.
5679
+ *
5680
+ * @param shape - The shape.
5681
+ * @param handle - The handle, by compass direction in the shape's own frame.
5682
+ * @returns The handle's centre, in image coordinates.
5683
+ */
5684
+ function shapeHandlePoint(shape, handle) {
5685
+ const d = handleDirection(handle);
5686
+ return fromShapeFrame(shape, {
5687
+ x: d.x * shape.width / 2,
5688
+ y: d.y * shape.height / 2
5689
+ });
5690
+ }
5691
+ /**
5692
+ * Where the rotation handle sits: beyond the middle of the top side, along the shape's own
5693
+ * up direction.
5694
+ *
5695
+ * @param shape - The shape.
5696
+ * @param distance - How far past the top side, in image pixels. For a screen-constant handle,
5697
+ * pass `useScreenPx()(css)`.
5698
+ * @returns The handle's centre, in image coordinates.
5699
+ */
5700
+ function rotationHandlePoint(shape, distance) {
5701
+ return fromShapeFrame(shape, {
5702
+ x: 0,
5703
+ y: -shape.height / 2 - distance
5704
+ });
5705
+ }
5706
+ /**
5707
+ * Drag a handle to `to`.
5708
+ *
5709
+ * The dragged side or corner follows the pointer in the shape's own frame and the opposite
5710
+ * side or corner stays where it is in the image, which is what makes a handle feel attached.
5711
+ * The shape does not flip when dragged through the opposite side: it stops at `minSize`.
5712
+ *
5713
+ * @param shape - The shape before the drag.
5714
+ * @param handle - The handle being dragged.
5715
+ * @param to - The pointer, in image coordinates.
5716
+ * @param minSize - The smallest extent on either axis, in image pixels.
5717
+ * @returns The resized shape: the same rotation, and the opposite side or corner unmoved.
5718
+ */
5719
+ function resizeShape(shape, handle, to, minSize) {
5720
+ const d = handleDirection(handle);
5721
+ const u = toShapeFrame(shape, to);
5722
+ let width = shape.width;
5723
+ let height = shape.height;
5724
+ let x = 0;
5725
+ let y = 0;
5726
+ if (d.x !== 0) {
5727
+ width = Math.max(minSize, d.x * u.x + shape.width / 2);
5728
+ x = -d.x * (shape.width / 2) + d.x * width / 2;
5729
+ }
5730
+ if (d.y !== 0) {
5731
+ height = Math.max(minSize, d.y * u.y + shape.height / 2);
5732
+ y = -d.y * (shape.height / 2) + d.y * height / 2;
5733
+ }
5734
+ const centre = fromShapeFrame(shape, {
5735
+ x,
5736
+ y
5737
+ });
5738
+ return {
5739
+ cx: centre.x,
5740
+ cy: centre.y,
5741
+ width,
5742
+ height,
5743
+ rotation: shape.rotation
5744
+ };
5745
+ }
5746
+ /**
5747
+ * Turn the shape about its centre so that its rotation handle points at `to`.
5748
+ *
5749
+ * @param shape - The shape before the drag.
5750
+ * @param to - The pointer, in image coordinates.
5751
+ * @param snap - Round the rotation to a multiple of this many radians (Shift while dragging
5752
+ * rounds to 15°). Defaults to no rounding.
5753
+ * @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.
5754
+ */
5755
+ function rotateShape(shape, to, snap = 0) {
5756
+ let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;
5757
+ if (snap > 0) rotation = Math.round(rotation / snap) * snap;
5758
+ return {
5759
+ ...shape,
5760
+ rotation: normalizeAngle(rotation)
5761
+ };
5762
+ }
5763
+ /**
5764
+ * Move the shape.
5765
+ *
5766
+ * @param shape - The shape.
5767
+ * @param dx - Horizontal shift, in image pixels.
5768
+ * @param dy - Vertical shift, in image pixels.
5769
+ * @returns The moved shape.
5770
+ */
5771
+ function moveShape(shape, dx, dy) {
5772
+ return {
5773
+ ...shape,
5774
+ cx: shape.cx + dx,
5775
+ cy: shape.cy + dy
5776
+ };
5777
+ }
5778
+ /**
5779
+ * An angle as the equivalent one in `(-π, π]`.
5780
+ *
5781
+ * @param angle - Radians.
5782
+ * @returns The angle in `(-π, π]`.
5783
+ */
5784
+ function normalizeAngle(angle) {
5785
+ const turn = 2 * Math.PI;
5786
+ let a = angle % turn;
5787
+ if (a > Math.PI) a -= turn;
5788
+ else if (a <= -Math.PI) a += turn;
5789
+ return a;
5790
+ }
5791
+ /**
5792
+ * The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize
5793
+ * cursors to the handle's direction on screen.
5794
+ *
5795
+ * @param handle - The handle.
5796
+ * @param rotation - The shape's rotation, in radians.
5797
+ * @returns A CSS `cursor` value.
5798
+ */
5799
+ function shapeHandleCursor(handle, rotation) {
5800
+ const d = handleDirection(handle);
5801
+ const half = ((Math.atan2(d.y, d.x) + rotation) % Math.PI + Math.PI) % Math.PI;
5802
+ return [
5803
+ "ew-resize",
5804
+ "nwse-resize",
5805
+ "ns-resize",
5806
+ "nesw-resize"
5807
+ ][Math.round(half / (Math.PI / 4)) % 4];
5808
+ }
5809
+ /**
5810
+ * The shape for a rectangle given as an origin corner, a size and a rotation about that
5811
+ * corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.
5812
+ *
5813
+ * @param corner - The corner the rotation is about, in image coordinates.
5814
+ * @param width - Extent along the rotated x axis.
5815
+ * @param height - Extent along the rotated y axis.
5816
+ * @param rotation - Radians, clockwise on screen.
5817
+ * @returns The same rectangle as a `RotatedShape`.
5818
+ */
5819
+ function shapeFromCorner(corner, width, height, rotation) {
5820
+ const c = Math.cos(rotation);
5821
+ const s = Math.sin(rotation);
5822
+ return {
5823
+ cx: corner.x + (c * width - s * height) / 2,
5824
+ cy: corner.y + (s * width + c * height) / 2,
5825
+ width,
5826
+ height,
5827
+ rotation
5828
+ };
5829
+ }
5830
+ /**
5831
+ * The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;
5832
+ * the inverse of `shapeFromCorner`.
5833
+ *
5834
+ * @param shape - The shape.
5835
+ * @returns The corner, in image coordinates.
5836
+ */
5837
+ function shapeCorner(shape) {
5838
+ return fromShapeFrame(shape, {
5839
+ x: -shape.width / 2,
5840
+ y: -shape.height / 2
5841
+ });
5842
+ }
5843
+ /**
5844
+ * Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).
5845
+ *
5846
+ * @param a - A shape, or `null`.
5847
+ * @param b - A shape, or `null`.
5848
+ * @param epsilon - The tolerance. Defaults to 1e-6.
5849
+ * @returns `true` for two equal shapes, or two `null`s.
5850
+ */
5851
+ function sameShape(a, b, epsilon = 1e-6) {
5852
+ if (a === null || b === null) return a === b;
5853
+ return Math.abs(a.cx - b.cx) < epsilon && Math.abs(a.cy - b.cy) < epsilon && Math.abs(a.width - b.width) < epsilon && Math.abs(a.height - b.height) < epsilon && Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon;
5854
+ }
5855
+ /**
5856
+ * How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is
5857
+ * a first-order estimate, which is exact on the axes and good to a few percent elsewhere.
5858
+ */
5859
+ function distanceOutside(shape, kind, p) {
5860
+ const u = toShapeFrame(shape, p);
5861
+ const a = Math.max(shape.width / 2, 1e-9);
5862
+ const b = Math.max(shape.height / 2, 1e-9);
5863
+ if (kind === "rect") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));
5864
+ const f = (u.x / a) ** 2 + (u.y / b) ** 2;
5865
+ if (f <= 1) return 0;
5866
+ const g = Math.hypot(u.x / (a * a), u.y / (b * b));
5867
+ return (f - Math.sqrt(f)) / g;
5868
+ }
5869
+ /**
5870
+ * What a press on an editable shape means, decided once for the whole editor so that a small
5871
+ * shape's interior never steals a press meant for its handle.
5872
+ *
5873
+ * In order:
5874
+ * 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen
5875
+ * distance from the press is within `radius` plus the handle's half size: resize or rotate.
5876
+ * 2. Inside the shape, or within `radius` screen pixels of its outline: move.
5877
+ * 3. Otherwise `null`: the press is declined and belongs to whatever is below.
5878
+ *
5879
+ * @param shape - The shape.
5880
+ * @param kind - `"rect"` or `"ellipse"` (the outline differs).
5881
+ * @param scale - The view scale: screen pixels per image pixel.
5882
+ * @param point - The press, in image coordinates.
5883
+ * @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.
5884
+ * @param rotatable - Whether the rotation handle exists. Defaults to `true`.
5885
+ * @returns The decision, or `null`.
5886
+ */
5887
+ function shapePress(shape, kind, scale, point, radius, rotatable = true) {
5888
+ const best = {
5889
+ press: null,
5890
+ distance: Infinity
5891
+ };
5892
+ const consider = (candidate, at, half) => {
5893
+ const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;
5894
+ if (d <= radius + half && d < best.distance) {
5895
+ best.press = candidate;
5896
+ best.distance = d;
5897
+ }
5898
+ };
5899
+ for (const handle of ROI_HANDLES) consider({
5900
+ kind: "resize",
5901
+ handle
5902
+ }, shapeHandlePoint(shape, handle), 9 / 2);
5903
+ if (rotatable) consider({ kind: "rotate" }, rotationHandlePoint(shape, 24 / scale), 5);
5904
+ if (best.press) return best.press;
5905
+ return distanceOutside(shape, kind, point) * scale <= radius ? { kind: "move" } : null;
5906
+ }
5907
+ //#endregion
5908
+ //#region src/components/stage/useCoarsePointer.ts
5909
+ /**
5910
+ * Whether the device's primary pointer is coarse (a finger), for sizing a press target that
5911
+ * must exist before any pointer event says which pointer is coming.
5912
+ */
5913
+ const QUERY = "(pointer: coarse)";
5914
+ function mediaList() {
5915
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(QUERY) : null;
5916
+ }
5917
+ function subscribe(onChange) {
5918
+ const list = mediaList();
5919
+ list?.addEventListener("change", onChange);
5920
+ return () => list?.removeEventListener("change", onChange);
5921
+ }
5922
+ const snapshot = () => mediaList()?.matches ?? false;
5923
+ /**
5924
+ * Whether `(pointer: coarse)` matches: the primary pointer is a finger. `false` on the server
5925
+ * and wherever `matchMedia` is missing.
5926
+ *
5927
+ * @returns `true` on a touch-first device.
5928
+ */
5929
+ function useCoarsePointer() {
5930
+ return useSyncExternalStore(subscribe, snapshot, () => false);
5931
+ }
5932
+ //#endregion
5933
+ //#region src/components/ShapeEditor.tsx
5934
+ /**
5935
+ * A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own
5936
+ * frame, and turned from a rotation handle, on the image.
5937
+ *
5938
+ * The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which
5939
+ * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
5940
+ * this is the gestures, the handles and the keyboard.
5941
+ */
5942
+ /** Outline width, in screen pixels. */
5943
+ const STROKE_PX$1 = 1.5;
5944
+ /** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
5945
+ const SNAP = Math.PI / 12;
5946
+ const KEY_TURN = Math.PI / 180;
5947
+ const HALO$1 = overlayRole("halo");
5948
+ /**
5949
+ * An editable rotated rectangle or ellipse inside an `ImageStage`.
5950
+ *
5951
+ * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
5952
+ * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
5953
+ * `minSize` rather than flipping. The interior moves it, and so does the band along its
5954
+ * outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin
5955
+ * or rotated shape is grabbed. The band is as wide as the device's primary pointer needs
5956
+ * (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to
5957
+ * 12 px outside the outline reaches the layers below instead of the editor.
5958
+ * - **Press order.** One decision serves every part of the editor: the nearest handle first,
5959
+ * then the interior or outline band (move), then nothing. A small shape's interior does not
5960
+ * steal a press meant for a handle, and a press that hits none of them is not claimed, so
5961
+ * it reaches whatever is below, or the stage.
5962
+ * - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit
5963
+ * cancels it (the shape reverts, nothing is committed) and is left to the stage.
5964
+ * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
5965
+ * round to 15°.
5966
+ * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
5967
+ * with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`
5968
+ * turn it by 1° (15° with Shift).
5969
+ * - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an
5970
+ * ellipse also shows its bounding box, where the handles are.
5971
+ * - **Panning.** A press with the hand tool, or with space held, still pans.
5972
+ *
5973
+ * It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does
5974
+ * not keep the shape inside the image.
5975
+ *
5976
+ * The SVG carries `data-editable`; the outline carries `data-shape`.
5977
+ */
5978
+ function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, rotatable = true, minSize = 5, label = "Shape", stroke = overlayRole("selection") }) {
5979
+ const stage = useStage();
5980
+ const px = useScreenPx();
5981
+ const coarse = useCoarsePointer();
5982
+ const dragRef = useRef(null);
5983
+ const lastRef = useRef(null);
5984
+ const stopWatchRef = useRef(null);
5985
+ const report = (next) => {
5986
+ lastRef.current = next;
5987
+ onValueChange(next);
5988
+ };
5989
+ /** Abandon an edit in flight: the shape reverts and nothing is committed. */
5990
+ const cancelEdit = () => {
5991
+ const drag = dragRef.current;
5992
+ dragRef.current = null;
5993
+ stopWatchRef.current?.();
5994
+ stopWatchRef.current = null;
5995
+ if (drag && lastRef.current) onValueChange(drag.start);
5996
+ lastRef.current = null;
5997
+ };
5998
+ useEffect(() => () => stopWatchRef.current?.(), []);
5999
+ /**
6000
+ * The one press decision for the whole editor: every target (the interior, the outline
6001
+ * band, a handle) comes here, and the nearest handle wins over the interior. A declined
6002
+ * press is not claimed and bubbles to the stage.
6003
+ */
6004
+ const press = (event) => {
6005
+ if (!value || stage.panMode) return;
6006
+ const touch = event.pointerType === "touch";
6007
+ if (!touch && event.button !== 0) return;
6008
+ if (dragRef.current) {
6009
+ if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();
6010
+ return;
6011
+ }
6012
+ const at = stage.toImage({
6013
+ x: event.clientX,
6014
+ y: event.clientY
6015
+ });
6016
+ const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);
6017
+ if (!decision) return;
6018
+ event.stopPropagation();
6019
+ event.preventDefault();
6020
+ try {
6021
+ event.currentTarget.setPointerCapture(event.pointerId);
6022
+ } catch {}
6023
+ const base = {
6024
+ start: value,
6025
+ moved: false,
6026
+ pointerId: event.pointerId
6027
+ };
6028
+ dragRef.current = decision.kind === "move" ? {
6029
+ ...base,
6030
+ kind: "move",
6031
+ from: at
6032
+ } : decision.kind === "resize" ? {
6033
+ ...base,
6034
+ kind: "resize",
6035
+ handle: decision.handle
6036
+ } : {
6037
+ ...base,
6038
+ kind: "rotate"
6039
+ };
6040
+ lastRef.current = null;
6041
+ if (touch) {
6042
+ const id = event.pointerId;
6043
+ const other = (e) => {
6044
+ if (e.pointerId !== id && e.pointerType === "touch") cancelEdit();
6045
+ };
6046
+ window.addEventListener("pointerdown", other);
6047
+ stopWatchRef.current = () => window.removeEventListener("pointerdown", other);
6048
+ }
6049
+ };
6050
+ const onMove = (event) => {
6051
+ const drag = dragRef.current;
6052
+ if (!drag || drag.pointerId !== event.pointerId) return;
6053
+ event.stopPropagation();
6054
+ const p = stage.toImage({
6055
+ x: event.clientX,
6056
+ y: event.clientY
6057
+ });
6058
+ drag.moved = true;
6059
+ if (drag.kind === "move") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));
6060
+ else if (drag.kind === "resize") report(resizeShape(drag.start, drag.handle, p, minSize));
6061
+ else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));
6062
+ };
6063
+ const onEnd = (event) => {
6064
+ const drag = dragRef.current;
6065
+ if (!drag || drag.pointerId !== event.pointerId) return;
6066
+ event.stopPropagation();
6067
+ dragRef.current = null;
6068
+ stopWatchRef.current?.();
6069
+ stopWatchRef.current = null;
6070
+ if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
6071
+ };
6072
+ /** The handlers every target of the editor shares. */
6073
+ const gesture = {
6074
+ onPointerDown: press,
6075
+ onPointerMove: onMove,
6076
+ onPointerUp: onEnd,
6077
+ onPointerCancel: (event) => {
6078
+ if (dragRef.current?.pointerId === event.pointerId) cancelEdit();
6079
+ },
6080
+ onLostPointerCapture: onEnd,
6081
+ onDoubleClick: (event) => event.stopPropagation()
6082
+ };
6083
+ const onKeyDown = (event) => {
6084
+ if (!editable || value === null) return;
6085
+ if (rotatable && (event.key === "[" || event.key === "]")) {
6086
+ event.preventDefault();
6087
+ event.stopPropagation();
6088
+ const angle = (event.key === "]" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);
6089
+ const next = {
6090
+ ...value,
6091
+ rotation: value.rotation + angle
6092
+ };
6093
+ onValueChange(next);
6094
+ onCommit?.(next);
6095
+ return;
6096
+ }
6097
+ const step = event.shiftKey ? 10 : 1;
6098
+ const d = {
6099
+ ArrowLeft: {
6100
+ x: -step,
6101
+ y: 0
6102
+ },
6103
+ ArrowRight: {
6104
+ x: step,
6105
+ y: 0
6106
+ },
6107
+ ArrowUp: {
6108
+ x: 0,
6109
+ y: -step
6110
+ },
6111
+ ArrowDown: {
6112
+ x: 0,
6113
+ y: step
6114
+ }
6115
+ }[event.key];
6116
+ if (!d) return;
6117
+ event.preventDefault();
6118
+ event.stopPropagation();
6119
+ const next = event.altKey ? resizeShape(value, "se", fromShapeFrame(value, {
6120
+ x: value.width / 2 + d.x,
6121
+ y: value.height / 2 + d.y
6122
+ }), minSize) : moveShape(value, d.x, d.y);
6123
+ onValueChange(next);
6124
+ onCommit?.(next);
6125
+ };
6126
+ const stem = value ? {
6127
+ from: shapeHandlePoint(value, "n"),
6128
+ to: rotationHandlePoint(value, px(24))
6129
+ } : null;
6130
+ const handleSize = px(9);
6131
+ return /* @__PURE__ */ jsxs("svg", {
6132
+ viewBox: imageViewBox(stage.image),
6133
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
6134
+ "data-editable": editable ? "" : void 0,
6135
+ children: [
6136
+ value && /* @__PURE__ */ jsx(Outline, {
6137
+ kind,
6138
+ shape: value,
6139
+ fill: "none",
6140
+ stroke: HALO$1,
6141
+ strokeWidth: px(3.5)
6142
+ }),
6143
+ value && /* @__PURE__ */ jsx(Outline, {
6144
+ kind,
6145
+ shape: value,
6146
+ "data-shape": kind,
6147
+ fill: stroke,
6148
+ fillOpacity: .12,
6149
+ stroke,
6150
+ strokeWidth: px(STROKE_PX$1)
6151
+ }),
6152
+ kind === "ellipse" && value && /* @__PURE__ */ jsx("rect", {
6153
+ x: value.cx - value.width / 2,
6154
+ y: value.cy - value.height / 2,
6155
+ width: value.width,
6156
+ height: value.height,
6157
+ transform: turned(value),
6158
+ fill: "none",
6159
+ stroke,
6160
+ strokeWidth: px(1),
6161
+ strokeDasharray: `${px(4)} ${px(3)}`,
6162
+ opacity: .6
6163
+ }),
6164
+ editable && value && /* @__PURE__ */ jsx(Outline, {
6165
+ kind,
6166
+ shape: value,
6167
+ "data-shape-band": "",
6168
+ fill: "none",
6169
+ stroke: "transparent",
6170
+ strokeWidth: px(2 * (coarse ? 12 : 6)),
6171
+ strokeLinejoin: "round",
6172
+ "aria-hidden": true,
6173
+ className: "pointer-events-auto cursor-move",
6174
+ style: { pointerEvents: "stroke" },
6175
+ ...gesture
6176
+ }),
6177
+ editable && value && /* @__PURE__ */ jsx(Outline, {
6178
+ kind,
6179
+ shape: value,
6180
+ fill: "transparent",
6181
+ role: "button",
6182
+ tabIndex: 0,
6183
+ "aria-label": `${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt(value.rotation * 180 / Math.PI)}°`,
6184
+ "aria-roledescription": kind === "rect" ? "rotated rectangle" : "ellipse",
6185
+ className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
6186
+ strokeWidth: px(2),
6187
+ ...gesture,
6188
+ onKeyDown
6189
+ }),
6190
+ editable && value && rotatable && stem && /* @__PURE__ */ jsxs(Fragment, { children: [
6191
+ /* @__PURE__ */ jsx("line", {
6192
+ x1: stem.from.x,
6193
+ y1: stem.from.y,
6194
+ x2: stem.to.x,
6195
+ y2: stem.to.y,
6196
+ stroke: HALO$1,
6197
+ strokeWidth: px(3)
6198
+ }),
6199
+ /* @__PURE__ */ jsx("line", {
6200
+ x1: stem.from.x,
6201
+ y1: stem.from.y,
6202
+ x2: stem.to.x,
6203
+ y2: stem.to.y,
6204
+ stroke,
6205
+ strokeWidth: px(1)
6206
+ }),
6207
+ /* @__PURE__ */ jsx("circle", {
6208
+ "data-handle": "rotate",
6209
+ cx: stem.to.x,
6210
+ cy: stem.to.y,
6211
+ r: px(5),
6212
+ fill: stroke,
6213
+ stroke: HALO$1,
6214
+ strokeWidth: px(1),
6215
+ className: "pointer-events-auto",
6216
+ style: { cursor: "grab" },
6217
+ ...gesture
6218
+ })
6219
+ ] }),
6220
+ editable && value && ROI_HANDLES.map((handle) => {
6221
+ const centre = shapeHandlePoint(value, handle);
6222
+ return /* @__PURE__ */ jsx("rect", {
6223
+ "data-handle": handle,
6224
+ x: centre.x - handleSize / 2,
6225
+ y: centre.y - handleSize / 2,
6226
+ width: handleSize,
6227
+ height: handleSize,
6228
+ fill: stroke,
6229
+ stroke: HALO$1,
6230
+ strokeWidth: px(1),
6231
+ className: "pointer-events-auto",
6232
+ style: { cursor: shapeHandleCursor(handle, value.rotation) },
6233
+ ...gesture
6234
+ }, handle);
6235
+ })
6236
+ ]
6237
+ });
6238
+ }
6239
+ /** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */
6240
+ function Outline({ kind, shape, ...rest }) {
6241
+ const transform = turned(shape);
6242
+ return kind === "rect" ? /* @__PURE__ */ jsx("rect", {
6243
+ x: shape.cx - shape.width / 2,
6244
+ y: shape.cy - shape.height / 2,
6245
+ width: shape.width,
6246
+ height: shape.height,
6247
+ transform,
6248
+ ...rest
6249
+ }) : /* @__PURE__ */ jsx("ellipse", {
6250
+ cx: shape.cx,
6251
+ cy: shape.cy,
6252
+ rx: shape.width / 2,
6253
+ ry: shape.height / 2,
6254
+ transform,
6255
+ ...rest
6256
+ });
6257
+ }
6258
+ /** The SVG transform that turns a shape drawn level about its centre. */
6259
+ function turned(shape) {
6260
+ return `rotate(${shape.rotation * 180 / Math.PI} ${shape.cx} ${shape.cy})`;
6261
+ }
6262
+ function fmt(value) {
6263
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
6264
+ }
6265
+ //#endregion
6266
+ //#region src/components/DraftShape.tsx
6267
+ /**
6268
+ * What an annotation tool shows while a shape is being drawn: a dashed preview of the
6269
+ * point, line, polyline, polygon, rectangle or ellipse so far, and the rubber band of a
6270
+ * multi-select.
6271
+ *
6272
+ * Both draw from state the app's tool keeps; neither takes input. The tool decides what a
6273
+ * press means (`StageSurface` and `useStageHitTest`); these only make it visible.
6274
+ */
6275
+ const HALO = overlayRole("halo");
6276
+ /** Dash, gap, outline width and vertex dot size, in screen pixels. */
6277
+ const DASH = 6;
6278
+ const GAP = 4;
6279
+ const STROKE_PX = 1.5;
6280
+ const VERTEX_PX = 6;
6281
+ /**
6282
+ * A dashed preview of a shape being drawn, inside an `ImageStage`.
6283
+ *
6284
+ * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by
6285
+ * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline
6286
+ * or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also
6287
+ * shows, fainter, the segment that would close it. It takes no pointer events and is hidden
6288
+ * from assistive technology: it is transient feedback for a gesture.
6289
+ *
6290
+ * The SVG carries `data-draft` (the shape's kind).
6291
+ */
6292
+ function DraftShape({ shape, role = "selection", halo = true }) {
6293
+ const stage = useStage();
6294
+ const px = useScreenPx();
6295
+ const colour = overlayRole(role);
6296
+ const dash = `${px(DASH)} ${px(GAP)}`;
6297
+ const width = px(STROKE_PX);
6298
+ const parts = shape ? draftParts(shape, px(1)) : null;
6299
+ return /* @__PURE__ */ jsx("svg", {
6300
+ viewBox: imageViewBox(stage.image),
6301
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
6302
+ "aria-hidden": true,
6303
+ "data-draft": shape?.kind,
6304
+ children: parts && /* @__PURE__ */ jsxs("g", {
6305
+ fill: "none",
6306
+ strokeLinecap: "round",
6307
+ strokeLinejoin: "round",
6308
+ children: [
6309
+ parts.outline && halo && /* @__PURE__ */ jsx("path", {
6310
+ d: parts.outline,
6311
+ stroke: HALO,
6312
+ strokeWidth: width + px(2),
6313
+ opacity: .6
6314
+ }),
6315
+ parts.outline && parts.region && /* @__PURE__ */ jsx("path", {
6316
+ d: parts.outline,
6317
+ fill: colour,
6318
+ fillOpacity: .12,
6319
+ stroke: "none"
6320
+ }),
6321
+ parts.outline && /* @__PURE__ */ jsx("path", {
6322
+ "data-draft-outline": "",
6323
+ d: parts.outline,
6324
+ stroke: colour,
6325
+ strokeWidth: width,
6326
+ strokeDasharray: dash
6327
+ }),
6328
+ parts.closing && /* @__PURE__ */ jsx("path", {
6329
+ "data-draft-closing": "",
6330
+ d: parts.closing,
6331
+ stroke: colour,
6332
+ strokeWidth: px(1),
6333
+ strokeDasharray: dash,
6334
+ opacity: .5
6335
+ }),
6336
+ parts.vertices && /* @__PURE__ */ jsx("path", {
6337
+ "data-draft-vertices": "",
6338
+ d: parts.vertices,
6339
+ stroke: colour,
6340
+ strokeWidth: px(VERTEX_PX)
6341
+ })
6342
+ ]
6343
+ })
6344
+ });
6345
+ }
6346
+ /** An ellipse with the given centre and radii as two arcs. */
6347
+ function ellipsePath$1(cx, cy, rx, ry) {
6348
+ return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
6349
+ }
6350
+ function draftParts(shape, unit) {
6351
+ switch (shape.kind) {
6352
+ case "point": return {
6353
+ outline: ellipsePath$1(shape.x, shape.y, 8 * unit, 8 * unit),
6354
+ region: false,
6355
+ closing: null,
6356
+ vertices: `M${shape.x} ${shape.y}h0`
6357
+ };
6358
+ case "line": return {
6359
+ outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`,
6360
+ region: false,
6361
+ closing: null,
6362
+ vertices: null
6363
+ };
6364
+ case "rect":
6365
+ case "ellipse": {
6366
+ const box = rectFromCorners(shape.from, shape.to);
6367
+ return {
6368
+ outline: shape.kind === "rect" ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z` : ellipsePath$1(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2),
6369
+ region: true,
6370
+ closing: null,
6371
+ vertices: null
6372
+ };
6373
+ }
6374
+ case "polyline":
6375
+ case "polygon": {
6376
+ const n = Math.floor(shape.points.length / 2);
6377
+ if (n === 0) return {
6378
+ outline: null,
6379
+ region: false,
6380
+ closing: null,
6381
+ vertices: null
6382
+ };
6383
+ let outline = "";
6384
+ let vertices = "";
6385
+ for (let i = 0; i < n; i++) {
6386
+ outline += `${i === 0 ? "M" : "L"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;
6387
+ vertices += `M${shape.points[2 * i]} ${shape.points[2 * i + 1]}h0`;
6388
+ }
6389
+ if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;
6390
+ const polygon = shape.kind === "polygon";
6391
+ return {
6392
+ outline,
6393
+ region: polygon && n + (shape.cursor ? 1 : 0) >= 3,
6394
+ closing: polygon && shape.cursor ? `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}` : null,
6395
+ vertices
6396
+ };
6397
+ }
6398
+ }
6399
+ }
6400
+ /**
6401
+ * The rubber band of a multi-select, inside an `ImageStage`: the 12 % fill and a 1 screen px
6402
+ * outline in the selection colour, the same as `PolylineSet`'s own band. Feed it the box
6403
+ * between the press and the pointer from `StageSurface`, and the box to `pointsInRect`,
6404
+ * `polylinesInRect` or `areasInRect` at the release. It takes no pointer events.
6405
+ *
6406
+ * The SVG carries `data-marquee`.
6407
+ */
6408
+ function MarqueeRect({ rect, stroke = overlayRole("selection") }) {
6409
+ const stage = useStage();
6410
+ const px = useScreenPx();
6411
+ return /* @__PURE__ */ jsx("svg", {
6412
+ viewBox: imageViewBox(stage.image),
6413
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
6414
+ "aria-hidden": true,
6415
+ "data-marquee": rect ? "" : void 0,
6416
+ children: rect && /* @__PURE__ */ jsx("rect", {
6417
+ x: rect.x,
6418
+ y: rect.y,
6419
+ width: rect.width,
6420
+ height: rect.height,
6421
+ fill: stroke,
6422
+ fillOpacity: .12,
6423
+ stroke,
6424
+ strokeWidth: px(1)
6425
+ })
6426
+ });
6427
+ }
6428
+ //#endregion
6429
+ //#region src/components/useShapeDrag.ts
6430
+ /**
6431
+ * Moving a manual shape: a press on a selected item becomes image-space displacements, with the
6432
+ * click-slop handling every selection UI needs (a press that barely moves is a click, not a
6433
+ * drag).
6434
+ *
6435
+ * The layers resolve what is under the pointer (`onItemPress`); this turns the press that
6436
+ * follows into a move. The app keeps the item's geometry, shows the displaced copy while the
6437
+ * drag is in flight, and commits it at the end:
6438
+ *
6439
+ * <AreaSet items={items} selectedIds={selected}
6440
+ * onItemPress={(id, event) => {
6441
+ * if (!selected.has(id)) return select(id);
6442
+ * startMove(event, {
6443
+ * onMove: setOffset, // preview: draw the item shifted
6444
+ * onEnd: (delta, moved) => moved ? commit(id, delta) : select(id),
6445
+ * onCancel: () => setOffset(null),
6446
+ * });
6447
+ * }} />
6448
+ */
6449
+ /** The default click slop, in screen pixels (the stage's own). */
6450
+ const DEFAULT_SLOP = 3;
6451
+ /**
6452
+ * Start moving a shape from a press, inside an `ImageStage`.
6453
+ *
6454
+ * Returns `start(event, handlers, options?)`. Call it from `onItemPress` of a layer with the
6455
+ * press event: the press is claimed, so the stage does not pan, and the pointer is followed on
6456
+ * `window` until it is released, whether or not it leaves the canvas. A touch tap reaches
6457
+ * `onItemPress` on release, so there is nothing to follow: it ends at once as a click
6458
+ * (`moved` false). Move a shape on touch with `ShapeEditor`'s handles or the app's own mode.
6459
+ *
6460
+ * @returns `start`.
6461
+ */
6462
+ function useShapeDrag() {
6463
+ const { toImage } = useStage();
6464
+ const startDrag = useStageDrag();
6465
+ return useCallback((event, handlers, options) => {
6466
+ if (event.type !== "pointerdown") {
6467
+ handlers.onEnd?.({
6468
+ x: 0,
6469
+ y: 0
6470
+ }, false, event.nativeEvent);
6471
+ return;
6472
+ }
6473
+ const slop = options?.slop ?? DEFAULT_SLOP;
6474
+ const from = {
6475
+ x: event.clientX,
6476
+ y: event.clientY
6477
+ };
6478
+ const press = toImage(from);
6479
+ const displacement = (point) => ({
6480
+ x: point.x - press.x,
6481
+ y: point.y - press.y
6482
+ });
6483
+ let moved = false;
6484
+ startDrag(event, {
6485
+ onMove: (point, e) => {
6486
+ if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= slop) return;
6487
+ moved = true;
6488
+ handlers.onMove?.(displacement(point), e);
6489
+ },
6490
+ onEnd: (point, e) => handlers.onEnd?.(moved ? displacement(point) : {
6491
+ x: 0,
6492
+ y: 0
6493
+ }, moved, e),
6494
+ onCancel: handlers.onCancel
6495
+ });
6496
+ }, [toImage, startDrag]);
6497
+ }
6498
+ /**
6499
+ * Move flat points by a displacement.
6500
+ *
6501
+ * @param points - `[x0, y0, x1, y1, …]`.
6502
+ * @param delta - The displacement, in the points' units.
6503
+ * @returns A new array, `points` shifted.
6504
+ */
6505
+ function translatePoints(points, delta) {
6506
+ const out = new Array(points.length);
6507
+ for (let i = 0; i < points.length; i++) out[i] = points[i] + (i % 2 === 0 ? delta.x : delta.y);
6508
+ return out;
6509
+ }
6510
+ //#endregion
3992
6511
  //#region src/components/MaskEditor.tsx
3993
6512
  /** A source-pixel raster mask layer with a small paint/erase brush. */
3994
6513
  /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
@@ -4165,6 +6684,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
4165
6684
  })] });
4166
6685
  }
4167
6686
  //#endregion
4168
- export { ContourEditor, FULL_TIER_ZOOM, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, 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, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, moveRect, nativeZoomFor, nearestContourSegment, nearestPoint, nearestPolyline, overlayRole, paintMask, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rectFromCorners, resizeRect, roiHandlePoint, rotatePoint, sameRect, scaleRange, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, useScreenPx, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
6687
+ export { AreaSet, ContourEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestPoint, nearestPolyline, normalizeAngle, overlayRole, paintMask, planeRange, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
4169
6688
 
4170
6689
  //# sourceMappingURL=index.js.map