@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
package/dist/index.js
ADDED
|
@@ -0,0 +1,1559 @@
|
|
|
1
|
+
import { createContext, use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { cn, focusRing, toneColor } from "@vitavision/ui";
|
|
3
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
import { Maximize2, Minus, Plus, Scan } from "lucide-react";
|
|
5
|
+
//#region src/components/stage/view.ts
|
|
6
|
+
/**
|
|
7
|
+
* The offset between the two pixel conventions: an image coordinate `i` sits at CSS
|
|
8
|
+
* `i + 0.5` inside a stage laid out at the image's natural size.
|
|
9
|
+
*/
|
|
10
|
+
const PIXEL_CENTRE = .5;
|
|
11
|
+
/**
|
|
12
|
+
* The `viewBox` for an SVG layer drawn in image coordinates, over a stage of that image.
|
|
13
|
+
*
|
|
14
|
+
* Shifted by half a pixel so a primitive at image coordinate `i` lands on the *centre* of
|
|
15
|
+
* pixel `i` rather than on its left edge. Its extent is unchanged — the box still covers
|
|
16
|
+
* exactly the image — so nothing about sizing or `preserveAspectRatio` changes with it.
|
|
17
|
+
*/
|
|
18
|
+
function imageViewBox(image) {
|
|
19
|
+
return `-0.5 -0.5 ${image.width} ${image.height}`;
|
|
20
|
+
}
|
|
21
|
+
/** The most a viewer may magnify: past this the resampler is the subject, not the sensor. */
|
|
22
|
+
const MAX_SCALE = 32;
|
|
23
|
+
/**
|
|
24
|
+
* How far below fit zooming out may go.
|
|
25
|
+
*
|
|
26
|
+
* `ZoomPanCanvas` bottomed out *at* fit, on the reasoning that there is nothing further to
|
|
27
|
+
* see. There is: room around the part, which is what you want when dragging an ROI out to
|
|
28
|
+
* the frame edge or checking that a model's points do not run off the image.
|
|
29
|
+
*/
|
|
30
|
+
const MIN_SCALE_VS_FIT = .25;
|
|
31
|
+
/** Zoom in/out steps, as the percentages a readout can show without apologising. */
|
|
32
|
+
const SCALE_LADDER = [
|
|
33
|
+
.05,
|
|
34
|
+
.0833,
|
|
35
|
+
.125,
|
|
36
|
+
.1667,
|
|
37
|
+
.25,
|
|
38
|
+
.3333,
|
|
39
|
+
.5,
|
|
40
|
+
.6667,
|
|
41
|
+
1,
|
|
42
|
+
1.5,
|
|
43
|
+
2,
|
|
44
|
+
3,
|
|
45
|
+
4,
|
|
46
|
+
6,
|
|
47
|
+
8,
|
|
48
|
+
12,
|
|
49
|
+
16,
|
|
50
|
+
24,
|
|
51
|
+
32
|
|
52
|
+
];
|
|
53
|
+
/** Relative tolerance for "is this the same scale" — a hair under a tenth of a percent. */
|
|
54
|
+
const SCALE_EPSILON = .001;
|
|
55
|
+
/** Absolute tolerance for "is this the same offset", in CSS pixels. */
|
|
56
|
+
const OFFSET_EPSILON = .5;
|
|
57
|
+
/** The scale at which the whole image is just visible inside `box`. */
|
|
58
|
+
function fitScale(box, image) {
|
|
59
|
+
if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;
|
|
60
|
+
return Math.min(box.width / image.width, box.height / image.height);
|
|
61
|
+
}
|
|
62
|
+
/** Fit, centred — the view a viewer opens at and the one `0` returns to. */
|
|
63
|
+
function fitView(box, image) {
|
|
64
|
+
return centred(fitScale(box, image), box, image);
|
|
65
|
+
}
|
|
66
|
+
/** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */
|
|
67
|
+
function initialView(box, image) {
|
|
68
|
+
return centred(Math.min(1, fitScale(box, image)), box, image);
|
|
69
|
+
}
|
|
70
|
+
function centred(scale, box, image) {
|
|
71
|
+
return {
|
|
72
|
+
scale,
|
|
73
|
+
tx: (box.width - image.width * scale) / 2,
|
|
74
|
+
ty: (box.height - image.height * scale) / 2
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** Whether `view` is (indistinguishably) the fit view for this box and image. */
|
|
78
|
+
function isFit(view, box, image) {
|
|
79
|
+
const fit = fitView(box, image);
|
|
80
|
+
return Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON && Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON && Math.abs(view.ty - fit.ty) <= OFFSET_EPSILON;
|
|
81
|
+
}
|
|
82
|
+
/** Where the **centre of** image pixel `p` lands in the viewport. */
|
|
83
|
+
function toScreen(view, p) {
|
|
84
|
+
return {
|
|
85
|
+
x: (p.x + PIXEL_CENTRE) * view.scale + view.tx,
|
|
86
|
+
y: (p.y + PIXEL_CENTRE) * view.scale + view.ty
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Which image coordinate a viewport position is over, in the same pixel-centre convention:
|
|
91
|
+
* the exact centre of the top-left pixel reads `0, 0`, and its top-left corner `-0.5, -0.5`.
|
|
92
|
+
*
|
|
93
|
+
* Unbounded — callers clamp if they care.
|
|
94
|
+
*/
|
|
95
|
+
function toImage(view, p) {
|
|
96
|
+
return {
|
|
97
|
+
x: (p.x - view.tx) / view.scale - PIXEL_CENTRE,
|
|
98
|
+
y: (p.y - view.ty) / view.scale - PIXEL_CENTRE
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Whether an image coordinate is inside the image, in the pixel-centre convention. */
|
|
102
|
+
function insideImage(p, image) {
|
|
103
|
+
return p.x >= -.5 && p.y >= -.5 && p.x < image.width - .5 && p.y < image.height - .5;
|
|
104
|
+
}
|
|
105
|
+
/** A length in image pixels that covers `css` screen pixels at this view. */
|
|
106
|
+
function imageLengthFor(view, css) {
|
|
107
|
+
return view.scale > 0 ? css / view.scale : css;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Change the scale while holding whatever is under `anchor` where it is.
|
|
111
|
+
*
|
|
112
|
+
* The one piece of arithmetic here that is silently wrong when centre-anchored instead:
|
|
113
|
+
* magnifying a defect in a corner then costs a drag to undo every wheel notch.
|
|
114
|
+
*/
|
|
115
|
+
function zoomAbout(view, scale, anchor) {
|
|
116
|
+
if (!(view.scale > 0) || !(scale > 0)) return view;
|
|
117
|
+
const ratio = scale / view.scale;
|
|
118
|
+
return {
|
|
119
|
+
scale,
|
|
120
|
+
tx: anchor.x - (anchor.x - view.tx) * ratio,
|
|
121
|
+
ty: anchor.y - (anchor.y - view.ty) * ratio
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** The scale range a viewport allows for an image, as `[min, max]`. */
|
|
125
|
+
function scaleRange(box, image, options = {}) {
|
|
126
|
+
const min = fitScale(box, image) * (options.minScaleVsFit ?? .25);
|
|
127
|
+
return [min, Math.max(min, options.maxScale ?? 32)];
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Keep the view legal: scale inside its range, and the image never dragged off screen.
|
|
131
|
+
*
|
|
132
|
+
* An axis where the scaled image is smaller than the viewport is centred rather than left
|
|
133
|
+
* where a drag put it — free-floating pixels in a grey field is a way to be lost with no
|
|
134
|
+
* visible handle to get back. An axis where it is larger is held so the viewport stays
|
|
135
|
+
* covered.
|
|
136
|
+
*/
|
|
137
|
+
function clampView(view, box, image, options = {}) {
|
|
138
|
+
const [min, max] = scaleRange(box, image, options);
|
|
139
|
+
const scale = clamp$1(view.scale, min, max);
|
|
140
|
+
return {
|
|
141
|
+
scale,
|
|
142
|
+
tx: clampAxis(view.tx, box.width, image.width * scale),
|
|
143
|
+
ty: clampAxis(view.ty, box.height, image.height * scale)
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function clampAxis(t, boxLength, contentLength) {
|
|
147
|
+
if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
|
|
148
|
+
return clamp$1(t, boxLength - contentLength, 0);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The view that puts `rect` (image coordinates) on screen with a margin around it.
|
|
152
|
+
*
|
|
153
|
+
* `pad` is a fraction of the rect's own size, so framing a long thin contour and framing a
|
|
154
|
+
* blob both leave a proportionate border rather than a fixed one that swallows the small
|
|
155
|
+
* one.
|
|
156
|
+
*/
|
|
157
|
+
function frameRect(box, image, rect, pad = .15) {
|
|
158
|
+
const width = Math.max(rect.width, 1e-6) * (1 + 2 * pad);
|
|
159
|
+
const height = Math.max(rect.height, 1e-6) * (1 + 2 * pad);
|
|
160
|
+
const scale = Math.min(box.width / width, box.height / height);
|
|
161
|
+
const centre = {
|
|
162
|
+
x: rect.x + rect.width / 2,
|
|
163
|
+
y: rect.y + rect.height / 2
|
|
164
|
+
};
|
|
165
|
+
return clampView({
|
|
166
|
+
scale,
|
|
167
|
+
tx: box.width / 2 - (centre.x + PIXEL_CENTRE) * scale,
|
|
168
|
+
ty: box.height / 2 - (centre.y + PIXEL_CENTRE) * scale
|
|
169
|
+
}, box, image, { maxScale: 32 });
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The same view, after the viewport changed size.
|
|
173
|
+
*
|
|
174
|
+
* The image point at the old centre stays at the new centre, at the same scale — so a
|
|
175
|
+
* window resize moves the frame around the picture instead of moving the picture. A view
|
|
176
|
+
* that was *fit* re-fits instead, because fit is a relationship to the viewport rather than
|
|
177
|
+
* a particular pair of numbers.
|
|
178
|
+
*/
|
|
179
|
+
function preserveCenter(view, from, to, image, options = {}) {
|
|
180
|
+
if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);
|
|
181
|
+
if (isFit(view, from, image)) return fitView(to, image);
|
|
182
|
+
const centre = toImage(view, {
|
|
183
|
+
x: from.width / 2,
|
|
184
|
+
y: from.height / 2
|
|
185
|
+
});
|
|
186
|
+
return clampView({
|
|
187
|
+
scale: view.scale,
|
|
188
|
+
tx: to.width / 2 - (centre.x + PIXEL_CENTRE) * view.scale,
|
|
189
|
+
ty: to.height / 2 - (centre.y + PIXEL_CENTRE) * view.scale
|
|
190
|
+
}, to, image, options);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The next scale up or down the ladder from `scale`, so the readout lands on a round
|
|
194
|
+
* percentage rather than wherever a multiplier happened to leave it.
|
|
195
|
+
*/
|
|
196
|
+
function steppedScale(scale, direction, min, max) {
|
|
197
|
+
const ladder = SCALE_LADDER.filter((s) => s >= min - 1e-9 && s <= max + 1e-9);
|
|
198
|
+
const candidates = ladder.length > 0 ? ladder : [clamp$1(scale, min, max)];
|
|
199
|
+
if (direction > 0) return candidates.find((s) => s > scale * 1.001) ?? Math.min(max, Math.max(scale, candidates[candidates.length - 1]));
|
|
200
|
+
return [...candidates].reverse().find((s) => s < scale * .999) ?? Math.max(min, Math.min(scale, candidates[0]));
|
|
201
|
+
}
|
|
202
|
+
/** `0.5` → `"50%"`, `1` → `"100%"`, `0.0833` → `"8%"`. */
|
|
203
|
+
function formatScale(scale) {
|
|
204
|
+
const percent = scale * 100;
|
|
205
|
+
if (percent >= 100) return `${Math.round(percent)}%`;
|
|
206
|
+
if (percent >= 10) return `${Math.round(percent)}%`;
|
|
207
|
+
return `${percent.toFixed(1)}%`;
|
|
208
|
+
}
|
|
209
|
+
function clamp$1(value, low, high) {
|
|
210
|
+
return Math.min(high, Math.max(low, value));
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/components/stage/ImageStage.tsx
|
|
214
|
+
/**
|
|
215
|
+
* A pannable, zoomable frame that transforms **everything stacked inside it together**.
|
|
216
|
+
*
|
|
217
|
+
* A result viewer over a stack — a photograph, an anomaly map, a model's segmentation, a
|
|
218
|
+
* measurement overlay drawn in source-image pixel coordinates — and the layers only stay
|
|
219
|
+
* registered with each other if one transform moves all of them.
|
|
220
|
+
*
|
|
221
|
+
* The stage element is laid out at **exactly the image's pixel size** and carries the whole
|
|
222
|
+
* transform (see `view.ts`). Two things follow, and both are the point:
|
|
223
|
+
*
|
|
224
|
+
* - a child `<svg viewBox="0 0 W H">` at `inset-0` is registered with the photograph at
|
|
225
|
+
* every viewport size, with no letterbox correction to get wrong. Its predecessor
|
|
226
|
+
* scaled layers by the *frame's* size, so an aspect mismatch between frame and image
|
|
227
|
+
* drew the overlay stretched against a letterboxed picture — layers drifting apart on
|
|
228
|
+
* window resize;
|
|
229
|
+
* - `scale` means CSS pixels per image pixel, so "100%" is a value rather than a
|
|
230
|
+
* coincidence, and zooming *out* past fit is expressible.
|
|
231
|
+
*
|
|
232
|
+
* Interactive children are supported, which is the other half of the rewrite. This stage
|
|
233
|
+
* starts a pan only when the gesture is unclaimed — the press landed on the background, or
|
|
234
|
+
* used the middle button, or held space, or the caller says the pan tool is active. A layer
|
|
235
|
+
* that wants a press simply handles it. The predecessor called `setPointerCapture` on every
|
|
236
|
+
* `pointerdown`, so an ROI handle or a clickable contour could not exist inside it at all,
|
|
237
|
+
* and its consumers put those layers *outside* the transform — where they no longer moved
|
|
238
|
+
* with the image.
|
|
239
|
+
*/
|
|
240
|
+
const WHEEL_SENSITIVITY = .0015;
|
|
241
|
+
/** How far a press may travel and still count as a click rather than a pan. */
|
|
242
|
+
const CLICK_SLOP = 3;
|
|
243
|
+
/** The view before the viewport has been measured — nothing is on screen yet. */
|
|
244
|
+
const UNMEASURED_VIEW = {
|
|
245
|
+
scale: 1,
|
|
246
|
+
tx: 0,
|
|
247
|
+
ty: 0
|
|
248
|
+
};
|
|
249
|
+
const ImageStageContext = createContext(null);
|
|
250
|
+
/**
|
|
251
|
+
* The stage a layer is drawn into: its view, the coordinate conversions, and the zoom
|
|
252
|
+
* controls.
|
|
253
|
+
*
|
|
254
|
+
* @throws `Error` outside an `ImageStage`, which is always a wiring bug.
|
|
255
|
+
*/
|
|
256
|
+
function useStage() {
|
|
257
|
+
const ctx = use(ImageStageContext);
|
|
258
|
+
if (ctx === null) throw new Error("useStage must be used inside <ImageStage>.");
|
|
259
|
+
return ctx;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* A pannable, zoomable viewport over a stack of layers laid out at the image's own pixel
|
|
263
|
+
* size, so an overlay drawn in image coordinates stays registered with the photograph at
|
|
264
|
+
* any zoom and window size. Layers read the transform through `useStage`.
|
|
265
|
+
*
|
|
266
|
+
* State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
|
|
267
|
+
* is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
|
|
268
|
+
* or absent.
|
|
269
|
+
*/
|
|
270
|
+
function ImageStage({ image, view, onView, children, toolbar, readout, banner, panTool = false, className, style, onHover, onBackgroundClick, clamp, shortcuts = true, panKeys = true, label = "Image canvas" }) {
|
|
271
|
+
const viewportRef = useRef(null);
|
|
272
|
+
const [box, setBox] = useState({
|
|
273
|
+
width: 0,
|
|
274
|
+
height: 0
|
|
275
|
+
});
|
|
276
|
+
const measuredRef = useRef({
|
|
277
|
+
width: 0,
|
|
278
|
+
height: 0
|
|
279
|
+
});
|
|
280
|
+
const [panning, setPanning] = useState(false);
|
|
281
|
+
const [spaceHeld, setSpaceHeld] = useState(false);
|
|
282
|
+
const panMode = panTool || spaceHeld;
|
|
283
|
+
const latestRef = useRef({
|
|
284
|
+
view,
|
|
285
|
+
box,
|
|
286
|
+
image,
|
|
287
|
+
clamp,
|
|
288
|
+
onView
|
|
289
|
+
});
|
|
290
|
+
useLayoutEffect(() => {
|
|
291
|
+
latestRef.current = {
|
|
292
|
+
view,
|
|
293
|
+
box,
|
|
294
|
+
image,
|
|
295
|
+
clamp,
|
|
296
|
+
onView
|
|
297
|
+
};
|
|
298
|
+
});
|
|
299
|
+
/** The view to come back to when a double-click leaves fit. */
|
|
300
|
+
const previousRef = useRef(null);
|
|
301
|
+
const dragRef = useRef(null);
|
|
302
|
+
const effective = useMemo(() => view ?? (box.width > 0 ? initialView(box, image) : UNMEASURED_VIEW), [
|
|
303
|
+
view,
|
|
304
|
+
box,
|
|
305
|
+
image
|
|
306
|
+
]);
|
|
307
|
+
const commit = useCallback((next) => {
|
|
308
|
+
const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
309
|
+
report(b.width > 0 ? clampView(next, b, i, c) : next);
|
|
310
|
+
}, []);
|
|
311
|
+
const attachViewport = useCallback((element) => {
|
|
312
|
+
viewportRef.current = element;
|
|
313
|
+
if (!element) return;
|
|
314
|
+
const measure = ({ width, height }) => {
|
|
315
|
+
if (!(width > 0) || !(height > 0)) return;
|
|
316
|
+
const current = measuredRef.current;
|
|
317
|
+
if (current.width === width && current.height === height) return;
|
|
318
|
+
const next = {
|
|
319
|
+
width,
|
|
320
|
+
height
|
|
321
|
+
};
|
|
322
|
+
measuredRef.current = next;
|
|
323
|
+
setBox(next);
|
|
324
|
+
const { view: v, image: i, clamp: c, onView: report } = latestRef.current;
|
|
325
|
+
if (v === null) report(initialView(next, i));
|
|
326
|
+
else if (!(current.width > 0)) report(clampView(v, next, i, c));
|
|
327
|
+
else report(preserveCenter(v, current, next, i, c));
|
|
328
|
+
};
|
|
329
|
+
measure(contentSize(element));
|
|
330
|
+
const observer = new ResizeObserver((entries) => {
|
|
331
|
+
const entry = entries[0];
|
|
332
|
+
if (entry) measure(entry.contentRect);
|
|
333
|
+
});
|
|
334
|
+
observer.observe(element);
|
|
335
|
+
const onWheel = (event) => {
|
|
336
|
+
event.preventDefault();
|
|
337
|
+
const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
338
|
+
if (v === null || !(b.width > 0)) return;
|
|
339
|
+
const origin = viewportOrigin(element);
|
|
340
|
+
const [min, max] = scaleRange(b, i, c);
|
|
341
|
+
const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
|
|
342
|
+
report(clampView(zoomAbout(v, Math.min(max, Math.max(min, v.scale * factor)), {
|
|
343
|
+
x: event.clientX - origin.x,
|
|
344
|
+
y: event.clientY - origin.y
|
|
345
|
+
}), b, i, c));
|
|
346
|
+
};
|
|
347
|
+
element.addEventListener("wheel", onWheel, { passive: false });
|
|
348
|
+
return () => {
|
|
349
|
+
observer.disconnect();
|
|
350
|
+
element.removeEventListener("wheel", onWheel);
|
|
351
|
+
viewportRef.current = null;
|
|
352
|
+
};
|
|
353
|
+
}, []);
|
|
354
|
+
useEffect(() => {
|
|
355
|
+
if (!shortcuts) return;
|
|
356
|
+
const down = (event) => {
|
|
357
|
+
if (event.code === "Space" && !isTypingTarget(event.target)) setSpaceHeld(true);
|
|
358
|
+
};
|
|
359
|
+
const up = (event) => {
|
|
360
|
+
if (event.code === "Space") setSpaceHeld(false);
|
|
361
|
+
};
|
|
362
|
+
const blur = () => setSpaceHeld(false);
|
|
363
|
+
window.addEventListener("keydown", down);
|
|
364
|
+
window.addEventListener("keyup", up);
|
|
365
|
+
window.addEventListener("blur", blur);
|
|
366
|
+
return () => {
|
|
367
|
+
window.removeEventListener("keydown", down);
|
|
368
|
+
window.removeEventListener("keyup", up);
|
|
369
|
+
window.removeEventListener("blur", blur);
|
|
370
|
+
};
|
|
371
|
+
}, [shortcuts]);
|
|
372
|
+
const clientToImage = useCallback((p) => {
|
|
373
|
+
const element = viewportRef.current;
|
|
374
|
+
const { view: v } = latestRef.current;
|
|
375
|
+
if (!element || v === null) return {
|
|
376
|
+
x: 0,
|
|
377
|
+
y: 0
|
|
378
|
+
};
|
|
379
|
+
const origin = viewportOrigin(element);
|
|
380
|
+
return toImage(v, {
|
|
381
|
+
x: p.x - origin.x,
|
|
382
|
+
y: p.y - origin.y
|
|
383
|
+
});
|
|
384
|
+
}, []);
|
|
385
|
+
const imageToClient = useCallback((p) => {
|
|
386
|
+
const element = viewportRef.current;
|
|
387
|
+
const { view: v } = latestRef.current;
|
|
388
|
+
if (!element || v === null) return {
|
|
389
|
+
x: 0,
|
|
390
|
+
y: 0
|
|
391
|
+
};
|
|
392
|
+
const origin = viewportOrigin(element);
|
|
393
|
+
const local = toScreen(v, p);
|
|
394
|
+
return {
|
|
395
|
+
x: local.x + origin.x,
|
|
396
|
+
y: local.y + origin.y
|
|
397
|
+
};
|
|
398
|
+
}, []);
|
|
399
|
+
const fit = useCallback(() => {
|
|
400
|
+
const { box: b, image: i, view: v, onView: report } = latestRef.current;
|
|
401
|
+
if (!(b.width > 0)) return;
|
|
402
|
+
if (v !== null && !isFit(v, b, i)) previousRef.current = v;
|
|
403
|
+
report(fitView(b, i));
|
|
404
|
+
}, []);
|
|
405
|
+
const zoomTo = useCallback((scale, anchor) => {
|
|
406
|
+
const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
407
|
+
const element = viewportRef.current;
|
|
408
|
+
if (v === null || !(b.width > 0) || !element) return;
|
|
409
|
+
const origin = viewportOrigin(element);
|
|
410
|
+
const local = anchor ? {
|
|
411
|
+
x: anchor.x - origin.x,
|
|
412
|
+
y: anchor.y - origin.y
|
|
413
|
+
} : {
|
|
414
|
+
x: b.width / 2,
|
|
415
|
+
y: b.height / 2
|
|
416
|
+
};
|
|
417
|
+
const [min, max] = scaleRange(b, i, c);
|
|
418
|
+
report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
|
|
419
|
+
}, []);
|
|
420
|
+
const frame = useCallback((rect, pad) => {
|
|
421
|
+
const { box: b, image: i, onView: report } = latestRef.current;
|
|
422
|
+
if (!(b.width > 0)) return;
|
|
423
|
+
report(frameRect(b, i, rect, pad));
|
|
424
|
+
}, []);
|
|
425
|
+
const atFit = box.width > 0 && isFit(effective, box, image);
|
|
426
|
+
const context = useMemo(() => ({
|
|
427
|
+
view: effective,
|
|
428
|
+
setView: commit,
|
|
429
|
+
image,
|
|
430
|
+
box,
|
|
431
|
+
toImage: clientToImage,
|
|
432
|
+
toClient: imageToClient,
|
|
433
|
+
toViewport: (p) => toScreen(effective, p),
|
|
434
|
+
imageLength: (css) => imageLengthFor(effective, css),
|
|
435
|
+
frame,
|
|
436
|
+
fit,
|
|
437
|
+
zoomTo,
|
|
438
|
+
isFit: atFit,
|
|
439
|
+
panning,
|
|
440
|
+
panMode
|
|
441
|
+
}), [
|
|
442
|
+
effective,
|
|
443
|
+
commit,
|
|
444
|
+
image,
|
|
445
|
+
box,
|
|
446
|
+
clientToImage,
|
|
447
|
+
imageToClient,
|
|
448
|
+
frame,
|
|
449
|
+
fit,
|
|
450
|
+
zoomTo,
|
|
451
|
+
atFit,
|
|
452
|
+
panning,
|
|
453
|
+
panMode
|
|
454
|
+
]);
|
|
455
|
+
const onPointerDown = (event) => {
|
|
456
|
+
if (event.button !== 0 && event.button !== 1) return;
|
|
457
|
+
event.preventDefault();
|
|
458
|
+
dragRef.current = {
|
|
459
|
+
x: event.clientX,
|
|
460
|
+
y: event.clientY,
|
|
461
|
+
tx: effective.tx,
|
|
462
|
+
ty: effective.ty,
|
|
463
|
+
moved: false
|
|
464
|
+
};
|
|
465
|
+
setPanning(true);
|
|
466
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
467
|
+
};
|
|
468
|
+
const onPointerMove = (event) => {
|
|
469
|
+
const origin = dragRef.current;
|
|
470
|
+
if (!origin) {
|
|
471
|
+
onHover?.(hoverPoint(event, viewportRef.current, effective, image));
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const dx = event.clientX - origin.x;
|
|
475
|
+
const dy = event.clientY - origin.y;
|
|
476
|
+
if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;
|
|
477
|
+
origin.moved = true;
|
|
478
|
+
onHover?.(null);
|
|
479
|
+
commit({
|
|
480
|
+
scale: effective.scale,
|
|
481
|
+
tx: origin.tx + dx,
|
|
482
|
+
ty: origin.ty + dy
|
|
483
|
+
});
|
|
484
|
+
};
|
|
485
|
+
const endDrag = (event) => {
|
|
486
|
+
const origin = dragRef.current;
|
|
487
|
+
dragRef.current = null;
|
|
488
|
+
setPanning(false);
|
|
489
|
+
if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
|
|
490
|
+
};
|
|
491
|
+
const onDoubleClick = (event) => {
|
|
492
|
+
if (!(box.width > 0)) return;
|
|
493
|
+
if (atFit) {
|
|
494
|
+
const restore = previousRef.current;
|
|
495
|
+
if (restore) onView(clampView(restore, box, image, clamp));
|
|
496
|
+
else zoomTo(1, {
|
|
497
|
+
x: event.clientX,
|
|
498
|
+
y: event.clientY
|
|
499
|
+
});
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
previousRef.current = effective;
|
|
503
|
+
onView(fitView(box, image));
|
|
504
|
+
};
|
|
505
|
+
const onKeyDown = (event) => {
|
|
506
|
+
if (!shortcuts || isTypingTarget(event.target)) return;
|
|
507
|
+
const [min, max] = scaleRange(box, image, clamp);
|
|
508
|
+
const nudge = 60;
|
|
509
|
+
switch (event.key) {
|
|
510
|
+
case "+":
|
|
511
|
+
case "=":
|
|
512
|
+
zoomTo(Math.min(max, effective.scale * 1.5));
|
|
513
|
+
break;
|
|
514
|
+
case "-":
|
|
515
|
+
case "_":
|
|
516
|
+
zoomTo(Math.max(min, effective.scale / 1.5));
|
|
517
|
+
break;
|
|
518
|
+
case "0":
|
|
519
|
+
fit();
|
|
520
|
+
break;
|
|
521
|
+
case "1":
|
|
522
|
+
zoomTo(1);
|
|
523
|
+
break;
|
|
524
|
+
case "ArrowLeft":
|
|
525
|
+
if (!panKeys) return;
|
|
526
|
+
commit({
|
|
527
|
+
...effective,
|
|
528
|
+
tx: effective.tx + nudge
|
|
529
|
+
});
|
|
530
|
+
break;
|
|
531
|
+
case "ArrowRight":
|
|
532
|
+
if (!panKeys) return;
|
|
533
|
+
commit({
|
|
534
|
+
...effective,
|
|
535
|
+
tx: effective.tx - nudge
|
|
536
|
+
});
|
|
537
|
+
break;
|
|
538
|
+
case "ArrowUp":
|
|
539
|
+
if (!panKeys) return;
|
|
540
|
+
commit({
|
|
541
|
+
...effective,
|
|
542
|
+
ty: effective.ty + nudge
|
|
543
|
+
});
|
|
544
|
+
break;
|
|
545
|
+
case "ArrowDown":
|
|
546
|
+
if (!panKeys) return;
|
|
547
|
+
commit({
|
|
548
|
+
...effective,
|
|
549
|
+
ty: effective.ty - nudge
|
|
550
|
+
});
|
|
551
|
+
break;
|
|
552
|
+
default: return;
|
|
553
|
+
}
|
|
554
|
+
event.preventDefault();
|
|
555
|
+
};
|
|
556
|
+
return /* @__PURE__ */ jsx(ImageStageContext, {
|
|
557
|
+
value: context,
|
|
558
|
+
children: /* @__PURE__ */ jsxs("div", {
|
|
559
|
+
ref: attachViewport,
|
|
560
|
+
role: "application",
|
|
561
|
+
"aria-label": label,
|
|
562
|
+
tabIndex: 0,
|
|
563
|
+
style,
|
|
564
|
+
"data-fit": atFit ? "" : void 0,
|
|
565
|
+
"data-panning": panning ? "" : void 0,
|
|
566
|
+
"data-pan-mode": panMode ? "" : void 0,
|
|
567
|
+
className: cn("relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
|
|
568
|
+
onPointerDown,
|
|
569
|
+
onPointerMove,
|
|
570
|
+
onPointerUp: endDrag,
|
|
571
|
+
onPointerCancel: endDrag,
|
|
572
|
+
onLostPointerCapture: endDrag,
|
|
573
|
+
onPointerLeave: () => onHover?.(null),
|
|
574
|
+
onDoubleClick,
|
|
575
|
+
onKeyDown,
|
|
576
|
+
children: [
|
|
577
|
+
/* @__PURE__ */ jsx("div", {
|
|
578
|
+
"data-stage": true,
|
|
579
|
+
className: "absolute top-0 left-0 origin-top-left",
|
|
580
|
+
style: {
|
|
581
|
+
width: image.width,
|
|
582
|
+
height: image.height,
|
|
583
|
+
transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`
|
|
584
|
+
},
|
|
585
|
+
children
|
|
586
|
+
}),
|
|
587
|
+
banner && /* @__PURE__ */ jsx("div", {
|
|
588
|
+
className: "pointer-events-none absolute top-2 left-2 z-10",
|
|
589
|
+
children: banner
|
|
590
|
+
}),
|
|
591
|
+
(toolbar || readout) && /* @__PURE__ */ jsxs("div", {
|
|
592
|
+
className: "pointer-events-none absolute inset-x-2 bottom-2 z-10 flex items-end justify-between gap-2",
|
|
593
|
+
children: [/* @__PURE__ */ jsx("div", {
|
|
594
|
+
className: "pointer-events-auto shrink-0",
|
|
595
|
+
children: toolbar
|
|
596
|
+
}), /* @__PURE__ */ jsx("div", {
|
|
597
|
+
className: "min-w-0 truncate",
|
|
598
|
+
children: readout
|
|
599
|
+
})]
|
|
600
|
+
})
|
|
601
|
+
]
|
|
602
|
+
})
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
function hoverPoint(event, element, view, image) {
|
|
606
|
+
if (!element) return null;
|
|
607
|
+
const origin = viewportOrigin(element);
|
|
608
|
+
const p = toImage(view, {
|
|
609
|
+
x: event.clientX - origin.x,
|
|
610
|
+
y: event.clientY - origin.y
|
|
611
|
+
});
|
|
612
|
+
return insideImage(p, image) ? p : null;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Where viewport-local `(0, 0)` is in client coordinates: the *padding* box's corner, which
|
|
616
|
+
* is where the absolutely positioned stage sits — not the border box's, which is what
|
|
617
|
+
* `getBoundingClientRect` reports. The difference is the border's width, a whole image
|
|
618
|
+
* pixel at 100% between the cursor and the pixel reported under it.
|
|
619
|
+
*/
|
|
620
|
+
function viewportOrigin(element) {
|
|
621
|
+
const rect = element.getBoundingClientRect();
|
|
622
|
+
return {
|
|
623
|
+
x: rect.left + element.clientLeft,
|
|
624
|
+
y: rect.top + element.clientTop
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
/** The element's content-box size, the box `ResizeObserver` reports as `contentRect`. */
|
|
628
|
+
function contentSize(element) {
|
|
629
|
+
const rect = element.getBoundingClientRect();
|
|
630
|
+
const style = getComputedStyle(element);
|
|
631
|
+
const px = (value) => Number.parseFloat(value) || 0;
|
|
632
|
+
return {
|
|
633
|
+
width: rect.width - px(style.borderLeftWidth) - px(style.borderRightWidth) - px(style.paddingLeft) - px(style.paddingRight),
|
|
634
|
+
height: rect.height - px(style.borderTopWidth) - px(style.borderBottomWidth) - px(style.paddingTop) - px(style.paddingBottom)
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
function isTypingTarget(target) {
|
|
638
|
+
if (!(target instanceof HTMLElement)) return false;
|
|
639
|
+
const tag = target.tagName;
|
|
640
|
+
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
|
|
641
|
+
}
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/components/stage/StageToolbar.tsx
|
|
644
|
+
/**
|
|
645
|
+
* The viewer's own controls, floating over the image rather than filed in a side panel.
|
|
646
|
+
*
|
|
647
|
+
* Zoom, fit and 1:1 are properties of *the picture*, not of the task beside it, and a
|
|
648
|
+
* workbench that puts them in the inspector spends inspector width on them on every screen
|
|
649
|
+
* while leaving the canvas with no visible affordance at all — which is indistinguishable
|
|
650
|
+
* from a canvas that cannot zoom.
|
|
651
|
+
*
|
|
652
|
+
* The bar is deliberately small and quiet: `bg-overlay/85` over a blur, one row of icon
|
|
653
|
+
* buttons, no labels except the percentage. It is chrome over the subject, so it recedes
|
|
654
|
+
* until aimed at.
|
|
655
|
+
*/
|
|
656
|
+
/** The presets the percentage menu offers, beside "Fit". */
|
|
657
|
+
const PRESETS = [
|
|
658
|
+
.25,
|
|
659
|
+
.5,
|
|
660
|
+
1,
|
|
661
|
+
2,
|
|
662
|
+
4,
|
|
663
|
+
8
|
|
664
|
+
];
|
|
665
|
+
/**
|
|
666
|
+
* The stage's zoom controls — zoom out, a percentage menu (fit and presets), zoom in, fit,
|
|
667
|
+
* and 100% — plus any app groups passed as children. Pass it as `ImageStage`'s `toolbar`;
|
|
668
|
+
* it reads the stage through `useStage`.
|
|
669
|
+
*
|
|
670
|
+
* The bar carries `data-fit` while the view is fit; the percentage button carries
|
|
671
|
+
* `data-state="open"` or `"closed"` for its menu.
|
|
672
|
+
*/
|
|
673
|
+
function StageToolbar({ children, className }) {
|
|
674
|
+
const stage = useStage();
|
|
675
|
+
const [menuOpen, setMenuOpen] = useState(false);
|
|
676
|
+
const menuRef = useRef(null);
|
|
677
|
+
const [min, max] = scaleRange(stage.box, stage.image);
|
|
678
|
+
useEffect(() => {
|
|
679
|
+
if (!menuOpen) return;
|
|
680
|
+
const close = (event) => {
|
|
681
|
+
if (!menuRef.current?.contains(event.target)) setMenuOpen(false);
|
|
682
|
+
};
|
|
683
|
+
window.addEventListener("pointerdown", close);
|
|
684
|
+
return () => window.removeEventListener("pointerdown", close);
|
|
685
|
+
}, [menuOpen]);
|
|
686
|
+
const step = (direction) => stage.zoomTo(steppedScale(stage.view.scale, direction, min, max));
|
|
687
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
688
|
+
"data-fit": stage.isFit ? "" : void 0,
|
|
689
|
+
className: cn("flex items-center gap-0.5 rounded-panel border border-line bg-overlay/85 p-1 shadow-lg backdrop-blur", className),
|
|
690
|
+
onPointerDown: (event) => event.stopPropagation(),
|
|
691
|
+
onDoubleClick: (event) => event.stopPropagation(),
|
|
692
|
+
children: [
|
|
693
|
+
/* @__PURE__ */ jsx(StageButton, {
|
|
694
|
+
label: "Zoom out",
|
|
695
|
+
onClick: () => step(-1),
|
|
696
|
+
disabled: stage.view.scale <= min + 1e-9,
|
|
697
|
+
children: /* @__PURE__ */ jsx(Minus, {
|
|
698
|
+
className: "size-4",
|
|
699
|
+
"aria-hidden": true
|
|
700
|
+
})
|
|
701
|
+
}),
|
|
702
|
+
/* @__PURE__ */ jsxs("div", {
|
|
703
|
+
className: "relative",
|
|
704
|
+
ref: menuRef,
|
|
705
|
+
children: [/* @__PURE__ */ jsx("button", {
|
|
706
|
+
type: "button",
|
|
707
|
+
"aria-haspopup": "menu",
|
|
708
|
+
"aria-expanded": menuOpen,
|
|
709
|
+
"data-state": menuOpen ? "open" : "closed",
|
|
710
|
+
onClick: () => setMenuOpen((open) => !open),
|
|
711
|
+
className: cn("h-7 min-w-14 rounded-control px-2 font-mono text-xs text-fg tabular-nums hover:bg-raised", focusRing),
|
|
712
|
+
children: stage.isFit ? "Fit" : formatScale(stage.view.scale)
|
|
713
|
+
}), menuOpen && /* @__PURE__ */ jsxs("div", {
|
|
714
|
+
role: "menu",
|
|
715
|
+
className: "absolute bottom-9 left-0 z-20 min-w-28 rounded-panel border border-line bg-overlay p-1 shadow-lg",
|
|
716
|
+
children: [/* @__PURE__ */ jsx(MenuItem, {
|
|
717
|
+
onClick: () => {
|
|
718
|
+
stage.fit();
|
|
719
|
+
setMenuOpen(false);
|
|
720
|
+
},
|
|
721
|
+
active: stage.isFit,
|
|
722
|
+
children: "Fit"
|
|
723
|
+
}), PRESETS.filter((scale) => scale >= min && scale <= max).map((scale) => /* @__PURE__ */ jsx(MenuItem, {
|
|
724
|
+
onClick: () => {
|
|
725
|
+
stage.zoomTo(scale);
|
|
726
|
+
setMenuOpen(false);
|
|
727
|
+
},
|
|
728
|
+
active: !stage.isFit && Math.abs(stage.view.scale - scale) < 1e-6,
|
|
729
|
+
children: formatScale(scale)
|
|
730
|
+
}, scale))]
|
|
731
|
+
})]
|
|
732
|
+
}),
|
|
733
|
+
/* @__PURE__ */ jsx(StageButton, {
|
|
734
|
+
label: "Zoom in",
|
|
735
|
+
onClick: () => step(1),
|
|
736
|
+
disabled: stage.view.scale >= Math.min(max, 32) - 1e-9,
|
|
737
|
+
children: /* @__PURE__ */ jsx(Plus, {
|
|
738
|
+
className: "size-4",
|
|
739
|
+
"aria-hidden": true
|
|
740
|
+
})
|
|
741
|
+
}),
|
|
742
|
+
/* @__PURE__ */ jsx(StageToolbarDivider, {}),
|
|
743
|
+
/* @__PURE__ */ jsx(StageButton, {
|
|
744
|
+
label: "Fit to window",
|
|
745
|
+
onClick: stage.fit,
|
|
746
|
+
pressed: stage.isFit,
|
|
747
|
+
children: /* @__PURE__ */ jsx(Maximize2, {
|
|
748
|
+
className: "size-4",
|
|
749
|
+
"aria-hidden": true
|
|
750
|
+
})
|
|
751
|
+
}),
|
|
752
|
+
/* @__PURE__ */ jsx(StageButton, {
|
|
753
|
+
label: "Actual size (100%)",
|
|
754
|
+
onClick: () => stage.zoomTo(1),
|
|
755
|
+
pressed: !stage.isFit && Math.abs(stage.view.scale - 1) < 1e-6,
|
|
756
|
+
children: /* @__PURE__ */ jsx(Scan, {
|
|
757
|
+
className: "size-4",
|
|
758
|
+
"aria-hidden": true
|
|
759
|
+
})
|
|
760
|
+
}),
|
|
761
|
+
children && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(StageToolbarDivider, {}), children] })
|
|
762
|
+
]
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* The bar's own button shape, exported so app groups match it exactly. An icon button
|
|
767
|
+
* named by `label`; a toggle when `pressed` is given, exposed as `aria-pressed` and
|
|
768
|
+
* `data-state="on"` or `"off"`. Other button props (and `ref`) are passed through.
|
|
769
|
+
*/
|
|
770
|
+
function StageButton({ label, pressed, className, children, ...props }) {
|
|
771
|
+
return /* @__PURE__ */ jsx("button", {
|
|
772
|
+
...props,
|
|
773
|
+
type: "button",
|
|
774
|
+
title: label,
|
|
775
|
+
"aria-label": label,
|
|
776
|
+
"aria-pressed": pressed,
|
|
777
|
+
"data-state": pressed === void 0 ? void 0 : pressed ? "on" : "off",
|
|
778
|
+
className: cn("grid size-7 place-items-center rounded-control text-fg-muted transition-colors", "hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40", pressed && "bg-signal/15 text-signal", focusRing, className),
|
|
779
|
+
children
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
/** A thin vertical rule between groups of `StageButton`s. Decorative (`aria-hidden`). */
|
|
783
|
+
function StageToolbarDivider({ className }) {
|
|
784
|
+
return /* @__PURE__ */ jsx("span", {
|
|
785
|
+
className: cn("mx-0.5 h-5 w-px bg-line", className),
|
|
786
|
+
"aria-hidden": true
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
function MenuItem({ onClick, active, children }) {
|
|
790
|
+
return /* @__PURE__ */ jsx("button", {
|
|
791
|
+
type: "button",
|
|
792
|
+
role: "menuitem",
|
|
793
|
+
onClick,
|
|
794
|
+
className: cn("block w-full rounded-control px-2 py-1 text-left font-mono text-xs tabular-nums hover:bg-raised", active ? "text-signal" : "text-fg", focusRing),
|
|
795
|
+
children
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* The instrument's display line for the canvas: where the cursor is, and how magnified.
|
|
800
|
+
* Pass it as `ImageStage`'s `readout`; it reads the stage through `useStage`.
|
|
801
|
+
*
|
|
802
|
+
* In image pixels, because that is the coordinate every number the backend returns is in —
|
|
803
|
+
* a readout in screen pixels would be a second coordinate system to reconcile by hand.
|
|
804
|
+
*/
|
|
805
|
+
function StageReadout({ cursor, extra, className }) {
|
|
806
|
+
const stage = useStage();
|
|
807
|
+
return /* @__PURE__ */ jsxs("span", {
|
|
808
|
+
className: cn("rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums", className),
|
|
809
|
+
children: [
|
|
810
|
+
cursor ? `${cursor.x.toFixed(1)}, ${cursor.y.toFixed(1)} px` : `${stage.image.width}×${stage.image.height}`,
|
|
811
|
+
" · ",
|
|
812
|
+
stage.isFit ? "fit" : formatScale(stage.view.scale),
|
|
813
|
+
extra && /* @__PURE__ */ jsxs(Fragment, { children: [" · ", extra] })
|
|
814
|
+
]
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
//#endregion
|
|
818
|
+
//#region src/components/ZoomPanCanvas.tsx
|
|
819
|
+
/**
|
|
820
|
+
* A pannable, zoomable frame that transforms **everything stacked inside it together**.
|
|
821
|
+
*
|
|
822
|
+
* Deprecated: use `ImageStage` (`components/stage`). Two limits of this component turned out
|
|
823
|
+
* to be load-bearing rather than incidental, and neither can be lifted without changing what
|
|
824
|
+
* its props mean:
|
|
825
|
+
*
|
|
826
|
+
* - it scales its layers by the *frame's* size, so every consumer must lay the frame out
|
|
827
|
+
* at the source aspect ratio and the one that forgot drew its overlays stretched against
|
|
828
|
+
* a letterboxed photograph — layers drifting apart on window resize, invisibly, at
|
|
829
|
+
* every window size but one;
|
|
830
|
+
* - it calls `setPointerCapture` on every `pointerdown` to pan, so an interactive child —
|
|
831
|
+
* a draggable ROI handle, a clickable contour — cannot exist inside it, and consumers
|
|
832
|
+
* mounted those layers *outside* the transform, where they stopped moving with the image.
|
|
833
|
+
*
|
|
834
|
+
* `ImageStage` lays the stage out at the image's own pixel size (so registration is
|
|
835
|
+
* structural, not a caller's responsibility), treats `scale` as CSS pixels per image pixel
|
|
836
|
+
* (so "100%" is a value and zooming out past fit is expressible), and pans only when a
|
|
837
|
+
* gesture is unclaimed. This component stays exported and unchanged for consumers that have
|
|
838
|
+
* not migrated.
|
|
839
|
+
*
|
|
840
|
+
* A result viewer over a stack -- a photograph, an anomaly map, a model's segmentation, a
|
|
841
|
+
* measurement overlay drawn in source-image pixel coordinates (see `MeasureOverlay`) -- and
|
|
842
|
+
* the layers only stay registered with each other if one transform moves all of them.
|
|
843
|
+
* Transforming each layer separately would drift them apart at the exact zoom level where a
|
|
844
|
+
* reader is trying to judge whether a caliper box lands on the edge it claims to measure.
|
|
845
|
+
*
|
|
846
|
+
* Zoom bottoms out at 1x and snaps the pan back to centre there, so there is always a
|
|
847
|
+
* gesture that gets you unlost — and zoom 1 *is* fit-to-window, because the canvas is laid
|
|
848
|
+
* out inside `max-h-full max-w-full` with the source aspect ratio. That is why the
|
|
849
|
+
* double-click gesture toggles fit against **1:1 native pixels** rather than "fitting":
|
|
850
|
+
* fitting is where you already are, and the thing a reader actually wants at a defect, or
|
|
851
|
+
* at a subpixel edge, is the sensor's own resolution with no resampling between them and it.
|
|
852
|
+
*/
|
|
853
|
+
/** Zoom 1, centred — which is fit-to-window, given how the canvas is laid out. */
|
|
854
|
+
const RESET_VIEW = {
|
|
855
|
+
zoom: 1,
|
|
856
|
+
x: 0,
|
|
857
|
+
y: 0
|
|
858
|
+
};
|
|
859
|
+
/** The lowest zoom `zoomAt` allows: fit. */
|
|
860
|
+
const MIN_ZOOM = 1;
|
|
861
|
+
/** The highest zoom `zoomAt` allows. */
|
|
862
|
+
const MAX_ZOOM = 12;
|
|
863
|
+
const ZOOM_SENSITIVITY = .0015;
|
|
864
|
+
/** The zoom past which a preview tier stops being enough and real pixels are wanted. */
|
|
865
|
+
const FULL_TIER_ZOOM = 2;
|
|
866
|
+
/**
|
|
867
|
+
* Zoom by `factor` about a point, keeping whatever is under that point where it is.
|
|
868
|
+
*
|
|
869
|
+
* Pure, and exported, because it is the one piece of arithmetic here that can be silently
|
|
870
|
+
* wrong: a centre-anchored zoom looks correct until someone tries to magnify a defect in a
|
|
871
|
+
* corner, at which point every wheel notch has to be undone with a drag.
|
|
872
|
+
*
|
|
873
|
+
* The transform is `translate(t) scale(z)` about the box's centre, so a content point `c`
|
|
874
|
+
* lands at `p = c·z + t`. Holding `c` fixed while `z` becomes `z'` gives
|
|
875
|
+
* `t' = p − (p − t)·z'/z`, with `p` measured from the centre.
|
|
876
|
+
*/
|
|
877
|
+
function zoomAt(view, pointer, rect, factor) {
|
|
878
|
+
const zoom = clamp(view.zoom * factor, 1, 12);
|
|
879
|
+
if (zoom === 1) return RESET_VIEW;
|
|
880
|
+
const px = pointer.x - rect.left - rect.width / 2;
|
|
881
|
+
const py = pointer.y - rect.top - rect.height / 2;
|
|
882
|
+
const ratio = zoom / view.zoom;
|
|
883
|
+
return {
|
|
884
|
+
zoom,
|
|
885
|
+
x: px - (px - view.x) * ratio,
|
|
886
|
+
y: py - (py - view.y) * ratio
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Where a pointer is over the *content*, as fractions of the frame, or `null` outside it.
|
|
891
|
+
*
|
|
892
|
+
* The inverse of the transform `zoomAt` maintains, and pure for the same reason: this is
|
|
893
|
+
* what turns a cursor position into an index into a value plane or a source-pixel
|
|
894
|
+
* coordinate, and it is wrong in a way nothing on screen would reveal — a readout that is
|
|
895
|
+
* confidently off by a pan offset looks exactly like a readout that works.
|
|
896
|
+
*
|
|
897
|
+
* The content fills the frame at zoom 1 by construction (the canvas is laid out with the
|
|
898
|
+
* source aspect ratio), so `[0, 1)` over the frame *is* `[0, 1)` over the image, with no
|
|
899
|
+
* letterbox correction to reconstruct.
|
|
900
|
+
*/
|
|
901
|
+
function contentUnder(view, pointer, rect) {
|
|
902
|
+
const px = pointer.clientX - rect.left - rect.width / 2;
|
|
903
|
+
const py = pointer.clientY - rect.top - rect.height / 2;
|
|
904
|
+
const u = (px - view.x) / view.zoom / rect.width + .5;
|
|
905
|
+
const v = (py - view.y) / view.zoom / rect.height + .5;
|
|
906
|
+
if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;
|
|
907
|
+
return {
|
|
908
|
+
u,
|
|
909
|
+
v
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* The zoom at which one source pixel covers one CSS pixel.
|
|
914
|
+
*
|
|
915
|
+
* Clamped, so an image smaller than its frame reports 1: there are no further pixels to
|
|
916
|
+
* reveal, and pretending otherwise would magnify the resampler rather than the sensor.
|
|
917
|
+
*/
|
|
918
|
+
function nativeZoomFor(sourceWidth, boxWidth) {
|
|
919
|
+
if (!(sourceWidth > 0) || !(boxWidth > 0)) return 2;
|
|
920
|
+
return clamp(sourceWidth / boxWidth, 1, 12);
|
|
921
|
+
}
|
|
922
|
+
function clamp(value, low, high) {
|
|
923
|
+
return Math.min(high, Math.max(low, value));
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* A pannable, zoomable frame that transforms its stacked children together; zoom 1 is fit.
|
|
927
|
+
*
|
|
928
|
+
* State is exposed as `data-panning` (present during a drag) and `data-fit` (present at
|
|
929
|
+
* zoom 1) on the frame.
|
|
930
|
+
*
|
|
931
|
+
* @deprecated Use `ImageStage`. This component scales its layers by the frame's size (so
|
|
932
|
+
* the frame must be laid out at the image's aspect ratio) and captures every press to pan
|
|
933
|
+
* (so no interactive layer can live inside it). It stays exported, unchanged in behaviour,
|
|
934
|
+
* for consumers that have not migrated.
|
|
935
|
+
*/
|
|
936
|
+
function ZoomPanCanvas({ view, onView, children, className, style, label, nativeWidth, fitLabel = "Fit", onHover }) {
|
|
937
|
+
const draggingRef = useRef(null);
|
|
938
|
+
const [grabbing, setGrabbing] = useState(false);
|
|
939
|
+
const boxRef = useRef(null);
|
|
940
|
+
const latestRef = useRef({
|
|
941
|
+
view,
|
|
942
|
+
onView
|
|
943
|
+
});
|
|
944
|
+
useLayoutEffect(() => {
|
|
945
|
+
latestRef.current = {
|
|
946
|
+
view,
|
|
947
|
+
onView
|
|
948
|
+
};
|
|
949
|
+
});
|
|
950
|
+
useEffect(() => {
|
|
951
|
+
const element = boxRef.current;
|
|
952
|
+
if (!element) return;
|
|
953
|
+
const onWheel = (event) => {
|
|
954
|
+
event.preventDefault();
|
|
955
|
+
const rect = element.getBoundingClientRect();
|
|
956
|
+
const factor = 1 - event.deltaY * ZOOM_SENSITIVITY;
|
|
957
|
+
const { view: current, onView: report } = latestRef.current;
|
|
958
|
+
report(zoomAt(current, {
|
|
959
|
+
x: event.clientX,
|
|
960
|
+
y: event.clientY
|
|
961
|
+
}, rect, factor));
|
|
962
|
+
};
|
|
963
|
+
element.addEventListener("wheel", onWheel, { passive: false });
|
|
964
|
+
return () => element.removeEventListener("wheel", onWheel);
|
|
965
|
+
}, []);
|
|
966
|
+
const toggleNative = (event) => {
|
|
967
|
+
const element = boxRef.current;
|
|
968
|
+
if (!element) return;
|
|
969
|
+
const rect = element.getBoundingClientRect();
|
|
970
|
+
const native = nativeZoomFor(nativeWidth ?? 0, rect.width);
|
|
971
|
+
const target = view.zoom > 1 ? 1 : native;
|
|
972
|
+
onView(zoomAt(view, {
|
|
973
|
+
x: event.clientX,
|
|
974
|
+
y: event.clientY
|
|
975
|
+
}, rect, target / view.zoom));
|
|
976
|
+
};
|
|
977
|
+
const endDrag = () => {
|
|
978
|
+
draggingRef.current = null;
|
|
979
|
+
setGrabbing(false);
|
|
980
|
+
};
|
|
981
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
982
|
+
ref: boxRef,
|
|
983
|
+
style,
|
|
984
|
+
"data-panning": grabbing ? "" : void 0,
|
|
985
|
+
"data-fit": view.zoom <= 1 ? "" : void 0,
|
|
986
|
+
className: cn("relative overflow-hidden rounded border border-line bg-canvas select-none", grabbing ? "cursor-grabbing" : "cursor-grab", className),
|
|
987
|
+
onPointerDown: (event) => {
|
|
988
|
+
draggingRef.current = {
|
|
989
|
+
x: event.clientX - view.x,
|
|
990
|
+
y: event.clientY - view.y
|
|
991
|
+
};
|
|
992
|
+
setGrabbing(true);
|
|
993
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
994
|
+
},
|
|
995
|
+
onPointerMove: (event) => {
|
|
996
|
+
const origin = draggingRef.current;
|
|
997
|
+
if (!origin) {
|
|
998
|
+
onHover?.(contentUnder(view, event, event.currentTarget.getBoundingClientRect()));
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
onHover?.(null);
|
|
1002
|
+
onView({
|
|
1003
|
+
...view,
|
|
1004
|
+
x: event.clientX - origin.x,
|
|
1005
|
+
y: event.clientY - origin.y
|
|
1006
|
+
});
|
|
1007
|
+
},
|
|
1008
|
+
onPointerLeave: () => onHover?.(null),
|
|
1009
|
+
onPointerUp: endDrag,
|
|
1010
|
+
onPointerCancel: endDrag,
|
|
1011
|
+
onLostPointerCapture: endDrag,
|
|
1012
|
+
onDoubleClick: toggleNative,
|
|
1013
|
+
children: [
|
|
1014
|
+
/* @__PURE__ */ jsx("div", {
|
|
1015
|
+
className: "h-full w-full",
|
|
1016
|
+
style: {
|
|
1017
|
+
transform: `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`,
|
|
1018
|
+
transformOrigin: "center"
|
|
1019
|
+
},
|
|
1020
|
+
children
|
|
1021
|
+
}),
|
|
1022
|
+
label && /* @__PURE__ */ jsx("span", {
|
|
1023
|
+
className: "pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white",
|
|
1024
|
+
children: label
|
|
1025
|
+
}),
|
|
1026
|
+
fitLabel !== null && view.zoom > 1 && /* @__PURE__ */ jsx("button", {
|
|
1027
|
+
type: "button",
|
|
1028
|
+
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",
|
|
1029
|
+
onPointerDown: (event) => event.stopPropagation(),
|
|
1030
|
+
onClick: (event) => {
|
|
1031
|
+
event.stopPropagation();
|
|
1032
|
+
onView(RESET_VIEW);
|
|
1033
|
+
},
|
|
1034
|
+
onDoubleClick: (event) => event.stopPropagation(),
|
|
1035
|
+
children: fitLabel
|
|
1036
|
+
})
|
|
1037
|
+
]
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
//#endregion
|
|
1041
|
+
//#region src/api/mapValues.ts
|
|
1042
|
+
/**
|
|
1043
|
+
* The numbers behind a picture.
|
|
1044
|
+
*
|
|
1045
|
+
* A rendered anomaly map or false-colour measurement overlay answers "is this region
|
|
1046
|
+
* hotter than that one" or "roughly where does the edge fall". The next question — *how
|
|
1047
|
+
* hot, in the units a metric is computed in* or *at what subpixel coordinate* — cannot be
|
|
1048
|
+
* answered from the picture: a colormap clips at both ends and quantizes to 256 entries,
|
|
1049
|
+
* and alpha is a gamma of the normalized value, so the inverse is multi-valued.
|
|
1050
|
+
*
|
|
1051
|
+
* So the values arrive as values, in a fixed 24-byte-header format that is deliberately
|
|
1052
|
+
* **not** `.npy` — there is no dtype string to parse and no shape tuple. This module
|
|
1053
|
+
* decodes them and indexes them. **It never draws.** Colour range and colormap stay wherever
|
|
1054
|
+
* the values were produced.
|
|
1055
|
+
*/
|
|
1056
|
+
const MAGIC = 1447120177;
|
|
1057
|
+
const HEADER_SIZE = 24;
|
|
1058
|
+
/** Thrown by `decodePlane` when a buffer is not a well-formed value plane. */
|
|
1059
|
+
var PlaneFormatError = class extends Error {};
|
|
1060
|
+
/**
|
|
1061
|
+
* Decode a value plane from its binary form: a 24-byte header (big-endian magic `VAM1`,
|
|
1062
|
+
* then little-endian `u32` width, height, stride and channels, and 4 reserved bytes)
|
|
1063
|
+
* followed by `width · height · channels` little-endian `f32` values.
|
|
1064
|
+
*
|
|
1065
|
+
* The returned `values` is a view onto `buffer`, not a copy.
|
|
1066
|
+
*
|
|
1067
|
+
* @throws `PlaneFormatError` when the header is short, the magic is wrong, or the buffer
|
|
1068
|
+
* holds fewer values than the header promises.
|
|
1069
|
+
*/
|
|
1070
|
+
function decodePlane(buffer) {
|
|
1071
|
+
if (buffer.byteLength < HEADER_SIZE) throw new PlaneFormatError("a value plane is at least a 24-byte header");
|
|
1072
|
+
const header = new DataView(buffer);
|
|
1073
|
+
if (header.getUint32(0, false) !== MAGIC) throw new PlaneFormatError("not a value plane — wrong magic");
|
|
1074
|
+
const width = header.getUint32(4, true);
|
|
1075
|
+
const height = header.getUint32(8, true);
|
|
1076
|
+
const stride = header.getUint32(12, true);
|
|
1077
|
+
const channels = header.getUint32(16, true);
|
|
1078
|
+
const expected = width * height * channels;
|
|
1079
|
+
if (buffer.byteLength - HEADER_SIZE < expected * 4) throw new PlaneFormatError(`a ${width}x${height}x${channels} plane needs ${expected} values`);
|
|
1080
|
+
return {
|
|
1081
|
+
width,
|
|
1082
|
+
height,
|
|
1083
|
+
stride,
|
|
1084
|
+
channels,
|
|
1085
|
+
values: new Float32Array(buffer, HEADER_SIZE, expected)
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* The value at a normalized position, or `null` outside the plane.
|
|
1090
|
+
*
|
|
1091
|
+
* `u` and `v` are fractions of the source frame. A stored anomaly map or model-input plane
|
|
1092
|
+
* is expected to already be projected into that frame, so crop and letterbox geometry is
|
|
1093
|
+
* resolved once upstream rather than reconstructed here. NaN marks an uncovered pixel.
|
|
1094
|
+
*/
|
|
1095
|
+
function valueAt(plane, u, v, channel = 0) {
|
|
1096
|
+
if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;
|
|
1097
|
+
if (channel < 0 || channel >= plane.channels) return null;
|
|
1098
|
+
const x = Math.min(plane.width - 1, Math.floor(u * plane.width));
|
|
1099
|
+
const y = Math.min(plane.height - 1, Math.floor(v * plane.height));
|
|
1100
|
+
const value = plane.values[channel * plane.width * plane.height + y * plane.width + x];
|
|
1101
|
+
return value !== void 0 && Number.isFinite(value) ? value : null;
|
|
1102
|
+
}
|
|
1103
|
+
/** Every channel at one position, in order — one number for mono, three for RGB. */
|
|
1104
|
+
function valuesAt(plane, u, v) {
|
|
1105
|
+
const out = [];
|
|
1106
|
+
for (let channel = 0; channel < plane.channels; channel += 1) {
|
|
1107
|
+
const value = valueAt(plane, u, v, channel);
|
|
1108
|
+
if (value !== null) out.push(value);
|
|
1109
|
+
}
|
|
1110
|
+
return out;
|
|
1111
|
+
}
|
|
1112
|
+
/** Where a value sits in a range, as a fraction — `null` for a degenerate range. */
|
|
1113
|
+
function fractionOf(value, range) {
|
|
1114
|
+
if (!range || range.high <= range.low) return null;
|
|
1115
|
+
return (value - range.low) / (range.high - range.low);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Fetch a value plane from `url` and decode it.
|
|
1119
|
+
*
|
|
1120
|
+
* @throws `Error` on a non-2xx response, or `PlaneFormatError` for a malformed body.
|
|
1121
|
+
*/
|
|
1122
|
+
async function fetchPlane(url) {
|
|
1123
|
+
const response = await fetch(url);
|
|
1124
|
+
if (!response.ok) throw new Error(`${response.status} fetching values`);
|
|
1125
|
+
return decodePlane(await response.arrayBuffer());
|
|
1126
|
+
}
|
|
1127
|
+
//#endregion
|
|
1128
|
+
//#region src/components/measureGeometry.ts
|
|
1129
|
+
/**
|
|
1130
|
+
* The on-screen-constant stroke width for a shape drawn in native-pixel units.
|
|
1131
|
+
*
|
|
1132
|
+
* `MeasureOverlay` is rendered as an SVG whose `viewBox` is the native image size, sitting
|
|
1133
|
+
* inside `ZoomPanCanvas`'s own `scale(zoom)` transform. A stroke declared as `1` in that
|
|
1134
|
+
* SVG's user units is `1` *native pixel*, which is `strokeScale` screen pixels once both
|
|
1135
|
+
* transforms are applied (`strokeScale` = the SVG's own fit ratio × the canvas zoom, or
|
|
1136
|
+
* just the zoom when the overlay is already at native resolution). Dividing by it is what
|
|
1137
|
+
* keeps a 1px caliper edge looking like 1px at any zoom, rather than growing with it the
|
|
1138
|
+
* way a shape's own geometry does.
|
|
1139
|
+
*
|
|
1140
|
+
* `vector-effect="non-scaling-stroke"` addresses only the SVG's *internal* transforms and
|
|
1141
|
+
* is inconsistently applied across browsers once a CSS transform sits above the `<svg>`
|
|
1142
|
+
* itself (exactly the situation inside `ZoomPanCanvas`), so this is computed explicitly
|
|
1143
|
+
* rather than left to the renderer.
|
|
1144
|
+
*/
|
|
1145
|
+
function strokeWidthFor(strokeScale, screenPixels = 1) {
|
|
1146
|
+
if (!Number.isFinite(strokeScale) || strokeScale <= 0) return screenPixels;
|
|
1147
|
+
return screenPixels / strokeScale;
|
|
1148
|
+
}
|
|
1149
|
+
/** Rotate `(x, y)` about the origin by `angle` radians. */
|
|
1150
|
+
function rotatePoint(x, y, angle) {
|
|
1151
|
+
const c = Math.cos(angle);
|
|
1152
|
+
const s = Math.sin(angle);
|
|
1153
|
+
return {
|
|
1154
|
+
x: x * c - y * s,
|
|
1155
|
+
y: x * s + y * c
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
/** `M x,y L x,y … Z` through `points`, or `""` for fewer than two of them. */
|
|
1159
|
+
function polygonPath(points) {
|
|
1160
|
+
if (points.length < 2) return "";
|
|
1161
|
+
const [first, ...rest] = points;
|
|
1162
|
+
const p0 = first;
|
|
1163
|
+
const commands = [`M${p0.x.toFixed(2)} ${p0.y.toFixed(2)}`];
|
|
1164
|
+
for (const point of rest) commands.push(`L${point.x.toFixed(2)} ${point.y.toFixed(2)}`);
|
|
1165
|
+
commands.push("Z");
|
|
1166
|
+
return commands.join(" ");
|
|
1167
|
+
}
|
|
1168
|
+
/** The two line segments of a cross mark centred on `(x, y)`, each `2·size` long. */
|
|
1169
|
+
function crossSegments(x, y, size) {
|
|
1170
|
+
return [[{
|
|
1171
|
+
x: x - size,
|
|
1172
|
+
y
|
|
1173
|
+
}, {
|
|
1174
|
+
x: x + size,
|
|
1175
|
+
y
|
|
1176
|
+
}], [{
|
|
1177
|
+
x,
|
|
1178
|
+
y: y - size
|
|
1179
|
+
}, {
|
|
1180
|
+
x,
|
|
1181
|
+
y: y + size
|
|
1182
|
+
}]];
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* The angular sweep from `startAngle` to `endAngle`, going forward.
|
|
1186
|
+
*
|
|
1187
|
+
* Two angles alone cannot distinguish "no sweep at all" from "swept exactly one full turn"
|
|
1188
|
+
* — both have `endAngle - startAngle ≡ 0 (mod 2π)`. The raw (un-normalized) difference is
|
|
1189
|
+
* what carries that distinction: genuinely equal angles have a raw difference near zero,
|
|
1190
|
+
* while a caller asking for a full circle passes a raw difference of `2π` (or a multiple of
|
|
1191
|
+
* it). So only a raw difference near zero is treated as "nothing to draw"; every other
|
|
1192
|
+
* multiple of a full turn normalizes to `2π` itself rather than collapsing to `0`.
|
|
1193
|
+
*/
|
|
1194
|
+
function sweepAngle(startAngle, endAngle) {
|
|
1195
|
+
const turn = Math.PI * 2;
|
|
1196
|
+
const EPSILON = 1e-9;
|
|
1197
|
+
const raw = endAngle - startAngle;
|
|
1198
|
+
if (Math.abs(raw) < EPSILON) return 0;
|
|
1199
|
+
const delta = raw % turn;
|
|
1200
|
+
return delta <= EPSILON ? delta + turn : delta;
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* An SVG arc path centred at `(cx, cy)` with radius `r`, sweeping forward from `startAngle`
|
|
1204
|
+
* to `endAngle` (radians, standard `x = cx + r·cos(a)`, `y = cy + r·sin(a)` convention —
|
|
1205
|
+
* clockwise on screen, since image-pixel `y` increases downward).
|
|
1206
|
+
*
|
|
1207
|
+
* A single SVG `A` command cannot express a full circle (its start and end point coincide,
|
|
1208
|
+
* which most renderers treat as a zero-length arc), so a sweep that reaches all the way
|
|
1209
|
+
* around is split into two half-circle arcs instead.
|
|
1210
|
+
*/
|
|
1211
|
+
function arcPath(cx, cy, r, startAngle, endAngle) {
|
|
1212
|
+
if (!(r > 0)) return "";
|
|
1213
|
+
const start = {
|
|
1214
|
+
x: cx + r * Math.cos(startAngle),
|
|
1215
|
+
y: cy + r * Math.sin(startAngle)
|
|
1216
|
+
};
|
|
1217
|
+
const sweep = sweepAngle(startAngle, endAngle);
|
|
1218
|
+
const FULL_TURN_EPSILON = 1e-9;
|
|
1219
|
+
if (sweep < FULL_TURN_EPSILON) return "";
|
|
1220
|
+
if (sweep >= Math.PI * 2 - FULL_TURN_EPSILON) {
|
|
1221
|
+
const mid = {
|
|
1222
|
+
x: cx + r * Math.cos(startAngle + Math.PI),
|
|
1223
|
+
y: cy + r * Math.sin(startAngle + Math.PI)
|
|
1224
|
+
};
|
|
1225
|
+
return `M${start.x.toFixed(2)} ${start.y.toFixed(2)} A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${mid.x.toFixed(2)} ${mid.y.toFixed(2)} A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${start.x.toFixed(2)} ${start.y.toFixed(2)}`;
|
|
1226
|
+
}
|
|
1227
|
+
const end = {
|
|
1228
|
+
x: cx + r * Math.cos(endAngle),
|
|
1229
|
+
y: cy + r * Math.sin(endAngle)
|
|
1230
|
+
};
|
|
1231
|
+
const largeArc = sweep > Math.PI ? 1 : 0;
|
|
1232
|
+
return `M${start.x.toFixed(2)} ${start.y.toFixed(2)} A${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${end.x.toFixed(2)} ${end.y.toFixed(2)}`;
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* The four corners of a caliper box: a rectangle `width` (along its own measurement axis)
|
|
1236
|
+
* by `height`, centred at `(cx, cy)` and rotated by `angle` radians. Corner order is
|
|
1237
|
+
* suitable for `polygonPath` — around the box, not crossed.
|
|
1238
|
+
*/
|
|
1239
|
+
function caliperCorners(cx, cy, width, height, angle) {
|
|
1240
|
+
const hw = width / 2;
|
|
1241
|
+
const hh = height / 2;
|
|
1242
|
+
const [a, b, c, d] = [
|
|
1243
|
+
[-hw, -hh],
|
|
1244
|
+
[hw, -hh],
|
|
1245
|
+
[hw, hh],
|
|
1246
|
+
[-hw, hh]
|
|
1247
|
+
].map(([lx, ly]) => {
|
|
1248
|
+
const r = rotatePoint(lx, ly, angle);
|
|
1249
|
+
return {
|
|
1250
|
+
x: cx + r.x,
|
|
1251
|
+
y: cy + r.y
|
|
1252
|
+
};
|
|
1253
|
+
});
|
|
1254
|
+
return [
|
|
1255
|
+
a,
|
|
1256
|
+
b,
|
|
1257
|
+
c,
|
|
1258
|
+
d
|
|
1259
|
+
];
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* The direction arrow for a caliper box: from its centre to just past its `+local-x` edge,
|
|
1263
|
+
* along the box's own measurement axis. What the arrow points at is the scan direction the
|
|
1264
|
+
* caliper was evaluated in, not merely a decoration on the box.
|
|
1265
|
+
*/
|
|
1266
|
+
function caliperArrow(cx, cy, width, angle) {
|
|
1267
|
+
const tip = rotatePoint(width / 2 + Math.max(4, width * .2), 0, angle);
|
|
1268
|
+
return {
|
|
1269
|
+
from: {
|
|
1270
|
+
x: cx,
|
|
1271
|
+
y: cy
|
|
1272
|
+
},
|
|
1273
|
+
to: {
|
|
1274
|
+
x: cx + tip.x,
|
|
1275
|
+
y: cy + tip.y
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* A small open chevron at `tip`, pointing along `angle` (radians), for a caliper's
|
|
1281
|
+
* direction arrow. Three points — left-back, tip, right-back — meant for an unfilled
|
|
1282
|
+
* `<polyline>`, which keeps the arrowhead's colour exactly the stroke colour of the line it
|
|
1283
|
+
* caps without the fill-vs-stroke bookkeeping a filled triangle would need per tone.
|
|
1284
|
+
*/
|
|
1285
|
+
function arrowHeadPoints(tip, angle, size) {
|
|
1286
|
+
const back = size * 1.6;
|
|
1287
|
+
const spread = size;
|
|
1288
|
+
const left = rotatePoint(-back, spread, angle);
|
|
1289
|
+
const right = rotatePoint(-back, -spread, angle);
|
|
1290
|
+
return [
|
|
1291
|
+
{
|
|
1292
|
+
x: tip.x + left.x,
|
|
1293
|
+
y: tip.y + left.y
|
|
1294
|
+
},
|
|
1295
|
+
tip,
|
|
1296
|
+
{
|
|
1297
|
+
x: tip.x + right.x,
|
|
1298
|
+
y: tip.y + right.y
|
|
1299
|
+
}
|
|
1300
|
+
];
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* The leader geometry for a dimension annotation between two measured points, offset by
|
|
1304
|
+
* `offset` native pixels to the line's left (so a positive offset with a left-to-right
|
|
1305
|
+
* measurement draws the dimension line above it, consistent with `y` increasing downward).
|
|
1306
|
+
*
|
|
1307
|
+
* Degenerate input (`x1 === x2 && y1 === y2`) falls back to an arbitrary rightward normal
|
|
1308
|
+
* rather than dividing by zero, so a caller need not special-case a zero-length dimension.
|
|
1309
|
+
*/
|
|
1310
|
+
function dimensionGeometry(x1, y1, x2, y2, offset) {
|
|
1311
|
+
const dx = x2 - x1;
|
|
1312
|
+
const dy = y2 - y1;
|
|
1313
|
+
const length = Math.hypot(dx, dy);
|
|
1314
|
+
const [ux, uy] = length > 1e-9 ? [dx / length, dy / length] : [1, 0];
|
|
1315
|
+
const nx = uy;
|
|
1316
|
+
const ny = -ux;
|
|
1317
|
+
const p1 = {
|
|
1318
|
+
x: x1 + nx * offset,
|
|
1319
|
+
y: y1 + ny * offset
|
|
1320
|
+
};
|
|
1321
|
+
const p2 = {
|
|
1322
|
+
x: x2 + nx * offset,
|
|
1323
|
+
y: y2 + ny * offset
|
|
1324
|
+
};
|
|
1325
|
+
return {
|
|
1326
|
+
extensionLine1: [{
|
|
1327
|
+
x: x1,
|
|
1328
|
+
y: y1
|
|
1329
|
+
}, p1],
|
|
1330
|
+
extensionLine2: [{
|
|
1331
|
+
x: x2,
|
|
1332
|
+
y: y2
|
|
1333
|
+
}, p2],
|
|
1334
|
+
dimensionLine: [p1, p2],
|
|
1335
|
+
labelAnchor: {
|
|
1336
|
+
x: (p1.x + p2.x) / 2,
|
|
1337
|
+
y: (p1.y + p2.y) / 2
|
|
1338
|
+
},
|
|
1339
|
+
angleDegrees: Math.atan2(dy, dx) * 180 / Math.PI
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
//#endregion
|
|
1343
|
+
//#region src/components/MeasureOverlay.tsx
|
|
1344
|
+
/**
|
|
1345
|
+
* A vector overlay layer for measurement primitives, drawn in source-image pixel
|
|
1346
|
+
* coordinates.
|
|
1347
|
+
*
|
|
1348
|
+
* Meant to sit as one of the transformed children inside `ZoomPanCanvas`, alongside the
|
|
1349
|
+
* image itself and any raster layers (a mask, a false-colour value plane). Because the
|
|
1350
|
+
* whole stack is transformed together (see `ZoomPanCanvas`'s own docs), a caliper box
|
|
1351
|
+
* drawn here stays registered with the pixel it measures at any zoom or pan — the overlay
|
|
1352
|
+
* never touches the DOM to find out where it is; it is told, in `nativeWidth` ×
|
|
1353
|
+
* `nativeHeight` pixel coordinates, via `primitives`.
|
|
1354
|
+
*
|
|
1355
|
+
* This component holds **no app state**: no fetch, no selection, no hover tracking. It is a
|
|
1356
|
+
* pure function of its props, on purpose — the app decides what a "caliper box" or a
|
|
1357
|
+
* "detected edge" *is*; this only knows how to draw one. The one piece of arithmetic it
|
|
1358
|
+
* owns is `strokeScale` compensation (see `measureGeometry.ts`'s `strokeWidthFor`), because
|
|
1359
|
+
* getting that wrong is invisible on screen until someone zooms in and a "1px" edge marker
|
|
1360
|
+
* has silently become 8px wide.
|
|
1361
|
+
*/
|
|
1362
|
+
const DEFAULT_LABEL_SIZE = 11;
|
|
1363
|
+
const DEFAULT_POINT_RADIUS = 3;
|
|
1364
|
+
const DEFAULT_CROSS_SIZE = 5;
|
|
1365
|
+
const DEFAULT_DIMENSION_OFFSET = 16;
|
|
1366
|
+
/**
|
|
1367
|
+
* A vector overlay of measurement primitives — points, segments, circles, arcs, caliper
|
|
1368
|
+
* boxes, dimensions — drawn in source-image pixel coordinates.
|
|
1369
|
+
*
|
|
1370
|
+
* Place it as a layer inside `ImageStage` so it moves with the image. It is a pure function
|
|
1371
|
+
* of its props and decorative to assistive technology (`aria-hidden`), so a result drawn
|
|
1372
|
+
* only here must also be stated in text.
|
|
1373
|
+
*/
|
|
1374
|
+
function MeasureOverlay({ nativeWidth, nativeHeight, primitives, strokeScale, className }) {
|
|
1375
|
+
const hairline = strokeWidthFor(strokeScale, 1);
|
|
1376
|
+
const thick = strokeWidthFor(strokeScale, 1.5);
|
|
1377
|
+
const labelSize = strokeWidthFor(strokeScale, DEFAULT_LABEL_SIZE);
|
|
1378
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
1379
|
+
role: "presentation",
|
|
1380
|
+
"aria-hidden": true,
|
|
1381
|
+
viewBox: imageViewBox({
|
|
1382
|
+
width: nativeWidth,
|
|
1383
|
+
height: nativeHeight
|
|
1384
|
+
}),
|
|
1385
|
+
preserveAspectRatio: "none",
|
|
1386
|
+
className: cn("pointer-events-none absolute inset-0 h-full w-full overflow-visible", className),
|
|
1387
|
+
children: primitives.map((primitive, index) => /* @__PURE__ */ jsx(Primitive, {
|
|
1388
|
+
primitive,
|
|
1389
|
+
hairline,
|
|
1390
|
+
thick,
|
|
1391
|
+
labelSize,
|
|
1392
|
+
strokeScale
|
|
1393
|
+
}, index))
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
function Primitive({ primitive, hairline, thick, labelSize, strokeScale }) {
|
|
1397
|
+
const colour = toneColor(primitive.tone);
|
|
1398
|
+
switch (primitive.kind) {
|
|
1399
|
+
case "point": {
|
|
1400
|
+
if (primitive.cross) {
|
|
1401
|
+
const size = strokeWidthFor(strokeScale, DEFAULT_CROSS_SIZE);
|
|
1402
|
+
const [h, v] = crossSegments(primitive.x, primitive.y, size);
|
|
1403
|
+
return /* @__PURE__ */ jsxs("g", {
|
|
1404
|
+
stroke: colour,
|
|
1405
|
+
strokeWidth: hairline,
|
|
1406
|
+
children: [
|
|
1407
|
+
/* @__PURE__ */ jsx("line", {
|
|
1408
|
+
x1: h[0].x,
|
|
1409
|
+
y1: h[0].y,
|
|
1410
|
+
x2: h[1].x,
|
|
1411
|
+
y2: h[1].y
|
|
1412
|
+
}),
|
|
1413
|
+
/* @__PURE__ */ jsx("line", {
|
|
1414
|
+
x1: v[0].x,
|
|
1415
|
+
y1: v[0].y,
|
|
1416
|
+
x2: v[1].x,
|
|
1417
|
+
y2: v[1].y
|
|
1418
|
+
}),
|
|
1419
|
+
/* @__PURE__ */ jsx(Label, {
|
|
1420
|
+
x: primitive.x,
|
|
1421
|
+
y: primitive.y - size - 2,
|
|
1422
|
+
text: primitive.label,
|
|
1423
|
+
colour,
|
|
1424
|
+
size: labelSize
|
|
1425
|
+
})
|
|
1426
|
+
]
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
const radius = strokeWidthFor(strokeScale, primitive.radius ?? DEFAULT_POINT_RADIUS);
|
|
1430
|
+
return /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("circle", {
|
|
1431
|
+
cx: primitive.x,
|
|
1432
|
+
cy: primitive.y,
|
|
1433
|
+
r: radius,
|
|
1434
|
+
fill: colour
|
|
1435
|
+
}), /* @__PURE__ */ jsx(Label, {
|
|
1436
|
+
x: primitive.x,
|
|
1437
|
+
y: primitive.y - radius - 2,
|
|
1438
|
+
text: primitive.label,
|
|
1439
|
+
colour,
|
|
1440
|
+
size: labelSize
|
|
1441
|
+
})] });
|
|
1442
|
+
}
|
|
1443
|
+
case "segment": return /* @__PURE__ */ jsx("line", {
|
|
1444
|
+
x1: primitive.x1,
|
|
1445
|
+
y1: primitive.y1,
|
|
1446
|
+
x2: primitive.x2,
|
|
1447
|
+
y2: primitive.y2,
|
|
1448
|
+
stroke: colour,
|
|
1449
|
+
strokeWidth: hairline,
|
|
1450
|
+
strokeDasharray: primitive.dashed ? `${hairline * 4} ${hairline * 3}` : void 0
|
|
1451
|
+
});
|
|
1452
|
+
case "circle": return /* @__PURE__ */ jsx("circle", {
|
|
1453
|
+
cx: primitive.cx,
|
|
1454
|
+
cy: primitive.cy,
|
|
1455
|
+
r: primitive.r,
|
|
1456
|
+
fill: primitive.filled ? colour : "none",
|
|
1457
|
+
stroke: primitive.filled ? "none" : colour,
|
|
1458
|
+
strokeWidth: hairline
|
|
1459
|
+
});
|
|
1460
|
+
case "arc": return /* @__PURE__ */ jsx("path", {
|
|
1461
|
+
d: arcPath(primitive.cx, primitive.cy, primitive.r, primitive.startAngle, primitive.endAngle),
|
|
1462
|
+
fill: "none",
|
|
1463
|
+
stroke: colour,
|
|
1464
|
+
strokeWidth: hairline,
|
|
1465
|
+
strokeLinecap: "round"
|
|
1466
|
+
});
|
|
1467
|
+
case "caliper": {
|
|
1468
|
+
const corners = caliperCorners(primitive.cx, primitive.cy, primitive.width, primitive.height, primitive.angle);
|
|
1469
|
+
const arrow = caliperArrow(primitive.cx, primitive.cy, primitive.width, primitive.angle);
|
|
1470
|
+
const head = arrowHeadPoints(arrow.to, primitive.angle, strokeWidthFor(strokeScale, 4));
|
|
1471
|
+
return /* @__PURE__ */ jsxs("g", { children: [
|
|
1472
|
+
/* @__PURE__ */ jsx("path", {
|
|
1473
|
+
d: polygonPath(corners),
|
|
1474
|
+
fill: "none",
|
|
1475
|
+
stroke: colour,
|
|
1476
|
+
strokeWidth: hairline
|
|
1477
|
+
}),
|
|
1478
|
+
primitive.showDirection !== false && /* @__PURE__ */ jsxs("g", {
|
|
1479
|
+
stroke: colour,
|
|
1480
|
+
strokeWidth: thick,
|
|
1481
|
+
strokeLinecap: "round",
|
|
1482
|
+
strokeLinejoin: "round",
|
|
1483
|
+
fill: "none",
|
|
1484
|
+
children: [/* @__PURE__ */ jsx("line", {
|
|
1485
|
+
x1: arrow.from.x,
|
|
1486
|
+
y1: arrow.from.y,
|
|
1487
|
+
x2: arrow.to.x,
|
|
1488
|
+
y2: arrow.to.y
|
|
1489
|
+
}), /* @__PURE__ */ jsx("polyline", { points: head.map((p) => `${p.x},${p.y}`).join(" ") })]
|
|
1490
|
+
}),
|
|
1491
|
+
/* @__PURE__ */ jsx(Label, {
|
|
1492
|
+
x: primitive.cx,
|
|
1493
|
+
y: primitive.cy,
|
|
1494
|
+
text: primitive.label,
|
|
1495
|
+
colour,
|
|
1496
|
+
size: labelSize
|
|
1497
|
+
})
|
|
1498
|
+
] });
|
|
1499
|
+
}
|
|
1500
|
+
case "dimension": {
|
|
1501
|
+
const offset = primitive.offset ?? DEFAULT_DIMENSION_OFFSET;
|
|
1502
|
+
const geometry = dimensionGeometry(primitive.x1, primitive.y1, primitive.x2, primitive.y2, offset);
|
|
1503
|
+
return /* @__PURE__ */ jsxs("g", {
|
|
1504
|
+
stroke: colour,
|
|
1505
|
+
strokeWidth: hairline,
|
|
1506
|
+
children: [
|
|
1507
|
+
/* @__PURE__ */ jsx("line", {
|
|
1508
|
+
x1: geometry.extensionLine1[0].x,
|
|
1509
|
+
y1: geometry.extensionLine1[0].y,
|
|
1510
|
+
x2: geometry.extensionLine1[1].x,
|
|
1511
|
+
y2: geometry.extensionLine1[1].y,
|
|
1512
|
+
opacity: .5
|
|
1513
|
+
}),
|
|
1514
|
+
/* @__PURE__ */ jsx("line", {
|
|
1515
|
+
x1: geometry.extensionLine2[0].x,
|
|
1516
|
+
y1: geometry.extensionLine2[0].y,
|
|
1517
|
+
x2: geometry.extensionLine2[1].x,
|
|
1518
|
+
y2: geometry.extensionLine2[1].y,
|
|
1519
|
+
opacity: .5
|
|
1520
|
+
}),
|
|
1521
|
+
/* @__PURE__ */ jsx("line", {
|
|
1522
|
+
x1: geometry.dimensionLine[0].x,
|
|
1523
|
+
y1: geometry.dimensionLine[0].y,
|
|
1524
|
+
x2: geometry.dimensionLine[1].x,
|
|
1525
|
+
y2: geometry.dimensionLine[1].y
|
|
1526
|
+
}),
|
|
1527
|
+
/* @__PURE__ */ jsx("text", {
|
|
1528
|
+
x: geometry.labelAnchor.x,
|
|
1529
|
+
y: geometry.labelAnchor.y,
|
|
1530
|
+
fontSize: labelSize,
|
|
1531
|
+
fill: colour,
|
|
1532
|
+
stroke: "none",
|
|
1533
|
+
textAnchor: "middle",
|
|
1534
|
+
dominantBaseline: "text-after-edge",
|
|
1535
|
+
transform: `rotate(${geometry.angleDegrees} ${geometry.labelAnchor.x} ${geometry.labelAnchor.y})`,
|
|
1536
|
+
children: primitive.label
|
|
1537
|
+
})
|
|
1538
|
+
]
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
default: return null;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
function Label({ x, y, text, colour, size }) {
|
|
1545
|
+
if (!text) return null;
|
|
1546
|
+
return /* @__PURE__ */ jsx("text", {
|
|
1547
|
+
x,
|
|
1548
|
+
y,
|
|
1549
|
+
fontSize: size,
|
|
1550
|
+
fill: colour,
|
|
1551
|
+
textAnchor: "middle",
|
|
1552
|
+
dominantBaseline: "text-after-edge",
|
|
1553
|
+
children: text
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1556
|
+
//#endregion
|
|
1557
|
+
export { FULL_TIER_ZOOM, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MeasureOverlay, PIXEL_CENTRE, PlaneFormatError, RESET_VIEW, StageButton, StageReadout, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, caliperArrow, caliperCorners, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, nativeZoomFor, polygonPath, preserveCenter, rotatePoint, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useStage, valueAt, valuesAt, zoomAbout, zoomAt };
|
|
1558
|
+
|
|
1559
|
+
//# sourceMappingURL=index.js.map
|