@vitavision/stage2d 0.8.1 → 0.10.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/README.md +41 -0
- package/dist/index.d.ts +1083 -3
- package/dist/index.js +2815 -68
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/AreaSet.tsx +312 -0
- package/src/components/DraftShape.tsx +175 -0
- package/src/components/GridLayer.tsx +209 -0
- package/src/components/HeatmapLayer.tsx +211 -0
- package/src/components/PointSet.tsx +366 -0
- package/src/components/PolylineSet.tsx +39 -0
- package/src/components/ShapeEditor.tsx +290 -0
- package/src/components/areaIndex.ts +361 -0
- package/src/components/gridEdges.ts +70 -0
- package/src/components/heatmapRaster.ts +84 -0
- package/src/components/labelLod.ts +90 -0
- package/src/components/markerShapes.ts +119 -0
- package/src/components/pointIndex.ts +320 -0
- package/src/components/polylineIndex.ts +4 -3
- package/src/components/shapeEdit.ts +232 -0
- package/src/components/stage/ImageStage.tsx +264 -59
- package/src/components/stage/gesture.ts +81 -0
- package/src/components/stage/hitContext.ts +16 -0
- package/src/components/stage/hitTest.ts +181 -0
- package/src/components/stage/useStageHitTest.ts +127 -0
- package/src/components/useShapeDrag.ts +104 -0
- package/src/index.ts +96 -0
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.
|
|
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__ */
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
className: "pointer-events-
|
|
613
|
-
children:
|
|
614
|
-
}),
|
|
615
|
-
|
|
616
|
-
className: "
|
|
617
|
-
children:
|
|
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.
|
|
@@ -1857,6 +2220,7 @@ function polylineBounds(points) {
|
|
|
1857
2220
|
height: maxY - minY
|
|
1858
2221
|
};
|
|
1859
2222
|
}
|
|
2223
|
+
/** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */
|
|
1860
2224
|
function closestOnSegment(p, ax, ay, bx, by) {
|
|
1861
2225
|
const dx = bx - ax;
|
|
1862
2226
|
const dy = by - ay;
|
|
@@ -1867,7 +2231,7 @@ function closestOnSegment(p, ax, ay, bx, by) {
|
|
|
1867
2231
|
y: ay + t * dy
|
|
1868
2232
|
};
|
|
1869
2233
|
}
|
|
1870
|
-
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
|
|
2234
|
+
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). Shared with `areaIndex.ts`. */
|
|
1871
2235
|
function segmentTouchesRect(ax, ay, bx, by, r) {
|
|
1872
2236
|
const xmin = r.x;
|
|
1873
2237
|
const xmax = r.x + r.width;
|
|
@@ -2495,10 +2859,10 @@ function clamp(value, low, high) {
|
|
|
2495
2859
|
* inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.
|
|
2496
2860
|
*/
|
|
2497
2861
|
/** Handle square side, in screen pixels. */
|
|
2498
|
-
const HANDLE_PX = 9;
|
|
2862
|
+
const HANDLE_PX$1 = 9;
|
|
2499
2863
|
/** Outline width, in screen pixels. */
|
|
2500
|
-
const STROKE_PX = 1.5;
|
|
2501
|
-
const HALO$
|
|
2864
|
+
const STROKE_PX$2 = 1.5;
|
|
2865
|
+
const HALO$6 = overlayRole("halo");
|
|
2502
2866
|
/**
|
|
2503
2867
|
* An editable axis-aligned region inside an `ImageStage`.
|
|
2504
2868
|
*
|
|
@@ -2609,7 +2973,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
|
|
|
2609
2973
|
width: shown.width,
|
|
2610
2974
|
height: shown.height,
|
|
2611
2975
|
fill: "none",
|
|
2612
|
-
stroke: HALO$
|
|
2976
|
+
stroke: HALO$6,
|
|
2613
2977
|
strokeWidth: px(3.5)
|
|
2614
2978
|
}), /* @__PURE__ */ jsx("rect", {
|
|
2615
2979
|
x: shown.x,
|
|
@@ -2619,7 +2983,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
|
|
|
2619
2983
|
fill: stroke,
|
|
2620
2984
|
fillOpacity: .06,
|
|
2621
2985
|
stroke,
|
|
2622
|
-
strokeWidth: px(STROKE_PX),
|
|
2986
|
+
strokeWidth: px(STROKE_PX$2),
|
|
2623
2987
|
strokeDasharray: `${px(6)} ${px(4)}`
|
|
2624
2988
|
})] });
|
|
2625
2989
|
return /* @__PURE__ */ jsxs("svg", {
|
|
@@ -2657,7 +3021,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
|
|
|
2657
3021
|
fill: "transparent",
|
|
2658
3022
|
role: "button",
|
|
2659
3023
|
tabIndex: 0,
|
|
2660
|
-
"aria-label": `${label}: ${fmt(value.x)}, ${fmt(value.y)}, ${fmt(value.width)} × ${fmt(value.height)} px`,
|
|
3024
|
+
"aria-label": `${label}: ${fmt$1(value.x)}, ${fmt$1(value.y)}, ${fmt$1(value.width)} × ${fmt$1(value.height)} px`,
|
|
2661
3025
|
"aria-roledescription": "region",
|
|
2662
3026
|
className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
|
|
2663
3027
|
onPointerDown: (event) => begin(event, {
|
|
@@ -2677,7 +3041,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
|
|
|
2677
3041
|
}),
|
|
2678
3042
|
editable && value && !drawing && ROI_HANDLES.map((handle) => {
|
|
2679
3043
|
const centre = roiHandlePoint(value, handle);
|
|
2680
|
-
const size = px(HANDLE_PX);
|
|
3044
|
+
const size = px(HANDLE_PX$1);
|
|
2681
3045
|
return /* @__PURE__ */ jsx("rect", {
|
|
2682
3046
|
"data-handle": handle,
|
|
2683
3047
|
x: centre.x - size / 2,
|
|
@@ -2685,7 +3049,7 @@ function RectRoiEditor({ value, onValueChange, onCommit, editable = true, draw =
|
|
|
2685
3049
|
width: size,
|
|
2686
3050
|
height: size,
|
|
2687
3051
|
fill: stroke,
|
|
2688
|
-
stroke: HALO$
|
|
3052
|
+
stroke: HALO$6,
|
|
2689
3053
|
strokeWidth: px(1),
|
|
2690
3054
|
className: "pointer-events-auto",
|
|
2691
3055
|
style: { cursor: ROI_HANDLE_CURSOR[handle] },
|
|
@@ -2710,7 +3074,7 @@ function clampPoint(p, area) {
|
|
|
2710
3074
|
y: Math.min(area.y + area.height, Math.max(area.y, p.y))
|
|
2711
3075
|
};
|
|
2712
3076
|
}
|
|
2713
|
-
function fmt(value) {
|
|
3077
|
+
function fmt$1(value) {
|
|
2714
3078
|
return Number.isInteger(value) ? String(value) : value.toFixed(1);
|
|
2715
3079
|
}
|
|
2716
3080
|
//#endregion
|
|
@@ -2725,7 +3089,7 @@ function fmt(value) {
|
|
|
2725
3089
|
* (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by
|
|
2726
3090
|
* `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
|
|
2727
3091
|
*/
|
|
2728
|
-
const HALO = overlayRole("halo");
|
|
3092
|
+
const HALO$5 = overlayRole("halo");
|
|
2729
3093
|
/** The most points drawn as dots at once; past this the dots are noise and a cost. */
|
|
2730
3094
|
const MAX_VERTEX_DOTS = 5e3;
|
|
2731
3095
|
/**
|
|
@@ -2742,14 +3106,26 @@ const MAX_VERTEX_DOTS = 5e3;
|
|
|
2742
3106
|
*
|
|
2743
3107
|
* The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
|
|
2744
3108
|
*/
|
|
2745
|
-
function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines" }) {
|
|
3109
|
+
function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange, onItemPress, onSelect, marquee = false, stroke = overlayRole("feature"), selectionStroke = overlayRole("selection"), hitWidth = 14, vertexScale = 3, label = "Lines", layerId, priority = STAGE_HIT_PRIORITY.line }) {
|
|
2746
3110
|
const stage = useStage();
|
|
2747
3111
|
const startDrag = useStageDrag();
|
|
2748
3112
|
const px = useScreenPx();
|
|
3113
|
+
const { hitTestAll } = useStageHitTest();
|
|
2749
3114
|
const index = useMemo(() => buildPolylineIndex(items), [items]);
|
|
2750
3115
|
const selectedSet = useMemo(() => new Set(selected ?? []), [selected]);
|
|
2751
3116
|
const dimmedSet = useMemo(() => new Set(dimmed ?? []), [dimmed]);
|
|
2752
3117
|
const byId = useMemo(() => new Map(items.map((item) => [item.id, item])), [items]);
|
|
3118
|
+
const ownId = useStageHitLayer({
|
|
3119
|
+
layerId,
|
|
3120
|
+
priority,
|
|
3121
|
+
pick: (point, radius) => {
|
|
3122
|
+
const hit = nearestPolyline(index, point, radius);
|
|
3123
|
+
return hit ? {
|
|
3124
|
+
id: hit.id,
|
|
3125
|
+
dist: hit.distance
|
|
3126
|
+
} : null;
|
|
3127
|
+
}
|
|
3128
|
+
});
|
|
2753
3129
|
const [ownHover, setOwnHover] = useState(null);
|
|
2754
3130
|
const hoverId = hovered !== void 0 ? hovered : ownHover;
|
|
2755
3131
|
const [band, setBand] = useState(null);
|
|
@@ -2821,6 +3197,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
|
|
|
2821
3197
|
if (id === hoverId) return;
|
|
2822
3198
|
setOwnHover(id);
|
|
2823
3199
|
onHover?.(id);
|
|
3200
|
+
onHoverChange?.(id);
|
|
2824
3201
|
};
|
|
2825
3202
|
const sweep = (event) => {
|
|
2826
3203
|
const from = stage.toImage({
|
|
@@ -2852,7 +3229,13 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
|
|
|
2852
3229
|
}
|
|
2853
3230
|
const id = pickAt(event);
|
|
2854
3231
|
if (id === null) return;
|
|
3232
|
+
const point = stage.toImage({
|
|
3233
|
+
x: event.clientX,
|
|
3234
|
+
y: event.clientY
|
|
3235
|
+
});
|
|
3236
|
+
if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
|
|
2855
3237
|
event.stopPropagation();
|
|
3238
|
+
onItemPress?.(id, event);
|
|
2856
3239
|
onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
|
|
2857
3240
|
};
|
|
2858
3241
|
const hairline = px(1.5);
|
|
@@ -2884,7 +3267,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
|
|
|
2884
3267
|
children: [
|
|
2885
3268
|
/* @__PURE__ */ jsx("path", {
|
|
2886
3269
|
d: groups.hit,
|
|
2887
|
-
stroke: HALO,
|
|
3270
|
+
stroke: HALO$5,
|
|
2888
3271
|
strokeWidth: px(3.5),
|
|
2889
3272
|
opacity: .6
|
|
2890
3273
|
}),
|
|
@@ -2897,7 +3280,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
|
|
|
2897
3280
|
}, `${batch.dim}|${batch.dashed}|${batch.stroke}`)),
|
|
2898
3281
|
groups.selected && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
|
|
2899
3282
|
d: groups.selected,
|
|
2900
|
-
stroke: HALO,
|
|
3283
|
+
stroke: HALO$5,
|
|
2901
3284
|
strokeWidth: px(4.5)
|
|
2902
3285
|
}), /* @__PURE__ */ jsx("path", {
|
|
2903
3286
|
"data-selected-lines": "",
|
|
@@ -2907,7 +3290,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onSelect, marq
|
|
|
2907
3290
|
})] }),
|
|
2908
3291
|
hoverPath && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("path", {
|
|
2909
3292
|
d: hoverPath,
|
|
2910
|
-
stroke: HALO,
|
|
3293
|
+
stroke: HALO$5,
|
|
2911
3294
|
strokeWidth: px(4)
|
|
2912
3295
|
}), /* @__PURE__ */ jsx("path", {
|
|
2913
3296
|
"data-hovered-line": "",
|
|
@@ -2960,6 +3343,2370 @@ function boxBetween(a, b) {
|
|
|
2960
3343
|
};
|
|
2961
3344
|
}
|
|
2962
3345
|
//#endregion
|
|
3346
|
+
//#region src/components/markerShapes.ts
|
|
3347
|
+
/** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
|
|
3348
|
+
function n(value) {
|
|
3349
|
+
return Math.round(value * 1e3) / 1e3;
|
|
3350
|
+
}
|
|
3351
|
+
/**
|
|
3352
|
+
* A circle as two arcs, centred at `(x, y)`.
|
|
3353
|
+
*
|
|
3354
|
+
* @param x - Centre x.
|
|
3355
|
+
* @param y - Centre y.
|
|
3356
|
+
* @param r - Radius, in the units of `x` and `y`.
|
|
3357
|
+
* @returns Path data.
|
|
3358
|
+
*/
|
|
3359
|
+
function circlePath(x, y, r) {
|
|
3360
|
+
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`;
|
|
3361
|
+
}
|
|
3362
|
+
/** The built-in kinds, with the overlay grammar's glyph for each. */
|
|
3363
|
+
const MARKER_SHAPES = {
|
|
3364
|
+
/** A blob, circle centre or keypoint: a dot of radius 2.5 px. */
|
|
3365
|
+
dot: {
|
|
3366
|
+
paint: "disc",
|
|
3367
|
+
size: 2.5,
|
|
3368
|
+
path: (x, y) => `M${n(x)} ${n(y)}h0`
|
|
3369
|
+
},
|
|
3370
|
+
/** A corner or X-junction: a plus with 5 px arms, so the centre stays visible. */
|
|
3371
|
+
plus: {
|
|
3372
|
+
paint: "line",
|
|
3373
|
+
size: 5,
|
|
3374
|
+
path: (x, y, u) => {
|
|
3375
|
+
const a = 5 * u;
|
|
3376
|
+
return `M${n(x - a)} ${n(y)}h${n(2 * a)}M${n(x)} ${n(y - a)}v${n(2 * a)}`;
|
|
3377
|
+
}
|
|
3378
|
+
},
|
|
3379
|
+
/** A diagonal cross with 4 px arms: a second corner style, or "rejected". */
|
|
3380
|
+
cross: {
|
|
3381
|
+
paint: "line",
|
|
3382
|
+
size: 4,
|
|
3383
|
+
path: (x, y, u) => {
|
|
3384
|
+
const a = 4 * u;
|
|
3385
|
+
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)}`;
|
|
3386
|
+
}
|
|
3387
|
+
},
|
|
3388
|
+
/** A hollow square of half-side 3.5 px. */
|
|
3389
|
+
square: {
|
|
3390
|
+
paint: "line",
|
|
3391
|
+
size: 3.5,
|
|
3392
|
+
path: (x, y, u) => {
|
|
3393
|
+
const a = 3.5 * u;
|
|
3394
|
+
return `M${n(x - a)} ${n(y - a)}h${n(2 * a)}v${n(2 * a)}h${n(-2 * a)}Z`;
|
|
3395
|
+
}
|
|
3396
|
+
},
|
|
3397
|
+
/** A reprojected or predicted point: a hollow circle of radius 4 px, in the model colour. */
|
|
3398
|
+
hollow: {
|
|
3399
|
+
paint: "line",
|
|
3400
|
+
size: 4,
|
|
3401
|
+
role: "model",
|
|
3402
|
+
path: (x, y, u) => circlePath(x, y, 4 * u)
|
|
3403
|
+
},
|
|
3404
|
+
/**
|
|
3405
|
+
* A point with an orientation: a small ring and a tick of length 8 px from it along
|
|
3406
|
+
* `angle`, measured clockwise from +x in image coordinates (y points down).
|
|
3407
|
+
*/
|
|
3408
|
+
directed: {
|
|
3409
|
+
paint: "line",
|
|
3410
|
+
size: 6,
|
|
3411
|
+
path: (x, y, u, angle) => {
|
|
3412
|
+
const c = Math.cos(angle);
|
|
3413
|
+
const s = Math.sin(angle);
|
|
3414
|
+
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)}`;
|
|
3415
|
+
}
|
|
3416
|
+
}
|
|
3417
|
+
};
|
|
3418
|
+
//#endregion
|
|
3419
|
+
//#region src/components/pointIndex.ts
|
|
3420
|
+
/** The most grid cells an index allocates, whatever the cell side asks for. */
|
|
3421
|
+
const MAX_CELLS$1 = 4e6;
|
|
3422
|
+
/**
|
|
3423
|
+
* Index a set of points.
|
|
3424
|
+
*
|
|
3425
|
+
* @param xy - Flat `[x0, y0, x1, y1, …]` in image coordinates; a `Float32Array` or
|
|
3426
|
+
* `Float64Array` avoids a copy at the call site.
|
|
3427
|
+
* @param options - Ids, per-point pick radii and the cell side.
|
|
3428
|
+
* @returns The index.
|
|
3429
|
+
*/
|
|
3430
|
+
function buildPointIndex(xy, options = {}) {
|
|
3431
|
+
const count = Math.floor(xy.length / 2);
|
|
3432
|
+
const ids = options.ids ?? null;
|
|
3433
|
+
const radii = options.radii ?? null;
|
|
3434
|
+
let minX = Infinity;
|
|
3435
|
+
let minY = Infinity;
|
|
3436
|
+
let maxX = -Infinity;
|
|
3437
|
+
let maxY = -Infinity;
|
|
3438
|
+
let maxRadius = 0;
|
|
3439
|
+
let live = 0;
|
|
3440
|
+
for (let i = 0; i < count; i++) {
|
|
3441
|
+
const x = xy[2 * i];
|
|
3442
|
+
const y = xy[2 * i + 1];
|
|
3443
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
|
3444
|
+
live++;
|
|
3445
|
+
if (x < minX) minX = x;
|
|
3446
|
+
if (x > maxX) maxX = x;
|
|
3447
|
+
if (y < minY) minY = y;
|
|
3448
|
+
if (y > maxY) maxY = y;
|
|
3449
|
+
if (radii) {
|
|
3450
|
+
const r = radii[i];
|
|
3451
|
+
if (r > maxRadius) maxRadius = r;
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3454
|
+
if (live === 0) return {
|
|
3455
|
+
count,
|
|
3456
|
+
xy,
|
|
3457
|
+
ids,
|
|
3458
|
+
radii,
|
|
3459
|
+
maxRadius,
|
|
3460
|
+
cell: 1,
|
|
3461
|
+
x0: 0,
|
|
3462
|
+
y0: 0,
|
|
3463
|
+
cols: 1,
|
|
3464
|
+
rows: 1,
|
|
3465
|
+
starts: /* @__PURE__ */ new Uint32Array(2),
|
|
3466
|
+
items: /* @__PURE__ */ new Uint32Array(0)
|
|
3467
|
+
};
|
|
3468
|
+
const width = maxX - minX;
|
|
3469
|
+
const height = maxY - minY;
|
|
3470
|
+
let cell = options.cell ?? Math.min(256, Math.max(4, Math.sqrt(Math.max(width, 1) * Math.max(height, 1) * 2 / live)));
|
|
3471
|
+
while ((Math.floor(width / cell) + 1) * (Math.floor(height / cell) + 1) > MAX_CELLS$1) cell *= 2;
|
|
3472
|
+
const cols = Math.floor(width / cell) + 1;
|
|
3473
|
+
const rows = Math.floor(height / cell) + 1;
|
|
3474
|
+
const cellOf = new Int32Array(count).fill(-1);
|
|
3475
|
+
const starts = new Uint32Array(cols * rows + 1);
|
|
3476
|
+
for (let i = 0; i < count; i++) {
|
|
3477
|
+
const x = xy[2 * i];
|
|
3478
|
+
const y = xy[2 * i + 1];
|
|
3479
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
|
3480
|
+
const c = Math.min(rows - 1, Math.floor((y - minY) / cell)) * cols + Math.min(cols - 1, Math.floor((x - minX) / cell));
|
|
3481
|
+
cellOf[i] = c;
|
|
3482
|
+
starts[c + 1]++;
|
|
3483
|
+
}
|
|
3484
|
+
for (let c = 0; c < cols * rows; c++) starts[c + 1] += starts[c];
|
|
3485
|
+
const fill = starts.slice(0, cols * rows);
|
|
3486
|
+
const items = new Uint32Array(live);
|
|
3487
|
+
for (let i = 0; i < count; i++) {
|
|
3488
|
+
const c = cellOf[i];
|
|
3489
|
+
if (c >= 0) items[fill[c]++] = i;
|
|
3490
|
+
}
|
|
3491
|
+
return {
|
|
3492
|
+
count,
|
|
3493
|
+
xy,
|
|
3494
|
+
ids,
|
|
3495
|
+
radii,
|
|
3496
|
+
maxRadius,
|
|
3497
|
+
cell,
|
|
3498
|
+
x0: minX,
|
|
3499
|
+
y0: minY,
|
|
3500
|
+
cols,
|
|
3501
|
+
rows,
|
|
3502
|
+
starts,
|
|
3503
|
+
items
|
|
3504
|
+
};
|
|
3505
|
+
}
|
|
3506
|
+
/**
|
|
3507
|
+
* Index items that carry their own position.
|
|
3508
|
+
*
|
|
3509
|
+
* @param items - The points, in order.
|
|
3510
|
+
* @param cell - The grid cell side; see `PointIndexOptions`.
|
|
3511
|
+
* @returns The index; its point indices are positions in `items`.
|
|
3512
|
+
*/
|
|
3513
|
+
function buildPointIndexFrom(items, cell) {
|
|
3514
|
+
const xy = new Float64Array(items.length * 2);
|
|
3515
|
+
const ids = new Array(items.length);
|
|
3516
|
+
let radii;
|
|
3517
|
+
items.forEach((item, i) => {
|
|
3518
|
+
xy[2 * i] = item.x;
|
|
3519
|
+
xy[2 * i + 1] = item.y;
|
|
3520
|
+
ids[i] = item.id;
|
|
3521
|
+
if (item.pickRadius !== void 0 && item.pickRadius > 0) {
|
|
3522
|
+
radii ??= new Float64Array(items.length);
|
|
3523
|
+
radii[i] = item.pickRadius;
|
|
3524
|
+
}
|
|
3525
|
+
});
|
|
3526
|
+
return buildPointIndex(xy, {
|
|
3527
|
+
ids,
|
|
3528
|
+
radii,
|
|
3529
|
+
cell
|
|
3530
|
+
});
|
|
3531
|
+
}
|
|
3532
|
+
/**
|
|
3533
|
+
* The point nearest to `(x, y)` whose pick disc reaches it, or `null`.
|
|
3534
|
+
*
|
|
3535
|
+
* @param index - The index.
|
|
3536
|
+
* @param x - The query's x, in image coordinates.
|
|
3537
|
+
* @param y - The query's y, in image coordinates.
|
|
3538
|
+
* @param radius - How far from a point's centre the query still picks it, in image pixels.
|
|
3539
|
+
* For a screen-constant tolerance, pass `useScreenPx()(css)`. A point's own `radii` entry
|
|
3540
|
+
* adds to it.
|
|
3541
|
+
* @returns The point nearest by centre distance; ties go to the lower index, so the result
|
|
3542
|
+
* does not depend on cell order.
|
|
3543
|
+
*/
|
|
3544
|
+
function nearestPoint(index, x, y, radius) {
|
|
3545
|
+
if (!(radius >= 0) || index.items.length === 0) return null;
|
|
3546
|
+
const { cell, x0, y0, cols, rows, starts, items, xy, radii, maxRadius } = index;
|
|
3547
|
+
const reach = radius + maxRadius;
|
|
3548
|
+
const cx0 = Math.max(0, Math.floor((x - reach - x0) / cell));
|
|
3549
|
+
const cx1 = Math.min(cols - 1, Math.floor((x + reach - x0) / cell));
|
|
3550
|
+
const cy0 = Math.max(0, Math.floor((y - reach - y0) / cell));
|
|
3551
|
+
const cy1 = Math.min(rows - 1, Math.floor((y + reach - y0) / cell));
|
|
3552
|
+
let best = -1;
|
|
3553
|
+
let bestD = Infinity;
|
|
3554
|
+
for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
|
|
3555
|
+
const c = cy * cols + cx;
|
|
3556
|
+
for (let k = starts[c]; k < starts[c + 1]; k++) {
|
|
3557
|
+
const i = items[k];
|
|
3558
|
+
const dx = xy[2 * i] - x;
|
|
3559
|
+
const dy = xy[2 * i + 1] - y;
|
|
3560
|
+
const d = dx * dx + dy * dy;
|
|
3561
|
+
const reachI = radii ? radius + radii[i] : radius;
|
|
3562
|
+
if (d <= reachI * reachI && (d < bestD || d === bestD && i < best)) {
|
|
3563
|
+
bestD = d;
|
|
3564
|
+
best = i;
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
return best < 0 ? null : {
|
|
3569
|
+
index: best,
|
|
3570
|
+
id: index.ids ? index.ids[best] : best,
|
|
3571
|
+
dist: Math.sqrt(bestD)
|
|
3572
|
+
};
|
|
3573
|
+
}
|
|
3574
|
+
/**
|
|
3575
|
+
* The points whose centre is inside `rect`, edges included.
|
|
3576
|
+
*
|
|
3577
|
+
* @param index - The index.
|
|
3578
|
+
* @param rect - The band, in image coordinates. A negative extent is read as the box
|
|
3579
|
+
* between its corners.
|
|
3580
|
+
* @returns Their indices, ascending.
|
|
3581
|
+
*/
|
|
3582
|
+
function pointsInRect(index, rect) {
|
|
3583
|
+
if (index.items.length === 0) return [];
|
|
3584
|
+
const { cell, x0, y0, cols, rows, starts, items, xy } = index;
|
|
3585
|
+
const left = Math.min(rect.x, rect.x + rect.width);
|
|
3586
|
+
const right = Math.max(rect.x, rect.x + rect.width);
|
|
3587
|
+
const top = Math.min(rect.y, rect.y + rect.height);
|
|
3588
|
+
const bottom = Math.max(rect.y, rect.y + rect.height);
|
|
3589
|
+
const cx0 = Math.max(0, Math.floor((left - x0) / cell));
|
|
3590
|
+
const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
|
|
3591
|
+
const cy0 = Math.max(0, Math.floor((top - y0) / cell));
|
|
3592
|
+
const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
|
|
3593
|
+
const found = [];
|
|
3594
|
+
for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
|
|
3595
|
+
const c = cy * cols + cx;
|
|
3596
|
+
for (let k = starts[c]; k < starts[c + 1]; k++) {
|
|
3597
|
+
const i = items[k];
|
|
3598
|
+
const px = xy[2 * i];
|
|
3599
|
+
const py = xy[2 * i + 1];
|
|
3600
|
+
if (px >= left && px <= right && py >= top && py <= bottom) found.push(i);
|
|
3601
|
+
}
|
|
3602
|
+
}
|
|
3603
|
+
return found.sort((a, b) => a - b);
|
|
3604
|
+
}
|
|
3605
|
+
/**
|
|
3606
|
+
* A greedy thinning: walk the points in `order` and keep each one that is at least `minDist`
|
|
3607
|
+
* from every point kept so far. This is how a label layer decides which labels the zoom has
|
|
3608
|
+
* room for.
|
|
3609
|
+
*
|
|
3610
|
+
* The result is *maximal*: every point left out is within `minDist` of one kept before it,
|
|
3611
|
+
* and every pair kept is at least `minDist` apart.
|
|
3612
|
+
*
|
|
3613
|
+
* @param xy - Flat points, in the units `minDist` is in (image pixels for a screen-px spacing
|
|
3614
|
+
* converted with `useScreenPx`).
|
|
3615
|
+
* @param minDist - The least distance between two kept points.
|
|
3616
|
+
* @param order - Point indices in priority order. Defaults to every point, in order.
|
|
3617
|
+
* Indices of non-finite points are skipped.
|
|
3618
|
+
* @returns The kept indices, in the order they were kept.
|
|
3619
|
+
*/
|
|
3620
|
+
function thinPoints(xy, minDist, order) {
|
|
3621
|
+
const kept = [];
|
|
3622
|
+
if (!(minDist > 0)) {
|
|
3623
|
+
for (const i of order ?? range(Math.floor(xy.length / 2))) if (isLive(xy, i)) kept.push(i);
|
|
3624
|
+
return kept;
|
|
3625
|
+
}
|
|
3626
|
+
const cells = /* @__PURE__ */ new Map();
|
|
3627
|
+
const key = (cx, cy) => cy * 4194304 + cx;
|
|
3628
|
+
const limit = minDist * minDist;
|
|
3629
|
+
for (const i of order ?? range(Math.floor(xy.length / 2))) {
|
|
3630
|
+
if (!isLive(xy, i)) continue;
|
|
3631
|
+
const x = xy[2 * i];
|
|
3632
|
+
const y = xy[2 * i + 1];
|
|
3633
|
+
const cx = Math.floor(x / minDist);
|
|
3634
|
+
const cy = Math.floor(y / minDist);
|
|
3635
|
+
let clear = true;
|
|
3636
|
+
scan: for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
3637
|
+
const bucket = cells.get(key(cx + dx, cy + dy));
|
|
3638
|
+
if (!bucket) continue;
|
|
3639
|
+
for (const j of bucket) {
|
|
3640
|
+
const ex = xy[2 * j] - x;
|
|
3641
|
+
const ey = xy[2 * j + 1] - y;
|
|
3642
|
+
if (ex * ex + ey * ey < limit) {
|
|
3643
|
+
clear = false;
|
|
3644
|
+
break scan;
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3647
|
+
}
|
|
3648
|
+
if (!clear) continue;
|
|
3649
|
+
kept.push(i);
|
|
3650
|
+
const k = key(cx, cy);
|
|
3651
|
+
const bucket = cells.get(k);
|
|
3652
|
+
if (bucket) bucket.push(i);
|
|
3653
|
+
else cells.set(k, [i]);
|
|
3654
|
+
}
|
|
3655
|
+
return kept;
|
|
3656
|
+
}
|
|
3657
|
+
function isLive(xy, i) {
|
|
3658
|
+
return Number.isFinite(xy[2 * i]) && Number.isFinite(xy[2 * i + 1]);
|
|
3659
|
+
}
|
|
3660
|
+
function* range(n) {
|
|
3661
|
+
for (let i = 0; i < n; i++) yield i;
|
|
3662
|
+
}
|
|
3663
|
+
/** The image-space rectangle on screen, or `null` before the viewport is measured. */
|
|
3664
|
+
function visibleRect(view, box) {
|
|
3665
|
+
if (!(box.width > 0) || !(view.scale > 0)) return null;
|
|
3666
|
+
return {
|
|
3667
|
+
x: -view.tx / view.scale,
|
|
3668
|
+
y: -view.ty / view.scale,
|
|
3669
|
+
width: box.width / view.scale,
|
|
3670
|
+
height: box.height / view.scale
|
|
3671
|
+
};
|
|
3672
|
+
}
|
|
3673
|
+
/**
|
|
3674
|
+
* Choose the labels to draw.
|
|
3675
|
+
*
|
|
3676
|
+
* @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).
|
|
3677
|
+
* @param forced - Anchors that always carry a label: the hovered and the selected.
|
|
3678
|
+
* @param inView - Whether an anchor is inside the viewport.
|
|
3679
|
+
* @returns The anchor indices to label: the forced ones first (at most 50), then the spaced
|
|
3680
|
+
* ones, 200 in all.
|
|
3681
|
+
*/
|
|
3682
|
+
function pickLabelIndices(spaced, forced, inView) {
|
|
3683
|
+
const shown = /* @__PURE__ */ new Set();
|
|
3684
|
+
for (const i of forced) {
|
|
3685
|
+
if (shown.size >= 50) break;
|
|
3686
|
+
if (i >= 0 && inView(i)) shown.add(i);
|
|
3687
|
+
}
|
|
3688
|
+
for (const i of spaced) {
|
|
3689
|
+
if (shown.size >= 200) break;
|
|
3690
|
+
if (inView(i)) shown.add(i);
|
|
3691
|
+
}
|
|
3692
|
+
return [...shown];
|
|
3693
|
+
}
|
|
3694
|
+
/**
|
|
3695
|
+
* The anchors to label at the stage's current zoom and viewport. The spacing depends on the
|
|
3696
|
+
* zoom only, so panning does not reshuffle which anchors carry a label.
|
|
3697
|
+
*
|
|
3698
|
+
* @param anchors - See `LabelAnchors`.
|
|
3699
|
+
* @returns Anchor indices.
|
|
3700
|
+
*/
|
|
3701
|
+
function useLabelIndices({ enabled, xy, labelled, forced }) {
|
|
3702
|
+
const stage = useStage();
|
|
3703
|
+
const spacing = 24 * useScreenPx()(1);
|
|
3704
|
+
const spaced = useMemo(() => enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : [], [
|
|
3705
|
+
enabled,
|
|
3706
|
+
labelled,
|
|
3707
|
+
xy,
|
|
3708
|
+
spacing
|
|
3709
|
+
]);
|
|
3710
|
+
return useMemo(() => {
|
|
3711
|
+
if (!enabled || spaced.length === 0 && forced.length === 0) return [];
|
|
3712
|
+
const view = visibleRect(stage.view, stage.box);
|
|
3713
|
+
const inView = (i) => {
|
|
3714
|
+
if (view === null) return true;
|
|
3715
|
+
const x = xy[2 * i];
|
|
3716
|
+
const y = xy[2 * i + 1];
|
|
3717
|
+
return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;
|
|
3718
|
+
};
|
|
3719
|
+
return pickLabelIndices(spaced, forced, inView);
|
|
3720
|
+
}, [
|
|
3721
|
+
enabled,
|
|
3722
|
+
spaced,
|
|
3723
|
+
forced,
|
|
3724
|
+
xy,
|
|
3725
|
+
stage.view,
|
|
3726
|
+
stage.box
|
|
3727
|
+
]);
|
|
3728
|
+
}
|
|
3729
|
+
//#endregion
|
|
3730
|
+
//#region src/components/PointSet.tsx
|
|
3731
|
+
/**
|
|
3732
|
+
* Many points over the image, hoverable and selectable: detected corners, ring centres,
|
|
3733
|
+
* keypoints, labelled landmarks.
|
|
3734
|
+
*
|
|
3735
|
+
* Drawn as a handful of batched paths, one per (state, style, marker kind), never one element
|
|
3736
|
+
* per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the
|
|
3737
|
+
* stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
|
|
3738
|
+
* 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
|
|
3739
|
+
*/
|
|
3740
|
+
/** Past this many points, outlines are generated for the visible part only. */
|
|
3741
|
+
const CULL_ABOVE = 3e3;
|
|
3742
|
+
/** How much bigger than a marker its selection ring is, in screen pixels. */
|
|
3743
|
+
const RING_GAP = 4;
|
|
3744
|
+
const HALO$4 = overlayRole("halo");
|
|
3745
|
+
const LABEL$1 = overlayRole("label");
|
|
3746
|
+
/**
|
|
3747
|
+
* A selectable set of points inside an `ImageStage`.
|
|
3748
|
+
*
|
|
3749
|
+
* - **Markers** by kind, from the overlay grammar: `dot`, `plus` (corner), `cross`, `square`,
|
|
3750
|
+
* `hollow` (predicted), `directed`. Add your own through `markers`.
|
|
3751
|
+
* - **States**, from visual-language §5: default 1.5 screen px, hover 2, selected 2.5 in the
|
|
3752
|
+
* selection colour with a ring, dimmed at 35 % opacity. Every mark has a halo.
|
|
3753
|
+
* - **Labels** only where points are at least 24 screen px apart, at most 200 at a time.
|
|
3754
|
+
* - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here,
|
|
3755
|
+
* and `useStageHitTest` for an app that arbitrates between layers.
|
|
3756
|
+
*
|
|
3757
|
+
* Outlines (`plus`, `cross`, …) are regenerated when the zoom changes, since their size is in
|
|
3758
|
+
* screen pixels; past 3,000 points only those near the viewport are generated. `dot` is a
|
|
3759
|
+
* zero-length stroke whose width is its size, so it is not regenerated at all.
|
|
3760
|
+
*
|
|
3761
|
+
* The SVG carries `data-hovered` (the hovered id).
|
|
3762
|
+
*/
|
|
3763
|
+
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" }) {
|
|
3764
|
+
const stage = useStage();
|
|
3765
|
+
const px = useScreenPx();
|
|
3766
|
+
const unit = px(1);
|
|
3767
|
+
const shapes = useMemo(() => ({
|
|
3768
|
+
...MARKER_SHAPES,
|
|
3769
|
+
...markers
|
|
3770
|
+
}), [markers]);
|
|
3771
|
+
const index = useMemo(() => buildPointIndexFrom(items), [items]);
|
|
3772
|
+
const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
|
|
3773
|
+
const isDimmed = useMemo(() => {
|
|
3774
|
+
if (typeof dimmed === "function") return dimmed;
|
|
3775
|
+
const set = new Set(dimmed ?? []);
|
|
3776
|
+
return (id) => set.has(id);
|
|
3777
|
+
}, [dimmed]);
|
|
3778
|
+
const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
|
|
3779
|
+
const [ownHover, setOwnHover] = useState(null);
|
|
3780
|
+
const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
|
|
3781
|
+
useStageHitLayer({
|
|
3782
|
+
layerId,
|
|
3783
|
+
priority,
|
|
3784
|
+
pick: (point, radius) => {
|
|
3785
|
+
const hit = nearestPoint(index, point.x, point.y, radius);
|
|
3786
|
+
return hit ? {
|
|
3787
|
+
id: hit.id,
|
|
3788
|
+
dist: hit.dist
|
|
3789
|
+
} : null;
|
|
3790
|
+
},
|
|
3791
|
+
onHover: (id) => {
|
|
3792
|
+
setOwnHover(id);
|
|
3793
|
+
onHoverChange?.(id);
|
|
3794
|
+
},
|
|
3795
|
+
onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
|
|
3796
|
+
});
|
|
3797
|
+
const groups = useMemo(() => {
|
|
3798
|
+
const normal = /* @__PURE__ */ new Map();
|
|
3799
|
+
const picked = /* @__PURE__ */ new Map();
|
|
3800
|
+
items.forEach((item, i) => {
|
|
3801
|
+
const kindName = item.kind ?? kind;
|
|
3802
|
+
const shape = shapes[kindName] ?? MARKER_SHAPES.dot;
|
|
3803
|
+
if (selectedSet.has(item.id)) {
|
|
3804
|
+
const key = kindName;
|
|
3805
|
+
let batch = picked.get(key);
|
|
3806
|
+
if (!batch) {
|
|
3807
|
+
batch = {
|
|
3808
|
+
key,
|
|
3809
|
+
shape,
|
|
3810
|
+
role: "selection",
|
|
3811
|
+
dim: false,
|
|
3812
|
+
indices: [],
|
|
3813
|
+
cache: null
|
|
3814
|
+
};
|
|
3815
|
+
picked.set(key, batch);
|
|
3816
|
+
}
|
|
3817
|
+
batch.indices.push(i);
|
|
3818
|
+
return;
|
|
3819
|
+
}
|
|
3820
|
+
const role = item.role ?? shape.role ?? "feature";
|
|
3821
|
+
const dim = isDimmed(item.id);
|
|
3822
|
+
const key = `${dim ? 1 : 0}|${role}|${kindName}`;
|
|
3823
|
+
let batch = normal.get(key);
|
|
3824
|
+
if (!batch) {
|
|
3825
|
+
batch = {
|
|
3826
|
+
key,
|
|
3827
|
+
shape,
|
|
3828
|
+
role,
|
|
3829
|
+
dim,
|
|
3830
|
+
indices: [],
|
|
3831
|
+
cache: null
|
|
3832
|
+
};
|
|
3833
|
+
normal.set(key, batch);
|
|
3834
|
+
}
|
|
3835
|
+
batch.indices.push(i);
|
|
3836
|
+
});
|
|
3837
|
+
const rings = [...picked.values()].map((batch) => ({
|
|
3838
|
+
...batch,
|
|
3839
|
+
key: `ring|${batch.key}`,
|
|
3840
|
+
shape: {
|
|
3841
|
+
paint: "line",
|
|
3842
|
+
size: 0,
|
|
3843
|
+
path: (x, y, u) => circlePath(x, y, (batch.shape.size + RING_GAP) * u)
|
|
3844
|
+
},
|
|
3845
|
+
cache: null
|
|
3846
|
+
}));
|
|
3847
|
+
return {
|
|
3848
|
+
normal: [...normal.values()],
|
|
3849
|
+
picked: [...picked.values()],
|
|
3850
|
+
rings
|
|
3851
|
+
};
|
|
3852
|
+
}, [
|
|
3853
|
+
items,
|
|
3854
|
+
kind,
|
|
3855
|
+
shapes,
|
|
3856
|
+
selectedSet,
|
|
3857
|
+
isDimmed
|
|
3858
|
+
]);
|
|
3859
|
+
const cull = cullWindow(stage.view, stage.box, items.length);
|
|
3860
|
+
const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
|
|
3861
|
+
const build = (batches) => batches.map((batch) => ({
|
|
3862
|
+
batch,
|
|
3863
|
+
d: batchPath(batch, items, unit, cull, cullKey)
|
|
3864
|
+
}));
|
|
3865
|
+
const paths = {
|
|
3866
|
+
normal: build(groups.normal),
|
|
3867
|
+
picked: build(groups.picked),
|
|
3868
|
+
rings: build(groups.rings)
|
|
3869
|
+
};
|
|
3870
|
+
const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
|
|
3871
|
+
const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
|
|
3872
|
+
const hoverShape = hoverItem ? shapes[hoverItem.kind ?? kind] ?? MARKER_SHAPES.dot : void 0;
|
|
3873
|
+
const hoverRole = hoverItem?.role ?? hoverShape?.role ?? "feature";
|
|
3874
|
+
const labelled = useMemo(() => {
|
|
3875
|
+
const list = [];
|
|
3876
|
+
items.forEach((item, i) => {
|
|
3877
|
+
if (item.label) list.push(i);
|
|
3878
|
+
});
|
|
3879
|
+
return list;
|
|
3880
|
+
}, [items]);
|
|
3881
|
+
const forced = useMemo(() => {
|
|
3882
|
+
const list = [];
|
|
3883
|
+
if (hoverItem?.label) list.push(positionOf.get(hoverItem.id));
|
|
3884
|
+
for (const id of selectedSet) {
|
|
3885
|
+
const i = positionOf.get(id);
|
|
3886
|
+
if (i !== void 0 && items[i].label) list.push(i);
|
|
3887
|
+
}
|
|
3888
|
+
return list;
|
|
3889
|
+
}, [
|
|
3890
|
+
hoverItem,
|
|
3891
|
+
selectedSet,
|
|
3892
|
+
positionOf,
|
|
3893
|
+
items
|
|
3894
|
+
]);
|
|
3895
|
+
const shownLabels = useLabelIndices({
|
|
3896
|
+
enabled: labels,
|
|
3897
|
+
xy: index.xy,
|
|
3898
|
+
labelled,
|
|
3899
|
+
forced
|
|
3900
|
+
});
|
|
3901
|
+
const widthOf = (shape, role, state) => {
|
|
3902
|
+
const thin = role === "model" || role === "structure";
|
|
3903
|
+
const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0);
|
|
3904
|
+
return px(shape.paint === "disc" ? 2 * shape.size + (OVERLAY_STATE_WIDTH[state] - 1.5) * 2 : base);
|
|
3905
|
+
};
|
|
3906
|
+
const ringWidth = px(1.5);
|
|
3907
|
+
return /* @__PURE__ */ jsxs("svg", {
|
|
3908
|
+
viewBox: imageViewBox(stage.image),
|
|
3909
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
3910
|
+
role: "img",
|
|
3911
|
+
"aria-label": `${label}: ${items.length} ${items.length === 1 ? "point" : "points"}, ${selectedSet.size} selected`,
|
|
3912
|
+
"data-hovered": hoverId ?? void 0,
|
|
3913
|
+
children: [/* @__PURE__ */ jsxs("g", {
|
|
3914
|
+
fill: "none",
|
|
3915
|
+
strokeLinecap: "round",
|
|
3916
|
+
strokeLinejoin: "round",
|
|
3917
|
+
children: [
|
|
3918
|
+
halo && paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3919
|
+
d,
|
|
3920
|
+
stroke: HALO$4,
|
|
3921
|
+
strokeWidth: widthOf(batch.shape, batch.role, "default") + px(2),
|
|
3922
|
+
opacity: .6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)
|
|
3923
|
+
}, `halo|${batch.key}`)),
|
|
3924
|
+
paths.normal.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3925
|
+
"data-batch": batch.key,
|
|
3926
|
+
d,
|
|
3927
|
+
stroke: overlayRole(batch.role),
|
|
3928
|
+
strokeWidth: widthOf(batch.shape, batch.role, "default"),
|
|
3929
|
+
opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1
|
|
3930
|
+
}, batch.key)),
|
|
3931
|
+
halo && paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3932
|
+
d,
|
|
3933
|
+
stroke: HALO$4,
|
|
3934
|
+
strokeWidth: widthOf(batch.shape, batch.role, "selected") + px(2)
|
|
3935
|
+
}, `halo|selected|${batch.key}`)),
|
|
3936
|
+
halo && paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3937
|
+
d,
|
|
3938
|
+
stroke: HALO$4,
|
|
3939
|
+
strokeWidth: ringWidth + px(2)
|
|
3940
|
+
}, `halo|${batch.key}`)),
|
|
3941
|
+
paths.picked.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3942
|
+
"data-selected-points": batch.key,
|
|
3943
|
+
d,
|
|
3944
|
+
stroke: selectionStroke,
|
|
3945
|
+
strokeWidth: widthOf(batch.shape, batch.role, "selected")
|
|
3946
|
+
}, `selected|${batch.key}`)),
|
|
3947
|
+
paths.rings.map(({ batch, d }) => /* @__PURE__ */ jsx("path", {
|
|
3948
|
+
"data-selection-rings": batch.key,
|
|
3949
|
+
d,
|
|
3950
|
+
stroke: selectionStroke,
|
|
3951
|
+
strokeWidth: ringWidth
|
|
3952
|
+
}, batch.key)),
|
|
3953
|
+
hoverItem && hoverShape && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
|
|
3954
|
+
d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
|
|
3955
|
+
stroke: HALO$4,
|
|
3956
|
+
strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)
|
|
3957
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
3958
|
+
"data-hovered-point": "",
|
|
3959
|
+
d: hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0),
|
|
3960
|
+
stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
|
|
3961
|
+
strokeWidth: widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")
|
|
3962
|
+
})] })
|
|
3963
|
+
]
|
|
3964
|
+
}), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
|
|
3965
|
+
"data-labels": "",
|
|
3966
|
+
fontSize: px(11),
|
|
3967
|
+
className: "font-mono",
|
|
3968
|
+
stroke: HALO$4,
|
|
3969
|
+
strokeWidth: px(3),
|
|
3970
|
+
paintOrder: "stroke",
|
|
3971
|
+
strokeLinejoin: "round",
|
|
3972
|
+
children: shownLabels.map((i) => {
|
|
3973
|
+
const item = items[i];
|
|
3974
|
+
return /* @__PURE__ */ jsx("text", {
|
|
3975
|
+
x: item.x + px(6),
|
|
3976
|
+
y: item.y - px(5),
|
|
3977
|
+
fill: LABEL$1,
|
|
3978
|
+
dominantBaseline: "text-after-edge",
|
|
3979
|
+
children: item.label
|
|
3980
|
+
}, item.id);
|
|
3981
|
+
})
|
|
3982
|
+
})]
|
|
3983
|
+
});
|
|
3984
|
+
}
|
|
3985
|
+
/**
|
|
3986
|
+
* The path data of a batch, generated again only when what it depends on changed: nothing
|
|
3987
|
+
* for a disc marker, the zoom and the window for an outline.
|
|
3988
|
+
*/
|
|
3989
|
+
function batchPath(batch, items, unit, cull, cullKey) {
|
|
3990
|
+
const disc = batch.shape.paint === "disc";
|
|
3991
|
+
const key = disc ? "" : `${unit}|${cullKey}`;
|
|
3992
|
+
if (batch.cache?.key === key) return batch.cache.d;
|
|
3993
|
+
const window = disc ? null : cull;
|
|
3994
|
+
let d = "";
|
|
3995
|
+
for (const i of batch.indices) {
|
|
3996
|
+
const item = items[i];
|
|
3997
|
+
if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;
|
|
3998
|
+
d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);
|
|
3999
|
+
}
|
|
4000
|
+
batch.cache = {
|
|
4001
|
+
key,
|
|
4002
|
+
d
|
|
4003
|
+
};
|
|
4004
|
+
return d;
|
|
4005
|
+
}
|
|
4006
|
+
/**
|
|
4007
|
+
* The window outlines are generated for: the viewport plus half a viewport on every side,
|
|
4008
|
+
* snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
|
|
4009
|
+
*/
|
|
4010
|
+
function cullWindow(view, box, count) {
|
|
4011
|
+
if (count <= CULL_ABOVE) return null;
|
|
4012
|
+
const visible = visibleRect(view, box);
|
|
4013
|
+
if (visible === null) return null;
|
|
4014
|
+
const sx = visible.width / 2;
|
|
4015
|
+
const sy = visible.height / 2;
|
|
4016
|
+
const left = Math.floor((visible.x - sx) / sx) * sx;
|
|
4017
|
+
const top = Math.floor((visible.y - sy) / sy) * sy;
|
|
4018
|
+
const right = Math.ceil((visible.x + visible.width + sx) / sx) * sx;
|
|
4019
|
+
const bottom = Math.ceil((visible.y + visible.height + sy) / sy) * sy;
|
|
4020
|
+
return {
|
|
4021
|
+
x: left,
|
|
4022
|
+
y: top,
|
|
4023
|
+
width: right - left,
|
|
4024
|
+
height: bottom - top
|
|
4025
|
+
};
|
|
4026
|
+
}
|
|
4027
|
+
//#endregion
|
|
4028
|
+
//#region src/components/areaIndex.ts
|
|
4029
|
+
/** The most grid cells an index allocates, and the most area-to-cell entries. */
|
|
4030
|
+
const MAX_CELLS = 4e6;
|
|
4031
|
+
const MAX_ENTRIES = 8e6;
|
|
4032
|
+
function vertexCount(points) {
|
|
4033
|
+
return Math.floor(points.length / 2);
|
|
4034
|
+
}
|
|
4035
|
+
/**
|
|
4036
|
+
* Whether `(x, y)` is inside the polygon, by the even-odd rule.
|
|
4037
|
+
*
|
|
4038
|
+
* @param points - Flat ring, implicitly closed.
|
|
4039
|
+
* @param x - The query's x.
|
|
4040
|
+
* @param y - The query's y.
|
|
4041
|
+
* @returns `false` for a ring with fewer than three vertices. A point exactly on the outline
|
|
4042
|
+
* may be either; `nearestArea` treats the outline separately.
|
|
4043
|
+
*/
|
|
4044
|
+
function pointInPolygon(points, x, y) {
|
|
4045
|
+
const n = vertexCount(points);
|
|
4046
|
+
if (n < 3) return false;
|
|
4047
|
+
let inside = false;
|
|
4048
|
+
for (let i = 0, j = n - 1; i < n; j = i++) {
|
|
4049
|
+
const xi = points[2 * i];
|
|
4050
|
+
const yi = points[2 * i + 1];
|
|
4051
|
+
const xj = points[2 * j];
|
|
4052
|
+
const yj = points[2 * j + 1];
|
|
4053
|
+
if (yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) inside = !inside;
|
|
4054
|
+
}
|
|
4055
|
+
return inside;
|
|
4056
|
+
}
|
|
4057
|
+
/**
|
|
4058
|
+
* The distance from `(x, y)` to the outline of a polygon (its closing edge included).
|
|
4059
|
+
*
|
|
4060
|
+
* @param points - Flat ring, implicitly closed.
|
|
4061
|
+
* @param x - The query's x.
|
|
4062
|
+
* @param y - The query's y.
|
|
4063
|
+
* @returns The distance; `Infinity` for an empty ring.
|
|
4064
|
+
*/
|
|
4065
|
+
function distanceToOutline(points, x, y) {
|
|
4066
|
+
const n = vertexCount(points);
|
|
4067
|
+
if (n === 0) return Infinity;
|
|
4068
|
+
const p = {
|
|
4069
|
+
x,
|
|
4070
|
+
y
|
|
4071
|
+
};
|
|
4072
|
+
let best = Infinity;
|
|
4073
|
+
const edges = n === 1 ? 1 : n === 2 ? 1 : n;
|
|
4074
|
+
for (let i = 0; i < edges; i++) {
|
|
4075
|
+
const j = n === 1 ? 0 : (i + 1) % n;
|
|
4076
|
+
const q = closestOnSegment(p, points[2 * i], points[2 * i + 1], points[2 * j], points[2 * j + 1]);
|
|
4077
|
+
const d = Math.hypot(q.x - x, q.y - y);
|
|
4078
|
+
if (d < best) best = d;
|
|
4079
|
+
}
|
|
4080
|
+
return best;
|
|
4081
|
+
}
|
|
4082
|
+
/**
|
|
4083
|
+
* The unsigned area of a polygon (shoelace).
|
|
4084
|
+
*
|
|
4085
|
+
* @param points - Flat ring, implicitly closed.
|
|
4086
|
+
* @returns The area; `0` for fewer than three vertices.
|
|
4087
|
+
*/
|
|
4088
|
+
function polygonArea(points) {
|
|
4089
|
+
const n = vertexCount(points);
|
|
4090
|
+
if (n < 3) return 0;
|
|
4091
|
+
let sum = 0;
|
|
4092
|
+
for (let i = 0, j = n - 1; i < n; j = i++) sum += points[2 * j] * points[2 * i + 1] - points[2 * i] * points[2 * j + 1];
|
|
4093
|
+
return Math.abs(sum) / 2;
|
|
4094
|
+
}
|
|
4095
|
+
/**
|
|
4096
|
+
* A polygon as an SVG path (`M … L … Z`) from its first vertex, wound the same way whatever the
|
|
4097
|
+
* input's winding.
|
|
4098
|
+
* A batched path of overlapping polygons filled with the nonzero rule would otherwise cut a
|
|
4099
|
+
* hole where a clockwise ring overlaps an anticlockwise one.
|
|
4100
|
+
*
|
|
4101
|
+
* @param points - Flat ring.
|
|
4102
|
+
* @returns Path data; `""` with no vertices.
|
|
4103
|
+
*/
|
|
4104
|
+
function areaPath(points) {
|
|
4105
|
+
const n = vertexCount(points);
|
|
4106
|
+
if (n === 0) return "";
|
|
4107
|
+
let signed = 0;
|
|
4108
|
+
for (let i = 0, j = n - 1; i < n; j = i++) signed += points[2 * j] * points[2 * i + 1] - points[2 * i] * points[2 * j + 1];
|
|
4109
|
+
const reversed = signed < 0;
|
|
4110
|
+
const at = (k) => reversed ? (n - k) % n : k;
|
|
4111
|
+
let d = `M${points[2 * at(0)]} ${points[2 * at(0) + 1]}`;
|
|
4112
|
+
if (n === 1) return `${d}h0`;
|
|
4113
|
+
for (let k = 1; k < n; k++) d += `L${points[2 * at(k)]} ${points[2 * at(k) + 1]}`;
|
|
4114
|
+
return `${d}Z`;
|
|
4115
|
+
}
|
|
4116
|
+
/**
|
|
4117
|
+
* The centre a label is drawn at: the mean of the vertices.
|
|
4118
|
+
*
|
|
4119
|
+
* @param points - Flat ring.
|
|
4120
|
+
* @returns The mean, or `null` for an empty ring.
|
|
4121
|
+
*/
|
|
4122
|
+
function areaCentre(points) {
|
|
4123
|
+
const n = vertexCount(points);
|
|
4124
|
+
if (n === 0) return null;
|
|
4125
|
+
let sx = 0;
|
|
4126
|
+
let sy = 0;
|
|
4127
|
+
for (let i = 0; i < n; i++) {
|
|
4128
|
+
sx += points[2 * i];
|
|
4129
|
+
sy += points[2 * i + 1];
|
|
4130
|
+
}
|
|
4131
|
+
return {
|
|
4132
|
+
x: sx / n,
|
|
4133
|
+
y: sy / n
|
|
4134
|
+
};
|
|
4135
|
+
}
|
|
4136
|
+
/**
|
|
4137
|
+
* Index a set of polygons.
|
|
4138
|
+
*
|
|
4139
|
+
* @param items - The polygons.
|
|
4140
|
+
* @param cell - The grid cell side in image pixels. Defaults to the median of the polygons'
|
|
4141
|
+
* larger bounding-box sides, within `[8, 256]`, doubled if the grid would be huge.
|
|
4142
|
+
* @returns The index.
|
|
4143
|
+
*/
|
|
4144
|
+
function buildAreaIndex(items, cell) {
|
|
4145
|
+
const count = items.length;
|
|
4146
|
+
const bounds = new Float64Array(count * 4).fill(NaN);
|
|
4147
|
+
const size = new Float64Array(count);
|
|
4148
|
+
let minX = Infinity;
|
|
4149
|
+
let minY = Infinity;
|
|
4150
|
+
let maxX = -Infinity;
|
|
4151
|
+
let maxY = -Infinity;
|
|
4152
|
+
const sides = [];
|
|
4153
|
+
items.forEach((item, a) => {
|
|
4154
|
+
const p = item.points;
|
|
4155
|
+
let x0 = Infinity;
|
|
4156
|
+
let y0 = Infinity;
|
|
4157
|
+
let x1 = -Infinity;
|
|
4158
|
+
let y1 = -Infinity;
|
|
4159
|
+
for (let i = 0; i + 1 < p.length; i += 2) {
|
|
4160
|
+
const x = p[i];
|
|
4161
|
+
const y = p[i + 1];
|
|
4162
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
|
4163
|
+
if (x < x0) x0 = x;
|
|
4164
|
+
if (x > x1) x1 = x;
|
|
4165
|
+
if (y < y0) y0 = y;
|
|
4166
|
+
if (y > y1) y1 = y;
|
|
4167
|
+
}
|
|
4168
|
+
if (!(x1 >= x0)) return;
|
|
4169
|
+
bounds[4 * a] = x0;
|
|
4170
|
+
bounds[4 * a + 1] = y0;
|
|
4171
|
+
bounds[4 * a + 2] = x1;
|
|
4172
|
+
bounds[4 * a + 3] = y1;
|
|
4173
|
+
size[a] = polygonArea(p);
|
|
4174
|
+
minX = Math.min(minX, x0);
|
|
4175
|
+
minY = Math.min(minY, y0);
|
|
4176
|
+
maxX = Math.max(maxX, x1);
|
|
4177
|
+
maxY = Math.max(maxY, y1);
|
|
4178
|
+
sides.push(Math.max(x1 - x0, y1 - y0));
|
|
4179
|
+
});
|
|
4180
|
+
if (sides.length === 0) return {
|
|
4181
|
+
items,
|
|
4182
|
+
bounds,
|
|
4183
|
+
size,
|
|
4184
|
+
cell: 1,
|
|
4185
|
+
x0: 0,
|
|
4186
|
+
y0: 0,
|
|
4187
|
+
cols: 1,
|
|
4188
|
+
rows: 1,
|
|
4189
|
+
starts: /* @__PURE__ */ new Uint32Array(2),
|
|
4190
|
+
entries: /* @__PURE__ */ new Uint32Array(0)
|
|
4191
|
+
};
|
|
4192
|
+
sides.sort((a, b) => a - b);
|
|
4193
|
+
let side = cell ?? Math.min(256, Math.max(8, sides[sides.length >> 1]));
|
|
4194
|
+
const width = maxX - minX;
|
|
4195
|
+
const height = maxY - minY;
|
|
4196
|
+
const cellsAt = (s) => (Math.floor(width / s) + 1) * (Math.floor(height / s) + 1);
|
|
4197
|
+
const entriesAt = (s) => {
|
|
4198
|
+
let total = 0;
|
|
4199
|
+
for (let a = 0; a < count; a++) {
|
|
4200
|
+
if (Number.isNaN(bounds[4 * a])) continue;
|
|
4201
|
+
total += (Math.floor((bounds[4 * a + 2] - bounds[4 * a]) / s) + 1) * (Math.floor((bounds[4 * a + 3] - bounds[4 * a + 1]) / s) + 1);
|
|
4202
|
+
}
|
|
4203
|
+
return total;
|
|
4204
|
+
};
|
|
4205
|
+
while (cellsAt(side) > MAX_CELLS || entriesAt(side) > MAX_ENTRIES) side *= 2;
|
|
4206
|
+
const cols = Math.floor(width / side) + 1;
|
|
4207
|
+
const rows = Math.floor(height / side) + 1;
|
|
4208
|
+
const cellX = (x) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / side)));
|
|
4209
|
+
const cellY = (y) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / side)));
|
|
4210
|
+
const starts = new Uint32Array(cols * rows + 1);
|
|
4211
|
+
const visit = (fn) => {
|
|
4212
|
+
for (let a = 0; a < count; a++) {
|
|
4213
|
+
if (Number.isNaN(bounds[4 * a])) continue;
|
|
4214
|
+
const cx0 = cellX(bounds[4 * a]);
|
|
4215
|
+
const cx1 = cellX(bounds[4 * a + 2]);
|
|
4216
|
+
const cy0 = cellY(bounds[4 * a + 1]);
|
|
4217
|
+
const cy1 = cellY(bounds[4 * a + 3]);
|
|
4218
|
+
for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, a);
|
|
4219
|
+
}
|
|
4220
|
+
};
|
|
4221
|
+
visit((c) => starts[c + 1]++);
|
|
4222
|
+
for (let c = 0; c < cols * rows; c++) starts[c + 1] += starts[c];
|
|
4223
|
+
const fill = starts.slice(0, cols * rows);
|
|
4224
|
+
const entries = new Uint32Array(starts[cols * rows]);
|
|
4225
|
+
visit((c, a) => {
|
|
4226
|
+
entries[fill[c]++] = a;
|
|
4227
|
+
});
|
|
4228
|
+
return {
|
|
4229
|
+
items,
|
|
4230
|
+
bounds,
|
|
4231
|
+
size,
|
|
4232
|
+
cell: side,
|
|
4233
|
+
x0: minX,
|
|
4234
|
+
y0: minY,
|
|
4235
|
+
cols,
|
|
4236
|
+
rows,
|
|
4237
|
+
starts,
|
|
4238
|
+
entries
|
|
4239
|
+
};
|
|
4240
|
+
}
|
|
4241
|
+
/** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */
|
|
4242
|
+
function candidates(index, left, top, right, bottom) {
|
|
4243
|
+
const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
|
|
4244
|
+
if (entries.length === 0) return [];
|
|
4245
|
+
const cx0 = Math.max(0, Math.floor((left - x0) / cell));
|
|
4246
|
+
const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));
|
|
4247
|
+
const cy0 = Math.max(0, Math.floor((top - y0) / cell));
|
|
4248
|
+
const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));
|
|
4249
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4250
|
+
for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) {
|
|
4251
|
+
const c = cy * cols + cx;
|
|
4252
|
+
for (let k = starts[c]; k < starts[c + 1]; k++) {
|
|
4253
|
+
const a = entries[k];
|
|
4254
|
+
if (seen.has(a)) continue;
|
|
4255
|
+
if (bounds[4 * a] <= right && bounds[4 * a + 2] >= left && bounds[4 * a + 1] <= bottom && bounds[4 * a + 3] >= top) seen.add(a);
|
|
4256
|
+
}
|
|
4257
|
+
}
|
|
4258
|
+
return [...seen].sort((a, b) => a - b);
|
|
4259
|
+
}
|
|
4260
|
+
/**
|
|
4261
|
+
* The area under a point: one whose outline passes within `radius`, or else one that contains it.
|
|
4262
|
+
*
|
|
4263
|
+
* An outline is the more precise gesture, so it wins: among areas whose outline is within
|
|
4264
|
+
* `radius` the nearest is picked, and only without one the containing area. Ties (equal
|
|
4265
|
+
* distance, or several containing areas) go to the smaller area, so a quad drawn inside a
|
|
4266
|
+
* region is picked rather than the region, then to the earlier one. The result does not depend
|
|
4267
|
+
* on cell order.
|
|
4268
|
+
*
|
|
4269
|
+
* @param index - The index.
|
|
4270
|
+
* @param p - The query, in image coordinates.
|
|
4271
|
+
* @param radius - How far from an outline the query still picks it, in image pixels.
|
|
4272
|
+
* @returns The area, or `null`.
|
|
4273
|
+
*/
|
|
4274
|
+
function nearestArea(index, p, radius) {
|
|
4275
|
+
if (!(radius >= 0)) return null;
|
|
4276
|
+
const { items, size } = index;
|
|
4277
|
+
let edge = null;
|
|
4278
|
+
let inner = null;
|
|
4279
|
+
for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
|
|
4280
|
+
const points = items[a].points;
|
|
4281
|
+
const distance = distanceToOutline(points, p.x, p.y);
|
|
4282
|
+
const inside = pointInPolygon(points, p.x, p.y);
|
|
4283
|
+
const hit = {
|
|
4284
|
+
id: items[a].id,
|
|
4285
|
+
index: a,
|
|
4286
|
+
inside,
|
|
4287
|
+
distance
|
|
4288
|
+
};
|
|
4289
|
+
if (distance <= radius) {
|
|
4290
|
+
if (edge === null || distance < edge.distance || distance === edge.distance && size[a] < size[edge.index]) edge = hit;
|
|
4291
|
+
} else if (inside && (inner === null || size[a] < size[inner.index])) inner = hit;
|
|
4292
|
+
}
|
|
4293
|
+
return edge ?? inner;
|
|
4294
|
+
}
|
|
4295
|
+
/**
|
|
4296
|
+
* The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole
|
|
4297
|
+
* rectangle lying inside the polygon.
|
|
4298
|
+
*
|
|
4299
|
+
* @param index - The index.
|
|
4300
|
+
* @param rect - The band, in image coordinates. A negative extent is read as the box between
|
|
4301
|
+
* its corners.
|
|
4302
|
+
* @returns Their ids, in the order the areas were given.
|
|
4303
|
+
*/
|
|
4304
|
+
function areasInRect(index, rect) {
|
|
4305
|
+
const box = {
|
|
4306
|
+
x: Math.min(rect.x, rect.x + rect.width),
|
|
4307
|
+
y: Math.min(rect.y, rect.y + rect.height),
|
|
4308
|
+
width: Math.abs(rect.width),
|
|
4309
|
+
height: Math.abs(rect.height)
|
|
4310
|
+
};
|
|
4311
|
+
const out = [];
|
|
4312
|
+
for (const a of candidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) if (polygonTouchesRect(index.items[a].points, box)) out.push(index.items[a].id);
|
|
4313
|
+
return out;
|
|
4314
|
+
}
|
|
4315
|
+
function polygonTouchesRect(points, rect) {
|
|
4316
|
+
const n = vertexCount(points);
|
|
4317
|
+
const right = rect.x + rect.width;
|
|
4318
|
+
const bottom = rect.y + rect.height;
|
|
4319
|
+
for (let i = 0; i < n; i++) {
|
|
4320
|
+
const x = points[2 * i];
|
|
4321
|
+
const y = points[2 * i + 1];
|
|
4322
|
+
if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;
|
|
4323
|
+
}
|
|
4324
|
+
const edges = n < 2 ? 0 : n === 2 ? 1 : n;
|
|
4325
|
+
for (let i = 0; i < edges; i++) {
|
|
4326
|
+
const j = (i + 1) % n;
|
|
4327
|
+
if (segmentTouchesRect(points[2 * i], points[2 * i + 1], points[2 * j], points[2 * j + 1], rect)) return true;
|
|
4328
|
+
}
|
|
4329
|
+
return pointInPolygon(points, rect.x, rect.y);
|
|
4330
|
+
}
|
|
4331
|
+
//#endregion
|
|
4332
|
+
//#region src/components/AreaSet.tsx
|
|
4333
|
+
/**
|
|
4334
|
+
* Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,
|
|
4335
|
+
* region annotations, defect outlines.
|
|
4336
|
+
*
|
|
4337
|
+
* Drawn as a handful of batched paths, one per (state, role), each outline with its 12 % fill
|
|
4338
|
+
* in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the
|
|
4339
|
+
* stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen
|
|
4340
|
+
* pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.
|
|
4341
|
+
*/
|
|
4342
|
+
const HALO$3 = overlayRole("halo");
|
|
4343
|
+
const LABEL = overlayRole("label");
|
|
4344
|
+
/** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */
|
|
4345
|
+
const FILL_OPACITY = .12;
|
|
4346
|
+
/** How long the first-vertex tick is, in screen pixels, at most. */
|
|
4347
|
+
const TICK_PX = 8;
|
|
4348
|
+
/**
|
|
4349
|
+
* A selectable set of closed regions inside an `ImageStage`.
|
|
4350
|
+
*
|
|
4351
|
+
* - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default).
|
|
4352
|
+
* Rings are wound alike before they are batched, so overlapping regions never cut a hole in
|
|
4353
|
+
* each other.
|
|
4354
|
+
* - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and
|
|
4355
|
+
* `structure`), hover 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every
|
|
4356
|
+
* outline has a halo. A region has no ring: its outline at 2.5 px is the mark.
|
|
4357
|
+
* - **Labels** at the centre of a region, only where regions are at least 24 screen px apart,
|
|
4358
|
+
* at most 200 at a time. The hovered and selected regions always carry theirs.
|
|
4359
|
+
* - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
|
|
4360
|
+
* an outline picks that region, else the smallest region containing the point. `onHoverChange`
|
|
4361
|
+
* and `onItemPress` here, and `useStageHitTest` for an app that arbitrates between layers.
|
|
4362
|
+
*
|
|
4363
|
+
* The SVG carries `data-hovered` (the hovered id).
|
|
4364
|
+
*/
|
|
4365
|
+
function AreaSet({ items, role = "feature", hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, labels = true, firstVertexTick = false, halo = true, selectionStroke = overlayRole("selection"), layerId, priority = STAGE_HIT_PRIORITY.area, label = "Areas" }) {
|
|
4366
|
+
const stage = useStage();
|
|
4367
|
+
const px = useScreenPx();
|
|
4368
|
+
const unit = px(1);
|
|
4369
|
+
const index = useMemo(() => buildAreaIndex(items), [items]);
|
|
4370
|
+
const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
|
|
4371
|
+
const isDimmed = useMemo(() => {
|
|
4372
|
+
if (typeof dimmed === "function") return dimmed;
|
|
4373
|
+
const set = new Set(dimmed ?? []);
|
|
4374
|
+
return (id) => set.has(id);
|
|
4375
|
+
}, [dimmed]);
|
|
4376
|
+
const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
|
|
4377
|
+
const [ownHover, setOwnHover] = useState(null);
|
|
4378
|
+
const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
|
|
4379
|
+
useStageHitLayer({
|
|
4380
|
+
layerId,
|
|
4381
|
+
priority,
|
|
4382
|
+
pick: (point, radius) => {
|
|
4383
|
+
const hit = nearestArea(index, point, radius);
|
|
4384
|
+
return hit ? {
|
|
4385
|
+
id: hit.id,
|
|
4386
|
+
dist: hit.inside ? 0 : hit.distance
|
|
4387
|
+
} : null;
|
|
4388
|
+
},
|
|
4389
|
+
onHover: (id) => {
|
|
4390
|
+
setOwnHover(id);
|
|
4391
|
+
onHoverChange?.(id);
|
|
4392
|
+
},
|
|
4393
|
+
onPress: onItemPress ? (id, event) => onItemPress(id, event) : void 0
|
|
4394
|
+
});
|
|
4395
|
+
const groups = useMemo(() => {
|
|
4396
|
+
const normal = /* @__PURE__ */ new Map();
|
|
4397
|
+
const picked = {
|
|
4398
|
+
key: "selected",
|
|
4399
|
+
role: "selection",
|
|
4400
|
+
dim: false,
|
|
4401
|
+
indices: [],
|
|
4402
|
+
d: ""
|
|
4403
|
+
};
|
|
4404
|
+
items.forEach((item, i) => {
|
|
4405
|
+
if (selectedSet.has(item.id)) {
|
|
4406
|
+
picked.indices.push(i);
|
|
4407
|
+
picked.d += areaPath(item.points);
|
|
4408
|
+
return;
|
|
4409
|
+
}
|
|
4410
|
+
const itemRole = item.role ?? role;
|
|
4411
|
+
const dim = isDimmed(item.id);
|
|
4412
|
+
const key = `${dim ? 1 : 0}|${itemRole}`;
|
|
4413
|
+
let batch = normal.get(key);
|
|
4414
|
+
if (!batch) {
|
|
4415
|
+
batch = {
|
|
4416
|
+
key,
|
|
4417
|
+
role: itemRole,
|
|
4418
|
+
dim,
|
|
4419
|
+
indices: [],
|
|
4420
|
+
d: ""
|
|
4421
|
+
};
|
|
4422
|
+
normal.set(key, batch);
|
|
4423
|
+
}
|
|
4424
|
+
batch.indices.push(i);
|
|
4425
|
+
batch.d += areaPath(item.points);
|
|
4426
|
+
});
|
|
4427
|
+
return {
|
|
4428
|
+
normal: [...normal.values()],
|
|
4429
|
+
picked: picked.indices.length > 0 ? picked : null
|
|
4430
|
+
};
|
|
4431
|
+
}, [
|
|
4432
|
+
items,
|
|
4433
|
+
role,
|
|
4434
|
+
selectedSet,
|
|
4435
|
+
isDimmed
|
|
4436
|
+
]);
|
|
4437
|
+
const ticks = useMemo(() => {
|
|
4438
|
+
if (!firstVertexTick) return [];
|
|
4439
|
+
return (groups.picked ? [...groups.normal, groups.picked] : groups.normal).map((batch) => {
|
|
4440
|
+
let d = "";
|
|
4441
|
+
for (const i of batch.indices) d += tickPath(items[i].points, TICK_PX * unit);
|
|
4442
|
+
return {
|
|
4443
|
+
batch,
|
|
4444
|
+
d
|
|
4445
|
+
};
|
|
4446
|
+
});
|
|
4447
|
+
}, [
|
|
4448
|
+
firstVertexTick,
|
|
4449
|
+
groups,
|
|
4450
|
+
items,
|
|
4451
|
+
unit
|
|
4452
|
+
]);
|
|
4453
|
+
const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : void 0;
|
|
4454
|
+
const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
|
|
4455
|
+
const hoverRole = hoverItem?.role ?? role;
|
|
4456
|
+
const anchors = useMemo(() => {
|
|
4457
|
+
const xy = new Float64Array(items.length * 2);
|
|
4458
|
+
const labelled = [];
|
|
4459
|
+
items.forEach((item, i) => {
|
|
4460
|
+
const c = areaCentre(item.points);
|
|
4461
|
+
xy[2 * i] = c?.x ?? NaN;
|
|
4462
|
+
xy[2 * i + 1] = c?.y ?? NaN;
|
|
4463
|
+
if (item.label) labelled.push(i);
|
|
4464
|
+
});
|
|
4465
|
+
return {
|
|
4466
|
+
xy,
|
|
4467
|
+
labelled
|
|
4468
|
+
};
|
|
4469
|
+
}, [items]);
|
|
4470
|
+
const forced = useMemo(() => {
|
|
4471
|
+
const list = [];
|
|
4472
|
+
if (hoverItem?.label) list.push(positionOf.get(hoverItem.id));
|
|
4473
|
+
for (const id of selectedSet) {
|
|
4474
|
+
const i = positionOf.get(id);
|
|
4475
|
+
if (i !== void 0 && items[i].label) list.push(i);
|
|
4476
|
+
}
|
|
4477
|
+
return list;
|
|
4478
|
+
}, [
|
|
4479
|
+
hoverItem,
|
|
4480
|
+
selectedSet,
|
|
4481
|
+
positionOf,
|
|
4482
|
+
items
|
|
4483
|
+
]);
|
|
4484
|
+
const shownLabels = useLabelIndices({
|
|
4485
|
+
enabled: labels,
|
|
4486
|
+
xy: anchors.xy,
|
|
4487
|
+
labelled: anchors.labelled,
|
|
4488
|
+
forced
|
|
4489
|
+
});
|
|
4490
|
+
const widthOf = (itemRole, state) => {
|
|
4491
|
+
const thin = itemRole === "model" || itemRole === "structure";
|
|
4492
|
+
return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
|
|
4493
|
+
};
|
|
4494
|
+
return /* @__PURE__ */ jsxs("svg", {
|
|
4495
|
+
viewBox: imageViewBox(stage.image),
|
|
4496
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
4497
|
+
role: "img",
|
|
4498
|
+
"aria-label": `${label}: ${items.length} ${items.length === 1 ? "area" : "areas"}, ${selectedSet.size} selected`,
|
|
4499
|
+
"data-hovered": hoverId ?? void 0,
|
|
4500
|
+
children: [/* @__PURE__ */ jsxs("g", {
|
|
4501
|
+
fill: "none",
|
|
4502
|
+
strokeLinecap: "round",
|
|
4503
|
+
strokeLinejoin: "round",
|
|
4504
|
+
children: [
|
|
4505
|
+
groups.normal.map((batch) => /* @__PURE__ */ jsxs("g", {
|
|
4506
|
+
opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
|
|
4507
|
+
children: [halo && /* @__PURE__ */ jsx("path", {
|
|
4508
|
+
d: batch.d,
|
|
4509
|
+
stroke: HALO$3,
|
|
4510
|
+
strokeWidth: widthOf(batch.role, "default") + px(2),
|
|
4511
|
+
opacity: .6
|
|
4512
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
4513
|
+
"data-batch": batch.key,
|
|
4514
|
+
d: batch.d,
|
|
4515
|
+
fill: overlayRole(batch.role),
|
|
4516
|
+
fillOpacity: FILL_OPACITY,
|
|
4517
|
+
stroke: overlayRole(batch.role),
|
|
4518
|
+
strokeWidth: widthOf(batch.role, "default")
|
|
4519
|
+
})]
|
|
4520
|
+
}, batch.key)),
|
|
4521
|
+
groups.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
|
|
4522
|
+
d: groups.picked.d,
|
|
4523
|
+
stroke: HALO$3,
|
|
4524
|
+
strokeWidth: widthOf("selection", "selected") + px(2)
|
|
4525
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
4526
|
+
"data-selected-areas": "",
|
|
4527
|
+
d: groups.picked.d,
|
|
4528
|
+
fill: selectionStroke,
|
|
4529
|
+
fillOpacity: FILL_OPACITY,
|
|
4530
|
+
stroke: selectionStroke,
|
|
4531
|
+
strokeWidth: widthOf("selection", "selected")
|
|
4532
|
+
})] }),
|
|
4533
|
+
hoverItem && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
|
|
4534
|
+
d: areaPath(hoverItem.points),
|
|
4535
|
+
stroke: HALO$3,
|
|
4536
|
+
strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover") + px(2)
|
|
4537
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
4538
|
+
"data-hovered-area": "",
|
|
4539
|
+
d: areaPath(hoverItem.points),
|
|
4540
|
+
stroke: hoverSelected ? selectionStroke : overlayRole(hoverRole),
|
|
4541
|
+
strokeWidth: widthOf(hoverRole, hoverSelected ? "selected" : "hover")
|
|
4542
|
+
})] }),
|
|
4543
|
+
ticks.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
|
|
4544
|
+
opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
|
|
4545
|
+
children: [halo && /* @__PURE__ */ jsx("path", {
|
|
4546
|
+
d,
|
|
4547
|
+
stroke: HALO$3,
|
|
4548
|
+
strokeWidth: px(OVERLAY_STATE_WIDTH.selected + 2),
|
|
4549
|
+
opacity: .6
|
|
4550
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
4551
|
+
"data-ticks": batch.key,
|
|
4552
|
+
d,
|
|
4553
|
+
stroke: batch === groups.picked ? selectionStroke : overlayRole(batch.role),
|
|
4554
|
+
strokeWidth: px(OVERLAY_STATE_WIDTH.selected)
|
|
4555
|
+
})]
|
|
4556
|
+
}, `tick|${batch.key}`))
|
|
4557
|
+
]
|
|
4558
|
+
}), shownLabels.length > 0 && /* @__PURE__ */ jsx("g", {
|
|
4559
|
+
"data-labels": "",
|
|
4560
|
+
fontSize: px(11),
|
|
4561
|
+
className: "font-mono",
|
|
4562
|
+
stroke: HALO$3,
|
|
4563
|
+
strokeWidth: px(3),
|
|
4564
|
+
paintOrder: "stroke",
|
|
4565
|
+
strokeLinejoin: "round",
|
|
4566
|
+
children: shownLabels.map((i) => /* @__PURE__ */ jsx("text", {
|
|
4567
|
+
x: anchors.xy[2 * i],
|
|
4568
|
+
y: anchors.xy[2 * i + 1],
|
|
4569
|
+
fill: LABEL,
|
|
4570
|
+
textAnchor: "middle",
|
|
4571
|
+
dominantBaseline: "central",
|
|
4572
|
+
children: items[i].label
|
|
4573
|
+
}, items[i].id))
|
|
4574
|
+
})]
|
|
4575
|
+
});
|
|
4576
|
+
}
|
|
4577
|
+
/**
|
|
4578
|
+
* The first-vertex tick of a ring: a segment from vertex 0 towards the ring's centre, at most
|
|
4579
|
+
* `length` long and at most 45 % of the way there, so a small quad's tick stays inside it.
|
|
4580
|
+
*/
|
|
4581
|
+
function tickPath(points, length) {
|
|
4582
|
+
const c = areaCentre(points);
|
|
4583
|
+
if (c === null || points.length < 4) return "";
|
|
4584
|
+
const x = points[0];
|
|
4585
|
+
const y = points[1];
|
|
4586
|
+
const dist = Math.hypot(c.x - x, c.y - y);
|
|
4587
|
+
if (!(dist > 0)) return "";
|
|
4588
|
+
const k = Math.min(length, .45 * dist) / dist;
|
|
4589
|
+
return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1e3) / 1e3} ${Math.round((y + (c.y - y) * k) * 1e3) / 1e3}`;
|
|
4590
|
+
}
|
|
4591
|
+
//#endregion
|
|
4592
|
+
//#region src/components/gridEdges.ts
|
|
4593
|
+
/** Indices past this magnitude are not hashed (the key must stay an exact integer). */
|
|
4594
|
+
const LIMIT = 2 ** 25;
|
|
4595
|
+
function key(i, j) {
|
|
4596
|
+
return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
|
|
4597
|
+
}
|
|
4598
|
+
/**
|
|
4599
|
+
* The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
|
|
4600
|
+
* axis.
|
|
4601
|
+
*
|
|
4602
|
+
* @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
|
|
4603
|
+
* integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
|
|
4604
|
+
* first one is the lattice's node there.
|
|
4605
|
+
* @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
|
|
4606
|
+
*/
|
|
4607
|
+
function latticeEdges(nodes) {
|
|
4608
|
+
const at = /* @__PURE__ */ new Map();
|
|
4609
|
+
const valid = (n) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
|
|
4610
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
4611
|
+
const node = nodes[p];
|
|
4612
|
+
if (!valid(node)) continue;
|
|
4613
|
+
const k = key(node.i, node.j);
|
|
4614
|
+
if (!at.has(k)) at.set(k, p);
|
|
4615
|
+
}
|
|
4616
|
+
const edges = [];
|
|
4617
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
4618
|
+
const node = nodes[p];
|
|
4619
|
+
if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
|
|
4620
|
+
if (node.i + 1 < LIMIT) {
|
|
4621
|
+
const q = at.get(key(node.i + 1, node.j));
|
|
4622
|
+
if (q !== void 0) edges.push({
|
|
4623
|
+
a: p,
|
|
4624
|
+
b: q,
|
|
4625
|
+
axis: "i"
|
|
4626
|
+
});
|
|
4627
|
+
}
|
|
4628
|
+
if (node.j + 1 < LIMIT) {
|
|
4629
|
+
const q = at.get(key(node.i, node.j + 1));
|
|
4630
|
+
if (q !== void 0) edges.push({
|
|
4631
|
+
a: p,
|
|
4632
|
+
b: q,
|
|
4633
|
+
axis: "j"
|
|
4634
|
+
});
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4637
|
+
return edges;
|
|
4638
|
+
}
|
|
4639
|
+
//#endregion
|
|
4640
|
+
//#region src/components/GridLayer.tsx
|
|
4641
|
+
/**
|
|
4642
|
+
* A detected lattice over the image: the corners of a calibration board with the row and
|
|
4643
|
+
* column edges between neighbours, and optional `(i, j)` labels.
|
|
4644
|
+
*
|
|
4645
|
+
* Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of
|
|
4646
|
+
* 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1
|
|
4647
|
+
* and 4). Edges are not picked: a person points at a corner.
|
|
4648
|
+
*/
|
|
4649
|
+
const HALO$2 = overlayRole("halo");
|
|
4650
|
+
/** A style with its defaults filled in. */
|
|
4651
|
+
function edgeStyle(style) {
|
|
4652
|
+
return {
|
|
4653
|
+
role: style?.role ?? "structure",
|
|
4654
|
+
dashed: style?.dashed ?? false,
|
|
4655
|
+
visible: style?.visible ?? true
|
|
4656
|
+
};
|
|
4657
|
+
}
|
|
4658
|
+
/**
|
|
4659
|
+
* A detected lattice inside an `ImageStage`.
|
|
4660
|
+
*
|
|
4661
|
+
* - **Nodes** are a `PointSet`: `plus` markers by default, picked through the point index at
|
|
4662
|
+
* point priority, with `onHoverChange`, `onItemPress`, selection (with ring) and dimming.
|
|
4663
|
+
* - **Edges** join `(i, j)` to `(i + 1, j)` and to `(i, j + 1)` where both nodes exist
|
|
4664
|
+
* (`latticeEdges`), in one path per axis and dimming, below the nodes. They are `structure`
|
|
4665
|
+
* role by default, 1 screen px with a halo; `edges` restyles each axis.
|
|
4666
|
+
* - **Labels** are the nodes' own `label`s, or with `indexLabels` their `i,j`, only where nodes
|
|
4667
|
+
* are at least 24 screen px apart.
|
|
4668
|
+
*
|
|
4669
|
+
* The edges' SVG carries `data-edges`; the nodes' is the `PointSet`'s.
|
|
4670
|
+
*/
|
|
4671
|
+
function GridLayer({ nodes, edges, kind = "plus", markers, indexLabels = false, labels = true, hoveredId, onHoverChange, selectedIds, dimmed, onItemPress, halo = true, selectionStroke, layerId, priority = STAGE_HIT_PRIORITY.point, label = "Grid" }) {
|
|
4672
|
+
const stage = useStage();
|
|
4673
|
+
const px = useScreenPx();
|
|
4674
|
+
const styles = {
|
|
4675
|
+
i: edgeStyle(edges?.i),
|
|
4676
|
+
j: edgeStyle(edges?.j)
|
|
4677
|
+
};
|
|
4678
|
+
const isDimmed = useMemo(() => {
|
|
4679
|
+
if (typeof dimmed === "function") return dimmed;
|
|
4680
|
+
const set = new Set(dimmed ?? []);
|
|
4681
|
+
return (id) => set.has(id);
|
|
4682
|
+
}, [dimmed]);
|
|
4683
|
+
const batches = useMemo(() => {
|
|
4684
|
+
const map = /* @__PURE__ */ new Map();
|
|
4685
|
+
for (const edge of latticeEdges(nodes)) {
|
|
4686
|
+
const a = nodes[edge.a];
|
|
4687
|
+
const b = nodes[edge.b];
|
|
4688
|
+
if (!Number.isFinite(a.x + a.y + b.x + b.y)) continue;
|
|
4689
|
+
const dim = isDimmed(a.id) && isDimmed(b.id);
|
|
4690
|
+
const k = `${edge.axis}|${dim ? 1 : 0}`;
|
|
4691
|
+
let batch = map.get(k);
|
|
4692
|
+
if (!batch) {
|
|
4693
|
+
batch = {
|
|
4694
|
+
key: k,
|
|
4695
|
+
axis: edge.axis,
|
|
4696
|
+
dim,
|
|
4697
|
+
d: ""
|
|
4698
|
+
};
|
|
4699
|
+
map.set(k, batch);
|
|
4700
|
+
}
|
|
4701
|
+
batch.d += `M${a.x} ${a.y}L${b.x} ${b.y}`;
|
|
4702
|
+
}
|
|
4703
|
+
return [...map.values()];
|
|
4704
|
+
}, [nodes, isDimmed]);
|
|
4705
|
+
const items = useMemo(() => indexLabels ? nodes.map((node) => node.label ? node : {
|
|
4706
|
+
...node,
|
|
4707
|
+
label: `${node.i},${node.j}`
|
|
4708
|
+
}) : nodes, [nodes, indexLabels]);
|
|
4709
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("svg", {
|
|
4710
|
+
viewBox: imageViewBox(stage.image),
|
|
4711
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
4712
|
+
"data-edges": "",
|
|
4713
|
+
"aria-hidden": true,
|
|
4714
|
+
children: /* @__PURE__ */ jsx("g", {
|
|
4715
|
+
fill: "none",
|
|
4716
|
+
strokeLinecap: "round",
|
|
4717
|
+
strokeLinejoin: "round",
|
|
4718
|
+
children: batches.filter((batch) => styles[batch.axis].visible).map((batch) => {
|
|
4719
|
+
const style = styles[batch.axis];
|
|
4720
|
+
const thin = style.role === "model" || style.role === "structure";
|
|
4721
|
+
const width = px(OVERLAY_STATE_WIDTH.default - (thin ? .5 : 0));
|
|
4722
|
+
const dash = style.dashed ? `${px(4)} ${px(3)}` : void 0;
|
|
4723
|
+
return /* @__PURE__ */ jsxs("g", {
|
|
4724
|
+
opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
|
|
4725
|
+
children: [halo && /* @__PURE__ */ jsx("path", {
|
|
4726
|
+
d: batch.d,
|
|
4727
|
+
stroke: HALO$2,
|
|
4728
|
+
strokeWidth: width + px(2),
|
|
4729
|
+
opacity: .6
|
|
4730
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
4731
|
+
"data-edge-batch": batch.key,
|
|
4732
|
+
d: batch.d,
|
|
4733
|
+
stroke: overlayRole(style.role),
|
|
4734
|
+
strokeWidth: width,
|
|
4735
|
+
strokeDasharray: dash
|
|
4736
|
+
})]
|
|
4737
|
+
}, batch.key);
|
|
4738
|
+
})
|
|
4739
|
+
})
|
|
4740
|
+
}), /* @__PURE__ */ jsx(PointSet, {
|
|
4741
|
+
items,
|
|
4742
|
+
kind,
|
|
4743
|
+
markers,
|
|
4744
|
+
hoveredId,
|
|
4745
|
+
onHoverChange,
|
|
4746
|
+
selectedIds,
|
|
4747
|
+
dimmed,
|
|
4748
|
+
onItemPress,
|
|
4749
|
+
labels,
|
|
4750
|
+
halo,
|
|
4751
|
+
selectionStroke,
|
|
4752
|
+
layerId,
|
|
4753
|
+
priority,
|
|
4754
|
+
label
|
|
4755
|
+
})] });
|
|
4756
|
+
}
|
|
4757
|
+
//#endregion
|
|
4758
|
+
//#region src/components/heatmapRaster.ts
|
|
4759
|
+
/** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */
|
|
4760
|
+
const STEPS = 256;
|
|
4761
|
+
/**
|
|
4762
|
+
* The extent of a plane's finite values.
|
|
4763
|
+
*
|
|
4764
|
+
* @param plane - The plane.
|
|
4765
|
+
* @param channel - Which of its channels. Defaults to the first.
|
|
4766
|
+
* @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.
|
|
4767
|
+
*/
|
|
4768
|
+
function planeRange(plane, channel = 0) {
|
|
4769
|
+
if (!(channel >= 0 && channel < plane.channels)) return null;
|
|
4770
|
+
const size = plane.width * plane.height;
|
|
4771
|
+
const offset = channel * size;
|
|
4772
|
+
let low = Infinity;
|
|
4773
|
+
let high = -Infinity;
|
|
4774
|
+
for (let k = 0; k < size; k++) {
|
|
4775
|
+
const v = plane.values[offset + k];
|
|
4776
|
+
if (!Number.isFinite(v)) continue;
|
|
4777
|
+
if (v < low) low = v;
|
|
4778
|
+
if (v > high) high = v;
|
|
4779
|
+
}
|
|
4780
|
+
return low <= high ? {
|
|
4781
|
+
low,
|
|
4782
|
+
high
|
|
4783
|
+
} : null;
|
|
4784
|
+
}
|
|
4785
|
+
/**
|
|
4786
|
+
* Colour a plane through a colour map.
|
|
4787
|
+
*
|
|
4788
|
+
* Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered
|
|
4789
|
+
* pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range
|
|
4790
|
+
* (`high <= low`) draws every pixel in the map's first colour.
|
|
4791
|
+
*
|
|
4792
|
+
* @param plane - The plane.
|
|
4793
|
+
* @param colormap - The colour map; sampled at 256 positions.
|
|
4794
|
+
* @param range - What the map spans. Defaults to the extent of the channel's finite values.
|
|
4795
|
+
* @param channel - Which channel to draw. Defaults to the first.
|
|
4796
|
+
* @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.
|
|
4797
|
+
*/
|
|
4798
|
+
function rasterizePlane(plane, colormap, range, channel = 0) {
|
|
4799
|
+
const size = plane.width * plane.height;
|
|
4800
|
+
const out = new Uint8ClampedArray(size * 4);
|
|
4801
|
+
if (!(channel >= 0 && channel < plane.channels)) return out;
|
|
4802
|
+
const { low, high } = range ?? planeRange(plane, channel) ?? {
|
|
4803
|
+
low: 0,
|
|
4804
|
+
high: 0
|
|
4805
|
+
};
|
|
4806
|
+
const lut = new Uint8ClampedArray(STEPS * 3);
|
|
4807
|
+
for (let s = 0; s < STEPS; s++) {
|
|
4808
|
+
const [r, g, b] = colormap(s / 255);
|
|
4809
|
+
lut[3 * s] = r;
|
|
4810
|
+
lut[3 * s + 1] = g;
|
|
4811
|
+
lut[3 * s + 2] = b;
|
|
4812
|
+
}
|
|
4813
|
+
const scale = high > low ? 255 / (high - low) : 0;
|
|
4814
|
+
const offset = channel * size;
|
|
4815
|
+
for (let k = 0; k < size; k++) {
|
|
4816
|
+
const v = plane.values[offset + k];
|
|
4817
|
+
if (!Number.isFinite(v)) continue;
|
|
4818
|
+
const s = Math.min(255, Math.max(0, Math.round((v - low) * scale)));
|
|
4819
|
+
out[4 * k] = lut[3 * s];
|
|
4820
|
+
out[4 * k + 1] = lut[3 * s + 1];
|
|
4821
|
+
out[4 * k + 2] = lut[3 * s + 2];
|
|
4822
|
+
out[4 * k + 3] = 255;
|
|
4823
|
+
}
|
|
4824
|
+
return out;
|
|
4825
|
+
}
|
|
4826
|
+
//#endregion
|
|
4827
|
+
//#region src/components/HeatmapLayer.tsx
|
|
4828
|
+
/**
|
|
4829
|
+
* A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.
|
|
4830
|
+
*
|
|
4831
|
+
* A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an
|
|
4832
|
+
* offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage
|
|
4833
|
+
* positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel
|
|
4834
|
+
* map costs one element. It takes no pointer events; to read the numbers under the pointer, use
|
|
4835
|
+
* `valueAt` on the plane.
|
|
4836
|
+
*/
|
|
4837
|
+
/**
|
|
4838
|
+
* A heatmap inside an `ImageStage`: a scalar field coloured through a colour map, or an RGBA
|
|
4839
|
+
* buffer, placed over the image (default) or any rectangle of it.
|
|
4840
|
+
*
|
|
4841
|
+
* - **Rasterised in an effect**, once per change of its data, into an offscreen canvas and an
|
|
4842
|
+
* object URL that is revoked when replaced and on unmount. Server rendering draws nothing.
|
|
4843
|
+
* - **Pixelated** from 4 CSS pixels per heatmap pixel, like `ImageLayer`, so the cells of a
|
|
4844
|
+
* coarse map are not smoothed into a blur.
|
|
4845
|
+
* - **Stacking:** it is drawn where it is placed among the stage's children. Before the
|
|
4846
|
+
* overlays it sits under them; the image layer goes before it.
|
|
4847
|
+
* - **Input:** none. It takes no pointer events, so presses reach the layers above and the stage.
|
|
4848
|
+
*
|
|
4849
|
+
* The image carries `data-heatmap`, `data-pixelated` while pixelated, and `data-ready`.
|
|
4850
|
+
*/
|
|
4851
|
+
function HeatmapLayer(props) {
|
|
4852
|
+
const { opacity = 1, visible = true, rect, pixelatedAbove = 4, alt = "", onReady, onError, className } = props;
|
|
4853
|
+
const stage = useStage();
|
|
4854
|
+
const [raster, setRaster] = useState(null);
|
|
4855
|
+
const [ready, setReady] = useState(false);
|
|
4856
|
+
const urlRef = useRef(null);
|
|
4857
|
+
const callbacksRef = useRef({
|
|
4858
|
+
onReady,
|
|
4859
|
+
onError
|
|
4860
|
+
});
|
|
4861
|
+
useEffect(() => {
|
|
4862
|
+
callbacksRef.current = {
|
|
4863
|
+
onReady,
|
|
4864
|
+
onError
|
|
4865
|
+
};
|
|
4866
|
+
});
|
|
4867
|
+
const { rgba, width, height, plane, colormap, channel } = props;
|
|
4868
|
+
const rangeLow = props.range?.low;
|
|
4869
|
+
const rangeHigh = props.range?.high;
|
|
4870
|
+
useEffect(() => {
|
|
4871
|
+
if (!visible) return;
|
|
4872
|
+
let cancelled = false;
|
|
4873
|
+
const source = rgba ? wrapRgba(rgba, width, height) : plane && colormap ? colourPlane(plane, colormap, rangeLow === void 0 || rangeHigh === void 0 ? void 0 : {
|
|
4874
|
+
low: rangeLow,
|
|
4875
|
+
high: rangeHigh
|
|
4876
|
+
}, channel) : null;
|
|
4877
|
+
const canvas = document.createElement("canvas");
|
|
4878
|
+
const context = source ? (canvas.width = source.width, canvas.height = source.height, canvas.getContext("2d")) : null;
|
|
4879
|
+
if (!source || !context) {
|
|
4880
|
+
callbacksRef.current.onError?.();
|
|
4881
|
+
return;
|
|
4882
|
+
}
|
|
4883
|
+
const { width: w, height: h } = source;
|
|
4884
|
+
context.putImageData(new ImageData(source.pixels, w, h), 0, 0);
|
|
4885
|
+
canvas.toBlob((blob) => {
|
|
4886
|
+
if (cancelled) return;
|
|
4887
|
+
if (!blob) {
|
|
4888
|
+
callbacksRef.current.onError?.();
|
|
4889
|
+
return;
|
|
4890
|
+
}
|
|
4891
|
+
const previous = urlRef.current;
|
|
4892
|
+
const url = URL.createObjectURL(blob);
|
|
4893
|
+
urlRef.current = url;
|
|
4894
|
+
setReady(false);
|
|
4895
|
+
setRaster({
|
|
4896
|
+
url,
|
|
4897
|
+
width: w,
|
|
4898
|
+
height: h
|
|
4899
|
+
});
|
|
4900
|
+
if (previous) URL.revokeObjectURL(previous);
|
|
4901
|
+
});
|
|
4902
|
+
return () => {
|
|
4903
|
+
cancelled = true;
|
|
4904
|
+
};
|
|
4905
|
+
}, [
|
|
4906
|
+
visible,
|
|
4907
|
+
rgba,
|
|
4908
|
+
width,
|
|
4909
|
+
height,
|
|
4910
|
+
plane,
|
|
4911
|
+
colormap,
|
|
4912
|
+
rangeLow,
|
|
4913
|
+
rangeHigh,
|
|
4914
|
+
channel
|
|
4915
|
+
]);
|
|
4916
|
+
useEffect(() => () => {
|
|
4917
|
+
if (urlRef.current) URL.revokeObjectURL(urlRef.current);
|
|
4918
|
+
urlRef.current = null;
|
|
4919
|
+
}, []);
|
|
4920
|
+
if (!visible || raster === null) return null;
|
|
4921
|
+
const box = rect ?? {
|
|
4922
|
+
x: -.5,
|
|
4923
|
+
y: -.5,
|
|
4924
|
+
width: stage.image.width,
|
|
4925
|
+
height: stage.image.height
|
|
4926
|
+
};
|
|
4927
|
+
const pixelated = stage.view.scale * box.width / raster.width >= pixelatedAbove;
|
|
4928
|
+
return /* @__PURE__ */ jsx("img", {
|
|
4929
|
+
src: raster.url,
|
|
4930
|
+
alt,
|
|
4931
|
+
draggable: false,
|
|
4932
|
+
"data-heatmap": "",
|
|
4933
|
+
"data-ready": ready ? "" : void 0,
|
|
4934
|
+
"data-pixelated": pixelated ? "" : void 0,
|
|
4935
|
+
onLoad: () => {
|
|
4936
|
+
setReady(true);
|
|
4937
|
+
callbacksRef.current.onReady?.();
|
|
4938
|
+
},
|
|
4939
|
+
className: cn("pointer-events-none absolute max-w-none select-none", className),
|
|
4940
|
+
style: {
|
|
4941
|
+
left: box.x + PIXEL_CENTRE,
|
|
4942
|
+
top: box.y + PIXEL_CENTRE,
|
|
4943
|
+
width: box.width,
|
|
4944
|
+
height: box.height,
|
|
4945
|
+
opacity,
|
|
4946
|
+
pointerEvents: "none",
|
|
4947
|
+
imageRendering: pixelated ? "pixelated" : void 0
|
|
4948
|
+
}
|
|
4949
|
+
});
|
|
4950
|
+
}
|
|
4951
|
+
/** The first `width · height · 4` bytes of an RGBA buffer, read in place; `null` if it is too short or empty. */
|
|
4952
|
+
function wrapRgba(rgba, width, height) {
|
|
4953
|
+
const length = width * height * 4;
|
|
4954
|
+
if (!(length > 0) || rgba.length < length) return null;
|
|
4955
|
+
return {
|
|
4956
|
+
pixels: new Uint8ClampedArray(rgba.buffer, rgba.byteOffset, length),
|
|
4957
|
+
width,
|
|
4958
|
+
height
|
|
4959
|
+
};
|
|
4960
|
+
}
|
|
4961
|
+
/** A plane through a colour map; `null` for an empty plane. */
|
|
4962
|
+
function colourPlane(plane, colormap, range, channel) {
|
|
4963
|
+
if (!(plane.width > 0 && plane.height > 0)) return null;
|
|
4964
|
+
return {
|
|
4965
|
+
pixels: rasterizePlane(plane, colormap, range, channel),
|
|
4966
|
+
width: plane.width,
|
|
4967
|
+
height: plane.height
|
|
4968
|
+
};
|
|
4969
|
+
}
|
|
4970
|
+
//#endregion
|
|
4971
|
+
//#region src/components/shapeEdit.ts
|
|
4972
|
+
/**
|
|
4973
|
+
* A point of image space in the shape's own frame: origin at its centre, axes along its sides.
|
|
4974
|
+
*
|
|
4975
|
+
* @param shape - The shape.
|
|
4976
|
+
* @param p - A point in image coordinates.
|
|
4977
|
+
* @returns The point relative to the shape.
|
|
4978
|
+
*/
|
|
4979
|
+
function toShapeFrame(shape, p) {
|
|
4980
|
+
const c = Math.cos(shape.rotation);
|
|
4981
|
+
const s = Math.sin(shape.rotation);
|
|
4982
|
+
const dx = p.x - shape.cx;
|
|
4983
|
+
const dy = p.y - shape.cy;
|
|
4984
|
+
return {
|
|
4985
|
+
x: c * dx + s * dy,
|
|
4986
|
+
y: -s * dx + c * dy
|
|
4987
|
+
};
|
|
4988
|
+
}
|
|
4989
|
+
/**
|
|
4990
|
+
* A point of the shape's own frame in image space; the inverse of `toShapeFrame`.
|
|
4991
|
+
*
|
|
4992
|
+
* @param shape - The shape.
|
|
4993
|
+
* @param p - A point relative to the shape.
|
|
4994
|
+
* @returns The point in image coordinates.
|
|
4995
|
+
*/
|
|
4996
|
+
function fromShapeFrame(shape, p) {
|
|
4997
|
+
const c = Math.cos(shape.rotation);
|
|
4998
|
+
const s = Math.sin(shape.rotation);
|
|
4999
|
+
return {
|
|
5000
|
+
x: shape.cx + c * p.x - s * p.y,
|
|
5001
|
+
y: shape.cy + s * p.x + c * p.y
|
|
5002
|
+
};
|
|
5003
|
+
}
|
|
5004
|
+
/** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */
|
|
5005
|
+
function handleDirection(handle) {
|
|
5006
|
+
return {
|
|
5007
|
+
x: handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0,
|
|
5008
|
+
y: handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0
|
|
5009
|
+
};
|
|
5010
|
+
}
|
|
5011
|
+
/**
|
|
5012
|
+
* Where a handle sits: a corner or the middle of a side, turned with the shape.
|
|
5013
|
+
*
|
|
5014
|
+
* @param shape - The shape.
|
|
5015
|
+
* @param handle - The handle, by compass direction in the shape's own frame.
|
|
5016
|
+
* @returns The handle's centre, in image coordinates.
|
|
5017
|
+
*/
|
|
5018
|
+
function shapeHandlePoint(shape, handle) {
|
|
5019
|
+
const d = handleDirection(handle);
|
|
5020
|
+
return fromShapeFrame(shape, {
|
|
5021
|
+
x: d.x * shape.width / 2,
|
|
5022
|
+
y: d.y * shape.height / 2
|
|
5023
|
+
});
|
|
5024
|
+
}
|
|
5025
|
+
/**
|
|
5026
|
+
* Where the rotation handle sits: beyond the middle of the top side, along the shape's own
|
|
5027
|
+
* up direction.
|
|
5028
|
+
*
|
|
5029
|
+
* @param shape - The shape.
|
|
5030
|
+
* @param distance - How far past the top side, in image pixels. For a screen-constant handle,
|
|
5031
|
+
* pass `useScreenPx()(css)`.
|
|
5032
|
+
* @returns The handle's centre, in image coordinates.
|
|
5033
|
+
*/
|
|
5034
|
+
function rotationHandlePoint(shape, distance) {
|
|
5035
|
+
return fromShapeFrame(shape, {
|
|
5036
|
+
x: 0,
|
|
5037
|
+
y: -shape.height / 2 - distance
|
|
5038
|
+
});
|
|
5039
|
+
}
|
|
5040
|
+
/**
|
|
5041
|
+
* Drag a handle to `to`.
|
|
5042
|
+
*
|
|
5043
|
+
* The dragged side or corner follows the pointer in the shape's own frame and the opposite
|
|
5044
|
+
* side or corner stays where it is in the image, which is what makes a handle feel attached.
|
|
5045
|
+
* The shape does not flip when dragged through the opposite side: it stops at `minSize`.
|
|
5046
|
+
*
|
|
5047
|
+
* @param shape - The shape before the drag.
|
|
5048
|
+
* @param handle - The handle being dragged.
|
|
5049
|
+
* @param to - The pointer, in image coordinates.
|
|
5050
|
+
* @param minSize - The smallest extent on either axis, in image pixels.
|
|
5051
|
+
* @returns The resized shape: the same rotation, and the opposite side or corner unmoved.
|
|
5052
|
+
*/
|
|
5053
|
+
function resizeShape(shape, handle, to, minSize) {
|
|
5054
|
+
const d = handleDirection(handle);
|
|
5055
|
+
const u = toShapeFrame(shape, to);
|
|
5056
|
+
let width = shape.width;
|
|
5057
|
+
let height = shape.height;
|
|
5058
|
+
let x = 0;
|
|
5059
|
+
let y = 0;
|
|
5060
|
+
if (d.x !== 0) {
|
|
5061
|
+
width = Math.max(minSize, d.x * u.x + shape.width / 2);
|
|
5062
|
+
x = -d.x * (shape.width / 2) + d.x * width / 2;
|
|
5063
|
+
}
|
|
5064
|
+
if (d.y !== 0) {
|
|
5065
|
+
height = Math.max(minSize, d.y * u.y + shape.height / 2);
|
|
5066
|
+
y = -d.y * (shape.height / 2) + d.y * height / 2;
|
|
5067
|
+
}
|
|
5068
|
+
const centre = fromShapeFrame(shape, {
|
|
5069
|
+
x,
|
|
5070
|
+
y
|
|
5071
|
+
});
|
|
5072
|
+
return {
|
|
5073
|
+
cx: centre.x,
|
|
5074
|
+
cy: centre.y,
|
|
5075
|
+
width,
|
|
5076
|
+
height,
|
|
5077
|
+
rotation: shape.rotation
|
|
5078
|
+
};
|
|
5079
|
+
}
|
|
5080
|
+
/**
|
|
5081
|
+
* Turn the shape about its centre so that its rotation handle points at `to`.
|
|
5082
|
+
*
|
|
5083
|
+
* @param shape - The shape before the drag.
|
|
5084
|
+
* @param to - The pointer, in image coordinates.
|
|
5085
|
+
* @param snap - Round the rotation to a multiple of this many radians (Shift while dragging
|
|
5086
|
+
* rounds to 15°). Defaults to no rounding.
|
|
5087
|
+
* @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.
|
|
5088
|
+
*/
|
|
5089
|
+
function rotateShape(shape, to, snap = 0) {
|
|
5090
|
+
let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;
|
|
5091
|
+
if (snap > 0) rotation = Math.round(rotation / snap) * snap;
|
|
5092
|
+
return {
|
|
5093
|
+
...shape,
|
|
5094
|
+
rotation: normalizeAngle(rotation)
|
|
5095
|
+
};
|
|
5096
|
+
}
|
|
5097
|
+
/**
|
|
5098
|
+
* Move the shape.
|
|
5099
|
+
*
|
|
5100
|
+
* @param shape - The shape.
|
|
5101
|
+
* @param dx - Horizontal shift, in image pixels.
|
|
5102
|
+
* @param dy - Vertical shift, in image pixels.
|
|
5103
|
+
* @returns The moved shape.
|
|
5104
|
+
*/
|
|
5105
|
+
function moveShape(shape, dx, dy) {
|
|
5106
|
+
return {
|
|
5107
|
+
...shape,
|
|
5108
|
+
cx: shape.cx + dx,
|
|
5109
|
+
cy: shape.cy + dy
|
|
5110
|
+
};
|
|
5111
|
+
}
|
|
5112
|
+
/**
|
|
5113
|
+
* An angle as the equivalent one in `(-π, π]`.
|
|
5114
|
+
*
|
|
5115
|
+
* @param angle - Radians.
|
|
5116
|
+
* @returns The angle in `(-π, π]`.
|
|
5117
|
+
*/
|
|
5118
|
+
function normalizeAngle(angle) {
|
|
5119
|
+
const turn = 2 * Math.PI;
|
|
5120
|
+
let a = angle % turn;
|
|
5121
|
+
if (a > Math.PI) a -= turn;
|
|
5122
|
+
else if (a <= -Math.PI) a += turn;
|
|
5123
|
+
return a;
|
|
5124
|
+
}
|
|
5125
|
+
/**
|
|
5126
|
+
* The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize
|
|
5127
|
+
* cursors to the handle's direction on screen.
|
|
5128
|
+
*
|
|
5129
|
+
* @param handle - The handle.
|
|
5130
|
+
* @param rotation - The shape's rotation, in radians.
|
|
5131
|
+
* @returns A CSS `cursor` value.
|
|
5132
|
+
*/
|
|
5133
|
+
function shapeHandleCursor(handle, rotation) {
|
|
5134
|
+
const d = handleDirection(handle);
|
|
5135
|
+
const half = ((Math.atan2(d.y, d.x) + rotation) % Math.PI + Math.PI) % Math.PI;
|
|
5136
|
+
return [
|
|
5137
|
+
"ew-resize",
|
|
5138
|
+
"nwse-resize",
|
|
5139
|
+
"ns-resize",
|
|
5140
|
+
"nesw-resize"
|
|
5141
|
+
][Math.round(half / (Math.PI / 4)) % 4];
|
|
5142
|
+
}
|
|
5143
|
+
/**
|
|
5144
|
+
* The shape for a rectangle given as an origin corner, a size and a rotation about that
|
|
5145
|
+
* corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.
|
|
5146
|
+
*
|
|
5147
|
+
* @param corner - The corner the rotation is about, in image coordinates.
|
|
5148
|
+
* @param width - Extent along the rotated x axis.
|
|
5149
|
+
* @param height - Extent along the rotated y axis.
|
|
5150
|
+
* @param rotation - Radians, clockwise on screen.
|
|
5151
|
+
* @returns The same rectangle as a `RotatedShape`.
|
|
5152
|
+
*/
|
|
5153
|
+
function shapeFromCorner(corner, width, height, rotation) {
|
|
5154
|
+
const c = Math.cos(rotation);
|
|
5155
|
+
const s = Math.sin(rotation);
|
|
5156
|
+
return {
|
|
5157
|
+
cx: corner.x + (c * width - s * height) / 2,
|
|
5158
|
+
cy: corner.y + (s * width + c * height) / 2,
|
|
5159
|
+
width,
|
|
5160
|
+
height,
|
|
5161
|
+
rotation
|
|
5162
|
+
};
|
|
5163
|
+
}
|
|
5164
|
+
/**
|
|
5165
|
+
* The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;
|
|
5166
|
+
* the inverse of `shapeFromCorner`.
|
|
5167
|
+
*
|
|
5168
|
+
* @param shape - The shape.
|
|
5169
|
+
* @returns The corner, in image coordinates.
|
|
5170
|
+
*/
|
|
5171
|
+
function shapeCorner(shape) {
|
|
5172
|
+
return fromShapeFrame(shape, {
|
|
5173
|
+
x: -shape.width / 2,
|
|
5174
|
+
y: -shape.height / 2
|
|
5175
|
+
});
|
|
5176
|
+
}
|
|
5177
|
+
/**
|
|
5178
|
+
* Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).
|
|
5179
|
+
*
|
|
5180
|
+
* @param a - A shape, or `null`.
|
|
5181
|
+
* @param b - A shape, or `null`.
|
|
5182
|
+
* @param epsilon - The tolerance. Defaults to 1e-6.
|
|
5183
|
+
* @returns `true` for two equal shapes, or two `null`s.
|
|
5184
|
+
*/
|
|
5185
|
+
function sameShape(a, b, epsilon = 1e-6) {
|
|
5186
|
+
if (a === null || b === null) return a === b;
|
|
5187
|
+
return Math.abs(a.cx - b.cx) < epsilon && Math.abs(a.cy - b.cy) < epsilon && Math.abs(a.width - b.width) < epsilon && Math.abs(a.height - b.height) < epsilon && Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon;
|
|
5188
|
+
}
|
|
5189
|
+
//#endregion
|
|
5190
|
+
//#region src/components/ShapeEditor.tsx
|
|
5191
|
+
/**
|
|
5192
|
+
* A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own
|
|
5193
|
+
* frame, and turned from a rotation handle, on the image.
|
|
5194
|
+
*
|
|
5195
|
+
* The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which
|
|
5196
|
+
* is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;
|
|
5197
|
+
* this is the gestures, the handles and the keyboard.
|
|
5198
|
+
*/
|
|
5199
|
+
/** Handle square side, in screen pixels. */
|
|
5200
|
+
const HANDLE_PX = 9;
|
|
5201
|
+
/** Rotation handle radius, and its distance past the top side, in screen pixels. */
|
|
5202
|
+
const ROTATE_RADIUS_PX = 5;
|
|
5203
|
+
const ROTATE_OFFSET_PX = 24;
|
|
5204
|
+
/** Outline width, in screen pixels. */
|
|
5205
|
+
const STROKE_PX$1 = 1.5;
|
|
5206
|
+
/** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */
|
|
5207
|
+
const SNAP = Math.PI / 12;
|
|
5208
|
+
const KEY_TURN = Math.PI / 180;
|
|
5209
|
+
const HALO$1 = overlayRole("halo");
|
|
5210
|
+
/**
|
|
5211
|
+
* An editable rotated rectangle or ellipse inside an `ImageStage`.
|
|
5212
|
+
*
|
|
5213
|
+
* - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
|
|
5214
|
+
* pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
|
|
5215
|
+
* `minSize` rather than flipping. The interior moves it.
|
|
5216
|
+
* - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
|
|
5217
|
+
* round to 15°.
|
|
5218
|
+
* - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
|
|
5219
|
+
* with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`
|
|
5220
|
+
* turn it by 1° (15° with Shift).
|
|
5221
|
+
* - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an
|
|
5222
|
+
* ellipse also shows its bounding box, where the handles are.
|
|
5223
|
+
* - **Panning.** A press with the hand tool, or with space held, still pans.
|
|
5224
|
+
*
|
|
5225
|
+
* It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does
|
|
5226
|
+
* not keep the shape inside the image.
|
|
5227
|
+
*
|
|
5228
|
+
* The SVG carries `data-editable`; the outline carries `data-shape`.
|
|
5229
|
+
*/
|
|
5230
|
+
function ShapeEditor({ kind, value, onValueChange, onCommit, editable = true, rotatable = true, minSize = 5, label = "Shape", stroke = overlayRole("selection") }) {
|
|
5231
|
+
const stage = useStage();
|
|
5232
|
+
const px = useScreenPx();
|
|
5233
|
+
const dragRef = useRef(null);
|
|
5234
|
+
const lastRef = useRef(null);
|
|
5235
|
+
const report = (next) => {
|
|
5236
|
+
lastRef.current = next;
|
|
5237
|
+
onValueChange(next);
|
|
5238
|
+
};
|
|
5239
|
+
const begin = (event, drag) => {
|
|
5240
|
+
if (stage.panMode || event.button !== 0) return;
|
|
5241
|
+
event.stopPropagation();
|
|
5242
|
+
event.preventDefault();
|
|
5243
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
5244
|
+
dragRef.current = drag;
|
|
5245
|
+
lastRef.current = null;
|
|
5246
|
+
};
|
|
5247
|
+
const onMove = (event) => {
|
|
5248
|
+
const drag = dragRef.current;
|
|
5249
|
+
if (!drag) return;
|
|
5250
|
+
event.stopPropagation();
|
|
5251
|
+
const p = stage.toImage({
|
|
5252
|
+
x: event.clientX,
|
|
5253
|
+
y: event.clientY
|
|
5254
|
+
});
|
|
5255
|
+
drag.moved = true;
|
|
5256
|
+
if (drag.kind === "move") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));
|
|
5257
|
+
else if (drag.kind === "resize") report(resizeShape(drag.start, drag.handle, p, minSize));
|
|
5258
|
+
else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));
|
|
5259
|
+
};
|
|
5260
|
+
const onEnd = (event) => {
|
|
5261
|
+
const drag = dragRef.current;
|
|
5262
|
+
if (!drag) return;
|
|
5263
|
+
event.stopPropagation();
|
|
5264
|
+
dragRef.current = null;
|
|
5265
|
+
if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
|
|
5266
|
+
};
|
|
5267
|
+
const onKeyDown = (event) => {
|
|
5268
|
+
if (!editable || value === null) return;
|
|
5269
|
+
if (rotatable && (event.key === "[" || event.key === "]")) {
|
|
5270
|
+
event.preventDefault();
|
|
5271
|
+
event.stopPropagation();
|
|
5272
|
+
const angle = (event.key === "]" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);
|
|
5273
|
+
const next = {
|
|
5274
|
+
...value,
|
|
5275
|
+
rotation: value.rotation + angle
|
|
5276
|
+
};
|
|
5277
|
+
onValueChange(next);
|
|
5278
|
+
onCommit?.(next);
|
|
5279
|
+
return;
|
|
5280
|
+
}
|
|
5281
|
+
const step = event.shiftKey ? 10 : 1;
|
|
5282
|
+
const d = {
|
|
5283
|
+
ArrowLeft: {
|
|
5284
|
+
x: -step,
|
|
5285
|
+
y: 0
|
|
5286
|
+
},
|
|
5287
|
+
ArrowRight: {
|
|
5288
|
+
x: step,
|
|
5289
|
+
y: 0
|
|
5290
|
+
},
|
|
5291
|
+
ArrowUp: {
|
|
5292
|
+
x: 0,
|
|
5293
|
+
y: -step
|
|
5294
|
+
},
|
|
5295
|
+
ArrowDown: {
|
|
5296
|
+
x: 0,
|
|
5297
|
+
y: step
|
|
5298
|
+
}
|
|
5299
|
+
}[event.key];
|
|
5300
|
+
if (!d) return;
|
|
5301
|
+
event.preventDefault();
|
|
5302
|
+
event.stopPropagation();
|
|
5303
|
+
const next = event.altKey ? resizeShape(value, "se", fromShapeFrame(value, {
|
|
5304
|
+
x: value.width / 2 + d.x,
|
|
5305
|
+
y: value.height / 2 + d.y
|
|
5306
|
+
}), minSize) : moveShape(value, d.x, d.y);
|
|
5307
|
+
onValueChange(next);
|
|
5308
|
+
onCommit?.(next);
|
|
5309
|
+
};
|
|
5310
|
+
const stem = value ? {
|
|
5311
|
+
from: shapeHandlePoint(value, "n"),
|
|
5312
|
+
to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX))
|
|
5313
|
+
} : null;
|
|
5314
|
+
const handleSize = px(HANDLE_PX);
|
|
5315
|
+
return /* @__PURE__ */ jsxs("svg", {
|
|
5316
|
+
viewBox: imageViewBox(stage.image),
|
|
5317
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
5318
|
+
"data-editable": editable ? "" : void 0,
|
|
5319
|
+
children: [
|
|
5320
|
+
value && /* @__PURE__ */ jsx(Outline, {
|
|
5321
|
+
kind,
|
|
5322
|
+
shape: value,
|
|
5323
|
+
fill: "none",
|
|
5324
|
+
stroke: HALO$1,
|
|
5325
|
+
strokeWidth: px(3.5)
|
|
5326
|
+
}),
|
|
5327
|
+
value && /* @__PURE__ */ jsx(Outline, {
|
|
5328
|
+
kind,
|
|
5329
|
+
shape: value,
|
|
5330
|
+
"data-shape": kind,
|
|
5331
|
+
fill: stroke,
|
|
5332
|
+
fillOpacity: .12,
|
|
5333
|
+
stroke,
|
|
5334
|
+
strokeWidth: px(STROKE_PX$1)
|
|
5335
|
+
}),
|
|
5336
|
+
kind === "ellipse" && value && /* @__PURE__ */ jsx("rect", {
|
|
5337
|
+
x: value.cx - value.width / 2,
|
|
5338
|
+
y: value.cy - value.height / 2,
|
|
5339
|
+
width: value.width,
|
|
5340
|
+
height: value.height,
|
|
5341
|
+
transform: turned(value),
|
|
5342
|
+
fill: "none",
|
|
5343
|
+
stroke,
|
|
5344
|
+
strokeWidth: px(1),
|
|
5345
|
+
strokeDasharray: `${px(4)} ${px(3)}`,
|
|
5346
|
+
opacity: .6
|
|
5347
|
+
}),
|
|
5348
|
+
editable && value && /* @__PURE__ */ jsx(Outline, {
|
|
5349
|
+
kind,
|
|
5350
|
+
shape: value,
|
|
5351
|
+
fill: "transparent",
|
|
5352
|
+
role: "button",
|
|
5353
|
+
tabIndex: 0,
|
|
5354
|
+
"aria-label": `${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt(value.rotation * 180 / Math.PI)}°`,
|
|
5355
|
+
"aria-roledescription": kind === "rect" ? "rotated rectangle" : "ellipse",
|
|
5356
|
+
className: "pointer-events-auto cursor-move outline-none focus-visible:stroke-signal",
|
|
5357
|
+
onPointerDown: (event) => begin(event, {
|
|
5358
|
+
kind: "move",
|
|
5359
|
+
from: stage.toImage({
|
|
5360
|
+
x: event.clientX,
|
|
5361
|
+
y: event.clientY
|
|
5362
|
+
}),
|
|
5363
|
+
start: value,
|
|
5364
|
+
moved: false
|
|
5365
|
+
}),
|
|
5366
|
+
onPointerMove: onMove,
|
|
5367
|
+
onPointerUp: onEnd,
|
|
5368
|
+
onLostPointerCapture: onEnd,
|
|
5369
|
+
onKeyDown,
|
|
5370
|
+
onDoubleClick: (event) => event.stopPropagation()
|
|
5371
|
+
}),
|
|
5372
|
+
editable && value && rotatable && stem && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
5373
|
+
/* @__PURE__ */ jsx("line", {
|
|
5374
|
+
x1: stem.from.x,
|
|
5375
|
+
y1: stem.from.y,
|
|
5376
|
+
x2: stem.to.x,
|
|
5377
|
+
y2: stem.to.y,
|
|
5378
|
+
stroke: HALO$1,
|
|
5379
|
+
strokeWidth: px(3)
|
|
5380
|
+
}),
|
|
5381
|
+
/* @__PURE__ */ jsx("line", {
|
|
5382
|
+
x1: stem.from.x,
|
|
5383
|
+
y1: stem.from.y,
|
|
5384
|
+
x2: stem.to.x,
|
|
5385
|
+
y2: stem.to.y,
|
|
5386
|
+
stroke,
|
|
5387
|
+
strokeWidth: px(1)
|
|
5388
|
+
}),
|
|
5389
|
+
/* @__PURE__ */ jsx("circle", {
|
|
5390
|
+
"data-handle": "rotate",
|
|
5391
|
+
cx: stem.to.x,
|
|
5392
|
+
cy: stem.to.y,
|
|
5393
|
+
r: px(ROTATE_RADIUS_PX),
|
|
5394
|
+
fill: stroke,
|
|
5395
|
+
stroke: HALO$1,
|
|
5396
|
+
strokeWidth: px(1),
|
|
5397
|
+
className: "pointer-events-auto",
|
|
5398
|
+
style: { cursor: "grab" },
|
|
5399
|
+
onPointerDown: (event) => begin(event, {
|
|
5400
|
+
kind: "rotate",
|
|
5401
|
+
start: value,
|
|
5402
|
+
moved: false
|
|
5403
|
+
}),
|
|
5404
|
+
onPointerMove: onMove,
|
|
5405
|
+
onPointerUp: onEnd,
|
|
5406
|
+
onLostPointerCapture: onEnd,
|
|
5407
|
+
onDoubleClick: (event) => event.stopPropagation()
|
|
5408
|
+
})
|
|
5409
|
+
] }),
|
|
5410
|
+
editable && value && ROI_HANDLES.map((handle) => {
|
|
5411
|
+
const centre = shapeHandlePoint(value, handle);
|
|
5412
|
+
return /* @__PURE__ */ jsx("rect", {
|
|
5413
|
+
"data-handle": handle,
|
|
5414
|
+
x: centre.x - handleSize / 2,
|
|
5415
|
+
y: centre.y - handleSize / 2,
|
|
5416
|
+
width: handleSize,
|
|
5417
|
+
height: handleSize,
|
|
5418
|
+
fill: stroke,
|
|
5419
|
+
stroke: HALO$1,
|
|
5420
|
+
strokeWidth: px(1),
|
|
5421
|
+
className: "pointer-events-auto",
|
|
5422
|
+
style: { cursor: shapeHandleCursor(handle, value.rotation) },
|
|
5423
|
+
onPointerDown: (event) => begin(event, {
|
|
5424
|
+
kind: "resize",
|
|
5425
|
+
handle,
|
|
5426
|
+
start: value,
|
|
5427
|
+
moved: false
|
|
5428
|
+
}),
|
|
5429
|
+
onPointerMove: onMove,
|
|
5430
|
+
onPointerUp: onEnd,
|
|
5431
|
+
onLostPointerCapture: onEnd,
|
|
5432
|
+
onDoubleClick: (event) => event.stopPropagation()
|
|
5433
|
+
}, handle);
|
|
5434
|
+
})
|
|
5435
|
+
]
|
|
5436
|
+
});
|
|
5437
|
+
}
|
|
5438
|
+
/** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */
|
|
5439
|
+
function Outline({ kind, shape, ...rest }) {
|
|
5440
|
+
const transform = turned(shape);
|
|
5441
|
+
return kind === "rect" ? /* @__PURE__ */ jsx("rect", {
|
|
5442
|
+
x: shape.cx - shape.width / 2,
|
|
5443
|
+
y: shape.cy - shape.height / 2,
|
|
5444
|
+
width: shape.width,
|
|
5445
|
+
height: shape.height,
|
|
5446
|
+
transform,
|
|
5447
|
+
...rest
|
|
5448
|
+
}) : /* @__PURE__ */ jsx("ellipse", {
|
|
5449
|
+
cx: shape.cx,
|
|
5450
|
+
cy: shape.cy,
|
|
5451
|
+
rx: shape.width / 2,
|
|
5452
|
+
ry: shape.height / 2,
|
|
5453
|
+
transform,
|
|
5454
|
+
...rest
|
|
5455
|
+
});
|
|
5456
|
+
}
|
|
5457
|
+
/** The SVG transform that turns a shape drawn level about its centre. */
|
|
5458
|
+
function turned(shape) {
|
|
5459
|
+
return `rotate(${shape.rotation * 180 / Math.PI} ${shape.cx} ${shape.cy})`;
|
|
5460
|
+
}
|
|
5461
|
+
function fmt(value) {
|
|
5462
|
+
return Number.isInteger(value) ? String(value) : value.toFixed(1);
|
|
5463
|
+
}
|
|
5464
|
+
//#endregion
|
|
5465
|
+
//#region src/components/DraftShape.tsx
|
|
5466
|
+
/**
|
|
5467
|
+
* What an annotation tool shows while a shape is being drawn: a dashed preview of the
|
|
5468
|
+
* point, line, polyline, polygon, rectangle or ellipse so far, and the rubber band of a
|
|
5469
|
+
* multi-select.
|
|
5470
|
+
*
|
|
5471
|
+
* Both draw from state the app's tool keeps; neither takes input. The tool decides what a
|
|
5472
|
+
* press means (`StageSurface` and `useStageHitTest`); these only make it visible.
|
|
5473
|
+
*/
|
|
5474
|
+
const HALO = overlayRole("halo");
|
|
5475
|
+
/** Dash, gap, outline width and vertex dot size, in screen pixels. */
|
|
5476
|
+
const DASH = 6;
|
|
5477
|
+
const GAP = 4;
|
|
5478
|
+
const STROKE_PX = 1.5;
|
|
5479
|
+
const VERTEX_PX = 6;
|
|
5480
|
+
/**
|
|
5481
|
+
* A dashed preview of a shape being drawn, inside an `ImageStage`.
|
|
5482
|
+
*
|
|
5483
|
+
* The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by
|
|
5484
|
+
* default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline
|
|
5485
|
+
* or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also
|
|
5486
|
+
* shows, fainter, the segment that would close it. It takes no pointer events and is hidden
|
|
5487
|
+
* from assistive technology: it is transient feedback for a gesture.
|
|
5488
|
+
*
|
|
5489
|
+
* The SVG carries `data-draft` (the shape's kind).
|
|
5490
|
+
*/
|
|
5491
|
+
function DraftShape({ shape, role = "selection", halo = true }) {
|
|
5492
|
+
const stage = useStage();
|
|
5493
|
+
const px = useScreenPx();
|
|
5494
|
+
const colour = overlayRole(role);
|
|
5495
|
+
const dash = `${px(DASH)} ${px(GAP)}`;
|
|
5496
|
+
const width = px(STROKE_PX);
|
|
5497
|
+
const parts = shape ? draftParts(shape, px(1)) : null;
|
|
5498
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
5499
|
+
viewBox: imageViewBox(stage.image),
|
|
5500
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
5501
|
+
"aria-hidden": true,
|
|
5502
|
+
"data-draft": shape?.kind,
|
|
5503
|
+
children: parts && /* @__PURE__ */ jsxs("g", {
|
|
5504
|
+
fill: "none",
|
|
5505
|
+
strokeLinecap: "round",
|
|
5506
|
+
strokeLinejoin: "round",
|
|
5507
|
+
children: [
|
|
5508
|
+
parts.outline && halo && /* @__PURE__ */ jsx("path", {
|
|
5509
|
+
d: parts.outline,
|
|
5510
|
+
stroke: HALO,
|
|
5511
|
+
strokeWidth: width + px(2),
|
|
5512
|
+
opacity: .6
|
|
5513
|
+
}),
|
|
5514
|
+
parts.outline && parts.region && /* @__PURE__ */ jsx("path", {
|
|
5515
|
+
d: parts.outline,
|
|
5516
|
+
fill: colour,
|
|
5517
|
+
fillOpacity: .12,
|
|
5518
|
+
stroke: "none"
|
|
5519
|
+
}),
|
|
5520
|
+
parts.outline && /* @__PURE__ */ jsx("path", {
|
|
5521
|
+
"data-draft-outline": "",
|
|
5522
|
+
d: parts.outline,
|
|
5523
|
+
stroke: colour,
|
|
5524
|
+
strokeWidth: width,
|
|
5525
|
+
strokeDasharray: dash
|
|
5526
|
+
}),
|
|
5527
|
+
parts.closing && /* @__PURE__ */ jsx("path", {
|
|
5528
|
+
"data-draft-closing": "",
|
|
5529
|
+
d: parts.closing,
|
|
5530
|
+
stroke: colour,
|
|
5531
|
+
strokeWidth: px(1),
|
|
5532
|
+
strokeDasharray: dash,
|
|
5533
|
+
opacity: .5
|
|
5534
|
+
}),
|
|
5535
|
+
parts.vertices && /* @__PURE__ */ jsx("path", {
|
|
5536
|
+
"data-draft-vertices": "",
|
|
5537
|
+
d: parts.vertices,
|
|
5538
|
+
stroke: colour,
|
|
5539
|
+
strokeWidth: px(VERTEX_PX)
|
|
5540
|
+
})
|
|
5541
|
+
]
|
|
5542
|
+
})
|
|
5543
|
+
});
|
|
5544
|
+
}
|
|
5545
|
+
/** An ellipse with the given centre and radii as two arcs. */
|
|
5546
|
+
function ellipsePath(cx, cy, rx, ry) {
|
|
5547
|
+
return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
|
|
5548
|
+
}
|
|
5549
|
+
function draftParts(shape, unit) {
|
|
5550
|
+
switch (shape.kind) {
|
|
5551
|
+
case "point": return {
|
|
5552
|
+
outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit),
|
|
5553
|
+
region: false,
|
|
5554
|
+
closing: null,
|
|
5555
|
+
vertices: `M${shape.x} ${shape.y}h0`
|
|
5556
|
+
};
|
|
5557
|
+
case "line": return {
|
|
5558
|
+
outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`,
|
|
5559
|
+
region: false,
|
|
5560
|
+
closing: null,
|
|
5561
|
+
vertices: null
|
|
5562
|
+
};
|
|
5563
|
+
case "rect":
|
|
5564
|
+
case "ellipse": {
|
|
5565
|
+
const box = rectFromCorners(shape.from, shape.to);
|
|
5566
|
+
return {
|
|
5567
|
+
outline: shape.kind === "rect" ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z` : ellipsePath(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2),
|
|
5568
|
+
region: true,
|
|
5569
|
+
closing: null,
|
|
5570
|
+
vertices: null
|
|
5571
|
+
};
|
|
5572
|
+
}
|
|
5573
|
+
case "polyline":
|
|
5574
|
+
case "polygon": {
|
|
5575
|
+
const n = Math.floor(shape.points.length / 2);
|
|
5576
|
+
if (n === 0) return {
|
|
5577
|
+
outline: null,
|
|
5578
|
+
region: false,
|
|
5579
|
+
closing: null,
|
|
5580
|
+
vertices: null
|
|
5581
|
+
};
|
|
5582
|
+
let outline = "";
|
|
5583
|
+
let vertices = "";
|
|
5584
|
+
for (let i = 0; i < n; i++) {
|
|
5585
|
+
outline += `${i === 0 ? "M" : "L"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;
|
|
5586
|
+
vertices += `M${shape.points[2 * i]} ${shape.points[2 * i + 1]}h0`;
|
|
5587
|
+
}
|
|
5588
|
+
if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;
|
|
5589
|
+
const polygon = shape.kind === "polygon";
|
|
5590
|
+
return {
|
|
5591
|
+
outline,
|
|
5592
|
+
region: polygon && n + (shape.cursor ? 1 : 0) >= 3,
|
|
5593
|
+
closing: polygon && shape.cursor ? `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}` : null,
|
|
5594
|
+
vertices
|
|
5595
|
+
};
|
|
5596
|
+
}
|
|
5597
|
+
}
|
|
5598
|
+
}
|
|
5599
|
+
/**
|
|
5600
|
+
* The rubber band of a multi-select, inside an `ImageStage`: the 12 % fill and a 1 screen px
|
|
5601
|
+
* outline in the selection colour, the same as `PolylineSet`'s own band. Feed it the box
|
|
5602
|
+
* between the press and the pointer from `StageSurface`, and the box to `pointsInRect`,
|
|
5603
|
+
* `polylinesInRect` or `areasInRect` at the release. It takes no pointer events.
|
|
5604
|
+
*
|
|
5605
|
+
* The SVG carries `data-marquee`.
|
|
5606
|
+
*/
|
|
5607
|
+
function MarqueeRect({ rect, stroke = overlayRole("selection") }) {
|
|
5608
|
+
const stage = useStage();
|
|
5609
|
+
const px = useScreenPx();
|
|
5610
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
5611
|
+
viewBox: imageViewBox(stage.image),
|
|
5612
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
5613
|
+
"aria-hidden": true,
|
|
5614
|
+
"data-marquee": rect ? "" : void 0,
|
|
5615
|
+
children: rect && /* @__PURE__ */ jsx("rect", {
|
|
5616
|
+
x: rect.x,
|
|
5617
|
+
y: rect.y,
|
|
5618
|
+
width: rect.width,
|
|
5619
|
+
height: rect.height,
|
|
5620
|
+
fill: stroke,
|
|
5621
|
+
fillOpacity: .12,
|
|
5622
|
+
stroke,
|
|
5623
|
+
strokeWidth: px(1)
|
|
5624
|
+
})
|
|
5625
|
+
});
|
|
5626
|
+
}
|
|
5627
|
+
//#endregion
|
|
5628
|
+
//#region src/components/useShapeDrag.ts
|
|
5629
|
+
/**
|
|
5630
|
+
* Moving a manual shape: a press on a selected item becomes image-space displacements, with the
|
|
5631
|
+
* click-slop handling every selection UI needs (a press that barely moves is a click, not a
|
|
5632
|
+
* drag).
|
|
5633
|
+
*
|
|
5634
|
+
* The layers resolve what is under the pointer (`onItemPress`); this turns the press that
|
|
5635
|
+
* follows into a move. The app keeps the item's geometry, shows the displaced copy while the
|
|
5636
|
+
* drag is in flight, and commits it at the end:
|
|
5637
|
+
*
|
|
5638
|
+
* <AreaSet items={items} selectedIds={selected}
|
|
5639
|
+
* onItemPress={(id, event) => {
|
|
5640
|
+
* if (!selected.has(id)) return select(id);
|
|
5641
|
+
* startMove(event, {
|
|
5642
|
+
* onMove: setOffset, // preview: draw the item shifted
|
|
5643
|
+
* onEnd: (delta, moved) => moved ? commit(id, delta) : select(id),
|
|
5644
|
+
* onCancel: () => setOffset(null),
|
|
5645
|
+
* });
|
|
5646
|
+
* }} />
|
|
5647
|
+
*/
|
|
5648
|
+
/** The default click slop, in screen pixels (the stage's own). */
|
|
5649
|
+
const DEFAULT_SLOP = 3;
|
|
5650
|
+
/**
|
|
5651
|
+
* Start moving a shape from a press, inside an `ImageStage`.
|
|
5652
|
+
*
|
|
5653
|
+
* Returns `start(event, handlers, options?)`. Call it from `onItemPress` of a layer with the
|
|
5654
|
+
* press event: the press is claimed, so the stage does not pan, and the pointer is followed on
|
|
5655
|
+
* `window` until it is released, whether or not it leaves the canvas. A touch tap reaches
|
|
5656
|
+
* `onItemPress` on release, so there is nothing to follow: it ends at once as a click
|
|
5657
|
+
* (`moved` false). Move a shape on touch with `ShapeEditor`'s handles or the app's own mode.
|
|
5658
|
+
*
|
|
5659
|
+
* @returns `start`.
|
|
5660
|
+
*/
|
|
5661
|
+
function useShapeDrag() {
|
|
5662
|
+
const { toImage } = useStage();
|
|
5663
|
+
const startDrag = useStageDrag();
|
|
5664
|
+
return useCallback((event, handlers, options) => {
|
|
5665
|
+
if (event.type !== "pointerdown") {
|
|
5666
|
+
handlers.onEnd?.({
|
|
5667
|
+
x: 0,
|
|
5668
|
+
y: 0
|
|
5669
|
+
}, false, event.nativeEvent);
|
|
5670
|
+
return;
|
|
5671
|
+
}
|
|
5672
|
+
const slop = options?.slop ?? DEFAULT_SLOP;
|
|
5673
|
+
const from = {
|
|
5674
|
+
x: event.clientX,
|
|
5675
|
+
y: event.clientY
|
|
5676
|
+
};
|
|
5677
|
+
const press = toImage(from);
|
|
5678
|
+
const displacement = (point) => ({
|
|
5679
|
+
x: point.x - press.x,
|
|
5680
|
+
y: point.y - press.y
|
|
5681
|
+
});
|
|
5682
|
+
let moved = false;
|
|
5683
|
+
startDrag(event, {
|
|
5684
|
+
onMove: (point, e) => {
|
|
5685
|
+
if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= slop) return;
|
|
5686
|
+
moved = true;
|
|
5687
|
+
handlers.onMove?.(displacement(point), e);
|
|
5688
|
+
},
|
|
5689
|
+
onEnd: (point, e) => handlers.onEnd?.(moved ? displacement(point) : {
|
|
5690
|
+
x: 0,
|
|
5691
|
+
y: 0
|
|
5692
|
+
}, moved, e),
|
|
5693
|
+
onCancel: handlers.onCancel
|
|
5694
|
+
});
|
|
5695
|
+
}, [toImage, startDrag]);
|
|
5696
|
+
}
|
|
5697
|
+
/**
|
|
5698
|
+
* Move flat points by a displacement.
|
|
5699
|
+
*
|
|
5700
|
+
* @param points - `[x0, y0, x1, y1, …]`.
|
|
5701
|
+
* @param delta - The displacement, in the points' units.
|
|
5702
|
+
* @returns A new array, `points` shifted.
|
|
5703
|
+
*/
|
|
5704
|
+
function translatePoints(points, delta) {
|
|
5705
|
+
const out = new Array(points.length);
|
|
5706
|
+
for (let i = 0; i < points.length; i++) out[i] = points[i] + (i % 2 === 0 ? delta.x : delta.y);
|
|
5707
|
+
return out;
|
|
5708
|
+
}
|
|
5709
|
+
//#endregion
|
|
2963
5710
|
//#region src/components/MaskEditor.tsx
|
|
2964
5711
|
/** A source-pixel raster mask layer with a small paint/erase brush. */
|
|
2965
5712
|
/** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
|
|
@@ -3136,6 +5883,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
|
|
|
3136
5883
|
})] });
|
|
3137
5884
|
}
|
|
3138
5885
|
//#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 };
|
|
5886
|
+
export { AreaSet, ContourEditor, DraftShape, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestPoint, nearestPolyline, normalizeAngle, overlayRole, paintMask, planeRange, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, steppedScale, strokeWidthFor, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
|
|
3140
5887
|
|
|
3141
5888
|
//# sourceMappingURL=index.js.map
|