@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/README.md +16 -0
- package/dist/index.d.ts +382 -1
- package/dist/index.js +944 -10
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/ContourLayer.tsx +211 -0
- package/src/components/PointMarquee.tsx +229 -0
- package/src/components/VectorField.tsx +302 -0
- package/src/components/VectorFieldKey.tsx +91 -0
- package/src/components/contour.ts +270 -0
- package/src/components/vectorGeometry.ts +159 -0
- package/src/index.ts +23 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vitavision/stage2d",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "The vitavision 2D image stage: view transform, zoom/pan, layered overlays, measurement.",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"react-dom": "^19.2.0"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@vitavision/ui": "^0.14.
|
|
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,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A rectangular marquee over a point set: hold a modifier, drag, and the ids of the points
|
|
3
|
+
* inside the rectangle are reported.
|
|
4
|
+
*
|
|
5
|
+
* Opt-in and inert without its modifier: a press without it is left to the stage (which pans),
|
|
6
|
+
* the wheel still zooms, and the layers below keep their own targets. The rectangle is drawn
|
|
7
|
+
* with `MarqueeRect` while the pointer moves.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
|
11
|
+
import type { PointerEvent as ReactPointerEvent, Ref } from "react";
|
|
12
|
+
|
|
13
|
+
import type { Point } from "./measureGeometry";
|
|
14
|
+
import { MarqueeRect } from "./DraftShape";
|
|
15
|
+
import { buildPointIndexFrom, pointsInRect, type PointId, type PointItem } from "./pointIndex";
|
|
16
|
+
import { useStage } from "./stage/ImageStage";
|
|
17
|
+
import type { StageDrag, StagePress } from "./stage/StageSurface";
|
|
18
|
+
import { useStageDrag } from "./stage/StageSurface";
|
|
19
|
+
import { imageViewBox, type Rect } from "./stage/view";
|
|
20
|
+
|
|
21
|
+
/** The key that arms a `PointMarquee`. `"meta"` is ⌘ on macOS and Ctrl elsewhere. */
|
|
22
|
+
export type PointMarqueeModifier = "shift" | "alt" | "meta";
|
|
23
|
+
|
|
24
|
+
/** How a marquee combines with the current selection: replaces it, or adds to it. */
|
|
25
|
+
export type PointMarqueeMode = "replace" | "add";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What `PointMarquee`'s `ref` exposes, for an app that already has a `StageSurface` (a stage
|
|
29
|
+
* has one full-frame press target) and starts the marquee from its `onPress`.
|
|
30
|
+
*/
|
|
31
|
+
export interface PointMarqueeHandle {
|
|
32
|
+
/**
|
|
33
|
+
* The marquee as a `StageDrag`, to return from `StageSurface`'s `onPress`.
|
|
34
|
+
*
|
|
35
|
+
* @param press - The press the surface was given.
|
|
36
|
+
* @returns The drag when the press holds the marquee's modifier, `undefined` otherwise: a
|
|
37
|
+
* declined press is for the surface's other tools or the stage's pan. A touch has no
|
|
38
|
+
* modifier, so it is never started here.
|
|
39
|
+
*/
|
|
40
|
+
sweepDrag(press: StagePress): StageDrag | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Props of `PointMarquee`. */
|
|
44
|
+
export interface PointMarqueeProps {
|
|
45
|
+
/** The points the marquee selects among, in image coordinates. Pass a stable array: a new one rebuilds the index. */
|
|
46
|
+
items: readonly PointItem[];
|
|
47
|
+
/**
|
|
48
|
+
* Called on release with the ids of the points inside the rectangle (edges included), in
|
|
49
|
+
* item order; an empty list for a rectangle that holds none. Not called for a modifier-press
|
|
50
|
+
* that did not move (a click is not a rectangle), nor after `Escape`.
|
|
51
|
+
*
|
|
52
|
+
* `mode` is `"add"` when ⌘/Ctrl is held as well as the modifier, `"replace"` otherwise. When
|
|
53
|
+
* the modifier is `"meta"` itself, the mode is always `"replace"`.
|
|
54
|
+
*/
|
|
55
|
+
onSelect: (ids: PointId[], mode: PointMarqueeMode) => void;
|
|
56
|
+
/** Called with the rectangle (image coordinates) while it is dragged, and with `null` when it ends. */
|
|
57
|
+
onBandChange?: ((band: Rect | null) => void) | undefined;
|
|
58
|
+
/** Called when a marquee is abandoned: `Escape`, or the pointer was cancelled. `onSelect` is not called. */
|
|
59
|
+
onCancel?: (() => void) | undefined;
|
|
60
|
+
/** The key that arms the marquee. Defaults to `"shift"`. */
|
|
61
|
+
modifier?: PointMarqueeModifier | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Whether the layer has a full-frame press target of its own. Defaults to `true`. The target
|
|
64
|
+
* exists only while the modifier is held, so it never covers the layers below otherwise. Turn
|
|
65
|
+
* it off to start the marquee from your own `StageSurface` through `ref`.
|
|
66
|
+
*/
|
|
67
|
+
surface?: boolean | undefined;
|
|
68
|
+
/** Turn the marquee off without unmounting it. Defaults to `true`. */
|
|
69
|
+
enabled?: boolean | undefined;
|
|
70
|
+
/** CSS colour of the rectangle. Defaults to the overlay `selection` role. */
|
|
71
|
+
stroke?: string | undefined;
|
|
72
|
+
/** Start a marquee from a press elsewhere; see `PointMarqueeHandle`. */
|
|
73
|
+
ref?: Ref<PointMarqueeHandle> | undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Whether a pointer or key event holds the modifier. */
|
|
77
|
+
function holds(modifier: PointMarqueeModifier, event: { shiftKey: boolean; altKey: boolean; metaKey: boolean; ctrlKey: boolean }): boolean {
|
|
78
|
+
if (modifier === "shift") return event.shiftKey;
|
|
79
|
+
if (modifier === "alt") return event.altKey;
|
|
80
|
+
return event.metaKey || event.ctrlKey;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function boxBetween(a: Point, b: Point): Rect {
|
|
84
|
+
return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A modifier-drag rectangle that selects points, inside an `ImageStage`.
|
|
89
|
+
*
|
|
90
|
+
* - **Opt-in**: a press without the modifier is left alone, so pan, wheel zoom and the layers
|
|
91
|
+
* below behave as without it. While the modifier is held the layer takes presses over the
|
|
92
|
+
* whole image and the cursor is a crosshair.
|
|
93
|
+
* - **Reports ids**, by the points' centres, through a spatial index: thousands of points cost
|
|
94
|
+
* microseconds.
|
|
95
|
+
* - **Escape** abandons a marquee in flight; releasing the pointer without moving does nothing.
|
|
96
|
+
* - **Touch** has no modifier: a finger pans as usual.
|
|
97
|
+
*
|
|
98
|
+
* It draws only the rectangle (`data-marquee`); selection feedback is the point layer's, fed by
|
|
99
|
+
* the ids the app keeps. The layer carries `data-armed` while the modifier is held and
|
|
100
|
+
* `data-sweeping` while a rectangle is being dragged.
|
|
101
|
+
*/
|
|
102
|
+
export function PointMarquee({
|
|
103
|
+
items,
|
|
104
|
+
onSelect,
|
|
105
|
+
onBandChange,
|
|
106
|
+
onCancel,
|
|
107
|
+
modifier = "shift",
|
|
108
|
+
surface = true,
|
|
109
|
+
enabled = true,
|
|
110
|
+
stroke,
|
|
111
|
+
ref,
|
|
112
|
+
}: PointMarqueeProps) {
|
|
113
|
+
const stage = useStage();
|
|
114
|
+
const startDrag = useStageDrag();
|
|
115
|
+
const index = useMemo(() => buildPointIndexFrom(items), [items]);
|
|
116
|
+
const [band, setBand] = useState<Rect | null>(null);
|
|
117
|
+
const [held, setHeld] = useState(false);
|
|
118
|
+
const armed = enabled && surface && held;
|
|
119
|
+
// An Escape ends the marquee at once; the pointer is still down until it is released.
|
|
120
|
+
const abandoned = useRef(false);
|
|
121
|
+
const live = useRef({ onSelect, onBandChange, onCancel });
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
live.current = { onSelect, onBandChange, onCancel };
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const publish = (next: Rect | null) => {
|
|
127
|
+
setBand(next);
|
|
128
|
+
live.current.onBandChange?.(next);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// The modifier is read from key and pointer events on the window, so the target appears when
|
|
132
|
+
// the key goes down and goes when it is released or the window loses focus.
|
|
133
|
+
useEffect(() => {
|
|
134
|
+
if (!enabled || !surface) return;
|
|
135
|
+
const sync = (event: { shiftKey: boolean; altKey: boolean; metaKey: boolean; ctrlKey: boolean }) => setHeld(holds(modifier, event));
|
|
136
|
+
const off = () => setHeld(false);
|
|
137
|
+
window.addEventListener("keydown", sync);
|
|
138
|
+
window.addEventListener("keyup", sync);
|
|
139
|
+
window.addEventListener("pointermove", sync);
|
|
140
|
+
window.addEventListener("blur", off);
|
|
141
|
+
return () => {
|
|
142
|
+
window.removeEventListener("keydown", sync);
|
|
143
|
+
window.removeEventListener("keyup", sync);
|
|
144
|
+
window.removeEventListener("pointermove", sync);
|
|
145
|
+
window.removeEventListener("blur", off);
|
|
146
|
+
};
|
|
147
|
+
}, [enabled, surface, modifier]);
|
|
148
|
+
|
|
149
|
+
// Escape abandons the marquee in flight.
|
|
150
|
+
const sweeping = band !== null;
|
|
151
|
+
useEffect(() => {
|
|
152
|
+
if (!sweeping) return;
|
|
153
|
+
const onKey = (event: KeyboardEvent) => {
|
|
154
|
+
if (event.key !== "Escape" || abandoned.current) return;
|
|
155
|
+
abandoned.current = true;
|
|
156
|
+
publish(null);
|
|
157
|
+
live.current.onCancel?.();
|
|
158
|
+
};
|
|
159
|
+
window.addEventListener("keydown", onKey);
|
|
160
|
+
return () => window.removeEventListener("keydown", onKey);
|
|
161
|
+
}, [sweeping]);
|
|
162
|
+
|
|
163
|
+
const dragFrom = (from: Point, additive: boolean, claimsTouch: boolean): StageDrag => {
|
|
164
|
+
abandoned.current = false;
|
|
165
|
+
publish({ x: from.x, y: from.y, width: 0, height: 0 });
|
|
166
|
+
return {
|
|
167
|
+
claimsTouch,
|
|
168
|
+
onMove: (p) => {
|
|
169
|
+
if (!abandoned.current) publish(boxBetween(from, p));
|
|
170
|
+
},
|
|
171
|
+
onEnd: (p, _event, moved) => {
|
|
172
|
+
if (abandoned.current) return;
|
|
173
|
+
publish(null);
|
|
174
|
+
if (moved)
|
|
175
|
+
live.current.onSelect(
|
|
176
|
+
pointsInRect(index, boxBetween(from, p)).map((i) => idAt(i)),
|
|
177
|
+
additive ? "add" : "replace",
|
|
178
|
+
);
|
|
179
|
+
},
|
|
180
|
+
onCancel: () => {
|
|
181
|
+
if (abandoned.current) return;
|
|
182
|
+
abandoned.current = true;
|
|
183
|
+
publish(null);
|
|
184
|
+
live.current.onCancel?.();
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
const idAt = (i: number): PointId => (index.ids ? index.ids[i]! : i);
|
|
189
|
+
const additiveOf = (event: { metaKey: boolean; ctrlKey: boolean }) => modifier !== "meta" && (event.metaKey || event.ctrlKey);
|
|
190
|
+
|
|
191
|
+
useImperativeHandle(ref, () => ({
|
|
192
|
+
sweepDrag: (press) => {
|
|
193
|
+
if (!enabled || press.touch) return undefined;
|
|
194
|
+
const held = modifier === "shift" ? press.shiftKey : modifier === "alt" ? press.altKey : press.metaKey;
|
|
195
|
+
return held ? dragFrom(press.point, modifier !== "meta" && press.metaKey, false) : undefined;
|
|
196
|
+
},
|
|
197
|
+
}));
|
|
198
|
+
|
|
199
|
+
const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {
|
|
200
|
+
if (!enabled || stage.panMode || event.button !== 0 || event.pointerType === "touch" || !holds(modifier, event)) return;
|
|
201
|
+
startDrag(event, dragFrom(stage.toImage({ x: event.clientX, y: event.clientY }), additiveOf(event), false));
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
return (
|
|
205
|
+
<>
|
|
206
|
+
{armed && (
|
|
207
|
+
<svg
|
|
208
|
+
viewBox={imageViewBox(stage.image)}
|
|
209
|
+
className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
|
|
210
|
+
aria-hidden
|
|
211
|
+
data-armed=""
|
|
212
|
+
data-sweeping={sweeping ? "" : undefined}
|
|
213
|
+
>
|
|
214
|
+
<rect
|
|
215
|
+
data-marquee-surface=""
|
|
216
|
+
x={-0.5}
|
|
217
|
+
y={-0.5}
|
|
218
|
+
width={stage.image.width}
|
|
219
|
+
height={stage.image.height}
|
|
220
|
+
fill="transparent"
|
|
221
|
+
className="pointer-events-auto cursor-crosshair"
|
|
222
|
+
onPointerDown={onPointerDown}
|
|
223
|
+
/>
|
|
224
|
+
</svg>
|
|
225
|
+
)}
|
|
226
|
+
<MarqueeRect rect={band} stroke={stroke} />
|
|
227
|
+
</>
|
|
228
|
+
);
|
|
229
|
+
}
|