@vitavision/stage2d 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/stage2d",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "The vitavision 2D image stage: view transform, zoom/pan, layered overlays, measurement.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,391 @@
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 { buildPointIndexFrom, nearestPoint, thinPoints, type PointId, type PointItem } from "./pointIndex";
16
+ import { useStage } from "./stage/ImageStage";
17
+ import type { StagePointerEvent } from "./stage/hitContext";
18
+ import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
19
+ import { useStageHitLayer } from "./stage/useStageHitTest";
20
+ import { useScreenPx } from "./stage/useScreenPx";
21
+ import { imageViewBox, type Rect } from "./stage/view";
22
+
23
+ /** One point of a `PointSet`. */
24
+ export interface PointSetItem extends PointItem {
25
+ /**
26
+ * The marker kind: a built-in (`dot`, `plus`, `cross`, `square`, `hollow`, `directed`) or
27
+ * a key of the layer's `markers`. Defaults to the layer's `kind`.
28
+ */
29
+ kind?: string | undefined;
30
+ /** The overlay role it is painted in. Defaults to the marker kind's role, usually `feature`. */
31
+ role?: OverlayRole | undefined;
32
+ /** Its orientation in radians, clockwise from +x; read by `directed`. */
33
+ angle?: number | undefined;
34
+ /** Text drawn beside it, when the zoom leaves room (points at least 24 screen px apart). */
35
+ label?: string | undefined;
36
+ }
37
+
38
+ /** Props of `PointSet`. */
39
+ export interface PointSetProps {
40
+ /** The points, in image coordinates. */
41
+ items: readonly PointSetItem[];
42
+ /** The marker kind of an item that names none. Defaults to `"dot"`. */
43
+ kind?: string | undefined;
44
+ /** More marker kinds, or replacements for built-in ones, by name. */
45
+ markers?: Readonly<Record<string, MarkerShape>> | undefined;
46
+ /** The hovered id, when the app controls hover (a list beside the stage hovers points too). */
47
+ hoveredId?: PointId | null | undefined;
48
+ /** Called when the point under the pointer changes. `null` when it leaves every point. */
49
+ onHoverChange?: ((id: PointId | null) => void) | undefined;
50
+ /** The selected ids, drawn at 2.5 px in the selection colour with a ring. */
51
+ selectedIds?: Iterable<PointId> | undefined;
52
+ /**
53
+ * Ids drawn at 35 % opacity, as a set or a predicate (outside the current filter, say).
54
+ * They still take hover and presses. Pass a stable value: a new one re-batches the layer.
55
+ */
56
+ dimmed?: Iterable<PointId> | ((id: PointId) => boolean) | undefined;
57
+ /**
58
+ * A press landed on a point. Setting it makes the layer claim presses on its points, so
59
+ * the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for a
60
+ * touch tap), so `useStageDrag` can start a drag from it.
61
+ *
62
+ * A mounted `StageSurface` hears a press first; there, ask `useStageHitTest` what is
63
+ * under it instead.
64
+ */
65
+ onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | undefined;
66
+ /** Show the items' `label`s where the zoom leaves room for them. On by default. */
67
+ labels?: boolean | undefined;
68
+ /** Draw the dark band under every mark. On by default; off for a fast, flat layer. */
69
+ halo?: boolean | undefined;
70
+ /** CSS colour of selected points and rings. Defaults to the overlay `selection` role. */
71
+ selectionStroke?: string | undefined;
72
+ /** The id hit-tests report for this layer. Defaults to a generated one. */
73
+ layerId?: string | undefined;
74
+ /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.point`. */
75
+ priority?: number | undefined;
76
+ /** The layer's accessible name. Defaults to "Points". */
77
+ label?: string | undefined;
78
+ }
79
+
80
+ /** Labels need this much room between points, in screen pixels (overlay grammar §5). */
81
+ const LABEL_SPACING = 24;
82
+ /** The most label elements drawn at once. */
83
+ const MAX_LABELS = 200;
84
+ /** The most hovered-or-selected labels forced on regardless of spacing. */
85
+ const MAX_FORCED_LABELS = 50;
86
+ /** Past this many points, outlines are generated for the visible part only. */
87
+ const CULL_ABOVE = 3000;
88
+ /** How much bigger than a marker its selection ring is, in screen pixels. */
89
+ const RING_GAP = 4;
90
+
91
+ const HALO = overlayRole("halo");
92
+ const LABEL = overlayRole("label");
93
+
94
+ /** The points of one batched path. */
95
+ interface Batch {
96
+ key: string;
97
+ shape: MarkerShape;
98
+ role: OverlayRole;
99
+ dim: boolean;
100
+ /** Item positions, ascending. */
101
+ indices: number[];
102
+ /** The last generated path data and what it was generated for. */
103
+ cache: { key: string; d: string } | null;
104
+ }
105
+
106
+ /**
107
+ * A selectable set of points inside an `ImageStage`.
108
+ *
109
+ * - **Markers** by kind, from the overlay grammar: `dot`, `plus` (corner), `cross`, `square`,
110
+ * `hollow` (predicted), `directed`. Add your own through `markers`.
111
+ * - **States**, from visual-language §5: default 1.5 screen px, hover 2, selected 2.5 in the
112
+ * selection colour with a ring, dimmed at 35 % opacity. Every mark has a halo.
113
+ * - **Labels** only where points are at least 24 screen px apart, at most 200 at a time.
114
+ * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here,
115
+ * and `useStageHitTest` for an app that arbitrates between layers.
116
+ *
117
+ * Outlines (`plus`, `cross`, …) are regenerated when the zoom changes, since their size is in
118
+ * screen pixels; past 3,000 points only those near the viewport are generated. `dot` is a
119
+ * zero-length stroke whose width is its size, so it is not regenerated at all.
120
+ *
121
+ * The SVG carries `data-hovered` (the hovered id).
122
+ */
123
+ export function PointSet({
124
+ items,
125
+ kind = "dot",
126
+ markers,
127
+ hoveredId,
128
+ onHoverChange,
129
+ selectedIds,
130
+ dimmed,
131
+ onItemPress,
132
+ labels = true,
133
+ halo = true,
134
+ selectionStroke = overlayRole("selection"),
135
+ layerId,
136
+ priority = STAGE_HIT_PRIORITY.point,
137
+ label = "Points",
138
+ }: PointSetProps) {
139
+ const stage = useStage();
140
+ const px = useScreenPx();
141
+ const unit = px(1);
142
+
143
+ const shapes = useMemo<Readonly<Record<string, MarkerShape>>>(() => ({ ...MARKER_SHAPES, ...markers }), [markers]);
144
+ const index = useMemo(() => buildPointIndexFrom(items), [items]);
145
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
146
+ const isDimmed = useMemo(() => {
147
+ if (typeof dimmed === "function") return dimmed;
148
+ const set = new Set(dimmed ?? []);
149
+ return (id: PointId) => set.has(id);
150
+ }, [dimmed]);
151
+ const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);
152
+
153
+ const [ownHover, setOwnHover] = useState<PointId | null>(null);
154
+ const hoverId = hoveredId !== undefined ? hoveredId : ownHover;
155
+
156
+ useStageHitLayer({
157
+ layerId,
158
+ priority,
159
+ pick: (point, radius) => {
160
+ const hit = nearestPoint(index, point.x, point.y, radius);
161
+ return hit ? { id: hit.id, dist: hit.dist } : null;
162
+ },
163
+ onHover: (id) => {
164
+ setOwnHover(id);
165
+ onHoverChange?.(id);
166
+ },
167
+ onPress: onItemPress ? (id, event) => onItemPress(id, event) : undefined,
168
+ });
169
+
170
+ // Items grouped by appearance. Rebuilt when the items or the selection change, never on
171
+ // hover or on a view change.
172
+ const groups = useMemo(() => {
173
+ const normal = new Map<string, Batch>();
174
+ const picked = new Map<string, Batch>();
175
+ items.forEach((item, i) => {
176
+ const kindName = item.kind ?? kind;
177
+ const shape = shapes[kindName] ?? MARKER_SHAPES.dot;
178
+ if (selectedSet.has(item.id)) {
179
+ const key = kindName;
180
+ let batch = picked.get(key);
181
+ if (!batch) {
182
+ batch = { key, shape, role: "selection", dim: false, indices: [], cache: null };
183
+ picked.set(key, batch);
184
+ }
185
+ batch.indices.push(i);
186
+ return;
187
+ }
188
+ const role = item.role ?? shape.role ?? "feature";
189
+ const dim = isDimmed(item.id);
190
+ const key = `${dim ? 1 : 0}|${role}|${kindName}`;
191
+ let batch = normal.get(key);
192
+ if (!batch) {
193
+ batch = { key, shape, role, dim, indices: [], cache: null };
194
+ normal.set(key, batch);
195
+ }
196
+ batch.indices.push(i);
197
+ });
198
+ const rings = [...picked.values()].map<Batch>((batch) => ({
199
+ ...batch,
200
+ key: `ring|${batch.key}`,
201
+ shape: {
202
+ paint: "line",
203
+ size: 0,
204
+ path: (x, y, u) => circlePath(x, y, (batch.shape.size + RING_GAP) * u),
205
+ },
206
+ cache: null,
207
+ }));
208
+ return { normal: [...normal.values()], picked: [...picked.values()], rings };
209
+ }, [items, kind, shapes, selectedSet, isDimmed]);
210
+
211
+ // The part of the scene to generate outlines for: everything for a small set, otherwise a
212
+ // window around the viewport, snapped so panning rebuilds it once per half screen.
213
+ const cull = cullWindow(stage.view, stage.box, items.length);
214
+ const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
215
+
216
+ // Each batch remembers the outline it last generated and what that was for, so this is
217
+ // O(batches) on a render that changed neither the zoom nor the window (a hover, a pan).
218
+ const build = (batches: Batch[]) => batches.map((batch) => ({ batch, d: batchPath(batch, items, unit, cull, cullKey) }));
219
+ const paths = { normal: build(groups.normal), picked: build(groups.picked), rings: build(groups.rings) };
220
+
221
+ const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : undefined;
222
+ const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;
223
+ const hoverShape = hoverItem ? (shapes[hoverItem.kind ?? kind] ?? MARKER_SHAPES.dot) : undefined;
224
+ const hoverRole = hoverItem?.role ?? hoverShape?.role ?? "feature";
225
+
226
+ // Labels: the spacing is a function of the zoom only, so panning does not reshuffle which
227
+ // points carry one.
228
+ const labelled = useMemo(() => {
229
+ const list: number[] = [];
230
+ items.forEach((item, i) => {
231
+ if (item.label) list.push(i);
232
+ });
233
+ return list;
234
+ }, [items]);
235
+ const spacing = LABEL_SPACING * unit;
236
+ const spaced = useMemo(
237
+ () => (labels && labelled.length > 0 ? thinPoints(index.xy, spacing, labelled) : []),
238
+ [labels, labelled, index, spacing],
239
+ );
240
+ const shownLabels = useMemo(() => {
241
+ if (!labels || (spaced.length === 0 && !hoverItem?.label && selectedSet.size === 0)) return [];
242
+ const view = visibleRect(stage.view, stage.box);
243
+ const inView = (i: number) => {
244
+ const item = items[i]!;
245
+ return view === null || (item.x >= view.x && item.x <= view.x + view.width && item.y >= view.y && item.y <= view.y + view.height);
246
+ };
247
+ const shown = new Set<number>();
248
+ const forced = [...(hoverItem ? [positionOf.get(hoverItem.id)!] : []), ...[...selectedSet].map((id) => positionOf.get(id) ?? -1)];
249
+ for (const i of forced) {
250
+ if (shown.size >= MAX_FORCED_LABELS) break;
251
+ if (i >= 0 && items[i]!.label && inView(i)) shown.add(i);
252
+ }
253
+ for (const i of spaced) {
254
+ if (shown.size >= MAX_LABELS) break;
255
+ if (inView(i)) shown.add(i);
256
+ }
257
+ return [...shown];
258
+ }, [labels, spaced, items, hoverItem, selectedSet, positionOf, stage.view, stage.box]);
259
+
260
+ const widthOf = (shape: MarkerShape, role: OverlayRole, state: "default" | "hover" | "selected"): number => {
261
+ const thin = role === "model" || role === "structure";
262
+ const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? 0.5 : 0);
263
+ // A disc's size is its stroke width: grow the diameter by twice the state's extra width.
264
+ return px(shape.paint === "disc" ? 2 * shape.size + (OVERLAY_STATE_WIDTH[state] - 1.5) * 2 : base);
265
+ };
266
+ const ringWidth = px(1.5);
267
+
268
+ return (
269
+ <svg
270
+ viewBox={imageViewBox(stage.image)}
271
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
272
+ role="img"
273
+ aria-label={`${label}: ${items.length} ${items.length === 1 ? "point" : "points"}, ${selectedSet.size} selected`}
274
+ data-hovered={hoverId ?? undefined}
275
+ >
276
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
277
+ {halo &&
278
+ paths.normal.map(({ batch, d }) => (
279
+ <path
280
+ key={`halo|${batch.key}`}
281
+ d={d}
282
+ stroke={HALO}
283
+ strokeWidth={widthOf(batch.shape, batch.role, "default") + px(2)}
284
+ opacity={0.6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)}
285
+ />
286
+ ))}
287
+ {paths.normal.map(({ batch, d }) => (
288
+ <path
289
+ key={batch.key}
290
+ data-batch={batch.key}
291
+ d={d}
292
+ stroke={overlayRole(batch.role)}
293
+ strokeWidth={widthOf(batch.shape, batch.role, "default")}
294
+ opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1}
295
+ />
296
+ ))}
297
+ {halo &&
298
+ paths.picked.map(({ batch, d }) => (
299
+ <path key={`halo|selected|${batch.key}`} d={d} stroke={HALO} strokeWidth={widthOf(batch.shape, batch.role, "selected") + px(2)} />
300
+ ))}
301
+ {halo &&
302
+ paths.rings.map(({ batch, d }) => (
303
+ <path key={`halo|${batch.key}`} d={d} stroke={HALO} strokeWidth={ringWidth + px(2)} />
304
+ ))}
305
+ {paths.picked.map(({ batch, d }) => (
306
+ <path
307
+ key={`selected|${batch.key}`}
308
+ data-selected-points={batch.key}
309
+ d={d}
310
+ stroke={selectionStroke}
311
+ strokeWidth={widthOf(batch.shape, batch.role, "selected")}
312
+ />
313
+ ))}
314
+ {paths.rings.map(({ batch, d }) => (
315
+ <path key={batch.key} data-selection-rings={batch.key} d={d} stroke={selectionStroke} strokeWidth={ringWidth} />
316
+ ))}
317
+ {hoverItem && hoverShape && (
318
+ <>
319
+ {halo && (
320
+ <path
321
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
322
+ stroke={HALO}
323
+ strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)}
324
+ />
325
+ )}
326
+ <path
327
+ data-hovered-point=""
328
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
329
+ stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}
330
+ strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")}
331
+ />
332
+ </>
333
+ )}
334
+ </g>
335
+ {shownLabels.length > 0 && (
336
+ <g data-labels="" fontSize={px(11)} className="font-mono" stroke={HALO} strokeWidth={px(3)} paintOrder="stroke" strokeLinejoin="round">
337
+ {shownLabels.map((i) => {
338
+ const item = items[i]!;
339
+ return (
340
+ <text key={item.id} x={item.x + px(6)} y={item.y - px(5)} fill={LABEL} dominantBaseline="text-after-edge">
341
+ {item.label}
342
+ </text>
343
+ );
344
+ })}
345
+ </g>
346
+ )}
347
+ </svg>
348
+ );
349
+ }
350
+
351
+ /**
352
+ * The path data of a batch, generated again only when what it depends on changed: nothing
353
+ * for a disc marker, the zoom and the window for an outline.
354
+ */
355
+ function batchPath(batch: Batch, items: readonly PointSetItem[], unit: number, cull: Rect | null, cullKey: string): string {
356
+ const disc = batch.shape.paint === "disc";
357
+ const key = disc ? "" : `${unit}|${cullKey}`;
358
+ if (batch.cache?.key === key) return batch.cache.d;
359
+ const window = disc ? null : cull;
360
+ let d = "";
361
+ for (const i of batch.indices) {
362
+ const item = items[i]!;
363
+ if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;
364
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);
365
+ }
366
+ batch.cache = { key, d };
367
+ return d;
368
+ }
369
+
370
+ /** The image-space rectangle on screen, or `null` before the viewport is measured. */
371
+ function visibleRect(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }): Rect | null {
372
+ if (!(box.width > 0) || !(view.scale > 0)) return null;
373
+ return { x: -view.tx / view.scale, y: -view.ty / view.scale, width: box.width / view.scale, height: box.height / view.scale };
374
+ }
375
+
376
+ /**
377
+ * The window outlines are generated for: the viewport plus half a viewport on every side,
378
+ * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
379
+ */
380
+ function cullWindow(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }, count: number): Rect | null {
381
+ if (count <= CULL_ABOVE) return null;
382
+ const visible = visibleRect(view, box);
383
+ if (visible === null) return null;
384
+ const sx = visible.width / 2;
385
+ const sy = visible.height / 2;
386
+ const left = Math.floor((visible.x - sx) / sx) * sx;
387
+ const top = Math.floor((visible.y - sy) / sy) * sy;
388
+ const right = Math.ceil((visible.x + visible.width + sx) / sx) * sx;
389
+ const bottom = Math.ceil((visible.y + visible.height + sy) / sy) * sy;
390
+ return { x: left, y: top, width: right - left, height: bottom - top };
391
+ }
@@ -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
 
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Marker glyphs for `PointSet`: one path generator per feature kind (overlay grammar,
3
+ * `docs/visual-language.md` §5).
4
+ *
5
+ * A glyph is a function from a position to SVG path data, so a layer can append thousands of
6
+ * them into one `<path>` per state and style. Sizes are screen pixels: a generator receives
7
+ * `unit`, the image pixels per screen pixel (`useScreenPx()(1)`), and scales its constants by
8
+ * it. A glyph whose `paint` is `"disc"` needs no `unit` at all (it is a zero-length segment
9
+ * drawn with round caps, its size the stroke width), so it is not rebuilt when the zoom
10
+ * changes.
11
+ *
12
+ * Pure: no React, no DOM.
13
+ */
14
+
15
+ import type { OverlayRole } from "./overlayRole";
16
+
17
+ /** One kind of marker. */
18
+ export interface MarkerShape {
19
+ /**
20
+ * How the path is painted:
21
+ * - `"disc"`: `path` returns a zero-length segment per marker; the stroke width is the
22
+ * disc's diameter. Independent of `unit`, so a batched path survives a zoom unchanged.
23
+ * - `"line"`: `path` returns an outline, stroked at the state's width.
24
+ */
25
+ readonly paint: "disc" | "line";
26
+ /** Half the glyph's extent in screen pixels at rest: a disc's radius, a plus's arm. */
27
+ readonly size: number;
28
+ /** The role a marker of this kind has unless the item says otherwise. Defaults to `feature`. */
29
+ readonly role?: OverlayRole | undefined;
30
+ /**
31
+ * The path data for one marker.
32
+ *
33
+ * @param x - Centre x, in image coordinates.
34
+ * @param y - Centre y, in image coordinates.
35
+ * @param unit - Image pixels per screen pixel.
36
+ * @param angle - The item's orientation in radians, `0` when it has none.
37
+ * @returns Path commands, absolute at the start (`M x y …`) and self-contained.
38
+ */
39
+ path: (x: number, y: number, unit: number, angle: number) => string;
40
+ }
41
+
42
+ /** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */
43
+ function n(value: number): number {
44
+ return Math.round(value * 1000) / 1000;
45
+ }
46
+
47
+ /**
48
+ * A circle as two arcs, centred at `(x, y)`.
49
+ *
50
+ * @param x - Centre x.
51
+ * @param y - Centre y.
52
+ * @param r - Radius, in the units of `x` and `y`.
53
+ * @returns Path data.
54
+ */
55
+ export function circlePath(x: number, y: number, r: number): string {
56
+ 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`;
57
+ }
58
+
59
+ /** The names of the built-in marker kinds. */
60
+ export type BuiltinMarkerKind = "dot" | "plus" | "cross" | "square" | "hollow" | "directed";
61
+
62
+ /** The built-in kinds, with the overlay grammar's glyph for each. */
63
+ export const MARKER_SHAPES: Readonly<Record<BuiltinMarkerKind, MarkerShape>> = {
64
+ /** A blob, circle centre or keypoint: a dot of radius 2.5 px. */
65
+ dot: {
66
+ paint: "disc",
67
+ size: 2.5,
68
+ path: (x, y) => `M${n(x)} ${n(y)}h0`,
69
+ },
70
+ /** A corner or X-junction: a plus with 5 px arms, so the centre stays visible. */
71
+ plus: {
72
+ paint: "line",
73
+ size: 5,
74
+ path: (x, y, u) => {
75
+ const a = 5 * u;
76
+ return `M${n(x - a)} ${n(y)}h${n(2 * a)}M${n(x)} ${n(y - a)}v${n(2 * a)}`;
77
+ },
78
+ },
79
+ /** A diagonal cross with 4 px arms: a second corner style, or "rejected". */
80
+ cross: {
81
+ paint: "line",
82
+ size: 4,
83
+ path: (x, y, u) => {
84
+ const a = 4 * u;
85
+ 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)}`;
86
+ },
87
+ },
88
+ /** A hollow square of half-side 3.5 px. */
89
+ square: {
90
+ paint: "line",
91
+ size: 3.5,
92
+ path: (x, y, u) => {
93
+ const a = 3.5 * u;
94
+ return `M${n(x - a)} ${n(y - a)}h${n(2 * a)}v${n(2 * a)}h${n(-2 * a)}Z`;
95
+ },
96
+ },
97
+ /** A reprojected or predicted point: a hollow circle of radius 4 px, in the model colour. */
98
+ hollow: {
99
+ paint: "line",
100
+ size: 4,
101
+ role: "model",
102
+ path: (x, y, u) => circlePath(x, y, 4 * u),
103
+ },
104
+ /**
105
+ * A point with an orientation: a small ring and a tick of length 8 px from it along
106
+ * `angle`, measured clockwise from +x in image coordinates (y points down).
107
+ */
108
+ directed: {
109
+ paint: "line",
110
+ size: 6,
111
+ path: (x, y, u, angle) => {
112
+ const c = Math.cos(angle);
113
+ const s = Math.sin(angle);
114
+ return (
115
+ `${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)}`
116
+ );
117
+ },
118
+ },
119
+ };