@vitavision/stage2d 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -127,6 +127,16 @@ function toImage(view, p) {
127
127
  function insideImage(p, image) {
128
128
  return p.x >= -.5 && p.y >= -.5 && p.x < image.width - .5 && p.y < image.height - .5;
129
129
  }
130
+ /**
131
+ * An image coordinate held to the image's extent, `[-0.5, w - 0.5] x [-0.5, h - 0.5]` in the
132
+ * pixel-centre convention: the point on the frame's edge nearest to `p`.
133
+ */
134
+ function clampToImage(p, image) {
135
+ return {
136
+ x: Math.min(image.width - PIXEL_CENTRE, Math.max(-.5, p.x)),
137
+ y: Math.min(image.height - PIXEL_CENTRE, Math.max(-.5, p.y))
138
+ };
139
+ }
130
140
  /** A length in image pixels that covers `css` screen pixels at this view. */
131
141
  function imageLengthFor(view, css) {
132
142
  return view.scale > 0 ? css / view.scale : css;
@@ -154,20 +164,26 @@ function scaleRange(box, image, options = {}) {
154
164
  /**
155
165
  * Keep the view legal: scale inside its range, and the image never dragged off screen.
156
166
  *
157
- * An axis where the scaled image is smaller than the viewport is centred rather than left
158
- * where a drag put it — free-floating pixels in a grey field is a way to be lost with no
159
- * visible handle to get back. An axis where it is larger is held so the viewport stays
160
- * covered.
167
+ * With the default `panBounds: "cover"`, an axis where the scaled image is smaller than the
168
+ * viewport is centred rather than left where a drag put it — free-floating pixels in a grey
169
+ * field is a way to be lost with no visible handle to get back — and an axis where it is
170
+ * larger is held so the viewport stays covered. With `"center"`, each axis only keeps some
171
+ * image point at or past the viewport's centre.
161
172
  */
162
173
  function clampView(view, box, image, options = {}) {
163
174
  const [min, max] = scaleRange(box, image, options);
164
175
  const scale = clamp$2(view.scale, min, max);
176
+ const axis = options.panBounds === "center" ? centreAxis : clampAxis;
165
177
  return {
166
178
  scale,
167
- tx: clampAxis(view.tx, box.width, image.width * scale),
168
- ty: clampAxis(view.ty, box.height, image.height * scale)
179
+ tx: axis(view.tx, box.width, image.width * scale),
180
+ ty: axis(view.ty, box.height, image.height * scale)
169
181
  };
170
182
  }
183
+ /** `"center"` bounds: the content's far edge may come to the centre, and its near edge too. */
184
+ function centreAxis(t, boxLength, contentLength) {
185
+ return clamp$2(t, boxLength / 2 - contentLength, boxLength / 2);
186
+ }
171
187
  function clampAxis(t, boxLength, contentLength) {
172
188
  if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
173
189
  return clamp$2(t, boxLength - contentLength, 0);
@@ -485,8 +501,16 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
485
501
  padding: fitOptions?.padding,
486
502
  upscale: fitOptions?.upscale
487
503
  }), [fitOptions?.padding, fitOptions?.upscale]);
504
+ const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW), [
505
+ view,
506
+ box,
507
+ image,
508
+ opening,
509
+ fitOpts
510
+ ]);
488
511
  const latestRef = useRef({
489
512
  view,
513
+ effective: UNMEASURED_VIEW,
490
514
  box,
491
515
  image,
492
516
  clamp,
@@ -497,6 +521,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
497
521
  useLayoutEffect(() => {
498
522
  latestRef.current = {
499
523
  view,
524
+ effective,
500
525
  box,
501
526
  image,
502
527
  clamp,
@@ -505,6 +530,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
505
530
  fitOpts
506
531
  };
507
532
  });
533
+ /** Whether the opening view of the current `null` view has been reported. */
534
+ const openedRef = useRef(false);
508
535
  /** The view to come back to when a double-click leaves fit. */
509
536
  const previousRef = useRef(null);
510
537
  const dragRef = useRef(null);
@@ -515,13 +542,6 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
515
542
  /** The registry the stage's layers answer hit-tests through. */
516
543
  const [hits] = useState(() => createHitRegistry());
517
544
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
518
- const effective = useMemo(() => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW), [
519
- view,
520
- box,
521
- image,
522
- opening,
523
- fitOpts
524
- ]);
525
545
  useEffect(() => {
526
546
  const element = boxRef.current;
527
547
  if (!element) return;
@@ -537,10 +557,35 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
537
557
  effective.tx,
538
558
  effective.ty
539
559
  ]);
540
- const commit = useCallback((next) => {
541
- const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
542
- report(b.width > 0 ? clampView(next, b, i, c) : next);
560
+ /** Report a view with its cause and the viewport it was made for (the measured one by default). */
561
+ const emit = useCallback((next, cause, box) => {
562
+ const { box: b, onView: report } = latestRef.current;
563
+ report(next, {
564
+ cause,
565
+ box: box ?? b
566
+ });
543
567
  }, []);
568
+ const commit = useCallback((next, cause = "command") => {
569
+ const { box: b, image: i, clamp: c } = latestRef.current;
570
+ emit(b.width > 0 ? clampView(next, b, i, c) : next, cause);
571
+ }, [emit]);
572
+ useEffect(() => {
573
+ if (view !== null) {
574
+ openedRef.current = false;
575
+ return;
576
+ }
577
+ if (box.width > 0 && !openedRef.current) {
578
+ openedRef.current = true;
579
+ emit(openingView(opening, box, image, fitOpts), "measure");
580
+ }
581
+ }, [
582
+ view,
583
+ box,
584
+ image,
585
+ opening,
586
+ fitOpts,
587
+ emit
588
+ ]);
544
589
  const attachViewport = useCallback((element) => {
545
590
  viewportRef.current = element;
546
591
  if (!element) return;
@@ -554,10 +599,12 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
554
599
  };
555
600
  measuredRef.current = next;
556
601
  setBox(next);
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));
559
- else if (!(current.width > 0)) report(clampView(v, next, i, c));
560
- else report(preserveCenter(v, current, next, i, c, f));
602
+ const { view: v, image: i, clamp: c, opening: o, fitOpts: f } = latestRef.current;
603
+ if (v === null) {
604
+ openedRef.current = true;
605
+ emit(openingView(o, next, i, f), "measure", next);
606
+ } else if (!(current.width > 0)) emit(clampView(v, next, i, c), "measure", next);
607
+ else emit(preserveCenter(v, current, next, i, c, f), "measure", next);
561
608
  };
562
609
  measure(contentSize(element));
563
610
  const observer = new ResizeObserver((entries) => {
@@ -567,15 +614,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
567
614
  observer.observe(element);
568
615
  const onWheel = (event) => {
569
616
  event.preventDefault();
570
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
571
- if (v === null || !(b.width > 0)) return;
617
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
618
+ if (!(b.width > 0)) return;
572
619
  const origin = viewportOrigin(element);
573
620
  const [min, max] = scaleRange(b, i, c);
574
621
  const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
575
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, v.scale * factor)), {
622
+ const scale = Math.min(max, Math.max(min, v.scale * factor));
623
+ const anchor = {
576
624
  x: event.clientX - origin.x,
577
625
  y: event.clientY - origin.y
578
- }), b, i, c));
626
+ };
627
+ emit(clampView(zoomAbout(v, scale, anchor), b, i, c), "gesture");
579
628
  };
580
629
  element.addEventListener("wheel", onWheel, { passive: false });
581
630
  return () => {
@@ -583,7 +632,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
583
632
  element.removeEventListener("wheel", onWheel);
584
633
  viewportRef.current = null;
585
634
  };
586
- }, []);
635
+ }, [emit]);
587
636
  useEffect(() => {
588
637
  if (!shortcuts) return;
589
638
  const down = (event) => {
@@ -604,8 +653,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
604
653
  }, [shortcuts]);
605
654
  const clientToImage = useCallback((p) => {
606
655
  const element = viewportRef.current;
607
- const { view: v } = latestRef.current;
608
- if (!element || v === null) return {
656
+ const { view: held, effective: v, box: b } = latestRef.current;
657
+ if (!element || held === null && !(b.width > 0)) return {
609
658
  x: 0,
610
659
  y: 0
611
660
  };
@@ -617,8 +666,8 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
617
666
  }, []);
618
667
  const imageToClient = useCallback((p) => {
619
668
  const element = viewportRef.current;
620
- const { view: v } = latestRef.current;
621
- if (!element || v === null) return {
669
+ const { view: held, effective: v, box: b } = latestRef.current;
670
+ if (!element || held === null && !(b.width > 0)) return {
622
671
  x: 0,
623
672
  y: 0
624
673
  };
@@ -629,16 +678,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
629
678
  y: local.y + origin.y
630
679
  };
631
680
  }, []);
632
- const fit = useCallback(() => {
633
- const { box: b, image: i, view: v, onView: report, fitOpts: f } = latestRef.current;
681
+ const fitBy = useCallback((cause) => {
682
+ const { box: b, image: i, view: v, fitOpts: f } = latestRef.current;
634
683
  if (!(b.width > 0)) return;
635
684
  if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
636
- report(fitView(b, i, f));
637
- }, []);
638
- const zoomTo = useCallback((scale, anchor) => {
639
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
685
+ emit(fitView(b, i, f), cause);
686
+ }, [emit]);
687
+ const fit = useCallback(() => fitBy("command"), [fitBy]);
688
+ const zoomBy = useCallback((cause, scale, anchor) => {
689
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
640
690
  const element = viewportRef.current;
641
- if (v === null || !(b.width > 0) || !element) return;
691
+ if (!(b.width > 0) || !element) return;
642
692
  const origin = viewportOrigin(element);
643
693
  const local = anchor ? {
644
694
  x: anchor.x - origin.x,
@@ -648,13 +698,14 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
648
698
  y: b.height / 2
649
699
  };
650
700
  const [min, max] = scaleRange(b, i, c);
651
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
652
- }, []);
701
+ emit(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c), cause);
702
+ }, [emit]);
703
+ const zoomTo = useCallback((scale, anchor) => zoomBy("command", scale, anchor), [zoomBy]);
653
704
  const frame = useCallback((rect, pad) => {
654
- const { box: b, image: i, onView: report } = latestRef.current;
705
+ const { box: b, image: i } = latestRef.current;
655
706
  if (!(b.width > 0)) return;
656
- report(frameRect(b, i, rect, pad));
657
- }, []);
707
+ emit(frameRect(b, i, rect, pad), "command");
708
+ }, [emit]);
658
709
  useImperativeHandle(ref, () => ({
659
710
  frame,
660
711
  fit,
@@ -750,14 +801,17 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
750
801
  scale: effective.scale,
751
802
  tx: origin.tx + dx,
752
803
  ty: origin.ty + dy
753
- });
804
+ }, "gesture");
754
805
  };
755
806
  const endDrag = (event) => {
756
807
  const origin = dragRef.current;
757
808
  if (origin?.touch) return;
758
809
  dragRef.current = null;
759
810
  setPanning(false);
760
- if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
811
+ if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event, clientToImage({
812
+ x: event.clientX,
813
+ y: event.clientY
814
+ }));
761
815
  };
762
816
  const touchDown = (event) => {
763
817
  const touches = touchesRef.current;
@@ -816,7 +870,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
816
870
  commit(pinchView(pinch.view, pinch.distance, pinch.centre, Math.hypot(a.x - b.x, a.y - b.y), {
817
871
  x: mid.x - origin.x,
818
872
  y: mid.y - origin.y
819
- }, scaleRange(box, image, clamp)));
873
+ }, scaleRange(box, image, clamp)), "gesture");
820
874
  return;
821
875
  }
822
876
  const drag = dragRef.current;
@@ -832,7 +886,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
832
886
  scale: effective.scale,
833
887
  tx: drag.tx + dx,
834
888
  ty: drag.ty + dy
835
- });
889
+ }, "gesture");
836
890
  };
837
891
  const touchEnd = (event, cancelled) => {
838
892
  const touches = touchesRef.current;
@@ -860,21 +914,24 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
860
914
  dragRef.current = null;
861
915
  setPanning(false);
862
916
  if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
863
- if (!routePress(event)) onBackgroundClick?.(event);
917
+ if (!routePress(event)) onBackgroundClick?.(event, clientToImage({
918
+ x: event.clientX,
919
+ y: event.clientY
920
+ }));
864
921
  };
865
922
  const onDoubleClick = (event) => {
866
923
  if (!doubleClickFit || !(box.width > 0)) return;
867
924
  if (atFit) {
868
925
  const restore = previousRef.current;
869
- if (restore) onView(clampView(restore, box, image, clamp));
870
- else zoomTo(1, {
926
+ if (restore) emit(clampView(restore, box, image, clamp), "gesture");
927
+ else zoomBy("gesture", 1, {
871
928
  x: event.clientX,
872
929
  y: event.clientY
873
930
  });
874
931
  return;
875
932
  }
876
933
  previousRef.current = effective;
877
- onView(fitView(box, image, fitOpts));
934
+ emit(fitView(box, image, fitOpts), "gesture");
878
935
  };
879
936
  const onKeyDown = (event) => {
880
937
  if (!shortcuts || isTypingTarget(event.target)) return;
@@ -883,45 +940,45 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
883
940
  switch (event.key) {
884
941
  case "+":
885
942
  case "=":
886
- zoomTo(Math.min(max, effective.scale * 1.5));
943
+ zoomBy("key", Math.min(max, effective.scale * 1.5));
887
944
  break;
888
945
  case "-":
889
946
  case "_":
890
- zoomTo(Math.max(min, effective.scale / 1.5));
947
+ zoomBy("key", Math.max(min, effective.scale / 1.5));
891
948
  break;
892
949
  case "0":
893
- fit();
950
+ fitBy("key");
894
951
  break;
895
952
  case "1":
896
- zoomTo(1);
953
+ zoomBy("key", 1);
897
954
  break;
898
955
  case "ArrowLeft":
899
956
  if (!panKeys) return;
900
957
  commit({
901
958
  ...effective,
902
959
  tx: effective.tx + nudge
903
- });
960
+ }, "key");
904
961
  break;
905
962
  case "ArrowRight":
906
963
  if (!panKeys) return;
907
964
  commit({
908
965
  ...effective,
909
966
  tx: effective.tx - nudge
910
- });
967
+ }, "key");
911
968
  break;
912
969
  case "ArrowUp":
913
970
  if (!panKeys) return;
914
971
  commit({
915
972
  ...effective,
916
973
  ty: effective.ty + nudge
917
- });
974
+ }, "key");
918
975
  break;
919
976
  case "ArrowDown":
920
977
  if (!panKeys) return;
921
978
  commit({
922
979
  ...effective,
923
980
  ty: effective.ty - nudge
924
- });
981
+ }, "key");
925
982
  break;
926
983
  default: return;
927
984
  }
@@ -1306,14 +1363,45 @@ function useStageDrag() {
1306
1363
  *
1307
1364
  * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
1308
1365
  *
1366
+ * With `extent="viewport"` the surface also takes presses in the margin around the image, and
1367
+ * clamps every reported point to the image.
1368
+ *
1309
1369
  * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
1310
1370
  */
1311
- function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1371
+ function StageSurface({ onPress, cursor, onHover, onDoubleClick, extent = "image" }) {
1312
1372
  const stage = useStage();
1313
1373
  const start = useStageDrag();
1314
1374
  const [dragging, setDragging] = useState(false);
1315
1375
  const watchRef = useRef(null);
1316
1376
  useEffect(() => () => watchRef.current?.(), []);
1377
+ const viewport = extent === "viewport";
1378
+ const pointAt = (client) => {
1379
+ const p = stage.toImage(client);
1380
+ return viewport ? clampToImage(p, stage.image) : p;
1381
+ };
1382
+ const target = (() => {
1383
+ const { image, view, box } = stage;
1384
+ if (!viewport || !(box.width > 0)) return {
1385
+ x: -.5,
1386
+ y: -.5,
1387
+ width: image.width,
1388
+ height: image.height
1389
+ };
1390
+ const a = toImage(view, {
1391
+ x: 0,
1392
+ y: 0
1393
+ });
1394
+ const b = toImage(view, {
1395
+ x: box.width,
1396
+ y: box.height
1397
+ });
1398
+ return {
1399
+ x: a.x,
1400
+ y: a.y,
1401
+ width: b.x - a.x,
1402
+ height: b.y - a.y
1403
+ };
1404
+ })();
1317
1405
  const onPointerDown = (event) => {
1318
1406
  const touch = event.pointerType === "touch";
1319
1407
  if (stage.panMode || !touch && event.button !== 0) return;
@@ -1323,7 +1411,7 @@ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1323
1411
  y: event.clientY
1324
1412
  };
1325
1413
  const drag = onPress({
1326
- point: stage.toImage(client),
1414
+ point: pointAt(client),
1327
1415
  client,
1328
1416
  touch,
1329
1417
  radius: hitRadiusPx(event.pointerType),
@@ -1340,13 +1428,13 @@ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1340
1428
  finish();
1341
1429
  };
1342
1430
  watchRef.current = watchTouch(event, {
1343
- onMove: (e) => drag.onMove?.(stage.toImage({
1431
+ onMove: (e) => drag.onMove?.(pointAt({
1344
1432
  x: e.clientX,
1345
1433
  y: e.clientY
1346
1434
  }), e),
1347
1435
  onEnd: (e, moved) => {
1348
1436
  release();
1349
- drag.onEnd?.(stage.toImage({
1437
+ drag.onEnd?.(pointAt({
1350
1438
  x: e.clientX,
1351
1439
  y: e.clientY
1352
1440
  }), e, moved);
@@ -1359,10 +1447,10 @@ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1359
1447
  return;
1360
1448
  }
1361
1449
  start(event, {
1362
- onMove: drag.onMove,
1450
+ onMove: drag.onMove && ((point, e) => drag.onMove?.(viewport ? clampToImage(point, stage.image) : point, e)),
1363
1451
  onEnd: (point, e, moved) => {
1364
1452
  finish();
1365
- drag.onEnd?.(point, e, moved);
1453
+ drag.onEnd?.(viewport ? clampToImage(point, stage.image) : point, e, moved);
1366
1454
  },
1367
1455
  onCancel: () => {
1368
1456
  finish();
@@ -1372,21 +1460,21 @@ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1372
1460
  };
1373
1461
  return /* @__PURE__ */ jsx("svg", {
1374
1462
  viewBox: imageViewBox(stage.image),
1375
- className: "pointer-events-none absolute inset-0 h-full w-full",
1463
+ className: cn("pointer-events-none absolute inset-0 h-full w-full", viewport && "overflow-visible"),
1376
1464
  "data-dragging": dragging ? "" : void 0,
1377
1465
  "aria-hidden": true,
1378
1466
  children: /* @__PURE__ */ jsx("rect", {
1379
1467
  "data-stage-surface": "",
1380
- x: -.5,
1381
- y: -.5,
1382
- width: stage.image.width,
1383
- height: stage.image.height,
1468
+ x: target.x,
1469
+ y: target.y,
1470
+ width: target.width,
1471
+ height: target.height,
1384
1472
  fill: "transparent",
1385
1473
  className: "pointer-events-auto",
1386
1474
  style: { cursor: stage.panMode ? void 0 : cursor },
1387
1475
  onPointerDown,
1388
1476
  onPointerMove: (event) => {
1389
- if (!dragging && event.pointerType !== "touch") onHover?.(stage.toImage({
1477
+ if (!dragging && event.pointerType !== "touch") onHover?.(pointAt({
1390
1478
  x: event.clientX,
1391
1479
  y: event.clientY
1392
1480
  }));
@@ -1394,7 +1482,7 @@ function StageSurface({ onPress, cursor, onHover, onDoubleClick }) {
1394
1482
  onDoubleClick: (event) => {
1395
1483
  if (!onDoubleClick) return;
1396
1484
  event.stopPropagation();
1397
- onDoubleClick(stage.toImage({
1485
+ onDoubleClick(pointAt({
1398
1486
  x: event.clientX,
1399
1487
  y: event.clientY
1400
1488
  }));
@@ -2728,7 +2816,7 @@ function nearestContourSegment(points, point) {
2728
2816
  return nearest;
2729
2817
  }
2730
2818
  /** Edit contour vertices over an ImageStage using its shared source-image transform. */
2731
- function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)" }) {
2819
+ function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)", bounds }) {
2732
2820
  const stage = useStage();
2733
2821
  const draggingRef = useRef(null);
2734
2822
  const movedRef = useRef(false);
@@ -2737,9 +2825,15 @@ function ContourEditor({ points, onChange, onCommit, editable = false, label = "
2737
2825
  const radius = stage.imageLength(5);
2738
2826
  const hairline = stage.imageLength(1.5);
2739
2827
  function clamp(point) {
2828
+ const area = bounds ?? {
2829
+ x: 0,
2830
+ y: 0,
2831
+ width: stage.image.width - 1,
2832
+ height: stage.image.height - 1
2833
+ };
2740
2834
  return {
2741
- x: Math.max(0, Math.min(stage.image.width - 1, point.x)),
2742
- y: Math.max(0, Math.min(stage.image.height - 1, point.y))
2835
+ x: Math.max(area.x, Math.min(area.x + area.width, point.x)),
2836
+ y: Math.max(area.y, Math.min(area.y + area.height, point.y))
2743
2837
  };
2744
2838
  }
2745
2839
  /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */
@@ -3060,8 +3154,8 @@ const HALO$7 = overlayRole("halo");
3060
3154
  function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw = false, bounds, minSize = 4, label = "Region", stroke = overlayRole("selection") }) {
3061
3155
  const stage = useStage();
3062
3156
  const area = bounds ?? {
3063
- x: 0,
3064
- y: 0,
3157
+ x: -.5,
3158
+ y: -.5,
3065
3159
  width: stage.image.width,
3066
3160
  height: stage.image.height
3067
3161
  };
@@ -3934,7 +4028,7 @@ function useLabelIndices({ enabled, xy, labelled, forced }) {
3934
4028
  * Many points over the image, hoverable and selectable: detected corners, ring centres,
3935
4029
  * keypoints, labelled landmarks.
3936
4030
  *
3937
- * Drawn as a handful of batched paths, one per (state, style, marker kind), never one element
4031
+ * Drawn as a handful of batched paths, one per (state, style, colour, marker kind), never one element
3938
4032
  * per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the
3939
4033
  * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
3940
4034
  * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
@@ -4010,6 +4104,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
4010
4104
  key,
4011
4105
  shape,
4012
4106
  role: "selection",
4107
+ color: void 0,
4013
4108
  dim: false,
4014
4109
  indices: [],
4015
4110
  cache: null
@@ -4021,13 +4116,15 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
4021
4116
  }
4022
4117
  const role = item.role ?? shape.role ?? "feature";
4023
4118
  const dim = isDimmed(item.id);
4024
- const key = `${dim ? 1 : 0}|${role}|${kindName}`;
4119
+ const color = item.color || void 0;
4120
+ const key = `${dim ? 1 : 0}|${role}|${kindName}${color ? `|${color}` : ""}`;
4025
4121
  let batch = normal.get(key);
4026
4122
  if (!batch) {
4027
4123
  batch = {
4028
4124
  key,
4029
4125
  shape,
4030
4126
  role,
4127
+ color,
4031
4128
  dim,
4032
4129
  indices: [],
4033
4130
  cache: null
@@ -4126,7 +4223,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
4126
4223
  paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
4127
4224
  "data-batch": batch.key,
4128
4225
  d,
4129
- stroke: overlayRole(batch.role),
4226
+ stroke: batch.color ?? overlayRole(batch.role),
4130
4227
  strokeWidth: widthOf(batch.shape, batch.role, "default"),
4131
4228
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1
4132
4229
  }, batch.key)),
@@ -4159,7 +4256,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
4159
4256
  }), /* @__PURE__ */ jsx("path", {
4160
4257
  "data-hovered-point": "",
4161
4258
  d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2),
4162
- stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
4259
+ stroke: hoverSelected ? selectionStroke : hoverItem?.color || overlayRole(hoverRole),
4163
4260
  strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
4164
4261
  })] })
4165
4262
  ]
@@ -4534,12 +4631,98 @@ function polygonTouchesRect(points, rect) {
4534
4631
  return pointInPolygon(points, rect.x, rect.y);
4535
4632
  }
4536
4633
  //#endregion
4634
+ //#region src/components/areaBatching.ts
4635
+ /**
4636
+ * How `AreaSet` groups its regions into batched paths: by appearance (state, role, colours),
4637
+ * either one batch per appearance or consecutive runs in item order. Pure, so the keys are
4638
+ * unit-tested without a DOM (ADR-0004 rule 1).
4639
+ */
4640
+ /**
4641
+ * The appearance key of an item. Without a custom colour it is `dim|role`, as before colours
4642
+ * existed; a custom colour appends the outline and fill it was given.
4643
+ *
4644
+ * @param dim - Whether the item is dimmed.
4645
+ * @param role - The item's role.
4646
+ * @param stroke - The outline colour, if any.
4647
+ * @param fill - The fill colour, if any.
4648
+ * @returns The key.
4649
+ */
4650
+ function areaBatchKey(dim, role, stroke, fill) {
4651
+ const base = `${dim ? 1 : 0}|${role}`;
4652
+ return stroke || fill ? `${base}|${stroke ?? ""}|${fill ?? ""}` : base;
4653
+ }
4654
+ /**
4655
+ * Groups items into batches. Selected items go to `picked` (drawn on top in the selection
4656
+ * colour), unless `selectionFill` is `"item"`: then they stay in their batch for the fill and
4657
+ * `picked` carries only their outlines.
4658
+ *
4659
+ * @param items - The regions.
4660
+ * @param options - What decides the grouping.
4661
+ * @returns The appearance batches in paint order, and the selected overlay.
4662
+ */
4663
+ function batchAreas(items, options) {
4664
+ const { role, stroke, paintOrder, fillRule, selectionFill, selected, isDimmed } = options;
4665
+ const keepSelected = selectionFill === "item";
4666
+ const separate = fillRule === "evenodd" || keepSelected;
4667
+ const byKey = /* @__PURE__ */ new Map();
4668
+ const runs = [];
4669
+ const picked = {
4670
+ key: "selected",
4671
+ id: "selected",
4672
+ role: "selection",
4673
+ stroke: void 0,
4674
+ fill: void 0,
4675
+ dim: false,
4676
+ indices: [],
4677
+ d: "",
4678
+ fills: fillRule === "evenodd" && !keepSelected ? [] : null
4679
+ };
4680
+ items.forEach((item, i) => {
4681
+ const isSelected = selected.has(item.id);
4682
+ if (isSelected) {
4683
+ const d = areaPath(item.points);
4684
+ picked.indices.push(i);
4685
+ picked.d += d;
4686
+ picked.fills?.push(d);
4687
+ if (!keepSelected) return;
4688
+ }
4689
+ const itemRole = item.role ?? role;
4690
+ const itemStroke = item.stroke ?? stroke;
4691
+ const dim = isDimmed(item.id);
4692
+ const key = areaBatchKey(dim, itemRole, itemStroke, item.fill);
4693
+ let batch = paintOrder === "items" ? runs[runs.length - 1] : byKey.get(key);
4694
+ if (!batch || batch.key !== key) {
4695
+ batch = {
4696
+ key,
4697
+ id: paintOrder === "items" ? `${key}#${runs.length}` : key,
4698
+ role: itemRole,
4699
+ stroke: itemStroke,
4700
+ fill: item.fill,
4701
+ dim,
4702
+ indices: [],
4703
+ d: "",
4704
+ fills: separate ? [] : null
4705
+ };
4706
+ byKey.set(key, batch);
4707
+ runs.push(batch);
4708
+ }
4709
+ const d = areaPath(item.points);
4710
+ batch.indices.push(i);
4711
+ batch.fills?.push(d);
4712
+ if (!(isSelected && keepSelected)) batch.d += d;
4713
+ });
4714
+ return {
4715
+ normal: runs,
4716
+ picked: picked.indices.length > 0 ? picked : null
4717
+ };
4718
+ }
4719
+ //#endregion
4537
4720
  //#region src/components/AreaSet.tsx
4538
4721
  /**
4539
4722
  * Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,
4540
4723
  * region annotations, defect outlines.
4541
4724
  *
4542
- * Drawn as a handful of batched paths, one per (state, role), each outline with its 12 % fill
4725
+ * Drawn as a handful of batched paths, one per (state, role, colours), each outline with its 12 % fill
4543
4726
  * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the
4544
4727
  * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
4545
4728
  * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
@@ -4553,7 +4736,8 @@ const TICK_PX = 8;
4553
4736
  /**
4554
4737
  * A selectable set of closed regions inside an `ImageStage`.
4555
4738
  *
4556
- * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default).
4739
+ * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default) or its own
4740
+ * `stroke` / `fill` colours (`fillOpacity`, `fillRule`, `paintOrder` and `selectionFill` tune the fill).
4557
4741
  * Rings are wound alike before they are batched, so overlapping regions never cut a hole in
4558
4742
  * each other.
4559
4743
  * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and
@@ -4567,7 +4751,7 @@ const TICK_PX = 8;
4567
4751
  *
4568
4752
  * The SVG carries `data-hovered` (the hovered id).
4569
4753
  */
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" }) {
4754
+ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, labels = true, firstVertexTick = false, stroke, fillOpacity = FILL_OPACITY, fillRule = "nonzero", paintOrder = "appearance", selectionFill = "selection", halo = true, selectionStroke = overlayRole("selection"), layerId, priority = STAGE_HIT_PRIORITY.area, label = "Areas" }) {
4571
4755
  const stage = useStage();
4572
4756
  const px = useScreenPx();
4573
4757
  const unit = px(1);
@@ -4597,53 +4781,35 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4597
4781
  },
4598
4782
  onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
4599
4783
  });
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
- }, [
4784
+ const groups = useMemo(() => batchAreas(items, {
4785
+ role,
4786
+ stroke,
4787
+ paintOrder,
4788
+ fillRule,
4789
+ selectionFill,
4790
+ selected: selectedSet,
4791
+ isDimmed
4792
+ }), [
4637
4793
  items,
4638
4794
  role,
4795
+ stroke,
4796
+ paintOrder,
4797
+ fillRule,
4798
+ selectionFill,
4639
4799
  selectedSet,
4640
4800
  isDimmed
4641
4801
  ]);
4802
+ const keepFill = selectionFill === "item";
4803
+ const evenOdd = fillRule === "evenodd";
4804
+ const separate = evenOdd || keepFill;
4642
4805
  const ticks = useMemo(() => {
4643
4806
  if (!firstVertexTick) return [];
4644
4807
  return (groups.picked ? [...groups.normal, groups.picked] : groups.normal).map((batch) => {
4645
4808
  let d = "";
4646
- for (const i of batch.indices) d += tickPath(items[i].points, TICK_PX * unit);
4809
+ for (const i of batch.indices) {
4810
+ if (keepFill && batch !== groups.picked && selectedSet.has(items[i].id)) continue;
4811
+ d += tickPath(items[i].points, TICK_PX * unit);
4812
+ }
4647
4813
  return {
4648
4814
  batch,
4649
4815
  d
@@ -4653,11 +4819,14 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4653
4819
  firstVertexTick,
4654
4820
  groups,
4655
4821
  items,
4656
- unit
4822
+ unit,
4823
+ keepFill,
4824
+ selectedSet
4657
4825
  ]);
4658
4826
  const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
4659
4827
  const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
4660
4828
  const hoverRole = hoverItem?.role ?? role;
4829
+ const hoverStroke = hoverItem ? hoverItem.stroke ?? stroke ?? overlayRole(hoverRole) : void 0;
4661
4830
  const anchors = useMemo(() => {
4662
4831
  const xy = new Float64Array(items.length * 2);
4663
4832
  const labelled = [];
@@ -4696,6 +4865,20 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4696
4865
  const thin = itemRole === "model" || itemRole === "structure";
4697
4866
  return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
4698
4867
  };
4868
+ const strokeOf = (batch) => batch.stroke ?? overlayRole(batch.role);
4869
+ /** Each region's fill as its own even-odd path, or all of them as one path. */
4870
+ const fillPaths = (batch, colour, tag) => evenOdd ? batch.fills.map((d, k) => /* @__PURE__ */ jsx("path", {
4871
+ "data-fill": tag,
4872
+ d,
4873
+ fill: colour,
4874
+ fillOpacity,
4875
+ fillRule: "evenodd"
4876
+ }, batch.indices[k])) : /* @__PURE__ */ jsx("path", {
4877
+ "data-fill": tag,
4878
+ d: batch.fills.join(""),
4879
+ fill: colour,
4880
+ fillOpacity
4881
+ });
4699
4882
  return /* @__PURE__ */ jsxs("svg", {
4700
4883
  viewBox: imageViewBox(stage.image),
4701
4884
  className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
@@ -4709,32 +4892,40 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4709
4892
  children: [
4710
4893
  groups.normal.map((batch) => /* @__PURE__ */ jsxs("g", {
4711
4894
  opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
4712
- children: [halo && /* @__PURE__ */ jsx("path", {
4713
- d: batch.d,
4895
+ children: [
4896
+ halo && (!separate || batch.d !== "") && /* @__PURE__ */ jsx("path", {
4897
+ d: batch.d,
4898
+ stroke: HALO$4,
4899
+ strokeWidth: widthOf(batch.role, "default") + px(2),
4900
+ opacity: .6
4901
+ }),
4902
+ separate && fillPaths(batch, batch.fill ?? strokeOf(batch), batch.key),
4903
+ (!separate || batch.d !== "") && /* @__PURE__ */ jsx("path", {
4904
+ "data-batch": batch.key,
4905
+ d: batch.d,
4906
+ fill: separate ? void 0 : batch.fill ?? strokeOf(batch),
4907
+ fillOpacity: separate ? void 0 : fillOpacity,
4908
+ stroke: strokeOf(batch),
4909
+ strokeWidth: widthOf(batch.role, "default")
4910
+ })
4911
+ ]
4912
+ }, batch.id)),
4913
+ groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [
4914
+ halo && /* @__PURE__ */ jsx("path", {
4915
+ d: groups.picked.d,
4714
4916
  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
- })] }),
4917
+ strokeWidth: widthOf("selection", "selected") + px(2)
4918
+ }),
4919
+ evenOdd && !keepFill && fillPaths(groups.picked, selectionStroke, "selected"),
4920
+ /* @__PURE__ */ jsx("path", {
4921
+ "data-selected-areas": "",
4922
+ d: groups.picked.d,
4923
+ fill: evenOdd || keepFill ? void 0 : selectionStroke,
4924
+ fillOpacity: evenOdd || keepFill ? void 0 : fillOpacity,
4925
+ stroke: selectionStroke,
4926
+ strokeWidth: widthOf("selection", "selected")
4927
+ })
4928
+ ] }),
4738
4929
  hoverItem && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
4739
4930
  d: areaPath(hoverItem.points),
4740
4931
  stroke: HALO$4,
@@ -4742,7 +4933,7 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4742
4933
  }), /* @__PURE__ */ jsx("path", {
4743
4934
  "data-hovered-area": "",
4744
4935
  d: areaPath(hoverItem.points),
4745
- stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
4936
+ stroke: hoverSelected ? selectionStroke : hoverStroke,
4746
4937
  strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover")
4747
4938
  })] }),
4748
4939
  ticks.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
@@ -4755,10 +4946,10 @@ function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedId
4755
4946
  }), /* @__PURE__ */ jsx("path", {
4756
4947
  "data-ticks": batch.key,
4757
4948
  d,
4758
- stroke: batch === groups.picked ? selectionStroke : overlayRole(batch.role),
4949
+ stroke: batch === groups.picked ? selectionStroke : strokeOf(batch),
4759
4950
  strokeWidth: px(OVERLAY_STATE_WIDTH.selected)
4760
4951
  })]
4761
- }, `tick|${batch.key}`))
4952
+ }, `tick|${batch.id}`))
4762
4953
  ]
4763
4954
  }), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
4764
4955
  "data-labels": "",
@@ -6284,15 +6475,20 @@ const VERTEX_PX = 6;
6284
6475
  * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by
6285
6476
  * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline
6286
6477
  * 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
6478
+ * shows, fainter, the segment that would close it; with `closing` the first vertex gets a
6479
+ * ring and that segment turns solid and full strength: "click here to close". A `stroke`
6480
+ * (brush trail) is a translucent band of its own width with round caps and joins and no
6481
+ * dashes, and a `brush` is a footprint ring: a dark ring under a light one, so it reads on
6482
+ * any image. `points` may be a typed-array view that changes identity every move: the draft
6483
+ * is rebuilt in one O(n) pass per render, with no per-vertex elements. It takes no pointer events and is hidden
6288
6484
  * from assistive technology: it is transient feedback for a gesture.
6289
6485
  *
6290
6486
  * The SVG carries `data-draft` (the shape's kind).
6291
6487
  */
6292
- function DraftShape({ shape, role = "selection", halo = true }) {
6488
+ function DraftShape({ shape, role = "selection", stroke, halo = true }) {
6293
6489
  const stage = useStage();
6294
6490
  const px = useScreenPx();
6295
- const colour = overlayRole(role);
6491
+ const colour = stroke ?? overlayRole(role);
6296
6492
  const dash = `${px(DASH)} ${px(GAP)}`;
6297
6493
  const width = px(STROKE_PX);
6298
6494
  const parts = shape ? draftParts(shape, px(1)) : null;
@@ -6325,13 +6521,40 @@ function DraftShape({ shape, role = "selection", halo = true }) {
6325
6521
  strokeWidth: width,
6326
6522
  strokeDasharray: dash
6327
6523
  }),
6524
+ parts.trail && /* @__PURE__ */ jsx("path", {
6525
+ "data-draft-stroke": "",
6526
+ d: parts.trail.d,
6527
+ stroke: colour,
6528
+ strokeWidth: Math.max(parts.trail.width, px(1)),
6529
+ opacity: .4
6530
+ }),
6531
+ parts.footprint && halo && /* @__PURE__ */ jsx("path", {
6532
+ d: parts.footprint,
6533
+ stroke: HALO,
6534
+ strokeWidth: px(3.5),
6535
+ opacity: .6
6536
+ }),
6537
+ parts.footprint && /* @__PURE__ */ jsx("path", {
6538
+ "data-draft-brush": "",
6539
+ d: parts.footprint,
6540
+ stroke: colour,
6541
+ strokeWidth: px(1.5)
6542
+ }),
6328
6543
  parts.closing && /* @__PURE__ */ jsx("path", {
6329
6544
  "data-draft-closing": "",
6330
6545
  d: parts.closing,
6331
6546
  stroke: colour,
6332
- strokeWidth: px(1),
6333
- strokeDasharray: dash,
6334
- opacity: .5
6547
+ strokeWidth: parts.armed ? width : px(1),
6548
+ strokeDasharray: parts.armed ? void 0 : dash,
6549
+ opacity: parts.armed ? 1 : .5
6550
+ }),
6551
+ parts.first && /* @__PURE__ */ jsx("path", {
6552
+ "data-draft-first": "",
6553
+ d: parts.first,
6554
+ stroke: colour,
6555
+ strokeWidth: width,
6556
+ fill: colour,
6557
+ fillOpacity: .35
6335
6558
  }),
6336
6559
  parts.vertices && /* @__PURE__ */ jsx("path", {
6337
6560
  "data-draft-vertices": "",
@@ -6343,6 +6566,16 @@ function DraftShape({ shape, role = "selection", halo = true }) {
6343
6566
  })
6344
6567
  });
6345
6568
  }
6569
+ const NONE = {
6570
+ outline: null,
6571
+ region: false,
6572
+ closing: null,
6573
+ vertices: null,
6574
+ armed: false,
6575
+ first: null,
6576
+ trail: null,
6577
+ footprint: null
6578
+ };
6346
6579
  /** An ellipse with the given centre and radii as two arcs. */
6347
6580
  function ellipsePath$1(cx, cy, rx, ry) {
6348
6581
  return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
@@ -6350,36 +6583,45 @@ function ellipsePath$1(cx, cy, rx, ry) {
6350
6583
  function draftParts(shape, unit) {
6351
6584
  switch (shape.kind) {
6352
6585
  case "point": return {
6586
+ ...NONE,
6353
6587
  outline: ellipsePath$1(shape.x, shape.y, 8 * unit, 8 * unit),
6354
- region: false,
6355
- closing: null,
6356
6588
  vertices: `M${shape.x} ${shape.y}h0`
6357
6589
  };
6358
6590
  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
6591
+ ...NONE,
6592
+ outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`
6363
6593
  };
6364
6594
  case "rect":
6365
6595
  case "ellipse": {
6366
6596
  const box = rectFromCorners(shape.from, shape.to);
6597
+ const outline = shape.kind === "rect" ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z` : ellipsePath$1(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2);
6598
+ return {
6599
+ ...NONE,
6600
+ outline,
6601
+ region: true
6602
+ };
6603
+ }
6604
+ case "brush": return {
6605
+ ...NONE,
6606
+ footprint: ellipsePath$1(shape.x, shape.y, Math.max(shape.diameter, 2 * unit) / 2, Math.max(shape.diameter, 2 * unit) / 2)
6607
+ };
6608
+ case "stroke": {
6609
+ const n = Math.floor(shape.points.length / 2);
6610
+ if (n === 0) return NONE;
6611
+ let d = "";
6612
+ for (let i = 0; i < n; i++) d += `${i === 0 ? "M" : "L"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;
6367
6613
  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
6614
+ ...NONE,
6615
+ trail: {
6616
+ d: n === 1 ? `${d}h0` : d,
6617
+ width: shape.width
6618
+ }
6372
6619
  };
6373
6620
  }
6374
6621
  case "polyline":
6375
6622
  case "polygon": {
6376
6623
  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
- };
6624
+ if (n === 0) return NONE;
6383
6625
  let outline = "";
6384
6626
  let vertices = "";
6385
6627
  for (let i = 0; i < n; i++) {
@@ -6388,11 +6630,18 @@ function draftParts(shape, unit) {
6388
6630
  }
6389
6631
  if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;
6390
6632
  const polygon = shape.kind === "polygon";
6633
+ const armed = polygon && shape.closing === true && n >= 2;
6634
+ let closing = null;
6635
+ if (armed) closing = `M${shape.points[2 * n - 2]} ${shape.points[2 * n - 1]}L${shape.points[0]} ${shape.points[1]}`;
6636
+ else if (polygon && shape.cursor) closing = `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}`;
6391
6637
  return {
6638
+ ...NONE,
6392
6639
  outline,
6393
6640
  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
6641
+ closing,
6642
+ vertices,
6643
+ armed,
6644
+ first: armed ? ellipsePath$1(shape.points[0], shape.points[1], 5 * unit, 5 * unit) : null
6396
6645
  };
6397
6646
  }
6398
6647
  }
@@ -6539,7 +6788,11 @@ function paintMask(mask, width, height, from, to, radius, value) {
6539
6788
  }
6540
6789
  return next;
6541
6790
  }
6542
- /** Render and edit a binary raster mask within the enclosing ImageStage. */
6791
+ /**
6792
+ * Render and edit a binary raster mask within the enclosing ImageStage. While editing, a
6793
+ * `DraftShape` brush footprint (a circle of the brush's diameter) follows the mouse or pen
6794
+ * pointer, and the keyboard brush while the layer has keyboard focus.
6795
+ */
6543
6796
  function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = "paint", label = "Mask brush", color = [
6544
6797
  0,
6545
6798
  190,
@@ -6552,6 +6805,7 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
6552
6805
  const lastRef = useRef(null);
6553
6806
  const cursorRef = useRef(null);
6554
6807
  const [brush, setBrush] = useState(null);
6808
+ const [hover, setHover] = useState(null);
6555
6809
  function cursor() {
6556
6810
  return cursorRef.current ?? {
6557
6811
  x: Math.floor(stage.image.width / 2),
@@ -6588,15 +6842,26 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
6588
6842
  lastRef.current = point;
6589
6843
  cursorRef.current = point;
6590
6844
  setBrush(null);
6845
+ if (event.pointerType !== "touch") setHover(point);
6591
6846
  apply(point, point);
6592
6847
  }
6593
6848
  function move(event) {
6594
- if (!lastRef.current) return;
6849
+ if (!lastRef.current) {
6850
+ if (editable && !stage.panMode && event.pointerType !== "touch") {
6851
+ setHover(stage.toImage({
6852
+ x: event.clientX,
6853
+ y: event.clientY
6854
+ }));
6855
+ setBrush(null);
6856
+ }
6857
+ return;
6858
+ }
6595
6859
  event.stopPropagation();
6596
6860
  const point = stage.toImage({
6597
6861
  x: event.clientX,
6598
6862
  y: event.clientY
6599
6863
  });
6864
+ if (event.pointerType !== "touch") setHover(point);
6600
6865
  apply(lastRef.current, point);
6601
6866
  lastRef.current = point;
6602
6867
  cursorRef.current = point;
@@ -6605,6 +6870,7 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
6605
6870
  if (!lastRef.current) return;
6606
6871
  event.stopPropagation();
6607
6872
  lastRef.current = null;
6873
+ if (event.pointerType === "touch") setHover(null);
6608
6874
  onCommit?.();
6609
6875
  }
6610
6876
  function keyDown(event) {
@@ -6636,12 +6902,14 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
6636
6902
  y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y))
6637
6903
  };
6638
6904
  setBrush(cursorRef.current);
6905
+ setHover(null);
6639
6906
  } else if (event.key === "Enter") {
6640
6907
  event.preventDefault();
6641
6908
  event.stopPropagation();
6642
6909
  const at = cursor();
6643
6910
  draftRef.current = mask;
6644
6911
  setBrush(at);
6912
+ setHover(null);
6645
6913
  apply(at, at);
6646
6914
  onCommit?.();
6647
6915
  }
@@ -6668,22 +6936,21 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
6668
6936
  },
6669
6937
  onKeyDown: keyDown,
6670
6938
  onFocus: focus,
6671
- onBlur: () => setBrush(null)
6672
- }), brush && /* @__PURE__ */ jsx("svg", {
6673
- viewBox: imageViewBox(stage.image),
6674
- className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
6675
- "aria-hidden": "true",
6676
- children: /* @__PURE__ */ jsx("circle", {
6677
- cx: brush.x,
6678
- cy: brush.y,
6679
- r: Math.max(.75, brushRadius),
6680
- fill: "none",
6681
- stroke: "var(--signal)",
6682
- strokeWidth: stage.imageLength(1.5)
6683
- })
6939
+ onBlur: () => setBrush(null),
6940
+ onPointerLeave: () => {
6941
+ if (!lastRef.current) setHover(null);
6942
+ }
6943
+ }), (hover ?? brush) && editable && /* @__PURE__ */ jsx(DraftShape, {
6944
+ shape: {
6945
+ kind: "brush",
6946
+ x: (hover ?? brush).x,
6947
+ y: (hover ?? brush).y,
6948
+ diameter: 2 * Math.max(.75, brushRadius)
6949
+ },
6950
+ stroke: "var(--signal)"
6684
6951
  })] });
6685
6952
  }
6686
6953
  //#endregion
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 };
6954
+ export { AreaSet, ContourEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampToImage, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestPoint, nearestPolyline, normalizeAngle, overlayRole, paintMask, planeRange, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
6688
6955
 
6689
6956
  //# sourceMappingURL=index.js.map