@vitavision/stage2d 0.15.0 → 0.16.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/dist/index.js CHANGED
@@ -4728,7 +4728,7 @@ function range(from, to) {
4728
4728
  */
4729
4729
  const HALO$8 = overlayRole("halo");
4730
4730
  /** Dash, gap, outline width and vertex dot size, in screen pixels. */
4731
- const DASH = 6;
4731
+ const DASH$1 = 6;
4732
4732
  const GAP = 4;
4733
4733
  const STROKE_PX$2 = 1.5;
4734
4734
  const VERTEX_PX = 6;
@@ -4752,7 +4752,7 @@ function DraftShape({ shape, role = "selection", stroke, halo = true }) {
4752
4752
  const stage = useStage();
4753
4753
  const px = useScreenPx();
4754
4754
  const colour = stroke ?? overlayRole(role);
4755
- const dash = `${px(DASH)} ${px(GAP)}`;
4755
+ const dash = `${px(DASH$1)} ${px(GAP)}`;
4756
4756
  const width = px(STROKE_PX$2);
4757
4757
  const parts = shape ? draftParts(shape, px(1)) : null;
4758
4758
  return /* @__PURE__ */ jsx("svg", {
@@ -5860,10 +5860,10 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
5860
5860
  });
5861
5861
  setHover(null);
5862
5862
  return {
5863
- onMove: (p) => setBand(boxBetween(from, p)),
5863
+ onMove: (p) => setBand(boxBetween$1(from, p)),
5864
5864
  onEnd: (p) => {
5865
5865
  setBand(null);
5866
- onSelect?.(polylinesInRect(index, boxBetween(from, p)), additive ? "add" : "replace");
5866
+ onSelect?.(polylinesInRect(index, boxBetween$1(from, p)), additive ? "add" : "replace");
5867
5867
  },
5868
5868
  onCancel: () => setBand(null)
5869
5869
  };
@@ -6017,7 +6017,7 @@ function PolylineSet({ items, selected, dimmed, hovered, onHover, onHoverChange,
6017
6017
  ]
6018
6018
  });
6019
6019
  }
6020
- function boxBetween(a, b) {
6020
+ function boxBetween$1(a, b) {
6021
6021
  return {
6022
6022
  x: Math.min(a.x, b.x),
6023
6023
  y: Math.min(a.y, b.y),
@@ -6110,7 +6110,7 @@ const MARKER_SHAPES = {
6110
6110
  * plus at most 200 labels.
6111
6111
  */
6112
6112
  /** Past this many points, outlines are generated for the visible part only. */
6113
- const CULL_ABOVE = 3e3;
6113
+ const CULL_ABOVE$1 = 3e3;
6114
6114
  /** How much bigger than a marker its selection ring is, in screen pixels. */
6115
6115
  const RING_GAP = 4;
6116
6116
  const HALO$5 = overlayRole("halo");
@@ -6232,7 +6232,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
6232
6232
  selectedSet,
6233
6233
  isDimmed
6234
6234
  ]);
6235
- const cull = cullWindow(stage.view, stage.box, items.length);
6235
+ const cull = cullWindow$1(stage.view, stage.box, items.length);
6236
6236
  const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
6237
6237
  const build = (batches) => batches.map((batch) => ({
6238
6238
  batch,
@@ -6383,8 +6383,8 @@ function batchPath$1(batch, items, unit, cull, cullKey) {
6383
6383
  * The window outlines are generated for: the viewport plus half a viewport on every side,
6384
6384
  * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
6385
6385
  */
6386
- function cullWindow(view, box, count) {
6387
- if (count <= CULL_ABOVE) return null;
6386
+ function cullWindow$1(view, box, count) {
6387
+ if (count <= CULL_ABOVE$1) return null;
6388
6388
  const visible = visibleRect(view, box);
6389
6389
  if (visible === null) return null;
6390
6390
  const sx = visible.width / 2;
@@ -6401,6 +6401,160 @@ function cullWindow(view, box, count) {
6401
6401
  };
6402
6402
  }
6403
6403
  //#endregion
6404
+ //#region src/components/PointMarquee.tsx
6405
+ /**
6406
+ * A rectangular marquee over a point set: hold a modifier, drag, and the ids of the points
6407
+ * inside the rectangle are reported.
6408
+ *
6409
+ * Opt-in and inert without its modifier: a press without it is left to the stage (which pans),
6410
+ * the wheel still zooms, and the layers below keep their own targets. The rectangle is drawn
6411
+ * with `MarqueeRect` while the pointer moves.
6412
+ */
6413
+ /** Whether a pointer or key event holds the modifier. */
6414
+ function holds(modifier, event) {
6415
+ if (modifier === "shift") return event.shiftKey;
6416
+ if (modifier === "alt") return event.altKey;
6417
+ return event.metaKey || event.ctrlKey;
6418
+ }
6419
+ function boxBetween(a, b) {
6420
+ return {
6421
+ x: Math.min(a.x, b.x),
6422
+ y: Math.min(a.y, b.y),
6423
+ width: Math.abs(b.x - a.x),
6424
+ height: Math.abs(b.y - a.y)
6425
+ };
6426
+ }
6427
+ /**
6428
+ * A modifier-drag rectangle that selects points, inside an `ImageStage`.
6429
+ *
6430
+ * - **Opt-in**: a press without the modifier is left alone, so pan, wheel zoom and the layers
6431
+ * below behave as without it. While the modifier is held the layer takes presses over the
6432
+ * whole image and the cursor is a crosshair.
6433
+ * - **Reports ids**, by the points' centres, through a spatial index: thousands of points cost
6434
+ * microseconds.
6435
+ * - **Escape** abandons a marquee in flight; releasing the pointer without moving does nothing.
6436
+ * - **Touch** has no modifier: a finger pans as usual.
6437
+ *
6438
+ * It draws only the rectangle (`data-marquee`); selection feedback is the point layer's, fed by
6439
+ * the ids the app keeps. The layer carries `data-armed` while the modifier is held and
6440
+ * `data-sweeping` while a rectangle is being dragged.
6441
+ */
6442
+ function PointMarquee({ items, onSelect, onBandChange, onCancel, modifier = "shift", surface = true, enabled = true, stroke, ref }) {
6443
+ const stage = useStage();
6444
+ const startDrag = useStageDrag();
6445
+ const index = useMemo(() => buildPointIndexFrom(items), [items]);
6446
+ const [band, setBand] = useState(null);
6447
+ const [held, setHeld] = useState(false);
6448
+ const armed = enabled && surface && held;
6449
+ const abandoned = useRef(false);
6450
+ const live = useRef({
6451
+ onSelect,
6452
+ onBandChange,
6453
+ onCancel
6454
+ });
6455
+ useEffect(() => {
6456
+ live.current = {
6457
+ onSelect,
6458
+ onBandChange,
6459
+ onCancel
6460
+ };
6461
+ });
6462
+ const publish = (next) => {
6463
+ setBand(next);
6464
+ live.current.onBandChange?.(next);
6465
+ };
6466
+ useEffect(() => {
6467
+ if (!enabled || !surface) return;
6468
+ const sync = (event) => setHeld(holds(modifier, event));
6469
+ const off = () => setHeld(false);
6470
+ window.addEventListener("keydown", sync);
6471
+ window.addEventListener("keyup", sync);
6472
+ window.addEventListener("pointermove", sync);
6473
+ window.addEventListener("blur", off);
6474
+ return () => {
6475
+ window.removeEventListener("keydown", sync);
6476
+ window.removeEventListener("keyup", sync);
6477
+ window.removeEventListener("pointermove", sync);
6478
+ window.removeEventListener("blur", off);
6479
+ };
6480
+ }, [
6481
+ enabled,
6482
+ surface,
6483
+ modifier
6484
+ ]);
6485
+ const sweeping = band !== null;
6486
+ useEffect(() => {
6487
+ if (!sweeping) return;
6488
+ const onKey = (event) => {
6489
+ if (event.key !== "Escape" || abandoned.current) return;
6490
+ abandoned.current = true;
6491
+ publish(null);
6492
+ live.current.onCancel?.();
6493
+ };
6494
+ window.addEventListener("keydown", onKey);
6495
+ return () => window.removeEventListener("keydown", onKey);
6496
+ }, [sweeping]);
6497
+ const dragFrom = (from, additive, claimsTouch) => {
6498
+ abandoned.current = false;
6499
+ publish({
6500
+ x: from.x,
6501
+ y: from.y,
6502
+ width: 0,
6503
+ height: 0
6504
+ });
6505
+ return {
6506
+ claimsTouch,
6507
+ onMove: (p) => {
6508
+ if (!abandoned.current) publish(boxBetween(from, p));
6509
+ },
6510
+ onEnd: (p, _event, moved) => {
6511
+ if (abandoned.current) return;
6512
+ publish(null);
6513
+ if (moved) live.current.onSelect(pointsInRect(index, boxBetween(from, p)).map((i) => idAt(i)), additive ? "add" : "replace");
6514
+ },
6515
+ onCancel: () => {
6516
+ if (abandoned.current) return;
6517
+ abandoned.current = true;
6518
+ publish(null);
6519
+ live.current.onCancel?.();
6520
+ }
6521
+ };
6522
+ };
6523
+ const idAt = (i) => index.ids ? index.ids[i] : i;
6524
+ const additiveOf = (event) => modifier !== "meta" && (event.metaKey || event.ctrlKey);
6525
+ useImperativeHandle(ref, () => ({ sweepDrag: (press) => {
6526
+ if (!enabled || press.touch) return void 0;
6527
+ return (modifier === "shift" ? press.shiftKey : modifier === "alt" ? press.altKey : press.metaKey) ? dragFrom(press.point, modifier !== "meta" && press.metaKey, false) : void 0;
6528
+ } }));
6529
+ const onPointerDown = (event) => {
6530
+ if (!enabled || stage.panMode || event.button !== 0 || event.pointerType === "touch" || !holds(modifier, event)) return;
6531
+ startDrag(event, dragFrom(stage.toImage({
6532
+ x: event.clientX,
6533
+ y: event.clientY
6534
+ }), additiveOf(event), false));
6535
+ };
6536
+ return /* @__PURE__ */ jsxs(Fragment, { children: [armed && /* @__PURE__ */ jsx("svg", {
6537
+ viewBox: imageViewBox(stage.image),
6538
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
6539
+ "aria-hidden": true,
6540
+ "data-armed": "",
6541
+ "data-sweeping": sweeping ? "" : void 0,
6542
+ children: /* @__PURE__ */ jsx("rect", {
6543
+ "data-marquee-surface": "",
6544
+ x: -.5,
6545
+ y: -.5,
6546
+ width: stage.image.width,
6547
+ height: stage.image.height,
6548
+ fill: "transparent",
6549
+ className: "pointer-events-auto cursor-crosshair",
6550
+ onPointerDown
6551
+ })
6552
+ }), /* @__PURE__ */ jsx(MarqueeRect, {
6553
+ rect: band,
6554
+ stroke
6555
+ })] });
6556
+ }
6557
+ //#endregion
6404
6558
  //#region src/components/areaIndex.ts
6405
6559
  /** The most grid cells an index allocates, and the most area-to-cell entries. */
6406
6560
  const MAX_CELLS = 4e6;
@@ -7895,6 +8049,786 @@ function colourPlane(plane, colormap, range, channel) {
7895
8049
  height: plane.height
7896
8050
  };
7897
8051
  }
8052
+ /**
8053
+ * The levels to draw.
8054
+ *
8055
+ * @param spec - Explicit levels (non-finite ones are dropped, duplicates merged), or `{ step }`:
8056
+ * every multiple of `step` (offset by `origin`) inside `[min, max]`. If that gives more than
8057
+ * `MAX_LEVELS` levels the step is multiplied by a whole number until it does not.
8058
+ * @param min - The field's smallest finite value, for a step.
8059
+ * @param max - The field's largest finite value.
8060
+ * @returns Ascending, distinct levels.
8061
+ */
8062
+ function resolveLevels(spec, min, max) {
8063
+ if (Array.isArray(spec) || ArrayBuffer.isView(spec)) return [...new Set(spec.filter(Number.isFinite))].sort((a, b) => a - b);
8064
+ const { step, origin = 0 } = spec;
8065
+ if (!(step > 0) || !Number.isFinite(step) || !Number.isFinite(min) || !Number.isFinite(max) || max < min) return [];
8066
+ let use = step;
8067
+ while ((max - min) / use > 64) use += step;
8068
+ const first = Math.ceil((min - origin) / use - 1e-9);
8069
+ const last = Math.floor((max - origin) / use + 1e-9);
8070
+ const levels = [];
8071
+ for (let k = first; k <= last; k++) levels.push(origin + k * use);
8072
+ return levels;
8073
+ }
8074
+ /** The finite extent of one channel of a plane, `null` when it has no finite value. */
8075
+ function channelExtent(plane, channel = 0) {
8076
+ const size = plane.width * plane.height;
8077
+ const base = channel * size;
8078
+ let min = Infinity;
8079
+ let max = -Infinity;
8080
+ for (let k = 0; k < size; k++) {
8081
+ const v = plane.values[base + k];
8082
+ if (v < min) min = v;
8083
+ if (v > max) max = v;
8084
+ }
8085
+ return min <= max && Number.isFinite(min) && Number.isFinite(max) ? [min, max] : null;
8086
+ }
8087
+ /** Segment endpoints (as edges `T`op, `R`ight, `B`ottom, `L`eft) for each case; corners a b c d clockwise from top-left, a = 8. */
8088
+ const T = 0;
8089
+ const R = 1;
8090
+ const B = 2;
8091
+ const L = 3;
8092
+ const CASES = [
8093
+ [],
8094
+ [[L, B]],
8095
+ [[B, R]],
8096
+ [[L, R]],
8097
+ [[T, R]],
8098
+ [],
8099
+ [[T, B]],
8100
+ [[T, L]],
8101
+ [[T, L]],
8102
+ [[T, B]],
8103
+ [],
8104
+ [[T, R]],
8105
+ [[L, R]],
8106
+ [[B, R]],
8107
+ [[L, B]],
8108
+ []
8109
+ ];
8110
+ /**
8111
+ * The iso-lines of one channel at one level.
8112
+ *
8113
+ * @param values - The samples, row-major within the channel (`plane.values`).
8114
+ * @param width - Columns (nodes).
8115
+ * @param height - Rows.
8116
+ * @param level - The level.
8117
+ * @param offset - Index of the channel's first sample. Default 0.
8118
+ * @returns The lines, in a deterministic order (by the first cell, row-major, each line starting
8119
+ * at its first segment). Empty for a plane under 2×2 nodes.
8120
+ */
8121
+ function contourAtLevel(values, width, height, level, offset = 0) {
8122
+ if (!(width >= 2 && height >= 2) || !Number.isFinite(level)) return [];
8123
+ const edgeId = (i, j, edge) => {
8124
+ switch (edge) {
8125
+ case T: return 2 * (j * width + i);
8126
+ case B: return 2 * ((j + 1) * width + i);
8127
+ case L: return 2 * (j * width + i) + 1;
8128
+ default: return 2 * (j * width + i + 1) + 1;
8129
+ }
8130
+ };
8131
+ const segments = [];
8132
+ for (let j = 0; j < height - 1; j++) for (let i = 0; i < width - 1; i++) {
8133
+ const a = values[offset + j * width + i];
8134
+ const b = values[offset + j * width + i + 1];
8135
+ const c = values[offset + (j + 1) * width + i + 1];
8136
+ const d = values[offset + (j + 1) * width + i];
8137
+ if (!(Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(c) && Number.isFinite(d))) continue;
8138
+ const index = (a >= level ? 8 : 0) | (b >= level ? 4 : 0) | (c >= level ? 2 : 0) | (d >= level ? 1 : 0);
8139
+ let pairs = CASES[index];
8140
+ if (index === 5 || index === 10) {
8141
+ const joined = (a + b + c + d) / 4 >= level;
8142
+ pairs = index === 5 ? joined ? [[T, L], [B, R]] : [[T, R], [L, B]] : joined ? [[T, R], [L, B]] : [[T, L], [B, R]];
8143
+ }
8144
+ for (const [e0, e1] of pairs) segments.push([edgeId(i, j, e0), edgeId(i, j, e1)]);
8145
+ }
8146
+ if (segments.length === 0) return [];
8147
+ const at = /* @__PURE__ */ new Map();
8148
+ segments.forEach(([p, q], s) => {
8149
+ for (const id of [p, q]) {
8150
+ const list = at.get(id);
8151
+ if (list) list.push(s);
8152
+ else at.set(id, [s]);
8153
+ }
8154
+ });
8155
+ const crossing = (id) => {
8156
+ const vertical = id % 2 === 1;
8157
+ const node = (id - (vertical ? 1 : 0)) / 2;
8158
+ const i = node % width;
8159
+ const j = (node - i) / width;
8160
+ const v0 = values[offset + node];
8161
+ const v1 = values[offset + node + (vertical ? width : 1)];
8162
+ const t = Math.min(1, Math.max(0, (level - v0) / (v1 - v0)));
8163
+ return vertical ? [i, j + t] : [i + t, j];
8164
+ };
8165
+ const used = new Uint8Array(segments.length);
8166
+ const lines = [];
8167
+ for (let s = 0; s < segments.length; s++) {
8168
+ if (used[s]) continue;
8169
+ used[s] = 1;
8170
+ const ids = [segments[s][0], segments[s][1]];
8171
+ walk(ids, at, segments, used, true);
8172
+ walk(ids, at, segments, used, false);
8173
+ const closed = ids.length > 2 && ids[0] === ids[ids.length - 1];
8174
+ if (closed) ids.pop();
8175
+ const points = [];
8176
+ for (const id of ids) points.push(...crossing(id));
8177
+ lines.push({
8178
+ level,
8179
+ points,
8180
+ closed
8181
+ });
8182
+ }
8183
+ return lines;
8184
+ }
8185
+ /** Extends a chain of edge ids at its tail (`forward`) or head by the unused segments meeting there. */
8186
+ function walk(ids, at, segments, used, forward) {
8187
+ for (;;) {
8188
+ const end = forward ? ids[ids.length - 1] : ids[0];
8189
+ if (ids.length > 2 && ids[0] === ids[ids.length - 1]) return;
8190
+ const next = at.get(end).find((other) => !used[other]);
8191
+ if (next === void 0) return;
8192
+ used[next] = 1;
8193
+ const [p, q] = segments[next];
8194
+ const far = p === end ? q : p;
8195
+ if (forward) ids.push(far);
8196
+ else ids.unshift(far);
8197
+ }
8198
+ }
8199
+ /**
8200
+ * The iso-lines of a plane's channel at every level, lowest level first.
8201
+ *
8202
+ * @param plane - The field; `NaN` is "no data".
8203
+ * @param channel - Which channel. Default 0; out of range gives no lines.
8204
+ * @param levels - See `resolveLevels`; the lines of each level, in turn.
8205
+ */
8206
+ function contourPaths(plane, channel, levels) {
8207
+ if (!Number.isInteger(channel) || channel < 0 || channel >= plane.channels) return [];
8208
+ const offset = channel * plane.width * plane.height;
8209
+ return levels.flatMap((level) => contourAtLevel(plane.values, plane.width, plane.height, level, offset));
8210
+ }
8211
+ /** Total length of a polyline (closing segment included for a closed line), in nodes. */
8212
+ function lineLength(line) {
8213
+ const p = line.points;
8214
+ let length = 0;
8215
+ for (let k = 2; k < p.length; k += 2) length += Math.hypot(p[k] - p[k - 2], p[k + 1] - p[k - 1]);
8216
+ if (line.closed && p.length >= 4) length += Math.hypot(p[0] - p[p.length - 2], p[1] - p[p.length - 1]);
8217
+ return length;
8218
+ }
8219
+ /**
8220
+ * Points along a line at fractions of its length, for placing labels.
8221
+ *
8222
+ * @param line - The line.
8223
+ * @param count - How many labels; they sit at `(k + 0.5) / count` of the arc length.
8224
+ * @returns `[x, y]` per label, in nodes.
8225
+ */
8226
+ function pointsAlong(line, count) {
8227
+ const p = line.points;
8228
+ const n = p.length / 2;
8229
+ if (n === 0 || count < 1) return [];
8230
+ const total = lineLength(line);
8231
+ if (n === 1 || total === 0) return [[p[0], p[1]]];
8232
+ const out = [];
8233
+ const segs = line.closed ? n : n - 1;
8234
+ for (let k = 0; k < count; k++) {
8235
+ let target = (k + .5) / count * total;
8236
+ for (let s = 0; s < segs; s++) {
8237
+ const x0 = p[2 * s];
8238
+ const y0 = p[2 * s + 1];
8239
+ const t = (s + 1) % n;
8240
+ const x1 = p[2 * t];
8241
+ const y1 = p[2 * t + 1];
8242
+ const len = Math.hypot(x1 - x0, y1 - y0);
8243
+ if (target <= len || s === segs - 1) {
8244
+ const f = len === 0 ? 0 : Math.min(1, target / len);
8245
+ out.push([x0 + f * (x1 - x0), y0 + f * (y1 - y0)]);
8246
+ break;
8247
+ }
8248
+ target -= len;
8249
+ }
8250
+ }
8251
+ return out;
8252
+ }
8253
+ //#endregion
8254
+ //#region src/components/ContourLayer.tsx
8255
+ /**
8256
+ * Iso-lines of a scalar field over the image: the level sets of a distortion map, a residual field,
8257
+ * a support boundary.
8258
+ *
8259
+ * The lines are found by marching squares over the plane's nodes (see `contourPaths`), drawn as one
8260
+ * path per style (a halo, the solid levels, the dashed ones), never one element per line, and
8261
+ * stroked at screen-constant width. The layer takes no pointer events.
8262
+ */
8263
+ /** A line is labelled only when it is at least this long on screen, in CSS pixels. */
8264
+ const MIN_LABELLED_LENGTH = 90;
8265
+ /** A long line is labelled again every this many screen pixels. */
8266
+ const LABEL_EVERY = 280;
8267
+ /** Dash and gap of a dashed level, in screen pixels. */
8268
+ const DASH = [5, 3];
8269
+ const defaultFormat = (level) => String(Number(level.toPrecision(3)));
8270
+ const sameLevel = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
8271
+ /**
8272
+ * Contour lines inside an `ImageStage`.
8273
+ *
8274
+ * - **Lines**: marching squares per level over the plane's nodes (pixel centres), linear along
8275
+ * edges; a saddle is resolved by the mean of its four corners. They are computed once per
8276
+ * change of `plane`, `channel` and `levels`, not on pan or zoom.
8277
+ * - **No data**: a cell touching a `NaN` node has no line, so a line stops at a hole.
8278
+ * - **Styles**: solid levels in one path, dashed ones in another, each over a halo.
8279
+ * - **Labels**: optional, by zoom (see `labels`).
8280
+ * - **Input**: none. The layer is decorative; the numbers are read from the plane (`valueAt`),
8281
+ * and a legend or `labels` carry the levels as text.
8282
+ *
8283
+ * The SVG carries `data-count` (lines) and `data-levels` (the levels drawn).
8284
+ */
8285
+ function ContourLayer({ plane, channel = 0, levels, dashedLevels, labels = false, rect, role = "structure", color, halo = true, visible = true, label = "Contours" }) {
8286
+ const stage = useStage();
8287
+ const px = useScreenPx();
8288
+ const unit = px(1);
8289
+ const levelsKey = Array.isArray(levels) ? `l:${levels.join(",")}` : `s:${levels.step}:${levels.origin ?? 0}`;
8290
+ const dashedKey = (dashedLevels ?? []).join(",");
8291
+ const drawn = useMemo(() => {
8292
+ if (!visible) return {
8293
+ lines: [],
8294
+ levels: [],
8295
+ dashed: []
8296
+ };
8297
+ const extent = Array.isArray(levels) ? null : channelExtent(plane, channel);
8298
+ const base = Array.isArray(levels) ? resolveLevels(levels, 0, 0) : extent ? resolveLevels(levels, extent[0], extent[1]) : [];
8299
+ const dashed = (dashedLevels ?? []).filter(Number.isFinite);
8300
+ const all = [...base];
8301
+ for (const level of dashed) if (!all.some((l) => sameLevel(l, level))) all.push(level);
8302
+ all.sort((a, b) => a - b);
8303
+ return {
8304
+ lines: contourPaths(plane, channel, all),
8305
+ levels: all,
8306
+ dashed
8307
+ };
8308
+ }, [
8309
+ visible,
8310
+ plane,
8311
+ channel,
8312
+ levelsKey,
8313
+ dashedKey
8314
+ ]);
8315
+ const box = rect ?? {
8316
+ x: -.5,
8317
+ y: -.5,
8318
+ width: stage.image.width,
8319
+ height: stage.image.height
8320
+ };
8321
+ const sx = plane.width > 0 ? box.width / plane.width : 1;
8322
+ const sy = plane.height > 0 ? box.height / plane.height : 1;
8323
+ const paths = useMemo(() => {
8324
+ let solid = "";
8325
+ let dashed = "";
8326
+ for (const line of drawn.lines) {
8327
+ let d = "";
8328
+ const p = line.points;
8329
+ for (let k = 0; k < p.length; k += 2) d += `${k === 0 ? "M" : "L"}${(box.x + (p[k] + .5) * sx).toFixed(2)} ${(box.y + (p[k + 1] + .5) * sy).toFixed(2)}`;
8330
+ if (line.closed) d += "Z";
8331
+ if (drawn.dashed.some((level) => sameLevel(level, line.level))) dashed += d;
8332
+ else solid += d;
8333
+ }
8334
+ return {
8335
+ solid,
8336
+ dashed
8337
+ };
8338
+ }, [
8339
+ drawn,
8340
+ box.x,
8341
+ box.y,
8342
+ sx,
8343
+ sy
8344
+ ]);
8345
+ const format = typeof labels === "function" ? labels : defaultFormat;
8346
+ const view = visibleRect(stage.view, stage.box);
8347
+ const labelled = useMemo(() => {
8348
+ if (labels === false) return [];
8349
+ const out = [];
8350
+ for (const line of drawn.lines) {
8351
+ const screen = lineLength(line) * Math.hypot(sx, sy) / Math.SQRT2 / unit;
8352
+ if (screen < MIN_LABELLED_LENGTH) continue;
8353
+ const count = Math.max(1, Math.floor(screen / LABEL_EVERY));
8354
+ for (const [x, y] of pointsAlong(line, count)) {
8355
+ const ix = box.x + (x + .5) * sx;
8356
+ const iy = box.y + (y + .5) * sy;
8357
+ if (view && (ix < view.x || ix > view.x + view.width || iy < view.y || iy > view.y + view.height)) continue;
8358
+ out.push({
8359
+ x: ix,
8360
+ y: iy,
8361
+ text: format(line.level)
8362
+ });
8363
+ if (out.length >= 200) return out;
8364
+ }
8365
+ }
8366
+ return out;
8367
+ }, [
8368
+ labels,
8369
+ drawn,
8370
+ box.x,
8371
+ box.y,
8372
+ sx,
8373
+ sy,
8374
+ unit,
8375
+ view?.x,
8376
+ view?.y,
8377
+ view?.width,
8378
+ view?.height
8379
+ ]);
8380
+ if (!visible) return null;
8381
+ const tone = color ?? overlayRole(role);
8382
+ const HALO = overlayRole("halo");
8383
+ const width = px(OVERLAY_STATE_WIDTH.default);
8384
+ const dash = `${px(DASH[0])} ${px(DASH[1])}`;
8385
+ const levelsText = drawn.levels.slice(0, 6).map(defaultFormat).join(", ") + (drawn.levels.length > 6 ? ", …" : "");
8386
+ return /* @__PURE__ */ jsxs("svg", {
8387
+ viewBox: imageViewBox(stage.image),
8388
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
8389
+ role: "img",
8390
+ "aria-label": `${label}: ${drawn.lines.length} ${drawn.lines.length === 1 ? "line" : "lines"}${levelsText ? ` at ${levelsText}` : ""}`,
8391
+ "data-count": drawn.lines.length,
8392
+ "data-levels": drawn.levels.join(","),
8393
+ children: [/* @__PURE__ */ jsxs("g", {
8394
+ fill: "none",
8395
+ strokeLinecap: "round",
8396
+ strokeLinejoin: "round",
8397
+ children: [
8398
+ halo && paths.solid !== "" && /* @__PURE__ */ jsx("path", {
8399
+ "data-halo": "",
8400
+ d: paths.solid,
8401
+ stroke: HALO,
8402
+ strokeWidth: width + px(2),
8403
+ opacity: .6
8404
+ }),
8405
+ halo && paths.dashed !== "" && /* @__PURE__ */ jsx("path", {
8406
+ "data-halo": "",
8407
+ d: paths.dashed,
8408
+ stroke: HALO,
8409
+ strokeWidth: width + px(2),
8410
+ opacity: .6
8411
+ }),
8412
+ paths.solid !== "" && /* @__PURE__ */ jsx("path", {
8413
+ "data-contours": "solid",
8414
+ d: paths.solid,
8415
+ stroke: tone,
8416
+ strokeWidth: width
8417
+ }),
8418
+ paths.dashed !== "" && /* @__PURE__ */ jsx("path", {
8419
+ "data-contours": "dashed",
8420
+ d: paths.dashed,
8421
+ stroke: tone,
8422
+ strokeWidth: width,
8423
+ strokeDasharray: dash,
8424
+ strokeLinecap: "butt"
8425
+ })
8426
+ ]
8427
+ }), labelled.length > 0 && /* @__PURE__ */ jsx("g", {
8428
+ "data-labels": "",
8429
+ fontSize: px(11),
8430
+ className: "font-mono",
8431
+ stroke: HALO,
8432
+ strokeWidth: px(3),
8433
+ paintOrder: "stroke",
8434
+ strokeLinejoin: "round",
8435
+ fill: overlayRole("label"),
8436
+ textAnchor: "middle",
8437
+ dominantBaseline: "central",
8438
+ children: labelled.map((entry) => /* @__PURE__ */ jsx("text", {
8439
+ x: entry.x,
8440
+ y: entry.y,
8441
+ children: entry.text
8442
+ }, `${entry.x},${entry.y},${entry.text}`))
8443
+ })]
8444
+ });
8445
+ }
8446
+ //#endregion
8447
+ //#region src/components/vectorGeometry.ts
8448
+ /**
8449
+ * The length of vector `i`, or `NaN` when it is absent.
8450
+ *
8451
+ * @param vectors - Flat `[dx0, dy0, …]`.
8452
+ * @param i - The vector's index.
8453
+ * @returns `hypot(dx, dy)`, or `NaN` for a non-finite component.
8454
+ */
8455
+ function vectorMagnitude(vectors, i) {
8456
+ const dx = vectors[2 * i];
8457
+ const dy = vectors[2 * i + 1];
8458
+ if (dx === void 0 || dy === void 0 || !Number.isFinite(dx) || !Number.isFinite(dy)) return NaN;
8459
+ return Math.hypot(dx, dy);
8460
+ }
8461
+ /**
8462
+ * The magnitudes of every vector, `NaN` for an absent one.
8463
+ *
8464
+ * @param vectors - Flat `[dx0, dy0, …]`.
8465
+ * @returns One magnitude per vector.
8466
+ */
8467
+ function vectorMagnitudes(vectors) {
8468
+ const count = Math.floor(vectors.length / 2);
8469
+ const out = new Float64Array(count);
8470
+ for (let i = 0; i < count; i++) out[i] = vectorMagnitude(vectors, i);
8471
+ return out;
8472
+ }
8473
+ /**
8474
+ * A magnitude's rank statistic over the present vectors.
8475
+ *
8476
+ * @param magnitudes - As `vectorMagnitudes` returns them; `NaN` entries are ignored.
8477
+ * @param p - The fraction in `[0, 1]` (clamped): `1` is the longest, `0.5` the median.
8478
+ * @returns The nearest-rank value, or `0` when no vector is present.
8479
+ */
8480
+ function magnitudePercentile(magnitudes, p) {
8481
+ const live = [];
8482
+ for (let i = 0; i < magnitudes.length; i++) {
8483
+ const m = magnitudes[i];
8484
+ if (Number.isFinite(m)) live.push(m);
8485
+ }
8486
+ if (live.length === 0) return 0;
8487
+ live.sort((a, b) => a - b);
8488
+ return live[Math.max(0, Math.ceil((Number.isFinite(p) ? Math.min(1, Math.max(0, p)) : 1) * live.length) - 1)];
8489
+ }
8490
+ /**
8491
+ * The scale in image pixels per data unit.
8492
+ *
8493
+ * @param scale - See `VectorScale`.
8494
+ * @param referenceMagnitude - The reference vector's length in data units, for an automatic scale.
8495
+ * @param imagePerScreenPx - Image pixels covered by one screen pixel at the current zoom.
8496
+ * @returns Image pixels per data unit; `0` when an automatic scale has no vector to measure.
8497
+ */
8498
+ function imagePerUnit(scale, referenceMagnitude, imagePerScreenPx) {
8499
+ if (typeof scale === "number") return Number.isFinite(scale) && scale > 0 ? scale : 0;
8500
+ if (!(referenceMagnitude > 0) || !(scale.length > 0)) return 0;
8501
+ return scale.length * imagePerScreenPx / referenceMagnitude;
8502
+ }
8503
+ /**
8504
+ * A round length for a key: the largest of 1, 2 and 5 times a power of ten that is at most `max`.
8505
+ *
8506
+ * @param max - The upper bound, in data units.
8507
+ * @returns The round length, or `0` for a non-positive `max`.
8508
+ */
8509
+ function niceLength(max) {
8510
+ if (!(max > 0) || !Number.isFinite(max)) return 0;
8511
+ const power = 10 ** Math.floor(Math.log10(max));
8512
+ for (const m of [
8513
+ 5,
8514
+ 2,
8515
+ 1
8516
+ ]) if (m * power <= max * (1 + 1e-12)) return m * power;
8517
+ return power;
8518
+ }
8519
+ const r = (v) => String(Math.round(v * 1e3) / 1e3);
8520
+ /**
8521
+ * The path data of one arrow: a shaft and a filled head.
8522
+ *
8523
+ * The head is capped at 45 % of the arrow's length, so a short arrow is a small wedge rather
8524
+ * than a head on no shaft. Lengths are in the units of `(x, y)` (image pixels); `unit` converts
8525
+ * the style's screen pixels to them.
8526
+ *
8527
+ * @param x - The anchor's x.
8528
+ * @param y - The anchor's y.
8529
+ * @param dx - The displacement's x, already scaled to image pixels.
8530
+ * @param dy - The displacement's y, already scaled to image pixels.
8531
+ * @param unit - Image pixels per screen pixel.
8532
+ * @param style - The arrow's shape.
8533
+ * @returns Path data, or `""` when the arrow is absent or shorter than `style.minLength`.
8534
+ */
8535
+ function arrowPath(x, y, dx, dy, unit, style) {
8536
+ const len = Math.hypot(dx, dy);
8537
+ if (!(len > 0) || len < style.minLength * unit) return "";
8538
+ const ux = dx / len;
8539
+ const uy = dy / len;
8540
+ const head = Math.min(style.head * unit, .45 * len);
8541
+ const half = head * style.headWidth / 2;
8542
+ const tx = x + dx;
8543
+ const ty = y + dy;
8544
+ const bx = tx - ux * head;
8545
+ const by = ty - uy * head;
8546
+ return `M${r(x)} ${r(y)}L${r(bx)} ${r(by)}M${r(tx)} ${r(ty)}L${r(bx - uy * half)} ${r(by + ux * half)}L${r(bx + uy * half)} ${r(by - ux * half)}Z`;
8547
+ }
8548
+ /** The number of colour steps a magnitude-coloured field is quantised into: one path each. */
8549
+ const VECTOR_COLOR_BINS = 24;
8550
+ /**
8551
+ * The colour bin of a magnitude.
8552
+ *
8553
+ * @param magnitude - The vector's length.
8554
+ * @param low - The magnitude drawn in the map's first colour.
8555
+ * @param high - The magnitude drawn in the map's last colour.
8556
+ * @param bins - The number of bins. Defaults to `VECTOR_COLOR_BINS`.
8557
+ * @returns An integer in `[0, bins - 1]`; a degenerate range puts everything in bin `0`.
8558
+ */
8559
+ function colorBin(magnitude, low, high, bins = 24) {
8560
+ if (!(high > low)) return 0;
8561
+ const t = (magnitude - low) / (high - low);
8562
+ return Math.min(bins - 1, Math.max(0, Math.floor(t * bins)));
8563
+ }
8564
+ //#endregion
8565
+ //#region src/components/VectorField.tsx
8566
+ /**
8567
+ * Many vectors over the image: a displacement, a flow, a gradient, a residual direction.
8568
+ *
8569
+ * Drawn as a handful of batched paths (one halo, then one per colour step), never one element per
8570
+ * vector; the pointer is resolved through the stage's hit registry from a spatial index over the
8571
+ * anchors, never by the DOM; arrowheads and strokes are sized in screen pixels. A field of 10,000
8572
+ * vectors is a dozen DOM nodes.
8573
+ */
8574
+ /** The arrow's shape, in screen pixels. */
8575
+ const ARROW = {
8576
+ head: 6,
8577
+ headWidth: .7,
8578
+ minLength: 1
8579
+ };
8580
+ /** Past this many vectors, paths are generated for the visible part only. */
8581
+ const CULL_ABOVE = 3e3;
8582
+ /** The reference vector of the default scale: the 95th percentile spans this many screen pixels. */
8583
+ const DEFAULT_SCALE = {
8584
+ length: 28,
8585
+ percentile: .95
8586
+ };
8587
+ /**
8588
+ * The reference vector of a scale and the scale it gives, shared by the layer and its key.
8589
+ *
8590
+ * @param vectors - Flat `[dx0, dy0, …]`.
8591
+ * @param scale - See `VectorScale`.
8592
+ * @returns The reference magnitude in data units, and image pixels per data unit.
8593
+ */
8594
+ function useVectorScale(vectors, scale = DEFAULT_SCALE) {
8595
+ const unit = useScreenPx()(1);
8596
+ const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
8597
+ const percentile = typeof scale === "number" ? 1 : scale.percentile ?? 1;
8598
+ const reference = useMemo(() => magnitudePercentile(mags, percentile), [mags, percentile]);
8599
+ return {
8600
+ reference,
8601
+ perUnit: imagePerUnit(scale, reference, unit)
8602
+ };
8603
+ }
8604
+ /** `rgb(r g b)` of a map's colour, channels rounded and clamped. */
8605
+ function css(colormap, t) {
8606
+ const [r, g, b] = colormap(t);
8607
+ const c = (v) => Math.min(255, Math.max(0, Math.round(v)));
8608
+ return `rgb(${c(r)} ${c(g)} ${c(b)})`;
8609
+ }
8610
+ /**
8611
+ * A field of arrows inside an `ImageStage`.
8612
+ *
8613
+ * - **Scale**: see `VectorScale`. The same `vectors` and `scale` given to `VectorFieldKey` draw a
8614
+ * reference length at exactly this scale.
8615
+ * - **Colour**: one tone (`color` or `role`), or by magnitude through `colormap` over `range`.
8616
+ * - **Absent data**: an anchor or vector with a non-finite number, or shorter than one screen
8617
+ * pixel, is not drawn.
8618
+ * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here, and
8619
+ * `useStageHitTest` for an app that arbitrates between layers. The hovered arrow is redrawn
8620
+ * at 2.5 screen px in the selection colour.
8621
+ *
8622
+ * Arrowheads and strokes are screen-constant; their paths are regenerated when the zoom changes,
8623
+ * and past 3,000 vectors only those near the viewport are generated. The SVG carries
8624
+ * `data-hovered` (the hovered id) and `data-count` (the vectors drawn).
8625
+ */
8626
+ function VectorField({ anchors, vectors, scale = DEFAULT_SCALE, color, role = "feature", colormap, range, ids, hoveredId, onHoverChange, onItemPress, halo = true, pickable = true, layerId, priority = STAGE_HIT_PRIORITY.point, label = "Vectors" }) {
8627
+ const stage = useStage();
8628
+ const px = useScreenPx();
8629
+ const unit = px(1);
8630
+ const count = Math.min(Math.floor(anchors.length / 2), Math.floor(vectors.length / 2));
8631
+ const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
8632
+ const { perUnit } = useVectorScale(vectors, scale);
8633
+ const index = useMemo(() => buildPointIndex(anchors, { ids }), [anchors, ids]);
8634
+ const [ownHover, setOwnHover] = useState(null);
8635
+ const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
8636
+ useStageHitLayer({
8637
+ layerId,
8638
+ priority,
8639
+ enabled: pickable,
8640
+ pick: (point, radius) => {
8641
+ const hit = nearestPoint(index, point.x, point.y, radius);
8642
+ return hit && hit.index < count && Number.isFinite(mags[hit.index]) ? {
8643
+ id: hit.id,
8644
+ dist: hit.dist
8645
+ } : null;
8646
+ },
8647
+ onHover: (id) => {
8648
+ setOwnHover(id);
8649
+ onHoverChange?.(id);
8650
+ },
8651
+ onPress: onItemPress
8652
+ });
8653
+ const colourRange = useMemo(() => {
8654
+ if (!colormap) return null;
8655
+ if (range) return range;
8656
+ let high = 0;
8657
+ for (let i = 0; i < count; i++) if (mags[i] > high) high = mags[i];
8658
+ return {
8659
+ low: 0,
8660
+ high
8661
+ };
8662
+ }, [
8663
+ colormap,
8664
+ range,
8665
+ mags,
8666
+ count
8667
+ ]);
8668
+ const cull = cullWindow(stage.view, stage.box, count, mags, perUnit);
8669
+ const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
8670
+ const built = useMemo(() => {
8671
+ const parts = new Array(colormap && colourRange ? 24 : 1).fill("");
8672
+ let drawn = 0;
8673
+ for (let i = 0; i < count; i++) {
8674
+ const m = mags[i];
8675
+ const x = anchors[2 * i];
8676
+ const y = anchors[2 * i + 1];
8677
+ if (!Number.isFinite(m) || !Number.isFinite(x) || !Number.isFinite(y)) continue;
8678
+ if (cull && (x < cull.x || x > cull.x + cull.width || y < cull.y || y > cull.y + cull.height)) continue;
8679
+ const d = arrowPath(x, y, vectors[2 * i] * perUnit, vectors[2 * i + 1] * perUnit, unit, ARROW);
8680
+ if (d === "") continue;
8681
+ const bin = colormap && colourRange ? colorBin(m, colourRange.low, colourRange.high) : 0;
8682
+ parts[bin] += d;
8683
+ drawn++;
8684
+ }
8685
+ return {
8686
+ parts,
8687
+ batches: parts.flatMap((d, bin) => d === "" ? [] : [{
8688
+ bin,
8689
+ d
8690
+ }]),
8691
+ drawn
8692
+ };
8693
+ }, [
8694
+ anchors,
8695
+ vectors,
8696
+ mags,
8697
+ count,
8698
+ perUnit,
8699
+ unit,
8700
+ colormap,
8701
+ colourRange,
8702
+ cullKey
8703
+ ]);
8704
+ const all = useMemo(() => built.parts.join(""), [built]);
8705
+ const hoverIndex = hoverId === null ? -1 : findIndex(index, hoverId, count);
8706
+ const hoverPath = hoverIndex >= 0 && Number.isFinite(mags[hoverIndex]) ? arrowPath(anchors[2 * hoverIndex], anchors[2 * hoverIndex + 1], vectors[2 * hoverIndex] * perUnit, vectors[2 * hoverIndex + 1] * perUnit, unit, ARROW) : "";
8707
+ const tone = color ?? overlayRole(role);
8708
+ const width = px(OVERLAY_STATE_WIDTH.default);
8709
+ const hoverWidth = px(OVERLAY_STATE_WIDTH.selected);
8710
+ const HALO = overlayRole("halo");
8711
+ return /* @__PURE__ */ jsx("svg", {
8712
+ viewBox: imageViewBox(stage.image),
8713
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
8714
+ role: "img",
8715
+ "aria-label": `${label}: ${built.drawn} ${built.drawn === 1 ? "vector" : "vectors"}`,
8716
+ "data-hovered": hoverId ?? void 0,
8717
+ "data-count": built.drawn,
8718
+ children: /* @__PURE__ */ jsxs("g", {
8719
+ fill: "none",
8720
+ strokeLinecap: "butt",
8721
+ strokeLinejoin: "round",
8722
+ children: [
8723
+ halo && all !== "" && /* @__PURE__ */ jsx("path", {
8724
+ "data-halo": "",
8725
+ d: all,
8726
+ stroke: HALO,
8727
+ fill: HALO,
8728
+ strokeWidth: width + px(2),
8729
+ opacity: .6
8730
+ }),
8731
+ built.batches.map(({ bin, d }) => /* @__PURE__ */ jsx("path", {
8732
+ "data-batch": bin,
8733
+ d,
8734
+ stroke: colormap ? css(colormap, (bin + .5) / 24) : tone,
8735
+ fill: colormap ? css(colormap, (bin + .5) / 24) : tone,
8736
+ strokeWidth: width
8737
+ }, bin)),
8738
+ hoverPath !== "" && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
8739
+ d: hoverPath,
8740
+ stroke: HALO,
8741
+ fill: HALO,
8742
+ strokeWidth: hoverWidth + px(2)
8743
+ }), /* @__PURE__ */ jsx("path", {
8744
+ "data-hovered-vector": "",
8745
+ d: hoverPath,
8746
+ stroke: overlayRole("selection"),
8747
+ fill: overlayRole("selection"),
8748
+ strokeWidth: hoverWidth
8749
+ })] })
8750
+ ]
8751
+ })
8752
+ });
8753
+ }
8754
+ /** The index of the vector with id `id`, or `-1`. */
8755
+ function findIndex(index, id, count) {
8756
+ if (index.ids === null) return typeof id === "number" && id >= 0 && id < count && Number.isInteger(id) ? id : -1;
8757
+ for (let i = 0; i < Math.min(count, index.ids.length); i++) if (index.ids[i] === id) return i;
8758
+ return -1;
8759
+ }
8760
+ /**
8761
+ * The window paths are generated for: the viewport plus the longest arrow on every side, snapped
8762
+ * outward to half-viewport steps so panning rebuilds it once per half screen. `null` for a small
8763
+ * field, or an unmeasured stage.
8764
+ */
8765
+ function cullWindow(view, box, count, mags, perUnit) {
8766
+ if (count <= CULL_ABOVE) return null;
8767
+ const visible = visibleRect(view, box);
8768
+ if (visible === null) return null;
8769
+ let longest = 0;
8770
+ for (let i = 0; i < count; i++) if (mags[i] > longest) longest = mags[i];
8771
+ const sx = visible.width / 2;
8772
+ const sy = visible.height / 2;
8773
+ const reach = Math.min(longest * perUnit, visible.width, visible.height);
8774
+ const left = Math.floor((visible.x - sx - reach) / sx) * sx;
8775
+ const top = Math.floor((visible.y - sy - reach) / sy) * sy;
8776
+ const right = Math.ceil((visible.x + visible.width + sx + reach) / sx) * sx;
8777
+ const bottom = Math.ceil((visible.y + visible.height + sy + reach) / sy) * sy;
8778
+ return {
8779
+ x: left,
8780
+ y: top,
8781
+ width: right - left,
8782
+ height: bottom - top
8783
+ };
8784
+ }
8785
+ //#endregion
8786
+ //#region src/components/VectorFieldKey.tsx
8787
+ /**
8788
+ * The reference length of a `VectorField`: an arrow of a round length with its value, so a
8789
+ * reader can turn arrow lengths back into data units.
8790
+ */
8791
+ const KEY_ARROW = {
8792
+ head: 5,
8793
+ headWidth: .7,
8794
+ minLength: 1
8795
+ };
8796
+ /** The key is not drawn wider than this, in screen pixels. */
8797
+ const MAX_WIDTH = 160;
8798
+ /**
8799
+ * An arrow of a known length and its value ("0.1 px"). Pass it as `ImageStage`'s `readout`, or
8800
+ * as the `extra` of a `StageReadout` with `bare`; it reads the stage's zoom through `useStage`, so it stays
8801
+ * true as the view changes, and draws nothing while the field has no scale or the arrow would
8802
+ * be wider than 160 screen pixels.
8803
+ *
8804
+ * On its own it is drawn in the readout's light-on-dark chip, so it sits on the image like the readout does.
8805
+ */
8806
+ function VectorFieldKey({ vectors, scale, length, unit, format = (value) => String(Number(value.toPrecision(3))), bare = false, className }) {
8807
+ const stage = useStage();
8808
+ const { reference, perUnit } = useVectorScale(vectors, scale);
8809
+ const value = length ?? niceLength(reference);
8810
+ const width = value * perUnit * stage.view.scale;
8811
+ if (!(value > 0) || !(width >= 1) || width > MAX_WIDTH) return null;
8812
+ return /* @__PURE__ */ jsxs("span", {
8813
+ className: cn("inline-flex items-center gap-1.5 align-middle font-mono text-[10px] tabular-nums", !bare && "rounded-control bg-black/60 px-1.5 py-0.5 text-white", className),
8814
+ "data-vector-key": "",
8815
+ title: `Arrow length: ${unit ? `${format(value)} ${unit}` : format(value)}`,
8816
+ children: [/* @__PURE__ */ jsx("svg", {
8817
+ "aria-hidden": true,
8818
+ width: width + 2,
8819
+ height: 10,
8820
+ viewBox: `-1 -5 ${width + 2} 10`,
8821
+ className: "shrink-0 overflow-visible",
8822
+ children: /* @__PURE__ */ jsx("path", {
8823
+ d: arrowPath(0, 0, width, 0, 1, KEY_ARROW),
8824
+ fill: "currentColor",
8825
+ stroke: "currentColor",
8826
+ strokeWidth: 1.5,
8827
+ strokeLinejoin: "round"
8828
+ })
8829
+ }), /* @__PURE__ */ jsx("span", { children: unit ? `${format(value)} ${unit}` : format(value) })]
8830
+ });
8831
+ }
7898
8832
  //#endregion
7899
8833
  //#region src/components/ShapeEditor.tsx
7900
8834
  /**
@@ -8845,6 +9779,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
8845
9779
  })] });
8846
9780
  }
8847
9781
  //#endregion
8848
- export { AreaSet, CompareLayer, ContourEditor, DATUM_ARM_PX, DATUM_HANDLE_PX, DATUM_RING_PX, DatumEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcLengths, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampToImage, clampView, contentUnder, crossSegments, datumAxes, datumPress, decodePlane, deformContour, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, eraseArc, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, measurePrimitiveDistance, moveDatum, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestMeasurePrimitive, nearestPoint, nearestPolyline, normalAtArc, normalizeAngle, overlayRole, paintMask, planeRange, pointAtArc, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, projectToArc, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotateDatum, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, segmentsPath, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, snapAngle, steppedScale, strokeWidthFor, subPath, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
9782
+ export { AreaSet, CompareLayer, ContourEditor, ContourLayer, DATUM_ARM_PX, DATUM_HANDLE_PX, DATUM_RING_PX, DatumEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointMarquee, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, VECTOR_COLOR_BINS, VectorField, VectorFieldKey, ZoomPanCanvas, arcLengths, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, arrowPath, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampToImage, clampView, colorBin, contentUnder, contourPaths, crossSegments, datumAxes, datumPress, decodePlane, deformContour, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, eraseArc, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imagePerUnit, imageViewBox, initialView, insideImage, isFit, latticeEdges, magnitudePercentile, measurePrimitiveDistance, moveDatum, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestMeasurePrimitive, nearestPoint, nearestPolyline, niceLength, normalAtArc, normalizeAngle, overlayRole, paintMask, planeRange, pointAtArc, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, projectToArc, rasterizePlane, rectFromCorners, resizeRect, resizeShape, resolveLevels, roiHandlePoint, rotateDatum, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, segmentsPath, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, snapAngle, steppedScale, strokeWidthFor, subPath, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, useVectorScale, valueAt, valuesAt, vectorMagnitude, vectorMagnitudes, zoomAbout, zoomAt };
8849
9783
 
8850
9784
  //# sourceMappingURL=index.js.map