@vitavision/stage2d 0.9.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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.
3
+ *
4
+ * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an
5
+ * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage
6
+ * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel
7
+ * map costs one element. It takes no pointer events; to read the numbers under the pointer, use
8
+ * `valueAt` on the plane.
9
+ */
10
+
11
+ import { useEffect, useRef, useState } from "react";
12
+
13
+ import { cn } from "@vitavision/ui";
14
+ import type { ValuePlane } from "../api/mapValues";
15
+ import { rasterizePlane, type Colormap, type ValueRange } from "./heatmapRaster";
16
+ import { useStage } from "./stage/ImageStage";
17
+ import { PIXEL_CENTRE, type Rect } from "./stage/view";
18
+
19
+ /** What every `HeatmapLayer` takes. */
20
+ export interface HeatmapLayerBaseProps {
21
+ /** How opaque the heatmap is, 0 to 1. Defaults to `1`. */
22
+ opacity?: number | undefined;
23
+ /** Draw it. Defaults to `true`. While `false` nothing is rasterised. */
24
+ visible?: boolean | undefined;
25
+ /**
26
+ * Where the raster is placed, in image coordinates: `x` and `y` the top-left edge of its
27
+ * first pixel's footprint (`-0.5, -0.5` is the image's own top-left corner), `width` and `height`
28
+ * the extent it is stretched over. Defaults to the whole image, so a raster of any
29
+ * resolution covers it 1:1 in position.
30
+ */
31
+ rect?: Rect | undefined;
32
+ /** The zoom (CSS pixels per heatmap pixel) from which heatmap pixels are drawn as blocks. Defaults to 4. */
33
+ pixelatedAbove?: number | undefined;
34
+ /** A description for assistive technology. Defaults to `""`: decorative, as the legend carries the meaning. */
35
+ alt?: string | undefined;
36
+ /** Called once the raster is on screen (and again for each new one). */
37
+ onReady?: (() => void) | undefined;
38
+ /** Called when the raster could not be made: a canvas that could not be allocated, or an `rgba` buffer too short for its size. */
39
+ onError?: (() => void) | undefined;
40
+ /** Merged onto the image with `cn`. */
41
+ className?: string | undefined;
42
+ }
43
+
44
+ /** A heatmap from pixels that are already coloured. */
45
+ export interface HeatmapRgbaProps extends HeatmapLayerBaseProps {
46
+ /** Row-major RGBA, `width · height · 4` bytes. A `Uint8Array` is read in place, not copied. */
47
+ rgba: Uint8ClampedArray | Uint8Array;
48
+ /** The raster's width in pixels. */
49
+ width: number;
50
+ /** The raster's height in pixels. */
51
+ height: number;
52
+ /** Not used with `rgba`. */
53
+ plane?: undefined;
54
+ /** Not used with `rgba`. */
55
+ colormap?: undefined;
56
+ /** Not used with `rgba`. */
57
+ range?: undefined;
58
+ /** Not used with `rgba`. */
59
+ channel?: undefined;
60
+ }
61
+
62
+ /** A heatmap from a scalar field and a colour map. */
63
+ export interface HeatmapPlaneProps extends HeatmapLayerBaseProps {
64
+ /** The field, as decoded by `decodePlane`. */
65
+ plane: ValuePlane;
66
+ /**
67
+ * The colour map. `NaN` pixels stay transparent. Pass a stable function: a new one
68
+ * re-rasterises the heatmap. `@vitavision/charts`' `(t) => colormapRgb("viridis", t)` is one.
69
+ */
70
+ colormap: Colormap;
71
+ /** What the map spans. Defaults to the extent of the channel's finite values. */
72
+ range?: ValueRange | undefined;
73
+ /** Which channel of the plane to draw. Defaults to the first. */
74
+ channel?: number | undefined;
75
+ /** Not used with `plane`. */
76
+ rgba?: undefined;
77
+ /** Not used with `plane`. */
78
+ width?: undefined;
79
+ /** Not used with `plane`. */
80
+ height?: undefined;
81
+ }
82
+
83
+ /** Props of `HeatmapLayer`: pre-coloured `rgba` pixels, or a `plane` with a `colormap`. */
84
+ export type HeatmapLayerProps = HeatmapRgbaProps | HeatmapPlaneProps;
85
+
86
+ /** A raster on screen and the object URL it came from. */
87
+ interface Raster {
88
+ url: string;
89
+ width: number;
90
+ height: number;
91
+ }
92
+
93
+ /**
94
+ * A heatmap inside an `ImageStage`: a scalar field coloured through a colour map, or an RGBA
95
+ * buffer, placed over the image (default) or any rectangle of it.
96
+ *
97
+ * - **Rasterised in an effect**, once per change of its data, into an offscreen canvas and an
98
+ * object URL that is revoked when replaced and on unmount. Server rendering draws nothing.
99
+ * - **Pixelated** from 4 CSS pixels per heatmap pixel, like `ImageLayer`, so the cells of a
100
+ * coarse map are not smoothed into a blur.
101
+ * - **Stacking:** it is drawn where it is placed among the stage's children. Before the
102
+ * overlays it sits under them; the image layer goes before it.
103
+ * - **Input:** none. It takes no pointer events, so presses reach the layers above and the stage.
104
+ *
105
+ * The image carries `data-heatmap`, `data-pixelated` while pixelated, and `data-ready`.
106
+ */
107
+ export function HeatmapLayer(props: HeatmapLayerProps) {
108
+ const { opacity = 1, visible = true, rect, pixelatedAbove = 4, alt = "", onReady, onError, className } = props;
109
+ const stage = useStage();
110
+ const [raster, setRaster] = useState<Raster | null>(null);
111
+ const [ready, setReady] = useState(false);
112
+ const urlRef = useRef<string | null>(null);
113
+ const callbacksRef = useRef({ onReady, onError });
114
+ useEffect(() => {
115
+ callbacksRef.current = { onReady, onError };
116
+ });
117
+
118
+ // The inputs that change what is drawn, spelled out so the effect re-runs on exactly those.
119
+ const { rgba, width, height, plane, colormap, channel } = props;
120
+ const rangeLow = props.range?.low;
121
+ const rangeHigh = props.range?.high;
122
+
123
+ useEffect(() => {
124
+ if (!visible) return;
125
+ let cancelled = false;
126
+ const range = rangeLow === undefined || rangeHigh === undefined ? undefined : { low: rangeLow, high: rangeHigh };
127
+ const source = rgba ? wrapRgba(rgba, width, height) : plane && colormap ? colourPlane(plane, colormap, range, channel) : null;
128
+ const canvas = document.createElement("canvas");
129
+ const context = source ? ((canvas.width = source.width), (canvas.height = source.height), canvas.getContext("2d")) : null;
130
+ if (!source || !context) {
131
+ callbacksRef.current.onError?.();
132
+ return;
133
+ }
134
+ const { width: w, height: h } = source;
135
+ context.putImageData(new ImageData(source.pixels, w, h), 0, 0);
136
+ canvas.toBlob((blob) => {
137
+ if (cancelled) return;
138
+ if (!blob) {
139
+ callbacksRef.current.onError?.();
140
+ return;
141
+ }
142
+ const previous = urlRef.current;
143
+ const url = URL.createObjectURL(blob);
144
+ urlRef.current = url;
145
+ setReady(false);
146
+ setRaster({ url, width: w, height: h });
147
+ // The old image is replaced in this commit; the browser has already decoded it.
148
+ if (previous) URL.revokeObjectURL(previous);
149
+ });
150
+ return () => {
151
+ cancelled = true;
152
+ };
153
+ }, [visible, rgba, width, height, plane, colormap, rangeLow, rangeHigh, channel]);
154
+
155
+ useEffect(
156
+ () => () => {
157
+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);
158
+ urlRef.current = null;
159
+ },
160
+ [],
161
+ );
162
+
163
+ if (!visible || raster === null) return null;
164
+ const box = rect ?? { x: -PIXEL_CENTRE, y: -PIXEL_CENTRE, width: stage.image.width, height: stage.image.height };
165
+ const pixelated = (stage.view.scale * box.width) / raster.width >= pixelatedAbove;
166
+ return (
167
+ <img
168
+ src={raster.url}
169
+ alt={alt}
170
+ draggable={false}
171
+ data-heatmap=""
172
+ data-ready={ready ? "" : undefined}
173
+ data-pixelated={pixelated ? "" : undefined}
174
+ onLoad={() => {
175
+ setReady(true);
176
+ callbacksRef.current.onReady?.();
177
+ }}
178
+ className={cn("pointer-events-none absolute max-w-none select-none", className)}
179
+ style={{
180
+ left: box.x + PIXEL_CENTRE,
181
+ top: box.y + PIXEL_CENTRE,
182
+ width: box.width,
183
+ height: box.height,
184
+ opacity,
185
+ pointerEvents: "none",
186
+ imageRendering: pixelated ? "pixelated" : undefined,
187
+ }}
188
+ />
189
+ );
190
+ }
191
+
192
+ /** Pixels to draw, and their size. */
193
+ interface Pixels {
194
+ pixels: Uint8ClampedArray<ArrayBuffer>;
195
+ width: number;
196
+ height: number;
197
+ }
198
+
199
+ /** The first `width · height · 4` bytes of an RGBA buffer, read in place; `null` if it is too short or empty. */
200
+ function wrapRgba(rgba: Uint8ClampedArray | Uint8Array, width: number, height: number): Pixels | null {
201
+ const length = width * height * 4;
202
+ if (!(length > 0) || rgba.length < length) return null;
203
+ return { pixels: new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, length), width, height };
204
+ }
205
+
206
+ /** A plane through a colour map; `null` for an empty plane. */
207
+ function colourPlane(plane: ValuePlane, colormap: Colormap, range: ValueRange | undefined, channel: number | undefined): Pixels | null {
208
+ if (!(plane.width > 0 && plane.height > 0)) return null;
209
+ const pixels = rasterizePlane(plane, colormap, range, channel) as Uint8ClampedArray<ArrayBuffer>;
210
+ return { pixels, width: plane.width, height: plane.height };
211
+ }
@@ -12,7 +12,8 @@ import { useMemo, useState } from "react";
12
12
 
13
13
  import { circlePath, MARKER_SHAPES, type MarkerShape } from "./markerShapes";
14
14
  import { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
15
- import { buildPointIndexFrom, nearestPoint, thinPoints, type PointId, type PointItem } from "./pointIndex";
15
+ import { useLabelIndices, visibleRect } from "./labelLod";
16
+ import { buildPointIndexFrom, nearestPoint, type PointId, type PointItem } from "./pointIndex";
16
17
  import { useStage } from "./stage/ImageStage";
17
18
  import type { StagePointerEvent } from "./stage/hitContext";
18
19
  import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
@@ -31,6 +32,8 @@ export interface PointSetItem extends PointItem {
31
32
  role?: OverlayRole | undefined;
32
33
  /** Its orientation in radians, clockwise from +x; read by `directed`. */
33
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;
34
37
  /** Text drawn beside it, when the zoom leaves room (points at least 24 screen px apart). */
35
38
  label?: string | undefined;
36
39
  }
@@ -77,12 +80,6 @@ export interface PointSetProps {
77
80
  label?: string | undefined;
78
81
  }
79
82
 
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
83
  /** Past this many points, outlines are generated for the visible part only. */
87
84
  const CULL_ABOVE = 3000;
88
85
  /** How much bigger than a marker its selection ring is, in screen pixels. */
@@ -232,30 +229,16 @@ export function PointSet({
232
229
  });
233
230
  return list;
234
231
  }, [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);
232
+ const forced = useMemo(() => {
233
+ const list: number[] = [];
234
+ if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);
235
+ for (const id of selectedSet) {
236
+ const i = positionOf.get(id);
237
+ if (i !== undefined && items[i]!.label) list.push(i);
256
238
  }
257
- return [...shown];
258
- }, [labels, spaced, items, hoverItem, selectedSet, positionOf, stage.view, stage.box]);
239
+ return list;
240
+ }, [hoverItem, selectedSet, positionOf, items]);
241
+ const shownLabels = useLabelIndices({ enabled: labels, xy: index.xy, labelled, forced });
259
242
 
260
243
  const widthOf = (shape: MarkerShape, role: OverlayRole, state: "default" | "hover" | "selected"): number => {
261
244
  const thin = role === "model" || role === "structure";
@@ -318,14 +301,14 @@ export function PointSet({
318
301
  <>
319
302
  {halo && (
320
303
  <path
321
- 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)}
322
305
  stroke={HALO}
323
306
  strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover") + px(2)}
324
307
  />
325
308
  )}
326
309
  <path
327
310
  data-hovered-point=""
328
- 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)}
329
312
  stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}
330
313
  strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? "selected" : "hover")}
331
314
  />
@@ -361,18 +344,12 @@ function batchPath(batch: Batch, items: readonly PointSetItem[], unit: number, c
361
344
  for (const i of batch.indices) {
362
345
  const item = items[i]!;
363
346
  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);
347
+ d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0, item.angle2);
365
348
  }
366
349
  batch.cache = { key, d };
367
350
  return d;
368
351
  }
369
352
 
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
353
  /**
377
354
  * The window outlines are generated for: the viewport plus half a viewport on every side,
378
355
  * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
@@ -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