@vitavision/stage2d 0.10.0 → 0.11.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.10.0",
3
+ "version": "0.11.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,292 @@
1
+ /**
2
+ * Many ellipses over the image whose size is data, hoverable and selectable: fitted ring
3
+ * edges, edge-bit dots, drawn ellipse annotations.
4
+ *
5
+ * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
6
+ * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
7
+ * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
8
+ * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
9
+ * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
10
+ */
11
+
12
+ import { useMemo, useState } from "react";
13
+
14
+ import { buildEllipseIndex, ellipsePath, nearestEllipse, type Ellipse, type EllipseId, type EllipseIndex } from "./ellipseIndex";
15
+ import { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
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 } from "./stage/view";
22
+
23
+ /** One ellipse of an `EllipseSet`. */
24
+ export interface EllipseSetItem extends Ellipse {
25
+ /** The overlay role it is painted in. Defaults to the layer's `role`. */
26
+ role?: OverlayRole | undefined;
27
+ /** Draw it dashed (4 3 screen px), so two kinds differ by more than colour. */
28
+ dashed?: boolean | undefined;
29
+ /** Opacity in [0, 1], rounded to a tenth so ellipses still share paths. Defaults to 1. */
30
+ opacity?: number | undefined;
31
+ }
32
+
33
+ /** Props of `EllipseSet`. */
34
+ export interface EllipseSetProps {
35
+ /** The ellipses, in image coordinates. */
36
+ items: readonly EllipseSetItem[];
37
+ /** The role of an item that names none. Defaults to `"feature"`. */
38
+ role?: OverlayRole | undefined;
39
+ /** The hovered id, when the app controls hover: its ellipses are drawn at 2 px. */
40
+ hoveredId?: EllipseId | null | undefined;
41
+ /** Called when the ellipse under the pointer changes. `null` when it leaves every ellipse. Not called when `pickable` is off. */
42
+ onHoverChange?: ((id: EllipseId | null) => void) | undefined;
43
+ /** The selected ids, drawn at 2.5 px in the selection colour. */
44
+ selectedIds?: Iterable<EllipseId> | undefined;
45
+ /** Ids drawn at 35 % opacity, as a set or a predicate. Pass a stable value: a new one re-batches the layer. */
46
+ dimmed?: Iterable<EllipseId> | ((id: EllipseId) => boolean) | undefined;
47
+ /**
48
+ * A press landed on an ellipse. Setting it makes the layer claim presses on its ellipses,
49
+ * so the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for
50
+ * a touch tap), so `useShapeDrag` can start a drag from it.
51
+ *
52
+ * A mounted `StageSurface` hears a press first; there, ask `useStageHitTest` what is
53
+ * under it instead.
54
+ */
55
+ onItemPress?: ((id: EllipseId, event: StagePointerEvent) => void) | undefined;
56
+ /**
57
+ * Whether the layer takes part in the stage's hit-test. On by default. Turn it off for a
58
+ * decorative layer (the ring outlines under a `PointSet` of centres), so it neither
59
+ * hovers, nor claims presses, nor answers `useStageHitTest`.
60
+ */
61
+ pickable?: boolean | undefined;
62
+ /** The id hit-tests report for this layer. Defaults to a generated one. */
63
+ layerId?: string | undefined;
64
+ /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.area`. */
65
+ priority?: number | undefined;
66
+ /** Draw the dark band under every stroke. On by default. */
67
+ halo?: boolean | undefined;
68
+ /**
69
+ * The smallest semi-axis, in screen pixels: a dot whose data size would vanish at the fitted
70
+ * zoom is still drawn this large. Omit for none.
71
+ */
72
+ minRadius?: number | undefined;
73
+ /** CSS colour of selected ellipses. Defaults to the overlay `selection` role. */
74
+ selectionStroke?: string | undefined;
75
+ /** Name the layer as an image for assistive technology. Without it the layer is decorative (`aria-hidden`). */
76
+ label?: string | undefined;
77
+ }
78
+
79
+ const HALO = overlayRole("halo");
80
+
81
+ /** The outline of an item, its semi-axes raised to `floor` image pixels. */
82
+ function outlineOf(item: EllipseSetItem, floor: number): string {
83
+ return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);
84
+ }
85
+
86
+ /** The concatenated outlines of the items at `indices`. */
87
+ function batchPath(items: readonly EllipseSetItem[], indices: readonly number[], floor: number): string {
88
+ let d = "";
89
+ for (const i of indices) d += outlineOf(items[i]!, floor);
90
+ return d;
91
+ }
92
+
93
+ /**
94
+ * The layer's entry in the stage's hit registry: a component, not a hook call in
95
+ * `EllipseSet`, so `pickable={false}` really unregisters it. Renders nothing.
96
+ */
97
+ function EllipseHits({
98
+ index,
99
+ layerId,
100
+ priority,
101
+ onHover,
102
+ onPress,
103
+ }: {
104
+ index: EllipseIndex;
105
+ layerId: string | undefined;
106
+ priority: number;
107
+ onHover: (id: EllipseId | null) => void;
108
+ onPress: ((id: EllipseId, event: StagePointerEvent) => void) | undefined;
109
+ }) {
110
+ useStageHitLayer({
111
+ layerId,
112
+ priority,
113
+ pick: (point, radius) => {
114
+ const hit = nearestEllipse(index, point, radius);
115
+ return hit ? { id: hit.id, dist: hit.inside ? 0 : hit.distance } : null;
116
+ },
117
+ onHover,
118
+ onPress: onPress ? (id, event) => onPress(id, event) : undefined,
119
+ });
120
+ return null;
121
+ }
122
+
123
+ /** The ellipses of one batched path. */
124
+ interface Batch {
125
+ key: string;
126
+ role: OverlayRole;
127
+ dashed: boolean;
128
+ opacity: number;
129
+ dim: boolean;
130
+ /** Item positions, ascending. */
131
+ indices: number[];
132
+ }
133
+
134
+ /**
135
+ * A batched set of ellipses inside an `ImageStage`.
136
+ *
137
+ * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
138
+ * the stroke is a screen constant.
139
+ * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
140
+ * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
141
+ * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
142
+ * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
143
+ * an outline picks that ellipse, else the smallest ellipse containing the point.
144
+ * `onHoverChange` and `onItemPress` here, and `useStageHitTest` for an app that arbitrates
145
+ * between layers. `pickable={false}` turns it off.
146
+ *
147
+ * The SVG carries `data-ellipses` (the count) and `data-hovered` (the hovered id).
148
+ */
149
+ export function EllipseSet({
150
+ items,
151
+ role = "feature",
152
+ hoveredId,
153
+ onHoverChange,
154
+ selectedIds,
155
+ dimmed,
156
+ onItemPress,
157
+ pickable = true,
158
+ layerId,
159
+ priority = STAGE_HIT_PRIORITY.area,
160
+ halo = true,
161
+ minRadius,
162
+ selectionStroke = overlayRole("selection"),
163
+ label,
164
+ }: EllipseSetProps) {
165
+ const stage = useStage();
166
+ const px = useScreenPx();
167
+ const unit = px(1);
168
+
169
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
170
+ const isDimmed = useMemo(() => {
171
+ if (typeof dimmed === "function") return dimmed;
172
+ const set = new Set(dimmed ?? []);
173
+ return (id: EllipseId) => set.has(id);
174
+ }, [dimmed]);
175
+
176
+ const index = useMemo(() => (pickable ? buildEllipseIndex(items) : null), [items, pickable]);
177
+ const [ownHover, setOwnHover] = useState<EllipseId | null>(null);
178
+ const hoverId = hoveredId !== undefined ? hoveredId : pickable ? ownHover : null;
179
+
180
+ const batches = useMemo(() => {
181
+ const normal = new Map<string, Batch>();
182
+ const picked: Batch = { key: "selected", role: "selection", dashed: false, opacity: 1, dim: false, indices: [] };
183
+ items.forEach((item, i) => {
184
+ if (selectedSet.has(item.id)) {
185
+ picked.indices.push(i);
186
+ return;
187
+ }
188
+ const itemRole = item.role ?? role;
189
+ const dashed = item.dashed ?? false;
190
+ const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;
191
+ const dim = isDimmed(item.id);
192
+ const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? "dashed" : "solid"}|${opacity}`;
193
+ let batch = normal.get(key);
194
+ if (!batch) {
195
+ batch = { key, role: itemRole, dashed, opacity, dim, indices: [] };
196
+ normal.set(key, batch);
197
+ }
198
+ batch.indices.push(i);
199
+ });
200
+ return { normal: [...normal.values()], picked: picked.indices.length > 0 ? picked : null };
201
+ }, [items, role, selectedSet, isDimmed]);
202
+
203
+ // Outlines depend on the zoom only through the screen-pixel floor.
204
+ const floor = minRadius !== undefined ? minRadius * unit : 0;
205
+ const normalPaths = useMemo(
206
+ () => batches.normal.map((batch) => ({ batch, d: batchPath(items, batch.indices, floor) })),
207
+ [batches, items, floor],
208
+ );
209
+ const pickedPath = useMemo(() => (batches.picked ? batchPath(items, batches.picked.indices, floor) : ""), [batches, items, floor]);
210
+
211
+ const hoverPositions: number[] = [];
212
+ if (hoverId !== null) {
213
+ items.forEach((item, i) => {
214
+ if (item.id === hoverId) hoverPositions.push(i);
215
+ });
216
+ }
217
+ const hoverSelected = hoverId !== null && selectedSet.has(hoverId);
218
+
219
+ const widthOf = (itemRole: OverlayRole, state: "default" | "hover" | "selected"): number => {
220
+ const thin = itemRole === "model" || itemRole === "structure";
221
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? 0.5 : 0));
222
+ };
223
+ const dash = `${px(4)} ${px(3)}`;
224
+
225
+ return (
226
+ <svg
227
+ viewBox={imageViewBox(stage.image)}
228
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
229
+ {...(label !== undefined ? { role: "img", "aria-label": label } : { "aria-hidden": true })}
230
+ data-ellipses={items.length}
231
+ data-hovered={hoverId ?? undefined}
232
+ >
233
+ {index && (
234
+ <EllipseHits
235
+ index={index}
236
+ layerId={layerId}
237
+ priority={priority}
238
+ onHover={(id) => {
239
+ setOwnHover(id);
240
+ onHoverChange?.(id);
241
+ }}
242
+ onPress={onItemPress}
243
+ />
244
+ )}
245
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
246
+ {normalPaths.map(({ batch, d }) => (
247
+ <g key={batch.key} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>
248
+ {halo && (
249
+ <path
250
+ d={d}
251
+ stroke={HALO}
252
+ strokeWidth={widthOf(batch.role, "default") + px(2)}
253
+ strokeDasharray={batch.dashed ? dash : undefined}
254
+ opacity={0.6 * batch.opacity}
255
+ />
256
+ )}
257
+ <path
258
+ data-batch={batch.key}
259
+ d={d}
260
+ stroke={overlayRole(batch.role)}
261
+ strokeWidth={widthOf(batch.role, "default")}
262
+ strokeDasharray={batch.dashed ? dash : undefined}
263
+ opacity={batch.opacity}
264
+ />
265
+ </g>
266
+ ))}
267
+ {batches.picked && (
268
+ <>
269
+ {halo && <path d={pickedPath} stroke={HALO} strokeWidth={widthOf("selection", "selected") + px(2)} />}
270
+ <path data-selected-ellipses="" d={pickedPath} stroke={selectionStroke} strokeWidth={widthOf("selection", "selected")} />
271
+ </>
272
+ )}
273
+ {hoverPositions.map((position) => {
274
+ const item = items[position]!;
275
+ const itemRole = item.role ?? role;
276
+ const state = hoverSelected ? "selected" : "hover";
277
+ return (
278
+ <g key={position}>
279
+ {halo && <path d={outlineOf(item, floor)} stroke={HALO} strokeWidth={widthOf(itemRole, state) + px(2)} />}
280
+ <path
281
+ data-hovered-ellipse=""
282
+ d={outlineOf(item, floor)}
283
+ stroke={hoverSelected ? selectionStroke : overlayRole(itemRole)}
284
+ strokeWidth={widthOf(itemRole, state)}
285
+ />
286
+ </g>
287
+ );
288
+ })}
289
+ </g>
290
+ </svg>
291
+ );
292
+ }
@@ -32,6 +32,8 @@ export interface PointSetItem extends PointItem {
32
32
  role?: OverlayRole | undefined;
33
33
  /** Its orientation in radians, clockwise from +x; read by `directed`. */
34
34
  angle?: number | undefined;
35
+ /** A second angle in radians, for a glyph with two axes. `MarkerShape.path` gets `undefined` without it. */
36
+ angle2?: number | undefined;
35
37
  /** Text drawn beside it, when the zoom leaves room (points at least 24 screen px apart). */
36
38
  label?: string | undefined;
37
39
  }
@@ -299,14 +301,14 @@ export function PointSet({
299
301
  <>
300
302
  {halo && (
301
303
  <path
302
- d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
304
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2)}
303
305
  stroke={HALO}
304
306
  strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)}
305
307
  />
306
308
  )}
307
309
  <path
308
310
  data-hovered-point=""
309
- d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}
311
+ d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0, hoverItem.angle2)}
310
312
  stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}
311
313
  strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")}
312
314
  />
@@ -342,7 +344,7 @@ function batchPath(batch: Batch, items: readonly PointSetItem[], unit: number, c
342
344
  for (const i of batch.indices) {
343
345
  const item = items[i]!;
344
346
  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);
347
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0, item.angle2);
346
348
  }
347
349
  batch.cache = { key, d };
348
350
  return d;
@@ -9,7 +9,7 @@
9
9
  * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.
10
10
  */
11
11
 
12
- import { useMemo, useState, type PointerEvent as ReactPointerEvent } from "react";
12
+ import { useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
13
13
 
14
14
  import type { Point } from "./measureGeometry";
15
15
  import {
@@ -26,6 +26,7 @@ import { useStageDrag } from "./stage/StageSurface";
26
26
  import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
27
27
  import { useStageHitLayer, useStageHitTest } from "./stage/useStageHitTest";
28
28
  import { useScreenPx } from "./stage/useScreenPx";
29
+ import { watchTouch } from "./stage/touchWatch";
29
30
  import { imageViewBox, type Rect } from "./stage/view";
30
31
 
31
32
  /** One polyline of a `PolylineSet`, with optional styling. */
@@ -76,6 +77,17 @@ export interface PolylineSetProps {
76
77
  * and to the layers below.
77
78
  */
78
79
  marquee?: boolean | undefined;
80
+ /**
81
+ * Whether the layer takes presses and hover. Defaults to `true` when any of `onItemPress`,
82
+ * `onSelect`, `onHover`, `onHoverChange` or `marquee` is given. When `false` the layer
83
+ * renders no press target at all: a press on a line falls through to whatever is below (a
84
+ * draw tool's `StageSurface`, say), while `useStageHitTest` still finds the lines. Set it
85
+ * `false` while a tool other than selection is active.
86
+ *
87
+ * A touch on an interactive layer is not claimed: the stage still pans and pinches, and the
88
+ * line is selected when the finger lifts after a tap.
89
+ */
90
+ interactive?: boolean | undefined;
79
91
  /** CSS colour of the lines. Defaults to the overlay `feature` role: they are detected lines. */
80
92
  stroke?: string | undefined;
81
93
  /** CSS colour of a selected line. Defaults to the overlay `selection` role. */
@@ -107,6 +119,8 @@ const MAX_VERTEX_DOTS = 5000;
107
119
  * - **Halo.** Every line has a halo, so it holds on any image.
108
120
  * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.
109
121
  * - **Panning.** The hand tool and a held space bar still pan.
122
+ * - **Tools.** Without a handler (or with `interactive={false}`) the layer takes no presses
123
+ * and only answers `useStageHitTest`, so a draw tool's surface below receives them.
110
124
  *
111
125
  * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.
112
126
  */
@@ -120,6 +134,7 @@ export function PolylineSet({
120
134
  onItemPress,
121
135
  onSelect,
122
136
  marquee = false,
137
+ interactive,
123
138
  stroke = overlayRole("feature"),
124
139
  selectionStroke = overlayRole("selection"),
125
140
  hitWidth = 14,
@@ -130,6 +145,12 @@ export function PolylineSet({
130
145
  }: PolylineSetProps) {
131
146
  const stage = useStage();
132
147
  const startDrag = useStageDrag();
148
+ const watchRef = useRef<(() => void) | null>(null);
149
+ // A touch still being watched when the layer goes away is cancelled, not left listening.
150
+ useEffect(() => () => watchRef.current?.(), []);
151
+ const takesPresses =
152
+ interactive ??
153
+ (onItemPress !== undefined || onSelect !== undefined || onHover !== undefined || onHoverChange !== undefined || marquee);
133
154
  const px = useScreenPx();
134
155
  const { hitTestAll } = useStageHitTest();
135
156
 
@@ -230,7 +251,9 @@ export function PolylineSet({
230
251
  };
231
252
 
232
253
  const onLinePointerDown = (event: ReactPointerEvent<SVGPathElement>) => {
233
- if (stage.panMode || event.button !== 0) return;
254
+ const touch = event.pointerType === "touch";
255
+ if (stage.panMode || (!touch && event.button !== 0)) return;
256
+ if (touch && watchRef.current) return; // a second finger: the watch cancels itself, the stage pinches
234
257
  // A band has to be able to start anywhere, and on a frame that is mostly lines "anywhere"
235
258
  // is usually on one. Declining here would hand the press to the stage (which pans), not to
236
259
  // a surface below, because only the topmost element is a press's target.
@@ -244,6 +267,22 @@ export function PolylineSet({
244
267
  // hands it to the point layer.
245
268
  const point = stage.toImage({ x: event.clientX, y: event.clientY });
246
269
  if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) return;
270
+ if (touch && !marquee) {
271
+ // Not claimed: the press may become a pan or a pinch, so the line is selected on the tap.
272
+ const additive = event.metaKey || event.ctrlKey;
273
+ watchRef.current = watchTouch(event, {
274
+ onEnd: (_e, _moved, tap) => {
275
+ watchRef.current = null;
276
+ if (!tap) return;
277
+ onItemPress?.(id, event);
278
+ onSelect?.([id], additive ? "toggle" : "replace");
279
+ },
280
+ onCancel: () => {
281
+ watchRef.current = null;
282
+ },
283
+ });
284
+ return;
285
+ }
247
286
  // Claimed, and selected on the press: a selection that waits for the release feels like
248
287
  // lag on a canvas where every other gesture is immediate.
249
288
  event.stopPropagation();
@@ -261,7 +300,7 @@ export function PolylineSet({
261
300
  data-hovered={hoverId ?? undefined}
262
301
  data-sweeping={band ? "" : undefined}
263
302
  >
264
- {marquee && (
303
+ {takesPresses && marquee && (
265
304
  <rect
266
305
  data-marquee-surface=""
267
306
  x={-0.5}
@@ -308,18 +347,20 @@ export function PolylineSet({
308
347
  {dots && <path data-points="" d={dots} stroke={selectionStroke} strokeWidth={px(3)} />}
309
348
  {/* The one hit target: every line, transparent, wide. Which line it was is the
310
349
  index's answer, not the DOM's. */}
311
- <path
312
- data-hit=""
313
- d={groups.hit}
314
- stroke="transparent"
315
- strokeWidth={px(hitWidth)}
316
- style={{ pointerEvents: "stroke", cursor: stage.panMode ? undefined : marquee ? "crosshair" : "pointer" }}
317
- onPointerDown={onLinePointerDown}
318
- onPointerMove={(event) => {
319
- if (!band) setHover(pickAt(event));
320
- }}
321
- onPointerLeave={() => setHover(null)}
322
- />
350
+ {takesPresses && (
351
+ <path
352
+ data-hit=""
353
+ d={groups.hit}
354
+ stroke="transparent"
355
+ strokeWidth={px(hitWidth)}
356
+ style={{ pointerEvents: "stroke", cursor: stage.panMode ? undefined : marquee ? "crosshair" : "pointer" }}
357
+ onPointerDown={onLinePointerDown}
358
+ onPointerMove={(event) => {
359
+ if (!band && event.pointerType !== "touch") setHover(pickAt(event));
360
+ }}
361
+ onPointerLeave={() => setHover(null)}
362
+ />
363
+ )}
323
364
  </g>
324
365
  {band && (
325
366
  <rect