@vitavision/stage2d 0.8.0 → 0.9.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, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
1
+ import { createContext, use, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } 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";
@@ -215,6 +215,151 @@ function formatScale(scale) {
215
215
  function clamp$2(value, low, high) {
216
216
  return Math.min(high, Math.max(low, value));
217
217
  }
218
+ const BUTTON_CODE = {
219
+ left: 0,
220
+ middle: 1,
221
+ right: 2
222
+ };
223
+ /**
224
+ * The `PointerEvent.button` codes a `panButton` prop names.
225
+ *
226
+ * @param panButton - One button or a list; omitted means left and middle, the stage's
227
+ * long-standing default.
228
+ * @returns The codes: 0 left, 1 middle, 2 right.
229
+ */
230
+ function panButtonCodes(panButton) {
231
+ if (panButton === void 0) return /* @__PURE__ */ new Set([0, 1]);
232
+ return new Set((typeof panButton === "string" ? [panButton] : panButton).map((button) => BUTTON_CODE[button]));
233
+ }
234
+ /**
235
+ * The midpoint of two points.
236
+ *
237
+ * @param a - One point.
238
+ * @param b - The other.
239
+ * @returns Their centroid.
240
+ */
241
+ function centroid(a, b) {
242
+ return {
243
+ x: (a.x + b.x) / 2,
244
+ y: (a.y + b.y) / 2
245
+ };
246
+ }
247
+ /**
248
+ * The view a pinch has reached: scaled by how much the fingers spread, and carried by how
249
+ * far their midpoint moved. The image point under the fingers' first midpoint stays under
250
+ * their current one, so the gesture reads as holding the picture with two fingers.
251
+ *
252
+ * @param start - The view when the second finger went down.
253
+ * @param startDistance - The fingers' distance then.
254
+ * @param startCentre - Their midpoint then.
255
+ * @param distance - Their distance now.
256
+ * @param centre - Their midpoint now.
257
+ * @param range - The `[min, max]` scale to stay within.
258
+ * @returns The view; not yet clamped to the legal pan range.
259
+ */
260
+ function pinchView(start, startDistance, startCentre, distance, centre, range) {
261
+ const ratio = startDistance > 0 ? distance / startDistance : 1;
262
+ const zoomed = zoomAbout(start, Math.min(range[1], Math.max(range[0], start.scale * ratio)), startCentre);
263
+ return {
264
+ scale: zoomed.scale,
265
+ tx: zoomed.tx + centre.x - startCentre.x,
266
+ ty: zoomed.ty + centre.y - startCentre.y
267
+ };
268
+ }
269
+ /**
270
+ * Whether a touch that has ended was a tap.
271
+ *
272
+ * @param travel - The farthest it strayed from where it began, in CSS pixels.
273
+ * @param elapsed - How long it lasted, in milliseconds.
274
+ * @returns `true` for a short touch that stayed put.
275
+ */
276
+ function isTap(travel, elapsed) {
277
+ return travel <= 3 && elapsed <= 500;
278
+ }
279
+ //#endregion
280
+ //#region src/components/stage/hitContext.ts
281
+ /**
282
+ * The context an `ImageStage` provides its layers' hit registry through. Its own module so
283
+ * that `ImageStage` (which provides it) and `useStageHitTest` (which reads it, and reads
284
+ * `useStage` from `ImageStage`) do not import each other.
285
+ */
286
+ /** The enclosing stage's registry, or `null` outside a stage. */
287
+ const StageHitContext = createContext(null);
288
+ //#endregion
289
+ //#region src/components/stage/hitTest.ts
290
+ /** What a layer is picked as, and so how it ranks against the layers around it. */
291
+ const STAGE_HIT_PRIORITY = {
292
+ /** A raster layer: only picked when nothing else is. */
293
+ image: 0,
294
+ /** A filled region or heatmap cell. */
295
+ area: 100,
296
+ /** A line or contour. */
297
+ line: 200,
298
+ /** A marker: small, so it wins over what it sits on. */
299
+ point: 300
300
+ };
301
+ /**
302
+ * Order two hits, best first.
303
+ *
304
+ * @returns Negative when `a` ranks above `b`.
305
+ */
306
+ function compareHits(a, b) {
307
+ if (a.priority !== b.priority) return b.priority - a.priority;
308
+ if (a.dist !== b.dist) return a.dist - b.dist;
309
+ return a.layerId < b.layerId ? -1 : a.layerId > b.layerId ? 1 : 0;
310
+ }
311
+ /** Make an empty registry. */
312
+ function createHitRegistry() {
313
+ const layers = /* @__PURE__ */ new Set();
314
+ let hovered = null;
315
+ const answers = (point, radius, options) => {
316
+ const out = [];
317
+ for (const layer of layers) {
318
+ if (options?.pressable && layer.pressable !== true) continue;
319
+ const found = layer.pick(point, radius);
320
+ if (found) out.push({
321
+ hit: {
322
+ id: found.id,
323
+ dist: found.dist,
324
+ layerId: layer.id,
325
+ priority: layer.priority
326
+ },
327
+ layer
328
+ });
329
+ }
330
+ return out.sort((a, b) => compareHits(a.hit, b.hit));
331
+ };
332
+ const setHover = (next) => {
333
+ const previous = hovered;
334
+ if (previous?.layer === next?.layer && previous?.id === next?.id) return;
335
+ hovered = next;
336
+ if (previous && previous.layer !== next?.layer) previous.layer.hover?.(null);
337
+ next?.layer.hover?.(next.id);
338
+ };
339
+ return {
340
+ register(layer) {
341
+ layers.add(layer);
342
+ return () => {
343
+ layers.delete(layer);
344
+ if (hovered?.layer === layer) hovered = null;
345
+ };
346
+ },
347
+ hitTestAll: (point, radius, options) => answers(point, radius, options).map((a) => a.hit),
348
+ hitTest: (point, radius, options) => answers(point, radius, options)[0]?.hit ?? null,
349
+ routeHover(point, radius) {
350
+ const best = answers(point, radius).find((a) => a.layer.hover !== void 0);
351
+ setHover(best ? {
352
+ layer: best.layer,
353
+ id: best.hit.id
354
+ } : null);
355
+ },
356
+ clearHover: () => setHover(null),
357
+ routePress(point, radius, event) {
358
+ for (const { hit, layer } of answers(point, radius, { pressable: true })) if (layer.press?.(hit.id, event) !== false) return true;
359
+ return false;
360
+ }
361
+ };
362
+ }
218
363
  //#endregion
219
364
  //#region src/components/stage/ImageStage.tsx
220
365
  /**
@@ -246,6 +391,9 @@ function clamp$2(value, low, high) {
246
391
  const WHEEL_SENSITIVITY = .0015;
247
392
  /** How far a press may travel and still count as a click rather than a pan. */
248
393
  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;
249
397
  /** The view before the viewport has been measured — nothing is on screen yet. */
250
398
  const UNMEASURED_VIEW = {
251
399
  scale: 1,
@@ -273,7 +421,7 @@ function useStage() {
273
421
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
274
422
  * or absent.
275
423
  */
276
- function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas", initialView: opening = "auto", ref }) {
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 }) {
277
425
  const viewportRef = useRef(null);
278
426
  const [box, setBox] = useState({
279
427
  width: 0,
@@ -307,6 +455,13 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
307
455
  /** The view to come back to when a double-click leaves fit. */
308
456
  const previousRef = useRef(null);
309
457
  const dragRef = useRef(null);
458
+ /** The touches down now, by pointer id, in client coordinates. */
459
+ const touchesRef = useRef(/* @__PURE__ */ new Map());
460
+ /** The two-finger gesture in progress, from the moment the second finger went down. */
461
+ const pinchRef = useRef(null);
462
+ /** The registry the stage's layers answer hit-tests through. */
463
+ const [hits] = useState(() => createHitRegistry());
464
+ const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
310
465
  const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW), [
311
466
  view,
312
467
  box,
@@ -470,23 +625,50 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
470
625
  panning,
471
626
  panMode
472
627
  ]);
628
+ /** 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);
630
+ /** Offer a press to the items under it, topmost first; whether one claimed it. */
631
+ const routePress = (event) => hits.routePress(clientToImage({
632
+ x: event.clientX,
633
+ y: event.clientY
634
+ }), hitRadius(event), event);
473
635
  const onPointerDown = (event) => {
474
- if (event.button !== 0 && event.button !== 1) return;
636
+ if (event.pointerType === "touch") {
637
+ touchDown(event);
638
+ return;
639
+ }
640
+ const primary = event.button === 0;
641
+ if (primary && !panMode && routePress(event)) return;
642
+ const pan = panButtons.has(event.button) || primary && panMode;
643
+ if (!pan && !primary) return;
475
644
  event.preventDefault();
476
645
  dragRef.current = {
477
646
  x: event.clientX,
478
647
  y: event.clientY,
479
648
  tx: effective.tx,
480
649
  ty: effective.ty,
481
- moved: false
650
+ moved: false,
651
+ pan,
652
+ touch: false,
653
+ at: event.timeStamp,
654
+ pointerId: event.pointerId
482
655
  };
483
- setPanning(true);
656
+ if (pan) setPanning(true);
484
657
  event.currentTarget.setPointerCapture(event.pointerId);
485
658
  };
486
659
  const onPointerMove = (event) => {
660
+ if (event.pointerType === "touch") {
661
+ touchMove(event);
662
+ return;
663
+ }
487
664
  const origin = dragRef.current;
488
- if (!origin) {
665
+ if (!origin?.pan) {
489
666
  onHover?.(hoverPoint(event, viewportRef.current, effective, image));
667
+ hits.routeHover(clientToImage({
668
+ x: event.clientX,
669
+ y: event.clientY
670
+ }), hitRadius(event));
671
+ if (origin && !origin.moved && Math.hypot(event.clientX - origin.x, event.clientY - origin.y) > CLICK_SLOP$1) origin.moved = true;
490
672
  return;
491
673
  }
492
674
  const dx = event.clientX - origin.x;
@@ -494,6 +676,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
494
676
  if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP$1) return;
495
677
  origin.moved = true;
496
678
  onHover?.(null);
679
+ hits.clearHover();
497
680
  commit({
498
681
  scale: effective.scale,
499
682
  tx: origin.tx + dx,
@@ -502,12 +685,116 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
502
685
  };
503
686
  const endDrag = (event) => {
504
687
  const origin = dragRef.current;
688
+ if (origin?.touch) return;
505
689
  dragRef.current = null;
506
690
  setPanning(false);
507
691
  if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
508
692
  };
693
+ const touchDown = (event) => {
694
+ const touches = touchesRef.current;
695
+ if (touches.size >= 2) return;
696
+ event.preventDefault();
697
+ touches.set(event.pointerId, {
698
+ x: event.clientX,
699
+ y: event.clientY
700
+ });
701
+ try {
702
+ event.currentTarget.setPointerCapture(event.pointerId);
703
+ } catch {}
704
+ if (touches.size === 1) {
705
+ dragRef.current = {
706
+ x: event.clientX,
707
+ y: event.clientY,
708
+ tx: effective.tx,
709
+ ty: effective.ty,
710
+ moved: false,
711
+ pan: touchPan === "one-finger" || panMode,
712
+ touch: true,
713
+ at: event.timeStamp,
714
+ pointerId: event.pointerId
715
+ };
716
+ return;
717
+ }
718
+ const [a, b] = [...touches.values()];
719
+ const origin = viewportOrigin(event.currentTarget);
720
+ const mid = centroid(a, b);
721
+ pinchRef.current = {
722
+ distance: Math.hypot(a.x - b.x, a.y - b.y),
723
+ centre: {
724
+ x: mid.x - origin.x,
725
+ y: mid.y - origin.y
726
+ },
727
+ view: effective
728
+ };
729
+ if (dragRef.current) dragRef.current.moved = true;
730
+ setPanning(true);
731
+ onHover?.(null);
732
+ hits.clearHover();
733
+ };
734
+ const touchMove = (event) => {
735
+ const touches = touchesRef.current;
736
+ if (!touches.has(event.pointerId)) return;
737
+ touches.set(event.pointerId, {
738
+ x: event.clientX,
739
+ y: event.clientY
740
+ });
741
+ const pinch = pinchRef.current;
742
+ if (pinch && touches.size === 2) {
743
+ if (!(box.width > 0)) return;
744
+ const [a, b] = [...touches.values()];
745
+ const origin = viewportOrigin(event.currentTarget);
746
+ const mid = centroid(a, b);
747
+ commit(pinchView(pinch.view, pinch.distance, pinch.centre, Math.hypot(a.x - b.x, a.y - b.y), {
748
+ x: mid.x - origin.x,
749
+ y: mid.y - origin.y
750
+ }, scaleRange(box, image, clamp)));
751
+ return;
752
+ }
753
+ const drag = dragRef.current;
754
+ if (!drag || drag.pointerId !== event.pointerId) return;
755
+ const dx = event.clientX - drag.x;
756
+ const dy = event.clientY - drag.y;
757
+ if (!drag.moved && Math.hypot(dx, dy) <= CLICK_SLOP$1) return;
758
+ drag.moved = true;
759
+ if (!drag.pan) return;
760
+ setPanning(true);
761
+ onHover?.(null);
762
+ commit({
763
+ scale: effective.scale,
764
+ tx: drag.tx + dx,
765
+ ty: drag.ty + dy
766
+ });
767
+ };
768
+ const touchEnd = (event, cancelled) => {
769
+ const touches = touchesRef.current;
770
+ if (!touches.delete(event.pointerId)) return;
771
+ if (pinchRef.current) {
772
+ pinchRef.current = null;
773
+ const rest = [...touches.entries()][0];
774
+ if (rest) {
775
+ dragRef.current = {
776
+ x: rest[1].x,
777
+ y: rest[1].y,
778
+ tx: effective.tx,
779
+ ty: effective.ty,
780
+ moved: true,
781
+ pan: touchPan === "one-finger" || panMode,
782
+ touch: true,
783
+ at: event.timeStamp,
784
+ pointerId: rest[0]
785
+ };
786
+ return;
787
+ }
788
+ }
789
+ if (touches.size > 0) return;
790
+ const drag = dragRef.current;
791
+ dragRef.current = null;
792
+ setPanning(false);
793
+ if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
794
+ if (!routePress(event)) onBackgroundClick?.(event);
795
+ };
509
796
  const onDoubleClick = (event) => {
510
- if (!(box.width > 0)) return;
797
+ if (!doubleClickFit || !(box.width > 0)) return;
511
798
  if (atFit) {
512
799
  const restore = previousRef.current;
513
800
  if (restore) onView(clampView(restore, box, image, clamp));
@@ -573,51 +860,58 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
573
860
  };
574
861
  return /* @__PURE__ */ jsx(ImageStageContext, {
575
862
  value: context,
576
- children: /* @__PURE__ */ jsxs("div", {
577
- ref: attachViewport,
578
- role: "application",
579
- "aria-label": label,
580
- tabIndex: 0,
581
- style,
582
- "data-fit": atFit ? "" : void 0,
583
- "data-panning": panning ? "" : void 0,
584
- "data-pan-mode": panMode ? "" : void 0,
585
- className: cn("@container/stage relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
586
- onPointerDown,
587
- onPointerMove,
588
- onPointerUp: endDrag,
589
- onPointerCancel: endDrag,
590
- onLostPointerCapture: endDrag,
591
- onPointerLeave: () => onHover?.(null),
592
- onDoubleClick,
593
- onKeyDown,
594
- children: [
595
- /* @__PURE__ */ jsx("div", {
596
- "data-stage": true,
597
- className: "absolute top-0 left-0 origin-top-left",
598
- style: {
599
- width: image.width,
600
- height: image.height,
601
- transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`
602
- },
603
- children
604
- }),
605
- banner && /* @__PURE__ */ jsx("div", {
606
- className: "pointer-events-none absolute top-2 left-2 z-10",
607
- children: banner
608
- }),
609
- (toolbar || readout) && /* @__PURE__ */ jsxs("div", {
610
- className: "pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2",
611
- children: [/* @__PURE__ */ jsx("div", {
612
- className: "pointer-events-auto max-w-full shrink-0",
613
- children: toolbar
614
- }), /* @__PURE__ */ jsx("div", {
615
- "data-readout-slot": "",
616
- className: "max-w-full min-w-0 truncate",
617
- children: readout
618
- })]
619
- })
620
- ]
863
+ children: /* @__PURE__ */ jsx(StageHitContext, {
864
+ value: hits,
865
+ children: /* @__PURE__ */ jsxs("div", {
866
+ ref: attachViewport,
867
+ role: "application",
868
+ "aria-label": label,
869
+ tabIndex: 0,
870
+ style,
871
+ "data-fit": atFit ? "" : void 0,
872
+ "data-panning": panning ? "" : void 0,
873
+ "data-pan-mode": panMode ? "" : void 0,
874
+ className: cn("@container/stage relative h-full w-full touch-none overflow-hidden rounded-control border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
875
+ onPointerDown,
876
+ onPointerMove,
877
+ onPointerUp: (event) => event.pointerType === "touch" ? touchEnd(event, false) : endDrag(event),
878
+ onPointerCancel: (event) => event.pointerType === "touch" ? touchEnd(event, true) : endDrag(event),
879
+ onLostPointerCapture: (event) => event.pointerType === "touch" ? touchEnd(event, true) : endDrag(event),
880
+ onPointerLeave: () => {
881
+ onHover?.(null);
882
+ hits.clearHover();
883
+ },
884
+ onDoubleClick,
885
+ onContextMenu: panButtons.has(2) ? (event) => event.preventDefault() : void 0,
886
+ onKeyDown,
887
+ children: [
888
+ /* @__PURE__ */ jsx("div", {
889
+ "data-stage": true,
890
+ className: "absolute top-0 left-0 origin-top-left",
891
+ style: {
892
+ width: image.width,
893
+ height: image.height,
894
+ transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`
895
+ },
896
+ children
897
+ }),
898
+ banner && /* @__PURE__ */ jsx("div", {
899
+ className: "pointer-events-none absolute top-2 left-2 z-10",
900
+ children: banner
901
+ }),
902
+ (toolbar || readout) && /* @__PURE__ */ jsxs("div", {
903
+ className: "pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2",
904
+ children: [/* @__PURE__ */ jsx("div", {
905
+ className: "pointer-events-auto max-w-full shrink-0",
906
+ children: toolbar
907
+ }), /* @__PURE__ */ jsx("div", {
908
+ "data-readout-slot": "",
909
+ className: "max-w-full min-w-0 truncate",
910
+ children: readout
911
+ })]
912
+ })
913
+ ]
914
+ })
621
915
  })
622
916
  });
623
917
  }
@@ -663,6 +957,75 @@ function isTypingTarget(target) {
663
957
  return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
664
958
  }
665
959
  //#endregion
960
+ //#region src/components/stage/useStageHitTest.ts
961
+ /**
962
+ * React wiring for the stage's hit-test registry: `useStageHitTest` for apps that ask "what
963
+ * is under the pointer", and `useStageHitLayer` for layers that answer.
964
+ */
965
+ /** The default pointer tolerance of `hitTest`, in screen pixels. */
966
+ const DEFAULT_RADIUS_PX = 6;
967
+ /**
968
+ * The stage's one hit-test, across every registered layer (`PointSet`, `PolylineSet`, and
969
+ * any layer built with `useStageHitLayer`). A press handler uses it to decide what a press
970
+ * means: an item under the pointer is selected, bare image is drawn on or panned.
971
+ *
972
+ * The answer comes from each layer's spatial index, never from the DOM, so it costs
973
+ * microseconds at any scene size.
974
+ *
975
+ * @returns `{ hitTest, hitTestAll }`.
976
+ * @throws `Error` outside an `ImageStage`, which is always a wiring bug.
977
+ */
978
+ function useStageHitTest() {
979
+ const registry = use(StageHitContext);
980
+ if (registry === null) throw new Error("useStageHitTest must be used inside <ImageStage>.");
981
+ const { imageLength } = useStage();
982
+ return useMemo(() => ({
983
+ hitTest: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) => registry.hitTest(point, imageLength(radiusScreenPx), options),
984
+ hitTestAll: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) => registry.hitTestAll(point, imageLength(radiusScreenPx), options)
985
+ }), [registry, imageLength]);
986
+ }
987
+ /**
988
+ * Register a layer with the stage's hit-test. The callbacks may change every render; the
989
+ * registration does not, so a layer is never missing from a hit-test for a frame.
990
+ *
991
+ * @param options - How the layer answers `pick`, and whether it takes hover and presses.
992
+ * @returns The layer's id, as hits report it.
993
+ * @throws `Error` outside an `ImageStage`.
994
+ */
995
+ function useStageHitLayer(options) {
996
+ const registry = use(StageHitContext);
997
+ if (registry === null) throw new Error("useStageHitLayer must be used inside <ImageStage>.");
998
+ const generatedId = useId();
999
+ const id = options.layerId ?? generatedId;
1000
+ const latestRef = useRef(options);
1001
+ useLayoutEffect(() => {
1002
+ latestRef.current = options;
1003
+ });
1004
+ const priority = options.priority;
1005
+ useLayoutEffect(() => {
1006
+ const layer = {
1007
+ id,
1008
+ priority,
1009
+ pick: (point, radius) => latestRef.current.pick(point, radius),
1010
+ get pressable() {
1011
+ return latestRef.current.onPress !== void 0;
1012
+ },
1013
+ get hover() {
1014
+ return latestRef.current.onHover === void 0 ? void 0 : (hovered) => latestRef.current.onHover?.(hovered);
1015
+ },
1016
+ get press() {
1017
+ return latestRef.current.onPress === void 0 ? void 0 : (hit, event) => latestRef.current.onPress?.(hit, event);
1018
+ }
1019
+ };
1020
+ return registry.register(layer);
1021
+ }, [
1022
+ registry,
1023
+ id,
1024
+ priority
1025
+ ]);
1026
+ return id;
1027
+ }
1028
+ //#endregion
666
1029
  //#region src/components/stage/ImageLayer.tsx
667
1030
  /**
668
1031
  * The photograph, as a stage layer.
@@ -2498,7 +2861,7 @@ function clamp(value, low, high) {
2498
2861
  const HANDLE_PX = 9;
2499
2862
  /** Outline width, in screen pixels. */
2500
2863
  const STROKE_PX = 1.5;
2501
- const HALO$1 = overlayRole("halo");
2864
+ const HALO$2 = overlayRole("halo");
2502
2865
  /**
2503
2866
  * An editable axis-aligned region inside an `ImageStage`.
2504
2867
  *
@@ -2609,7 +2972,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2609
2972
  width: shown.width,
2610
2973
  height: shown.height,
2611
2974
  fill: "none",
2612
- stroke: HALO$1,
2975
+ stroke: HALO$2,
2613
2976
  strokeWidth: px(3.5)
2614
2977
  }), /* @__PURE__ */ jsx("rect", {
2615
2978
  x: shown.x,
@@ -2685,7 +3048,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
2685
3048
  width: size,
2686
3049
  height: size,
2687
3050
  fill: stroke,
2688
- stroke: HALO$1,
3051
+ stroke: HALO$2,
2689
3052
  strokeWidth: px(1),
2690
3053
  className: "pointer-events-auto",
2691
3054
  style: { cursor: ROI_HANDLE_CURSOR[handle] },
@@ -2725,7 +3088,7 @@ function fmt(value) {
2725
3088
  * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
2726
3089
  * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
2727
3090
  */
2728
- const HALO = overlayRole("halo");
3091
+ const HALO$1 = overlayRole("halo");
2729
3092
  /** The most points drawn as dots at once; past this the dots are noise and a cost. */
2730
3093
  const MAX_VERTEX_DOTS = 5e3;
2731
3094
  /**
@@ -2742,14 +3105,26 @@ const MAX_VERTEX_DOTS = 5e3;
2742
3105
  *
2743
3106
  * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
2744
3107
  */
2745
- function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines" }) {
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 }) {
2746
3109
  const stage = useStage();
2747
3110
  const startDrag = useStageDrag();
2748
3111
  const px = useScreenPx();
3112
+ const { hitTestAll } = useStageHitTest();
2749
3113
  const index = useMemo(() => buildPolylineIndex(items), [items]);
2750
3114
  const selectedSet = useMemo(() => new Set(selected ?? []), [selected]);
2751
3115
  const dimmedSet = useMemo(() => new Set(dimmed ?? []), [dimmed]);
2752
3116
  const byId = useMemo(() => new Map(items.map((item) => [item.id, item])), [items]);
3117
+ const ownId = useStageHitLayer({
3118
+ layerId,
3119
+ priority,
3120
+ pick: (point, radius) => {
3121
+ const hit = nearestPolyline(index, point, radius);
3122
+ return hit ? {
3123
+ id: hit.id,
3124
+ dist: hit.distance
3125
+ } : null;
3126
+ }
3127
+ });
2753
3128
  const [ownHover, setOwnHover] = useState(null);
2754
3129
  const hoverId = hovered !== void 0 ? hovered : ownHover;
2755
3130
  const [band, setBand] = useState(null);
@@ -2821,6 +3196,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
2821
3196
  if (id === hoverId) return;
2822
3197
  setOwnHover(id);
2823
3198
  onHover?.(id);
3199
+ onHoverChange?.(id);
2824
3200
  };
2825
3201
  const sweep = (event) => {
2826
3202
  const from = stage.toImage({
@@ -2852,7 +3228,13 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
2852
3228
  }
2853
3229
  const id = pickAt(event);
2854
3230
  if (id === null) return;
3231
+ const point = stage.toImage({
3232
+ x: event.clientX,
3233
+ y: event.clientY
3234
+ });
3235
+ if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
2855
3236
  event.stopPropagation();
3237
+ onItemPress?.(id, event);
2856
3238
  onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
2857
3239
  };
2858
3240
  const hairline = px(1.5);
@@ -2884,7 +3266,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
2884
3266
  children: [
2885
3267
  /* @__PURE__ */ jsx("path", {
2886
3268
  d: groups.hit,
2887
- stroke: HALO,
3269
+ stroke: HALO$1,
2888
3270
  strokeWidth: px(3.5),
2889
3271
  opacity: .6
2890
3272
  }),
@@ -2897,7 +3279,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
2897
3279
  }, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
2898
3280
  groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
2899
3281
  d: groups.selected,
2900
- stroke: HALO,
3282
+ stroke: HALO$1,
2901
3283
  strokeWidth: px(4.5)
2902
3284
  }), /* @__PURE__ */ jsx("path", {
2903
3285
  "data-selected-lines": "",
@@ -2907,7 +3289,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
2907
3289
  })] }),
2908
3290
  hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
2909
3291
  d: hoverPath,
2910
- stroke: HALO,
3292
+ stroke: HALO$1,
2911
3293
  strokeWidth: px(4)
2912
3294
  }), /* @__PURE__ */ jsx("path", {
2913
3295
  "data-hovered-line": "",
@@ -2960,6 +3342,653 @@ function boxBetween(a, b) {
2960
3342
  };
2961
3343
  }
2962
3344
  //#endregion
3345
+ //#region src/components/markerShapes.ts
3346
+ /** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
3347
+ function n(value) {
3348
+ return Math.round(value * 1e3) / 1e3;
3349
+ }
3350
+ /**
3351
+ * A circle as two arcs, centred at `(x, y)`.
3352
+ *
3353
+ * @param x - Centre x.
3354
+ * @param y - Centre y.
3355
+ * @param r - Radius, in the units of `x` and `y`.
3356
+ * @returns Path data.
3357
+ */
3358
+ function circlePath(x, y, r) {
3359
+ return `M${n(x + r)} ${n(y)}a${n(r)} ${n(r)} 0 1 0 ${n(-2 * r)} 0a${n(r)} ${n(r)} 0 1 0 ${n(2 * r)} 0`;
3360
+ }
3361
+ /** The built-in kinds, with the overlay grammar's glyph for each. */
3362
+ const MARKER_SHAPES = {
3363
+ /** A blob, circle centre or keypoint: a dot of radius 2.5 px. */
3364
+ dot: {
3365
+ paint: "disc",
3366
+ size: 2.5,
3367
+ path: (x, y) => `M${n(x)} ${n(y)}h0`
3368
+ },
3369
+ /** A corner or X-junction: a plus with 5 px arms, so the centre stays visible. */
3370
+ plus: {
3371
+ paint: "line",
3372
+ size: 5,
3373
+ path: (x, y, u) => {
3374
+ const a = 5 * u;
3375
+ return `M${n(x - a)} ${n(y)}h${n(2 * a)}M${n(x)} ${n(y - a)}v${n(2 * a)}`;
3376
+ }
3377
+ },
3378
+ /** A diagonal cross with 4 px arms: a second corner style, or "rejected". */
3379
+ cross: {
3380
+ paint: "line",
3381
+ size: 4,
3382
+ path: (x, y, u) => {
3383
+ const a = 4 * u;
3384
+ return `M${n(x - a)} ${n(y - a)}l${n(2 * a)} ${n(2 * a)}M${n(x - a)} ${n(y + a)}l${n(2 * a)} ${n(-2 * a)}`;
3385
+ }
3386
+ },
3387
+ /** A hollow square of half-side 3.5 px. */
3388
+ square: {
3389
+ paint: "line",
3390
+ size: 3.5,
3391
+ path: (x, y, u) => {
3392
+ const a = 3.5 * u;
3393
+ return `M${n(x - a)} ${n(y - a)}h${n(2 * a)}v${n(2 * a)}h${n(-2 * a)}Z`;
3394
+ }
3395
+ },
3396
+ /** A reprojected or predicted point: a hollow circle of radius 4 px, in the model colour. */
3397
+ hollow: {
3398
+ paint: "line",
3399
+ size: 4,
3400
+ role: "model",
3401
+ path: (x, y, u) => circlePath(x, y, 4 * u)
3402
+ },
3403
+ /**
3404
+ * A point with an orientation: a small ring and a tick of length 8 px from it along
3405
+ * `angle`, measured clockwise from +x in image coordinates (y points down).
3406
+ */
3407
+ directed: {
3408
+ paint: "line",
3409
+ size: 6,
3410
+ path: (x, y, u, angle) => {
3411
+ const c = Math.cos(angle);
3412
+ const s = Math.sin(angle);
3413
+ return `${circlePath(x, y, 2 * u)}M${n(x + 2 * u * c)} ${n(y + 2 * u * s)}L${n(x + 8 * u * c)} ${n(y + 8 * u * s)}`;
3414
+ }
3415
+ }
3416
+ };
3417
+ //#endregion
3418
+ //#region src/components/pointIndex.ts
3419
+ /** The most grid cells an index allocates, whatever the cell side asks for. */
3420
+ const MAX_CELLS = 4e6;
3421
+ /**
3422
+ * Index a set of points.
3423
+ *
3424
+ * @param xy - Flat `[x0, y0, x1, y1, …]` in image coordinates; a `Float32Array` or
3425
+ * `Float64Array` avoids a copy at the call site.
3426
+ * @param options - Ids, per-point pick radii and the cell side.
3427
+ * @returns The index.
3428
+ */
3429
+ function buildPointIndex(xy, options = {}) {
3430
+ const count = Math.floor(xy.length / 2);
3431
+ const ids = options.ids ?? null;
3432
+ const radii = options.radii ?? null;
3433
+ let minX = Infinity;
3434
+ let minY = Infinity;
3435
+ let maxX = -Infinity;
3436
+ let maxY = -Infinity;
3437
+ let maxRadius = 0;
3438
+ let live = 0;
3439
+ for (let i = 0; i < count; i++) {
3440
+ const x = xy[2 * i];
3441
+ const y = xy[2 * i + 1];
3442
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
3443
+ live++;
3444
+ if (x < minX) minX = x;
3445
+ if (x > maxX) maxX = x;
3446
+ if (y < minY) minY = y;
3447
+ if (y > maxY) maxY = y;
3448
+ if (radii) {
3449
+ const r = radii[i];
3450
+ if (r > maxRadius) maxRadius = r;
3451
+ }
3452
+ }
3453
+ if (live === 0) return {
3454
+ count,
3455
+ xy,
3456
+ ids,
3457
+ radii,
3458
+ maxRadius,
3459
+ cell: 1,
3460
+ x0: 0,
3461
+ y0: 0,
3462
+ cols: 1,
3463
+ rows: 1,
3464
+ starts: /* @__PURE__ */ new Uint32Array(2),
3465
+ items: /* @__PURE__ */ new Uint32Array(0)
3466
+ };
3467
+ const width = maxX - minX;
3468
+ const height = maxY - minY;
3469
+ 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;
3471
+ const cols = Math.floor(width / cell) + 1;
3472
+ const rows = Math.floor(height / cell) + 1;
3473
+ const cellOf = new Int32Array(count).fill(-1);
3474
+ const starts = new Uint32Array(cols * rows + 1);
3475
+ for (let i = 0; i < count; i++) {
3476
+ const x = xy[2 * i];
3477
+ const y = xy[2 * i + 1];
3478
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
3479
+ const c = Math.min(rows - 1, Math.floor((y - minY) / cell)) * cols + Math.min(cols - 1, Math.floor((x - minX) / cell));
3480
+ cellOf[i] = c;
3481
+ starts[c + 1]++;
3482
+ }
3483
+ for (let c = 0; c < cols * rows; c++) starts[c + 1] += starts[c];
3484
+ const fill = starts.slice(0, cols * rows);
3485
+ const items = new Uint32Array(live);
3486
+ for (let i = 0; i < count; i++) {
3487
+ const c = cellOf[i];
3488
+ if (c >= 0) items[fill[c]++] = i;
3489
+ }
3490
+ return {
3491
+ count,
3492
+ xy,
3493
+ ids,
3494
+ radii,
3495
+ maxRadius,
3496
+ cell,
3497
+ x0: minX,
3498
+ y0: minY,
3499
+ cols,
3500
+ rows,
3501
+ starts,
3502
+ items
3503
+ };
3504
+ }
3505
+ /**
3506
+ * Index items that carry their own position.
3507
+ *
3508
+ * @param items - The points, in order.
3509
+ * @param cell - The grid cell side; see `PointIndexOptions`.
3510
+ * @returns The index; its point indices are positions in `items`.
3511
+ */
3512
+ function buildPointIndexFrom(items, cell) {
3513
+ const xy = new Float64Array(items.length * 2);
3514
+ const ids = new Array(items.length);
3515
+ let radii;
3516
+ items.forEach((item, i) => {
3517
+ xy[2 * i] = item.x;
3518
+ xy[2 * i + 1] = item.y;
3519
+ ids[i] = item.id;
3520
+ if (item.pickRadius !== void 0 && item.pickRadius > 0) {
3521
+ radii ??= new Float64Array(items.length);
3522
+ radii[i] = item.pickRadius;
3523
+ }
3524
+ });
3525
+ return buildPointIndex(xy, {
3526
+ ids,
3527
+ radii,
3528
+ cell
3529
+ });
3530
+ }
3531
+ /**
3532
+ * The point nearest to `(x, y)` whose pick disc reaches it, or `null`.
3533
+ *
3534
+ * @param index - The index.
3535
+ * @param x - The query's x, in image coordinates.
3536
+ * @param y - The query's y, in image coordinates.
3537
+ * @param radius - How far from a point's centre the query still picks it, in image pixels.
3538
+ * For a screen-constant tolerance, pass `useScreenPx()(css)`. A point's own `radii` entry
3539
+ * adds to it.
3540
+ * @returns The point nearest by centre distance; ties go to the lower index, so the result
3541
+ * does not depend on cell order.
3542
+ */
3543
+ function nearestPoint(index, x, y, radius) {
3544
+ if (!(radius >= 0) || index.items.length === 0) return null;
3545
+ const { cell, x0, y0, cols, rows, starts, items, xy, radii, maxRadius } = index;
3546
+ const reach = radius + maxRadius;
3547
+ const cx0 = Math.max(0, Math.floor((x - reach - x0) / cell));
3548
+ const cx1 = Math.min(cols - 1, Math.floor((x + reach - x0) / cell));
3549
+ const cy0 = Math.max(0, Math.floor((y - reach - y0) / cell));
3550
+ const cy1 = Math.min(rows - 1, Math.floor((y + reach - y0) / cell));
3551
+ let best = -1;
3552
+ let bestD = Infinity;
3553
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
3554
+ const c = cy * cols + cx;
3555
+ for (let k = starts[c]; k < starts[c + 1]; k++) {
3556
+ const i = items[k];
3557
+ const dx = xy[2 * i] - x;
3558
+ const dy = xy[2 * i + 1] - y;
3559
+ const d = dx * dx + dy * dy;
3560
+ const reachI = radii ? radius + radii[i] : radius;
3561
+ if (d <= reachI * reachI && (d < bestD || d === bestD && i < best)) {
3562
+ bestD = d;
3563
+ best = i;
3564
+ }
3565
+ }
3566
+ }
3567
+ return best < 0 ? null : {
3568
+ index: best,
3569
+ id: index.ids ? index.ids[best] : best,
3570
+ dist: Math.sqrt(bestD)
3571
+ };
3572
+ }
3573
+ /**
3574
+ * The points whose centre is inside `rect`, edges included.
3575
+ *
3576
+ * @param index - The index.
3577
+ * @param rect - The band, in image coordinates. A negative extent is read as the box
3578
+ * between its corners.
3579
+ * @returns Their indices, ascending.
3580
+ */
3581
+ function pointsInRect(index, rect) {
3582
+ if (index.items.length === 0) return [];
3583
+ const { cell, x0, y0, cols, rows, starts, items, xy } = index;
3584
+ const left = Math.min(rect.x, rect.x + rect.width);
3585
+ const right = Math.max(rect.x, rect.x + rect.width);
3586
+ const top = Math.min(rect.y, rect.y + rect.height);
3587
+ const bottom = Math.max(rect.y, rect.y + rect.height);
3588
+ const cx0 = Math.max(0, Math.floor((left - x0) / cell));
3589
+ const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
3590
+ const cy0 = Math.max(0, Math.floor((top - y0) / cell));
3591
+ const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
3592
+ const found = [];
3593
+ for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
3594
+ const c = cy * cols + cx;
3595
+ for (let k = starts[c]; k < starts[c + 1]; k++) {
3596
+ const i = items[k];
3597
+ const px = xy[2 * i];
3598
+ const py = xy[2 * i + 1];
3599
+ if (px >= left && px <= right && py >= top && py <= bottom) found.push(i);
3600
+ }
3601
+ }
3602
+ return found.sort((a, b) => a - b);
3603
+ }
3604
+ /**
3605
+ * A greedy thinning: walk the points in `order` and keep each one that is at least `minDist`
3606
+ * from every point kept so far. This is how a label layer decides which labels the zoom has
3607
+ * room for.
3608
+ *
3609
+ * The result is *maximal*: every point left out is within `minDist` of one kept before it,
3610
+ * and every pair kept is at least `minDist` apart.
3611
+ *
3612
+ * @param xy - Flat points, in the units `minDist` is in (image pixels for a screen-px spacing
3613
+ * converted with `useScreenPx`).
3614
+ * @param minDist - The least distance between two kept points.
3615
+ * @param order - Point indices in priority order. Defaults to every point, in order.
3616
+ * Indices of non-finite points are skipped.
3617
+ * @returns The kept indices, in the order they were kept.
3618
+ */
3619
+ function thinPoints(xy, minDist, order) {
3620
+ const kept = [];
3621
+ if (!(minDist > 0)) {
3622
+ for (const i of order ?? range(Math.floor(xy.length / 2))) if (isLive(xy, i)) kept.push(i);
3623
+ return kept;
3624
+ }
3625
+ const cells = /* @__PURE__ */ new Map();
3626
+ const key = (cx, cy) => cy * 4194304 + cx;
3627
+ const limit = minDist * minDist;
3628
+ for (const i of order ?? range(Math.floor(xy.length / 2))) {
3629
+ if (!isLive(xy, i)) continue;
3630
+ const x = xy[2 * i];
3631
+ const y = xy[2 * i + 1];
3632
+ const cx = Math.floor(x / minDist);
3633
+ const cy = Math.floor(y / minDist);
3634
+ let clear = true;
3635
+ scan: for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
3636
+ const bucket = cells.get(key(cx + dx, cy + dy));
3637
+ if (!bucket) continue;
3638
+ for (const j of bucket) {
3639
+ const ex = xy[2 * j] - x;
3640
+ const ey = xy[2 * j + 1] - y;
3641
+ if (ex * ex + ey * ey < limit) {
3642
+ clear = false;
3643
+ break scan;
3644
+ }
3645
+ }
3646
+ }
3647
+ if (!clear) continue;
3648
+ kept.push(i);
3649
+ const k = key(cx, cy);
3650
+ const bucket = cells.get(k);
3651
+ if (bucket) bucket.push(i);
3652
+ else cells.set(k, [i]);
3653
+ }
3654
+ return kept;
3655
+ }
3656
+ function isLive(xy, i) {
3657
+ return Number.isFinite(xy[2 * i]) && Number.isFinite(xy[2 * i + 1]);
3658
+ }
3659
+ function* range(n) {
3660
+ for (let i = 0; i < n; i++) yield i;
3661
+ }
3662
+ //#endregion
3663
+ //#region src/components/PointSet.tsx
3664
+ /**
3665
+ * Many points over the image, hoverable and selectable: detected corners, ring centres,
3666
+ * keypoints, labelled landmarks.
3667
+ *
3668
+ * Drawn as a handful of batched paths, one per (state, style, marker kind), never one element
3669
+ * per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the
3670
+ * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
3671
+ * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
3672
+ */
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
+ /** Past this many points, outlines are generated for the visible part only. */
3680
+ const CULL_ABOVE = 3e3;
3681
+ /** How much bigger than a marker its selection ring is, in screen pixels. */
3682
+ const RING_GAP = 4;
3683
+ const HALO = overlayRole("halo");
3684
+ const LABEL = overlayRole("label");
3685
+ /**
3686
+ * A selectable set of points inside an `ImageStage`.
3687
+ *
3688
+ * - **Markers** by kind, from the overlay grammar: `dot`, `plus` (corner), `cross`, `square`,
3689
+ * `hollow` (predicted), `directed`. Add your own through `markers`.
3690
+ * - **States**, from visual-language §5: default 1.5 screen px, hover 2, selected 2.5 in the
3691
+ * selection colour with a ring, dimmed at 35 % opacity. Every mark has a halo.
3692
+ * - **Labels** only where points are at least 24 screen px apart, at most 200 at a time.
3693
+ * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here,
3694
+ * and `useStageHitTest` for an app that arbitrates between layers.
3695
+ *
3696
+ * Outlines (`plus`, `cross`, …) are regenerated when the zoom changes, since their size is in
3697
+ * screen pixels; past 3,000 points only those near the viewport are generated. `dot` is a
3698
+ * zero-length stroke whose width is its size, so it is not regenerated at all.
3699
+ *
3700
+ * The SVG carries `data-hovered` (the hovered id).
3701
+ */
3702
+ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, labels = true, halo = true, selectionStroke = overlayRole("selection"), layerId, priority = STAGE_HIT_PRIORITY.point, label = "Points" }) {
3703
+ const stage = useStage();
3704
+ const px = useScreenPx();
3705
+ const unit = px(1);
3706
+ const shapes = useMemo(() => ({
3707
+ ...MARKER_SHAPES,
3708
+ ...markers
3709
+ }), [markers]);
3710
+ const index = useMemo(() => buildPointIndexFrom(items), [items]);
3711
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
3712
+ const isDimmed = useMemo(() => {
3713
+ if (typeof dimmed === "function") return dimmed;
3714
+ const set = new Set(dimmed ?? []);
3715
+ return (id) => set.has(id);
3716
+ }, [dimmed]);
3717
+ const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
3718
+ const [ownHover, setOwnHover] = useState(null);
3719
+ const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
3720
+ useStageHitLayer({
3721
+ layerId,
3722
+ priority,
3723
+ pick: (point, radius) => {
3724
+ const hit = nearestPoint(index, point.x, point.y, radius);
3725
+ return hit ? {
3726
+ id: hit.id,
3727
+ dist: hit.dist
3728
+ } : null;
3729
+ },
3730
+ onHover: (id) => {
3731
+ setOwnHover(id);
3732
+ onHoverChange?.(id);
3733
+ },
3734
+ onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
3735
+ });
3736
+ const groups = useMemo(() => {
3737
+ const normal = /* @__PURE__ */ new Map();
3738
+ const picked = /* @__PURE__ */ new Map();
3739
+ items.forEach((item, i) => {
3740
+ const kindName = item.kind ?? kind;
3741
+ const shape = shapes[kindName] ?? MARKER_SHAPES.dot;
3742
+ if (selectedSet.has(item.id)) {
3743
+ const key = kindName;
3744
+ let batch = picked.get(key);
3745
+ if (!batch) {
3746
+ batch = {
3747
+ key,
3748
+ shape,
3749
+ role: "selection",
3750
+ dim: false,
3751
+ indices: [],
3752
+ cache: null
3753
+ };
3754
+ picked.set(key, batch);
3755
+ }
3756
+ batch.indices.push(i);
3757
+ return;
3758
+ }
3759
+ const role = item.role ?? shape.role ?? "feature";
3760
+ const dim = isDimmed(item.id);
3761
+ const key = `${dim ? 1 : 0}|${role}|${kindName}`;
3762
+ let batch = normal.get(key);
3763
+ if (!batch) {
3764
+ batch = {
3765
+ key,
3766
+ shape,
3767
+ role,
3768
+ dim,
3769
+ indices: [],
3770
+ cache: null
3771
+ };
3772
+ normal.set(key, batch);
3773
+ }
3774
+ batch.indices.push(i);
3775
+ });
3776
+ const rings = [...picked.values()].map((batch) => ({
3777
+ ...batch,
3778
+ key: `ring|${batch.key}`,
3779
+ shape: {
3780
+ paint: "line",
3781
+ size: 0,
3782
+ path: (x, y, u) => circlePath(x, y, (batch.shape.size + RING_GAP) * u)
3783
+ },
3784
+ cache: null
3785
+ }));
3786
+ return {
3787
+ normal: [...normal.values()],
3788
+ picked: [...picked.values()],
3789
+ rings
3790
+ };
3791
+ }, [
3792
+ items,
3793
+ kind,
3794
+ shapes,
3795
+ selectedSet,
3796
+ isDimmed
3797
+ ]);
3798
+ const cull = cullWindow(stage.view, stage.box, items.length);
3799
+ const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
3800
+ const build = (batches) => batches.map((batch) => ({
3801
+ batch,
3802
+ d: batchPath(batch, items, unit, cull, cullKey)
3803
+ }));
3804
+ const paths = {
3805
+ normal: build(groups.normal),
3806
+ picked: build(groups.picked),
3807
+ rings: build(groups.rings)
3808
+ };
3809
+ const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
3810
+ const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
3811
+ const hoverShape = hoverItem ? shapes[hoverItem.kind ?? kind] ?? MARKER_SHAPES.dot : void 0;
3812
+ const hoverRole = hoverItem?.role ?? hoverShape?.role ?? "feature";
3813
+ const labelled = useMemo(() => {
3814
+ const list = [];
3815
+ items.forEach((item, i) => {
3816
+ if (item.label) list.push(i);
3817
+ });
3818
+ return list;
3819
+ }, [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);
3843
+ }
3844
+ return [...shown];
3845
+ }, [
3846
+ labels,
3847
+ spaced,
3848
+ items,
3849
+ hoverItem,
3850
+ selectedSet,
3851
+ positionOf,
3852
+ stage.view,
3853
+ stage.box
3854
+ ]);
3855
+ const widthOf = (shape, role, state) => {
3856
+ const thin = role === "model" || role === "structure";
3857
+ const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0);
3858
+ return px(shape.paint === "disc" ? 2 * shape.size + (OVERLAY_STATE_WIDTH[state] - 1.5) * 2 : base);
3859
+ };
3860
+ const ringWidth = px(1.5);
3861
+ return /* @__PURE__ */ jsxs("svg", {
3862
+ viewBox: imageViewBox(stage.image),
3863
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
3864
+ role: "img",
3865
+ "aria-label": `${label}: ${items.length} ${items.length === 1 ? "point" : "points"}, ${selectedSet.size} selected`,
3866
+ "data-hovered": hoverId ?? void 0,
3867
+ children: [/* @__PURE__ */ jsxs("g", {
3868
+ fill: "none",
3869
+ strokeLinecap: "round",
3870
+ strokeLinejoin: "round",
3871
+ children: [
3872
+ halo && paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3873
+ d,
3874
+ stroke: HALO,
3875
+ strokeWidth: widthOf(batch.shape, batch.role, "default") + px(2),
3876
+ opacity: .6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)
3877
+ }, `halo|${batch.key}`)),
3878
+ paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3879
+ "data-batch": batch.key,
3880
+ d,
3881
+ stroke: overlayRole(batch.role),
3882
+ strokeWidth: widthOf(batch.shape, batch.role, "default"),
3883
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1
3884
+ }, batch.key)),
3885
+ halo && paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3886
+ d,
3887
+ stroke: HALO,
3888
+ strokeWidth: widthOf(batch.shape, batch.role, "selected") + px(2)
3889
+ }, `halo|selected|${batch.key}`)),
3890
+ halo && paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3891
+ d,
3892
+ stroke: HALO,
3893
+ strokeWidth: ringWidth + px(2)
3894
+ }, `halo|${batch.key}`)),
3895
+ paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3896
+ "data-selected-points": batch.key,
3897
+ d,
3898
+ stroke: selectionStroke,
3899
+ strokeWidth: widthOf(batch.shape, batch.role, "selected")
3900
+ }, `selected|${batch.key}`)),
3901
+ paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
3902
+ "data-selection-rings": batch.key,
3903
+ d,
3904
+ stroke: selectionStroke,
3905
+ strokeWidth: ringWidth
3906
+ }, batch.key)),
3907
+ 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,
3910
+ strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)
3911
+ }), /* @__PURE__ */ jsx("path", {
3912
+ "data-hovered-point": "",
3913
+ d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
3914
+ stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
3915
+ strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
3916
+ })] })
3917
+ ]
3918
+ }), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
3919
+ "data-labels": "",
3920
+ fontSize: px(11),
3921
+ className: "font-mono",
3922
+ stroke: HALO,
3923
+ strokeWidth: px(3),
3924
+ paintOrder: "stroke",
3925
+ strokeLinejoin: "round",
3926
+ children: shownLabels.map((i) => {
3927
+ const item = items[i];
3928
+ return /* @__PURE__ */ jsx("text", {
3929
+ x: item.x + px(6),
3930
+ y: item.y - px(5),
3931
+ fill: LABEL,
3932
+ dominantBaseline: "text-after-edge",
3933
+ children: item.label
3934
+ }, item.id);
3935
+ })
3936
+ })]
3937
+ });
3938
+ }
3939
+ /**
3940
+ * The path data of a batch, generated again only when what it depends on changed: nothing
3941
+ * for a disc marker, the zoom and the window for an outline.
3942
+ */
3943
+ function batchPath(batch, items, unit, cull, cullKey) {
3944
+ const disc = batch.shape.paint === "disc";
3945
+ const key = disc ? "" : `${unit}|${cullKey}`;
3946
+ if (batch.cache?.key === key) return batch.cache.d;
3947
+ const window = disc ? null : cull;
3948
+ let d = "";
3949
+ for (const i of batch.indices) {
3950
+ const item = items[i];
3951
+ 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);
3953
+ }
3954
+ batch.cache = {
3955
+ key,
3956
+ d
3957
+ };
3958
+ return d;
3959
+ }
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
+ /**
3971
+ * The window outlines are generated for: the viewport plus half a viewport on every side,
3972
+ * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
3973
+ */
3974
+ function cullWindow(view, box, count) {
3975
+ if (count <= CULL_ABOVE) return null;
3976
+ const visible = visibleRect(view, box);
3977
+ if (visible === null) return null;
3978
+ const sx = visible.width / 2;
3979
+ const sy = visible.height / 2;
3980
+ const left = Math.floor((visible.x - sx) / sx) * sx;
3981
+ const top = Math.floor((visible.y - sy) / sy) * sy;
3982
+ const right = Math.ceil((visible.x + visible.width + sx) / sx) * sx;
3983
+ const bottom = Math.ceil((visible.y + visible.height + sy) / sy) * sy;
3984
+ return {
3985
+ x: left,
3986
+ y: top,
3987
+ width: right - left,
3988
+ height: bottom - top
3989
+ };
3990
+ }
3991
+ //#endregion
2963
3992
  //#region src/components/MaskEditor.tsx
2964
3993
  /** A source-pixel raster mask layer with a small paint/erase brush. */
2965
3994
  /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
@@ -3136,6 +4165,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
3136
4165
  })] });
3137
4166
  }
3138
4167
  //#endregion
3139
- export { ContourEditor, FULL_TIER_ZOOM, ImageLayer, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, buildPolylineIndex, caliperArrow, caliperCorners, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, moveRect, nativeZoomFor, nearestContourSegment, nearestPolyline, overlayRole, paintMask, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rectFromCorners, resizeRect, roiHandlePoint, rotatePoint, sameRect, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useScreenPx, useStage, useStageDrag, valueAt, valuesAt, zoomAbout, zoomAt };
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 };
3140
4169
 
3141
4170
  //# sourceMappingURL=index.js.map