@vitavision/stage2d 0.6.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/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +99 -0
- package/dist/index.d.ts +712 -0
- package/dist/index.js +1559 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -0
- package/src/api/mapValues.ts +127 -0
- package/src/components/MeasureOverlay.tsx +353 -0
- package/src/components/ZoomPanCanvas.tsx +314 -0
- package/src/components/measureGeometry.ts +234 -0
- package/src/components/stage/ImageStage.tsx +594 -0
- package/src/components/stage/StageToolbar.tsx +254 -0
- package/src/components/stage/view.ts +319 -0
- package/src/index.ts +97 -0
- package/src/styles.css +7 -0
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A vector overlay layer for measurement primitives, drawn in source-image pixel
|
|
3
|
+
* coordinates.
|
|
4
|
+
*
|
|
5
|
+
* Meant to sit as one of the transformed children inside `ZoomPanCanvas`, alongside the
|
|
6
|
+
* image itself and any raster layers (a mask, a false-colour value plane). Because the
|
|
7
|
+
* whole stack is transformed together (see `ZoomPanCanvas`'s own docs), a caliper box
|
|
8
|
+
* drawn here stays registered with the pixel it measures at any zoom or pan — the overlay
|
|
9
|
+
* never touches the DOM to find out where it is; it is told, in `nativeWidth` ×
|
|
10
|
+
* `nativeHeight` pixel coordinates, via `primitives`.
|
|
11
|
+
*
|
|
12
|
+
* This component holds **no app state**: no fetch, no selection, no hover tracking. It is a
|
|
13
|
+
* pure function of its props, on purpose — the app decides what a "caliper box" or a
|
|
14
|
+
* "detected edge" *is*; this only knows how to draw one. The one piece of arithmetic it
|
|
15
|
+
* owns is `strokeScale` compensation (see `measureGeometry.ts`'s `strokeWidthFor`), because
|
|
16
|
+
* getting that wrong is invisible on screen until someone zooms in and a "1px" edge marker
|
|
17
|
+
* has silently become 8px wide.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { imageViewBox } from "./stage/view";
|
|
21
|
+
import { arcPath, arrowHeadPoints, caliperArrow, caliperCorners, crossSegments, dimensionGeometry, polygonPath, strokeWidthFor } from "./measureGeometry";
|
|
22
|
+
import { cn, toneColor, type MeasureTone } from "@vitavision/ui";
|
|
23
|
+
|
|
24
|
+
export type { MeasureTone };
|
|
25
|
+
|
|
26
|
+
/** A marked location: a dot, or a cross for a subpixel edge. */
|
|
27
|
+
export interface PointPrimitive {
|
|
28
|
+
/** Discriminant. */
|
|
29
|
+
kind: "point";
|
|
30
|
+
/** Image x of the point. */
|
|
31
|
+
x: number;
|
|
32
|
+
/** Image y of the point. */
|
|
33
|
+
y: number;
|
|
34
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
35
|
+
tone?: MeasureTone;
|
|
36
|
+
/** Native-pixel radius of the dot. Ignored when `cross` is set. */
|
|
37
|
+
radius?: number;
|
|
38
|
+
/** Drawn as a cross instead of a dot — the usual mark for a subpixel edge location. */
|
|
39
|
+
cross?: boolean;
|
|
40
|
+
/** Text drawn just above the mark. */
|
|
41
|
+
label?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A straight line between two image points. */
|
|
45
|
+
export interface SegmentPrimitive {
|
|
46
|
+
/** Discriminant. */
|
|
47
|
+
kind: "segment";
|
|
48
|
+
/** Image x of the first end. */
|
|
49
|
+
x1: number;
|
|
50
|
+
/** Image y of the first end. */
|
|
51
|
+
y1: number;
|
|
52
|
+
/** Image x of the second end. */
|
|
53
|
+
x2: number;
|
|
54
|
+
/** Image y of the second end. */
|
|
55
|
+
y2: number;
|
|
56
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
57
|
+
tone?: MeasureTone;
|
|
58
|
+
/** A short dash pattern, e.g. for a fitted line shown against its inlier points. */
|
|
59
|
+
dashed?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A circle — a fitted bore, a tolerance ring. */
|
|
63
|
+
export interface CirclePrimitive {
|
|
64
|
+
/** Discriminant. */
|
|
65
|
+
kind: "circle";
|
|
66
|
+
/** Image x of the centre. */
|
|
67
|
+
cx: number;
|
|
68
|
+
/** Image y of the centre. */
|
|
69
|
+
cy: number;
|
|
70
|
+
/** Radius, in image pixels. */
|
|
71
|
+
r: number;
|
|
72
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
73
|
+
tone?: MeasureTone;
|
|
74
|
+
/** Filled rather than stroked — rare, but a small confidence disc wants it. */
|
|
75
|
+
filled?: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A circular arc, swept forward (clockwise on screen) from `startAngle` to `endAngle`. */
|
|
79
|
+
export interface ArcPrimitive {
|
|
80
|
+
/** Discriminant. */
|
|
81
|
+
kind: "arc";
|
|
82
|
+
/** Image x of the centre. */
|
|
83
|
+
cx: number;
|
|
84
|
+
/** Image y of the centre. */
|
|
85
|
+
cy: number;
|
|
86
|
+
/** Radius, in image pixels. */
|
|
87
|
+
r: number;
|
|
88
|
+
/** Radians. `x = cx + r·cos(a)`, `y = cy + r·sin(a)` — clockwise on screen. */
|
|
89
|
+
startAngle: number;
|
|
90
|
+
/** Radians, same convention as `startAngle`. A full turn past it draws a whole circle. */
|
|
91
|
+
endAngle: number;
|
|
92
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
93
|
+
tone?: MeasureTone;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A caliper search box: a rotated rectangle with an arrow along its scan direction. */
|
|
97
|
+
export interface CaliperPrimitive {
|
|
98
|
+
/** Discriminant. */
|
|
99
|
+
kind: "caliper";
|
|
100
|
+
/** Image x of the box centre. */
|
|
101
|
+
cx: number;
|
|
102
|
+
/** Image y of the box centre. */
|
|
103
|
+
cy: number;
|
|
104
|
+
/** Along the box's own measurement axis. */
|
|
105
|
+
width: number;
|
|
106
|
+
/** Perpendicular to the measurement axis — the search span. */
|
|
107
|
+
height: number;
|
|
108
|
+
/** Radians, the box's own rotation (and its measurement direction). */
|
|
109
|
+
angle: number;
|
|
110
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
111
|
+
tone?: MeasureTone;
|
|
112
|
+
/** Draws the direction arrow along the box's +x axis. Defaults to on. */
|
|
113
|
+
showDirection?: boolean;
|
|
114
|
+
/** Text drawn at the box centre. */
|
|
115
|
+
label?: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A dimension annotation: extension lines, an offset dimension line, and its value as text. */
|
|
119
|
+
export interface DimensionPrimitive {
|
|
120
|
+
/** Discriminant. */
|
|
121
|
+
kind: "dimension";
|
|
122
|
+
/** Image x of the first measured point. */
|
|
123
|
+
x1: number;
|
|
124
|
+
/** Image y of the first measured point. */
|
|
125
|
+
y1: number;
|
|
126
|
+
/** Image x of the second measured point. */
|
|
127
|
+
x2: number;
|
|
128
|
+
/** Image y of the second measured point. */
|
|
129
|
+
y2: number;
|
|
130
|
+
/** The measured value as text, drawn along the dimension line. */
|
|
131
|
+
label: string;
|
|
132
|
+
/** Verdict colour. Defaults to the neutral tone. */
|
|
133
|
+
tone?: MeasureTone;
|
|
134
|
+
/** Native pixels the dimension line sits off the measured span. Defaults to 16. */
|
|
135
|
+
offset?: number;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Anything `MeasureOverlay` can draw, discriminated by `kind`. */
|
|
139
|
+
export type MeasurePrimitive =
|
|
140
|
+
| PointPrimitive
|
|
141
|
+
| SegmentPrimitive
|
|
142
|
+
| CirclePrimitive
|
|
143
|
+
| ArcPrimitive
|
|
144
|
+
| CaliperPrimitive
|
|
145
|
+
| DimensionPrimitive;
|
|
146
|
+
|
|
147
|
+
const DEFAULT_LABEL_SIZE = 11;
|
|
148
|
+
const DEFAULT_POINT_RADIUS = 3;
|
|
149
|
+
const DEFAULT_CROSS_SIZE = 5;
|
|
150
|
+
const DEFAULT_DIMENSION_OFFSET = 16;
|
|
151
|
+
|
|
152
|
+
/** Props of `MeasureOverlay`. */
|
|
153
|
+
export interface MeasureOverlayProps {
|
|
154
|
+
/** The source image's pixel width — the overlay's `viewBox`, and every primitive's frame. */
|
|
155
|
+
nativeWidth: number;
|
|
156
|
+
/** The source image's pixel height. */
|
|
157
|
+
nativeHeight: number;
|
|
158
|
+
/** What to draw, in image pixel coordinates, bottom to top. */
|
|
159
|
+
primitives: MeasurePrimitive[];
|
|
160
|
+
/**
|
|
161
|
+
* The combined image-pixel → screen-pixel scale currently in effect, so a stroke or a
|
|
162
|
+
* label declared at "1 screen pixel" stays that size regardless of zoom. Inside an
|
|
163
|
+
* `ImageStage` (which lays the overlay out at exactly `nativeWidth` × `nativeHeight` CSS
|
|
164
|
+
* pixels) this is simply `useStage().view.scale`. See `strokeWidthFor`.
|
|
165
|
+
*/
|
|
166
|
+
strokeScale: number;
|
|
167
|
+
/** Merged onto the `<svg>` with `cn`. */
|
|
168
|
+
className?: string;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* A vector overlay of measurement primitives — points, segments, circles, arcs, caliper
|
|
173
|
+
* boxes, dimensions — drawn in source-image pixel coordinates.
|
|
174
|
+
*
|
|
175
|
+
* Place it as a layer inside `ImageStage` so it moves with the image. It is a pure function
|
|
176
|
+
* of its props and decorative to assistive technology (`aria-hidden`), so a result drawn
|
|
177
|
+
* only here must also be stated in text.
|
|
178
|
+
*/
|
|
179
|
+
export function MeasureOverlay({
|
|
180
|
+
nativeWidth,
|
|
181
|
+
nativeHeight,
|
|
182
|
+
primitives,
|
|
183
|
+
strokeScale,
|
|
184
|
+
className,
|
|
185
|
+
}: MeasureOverlayProps) {
|
|
186
|
+
const hairline = strokeWidthFor(strokeScale, 1);
|
|
187
|
+
const thick = strokeWidthFor(strokeScale, 1.5);
|
|
188
|
+
const labelSize = strokeWidthFor(strokeScale, DEFAULT_LABEL_SIZE);
|
|
189
|
+
|
|
190
|
+
return (
|
|
191
|
+
<svg
|
|
192
|
+
role="presentation"
|
|
193
|
+
aria-hidden
|
|
194
|
+
viewBox={imageViewBox({ width: nativeWidth, height: nativeHeight })}
|
|
195
|
+
preserveAspectRatio="none"
|
|
196
|
+
className={cn("pointer-events-none absolute inset-0 h-full w-full overflow-visible", className)}
|
|
197
|
+
>
|
|
198
|
+
{primitives.map((primitive, index) => (
|
|
199
|
+
<Primitive
|
|
200
|
+
// Primitives carry no identity and hold no state; a position is the only key.
|
|
201
|
+
// eslint-disable-next-line @eslint-react/no-array-index-key
|
|
202
|
+
key={index}
|
|
203
|
+
primitive={primitive}
|
|
204
|
+
hairline={hairline}
|
|
205
|
+
thick={thick}
|
|
206
|
+
labelSize={labelSize}
|
|
207
|
+
strokeScale={strokeScale}
|
|
208
|
+
/>
|
|
209
|
+
))}
|
|
210
|
+
</svg>
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function Primitive({
|
|
215
|
+
primitive,
|
|
216
|
+
hairline,
|
|
217
|
+
thick,
|
|
218
|
+
labelSize,
|
|
219
|
+
strokeScale,
|
|
220
|
+
}: {
|
|
221
|
+
primitive: MeasurePrimitive;
|
|
222
|
+
hairline: number;
|
|
223
|
+
thick: number;
|
|
224
|
+
labelSize: number;
|
|
225
|
+
strokeScale: number;
|
|
226
|
+
}) {
|
|
227
|
+
const colour = toneColor(primitive.tone);
|
|
228
|
+
|
|
229
|
+
switch (primitive.kind) {
|
|
230
|
+
case "point": {
|
|
231
|
+
if (primitive.cross) {
|
|
232
|
+
const size = strokeWidthFor(strokeScale, DEFAULT_CROSS_SIZE);
|
|
233
|
+
const [h, v] = crossSegments(primitive.x, primitive.y, size);
|
|
234
|
+
return (
|
|
235
|
+
<g stroke={colour} strokeWidth={hairline}>
|
|
236
|
+
<line x1={h[0].x} y1={h[0].y} x2={h[1].x} y2={h[1].y} />
|
|
237
|
+
<line x1={v[0].x} y1={v[0].y} x2={v[1].x} y2={v[1].y} />
|
|
238
|
+
<Label x={primitive.x} y={primitive.y - size - 2} text={primitive.label} colour={colour} size={labelSize} />
|
|
239
|
+
</g>
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
const radius = strokeWidthFor(strokeScale, primitive.radius ?? DEFAULT_POINT_RADIUS);
|
|
243
|
+
return (
|
|
244
|
+
<g>
|
|
245
|
+
<circle cx={primitive.x} cy={primitive.y} r={radius} fill={colour} />
|
|
246
|
+
<Label x={primitive.x} y={primitive.y - radius - 2} text={primitive.label} colour={colour} size={labelSize} />
|
|
247
|
+
</g>
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
case "segment":
|
|
252
|
+
return (
|
|
253
|
+
<line
|
|
254
|
+
x1={primitive.x1}
|
|
255
|
+
y1={primitive.y1}
|
|
256
|
+
x2={primitive.x2}
|
|
257
|
+
y2={primitive.y2}
|
|
258
|
+
stroke={colour}
|
|
259
|
+
strokeWidth={hairline}
|
|
260
|
+
strokeDasharray={primitive.dashed ? `${hairline * 4} ${hairline * 3}` : undefined}
|
|
261
|
+
/>
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
case "circle":
|
|
265
|
+
return (
|
|
266
|
+
<circle
|
|
267
|
+
cx={primitive.cx}
|
|
268
|
+
cy={primitive.cy}
|
|
269
|
+
r={primitive.r}
|
|
270
|
+
fill={primitive.filled ? colour : "none"}
|
|
271
|
+
stroke={primitive.filled ? "none" : colour}
|
|
272
|
+
strokeWidth={hairline}
|
|
273
|
+
/>
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
case "arc":
|
|
277
|
+
return (
|
|
278
|
+
<path
|
|
279
|
+
d={arcPath(primitive.cx, primitive.cy, primitive.r, primitive.startAngle, primitive.endAngle)}
|
|
280
|
+
fill="none"
|
|
281
|
+
stroke={colour}
|
|
282
|
+
strokeWidth={hairline}
|
|
283
|
+
strokeLinecap="round"
|
|
284
|
+
/>
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
case "caliper": {
|
|
288
|
+
const corners = caliperCorners(primitive.cx, primitive.cy, primitive.width, primitive.height, primitive.angle);
|
|
289
|
+
const arrow = caliperArrow(primitive.cx, primitive.cy, primitive.width, primitive.angle);
|
|
290
|
+
const head = arrowHeadPoints(arrow.to, primitive.angle, strokeWidthFor(strokeScale, 4));
|
|
291
|
+
return (
|
|
292
|
+
<g>
|
|
293
|
+
<path d={polygonPath(corners)} fill="none" stroke={colour} strokeWidth={hairline} />
|
|
294
|
+
{primitive.showDirection !== false && (
|
|
295
|
+
<g stroke={colour} strokeWidth={thick} strokeLinecap="round" strokeLinejoin="round" fill="none">
|
|
296
|
+
<line x1={arrow.from.x} y1={arrow.from.y} x2={arrow.to.x} y2={arrow.to.y} />
|
|
297
|
+
<polyline points={head.map((p) => `${p.x},${p.y}`).join(" ")} />
|
|
298
|
+
</g>
|
|
299
|
+
)}
|
|
300
|
+
<Label x={primitive.cx} y={primitive.cy} text={primitive.label} colour={colour} size={labelSize} />
|
|
301
|
+
</g>
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
case "dimension": {
|
|
306
|
+
const offset = primitive.offset ?? DEFAULT_DIMENSION_OFFSET;
|
|
307
|
+
const geometry = dimensionGeometry(primitive.x1, primitive.y1, primitive.x2, primitive.y2, offset);
|
|
308
|
+
return (
|
|
309
|
+
<g stroke={colour} strokeWidth={hairline}>
|
|
310
|
+
<line x1={geometry.extensionLine1[0].x} y1={geometry.extensionLine1[0].y} x2={geometry.extensionLine1[1].x} y2={geometry.extensionLine1[1].y} opacity={0.5} />
|
|
311
|
+
<line x1={geometry.extensionLine2[0].x} y1={geometry.extensionLine2[0].y} x2={geometry.extensionLine2[1].x} y2={geometry.extensionLine2[1].y} opacity={0.5} />
|
|
312
|
+
<line x1={geometry.dimensionLine[0].x} y1={geometry.dimensionLine[0].y} x2={geometry.dimensionLine[1].x} y2={geometry.dimensionLine[1].y} />
|
|
313
|
+
<text
|
|
314
|
+
x={geometry.labelAnchor.x}
|
|
315
|
+
y={geometry.labelAnchor.y}
|
|
316
|
+
fontSize={labelSize}
|
|
317
|
+
fill={colour}
|
|
318
|
+
stroke="none"
|
|
319
|
+
textAnchor="middle"
|
|
320
|
+
dominantBaseline="text-after-edge"
|
|
321
|
+
transform={`rotate(${geometry.angleDegrees} ${geometry.labelAnchor.x} ${geometry.labelAnchor.y})`}
|
|
322
|
+
>
|
|
323
|
+
{primitive.label}
|
|
324
|
+
</text>
|
|
325
|
+
</g>
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
default:
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function Label({
|
|
335
|
+
x,
|
|
336
|
+
y,
|
|
337
|
+
text,
|
|
338
|
+
colour,
|
|
339
|
+
size,
|
|
340
|
+
}: {
|
|
341
|
+
x: number;
|
|
342
|
+
y: number;
|
|
343
|
+
text?: string | undefined;
|
|
344
|
+
colour: string;
|
|
345
|
+
size: number;
|
|
346
|
+
}) {
|
|
347
|
+
if (!text) return null;
|
|
348
|
+
return (
|
|
349
|
+
<text x={x} y={y} fontSize={size} fill={colour} textAnchor="middle" dominantBaseline="text-after-edge">
|
|
350
|
+
{text}
|
|
351
|
+
</text>
|
|
352
|
+
);
|
|
353
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pannable, zoomable frame that transforms **everything stacked inside it together**.
|
|
3
|
+
*
|
|
4
|
+
* Deprecated: use `ImageStage` (`components/stage`). Two limits of this component turned out
|
|
5
|
+
* to be load-bearing rather than incidental, and neither can be lifted without changing what
|
|
6
|
+
* its props mean:
|
|
7
|
+
*
|
|
8
|
+
* - it scales its layers by the *frame's* size, so every consumer must lay the frame out
|
|
9
|
+
* at the source aspect ratio and the one that forgot drew its overlays stretched against
|
|
10
|
+
* a letterboxed photograph — layers drifting apart on window resize, invisibly, at
|
|
11
|
+
* every window size but one;
|
|
12
|
+
* - it calls `setPointerCapture` on every `pointerdown` to pan, so an interactive child —
|
|
13
|
+
* a draggable ROI handle, a clickable contour — cannot exist inside it, and consumers
|
|
14
|
+
* mounted those layers *outside* the transform, where they stopped moving with the image.
|
|
15
|
+
*
|
|
16
|
+
* `ImageStage` lays the stage out at the image's own pixel size (so registration is
|
|
17
|
+
* structural, not a caller's responsibility), treats `scale` as CSS pixels per image pixel
|
|
18
|
+
* (so "100%" is a value and zooming out past fit is expressible), and pans only when a
|
|
19
|
+
* gesture is unclaimed. This component stays exported and unchanged for consumers that have
|
|
20
|
+
* not migrated.
|
|
21
|
+
*
|
|
22
|
+
* A result viewer over a stack -- a photograph, an anomaly map, a model's segmentation, a
|
|
23
|
+
* measurement overlay drawn in source-image pixel coordinates (see `MeasureOverlay`) -- and
|
|
24
|
+
* the layers only stay registered with each other if one transform moves all of them.
|
|
25
|
+
* Transforming each layer separately would drift them apart at the exact zoom level where a
|
|
26
|
+
* reader is trying to judge whether a caliper box lands on the edge it claims to measure.
|
|
27
|
+
*
|
|
28
|
+
* Zoom bottoms out at 1x and snaps the pan back to centre there, so there is always a
|
|
29
|
+
* gesture that gets you unlost — and zoom 1 *is* fit-to-window, because the canvas is laid
|
|
30
|
+
* out inside `max-h-full max-w-full` with the source aspect ratio. That is why the
|
|
31
|
+
* double-click gesture toggles fit against **1:1 native pixels** rather than "fitting":
|
|
32
|
+
* fitting is where you already are, and the thing a reader actually wants at a defect, or
|
|
33
|
+
* at a subpixel edge, is the sensor's own resolution with no resampling between them and it.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
|
37
|
+
import type { CSSProperties, ReactNode } from "react";
|
|
38
|
+
|
|
39
|
+
import { cn } from "@vitavision/ui";
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `ZoomPanCanvas`'s view: `translate(x, y) scale(zoom)` about the frame's centre.
|
|
43
|
+
* `ImageStage` uses `StageView` instead.
|
|
44
|
+
*/
|
|
45
|
+
export interface View {
|
|
46
|
+
/** Magnification relative to fit; `1` is fit-to-window. */
|
|
47
|
+
zoom: number;
|
|
48
|
+
/** Horizontal pan, in CSS pixels, from the centred position. */
|
|
49
|
+
x: number;
|
|
50
|
+
/** Vertical pan, in CSS pixels, from the centred position. */
|
|
51
|
+
y: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Zoom 1, centred — which is fit-to-window, given how the canvas is laid out. */
|
|
55
|
+
export const RESET_VIEW: View = { zoom: 1, x: 0, y: 0 };
|
|
56
|
+
|
|
57
|
+
/** The lowest zoom `zoomAt` allows: fit. */
|
|
58
|
+
export const MIN_ZOOM = 1;
|
|
59
|
+
/** The highest zoom `zoomAt` allows. */
|
|
60
|
+
export const MAX_ZOOM = 12;
|
|
61
|
+
const ZOOM_SENSITIVITY = 0.0015;
|
|
62
|
+
|
|
63
|
+
/** The zoom past which a preview tier stops being enough and real pixels are wanted. */
|
|
64
|
+
export const FULL_TIER_ZOOM = 2;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Zoom by `factor` about a point, keeping whatever is under that point where it is.
|
|
68
|
+
*
|
|
69
|
+
* Pure, and exported, because it is the one piece of arithmetic here that can be silently
|
|
70
|
+
* wrong: a centre-anchored zoom looks correct until someone tries to magnify a defect in a
|
|
71
|
+
* corner, at which point every wheel notch has to be undone with a drag.
|
|
72
|
+
*
|
|
73
|
+
* The transform is `translate(t) scale(z)` about the box's centre, so a content point `c`
|
|
74
|
+
* lands at `p = c·z + t`. Holding `c` fixed while `z` becomes `z'` gives
|
|
75
|
+
* `t' = p − (p − t)·z'/z`, with `p` measured from the centre.
|
|
76
|
+
*/
|
|
77
|
+
export function zoomAt(
|
|
78
|
+
view: View,
|
|
79
|
+
pointer: { x: number; y: number },
|
|
80
|
+
rect: { left: number; top: number; width: number; height: number },
|
|
81
|
+
factor: number,
|
|
82
|
+
): View {
|
|
83
|
+
const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);
|
|
84
|
+
// Bottoming out is a reset: at 1x the content fills the frame, so any offset is a way to
|
|
85
|
+
// be lost with no visible handle to get back.
|
|
86
|
+
if (zoom === MIN_ZOOM) return RESET_VIEW;
|
|
87
|
+
|
|
88
|
+
const px = pointer.x - rect.left - rect.width / 2;
|
|
89
|
+
const py = pointer.y - rect.top - rect.height / 2;
|
|
90
|
+
const ratio = zoom / view.zoom;
|
|
91
|
+
return {
|
|
92
|
+
zoom,
|
|
93
|
+
x: px - (px - view.x) * ratio,
|
|
94
|
+
y: py - (py - view.y) * ratio,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Where a pointer is over the *content*, as fractions of the frame, or `null` outside it.
|
|
100
|
+
*
|
|
101
|
+
* The inverse of the transform `zoomAt` maintains, and pure for the same reason: this is
|
|
102
|
+
* what turns a cursor position into an index into a value plane or a source-pixel
|
|
103
|
+
* coordinate, and it is wrong in a way nothing on screen would reveal — a readout that is
|
|
104
|
+
* confidently off by a pan offset looks exactly like a readout that works.
|
|
105
|
+
*
|
|
106
|
+
* The content fills the frame at zoom 1 by construction (the canvas is laid out with the
|
|
107
|
+
* source aspect ratio), so `[0, 1)` over the frame *is* `[0, 1)` over the image, with no
|
|
108
|
+
* letterbox correction to reconstruct.
|
|
109
|
+
*/
|
|
110
|
+
export function contentUnder(
|
|
111
|
+
view: View,
|
|
112
|
+
pointer: { clientX: number; clientY: number },
|
|
113
|
+
rect: { left: number; top: number; width: number; height: number },
|
|
114
|
+
): { u: number; v: number } | null {
|
|
115
|
+
const px = pointer.clientX - rect.left - rect.width / 2;
|
|
116
|
+
const py = pointer.clientY - rect.top - rect.height / 2;
|
|
117
|
+
const u = (px - view.x) / view.zoom / rect.width + 0.5;
|
|
118
|
+
const v = (py - view.y) / view.zoom / rect.height + 0.5;
|
|
119
|
+
if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;
|
|
120
|
+
return { u, v };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The zoom at which one source pixel covers one CSS pixel.
|
|
125
|
+
*
|
|
126
|
+
* Clamped, so an image smaller than its frame reports 1: there are no further pixels to
|
|
127
|
+
* reveal, and pretending otherwise would magnify the resampler rather than the sensor.
|
|
128
|
+
*/
|
|
129
|
+
export function nativeZoomFor(sourceWidth: number, boxWidth: number): number {
|
|
130
|
+
if (!(sourceWidth > 0) || !(boxWidth > 0)) return FULL_TIER_ZOOM;
|
|
131
|
+
return clamp(sourceWidth / boxWidth, MIN_ZOOM, MAX_ZOOM);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function clamp(value: number, low: number, high: number): number {
|
|
135
|
+
return Math.min(high, Math.max(low, value));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Props of `ZoomPanCanvas`.
|
|
140
|
+
*
|
|
141
|
+
* @deprecated Use `ImageStage` and `ImageStageProps`.
|
|
142
|
+
*/
|
|
143
|
+
export interface ZoomPanCanvasProps {
|
|
144
|
+
/** The current view (controlled). */
|
|
145
|
+
view: View;
|
|
146
|
+
/** Called with every view change — wheel, drag, double-click, the "Fit" button. */
|
|
147
|
+
onView: (view: View) => void;
|
|
148
|
+
/** The stacked layers, each filling the frame. */
|
|
149
|
+
children: ReactNode;
|
|
150
|
+
/** Height and any other framing, merged with `cn`; the transform and overflow are handled here. */
|
|
151
|
+
className?: string;
|
|
152
|
+
/** For `aspect-ratio`, which has to be a computed value rather than a utility class. */
|
|
153
|
+
style?: CSSProperties;
|
|
154
|
+
/** Drawn bottom-left over the image, where it cannot push the canvas down. */
|
|
155
|
+
label?: ReactNode;
|
|
156
|
+
/**
|
|
157
|
+
* The source image's pixel width, so double-click can reach true 1:1. Without it the
|
|
158
|
+
* gesture falls back to `FULL_TIER_ZOOM`, which is at least the tier boundary.
|
|
159
|
+
*/
|
|
160
|
+
nativeWidth?: number;
|
|
161
|
+
/** Hidden by passing `null` — a caller with its own fit button beside the canvas. */
|
|
162
|
+
fitLabel?: ReactNode;
|
|
163
|
+
/**
|
|
164
|
+
* Where the pointer is over the *content*, as fractions in `[0, 1)`, or `null` when it
|
|
165
|
+
* is outside. Reported through the same transform the layers use, so the coordinate is
|
|
166
|
+
* the one a value plane or a measurement overlay is indexed by however the frame is
|
|
167
|
+
* zoomed or panned. Suppressed while dragging: during a pan the pointer is holding the
|
|
168
|
+
* image, not pointing at a pixel.
|
|
169
|
+
*/
|
|
170
|
+
onHover?: (position: { u: number; v: number } | null) => void;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A pannable, zoomable frame that transforms its stacked children together; zoom 1 is fit.
|
|
175
|
+
*
|
|
176
|
+
* State is exposed as `data-panning` (present during a drag) and `data-fit` (present at
|
|
177
|
+
* zoom 1) on the frame.
|
|
178
|
+
*
|
|
179
|
+
* @deprecated Use `ImageStage`. This component scales its layers by the frame's size (so
|
|
180
|
+
* the frame must be laid out at the image's aspect ratio) and captures every press to pan
|
|
181
|
+
* (so no interactive layer can live inside it). It stays exported, unchanged in behaviour,
|
|
182
|
+
* for consumers that have not migrated.
|
|
183
|
+
*/
|
|
184
|
+
export function ZoomPanCanvas({
|
|
185
|
+
view,
|
|
186
|
+
onView,
|
|
187
|
+
children,
|
|
188
|
+
className,
|
|
189
|
+
style,
|
|
190
|
+
label,
|
|
191
|
+
nativeWidth,
|
|
192
|
+
fitLabel = "Fit",
|
|
193
|
+
onHover,
|
|
194
|
+
}: ZoomPanCanvasProps) {
|
|
195
|
+
const draggingRef = useRef<{ x: number; y: number } | null>(null);
|
|
196
|
+
// Mirrored into state only so the cursor can change — the ref is what the move handler
|
|
197
|
+
// reads, because a re-render per pointermove would be a cost for nothing.
|
|
198
|
+
const [grabbing, setGrabbing] = useState(false);
|
|
199
|
+
const boxRef = useRef<HTMLDivElement>(null);
|
|
200
|
+
// What the wheel listener, attached once, reads: the view and callback of the last commit.
|
|
201
|
+
const latestRef = useRef({ view, onView });
|
|
202
|
+
useLayoutEffect(() => {
|
|
203
|
+
latestRef.current = { view, onView };
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
/*
|
|
207
|
+
* The wheel listener is attached by hand because React registers `wheel` at the root as
|
|
208
|
+
* **passive**, which makes `preventDefault` in a synthetic handler a no-op. Without it
|
|
209
|
+
* the page scrolls behind the canvas while you zoom, so a gesture aimed at the image
|
|
210
|
+
* moves the document instead — which reads as the zoom being broken.
|
|
211
|
+
*/
|
|
212
|
+
useEffect(() => {
|
|
213
|
+
const element = boxRef.current;
|
|
214
|
+
if (!element) return;
|
|
215
|
+
|
|
216
|
+
const onWheel = (event: WheelEvent) => {
|
|
217
|
+
event.preventDefault();
|
|
218
|
+
const rect = element.getBoundingClientRect();
|
|
219
|
+
const factor = 1 - event.deltaY * ZOOM_SENSITIVITY;
|
|
220
|
+
const { view: current, onView: report } = latestRef.current;
|
|
221
|
+
report(zoomAt(current, { x: event.clientX, y: event.clientY }, rect, factor));
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
element.addEventListener("wheel", onWheel, { passive: false });
|
|
225
|
+
return () => element.removeEventListener("wheel", onWheel);
|
|
226
|
+
}, []);
|
|
227
|
+
|
|
228
|
+
const toggleNative = (event: { clientX: number; clientY: number }) => {
|
|
229
|
+
const element = boxRef.current;
|
|
230
|
+
if (!element) return;
|
|
231
|
+
const rect = element.getBoundingClientRect();
|
|
232
|
+
const native = nativeZoomFor(nativeWidth ?? 0, rect.width);
|
|
233
|
+
// Anywhere but fit goes back to fit; fit goes to 1:1 under the cursor.
|
|
234
|
+
const target = view.zoom > MIN_ZOOM ? MIN_ZOOM : native;
|
|
235
|
+
onView(zoomAt(view, { x: event.clientX, y: event.clientY }, rect, target / view.zoom));
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const endDrag = () => {
|
|
239
|
+
draggingRef.current = null;
|
|
240
|
+
setGrabbing(false);
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
return (
|
|
244
|
+
<div
|
|
245
|
+
ref={boxRef}
|
|
246
|
+
style={style}
|
|
247
|
+
data-panning={grabbing ? "" : undefined}
|
|
248
|
+
data-fit={view.zoom <= MIN_ZOOM ? "" : undefined}
|
|
249
|
+
className={cn(
|
|
250
|
+
"relative overflow-hidden rounded border border-line bg-canvas select-none",
|
|
251
|
+
grabbing ? "cursor-grabbing" : "cursor-grab",
|
|
252
|
+
className,
|
|
253
|
+
)}
|
|
254
|
+
onPointerDown={(event) => {
|
|
255
|
+
draggingRef.current = { x: event.clientX - view.x, y: event.clientY - view.y };
|
|
256
|
+
setGrabbing(true);
|
|
257
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
258
|
+
}}
|
|
259
|
+
onPointerMove={(event) => {
|
|
260
|
+
const origin = draggingRef.current;
|
|
261
|
+
if (!origin) {
|
|
262
|
+
onHover?.(contentUnder(view, event, event.currentTarget.getBoundingClientRect()));
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
// During a pan the pointer is holding the image rather than pointing at a pixel.
|
|
266
|
+
onHover?.(null);
|
|
267
|
+
onView({ ...view, x: event.clientX - origin.x, y: event.clientY - origin.y });
|
|
268
|
+
}}
|
|
269
|
+
onPointerLeave={() => onHover?.(null)}
|
|
270
|
+
onPointerUp={endDrag}
|
|
271
|
+
// A drag interrupted by a lost capture — a context menu, a browser gesture, the
|
|
272
|
+
// pointer leaving the window — used to leave `dragging` set, so the next hover
|
|
273
|
+
// panned the image without a button held down.
|
|
274
|
+
onPointerCancel={endDrag}
|
|
275
|
+
onLostPointerCapture={endDrag}
|
|
276
|
+
onDoubleClick={toggleNative}
|
|
277
|
+
>
|
|
278
|
+
{/* One transformed box holding every layer, so they cannot drift apart. */}
|
|
279
|
+
<div
|
|
280
|
+
className="h-full w-full"
|
|
281
|
+
style={{
|
|
282
|
+
transform: `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`,
|
|
283
|
+
transformOrigin: "center",
|
|
284
|
+
}}
|
|
285
|
+
>
|
|
286
|
+
{children}
|
|
287
|
+
</div>
|
|
288
|
+
{label && (
|
|
289
|
+
<span className="pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white">
|
|
290
|
+
{label}
|
|
291
|
+
</span>
|
|
292
|
+
)}
|
|
293
|
+
{fitLabel !== null && view.zoom > MIN_ZOOM && (
|
|
294
|
+
<button
|
|
295
|
+
type="button"
|
|
296
|
+
className="absolute right-1 bottom-1 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80"
|
|
297
|
+
// Stopping `pointerdown` is what makes the button work at all: without it the
|
|
298
|
+
// press bubbles to the canvas, which calls `setPointerCapture` on itself and
|
|
299
|
+
// takes the click with it, so the button rendered and did nothing.
|
|
300
|
+
onPointerDown={(event) => event.stopPropagation()}
|
|
301
|
+
onClick={(event) => {
|
|
302
|
+
event.stopPropagation();
|
|
303
|
+
onView(RESET_VIEW);
|
|
304
|
+
}}
|
|
305
|
+
// The canvas swallows double-clicks to toggle 1:1; without this the second click
|
|
306
|
+
// of a fast double-tap on the button reaches the canvas and zooms straight back.
|
|
307
|
+
onDoubleClick={(event) => event.stopPropagation()}
|
|
308
|
+
>
|
|
309
|
+
{fitLabel}
|
|
310
|
+
</button>
|
|
311
|
+
)}
|
|
312
|
+
</div>
|
|
313
|
+
);
|
|
314
|
+
}
|