@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,594 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pannable, zoomable frame that transforms **everything stacked inside it together**.
|
|
3
|
+
*
|
|
4
|
+
* A result viewer over a stack — a photograph, an anomaly map, a model's segmentation, a
|
|
5
|
+
* measurement overlay drawn in source-image pixel coordinates — and the layers only stay
|
|
6
|
+
* registered with each other if one transform moves all of them.
|
|
7
|
+
*
|
|
8
|
+
* The stage element is laid out at **exactly the image's pixel size** and carries the whole
|
|
9
|
+
* transform (see `view.ts`). Two things follow, and both are the point:
|
|
10
|
+
*
|
|
11
|
+
* - a child `<svg viewBox="0 0 W H">` at `inset-0` is registered with the photograph at
|
|
12
|
+
* every viewport size, with no letterbox correction to get wrong. Its predecessor
|
|
13
|
+
* scaled layers by the *frame's* size, so an aspect mismatch between frame and image
|
|
14
|
+
* drew the overlay stretched against a letterboxed picture — layers drifting apart on
|
|
15
|
+
* window resize;
|
|
16
|
+
* - `scale` means CSS pixels per image pixel, so "100%" is a value rather than a
|
|
17
|
+
* coincidence, and zooming *out* past fit is expressible.
|
|
18
|
+
*
|
|
19
|
+
* Interactive children are supported, which is the other half of the rewrite. This stage
|
|
20
|
+
* starts a pan only when the gesture is unclaimed — the press landed on the background, or
|
|
21
|
+
* used the middle button, or held space, or the caller says the pan tool is active. A layer
|
|
22
|
+
* that wants a press simply handles it. The predecessor called `setPointerCapture` on every
|
|
23
|
+
* `pointerdown`, so an ROI handle or a clickable contour could not exist inside it at all,
|
|
24
|
+
* and its consumers put those layers *outside* the transform — where they no longer moved
|
|
25
|
+
* with the image.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import {
|
|
29
|
+
createContext,
|
|
30
|
+
use,
|
|
31
|
+
useCallback,
|
|
32
|
+
useEffect,
|
|
33
|
+
useLayoutEffect,
|
|
34
|
+
useMemo,
|
|
35
|
+
useRef,
|
|
36
|
+
useState,
|
|
37
|
+
} from "react";
|
|
38
|
+
import type {
|
|
39
|
+
CSSProperties,
|
|
40
|
+
KeyboardEvent as ReactKeyboardEvent,
|
|
41
|
+
PointerEvent as ReactPointerEvent,
|
|
42
|
+
ReactNode,
|
|
43
|
+
} from "react";
|
|
44
|
+
|
|
45
|
+
import { cn } from "@vitavision/ui";
|
|
46
|
+
import type { Point } from "../measureGeometry";
|
|
47
|
+
import {
|
|
48
|
+
clampView,
|
|
49
|
+
fitView,
|
|
50
|
+
frameRect,
|
|
51
|
+
imageLengthFor,
|
|
52
|
+
initialView,
|
|
53
|
+
insideImage,
|
|
54
|
+
isFit,
|
|
55
|
+
preserveCenter,
|
|
56
|
+
scaleRange,
|
|
57
|
+
toImage,
|
|
58
|
+
toScreen,
|
|
59
|
+
zoomAbout,
|
|
60
|
+
type Box,
|
|
61
|
+
type ClampOptions,
|
|
62
|
+
type Rect,
|
|
63
|
+
type StageView,
|
|
64
|
+
} from "./view";
|
|
65
|
+
|
|
66
|
+
const WHEEL_SENSITIVITY = 0.0015;
|
|
67
|
+
/** How far a press may travel and still count as a click rather than a pan. */
|
|
68
|
+
const CLICK_SLOP = 3;
|
|
69
|
+
/** The view before the viewport has been measured — nothing is on screen yet. */
|
|
70
|
+
const UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };
|
|
71
|
+
|
|
72
|
+
/** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */
|
|
73
|
+
export interface StageContext {
|
|
74
|
+
/** The view in effect — the controlled `view`, or the opening view while that is `null`. */
|
|
75
|
+
view: StageView;
|
|
76
|
+
/** Set a view, clamped to the legal range for the current viewport. */
|
|
77
|
+
setView: (view: StageView) => void;
|
|
78
|
+
/** The source image's pixel dimensions. */
|
|
79
|
+
image: Box;
|
|
80
|
+
/** The viewport's CSS size — `{0, 0}` until first measured. */
|
|
81
|
+
box: Box;
|
|
82
|
+
/** Client coordinates → image pixels. */
|
|
83
|
+
toImage: (client: Point) => Point;
|
|
84
|
+
/** Image pixels → client coordinates. */
|
|
85
|
+
toClient: (image: Point) => Point;
|
|
86
|
+
/** Image pixels → viewport-local CSS pixels. */
|
|
87
|
+
toViewport: (image: Point) => Point;
|
|
88
|
+
/** The image-pixel length that covers `css` screen pixels — for screen-constant geometry. */
|
|
89
|
+
imageLength: (css: number) => number;
|
|
90
|
+
/** Put a rect (image coordinates) on screen with a margin. */
|
|
91
|
+
frame: (rect: Rect, pad?: number) => void;
|
|
92
|
+
/** Fit the whole image. */
|
|
93
|
+
fit: () => void;
|
|
94
|
+
/** Set a scale about the viewport centre, or about `anchor` in client coordinates. */
|
|
95
|
+
zoomTo: (scale: number, anchor?: Point) => void;
|
|
96
|
+
/** Whether the view is (indistinguishably) fit. */
|
|
97
|
+
isFit: boolean;
|
|
98
|
+
/** True while a pan is in progress, so layers can suppress hover work. */
|
|
99
|
+
panning: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* True when panning must win over anything a layer would otherwise do with a press —
|
|
102
|
+
* the hand tool, or space held. Layers check this before claiming a `pointerdown`; it is
|
|
103
|
+
* the only way a modifier can outrank a child, since a child that stops propagation is
|
|
104
|
+
* heard before this component is.
|
|
105
|
+
*/
|
|
106
|
+
panMode: boolean;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const ImageStageContext = createContext<StageContext | null>(null);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The stage a layer is drawn into: its view, the coordinate conversions, and the zoom
|
|
113
|
+
* controls.
|
|
114
|
+
*
|
|
115
|
+
* @throws `Error` outside an `ImageStage`, which is always a wiring bug.
|
|
116
|
+
*/
|
|
117
|
+
export function useStage(): StageContext {
|
|
118
|
+
const ctx = use(ImageStageContext);
|
|
119
|
+
if (ctx === null) throw new Error("useStage must be used inside <ImageStage>.");
|
|
120
|
+
return ctx;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Props of `ImageStage`. */
|
|
124
|
+
export interface ImageStageProps {
|
|
125
|
+
/** The source image's pixel dimensions — the stage's own layout size. */
|
|
126
|
+
image: Box;
|
|
127
|
+
/**
|
|
128
|
+
* The view (controlled). `null` opens at a sensible view — 1:1 if the image fits,
|
|
129
|
+
* otherwise fit — reported through `onView` once the viewport is measured. A non-null
|
|
130
|
+
* view is kept on first measure, only clamped to the legal range.
|
|
131
|
+
*/
|
|
132
|
+
view: StageView | null;
|
|
133
|
+
/** Called with every view change: gestures, keys, toolbar, and viewport resizes. */
|
|
134
|
+
onView: (view: StageView) => void;
|
|
135
|
+
/** Layers, each `absolute inset-0` and sized by the stage. */
|
|
136
|
+
children: ReactNode;
|
|
137
|
+
/** Rendered floating over the bottom-left, outside the transform. */
|
|
138
|
+
toolbar?: ReactNode;
|
|
139
|
+
/** Rendered floating over the bottom-right, outside the transform. */
|
|
140
|
+
readout?: ReactNode;
|
|
141
|
+
/** Rendered over the top-left — a mode banner, a staleness warning. */
|
|
142
|
+
banner?: ReactNode;
|
|
143
|
+
/** Force panning regardless of where the press lands (a "hand tool"). */
|
|
144
|
+
panTool?: boolean;
|
|
145
|
+
/** Merged onto the viewport with `cn`. */
|
|
146
|
+
className?: string;
|
|
147
|
+
/** Inline style for the viewport. */
|
|
148
|
+
style?: CSSProperties;
|
|
149
|
+
/** Where the pointer is over the image, in image pixels, or `null` when it is outside. */
|
|
150
|
+
onHover?: (point: Point | null) => void;
|
|
151
|
+
/** A press on the background that was not a pan — how a layer hears "deselect". */
|
|
152
|
+
onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>) => void;
|
|
153
|
+
/** The legal scale range; see `clampView`. */
|
|
154
|
+
clamp?: ClampOptions;
|
|
155
|
+
/** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */
|
|
156
|
+
shortcuts?: boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Whether the arrow keys pan. On by default, and worth turning off in an app where the
|
|
159
|
+
* arrows have a better job — stepping through a list of findings, say. The zoom keys
|
|
160
|
+
* (`+`, `-`, `0`, `1`) are unaffected, and dragging still pans either way.
|
|
161
|
+
*/
|
|
162
|
+
panKeys?: boolean;
|
|
163
|
+
/** The viewport's accessible name. Defaults to "Image canvas". */
|
|
164
|
+
label?: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* A pannable, zoomable viewport over a stack of layers laid out at the image's own pixel
|
|
169
|
+
* size, so an overlay drawn in image coordinates stays registered with the photograph at
|
|
170
|
+
* any zoom and window size. Layers read the transform through `useStage`.
|
|
171
|
+
*
|
|
172
|
+
* State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
|
|
173
|
+
* is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
|
|
174
|
+
* or absent.
|
|
175
|
+
*/
|
|
176
|
+
export function ImageStage({
|
|
177
|
+
image,
|
|
178
|
+
view,
|
|
179
|
+
onView,
|
|
180
|
+
children,
|
|
181
|
+
toolbar,
|
|
182
|
+
readout,
|
|
183
|
+
banner,
|
|
184
|
+
panTool = false,
|
|
185
|
+
className,
|
|
186
|
+
style,
|
|
187
|
+
onHover,
|
|
188
|
+
onBackgroundClick,
|
|
189
|
+
clamp,
|
|
190
|
+
shortcuts = true,
|
|
191
|
+
panKeys = true,
|
|
192
|
+
label = "Image canvas",
|
|
193
|
+
}: ImageStageProps) {
|
|
194
|
+
const viewportRef = useRef<HTMLDivElement | null>(null);
|
|
195
|
+
const [box, setBox] = useState<Box>({ width: 0, height: 0 });
|
|
196
|
+
// The measured size, readable synchronously — `setBox`'s updater must stay pure, and the
|
|
197
|
+
// resize handler needs the *previous* box to re-anchor the view against.
|
|
198
|
+
const measuredRef = useRef<Box>({ width: 0, height: 0 });
|
|
199
|
+
const [panning, setPanning] = useState(false);
|
|
200
|
+
const [spaceHeld, setSpaceHeld] = useState(false);
|
|
201
|
+
const panMode = panTool || spaceHeld;
|
|
202
|
+
|
|
203
|
+
// What the handlers attached once (and the stable callbacks below) read: the props and
|
|
204
|
+
// box of the last commit, so none of them closes over stale values.
|
|
205
|
+
const latestRef = useRef({ view, box, image, clamp, onView });
|
|
206
|
+
useLayoutEffect(() => {
|
|
207
|
+
latestRef.current = { view, box, image, clamp, onView };
|
|
208
|
+
});
|
|
209
|
+
/** The view to come back to when a double-click leaves fit. */
|
|
210
|
+
const previousRef = useRef<StageView | null>(null);
|
|
211
|
+
const dragRef = useRef<{ x: number; y: number; tx: number; ty: number; moved: boolean } | null>(null);
|
|
212
|
+
|
|
213
|
+
const effective = useMemo(
|
|
214
|
+
() => view ?? (box.width > 0 ? initialView(box, image) : UNMEASURED_VIEW),
|
|
215
|
+
[view, box, image],
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
const commit = useCallback((next: StageView) => {
|
|
219
|
+
const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
220
|
+
report(b.width > 0 ? clampView(next, b, i, c) : next);
|
|
221
|
+
}, []);
|
|
222
|
+
|
|
223
|
+
/*
|
|
224
|
+
* The viewport, measured and observed from the moment it mounts (a callback ref with a
|
|
225
|
+
* cleanup, so the subscription lives exactly as long as the element).
|
|
226
|
+
*
|
|
227
|
+
* Its size is a *dependency* of the view, not just of the layout: fit is a relationship to
|
|
228
|
+
* it, and a pan offset that was legal in a wide window is off-screen in a narrow one.
|
|
229
|
+
* Without this the picture appeared to slide out from under its own overlay whenever the
|
|
230
|
+
* window changed shape.
|
|
231
|
+
*
|
|
232
|
+
* The wheel listener is attached here by hand because React registers `wheel` at the root
|
|
233
|
+
* as **passive**, which makes `preventDefault` in a synthetic handler a no-op — the page
|
|
234
|
+
* would scroll behind the canvas while you zoom, which reads as the zoom being broken.
|
|
235
|
+
*/
|
|
236
|
+
const attachViewport = useCallback((element: HTMLDivElement | null) => {
|
|
237
|
+
viewportRef.current = element;
|
|
238
|
+
if (!element) return;
|
|
239
|
+
|
|
240
|
+
const measure = ({ width, height }: Box) => {
|
|
241
|
+
if (!(width > 0) || !(height > 0)) return;
|
|
242
|
+
const current = measuredRef.current;
|
|
243
|
+
if (current.width === width && current.height === height) return;
|
|
244
|
+
const next = { width, height };
|
|
245
|
+
measuredRef.current = next;
|
|
246
|
+
setBox(next);
|
|
247
|
+
const { view: v, image: i, clamp: c, onView: report } = latestRef.current;
|
|
248
|
+
if (v === null) report(initialView(next, i));
|
|
249
|
+
// The first measurement: there is no previous viewport to re-anchor against, so the
|
|
250
|
+
// caller's view is kept — only made legal for this one.
|
|
251
|
+
else if (!(current.width > 0)) report(clampView(v, next, i, c));
|
|
252
|
+
else report(preserveCenter(v, current, next, i, c));
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
// Synchronously, so the first paint already has the right view — and as the *content*
|
|
256
|
+
// box, which is what the observer reports; measuring the border box here re-anchored
|
|
257
|
+
// the view by the border's width as soon as the observer's first report arrived.
|
|
258
|
+
measure(contentSize(element));
|
|
259
|
+
const observer = new ResizeObserver((entries) => {
|
|
260
|
+
const entry = entries[0];
|
|
261
|
+
if (entry) measure(entry.contentRect);
|
|
262
|
+
});
|
|
263
|
+
observer.observe(element);
|
|
264
|
+
|
|
265
|
+
const onWheel = (event: WheelEvent) => {
|
|
266
|
+
event.preventDefault();
|
|
267
|
+
const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
268
|
+
if (v === null || !(b.width > 0)) return;
|
|
269
|
+
const origin = viewportOrigin(element);
|
|
270
|
+
const [min, max] = scaleRange(b, i, c);
|
|
271
|
+
const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
|
|
272
|
+
const scale = Math.min(max, Math.max(min, v.scale * factor));
|
|
273
|
+
const anchor = { x: event.clientX - origin.x, y: event.clientY - origin.y };
|
|
274
|
+
report(clampView(zoomAbout(v, scale, anchor), b, i, c));
|
|
275
|
+
};
|
|
276
|
+
element.addEventListener("wheel", onWheel, { passive: false });
|
|
277
|
+
|
|
278
|
+
return () => {
|
|
279
|
+
observer.disconnect();
|
|
280
|
+
element.removeEventListener("wheel", onWheel);
|
|
281
|
+
viewportRef.current = null;
|
|
282
|
+
};
|
|
283
|
+
}, []);
|
|
284
|
+
|
|
285
|
+
/* Space is a *modifier*, not a command: held, it turns any press into a pan, which is the
|
|
286
|
+
* one gesture that has to work no matter which layer is under the cursor. */
|
|
287
|
+
useEffect(() => {
|
|
288
|
+
if (!shortcuts) return;
|
|
289
|
+
const down = (event: KeyboardEvent) => {
|
|
290
|
+
if (event.code === "Space" && !isTypingTarget(event.target)) setSpaceHeld(true);
|
|
291
|
+
};
|
|
292
|
+
const up = (event: KeyboardEvent) => {
|
|
293
|
+
if (event.code === "Space") setSpaceHeld(false);
|
|
294
|
+
};
|
|
295
|
+
const blur = () => setSpaceHeld(false);
|
|
296
|
+
window.addEventListener("keydown", down);
|
|
297
|
+
window.addEventListener("keyup", up);
|
|
298
|
+
window.addEventListener("blur", blur);
|
|
299
|
+
return () => {
|
|
300
|
+
window.removeEventListener("keydown", down);
|
|
301
|
+
window.removeEventListener("keyup", up);
|
|
302
|
+
window.removeEventListener("blur", blur);
|
|
303
|
+
};
|
|
304
|
+
}, [shortcuts]);
|
|
305
|
+
|
|
306
|
+
const clientToImage = useCallback((p: Point): Point => {
|
|
307
|
+
const element = viewportRef.current;
|
|
308
|
+
const { view: v } = latestRef.current;
|
|
309
|
+
if (!element || v === null) return { x: 0, y: 0 };
|
|
310
|
+
const origin = viewportOrigin(element);
|
|
311
|
+
return toImage(v, { x: p.x - origin.x, y: p.y - origin.y });
|
|
312
|
+
}, []);
|
|
313
|
+
|
|
314
|
+
const imageToClient = useCallback((p: Point): Point => {
|
|
315
|
+
const element = viewportRef.current;
|
|
316
|
+
const { view: v } = latestRef.current;
|
|
317
|
+
if (!element || v === null) return { x: 0, y: 0 };
|
|
318
|
+
const origin = viewportOrigin(element);
|
|
319
|
+
const local = toScreen(v, p);
|
|
320
|
+
return { x: local.x + origin.x, y: local.y + origin.y };
|
|
321
|
+
}, []);
|
|
322
|
+
|
|
323
|
+
const fit = useCallback(() => {
|
|
324
|
+
const { box: b, image: i, view: v, onView: report } = latestRef.current;
|
|
325
|
+
if (!(b.width > 0)) return;
|
|
326
|
+
if (v !== null && !isFit(v, b, i)) previousRef.current = v;
|
|
327
|
+
report(fitView(b, i));
|
|
328
|
+
}, []);
|
|
329
|
+
|
|
330
|
+
const zoomTo = useCallback((scale: number, anchor?: Point) => {
|
|
331
|
+
const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
|
|
332
|
+
const element = viewportRef.current;
|
|
333
|
+
if (v === null || !(b.width > 0) || !element) return;
|
|
334
|
+
const origin = viewportOrigin(element);
|
|
335
|
+
const local = anchor
|
|
336
|
+
? { x: anchor.x - origin.x, y: anchor.y - origin.y }
|
|
337
|
+
: { x: b.width / 2, y: b.height / 2 };
|
|
338
|
+
const [min, max] = scaleRange(b, i, c);
|
|
339
|
+
report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
|
|
340
|
+
}, []);
|
|
341
|
+
|
|
342
|
+
const frame = useCallback((rect: Rect, pad?: number) => {
|
|
343
|
+
const { box: b, image: i, onView: report } = latestRef.current;
|
|
344
|
+
if (!(b.width > 0)) return;
|
|
345
|
+
report(frameRect(b, i, rect, pad));
|
|
346
|
+
}, []);
|
|
347
|
+
|
|
348
|
+
const atFit = box.width > 0 && isFit(effective, box, image);
|
|
349
|
+
|
|
350
|
+
const context = useMemo<StageContext>(
|
|
351
|
+
() => ({
|
|
352
|
+
view: effective,
|
|
353
|
+
setView: commit,
|
|
354
|
+
image,
|
|
355
|
+
box,
|
|
356
|
+
toImage: clientToImage,
|
|
357
|
+
toClient: imageToClient,
|
|
358
|
+
toViewport: (p: Point) => toScreen(effective, p),
|
|
359
|
+
imageLength: (css: number) => imageLengthFor(effective, css),
|
|
360
|
+
frame,
|
|
361
|
+
fit,
|
|
362
|
+
zoomTo,
|
|
363
|
+
isFit: atFit,
|
|
364
|
+
panning,
|
|
365
|
+
panMode,
|
|
366
|
+
}),
|
|
367
|
+
[
|
|
368
|
+
effective,
|
|
369
|
+
commit,
|
|
370
|
+
image,
|
|
371
|
+
box,
|
|
372
|
+
clientToImage,
|
|
373
|
+
imageToClient,
|
|
374
|
+
frame,
|
|
375
|
+
fit,
|
|
376
|
+
zoomTo,
|
|
377
|
+
atFit,
|
|
378
|
+
panning,
|
|
379
|
+
panMode,
|
|
380
|
+
],
|
|
381
|
+
);
|
|
382
|
+
|
|
383
|
+
/*
|
|
384
|
+
* Panning is the *default* reading of a press, and a layer opts out of it by handling the
|
|
385
|
+
* event and stopping propagation — so the stage needs to know nothing about ROI handles or
|
|
386
|
+
* clickable contours, and a layer needs no permission to exist. The predecessor inverted
|
|
387
|
+
* this: it captured every `pointerdown` unconditionally, which is why its consumers had to
|
|
388
|
+
* mount interactive layers outside the transform, where they stopped moving with the image.
|
|
389
|
+
*/
|
|
390
|
+
const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
|
|
391
|
+
if (event.button !== 0 && event.button !== 1) return;
|
|
392
|
+
event.preventDefault();
|
|
393
|
+
dragRef.current = {
|
|
394
|
+
x: event.clientX,
|
|
395
|
+
y: event.clientY,
|
|
396
|
+
tx: effective.tx,
|
|
397
|
+
ty: effective.ty,
|
|
398
|
+
moved: false,
|
|
399
|
+
};
|
|
400
|
+
setPanning(true);
|
|
401
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
|
|
405
|
+
const origin = dragRef.current;
|
|
406
|
+
if (!origin) {
|
|
407
|
+
onHover?.(hoverPoint(event, viewportRef.current, effective, image));
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const dx = event.clientX - origin.x;
|
|
411
|
+
const dy = event.clientY - origin.y;
|
|
412
|
+
if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;
|
|
413
|
+
origin.moved = true;
|
|
414
|
+
// During a pan the pointer is holding the image, not pointing at a pixel.
|
|
415
|
+
onHover?.(null);
|
|
416
|
+
commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy });
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
|
|
420
|
+
const origin = dragRef.current;
|
|
421
|
+
dragRef.current = null;
|
|
422
|
+
setPanning(false);
|
|
423
|
+
if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
/*
|
|
427
|
+
* Fit ↔ **the view you were just at**, which is the gesture a reader actually wants: a
|
|
428
|
+
* double-click to see the whole part, another to go back to the corner they were working
|
|
429
|
+
* in. Toggling against 1:1 instead (the predecessor's behaviour) throws that place away.
|
|
430
|
+
*/
|
|
431
|
+
const onDoubleClick = (event: ReactPointerEvent<HTMLDivElement>) => {
|
|
432
|
+
if (!(box.width > 0)) return;
|
|
433
|
+
if (atFit) {
|
|
434
|
+
const restore = previousRef.current;
|
|
435
|
+
if (restore) {
|
|
436
|
+
onView(clampView(restore, box, image, clamp));
|
|
437
|
+
} else {
|
|
438
|
+
zoomTo(1, { x: event.clientX, y: event.clientY });
|
|
439
|
+
}
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
previousRef.current = effective;
|
|
443
|
+
onView(fitView(box, image));
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
|
|
447
|
+
if (!shortcuts || isTypingTarget(event.target)) return;
|
|
448
|
+
const [min, max] = scaleRange(box, image, clamp);
|
|
449
|
+
const nudge = 60;
|
|
450
|
+
switch (event.key) {
|
|
451
|
+
case "+":
|
|
452
|
+
case "=":
|
|
453
|
+
zoomTo(Math.min(max, effective.scale * 1.5));
|
|
454
|
+
break;
|
|
455
|
+
case "-":
|
|
456
|
+
case "_":
|
|
457
|
+
zoomTo(Math.max(min, effective.scale / 1.5));
|
|
458
|
+
break;
|
|
459
|
+
case "0":
|
|
460
|
+
fit();
|
|
461
|
+
break;
|
|
462
|
+
case "1":
|
|
463
|
+
zoomTo(1);
|
|
464
|
+
break;
|
|
465
|
+
case "ArrowLeft":
|
|
466
|
+
if (!panKeys) return;
|
|
467
|
+
commit({ ...effective, tx: effective.tx + nudge });
|
|
468
|
+
break;
|
|
469
|
+
case "ArrowRight":
|
|
470
|
+
if (!panKeys) return;
|
|
471
|
+
commit({ ...effective, tx: effective.tx - nudge });
|
|
472
|
+
break;
|
|
473
|
+
case "ArrowUp":
|
|
474
|
+
if (!panKeys) return;
|
|
475
|
+
commit({ ...effective, ty: effective.ty + nudge });
|
|
476
|
+
break;
|
|
477
|
+
case "ArrowDown":
|
|
478
|
+
if (!panKeys) return;
|
|
479
|
+
commit({ ...effective, ty: effective.ty - nudge });
|
|
480
|
+
break;
|
|
481
|
+
default:
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
event.preventDefault();
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
return (
|
|
488
|
+
<ImageStageContext value={context}>
|
|
489
|
+
<div
|
|
490
|
+
ref={attachViewport}
|
|
491
|
+
role="application"
|
|
492
|
+
aria-label={label}
|
|
493
|
+
tabIndex={0}
|
|
494
|
+
style={style}
|
|
495
|
+
data-fit={atFit ? "" : undefined}
|
|
496
|
+
data-panning={panning ? "" : undefined}
|
|
497
|
+
data-pan-mode={panMode ? "" : undefined}
|
|
498
|
+
className={cn(
|
|
499
|
+
"relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none",
|
|
500
|
+
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal",
|
|
501
|
+
panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default",
|
|
502
|
+
className,
|
|
503
|
+
)}
|
|
504
|
+
onPointerDown={onPointerDown}
|
|
505
|
+
onPointerMove={onPointerMove}
|
|
506
|
+
onPointerUp={endDrag}
|
|
507
|
+
// A drag interrupted by a lost capture — a context menu, a browser gesture, the
|
|
508
|
+
// pointer leaving the window — used to leave the drag set, so the next hover panned
|
|
509
|
+
// the image with no button held down.
|
|
510
|
+
onPointerCancel={endDrag}
|
|
511
|
+
onLostPointerCapture={endDrag}
|
|
512
|
+
onPointerLeave={() => onHover?.(null)}
|
|
513
|
+
onDoubleClick={onDoubleClick}
|
|
514
|
+
onKeyDown={onKeyDown}
|
|
515
|
+
>
|
|
516
|
+
{/* One transformed box holding every layer, laid out at the image's own pixel size. */}
|
|
517
|
+
<div
|
|
518
|
+
data-stage
|
|
519
|
+
className="absolute top-0 left-0 origin-top-left"
|
|
520
|
+
style={{
|
|
521
|
+
width: image.width,
|
|
522
|
+
height: image.height,
|
|
523
|
+
transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`,
|
|
524
|
+
}}
|
|
525
|
+
>
|
|
526
|
+
{children}
|
|
527
|
+
</div>
|
|
528
|
+
|
|
529
|
+
{banner && <div className="pointer-events-none absolute top-2 left-2 z-10">{banner}</div>}
|
|
530
|
+
|
|
531
|
+
{/* One row, not two corners: as separate absolute boxes the toolbar and the readout
|
|
532
|
+
overlapped as soon as the canvas was narrower than their combined width, which is
|
|
533
|
+
an ordinary window on a two-column workbench. `justify-between` keeps them apart
|
|
534
|
+
and lets the readout be the one that gives up room. */}
|
|
535
|
+
{(toolbar || readout) && (
|
|
536
|
+
<div className="pointer-events-none absolute inset-x-2 bottom-2 z-10 flex items-end justify-between gap-2">
|
|
537
|
+
<div className="pointer-events-auto shrink-0">{toolbar}</div>
|
|
538
|
+
<div className="min-w-0 truncate">{readout}</div>
|
|
539
|
+
</div>
|
|
540
|
+
)}
|
|
541
|
+
</div>
|
|
542
|
+
</ImageStageContext>
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function hoverPoint(
|
|
547
|
+
event: { clientX: number; clientY: number },
|
|
548
|
+
element: HTMLDivElement | null,
|
|
549
|
+
view: StageView,
|
|
550
|
+
image: Box,
|
|
551
|
+
): Point | null {
|
|
552
|
+
if (!element) return null;
|
|
553
|
+
const origin = viewportOrigin(element);
|
|
554
|
+
const p = toImage(view, { x: event.clientX - origin.x, y: event.clientY - origin.y });
|
|
555
|
+
return insideImage(p, image) ? p : null;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Where viewport-local `(0, 0)` is in client coordinates: the *padding* box's corner, which
|
|
560
|
+
* is where the absolutely positioned stage sits — not the border box's, which is what
|
|
561
|
+
* `getBoundingClientRect` reports. The difference is the border's width, a whole image
|
|
562
|
+
* pixel at 100% between the cursor and the pixel reported under it.
|
|
563
|
+
*/
|
|
564
|
+
function viewportOrigin(element: HTMLElement): Point {
|
|
565
|
+
const rect = element.getBoundingClientRect();
|
|
566
|
+
return { x: rect.left + element.clientLeft, y: rect.top + element.clientTop };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** The element's content-box size, the box `ResizeObserver` reports as `contentRect`. */
|
|
570
|
+
function contentSize(element: HTMLElement): Box {
|
|
571
|
+
const rect = element.getBoundingClientRect();
|
|
572
|
+
const style = getComputedStyle(element);
|
|
573
|
+
const px = (value: string) => Number.parseFloat(value) || 0;
|
|
574
|
+
return {
|
|
575
|
+
width:
|
|
576
|
+
rect.width -
|
|
577
|
+
px(style.borderLeftWidth) -
|
|
578
|
+
px(style.borderRightWidth) -
|
|
579
|
+
px(style.paddingLeft) -
|
|
580
|
+
px(style.paddingRight),
|
|
581
|
+
height:
|
|
582
|
+
rect.height -
|
|
583
|
+
px(style.borderTopWidth) -
|
|
584
|
+
px(style.borderBottomWidth) -
|
|
585
|
+
px(style.paddingTop) -
|
|
586
|
+
px(style.paddingBottom),
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function isTypingTarget(target: EventTarget | null): boolean {
|
|
591
|
+
if (!(target instanceof HTMLElement)) return false;
|
|
592
|
+
const tag = target.tagName;
|
|
593
|
+
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
|
|
594
|
+
}
|