@vitavision/stage2d 0.9.0 → 0.10.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 +29 -2
- package/dist/index.d.ts +703 -1
- package/dist/index.js +1788 -70
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/AreaSet.tsx +312 -0
- package/src/components/DraftShape.tsx +175 -0
- package/src/components/GridLayer.tsx +209 -0
- package/src/components/HeatmapLayer.tsx +211 -0
- package/src/components/PointSet.tsx +11 -36
- package/src/components/ShapeEditor.tsx +290 -0
- package/src/components/areaIndex.ts +361 -0
- package/src/components/gridEdges.ts +70 -0
- package/src/components/heatmapRaster.ts +84 -0
- package/src/components/labelLod.ts +90 -0
- package/src/components/polylineIndex.ts +4 -3
- package/src/components/shapeEdit.ts +232 -0
- package/src/components/useShapeDrag.ts +104 -0
- package/src/index.ts +61 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The edges of a detected lattice: which nodes are neighbours.
|
|
3
|
+
*
|
|
4
|
+
* A calibration detector returns its corners with integer lattice indices `(i, j)` and gaps
|
|
5
|
+
* where a corner was not found. The edges are not data: node `(i, j)` is joined to
|
|
6
|
+
* `(i + 1, j)` and to `(i, j + 1)` when both exist. This module computes them in O(n) with a
|
|
7
|
+
* hash of the indices. It imports neither React nor the DOM.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** What `latticeEdges` reads from each node. */
|
|
11
|
+
export interface LatticeNode {
|
|
12
|
+
/** The lattice index along the first axis. A non-integer index is not part of the lattice. */
|
|
13
|
+
i: number;
|
|
14
|
+
/** The lattice index along the second axis. A non-integer index is not part of the lattice. */
|
|
15
|
+
j: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The lattice axis an edge runs along: `"i"` joins `(i, j)` to `(i + 1, j)`, `"j"` joins `(i, j)` to `(i, j + 1)`. */
|
|
19
|
+
export type LatticeAxis = "i" | "j";
|
|
20
|
+
|
|
21
|
+
/** An edge between two neighbouring nodes. */
|
|
22
|
+
export interface LatticeEdge {
|
|
23
|
+
/** Position in the node array of the end with the lower index along `axis`. */
|
|
24
|
+
a: number;
|
|
25
|
+
/** Position in the node array of the end with the higher index along `axis`. */
|
|
26
|
+
b: number;
|
|
27
|
+
/** The axis it runs along. */
|
|
28
|
+
axis: LatticeAxis;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Indices past this magnitude are not hashed (the key must stay an exact integer). */
|
|
32
|
+
const LIMIT = 2 ** 25;
|
|
33
|
+
|
|
34
|
+
function key(i: number, j: number): number {
|
|
35
|
+
return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The edges of a lattice: every pair of nodes whose indices differ by one along exactly one
|
|
40
|
+
* axis.
|
|
41
|
+
*
|
|
42
|
+
* @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an
|
|
43
|
+
* integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the
|
|
44
|
+
* first one is the lattice's node there.
|
|
45
|
+
* @returns The edges, ordered by the position of `a`, then `"i"` before `"j"`.
|
|
46
|
+
*/
|
|
47
|
+
export function latticeEdges(nodes: ArrayLike<LatticeNode>): LatticeEdge[] {
|
|
48
|
+
const at = new Map<number, number>();
|
|
49
|
+
const valid = (n: LatticeNode) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;
|
|
50
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
51
|
+
const node = nodes[p]!;
|
|
52
|
+
if (!valid(node)) continue;
|
|
53
|
+
const k = key(node.i, node.j);
|
|
54
|
+
if (!at.has(k)) at.set(k, p);
|
|
55
|
+
}
|
|
56
|
+
const edges: LatticeEdge[] = [];
|
|
57
|
+
for (let p = 0; p < nodes.length; p++) {
|
|
58
|
+
const node = nodes[p]!;
|
|
59
|
+
if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;
|
|
60
|
+
if (node.i + 1 < LIMIT) {
|
|
61
|
+
const q = at.get(key(node.i + 1, node.j));
|
|
62
|
+
if (q !== undefined) edges.push({ a: p, b: q, axis: "i" });
|
|
63
|
+
}
|
|
64
|
+
if (node.j + 1 < LIMIT) {
|
|
65
|
+
const q = at.get(key(node.i, node.j + 1));
|
|
66
|
+
if (q !== undefined) edges.push({ a: p, b: q, axis: "j" });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return edges;
|
|
70
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scalar field to pixels: the colourising step of `HeatmapLayer`, pure so the cases that bite
|
|
3
|
+
* (NaN holes, a flat field, a value outside the range) are tested without a canvas.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ValuePlane } from "../api/mapValues";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A sequential colour map: a position in `[0, 1]` to an `[r, g, b]` colour, each channel
|
|
10
|
+
* 0 to 255. `@vitavision/charts`' `colormapRgb(name, t)` is one: `(t) => colormapRgb("viridis", t)`.
|
|
11
|
+
*/
|
|
12
|
+
export type Colormap = (t: number) => readonly [number, number, number];
|
|
13
|
+
|
|
14
|
+
/** A range of values mapped onto the colour map: `low` to its start, `high` to its end. */
|
|
15
|
+
export interface ValueRange {
|
|
16
|
+
/** The value drawn in the map's first colour. */
|
|
17
|
+
low: number;
|
|
18
|
+
/** The value drawn in the map's last colour. */
|
|
19
|
+
high: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */
|
|
23
|
+
const STEPS = 256;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The extent of a plane's finite values.
|
|
27
|
+
*
|
|
28
|
+
* @param plane - The plane.
|
|
29
|
+
* @param channel - Which of its channels. Defaults to the first.
|
|
30
|
+
* @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.
|
|
31
|
+
*/
|
|
32
|
+
export function planeRange(plane: ValuePlane, channel = 0): ValueRange | null {
|
|
33
|
+
if (!(channel >= 0 && channel < plane.channels)) return null;
|
|
34
|
+
const size = plane.width * plane.height;
|
|
35
|
+
const offset = channel * size;
|
|
36
|
+
let low = Infinity;
|
|
37
|
+
let high = -Infinity;
|
|
38
|
+
for (let k = 0; k < size; k++) {
|
|
39
|
+
const v = plane.values[offset + k]!;
|
|
40
|
+
if (!Number.isFinite(v)) continue;
|
|
41
|
+
if (v < low) low = v;
|
|
42
|
+
if (v > high) high = v;
|
|
43
|
+
}
|
|
44
|
+
return low <= high ? { low, high } : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Colour a plane through a colour map.
|
|
49
|
+
*
|
|
50
|
+
* Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered
|
|
51
|
+
* pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range
|
|
52
|
+
* (`high <= low`) draws every pixel in the map's first colour.
|
|
53
|
+
*
|
|
54
|
+
* @param plane - The plane.
|
|
55
|
+
* @param colormap - The colour map; sampled at 256 positions.
|
|
56
|
+
* @param range - What the map spans. Defaults to the extent of the channel's finite values.
|
|
57
|
+
* @param channel - Which channel to draw. Defaults to the first.
|
|
58
|
+
* @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.
|
|
59
|
+
*/
|
|
60
|
+
export function rasterizePlane(plane: ValuePlane, colormap: Colormap, range?: ValueRange, channel = 0): Uint8ClampedArray {
|
|
61
|
+
const size = plane.width * plane.height;
|
|
62
|
+
const out = new Uint8ClampedArray(size * 4);
|
|
63
|
+
if (!(channel >= 0 && channel < plane.channels)) return out;
|
|
64
|
+
const { low, high } = range ?? planeRange(plane, channel) ?? { low: 0, high: 0 };
|
|
65
|
+
const lut = new Uint8ClampedArray(STEPS * 3);
|
|
66
|
+
for (let s = 0; s < STEPS; s++) {
|
|
67
|
+
const [r, g, b] = colormap(s / (STEPS - 1));
|
|
68
|
+
lut[3 * s] = r;
|
|
69
|
+
lut[3 * s + 1] = g;
|
|
70
|
+
lut[3 * s + 2] = b;
|
|
71
|
+
}
|
|
72
|
+
const scale = high > low ? (STEPS - 1) / (high - low) : 0;
|
|
73
|
+
const offset = channel * size;
|
|
74
|
+
for (let k = 0; k < size; k++) {
|
|
75
|
+
const v = plane.values[offset + k]!;
|
|
76
|
+
if (!Number.isFinite(v)) continue;
|
|
77
|
+
const s = Math.min(STEPS - 1, Math.max(0, Math.round((v - low) * scale)));
|
|
78
|
+
out[4 * k] = lut[3 * s]!;
|
|
79
|
+
out[4 * k + 1] = lut[3 * s + 1]!;
|
|
80
|
+
out[4 * k + 2] = lut[3 * s + 2]!;
|
|
81
|
+
out[4 * k + 3] = 255;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which labels a layer draws: the level-of-detail rule of the overlay grammar
|
|
3
|
+
* (`docs/visual-language.md` §5), shared by `PointSet`, `AreaSet` and `GridLayer`.
|
|
4
|
+
*
|
|
5
|
+
* Labels are 11 px mono. They are shown only where their anchors are at least 24 screen
|
|
6
|
+
* pixels apart (so a zoomed-out scene shows none and a zoomed-in one shows all), at most 200 at
|
|
7
|
+
* a time, and only inside the viewport. The hovered and selected items always carry theirs.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { useMemo } from "react";
|
|
11
|
+
|
|
12
|
+
import { thinPoints } from "./pointIndex";
|
|
13
|
+
import { useStage } from "./stage/ImageStage";
|
|
14
|
+
import { useScreenPx } from "./stage/useScreenPx";
|
|
15
|
+
import type { Rect } from "./stage/view";
|
|
16
|
+
|
|
17
|
+
/** Labels need this much room between anchors, in screen pixels (overlay grammar §5). */
|
|
18
|
+
export const LABEL_SPACING = 24;
|
|
19
|
+
/** The most label elements drawn at once. */
|
|
20
|
+
export const MAX_LABELS = 200;
|
|
21
|
+
/** The most hovered-or-selected labels forced on regardless of spacing. */
|
|
22
|
+
export const MAX_FORCED_LABELS = 50;
|
|
23
|
+
|
|
24
|
+
/** The image-space rectangle on screen, or `null` before the viewport is measured. */
|
|
25
|
+
export function visibleRect(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }): Rect | null {
|
|
26
|
+
if (!(box.width > 0) || !(view.scale > 0)) return null;
|
|
27
|
+
return { x: -view.tx / view.scale, y: -view.ty / view.scale, width: box.width / view.scale, height: box.height / view.scale };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Choose the labels to draw.
|
|
32
|
+
*
|
|
33
|
+
* @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).
|
|
34
|
+
* @param forced - Anchors that always carry a label: the hovered and the selected.
|
|
35
|
+
* @param inView - Whether an anchor is inside the viewport.
|
|
36
|
+
* @returns The anchor indices to label: the forced ones first (at most 50), then the spaced
|
|
37
|
+
* ones, 200 in all.
|
|
38
|
+
*/
|
|
39
|
+
export function pickLabelIndices(spaced: readonly number[], forced: readonly number[], inView: (index: number) => boolean): number[] {
|
|
40
|
+
const shown = new Set<number>();
|
|
41
|
+
for (const i of forced) {
|
|
42
|
+
if (shown.size >= MAX_FORCED_LABELS) break;
|
|
43
|
+
if (i >= 0 && inView(i)) shown.add(i);
|
|
44
|
+
}
|
|
45
|
+
for (const i of spaced) {
|
|
46
|
+
if (shown.size >= MAX_LABELS) break;
|
|
47
|
+
if (inView(i)) shown.add(i);
|
|
48
|
+
}
|
|
49
|
+
return [...shown];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What `useLabelIndices` reads. */
|
|
53
|
+
export interface LabelAnchors {
|
|
54
|
+
/** Whether labels are shown at all. */
|
|
55
|
+
enabled: boolean;
|
|
56
|
+
/** Flat `[x0, y0, x1, y1, …]` anchors, in image coordinates. */
|
|
57
|
+
xy: ArrayLike<number>;
|
|
58
|
+
/** The anchors that have a label, in priority order. Pass a stable array. */
|
|
59
|
+
labelled: readonly number[];
|
|
60
|
+
/** The anchors that must carry theirs (hovered, selected) and have one. Pass a stable array. */
|
|
61
|
+
forced: readonly number[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The anchors to label at the stage's current zoom and viewport. The spacing depends on the
|
|
66
|
+
* zoom only, so panning does not reshuffle which anchors carry a label.
|
|
67
|
+
*
|
|
68
|
+
* @param anchors - See `LabelAnchors`.
|
|
69
|
+
* @returns Anchor indices.
|
|
70
|
+
*/
|
|
71
|
+
export function useLabelIndices({ enabled, xy, labelled, forced }: LabelAnchors): number[] {
|
|
72
|
+
const stage = useStage();
|
|
73
|
+
const unit = useScreenPx()(1);
|
|
74
|
+
const spacing = LABEL_SPACING * unit;
|
|
75
|
+
const spaced = useMemo(
|
|
76
|
+
() => (enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : []),
|
|
77
|
+
[enabled, labelled, xy, spacing],
|
|
78
|
+
);
|
|
79
|
+
return useMemo(() => {
|
|
80
|
+
if (!enabled || (spaced.length === 0 && forced.length === 0)) return [];
|
|
81
|
+
const view = visibleRect(stage.view, stage.box);
|
|
82
|
+
const inView = (i: number) => {
|
|
83
|
+
if (view === null) return true;
|
|
84
|
+
const x = xy[2 * i]!;
|
|
85
|
+
const y = xy[2 * i + 1]!;
|
|
86
|
+
return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;
|
|
87
|
+
};
|
|
88
|
+
return pickLabelIndices(spaced, forced, inView);
|
|
89
|
+
}, [enabled, spaced, forced, xy, stage.view, stage.box]);
|
|
90
|
+
}
|
|
@@ -254,7 +254,8 @@ export function polylineBounds(points: ArrayLike<number>): Rect | null {
|
|
|
254
254
|
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
-
|
|
257
|
+
/** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */
|
|
258
|
+
export function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {
|
|
258
259
|
const dx = bx - ax;
|
|
259
260
|
const dy = by - ay;
|
|
260
261
|
const len2 = dx * dx + dy * dy;
|
|
@@ -262,8 +263,8 @@ function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: numb
|
|
|
262
263
|
return { x: ax + t * dx, y: ay + t * dy };
|
|
263
264
|
}
|
|
264
265
|
|
|
265
|
-
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
|
|
266
|
-
function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
|
|
266
|
+
/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). Shared with `areaIndex.ts`. */
|
|
267
|
+
export function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
|
|
267
268
|
const xmin = r.x;
|
|
268
269
|
const xmax = r.x + r.width;
|
|
269
270
|
const ymin = r.y;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of editing a rotated rectangle or ellipse: eight handles, a rotation handle
|
|
3
|
+
* and an interior.
|
|
4
|
+
*
|
|
5
|
+
* A shape is its centre, its size and a rotation, so a resize can be done in the shape's own
|
|
6
|
+
* frame (where its sides are axis-aligned) and the opposite edge stays put whatever the
|
|
7
|
+
* rotation. Kept pure, so the cases that bite are tested without a pointer:
|
|
8
|
+
* - a handle dragged across the shape, or to a point far away;
|
|
9
|
+
* - a shape collapsed below the minimum size;
|
|
10
|
+
* - a rotation about the centre and not about a corner.
|
|
11
|
+
*
|
|
12
|
+
* Everything is in the stage's image coordinates. **Rotation is in radians, positive
|
|
13
|
+
* clockwise on screen** (image `y` points down), zero when the shape's width runs along `x`.
|
|
14
|
+
* A degrees-clockwise value, such as Konva's `rotation`, is `degrees * Math.PI / 180`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Point } from "./measureGeometry";
|
|
18
|
+
import type { RoiHandle } from "./roiEdit";
|
|
19
|
+
|
|
20
|
+
/** A rotated rectangle, or the ellipse inscribed in one. */
|
|
21
|
+
export interface RotatedShape {
|
|
22
|
+
/** Centre x, in image coordinates. */
|
|
23
|
+
cx: number;
|
|
24
|
+
/** Centre y, in image coordinates. */
|
|
25
|
+
cy: number;
|
|
26
|
+
/** Extent along the shape's own x axis: a rectangle's width, an ellipse's full axis `2·rx`. */
|
|
27
|
+
width: number;
|
|
28
|
+
/** Extent along the shape's own y axis: a rectangle's height, an ellipse's full axis `2·ry`. */
|
|
29
|
+
height: number;
|
|
30
|
+
/** Radians, clockwise on screen: the turn from the image's x axis to the shape's own. */
|
|
31
|
+
rotation: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A point of image space in the shape's own frame: origin at its centre, axes along its sides.
|
|
36
|
+
*
|
|
37
|
+
* @param shape - The shape.
|
|
38
|
+
* @param p - A point in image coordinates.
|
|
39
|
+
* @returns The point relative to the shape.
|
|
40
|
+
*/
|
|
41
|
+
export function toShapeFrame(shape: RotatedShape, p: Point): Point {
|
|
42
|
+
const c = Math.cos(shape.rotation);
|
|
43
|
+
const s = Math.sin(shape.rotation);
|
|
44
|
+
const dx = p.x - shape.cx;
|
|
45
|
+
const dy = p.y - shape.cy;
|
|
46
|
+
return { x: c * dx + s * dy, y: -s * dx + c * dy };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A point of the shape's own frame in image space; the inverse of `toShapeFrame`.
|
|
51
|
+
*
|
|
52
|
+
* @param shape - The shape.
|
|
53
|
+
* @param p - A point relative to the shape.
|
|
54
|
+
* @returns The point in image coordinates.
|
|
55
|
+
*/
|
|
56
|
+
export function fromShapeFrame(shape: RotatedShape, p: Point): Point {
|
|
57
|
+
const c = Math.cos(shape.rotation);
|
|
58
|
+
const s = Math.sin(shape.rotation);
|
|
59
|
+
return { x: shape.cx + c * p.x - s * p.y, y: shape.cy + s * p.x + c * p.y };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */
|
|
63
|
+
function handleDirection(handle: RoiHandle): Point {
|
|
64
|
+
return { x: handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0, y: handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0 };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Where a handle sits: a corner or the middle of a side, turned with the shape.
|
|
69
|
+
*
|
|
70
|
+
* @param shape - The shape.
|
|
71
|
+
* @param handle - The handle, by compass direction in the shape's own frame.
|
|
72
|
+
* @returns The handle's centre, in image coordinates.
|
|
73
|
+
*/
|
|
74
|
+
export function shapeHandlePoint(shape: RotatedShape, handle: RoiHandle): Point {
|
|
75
|
+
const d = handleDirection(handle);
|
|
76
|
+
return fromShapeFrame(shape, { x: (d.x * shape.width) / 2, y: (d.y * shape.height) / 2 });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Where the rotation handle sits: beyond the middle of the top side, along the shape's own
|
|
81
|
+
* up direction.
|
|
82
|
+
*
|
|
83
|
+
* @param shape - The shape.
|
|
84
|
+
* @param distance - How far past the top side, in image pixels. For a screen-constant handle,
|
|
85
|
+
* pass `useScreenPx()(css)`.
|
|
86
|
+
* @returns The handle's centre, in image coordinates.
|
|
87
|
+
*/
|
|
88
|
+
export function rotationHandlePoint(shape: RotatedShape, distance: number): Point {
|
|
89
|
+
return fromShapeFrame(shape, { x: 0, y: -shape.height / 2 - distance });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Drag a handle to `to`.
|
|
94
|
+
*
|
|
95
|
+
* The dragged side or corner follows the pointer in the shape's own frame and the opposite
|
|
96
|
+
* side or corner stays where it is in the image, which is what makes a handle feel attached.
|
|
97
|
+
* The shape does not flip when dragged through the opposite side: it stops at `minSize`.
|
|
98
|
+
*
|
|
99
|
+
* @param shape - The shape before the drag.
|
|
100
|
+
* @param handle - The handle being dragged.
|
|
101
|
+
* @param to - The pointer, in image coordinates.
|
|
102
|
+
* @param minSize - The smallest extent on either axis, in image pixels.
|
|
103
|
+
* @returns The resized shape: the same rotation, and the opposite side or corner unmoved.
|
|
104
|
+
*/
|
|
105
|
+
export function resizeShape(shape: RotatedShape, handle: RoiHandle, to: Point, minSize: number): RotatedShape {
|
|
106
|
+
const d = handleDirection(handle);
|
|
107
|
+
const u = toShapeFrame(shape, to);
|
|
108
|
+
let width = shape.width;
|
|
109
|
+
let height = shape.height;
|
|
110
|
+
let x = 0;
|
|
111
|
+
let y = 0;
|
|
112
|
+
if (d.x !== 0) {
|
|
113
|
+
// The fixed side is at `-d.x · width / 2`; the new extent runs from it to the pointer.
|
|
114
|
+
width = Math.max(minSize, d.x * u.x + shape.width / 2);
|
|
115
|
+
x = -d.x * (shape.width / 2) + (d.x * width) / 2;
|
|
116
|
+
}
|
|
117
|
+
if (d.y !== 0) {
|
|
118
|
+
height = Math.max(minSize, d.y * u.y + shape.height / 2);
|
|
119
|
+
y = -d.y * (shape.height / 2) + (d.y * height) / 2;
|
|
120
|
+
}
|
|
121
|
+
const centre = fromShapeFrame(shape, { x, y });
|
|
122
|
+
return { cx: centre.x, cy: centre.y, width, height, rotation: shape.rotation };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Turn the shape about its centre so that its rotation handle points at `to`.
|
|
127
|
+
*
|
|
128
|
+
* @param shape - The shape before the drag.
|
|
129
|
+
* @param to - The pointer, in image coordinates.
|
|
130
|
+
* @param snap - Round the rotation to a multiple of this many radians (Shift while dragging
|
|
131
|
+
* rounds to 15°). Defaults to no rounding.
|
|
132
|
+
* @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.
|
|
133
|
+
*/
|
|
134
|
+
export function rotateShape(shape: RotatedShape, to: Point, snap = 0): RotatedShape {
|
|
135
|
+
// The handle sits along the shape's own up direction, which is at angle `rotation - π/2`.
|
|
136
|
+
let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;
|
|
137
|
+
if (snap > 0) rotation = Math.round(rotation / snap) * snap;
|
|
138
|
+
return { ...shape, rotation: normalizeAngle(rotation) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Move the shape.
|
|
143
|
+
*
|
|
144
|
+
* @param shape - The shape.
|
|
145
|
+
* @param dx - Horizontal shift, in image pixels.
|
|
146
|
+
* @param dy - Vertical shift, in image pixels.
|
|
147
|
+
* @returns The moved shape.
|
|
148
|
+
*/
|
|
149
|
+
export function moveShape(shape: RotatedShape, dx: number, dy: number): RotatedShape {
|
|
150
|
+
return { ...shape, cx: shape.cx + dx, cy: shape.cy + dy };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* An angle as the equivalent one in `(-π, π]`.
|
|
155
|
+
*
|
|
156
|
+
* @param angle - Radians.
|
|
157
|
+
* @returns The angle in `(-π, π]`.
|
|
158
|
+
*/
|
|
159
|
+
export function normalizeAngle(angle: number): number {
|
|
160
|
+
const turn = 2 * Math.PI;
|
|
161
|
+
let a = angle % turn;
|
|
162
|
+
if (a > Math.PI) a -= turn;
|
|
163
|
+
else if (a <= -Math.PI) a += turn;
|
|
164
|
+
return a;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize
|
|
169
|
+
* cursors to the handle's direction on screen.
|
|
170
|
+
*
|
|
171
|
+
* @param handle - The handle.
|
|
172
|
+
* @param rotation - The shape's rotation, in radians.
|
|
173
|
+
* @returns A CSS `cursor` value.
|
|
174
|
+
*/
|
|
175
|
+
export function shapeHandleCursor(handle: RoiHandle, rotation: number): string {
|
|
176
|
+
const d = handleDirection(handle);
|
|
177
|
+
const angle = Math.atan2(d.y, d.x) + rotation;
|
|
178
|
+
const half = ((angle % Math.PI) + Math.PI) % Math.PI;
|
|
179
|
+
return ["ew-resize", "nwse-resize", "ns-resize", "nesw-resize"][Math.round(half / (Math.PI / 4)) % 4]!;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The shape for a rectangle given as an origin corner, a size and a rotation about that
|
|
184
|
+
* corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.
|
|
185
|
+
*
|
|
186
|
+
* @param corner - The corner the rotation is about, in image coordinates.
|
|
187
|
+
* @param width - Extent along the rotated x axis.
|
|
188
|
+
* @param height - Extent along the rotated y axis.
|
|
189
|
+
* @param rotation - Radians, clockwise on screen.
|
|
190
|
+
* @returns The same rectangle as a `RotatedShape`.
|
|
191
|
+
*/
|
|
192
|
+
export function shapeFromCorner(corner: Point, width: number, height: number, rotation: number): RotatedShape {
|
|
193
|
+
const c = Math.cos(rotation);
|
|
194
|
+
const s = Math.sin(rotation);
|
|
195
|
+
return {
|
|
196
|
+
cx: corner.x + (c * width - s * height) / 2,
|
|
197
|
+
cy: corner.y + (s * width + c * height) / 2,
|
|
198
|
+
width,
|
|
199
|
+
height,
|
|
200
|
+
rotation,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;
|
|
206
|
+
* the inverse of `shapeFromCorner`.
|
|
207
|
+
*
|
|
208
|
+
* @param shape - The shape.
|
|
209
|
+
* @returns The corner, in image coordinates.
|
|
210
|
+
*/
|
|
211
|
+
export function shapeCorner(shape: RotatedShape): Point {
|
|
212
|
+
return fromShapeFrame(shape, { x: -shape.width / 2, y: -shape.height / 2 });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).
|
|
217
|
+
*
|
|
218
|
+
* @param a - A shape, or `null`.
|
|
219
|
+
* @param b - A shape, or `null`.
|
|
220
|
+
* @param epsilon - The tolerance. Defaults to 1e-6.
|
|
221
|
+
* @returns `true` for two equal shapes, or two `null`s.
|
|
222
|
+
*/
|
|
223
|
+
export function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilon = 1e-6): boolean {
|
|
224
|
+
if (a === null || b === null) return a === b;
|
|
225
|
+
return (
|
|
226
|
+
Math.abs(a.cx - b.cx) < epsilon &&
|
|
227
|
+
Math.abs(a.cy - b.cy) < epsilon &&
|
|
228
|
+
Math.abs(a.width - b.width) < epsilon &&
|
|
229
|
+
Math.abs(a.height - b.height) < epsilon &&
|
|
230
|
+
Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon
|
|
231
|
+
);
|
|
232
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Moving a manual shape: a press on a selected item becomes image-space displacements, with the
|
|
3
|
+
* click-slop handling every selection UI needs (a press that barely moves is a click, not a
|
|
4
|
+
* drag).
|
|
5
|
+
*
|
|
6
|
+
* The layers resolve what is under the pointer (`onItemPress`); this turns the press that
|
|
7
|
+
* follows into a move. The app keeps the item's geometry, shows the displaced copy while the
|
|
8
|
+
* drag is in flight, and commits it at the end:
|
|
9
|
+
*
|
|
10
|
+
* <AreaSet items={items} selectedIds={selected}
|
|
11
|
+
* onItemPress={(id, event) => {
|
|
12
|
+
* if (!selected.has(id)) return select(id);
|
|
13
|
+
* startMove(event, {
|
|
14
|
+
* onMove: setOffset, // preview: draw the item shifted
|
|
15
|
+
* onEnd: (delta, moved) => moved ? commit(id, delta) : select(id),
|
|
16
|
+
* onCancel: () => setOffset(null),
|
|
17
|
+
* });
|
|
18
|
+
* }} />
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { useCallback } from "react";
|
|
22
|
+
|
|
23
|
+
import type { Point } from "./measureGeometry";
|
|
24
|
+
import type { StagePointerEvent } from "./stage/hitContext";
|
|
25
|
+
import { useStage } from "./stage/ImageStage";
|
|
26
|
+
import { useStageDrag } from "./stage/StageSurface";
|
|
27
|
+
|
|
28
|
+
/** What a shape drag does as the pointer moves and when it ends. Displacements are total, from the press. */
|
|
29
|
+
export interface ShapeDragHandlers {
|
|
30
|
+
/**
|
|
31
|
+
* Each move of the pointer once it has left the click slop: how far it is from where the
|
|
32
|
+
* press landed, in image pixels. Draw the shape shifted by it.
|
|
33
|
+
*/
|
|
34
|
+
onMove?: ((delta: Point, event: PointerEvent) => void) | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* The release. `moved` is whether the pointer ever left the click slop; when it did not,
|
|
37
|
+
* `delta` is `{ x: 0, y: 0 }` and the press was a click. Commit the shape shifted by `delta`.
|
|
38
|
+
*/
|
|
39
|
+
onEnd?: ((delta: Point, moved: boolean, event: PointerEvent) => void) | undefined;
|
|
40
|
+
/** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag: drop the preview. */
|
|
41
|
+
onCancel?: (() => void) | undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Options of the function `useShapeDrag` returns. */
|
|
45
|
+
export interface ShapeDragOptions {
|
|
46
|
+
/** How far the pointer may travel before the press is a drag, in screen pixels. Defaults to 3. */
|
|
47
|
+
slop?: number | undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The default click slop, in screen pixels (the stage's own). */
|
|
51
|
+
const DEFAULT_SLOP = 3;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Start moving a shape from a press, inside an `ImageStage`.
|
|
55
|
+
*
|
|
56
|
+
* Returns `start(event, handlers, options?)`. Call it from `onItemPress` of a layer with the
|
|
57
|
+
* press event: the press is claimed, so the stage does not pan, and the pointer is followed on
|
|
58
|
+
* `window` until it is released, whether or not it leaves the canvas. A touch tap reaches
|
|
59
|
+
* `onItemPress` on release, so there is nothing to follow: it ends at once as a click
|
|
60
|
+
* (`moved` false). Move a shape on touch with `ShapeEditor`'s handles or the app's own mode.
|
|
61
|
+
*
|
|
62
|
+
* @returns `start`.
|
|
63
|
+
*/
|
|
64
|
+
export function useShapeDrag(): (event: StagePointerEvent, handlers: ShapeDragHandlers, options?: ShapeDragOptions) => void {
|
|
65
|
+
const { toImage } = useStage();
|
|
66
|
+
const startDrag = useStageDrag();
|
|
67
|
+
return useCallback(
|
|
68
|
+
(event, handlers, options) => {
|
|
69
|
+
if (event.type !== "pointerdown") {
|
|
70
|
+
handlers.onEnd?.({ x: 0, y: 0 }, false, event.nativeEvent);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const slop = options?.slop ?? DEFAULT_SLOP;
|
|
74
|
+
const from = { x: event.clientX, y: event.clientY };
|
|
75
|
+
// Where the press landed, in image pixels: displacements are measured from it.
|
|
76
|
+
const press = toImage(from);
|
|
77
|
+
const displacement = (point: Point): Point => ({ x: point.x - press.x, y: point.y - press.y });
|
|
78
|
+
let moved = false;
|
|
79
|
+
startDrag(event, {
|
|
80
|
+
onMove: (point, e) => {
|
|
81
|
+
if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= slop) return;
|
|
82
|
+
moved = true;
|
|
83
|
+
handlers.onMove?.(displacement(point), e);
|
|
84
|
+
},
|
|
85
|
+
onEnd: (point, e) => handlers.onEnd?.(moved ? displacement(point) : { x: 0, y: 0 }, moved, e),
|
|
86
|
+
onCancel: handlers.onCancel,
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
[toImage, startDrag],
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Move flat points by a displacement.
|
|
95
|
+
*
|
|
96
|
+
* @param points - `[x0, y0, x1, y1, …]`.
|
|
97
|
+
* @param delta - The displacement, in the points' units.
|
|
98
|
+
* @returns A new array, `points` shifted.
|
|
99
|
+
*/
|
|
100
|
+
export function translatePoints(points: ArrayLike<number>, delta: Point): number[] {
|
|
101
|
+
const out = new Array<number>(points.length);
|
|
102
|
+
for (let i = 0; i < points.length; i++) out[i] = points[i]! + (i % 2 === 0 ? delta.x : delta.y);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -161,6 +161,67 @@ export {
|
|
|
161
161
|
type PointIndexOptions,
|
|
162
162
|
type PointItem,
|
|
163
163
|
} from "./components/pointIndex";
|
|
164
|
+
export {
|
|
165
|
+
AreaSet,
|
|
166
|
+
type AreaSetItem,
|
|
167
|
+
type AreaSetProps,
|
|
168
|
+
} from "./components/AreaSet";
|
|
169
|
+
export {
|
|
170
|
+
areaCentre,
|
|
171
|
+
areaPath,
|
|
172
|
+
areasInRect,
|
|
173
|
+
buildAreaIndex,
|
|
174
|
+
nearestArea,
|
|
175
|
+
pointInPolygon,
|
|
176
|
+
type Area,
|
|
177
|
+
type AreaHit,
|
|
178
|
+
type AreaId,
|
|
179
|
+
type AreaIndex,
|
|
180
|
+
} from "./components/areaIndex";
|
|
181
|
+
export {
|
|
182
|
+
GridLayer,
|
|
183
|
+
type GridEdgeStyle,
|
|
184
|
+
type GridLayerProps,
|
|
185
|
+
type GridNode,
|
|
186
|
+
} from "./components/GridLayer";
|
|
187
|
+
export { latticeEdges, type LatticeAxis, type LatticeEdge, type LatticeNode } from "./components/gridEdges";
|
|
188
|
+
export {
|
|
189
|
+
HeatmapLayer,
|
|
190
|
+
type HeatmapLayerBaseProps,
|
|
191
|
+
type HeatmapLayerProps,
|
|
192
|
+
type HeatmapPlaneProps,
|
|
193
|
+
type HeatmapRgbaProps,
|
|
194
|
+
} from "./components/HeatmapLayer";
|
|
195
|
+
export { planeRange, rasterizePlane, type Colormap, type ValueRange } from "./components/heatmapRaster";
|
|
196
|
+
export { ShapeEditor, type ShapeEditorProps } from "./components/ShapeEditor";
|
|
197
|
+
export {
|
|
198
|
+
fromShapeFrame,
|
|
199
|
+
moveShape,
|
|
200
|
+
normalizeAngle,
|
|
201
|
+
resizeShape,
|
|
202
|
+
rotateShape,
|
|
203
|
+
rotationHandlePoint,
|
|
204
|
+
sameShape,
|
|
205
|
+
shapeCorner,
|
|
206
|
+
shapeFromCorner,
|
|
207
|
+
shapeHandleCursor,
|
|
208
|
+
shapeHandlePoint,
|
|
209
|
+
toShapeFrame,
|
|
210
|
+
type RotatedShape,
|
|
211
|
+
} from "./components/shapeEdit";
|
|
212
|
+
export {
|
|
213
|
+
DraftShape,
|
|
214
|
+
MarqueeRect,
|
|
215
|
+
type DraftShapeProps,
|
|
216
|
+
type DraftShapeSpec,
|
|
217
|
+
type MarqueeRectProps,
|
|
218
|
+
} from "./components/DraftShape";
|
|
219
|
+
export {
|
|
220
|
+
translatePoints,
|
|
221
|
+
useShapeDrag,
|
|
222
|
+
type ShapeDragHandlers,
|
|
223
|
+
type ShapeDragOptions,
|
|
224
|
+
} from "./components/useShapeDrag";
|
|
164
225
|
export { MARKER_SHAPES, circlePath, type BuiltinMarkerKind, type MarkerShape } from "./components/markerShapes";
|
|
165
226
|
export {
|
|
166
227
|
ROI_HANDLES,
|