@vitavision/stage2d 0.14.0 → 0.15.1

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.14.0",
3
+ "version": "0.15.1",
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": {
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.14.0",
49
+ "@vitavision/ui": "^0.14.2",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Iso-lines of a scalar field over the image: the level sets of a distortion map, a residual field,
3
+ * a support boundary.
4
+ *
5
+ * The lines are found by marching squares over the plane's nodes (see `contourPaths`), drawn as one
6
+ * path per style (a halo, the solid levels, the dashed ones), never one element per line, and
7
+ * stroked at screen-constant width. The layer takes no pointer events.
8
+ */
9
+
10
+ import { useMemo } from "react";
11
+
12
+ import type { ValuePlane } from "../api/mapValues";
13
+ import { channelExtent, contourPaths, lineLength, pointsAlong, resolveLevels, type ContourLine } from "./contour";
14
+ import { MAX_LABELS, visibleRect } from "./labelLod";
15
+ import { overlayRole, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
16
+ import { useStage } from "./stage/ImageStage";
17
+ import { useScreenPx } from "./stage/useScreenPx";
18
+ import { imageViewBox, PIXEL_CENTRE, type Rect } from "./stage/view";
19
+
20
+ /** A line is labelled only when it is at least this long on screen, in CSS pixels. */
21
+ const MIN_LABELLED_LENGTH = 90;
22
+ /** A long line is labelled again every this many screen pixels. */
23
+ const LABEL_EVERY = 280;
24
+ /** Dash and gap of a dashed level, in screen pixels. */
25
+ const DASH: readonly [number, number] = [5, 3];
26
+
27
+ /** Props of `ContourLayer`. */
28
+ export interface ContourLayerProps {
29
+ /** The field, as decoded by `decodePlane`. `NaN` is "no data": a line never crosses it. */
30
+ plane: ValuePlane;
31
+ /** Which channel of the plane. Defaults to the first. */
32
+ channel?: number | undefined;
33
+ /**
34
+ * The levels to draw: a list of values, or `{ step, origin? }` for every multiple of `step`
35
+ * (from `origin`, default 0) inside the channel's finite range. A step that would give more than
36
+ * 64 levels is widened by whole multiples. Pass a stable value: a new one recomputes the lines.
37
+ */
38
+ levels: readonly number[] | { step: number; origin?: number | undefined };
39
+ /**
40
+ * Levels drawn dashed: a significance threshold, zero. They are drawn even when `levels` does
41
+ * not contain them, and a level in both is dashed. Compared with a relative tolerance of 1e-9.
42
+ */
43
+ dashedLevels?: readonly number[] | undefined;
44
+ /**
45
+ * Write each line's level on it: `true` for the level to three significant figures, or a
46
+ * function. Labels are horizontal, sit along lines at least 90 screen pixels long (again every
47
+ * 280), only inside the viewport, and at most 200 at a time.
48
+ */
49
+ labels?: boolean | ((level: number) => string) | undefined;
50
+ /**
51
+ * Where the plane is placed, in image coordinates, as for `HeatmapLayer`: the top-left edge of
52
+ * its first pixel's footprint and the extent it is stretched over. Defaults to the whole image,
53
+ * so a plane of any resolution lines up with a `HeatmapLayer` of the same plane.
54
+ */
55
+ rect?: Rect | undefined;
56
+ /** The overlay role of the lines. Defaults to `"structure"`. */
57
+ role?: OverlayRole | undefined;
58
+ /** One CSS colour for the lines instead of the role's (`#hex` or `var(--x)`, used as given). */
59
+ color?: string | undefined;
60
+ /** Draw the dark band under lines and labels. On by default. */
61
+ halo?: boolean | undefined;
62
+ /** Draw it. Defaults to `true`; while `false` nothing is computed. */
63
+ visible?: boolean | undefined;
64
+ /** The layer's accessible name. Defaults to "Contours". */
65
+ label?: string | undefined;
66
+ }
67
+
68
+ const defaultFormat = (level: number) => String(Number(level.toPrecision(3)));
69
+
70
+ const sameLevel = (a: number, b: number) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
71
+
72
+ /**
73
+ * Contour lines inside an `ImageStage`.
74
+ *
75
+ * - **Lines**: marching squares per level over the plane's nodes (pixel centres), linear along
76
+ * edges; a saddle is resolved by the mean of its four corners. They are computed once per
77
+ * change of `plane`, `channel` and `levels`, not on pan or zoom.
78
+ * - **No data**: a cell touching a `NaN` node has no line, so a line stops at a hole.
79
+ * - **Styles**: solid levels in one path, dashed ones in another, each over a halo.
80
+ * - **Labels**: optional, by zoom (see `labels`).
81
+ * - **Input**: none. The layer is decorative; the numbers are read from the plane (`valueAt`),
82
+ * and a legend or `labels` carry the levels as text.
83
+ *
84
+ * The SVG carries `data-count` (lines) and `data-levels` (the levels drawn).
85
+ */
86
+ export function ContourLayer({
87
+ plane,
88
+ channel = 0,
89
+ levels,
90
+ dashedLevels,
91
+ labels = false,
92
+ rect,
93
+ role = "structure",
94
+ color,
95
+ halo = true,
96
+ visible = true,
97
+ label = "Contours",
98
+ }: ContourLayerProps) {
99
+ const stage = useStage();
100
+ const px = useScreenPx();
101
+ const unit = px(1);
102
+
103
+ // Stable keys for inputs that are often written inline.
104
+ const levelsKey = Array.isArray(levels)
105
+ ? `l:${levels.join(",")}`
106
+ : `s:${(levels as { step: number }).step}:${(levels as { origin?: number }).origin ?? 0}`;
107
+ const dashedKey = (dashedLevels ?? []).join(",");
108
+
109
+ const drawn = useMemo(() => {
110
+ if (!visible) return { lines: [] as ContourLine[], levels: [] as number[], dashed: [] as number[] };
111
+ const extent = Array.isArray(levels) ? null : channelExtent(plane, channel);
112
+ const base = Array.isArray(levels) ? resolveLevels(levels, 0, 0) : extent ? resolveLevels(levels, extent[0], extent[1]) : [];
113
+ const dashed = (dashedLevels ?? []).filter(Number.isFinite);
114
+ const all = [...base];
115
+ for (const level of dashed) if (!all.some((l) => sameLevel(l, level))) all.push(level);
116
+ all.sort((a, b) => a - b);
117
+ return { lines: contourPaths(plane, channel, all), levels: all, dashed };
118
+ // The keys stand for `levels` and `dashedLevels`, which are often new arrays each render.
119
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
120
+ }, [visible, plane, channel, levelsKey, dashedKey]);
121
+
122
+ const box = rect ?? { x: -PIXEL_CENTRE, y: -PIXEL_CENTRE, width: stage.image.width, height: stage.image.height };
123
+ const sx = plane.width > 0 ? box.width / plane.width : 1;
124
+ const sy = plane.height > 0 ? box.height / plane.height : 1;
125
+
126
+ const paths = useMemo(() => {
127
+ let solid = "";
128
+ let dashed = "";
129
+ for (const line of drawn.lines) {
130
+ let d = "";
131
+ const p = line.points;
132
+ for (let k = 0; k < p.length; k += 2) {
133
+ d += `${k === 0 ? "M" : "L"}${(box.x + (p[k]! + 0.5) * sx).toFixed(2)} ${(box.y + (p[k + 1]! + 0.5) * sy).toFixed(2)}`;
134
+ }
135
+ if (line.closed) d += "Z";
136
+ if (drawn.dashed.some((level) => sameLevel(level, line.level))) dashed += d;
137
+ else solid += d;
138
+ }
139
+ return { solid, dashed };
140
+ }, [drawn, box.x, box.y, sx, sy]);
141
+
142
+ const format = typeof labels === "function" ? labels : defaultFormat;
143
+ const view = visibleRect(stage.view, stage.box);
144
+ const labelled = useMemo(() => {
145
+ if (labels === false) return [];
146
+ const out: { x: number; y: number; text: string }[] = [];
147
+ for (const line of drawn.lines) {
148
+ // Length on screen: nodes -> image (by the plane's pixel size) -> screen (by 1 / unit).
149
+ const screen = (lineLength(line) * Math.hypot(sx, sy)) / Math.SQRT2 / unit;
150
+ if (screen < MIN_LABELLED_LENGTH) continue;
151
+ const count = Math.max(1, Math.floor(screen / LABEL_EVERY));
152
+ for (const [x, y] of pointsAlong(line, count)) {
153
+ const ix = box.x + (x + 0.5) * sx;
154
+ const iy = box.y + (y + 0.5) * sy;
155
+ if (view && (ix < view.x || ix > view.x + view.width || iy < view.y || iy > view.y + view.height)) continue;
156
+ out.push({ x: ix, y: iy, text: format(line.level) });
157
+ if (out.length >= MAX_LABELS) return out;
158
+ }
159
+ }
160
+ return out;
161
+ // `format` is the caller's function; a new one relabels.
162
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
163
+ }, [labels, drawn, box.x, box.y, sx, sy, unit, view?.x, view?.y, view?.width, view?.height]);
164
+
165
+ if (!visible) return null;
166
+ const tone = color ?? overlayRole(role);
167
+ const HALO = overlayRole("halo");
168
+ const width = px(OVERLAY_STATE_WIDTH.default);
169
+ const dash = `${px(DASH[0])} ${px(DASH[1])}`;
170
+ const levelsText = drawn.levels.slice(0, 6).map(defaultFormat).join(", ") + (drawn.levels.length > 6 ? ", …" : "");
171
+
172
+ return (
173
+ <svg
174
+ viewBox={imageViewBox(stage.image)}
175
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
176
+ role="img"
177
+ aria-label={`${label}: ${drawn.lines.length} ${drawn.lines.length === 1 ? "line" : "lines"}${levelsText ? ` at ${levelsText}` : ""}`}
178
+ data-count={drawn.lines.length}
179
+ data-levels={drawn.levels.join(",")}
180
+ >
181
+ <g fill="none" strokeLinecap="round" strokeLinejoin="round">
182
+ {halo && paths.solid !== "" && <path data-halo="" d={paths.solid} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}
183
+ {halo && paths.dashed !== "" && <path data-halo="" d={paths.dashed} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}
184
+ {paths.solid !== "" && <path data-contours="solid" d={paths.solid} stroke={tone} strokeWidth={width} />}
185
+ {paths.dashed !== "" && (
186
+ <path data-contours="dashed" d={paths.dashed} stroke={tone} strokeWidth={width} strokeDasharray={dash} strokeLinecap="butt" />
187
+ )}
188
+ </g>
189
+ {labelled.length > 0 && (
190
+ <g
191
+ data-labels=""
192
+ fontSize={px(11)}
193
+ className="font-mono"
194
+ stroke={HALO}
195
+ strokeWidth={px(3)}
196
+ paintOrder="stroke"
197
+ strokeLinejoin="round"
198
+ fill={overlayRole("label")}
199
+ textAnchor="middle"
200
+ dominantBaseline="central"
201
+ >
202
+ {labelled.map((entry) => (
203
+ <text key={`${entry.x},${entry.y},${entry.text}`} x={entry.x} y={entry.y}>
204
+ {entry.text}
205
+ </text>
206
+ ))}
207
+ </g>
208
+ )}
209
+ </svg>
210
+ );
211
+ }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Many vectors over the image: a displacement, a flow, a gradient, a residual direction.
3
+ *
4
+ * Drawn as a handful of batched paths (one halo, then one per colour step), never one element per
5
+ * vector; the pointer is resolved through the stage's hit registry from a spatial index over the
6
+ * anchors, never by the DOM; arrowheads and strokes are sized in screen pixels. A field of 10,000
7
+ * vectors is a dozen DOM nodes.
8
+ */
9
+
10
+ import { useMemo, useState } from "react";
11
+
12
+ import type { Colormap, ValueRange } from "./heatmapRaster";
13
+ import { visibleRect } from "./labelLod";
14
+ import { overlayRole, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
15
+ import { buildPointIndex, nearestPoint, type PointId } 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
+ import {
23
+ arrowPath,
24
+ colorBin,
25
+ imagePerUnit,
26
+ magnitudePercentile,
27
+ vectorMagnitudes,
28
+ VECTOR_COLOR_BINS,
29
+ type ArrowStyle,
30
+ type VectorScale,
31
+ } from "./vectorGeometry";
32
+
33
+ /** The arrow's shape, in screen pixels. */
34
+ const ARROW: ArrowStyle = { head: 6, headWidth: 0.7, minLength: 1 };
35
+ /** Past this many vectors, paths are generated for the visible part only. */
36
+ const CULL_ABOVE = 3000;
37
+ /** The reference vector of the default scale: the 95th percentile spans this many screen pixels. */
38
+ const DEFAULT_SCALE: VectorScale = { length: 28, percentile: 0.95 };
39
+
40
+ /** Props of `VectorField`. */
41
+ export interface VectorFieldProps {
42
+ /** The anchors, flat `[x0, y0, x1, y1, …]` in image coordinates. A non-finite anchor is skipped. */
43
+ anchors: ArrayLike<number>;
44
+ /**
45
+ * The vectors, flat `[dx0, dy0, dx1, dy1, …]` in data units, one per anchor. A non-finite
46
+ * component, or a missing entry, skips the vector.
47
+ */
48
+ vectors: ArrayLike<number>;
49
+ /**
50
+ * How data units become image pixels: a number is image pixels per data unit and zooms with
51
+ * the image; `{ length, percentile }` makes the `percentile` vector (default `1`, the longest)
52
+ * span `length` screen pixels at every zoom. Defaults to the 95th-percentile vector at 28 screen
53
+ * pixels, so a few outliers do not shrink the rest to nothing.
54
+ */
55
+ scale?: VectorScale | undefined;
56
+ /**
57
+ * One CSS colour for every arrow (`#hex`, `var(--x)`; used as given). Ignored with `colormap`.
58
+ * Defaults to the `role`'s colour.
59
+ */
60
+ color?: string | undefined;
61
+ /** The overlay role the arrows are painted in without a `color`. Defaults to `"feature"`. */
62
+ role?: OverlayRole | undefined;
63
+ /**
64
+ * Colour each arrow by its magnitude through this map: a position in `[0, 1]` to `[r, g, b]`
65
+ * (the maps of `@vitavision/charts` fit, as for `HeatmapLayer`). Pass a stable function.
66
+ * Magnitudes are quantised into 24 steps, one path each.
67
+ */
68
+ colormap?: Colormap | undefined;
69
+ /** The magnitudes mapped onto `colormap`. Defaults to `0` to the longest vector. */
70
+ range?: ValueRange | undefined;
71
+ /** Ids by vector index. Defaults to the index. */
72
+ ids?: ArrayLike<PointId> | undefined;
73
+ /** The hovered id, when the app controls hover. */
74
+ hoveredId?: PointId | null | undefined;
75
+ /**
76
+ * Called when the vector under the pointer changes; `null` when it leaves every vector. A
77
+ * vector is picked at its anchor. Not called while `pickable` is off.
78
+ */
79
+ onHoverChange?: ((id: PointId | null) => void) | undefined;
80
+ /**
81
+ * A press landed on a vector's anchor. Setting it makes the layer claim presses there, so the
82
+ * stage does not pan from them.
83
+ */
84
+ onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | undefined;
85
+ /** Draw the dark band under every arrow. On by default; off for a fast, flat layer. */
86
+ halo?: boolean | undefined;
87
+ /** Whether the layer takes part in the stage's hit-test. On by default. */
88
+ pickable?: boolean | 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.point`. */
92
+ priority?: number | undefined;
93
+ /** The layer's accessible name. Defaults to "Vectors". */
94
+ label?: string | undefined;
95
+ }
96
+
97
+ /**
98
+ * The reference vector of a scale and the scale it gives, shared by the layer and its key.
99
+ *
100
+ * @param vectors - Flat `[dx0, dy0, …]`.
101
+ * @param scale - See `VectorScale`.
102
+ * @returns The reference magnitude in data units, and image pixels per data unit.
103
+ */
104
+ export function useVectorScale(vectors: ArrayLike<number>, scale: VectorScale = DEFAULT_SCALE): { reference: number; perUnit: number } {
105
+ const unit = useScreenPx()(1);
106
+ const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
107
+ const percentile = typeof scale === "number" ? 1 : (scale.percentile ?? 1);
108
+ const reference = useMemo(() => magnitudePercentile(mags, percentile), [mags, percentile]);
109
+ return { reference, perUnit: imagePerUnit(scale, reference, unit) };
110
+ }
111
+
112
+ /** `rgb(r g b)` of a map's colour, channels rounded and clamped. */
113
+ function css(colormap: Colormap, t: number): string {
114
+ const [r, g, b] = colormap(t);
115
+ const c = (v: number) => Math.min(255, Math.max(0, Math.round(v)));
116
+ return `rgb(${c(r)} ${c(g)} ${c(b)})`;
117
+ }
118
+
119
+ /**
120
+ * A field of arrows inside an `ImageStage`.
121
+ *
122
+ * - **Scale**: see `VectorScale`. The same `vectors` and `scale` given to `VectorFieldKey` draw a
123
+ * reference length at exactly this scale.
124
+ * - **Colour**: one tone (`color` or `role`), or by magnitude through `colormap` over `range`.
125
+ * - **Absent data**: an anchor or vector with a non-finite number, or shorter than one screen
126
+ * pixel, is not drawn.
127
+ * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here, and
128
+ * `useStageHitTest` for an app that arbitrates between layers. The hovered arrow is redrawn
129
+ * at 2.5 screen px in the selection colour.
130
+ *
131
+ * Arrowheads and strokes are screen-constant; their paths are regenerated when the zoom changes,
132
+ * and past 3,000 vectors only those near the viewport are generated. The SVG carries
133
+ * `data-hovered` (the hovered id) and `data-count` (the vectors drawn).
134
+ */
135
+ export function VectorField({
136
+ anchors,
137
+ vectors,
138
+ scale = DEFAULT_SCALE,
139
+ color,
140
+ role = "feature",
141
+ colormap,
142
+ range,
143
+ ids,
144
+ hoveredId,
145
+ onHoverChange,
146
+ onItemPress,
147
+ halo = true,
148
+ pickable = true,
149
+ layerId,
150
+ priority = STAGE_HIT_PRIORITY.point,
151
+ label = "Vectors",
152
+ }: VectorFieldProps) {
153
+ const stage = useStage();
154
+ const px = useScreenPx();
155
+ const unit = px(1);
156
+ const count = Math.min(Math.floor(anchors.length / 2), Math.floor(vectors.length / 2));
157
+
158
+ const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
159
+ const { perUnit } = useVectorScale(vectors, scale);
160
+ const index = useMemo(() => buildPointIndex(anchors, { ids }), [anchors, ids]);
161
+
162
+ const [ownHover, setOwnHover] = useState<PointId | null>(null);
163
+ const hoverId = hoveredId !== undefined ? hoveredId : ownHover;
164
+
165
+ useStageHitLayer({
166
+ layerId,
167
+ priority,
168
+ enabled: pickable,
169
+ pick: (point, radius) => {
170
+ const hit = nearestPoint(index, point.x, point.y, radius);
171
+ return hit && hit.index < count && Number.isFinite(mags[hit.index]) ? { id: hit.id, dist: hit.dist } : null;
172
+ },
173
+ onHover: (id) => {
174
+ setOwnHover(id);
175
+ onHoverChange?.(id);
176
+ },
177
+ onPress: onItemPress,
178
+ });
179
+
180
+ const colourRange = useMemo(() => {
181
+ if (!colormap) return null;
182
+ if (range) return range;
183
+ let high = 0;
184
+ for (let i = 0; i < count; i++) if (mags[i]! > high) high = mags[i]!;
185
+ return { low: 0, high };
186
+ }, [colormap, range, mags, count]);
187
+
188
+ const cull = cullWindow(stage.view, stage.box, count, mags, perUnit);
189
+ const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
190
+
191
+ const built = useMemo(() => {
192
+ const bins = colormap && colourRange ? VECTOR_COLOR_BINS : 1;
193
+ const parts: string[] = new Array<string>(bins).fill("");
194
+ let drawn = 0;
195
+ for (let i = 0; i < count; i++) {
196
+ const m = mags[i]!;
197
+ const x = anchors[2 * i]!;
198
+ const y = anchors[2 * i + 1]!;
199
+ if (!Number.isFinite(m) || !Number.isFinite(x) || !Number.isFinite(y)) continue;
200
+ if (cull && (x < cull.x || x > cull.x + cull.width || y < cull.y || y > cull.y + cull.height)) continue;
201
+ const d = arrowPath(x, y, vectors[2 * i]! * perUnit, vectors[2 * i + 1]! * perUnit, unit, ARROW);
202
+ if (d === "") continue;
203
+ const bin = colormap && colourRange ? colorBin(m, colourRange.low, colourRange.high) : 0;
204
+ parts[bin] += d;
205
+ drawn++;
206
+ }
207
+ const batches = parts.flatMap((d, bin) => (d === "" ? [] : [{ bin, d }]));
208
+ return { parts, batches, drawn };
209
+ // `cullKey` stands for `cull`, which is a new object each render.
210
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
211
+ }, [anchors, vectors, mags, count, perUnit, unit, colormap, colourRange, cullKey]);
212
+
213
+ const all = useMemo(() => built.parts.join(""), [built]);
214
+ const hoverIndex = hoverId === null ? -1 : findIndex(index, hoverId, count);
215
+ const hoverPath =
216
+ hoverIndex >= 0 && Number.isFinite(mags[hoverIndex])
217
+ ? arrowPath(
218
+ anchors[2 * hoverIndex]!,
219
+ anchors[2 * hoverIndex + 1]!,
220
+ vectors[2 * hoverIndex]! * perUnit,
221
+ vectors[2 * hoverIndex + 1]! * perUnit,
222
+ unit,
223
+ ARROW,
224
+ )
225
+ : "";
226
+
227
+ const tone = color ?? overlayRole(role);
228
+ const width = px(OVERLAY_STATE_WIDTH.default);
229
+ const hoverWidth = px(OVERLAY_STATE_WIDTH.selected);
230
+ const HALO = overlayRole("halo");
231
+
232
+ return (
233
+ <svg
234
+ viewBox={imageViewBox(stage.image)}
235
+ className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
236
+ role="img"
237
+ aria-label={`${label}: ${built.drawn} ${built.drawn === 1 ? "vector" : "vectors"}`}
238
+ data-hovered={hoverId ?? undefined}
239
+ data-count={built.drawn}
240
+ >
241
+ <g fill="none" strokeLinecap="butt" strokeLinejoin="round">
242
+ {halo && all !== "" && <path data-halo="" d={all} stroke={HALO} fill={HALO} strokeWidth={width + px(2)} opacity={0.6} />}
243
+ {built.batches.map(({ bin, d }) => (
244
+ <path
245
+ key={bin}
246
+ data-batch={bin}
247
+ d={d}
248
+ stroke={colormap ? css(colormap, (bin + 0.5) / VECTOR_COLOR_BINS) : tone}
249
+ fill={colormap ? css(colormap, (bin + 0.5) / VECTOR_COLOR_BINS) : tone}
250
+ strokeWidth={width}
251
+ />
252
+ ))}
253
+ {hoverPath !== "" && (
254
+ <>
255
+ {halo && <path d={hoverPath} stroke={HALO} fill={HALO} strokeWidth={hoverWidth + px(2)} />}
256
+ <path
257
+ data-hovered-vector=""
258
+ d={hoverPath}
259
+ stroke={overlayRole("selection")}
260
+ fill={overlayRole("selection")}
261
+ strokeWidth={hoverWidth}
262
+ />
263
+ </>
264
+ )}
265
+ </g>
266
+ </svg>
267
+ );
268
+ }
269
+
270
+ /** The index of the vector with id `id`, or `-1`. */
271
+ function findIndex(index: { ids: ArrayLike<PointId> | null }, id: PointId, count: number): number {
272
+ if (index.ids === null) return typeof id === "number" && id >= 0 && id < count && Number.isInteger(id) ? id : -1;
273
+ for (let i = 0; i < Math.min(count, index.ids.length); i++) if (index.ids[i] === id) return i;
274
+ return -1;
275
+ }
276
+
277
+ /**
278
+ * The window paths are generated for: the viewport plus the longest arrow on every side, snapped
279
+ * outward to half-viewport steps so panning rebuilds it once per half screen. `null` for a small
280
+ * field, or an unmeasured stage.
281
+ */
282
+ function cullWindow(
283
+ view: { scale: number; tx: number; ty: number },
284
+ box: { width: number; height: number },
285
+ count: number,
286
+ mags: ArrayLike<number>,
287
+ perUnit: number,
288
+ ): Rect | null {
289
+ if (count <= CULL_ABOVE) return null;
290
+ const visible = visibleRect(view, box);
291
+ if (visible === null) return null;
292
+ let longest = 0;
293
+ for (let i = 0; i < count; i++) if (mags[i]! > longest) longest = mags[i]!;
294
+ const sx = visible.width / 2;
295
+ const sy = visible.height / 2;
296
+ const reach = Math.min(longest * perUnit, visible.width, visible.height);
297
+ const left = Math.floor((visible.x - sx - reach) / sx) * sx;
298
+ const top = Math.floor((visible.y - sy - reach) / sy) * sy;
299
+ const right = Math.ceil((visible.x + visible.width + sx + reach) / sx) * sx;
300
+ const bottom = Math.ceil((visible.y + visible.height + sy + reach) / sy) * sy;
301
+ return { x: left, y: top, width: right - left, height: bottom - top };
302
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The reference length of a `VectorField`: an arrow of a round length with its value, so a
3
+ * reader can turn arrow lengths back into data units.
4
+ */
5
+
6
+ import { cn } from "@vitavision/ui";
7
+
8
+ import { useStage } from "./stage/ImageStage";
9
+ import { arrowPath, niceLength, type ArrowStyle, type VectorScale } from "./vectorGeometry";
10
+ import { useVectorScale } from "./VectorField";
11
+
12
+ /** Props of `VectorFieldKey`. */
13
+ export interface VectorFieldKeyProps {
14
+ /** The field's `vectors`: the scale of an automatic `scale` depends on them. */
15
+ vectors: ArrayLike<number>;
16
+ /** The field's `scale`, so the key is drawn at exactly the field's scale. Defaults as `VectorField` does. */
17
+ scale?: VectorScale | undefined;
18
+ /**
19
+ * The length the key shows, in data units. Defaults to the largest 1, 2 or 5 times a power of
20
+ * ten that is at most the field's reference vector.
21
+ */
22
+ length?: number | undefined;
23
+ /** The data unit, written after the value (`px`, `m/s`). */
24
+ unit?: string | undefined;
25
+ /** Formats the value. Defaults to at most 3 significant figures, without trailing zeros. */
26
+ format?: ((value: number) => string) | undefined;
27
+ /**
28
+ * Draw without its own dark chip, for a place that has one already: the `extra` of a
29
+ * `StageReadout`. Off by default.
30
+ */
31
+ bare?: boolean | undefined;
32
+ /** Merged onto the key with `cn`. */
33
+ className?: string | undefined;
34
+ }
35
+
36
+ const KEY_ARROW: ArrowStyle = { head: 5, headWidth: 0.7, minLength: 1 };
37
+ /** The key is not drawn wider than this, in screen pixels. */
38
+ const MAX_WIDTH = 160;
39
+
40
+ /**
41
+ * An arrow of a known length and its value ("0.1 px"). Pass it as `ImageStage`'s `readout`, or
42
+ * as the `extra` of a `StageReadout` with `bare`; it reads the stage's zoom through `useStage`, so it stays
43
+ * true as the view changes, and draws nothing while the field has no scale or the arrow would
44
+ * be wider than 160 screen pixels.
45
+ *
46
+ * On its own it is drawn in the readout's light-on-dark chip, so it sits on the image like the readout does.
47
+ */
48
+ export function VectorFieldKey({
49
+ vectors,
50
+ scale,
51
+ length,
52
+ unit,
53
+ format = (value) => String(Number(value.toPrecision(3))),
54
+ bare = false,
55
+ className,
56
+ }: VectorFieldKeyProps) {
57
+ const stage = useStage();
58
+ const { reference, perUnit } = useVectorScale(vectors, scale);
59
+ const value = length ?? niceLength(reference);
60
+ const width = value * perUnit * stage.view.scale;
61
+ if (!(value > 0) || !(width >= 1) || width > MAX_WIDTH) return null;
62
+ const pad = 1;
63
+ return (
64
+ <span
65
+ className={cn(
66
+ "inline-flex items-center gap-1.5 align-middle font-mono text-[10px] tabular-nums",
67
+ !bare && "rounded-control bg-black/60 px-1.5 py-0.5 text-white",
68
+ className,
69
+ )}
70
+ data-vector-key=""
71
+ title={`Arrow length: ${unit ? `${format(value)} ${unit}` : format(value)}`}
72
+ >
73
+ <svg
74
+ aria-hidden
75
+ width={width + 2 * pad}
76
+ height={10}
77
+ viewBox={`${-pad} -5 ${width + 2 * pad} 10`}
78
+ className="shrink-0 overflow-visible"
79
+ >
80
+ <path
81
+ d={arrowPath(0, 0, width, 0, 1, KEY_ARROW)}
82
+ fill="currentColor"
83
+ stroke="currentColor"
84
+ strokeWidth={1.5}
85
+ strokeLinejoin="round"
86
+ />
87
+ </svg>
88
+ <span>{unit ? `${format(value)} ${unit}` : format(value)}</span>
89
+ </span>
90
+ );
91
+ }