@vitavision/stage2d 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * "What is under the pointer?", answered across layers.
3
+ *
4
+ * Each layer that can be picked registers a `pick` function over its own spatial index. The
5
+ * stage asks every layer, ranks the answers and returns the best, so an app deciding what a
6
+ * press means (select, draw or pan) asks one question instead of arbitrating between layers.
7
+ * This module is the pure core: ranking, and a registry that also routes hover and presses.
8
+ * The React wiring is `useStageHitTest.ts`. It imports neither React nor the DOM.
9
+ *
10
+ * Ranking: a higher `priority` wins outright (points above lines above areas above images),
11
+ * then the smaller distance, then the layer id, so the result never depends on the order
12
+ * layers mounted in.
13
+ */
14
+
15
+ import type { Point } from "../measureGeometry";
16
+
17
+ /** What a layer is picked as, and so how it ranks against the layers around it. */
18
+ export const STAGE_HIT_PRIORITY = {
19
+ /** A raster layer: only picked when nothing else is. */
20
+ image: 0,
21
+ /** A filled region or heatmap cell. */
22
+ area: 100,
23
+ /** A line or contour. */
24
+ line: 200,
25
+ /** A marker: small, so it wins over what it sits on. */
26
+ point: 300,
27
+ } as const;
28
+
29
+ /** An item's identity within its layer. */
30
+ export type HitId = string | number;
31
+
32
+ /** What a layer's `pick` returns: the item, and how far from the pointer it is. */
33
+ export interface HitCandidate {
34
+ /** The item's id. */
35
+ id: HitId;
36
+ /** Distance from the query point, in image pixels. Compared only within one priority. */
37
+ dist: number;
38
+ }
39
+
40
+ /** One answer to a hit-test. */
41
+ export interface StageHit extends HitCandidate {
42
+ /** The layer that answered. */
43
+ layerId: string;
44
+ /** The layer's priority. */
45
+ priority: number;
46
+ }
47
+
48
+ /** What a layer registers. */
49
+ export interface StageHitLayerSpec<E = unknown> {
50
+ /** Reported as `StageHit.layerId`. */
51
+ id: string;
52
+ /** Ranks this layer against others; see `STAGE_HIT_PRIORITY`. */
53
+ priority: number;
54
+ /**
55
+ * The item under `point`, if any.
56
+ *
57
+ * @param point - The query, in image coordinates.
58
+ * @param radius - The pointer's tolerance, in image pixels.
59
+ */
60
+ pick: (point: Point, radius: number) => HitCandidate | null;
61
+ /** Whether a press on this layer's items does something (`press` is set and will claim). */
62
+ readonly pressable?: boolean | undefined;
63
+ /** The hovered item changed: an id, or `null` when the pointer left every item. */
64
+ hover?: ((id: HitId | null) => void) | undefined;
65
+ /** A press landed on an item. Return `false` to decline it. */
66
+ press?: ((id: HitId, event: E) => boolean | void) | undefined;
67
+ }
68
+
69
+ /** Options of a hit-test. */
70
+ export interface StageHitOptions {
71
+ /** Consider only layers whose presses are claimed (`pressable`). */
72
+ pressable?: boolean | undefined;
73
+ }
74
+
75
+ /**
76
+ * Order two hits, best first.
77
+ *
78
+ * @returns Negative when `a` ranks above `b`.
79
+ */
80
+ export function compareHits(a: StageHit, b: StageHit): number {
81
+ if (a.priority !== b.priority) return b.priority - a.priority;
82
+ if (a.dist !== b.dist) return a.dist - b.dist;
83
+ return a.layerId < b.layerId ? -1 : a.layerId > b.layerId ? 1 : 0;
84
+ }
85
+
86
+ /**
87
+ * Sort hits, best first.
88
+ *
89
+ * @param hits - Any hits.
90
+ * @returns A new, sorted array.
91
+ */
92
+ export function sortHits(hits: readonly StageHit[]): StageHit[] {
93
+ return [...hits].sort(compareHits);
94
+ }
95
+
96
+ /**
97
+ * The best of some hits.
98
+ *
99
+ * @param hits - Any hits.
100
+ * @returns The first by `compareHits`, or `null` when there are none.
101
+ */
102
+ export function bestHit(hits: readonly StageHit[]): StageHit | null {
103
+ let best: StageHit | null = null;
104
+ for (const hit of hits) if (best === null || compareHits(hit, best) < 0) best = hit;
105
+ return best;
106
+ }
107
+
108
+ /** The layers of one stage, and the routing of hover and presses between them. */
109
+ export interface HitRegistry<E = unknown> {
110
+ /**
111
+ * Add a layer.
112
+ *
113
+ * @returns The function that removes it.
114
+ */
115
+ register: (layer: StageHitLayerSpec<E>) => () => void;
116
+ /** Every layer's best answer at `point`, sorted best first. */
117
+ hitTestAll: (point: Point, radius: number, options?: StageHitOptions) => StageHit[];
118
+ /** The best answer at `point`, or `null`. */
119
+ hitTest: (point: Point, radius: number, options?: StageHitOptions) => StageHit | null;
120
+ /**
121
+ * Move hover to whatever is under `point`: the best hit among layers with a `hover`
122
+ * handler gets `hover(id)`, and the layer that had it before gets `hover(null)`. Calls
123
+ * nothing when the hovered item did not change.
124
+ */
125
+ routeHover: (point: Point, radius: number) => void;
126
+ /** Clear hover, e.g. when the pointer leaves the stage or starts a pan. */
127
+ clearHover: () => void;
128
+ /**
129
+ * Offer a press to the best pressable item under `point`, then the next, until one claims.
130
+ *
131
+ * @returns Whether a layer claimed it.
132
+ */
133
+ routePress: (point: Point, radius: number, event: E) => boolean;
134
+ }
135
+
136
+ /** Make an empty registry. */
137
+ export function createHitRegistry<E = unknown>(): HitRegistry<E> {
138
+ const layers = new Set<StageHitLayerSpec<E>>();
139
+ let hovered: { layer: StageHitLayerSpec<E>; id: HitId } | null = null;
140
+
141
+ const answers = (point: Point, radius: number, options?: StageHitOptions): { hit: StageHit; layer: StageHitLayerSpec<E> }[] => {
142
+ const out: { hit: StageHit; layer: StageHitLayerSpec<E> }[] = [];
143
+ for (const layer of layers) {
144
+ if (options?.pressable && layer.pressable !== true) continue;
145
+ const found = layer.pick(point, radius);
146
+ if (found) out.push({ hit: { id: found.id, dist: found.dist, layerId: layer.id, priority: layer.priority }, layer });
147
+ }
148
+ return out.sort((a, b) => compareHits(a.hit, b.hit));
149
+ };
150
+
151
+ const setHover = (next: { layer: StageHitLayerSpec<E>; id: HitId } | null) => {
152
+ const previous = hovered;
153
+ if (previous?.layer === next?.layer && previous?.id === next?.id) return;
154
+ hovered = next;
155
+ if (previous && previous.layer !== next?.layer) previous.layer.hover?.(null);
156
+ next?.layer.hover?.(next.id);
157
+ };
158
+
159
+ return {
160
+ register(layer) {
161
+ layers.add(layer);
162
+ return () => {
163
+ layers.delete(layer);
164
+ if (hovered?.layer === layer) hovered = null;
165
+ };
166
+ },
167
+ hitTestAll: (point, radius, options) => answers(point, radius, options).map((a) => a.hit),
168
+ hitTest: (point, radius, options) => answers(point, radius, options)[0]?.hit ?? null,
169
+ routeHover(point, radius) {
170
+ const best = answers(point, radius).find((a) => a.layer.hover !== undefined);
171
+ setHover(best ? { layer: best.layer, id: best.hit.id } : null);
172
+ },
173
+ clearHover: () => setHover(null),
174
+ routePress(point, radius, event) {
175
+ for (const { hit, layer } of answers(point, radius, { pressable: true })) {
176
+ if (layer.press?.(hit.id, event) !== false) return true;
177
+ }
178
+ return false;
179
+ },
180
+ };
181
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * React wiring for the stage's hit-test registry: `useStageHitTest` for apps that ask "what
3
+ * is under the pointer", and `useStageHitLayer` for layers that answer.
4
+ */
5
+
6
+ import { use, useId, useLayoutEffect, useMemo, useRef } from "react";
7
+
8
+ import type { Point } from "../measureGeometry";
9
+ import { useStage } from "./ImageStage";
10
+ import { StageHitContext, type StagePointerEvent } from "./hitContext";
11
+ import {
12
+ type HitCandidate,
13
+ type HitId,
14
+ type StageHit,
15
+ type StageHitLayerSpec,
16
+ type StageHitOptions,
17
+ } from "./hitTest";
18
+
19
+ /** The default pointer tolerance of `hitTest`, in screen pixels. */
20
+ const DEFAULT_RADIUS_PX = 6;
21
+
22
+ /** What `useStageHitTest` returns. */
23
+ export interface StageHitTestApi {
24
+ /**
25
+ * The best item under a point across every layer, or `null`.
26
+ *
27
+ * @param point - In image coordinates, e.g. a `StagePress.point`.
28
+ * @param radiusScreenPx - The pointer's tolerance in screen pixels. Defaults to 6.
29
+ * @param options - `pressable` limits the answer to layers that claim presses.
30
+ */
31
+ hitTest: (point: Point, radiusScreenPx?: number, options?: StageHitOptions) => StageHit | null;
32
+ /**
33
+ * Every layer's best item under a point, best first: higher priority, then nearer.
34
+ * Parameters as `hitTest`.
35
+ */
36
+ hitTestAll: (point: Point, radiusScreenPx?: number, options?: StageHitOptions) => StageHit[];
37
+ }
38
+
39
+ /**
40
+ * The stage's one hit-test, across every registered layer (`PointSet`, `PolylineSet`, and
41
+ * any layer built with `useStageHitLayer`). A press handler uses it to decide what a press
42
+ * means: an item under the pointer is selected, bare image is drawn on or panned.
43
+ *
44
+ * The answer comes from each layer's spatial index, never from the DOM, so it costs
45
+ * microseconds at any scene size.
46
+ *
47
+ * @returns `{ hitTest, hitTestAll }`.
48
+ * @throws `Error` outside an `ImageStage`, which is always a wiring bug.
49
+ */
50
+ export function useStageHitTest(): StageHitTestApi {
51
+ const registry = use(StageHitContext);
52
+ if (registry === null) throw new Error("useStageHitTest must be used inside <ImageStage>.");
53
+ const { imageLength } = useStage();
54
+ return useMemo(
55
+ () => ({
56
+ hitTest: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) =>
57
+ registry.hitTest(point, imageLength(radiusScreenPx), options),
58
+ hitTestAll: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) =>
59
+ registry.hitTestAll(point, imageLength(radiusScreenPx), options),
60
+ }),
61
+ [registry, imageLength],
62
+ );
63
+ }
64
+
65
+ /** What a layer passes `useStageHitLayer`. */
66
+ export interface StageHitLayerOptions {
67
+ /** The id hits report. Defaults to a generated, stable one; set it to tell layers apart. */
68
+ layerId?: string | undefined;
69
+ /** Rank against other layers; see `STAGE_HIT_PRIORITY`. */
70
+ priority: number;
71
+ /**
72
+ * The item under `point`, if any, within `radius` image pixels. Use the layer's index
73
+ * (`nearestPoint`, `nearestPolyline`), not the DOM.
74
+ */
75
+ pick: (point: Point, radius: number) => HitCandidate | null;
76
+ /**
77
+ * The hovered item changed. Setting this makes the stage route hover to the layer; the
78
+ * best item under the pointer across layers is the hovered one.
79
+ */
80
+ onHover?: ((id: HitId | null) => void) | undefined;
81
+ /**
82
+ * A press landed on an item and nothing above it claimed it. Setting this makes the layer
83
+ * claim presses on its items, so the stage does not pan from them. Return `false` to
84
+ * decline one. For a touch tap this is the `pointerup`.
85
+ */
86
+ onPress?: ((id: HitId, event: StagePointerEvent) => boolean | void) | undefined;
87
+ }
88
+
89
+ /**
90
+ * Register a layer with the stage's hit-test. The callbacks may change every render; the
91
+ * registration does not, so a layer is never missing from a hit-test for a frame.
92
+ *
93
+ * @param options - How the layer answers `pick`, and whether it takes hover and presses.
94
+ * @returns The layer's id, as hits report it.
95
+ * @throws `Error` outside an `ImageStage`.
96
+ */
97
+ export function useStageHitLayer(options: StageHitLayerOptions): string {
98
+ const registry = use(StageHitContext);
99
+ if (registry === null) throw new Error("useStageHitLayer must be used inside <ImageStage>.");
100
+ const generatedId = useId();
101
+ const id = options.layerId ?? generatedId;
102
+ const latestRef = useRef(options);
103
+ useLayoutEffect(() => {
104
+ latestRef.current = options;
105
+ });
106
+ const priority = options.priority;
107
+ useLayoutEffect(() => {
108
+ // Everything the registry reads goes through `latestRef`, so one registration serves the
109
+ // layer's whole life; `priority` and `id` are the only things that re-register it.
110
+ const layer: StageHitLayerSpec<StagePointerEvent> = {
111
+ id,
112
+ priority,
113
+ pick: (point, radius) => latestRef.current.pick(point, radius),
114
+ get pressable() {
115
+ return latestRef.current.onPress !== undefined;
116
+ },
117
+ get hover() {
118
+ return latestRef.current.onHover === undefined ? undefined : (hovered: HitId | null) => latestRef.current.onHover?.(hovered);
119
+ },
120
+ get press() {
121
+ return latestRef.current.onPress === undefined ? undefined : (hit: HitId, event: StagePointerEvent) => latestRef.current.onPress?.(hit, event);
122
+ },
123
+ };
124
+ return registry.register(layer);
125
+ }, [registry, id, priority]);
126
+ return id;
127
+ }
package/src/index.ts CHANGED
@@ -11,6 +11,23 @@ export {
11
11
  type StageHandle,
12
12
  } from "./components/stage/ImageStage";
13
13
 
14
+ export type { StageMouseButton } from "./components/stage/gesture";
15
+
16
+ export {
17
+ STAGE_HIT_PRIORITY,
18
+ type HitCandidate,
19
+ type HitId,
20
+ type StageHit,
21
+ type StageHitOptions,
22
+ } from "./components/stage/hitTest";
23
+ export type { StagePointerEvent } from "./components/stage/hitContext";
24
+ export {
25
+ useStageHitLayer,
26
+ useStageHitTest,
27
+ type StageHitLayerOptions,
28
+ type StageHitTestApi,
29
+ } from "./components/stage/useStageHitTest";
30
+
14
31
  export { ImageLayer, type ImageLayerProps, type ImageTier } from "./components/stage/ImageLayer";
15
32
 
16
33
  export {
@@ -127,6 +144,24 @@ export {
127
144
  type PolylineId,
128
145
  type PolylineIndex,
129
146
  } from "./components/polylineIndex";
147
+ export {
148
+ PointSet,
149
+ type PointSetItem,
150
+ type PointSetProps,
151
+ } from "./components/PointSet";
152
+ export {
153
+ buildPointIndex,
154
+ buildPointIndexFrom,
155
+ nearestPoint,
156
+ pointsInRect,
157
+ thinPoints,
158
+ type PointHit,
159
+ type PointId,
160
+ type PointIndex,
161
+ type PointIndexOptions,
162
+ type PointItem,
163
+ } from "./components/pointIndex";
164
+ export { MARKER_SHAPES, circlePath, type BuiltinMarkerKind, type MarkerShape } from "./components/markerShapes";
130
165
  export {
131
166
  ROI_HANDLES,
132
167
  ROI_HANDLE_CURSOR,