@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.
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Many points over the image, hoverable and selectable: detected corners, ring centres,
3
+ * keypoints, labelled landmarks.
4
+ *
5
+ * Drawn as a handful of batched paths, one per (state, style, marker kind), never one element
6
+ * per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the
7
+ * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule
8
+ * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.
9
+ */
10
+
11
+ import { useMemo, useState } from "react";
12
+
13
+ import { circlePath, MARKER_SHAPES, type MarkerShape } from "./markerShapes";
14
+ import { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
15
+ import { useLabelIndices, visibleRect } from "./labelLod";
16
+ import { buildPointIndexFrom, nearestPoint, type PointId, type PointItem } from "./pointIndex";
17
+ import { useStage } from "./stage/ImageStage";
18
+ import type { StagePointerEvent } from "./stage/hitContext";
19
+ import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
20
+ import { useStageHitLayer } from "./stage/useStageHitTest";
21
+ import { useScreenPx } from "./stage/useScreenPx";
22
+ import { imageViewBox, type Rect } from "./stage/view";
23
+
24
+ /** One point of a `PointSet`. */
25
+ export interface PointSetItem extends PointItem {
26
+ /**
27
+ * The marker kind: a built-in (`dot`, `plus`, `cross`, `square`, `hollow`, `directed`) or
28
+ * a key of the layer's `markers`. Defaults to the layer's `kind`.
29
+ */
30
+ kind?: string | undefined;
31
+ /** The overlay role it is painted in. Defaults to the marker kind's role, usually `feature`. */
32
+ role?: OverlayRole | undefined;
33
+ /** Its orientation in radians, clockwise from +x; read by `directed`. */
34
+ angle?: number | undefined;
35
+ /** Text drawn beside it, when the zoom leaves room (points at least 24 screen px apart). */
36
+ label?: string | undefined;
37
+ }
38
+
39
+ /** Props of `PointSet`. */
40
+ export interface PointSetProps {
41
+ /** The points, in image coordinates. */
42
+ items: readonly PointSetItem[];
43
+ /** The marker kind of an item that names none. Defaults to `"dot"`. */
44
+ kind?: string | undefined;
45
+ /** More marker kinds, or replacements for built-in ones, by name. */
46
+ markers?: Readonly<Record<string, MarkerShape>> | undefined;
47
+ /** The hovered id, when the app controls hover (a list beside the stage hovers points too). */
48
+ hoveredId?: PointId | null | undefined;
49
+ /** Called when the point under the pointer changes. `null` when it leaves every point. */
50
+ onHoverChange?: ((id: PointId | null) => void) | undefined;
51
+ /** The selected ids, drawn at 2.5 px in the selection colour with a ring. */
52
+ selectedIds?: Iterable<PointId> | undefined;
53
+ /**
54
+ * Ids drawn at 35 % opacity, as a set or a predicate (outside the current filter, say).
55
+ * They still take hover and presses. Pass a stable value: a new one re-batches the layer.
56
+ */
57
+ dimmed?: Iterable<PointId> | ((id: PointId) => boolean) | undefined;
58
+ /**
59
+ * A press landed on a point. Setting it makes the layer claim presses on its points, so
60
+ * the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for a
61
+ * touch tap), so `useStageDrag` can start a drag from it.
62
+ *
63
+ * A mounted `StageSurface` hears a press first; there, ask `useStageHitTest` what is
64
+ * under it instead.
65
+ */
66
+ onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | undefined;
67
+ /** Show the items' `label`s where the zoom leaves room for them. On by default. */
68
+ labels?: boolean | undefined;
69
+ /** Draw the dark band under every mark. On by default; off for a fast, flat layer. */
70
+ halo?: boolean | undefined;
71
+ /** CSS colour of selected points and rings. Defaults to the overlay `selection` role. */
72
+ selectionStroke?: string | undefined;
73
+ /** The id hit-tests report for this layer. Defaults to a generated one. */
74
+ layerId?: string | undefined;
75
+ /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.point`. */
76
+ priority?: number | undefined;
77
+ /** The layer's accessible name. Defaults to "Points". */
78
+ label?: string | undefined;
79
+ }
80
+
81
+ /** Past this many points, outlines are generated for the visible part only. */
82
+ const CULL_ABOVE = 3000;
83
+ /** How much bigger than a marker its selection ring is, in screen pixels. */
84
+ const RING_GAP = 4;
85
+
86
+ const HALO = overlayRole("halo");
87
+ const LABEL = overlayRole("label");
88
+
89
+ /** The points of one batched path. */
90
+ interface Batch {
91
+ key: string;
92
+ shape: MarkerShape;
93
+ role: OverlayRole;
94
+ dim: boolean;
95
+ /** Item positions, ascending. */
96
+ indices: number[];
97
+ /** The last generated path data and what it was generated for. */
98
+ cache: { key: string; d: string } | null;
99
+ }
100
+
101
+ /**
102
+ * A selectable set of points inside an `ImageStage`.
103
+ *
104
+ * - **Markers** by kind, from the overlay grammar: `dot`, `plus` (corner), `cross`, `square`,
105
+ * `hollow` (predicted), `directed`. Add your own through `markers`.
106
+ * - **States**, from visual-language §5: default 1.5 screen px, hover 2, selected 2.5 in the
107
+ * selection colour with a ring, dimmed at 35 % opacity. Every mark has a halo.
108
+ * - **Labels** only where points are at least 24 screen px apart, at most 200 at a time.
109
+ * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here,
110
+ * and `useStageHitTest` for an app that arbitrates between layers.
111
+ *
112
+ * Outlines (`plus`, `cross`, …) are regenerated when the zoom changes, since their size is in
113
+ * screen pixels; past 3,000 points only those near the viewport are generated. `dot` is a
114
+ * zero-length stroke whose width is its size, so it is not regenerated at all.
115
+ *
116
+ * The SVG carries `data-hovered` (the hovered id).
117
+ */
118
+ export function PointSet({
119
+ items,
120
+ kind = "dot",
121
+ markers,
122
+ hoveredId,
123
+ onHoverChange,
124
+ selectedIds,
125
+ dimmed,
126
+ onItemPress,
127
+ labels = true,
128
+ halo = true,
129
+ selectionStroke = overlayRole("selection"),
130
+ layerId,
131
+ priority = STAGE_HIT_PRIORITY.point,
132
+ label = "Points",
133
+ }: PointSetProps) {
134
+ const stage = useStage();
135
+ const px = useScreenPx();
136
+ const unit = px(1);
137
+
138
+ const shapes = useMemo<Readonly<Record<string, MarkerShape>>>(() => ({ ...MARKER_SHAPES, ...markers }), [markers]);
139
+ const index = useMemo(() => buildPointIndexFrom(items), [items]);
140
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
141
+ const isDimmed = useMemo(() => {
142
+ if (typeof dimmed === "function") return dimmed;
143
+ const set = new Set(dimmed ?? []);
144
+ return (id: PointId) => set.has(id);
145
+ }, [dimmed]);
146
+ const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
147
+
148
+ const [ownHover, setOwnHover] = useState<PointId | null>(null);
149
+ const hoverId = hoveredId !== undefined ? hoveredId : ownHover;
150
+
151
+ useStageHitLayer({
152
+ layerId,
153
+ priority,
154
+ pick: (point, radius) => {
155
+ const hit = nearestPoint(index, point.x, point.y, radius);
156
+ return hit ? { id: hit.id, dist: hit.dist } : null;
157
+ },
158
+ onHover: (id) => {
159
+ setOwnHover(id);
160
+ onHoverChange?.(id);
161
+ },
162
+ onPress: onItemPress ? (id, event) => onItemPress(id, event) : undefined,
163
+ });
164
+
165
+ // Items grouped by appearance. Rebuilt when the items or the selection change, never on
166
+ // hover or on a view change.
167
+ const groups = useMemo(() => {
168
+ const normal = new Map<string, Batch>();
169
+ const picked = new Map<string, Batch>();
170
+ items.forEach((item, i) => {
171
+ const kindName = item.kind ?? kind;
172
+ const shape = shapes[kindName] ?? MARKER_SHAPES.dot;
173
+ if (selectedSet.has(item.id)) {
174
+ const key = kindName;
175
+ let batch = picked.get(key);
176
+ if (!batch) {
177
+ batch = { key, shape, role: "selection", dim: false, indices: [], cache: null };
178
+ picked.set(key, batch);
179
+ }
180
+ batch.indices.push(i);
181
+ return;
182
+ }
183
+ const role = item.role ?? shape.role ?? "feature";
184
+ const dim = isDimmed(item.id);
185
+ const key = `${dim ? 1 : 0}|${role}|${kindName}`;
186
+ let batch = normal.get(key);
187
+ if (!batch) {
188
+ batch = { key, shape, role, dim, indices: [], cache: null };
189
+ normal.set(key, batch);
190
+ }
191
+ batch.indices.push(i);
192
+ });
193
+ const rings = [...picked.values()].map<Batch>((batch) => ({
194
+ ...batch,
195
+ key: `ring|${batch.key}`,
196
+ shape: {
197
+ paint: "line",
198
+ size: 0,
199
+ path: (x, y, u) => circlePath(x, y, (batch.shape.size + RING_GAP) * u),
200
+ },
201
+ cache: null,
202
+ }));
203
+ return { normal: [...normal.values()], picked: [...picked.values()], rings };
204
+ }, [items, kind, shapes, selectedSet, isDimmed]);
205
+
206
+ // The part of the scene to generate outlines for: everything for a small set, otherwise a
207
+ // window around the viewport, snapped so panning rebuilds it once per half screen.
208
+ const cull = cullWindow(stage.view, stage.box, items.length);
209
+ const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
210
+
211
+ // Each batch remembers the outline it last generated and what that was for, so this is
212
+ // O(batches) on a render that changed neither the zoom nor the window (a hover, a pan).
213
+ const build = (batches: Batch[]) => batches.map((batch) => ({ batch, d: batchPath(batch, items, unit, cull, cullKey) }));
214
+ const paths = { normal: build(groups.normal), picked: build(groups.picked), rings: build(groups.rings) };
215
+
216
+ const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : undefined;
217
+ const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
218
+ const hoverShape = hoverItem ? (shapes[hoverItem.kind ?? kind] ?? MARKER_SHAPES.dot) : undefined;
219
+ const hoverRole = hoverItem?.role ?? hoverShape?.role ?? "feature";
220
+
221
+ // Labels: the spacing is a function of the zoom only, so panning does not reshuffle which
222
+ // points carry one.
223
+ const labelled = useMemo(() => {
224
+ const list: number[] = [];
225
+ items.forEach((item, i) => {
226
+ if (item.label) list.push(i);
227
+ });
228
+ return list;
229
+ }, [items]);
230
+ const forced = useMemo(() => {
231
+ const list: number[] = [];
232
+ if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);
233
+ for (const id of selectedSet) {
234
+ const i = positionOf.get(id);
235
+ if (i !== undefined && items[i]!.label) list.push(i);
236
+ }
237
+ return list;
238
+ }, [hoverItem, selectedSet, positionOf, items]);
239
+ const shownLabels = useLabelIndices({ enabled: labels, xy: index.xy, labelled, forced });
240
+
241
+ const widthOf = (shape: MarkerShape, role: OverlayRole, state: "default" | "hover" | "selected"): number => {
242
+ const thin = role === "model" || role === "structure";
243
+ const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? 0.5 : 0);
244
+ // A disc's size is its stroke width: grow the diameter by twice the state's extra width.
245
+ return px(shape.paint === "disc" ? 2 * shape.size + (OVERLAY_STATE_WIDTH[state] - 1.5) * 2 : base);
246
+ };
247
+ const ringWidth = px(1.5);
248
+
249
+ return (
250
+ <svg
251
+ viewBox={imageViewBox(stage.image)}
252
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
253
+ role="img"
254
+ aria-label={`${label}: ${items.length} ${items.length === 1 ? "point" : "points"}, ${selectedSet.size} selected`}
255
+ data-hovered={hoverId ?? undefined}
256
+ >
257
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
258
+ {halo &&
259
+ paths.normal.map(({ batch, d }) => (
260
+ <path
261
+ key={`halo|${batch.key}`}
262
+ d={d}
263
+ stroke={HALO}
264
+ strokeWidth={widthOf(batch.shape, batch.role, "default") + px(2)}
265
+ opacity={0.6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)}
266
+ />
267
+ ))}
268
+ {paths.normal.map(({ batch, d }) => (
269
+ <path
270
+ key={batch.key}
271
+ data-batch={batch.key}
272
+ d={d}
273
+ stroke={overlayRole(batch.role)}
274
+ strokeWidth={widthOf(batch.shape, batch.role, "default")}
275
+ opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1}
276
+ />
277
+ ))}
278
+ {halo &&
279
+ paths.picked.map(({ batch, d }) => (
280
+ <path key={`halo|selected|${batch.key}`} d={d} stroke={HALO} strokeWidth={widthOf(batch.shape, batch.role, "selected") + px(2)} />
281
+ ))}
282
+ {halo &&
283
+ paths.rings.map(({ batch, d }) => (
284
+ <path key={`halo|${batch.key}`} d={d} stroke={HALO} strokeWidth={ringWidth + px(2)} />
285
+ ))}
286
+ {paths.picked.map(({ batch, d }) => (
287
+ <path
288
+ key={`selected|${batch.key}`}
289
+ data-selected-points={batch.key}
290
+ d={d}
291
+ stroke={selectionStroke}
292
+ strokeWidth={widthOf(batch.shape, batch.role, "selected")}
293
+ />
294
+ ))}
295
+ {paths.rings.map(({ batch, d }) => (
296
+ <path key={batch.key} data-selection-rings={batch.key} d={d} stroke={selectionStroke} strokeWidth={ringWidth} />
297
+ ))}
298
+ {hoverItem && hoverShape && (
299
+ <>
300
+ {halo && (
301
+ <path
302
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
303
+ stroke={HALO}
304
+ strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)}
305
+ />
306
+ )}
307
+ <path
308
+ data-hovered-point=""
309
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
310
+ stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}
311
+ strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")}
312
+ />
313
+ </>
314
+ )}
315
+ </g>
316
+ {shownLabels.length > 0 && (
317
+ <g data-labels="" fontSize={px(11)} className="font-mono" stroke={HALO} strokeWidth={px(3)} paintOrder="stroke" strokeLinejoin="round">
318
+ {shownLabels.map((i) => {
319
+ const item = items[i]!;
320
+ return (
321
+ <text key={item.id} x={item.x + px(6)} y={item.y - px(5)} fill={LABEL} dominantBaseline="text-after-edge">
322
+ {item.label}
323
+ </text>
324
+ );
325
+ })}
326
+ </g>
327
+ )}
328
+ </svg>
329
+ );
330
+ }
331
+
332
+ /**
333
+ * The path data of a batch, generated again only when what it depends on changed: nothing
334
+ * for a disc marker, the zoom and the window for an outline.
335
+ */
336
+ function batchPath(batch: Batch, items: readonly PointSetItem[], unit: number, cull: Rect | null, cullKey: string): string {
337
+ const disc = batch.shape.paint === "disc";
338
+ const key = disc ? "" : `${unit}|${cullKey}`;
339
+ if (batch.cache?.key === key) return batch.cache.d;
340
+ const window = disc ? null : cull;
341
+ let d = "";
342
+ for (const i of batch.indices) {
343
+ const item = items[i]!;
344
+ if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;
345
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);
346
+ }
347
+ batch.cache = { key, d };
348
+ return d;
349
+ }
350
+
351
+ /**
352
+ * The window outlines are generated for: the viewport plus half a viewport on every side,
353
+ * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
354
+ */
355
+ function cullWindow(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }, count: number): Rect | null {
356
+ if (count <= CULL_ABOVE) return null;
357
+ const visible = visibleRect(view, box);
358
+ if (visible === null) return null;
359
+ const sx = visible.width / 2;
360
+ const sy = visible.height / 2;
361
+ const left = Math.floor((visible.x - sx) / sx) * sx;
362
+ const top = Math.floor((visible.y - sy) / sy) * sy;
363
+ const right = Math.ceil((visible.x + visible.width + sx) / sx) * sx;
364
+ const bottom = Math.ceil((visible.y + visible.height + sy) / sy) * sy;
365
+ return { x: left, y: top, width: right - left, height: bottom - top };
366
+ }
@@ -23,6 +23,8 @@ import {
23
23
  import { overlayRole } from "./overlayRole";
24
24
  import { useStage } from "./stage/ImageStage";
25
25
  import { useStageDrag } from "./stage/StageSurface";
26
+ import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
27
+ import { useStageHitLayer, useStageHitTest } from "./stage/useStageHitTest";
26
28
  import { useScreenPx } from "./stage/useScreenPx";
27
29
  import { imageViewBox, type Rect } from "./stage/view";
28
30
 
@@ -49,6 +51,17 @@ export interface PolylineSetProps {
49
51
  hovered?: PolylineId | null | undefined;
50
52
  /** Called when the line under the pointer changes. */
51
53
  onHover?: ((id: PolylineId | null) => void) | undefined;
54
+ /**
55
+ * Called when the line under the pointer changes: the same as `onHover`, under the name
56
+ * `PointSet` uses, so an app handles every layer's hover alike.
57
+ */
58
+ onHoverChange?: ((id: PolylineId | null) => void) | undefined;
59
+ /**
60
+ * Called when a press lands on a line, with the `pointerdown`, before `onSelect`. It does
61
+ * not fire for a rubber band, nor when a point of a `PointSet` over the line takes the
62
+ * press instead.
63
+ */
64
+ onItemPress?: ((id: PolylineId, event: ReactPointerEvent<SVGPathElement>) => void) | undefined;
52
65
  /**
53
66
  * Called on a selection gesture.
54
67
  * - A click on a line → `[id]`, "replace".
@@ -73,6 +86,10 @@ export interface PolylineSetProps {
73
86
  vertexScale?: number | undefined;
74
87
  /** The layer's accessible name. Defaults to "Lines". */
75
88
  label?: string | undefined;
89
+ /** The id hit-tests report for this layer. Defaults to a generated one. */
90
+ layerId?: string | undefined;
91
+ /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.line`. */
92
+ priority?: number | undefined;
76
93
  }
77
94
 
78
95
  const HALO = overlayRole("halo");
@@ -99,6 +116,8 @@ export function PolylineSet({
99
116
  dimmed,
100
117
  hovered,
101
118
  onHover,
119
+ onHoverChange,
120
+ onItemPress,
102
121
  onSelect,
103
122
  marquee = false,
104
123
  stroke = overlayRole("feature"),
@@ -106,16 +125,30 @@ export function PolylineSet({
106
125
  hitWidth = 14,
107
126
  vertexScale = 3,
108
127
  label = "Lines",
128
+ layerId,
129
+ priority = STAGE_HIT_PRIORITY.line,
109
130
  }: PolylineSetProps) {
110
131
  const stage = useStage();
111
132
  const startDrag = useStageDrag();
112
133
  const px = useScreenPx();
134
+ const { hitTestAll } = useStageHitTest();
113
135
 
114
136
  const index = useMemo(() => buildPolylineIndex(items), [items]);
115
137
  const selectedSet = useMemo(() => new Set(selected ?? []), [selected]);
116
138
  const dimmedSet = useMemo(() => new Set(dimmed ?? []), [dimmed]);
117
139
  const byId = useMemo(() => new Map(items.map((item) => [item.id, item])), [items]);
118
140
 
141
+ // Answers the stage's hit-test, so an app can ask one question across layers. The line's
142
+ // own hover and press stay on its hit path, which gives the pointer cursor and the claim.
143
+ const ownId = useStageHitLayer({
144
+ layerId,
145
+ priority,
146
+ pick: (point, radius) => {
147
+ const hit = nearestPolyline(index, point, radius);
148
+ return hit ? { id: hit.id, dist: hit.distance } : null;
149
+ },
150
+ });
151
+
119
152
  const [ownHover, setOwnHover] = useState<PolylineId | null>(null);
120
153
  const hoverId = hovered !== undefined ? hovered : ownHover;
121
154
  const [band, setBand] = useState<Rect | null>(null);
@@ -178,6 +211,7 @@ export function PolylineSet({
178
211
  if (id === hoverId) return;
179
212
  setOwnHover(id);
180
213
  onHover?.(id);
214
+ onHoverChange?.(id);
181
215
  };
182
216
 
183
217
  const sweep = (event: ReactPointerEvent<SVGElement>) => {
@@ -206,9 +240,14 @@ export function PolylineSet({
206
240
  }
207
241
  const id = pickAt(event);
208
242
  if (id === null) return;
243
+ // A marker over the line is what the pointer is on: leave the press to the stage, which
244
+ // hands it to the point layer.
245
+ const point = stage.toImage({ x: event.clientX, y: event.clientY });
246
+ if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
209
247
  // Claimed, and selected on the press: a selection that waits for the release feels like
210
248
  // lag on a canvas where every other gesture is immediate.
211
249
  event.stopPropagation();
250
+ onItemPress?.(id, event);
212
251
  onSelect?.([id], event.metaKey || event.ctrlKey ? "toggle" : "replace");
213
252
  };
214
253