@vitavision/stage2d 0.10.0 → 0.12.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.
@@ -46,7 +46,7 @@ import type {
46
46
 
47
47
  import { cn } from "@vitavision/ui";
48
48
  import type { Point } from "../measureGeometry";
49
- import { centroid, isTap, panButtonCodes, pinchView, type StageMouseButton } from "./gesture";
49
+ import { centroid, hitRadiusPx, isTap, panButtonCodes, pinchView, type StageMouseButton } from "./gesture";
50
50
  import { StageHitContext, type StagePointerEvent } from "./hitContext";
51
51
  import { createHitRegistry } from "./hitTest";
52
52
  import {
@@ -64,16 +64,25 @@ import {
64
64
  zoomAbout,
65
65
  type Box,
66
66
  type ClampOptions,
67
+ type FitOptions,
67
68
  type Rect,
68
69
  type StageView,
69
70
  } from "./view";
70
71
 
71
72
  const WHEEL_SENSITIVITY = 0.0015;
73
+ /**
74
+ * How long after the last view change the stage box keeps `will-change: transform`.
75
+ *
76
+ * The hint keeps a pan on the compositor (without it every overlay path is repainted each
77
+ * frame: 130 ms against 17 ms with 4,000 corners in view under software raster), but Chromium
78
+ * then keeps the layer at the raster scale it had when the hint was applied, so the stage
79
+ * would stay blurry after a zoom. Measured in `willChange.browser.test.ts`: always on, the
80
+ * edge of a zoomed image ramps over 6 px and a 1 px line smears to 10; cleared once the view
81
+ * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.
82
+ */
83
+ const MOVING_SETTLE_MS = 150;
72
84
  /** How far a press may travel and still count as a click rather than a pan. */
73
85
  const CLICK_SLOP = 3;
74
- /** The pointer's tolerance for hover and presses, in screen pixels: a mouse, and a fingertip. */
75
- const POINTER_RADIUS = 6;
76
- const TOUCH_RADIUS = 12;
77
86
  /** The view before the viewport has been measured — nothing is on screen yet. */
78
87
  const UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };
79
88
 
@@ -95,6 +104,21 @@ interface Drag {
95
104
  pointerId: number;
96
105
  }
97
106
 
107
+ /** Why a view was reported through `ImageStage`'s `onView`. */
108
+ export interface StageViewChange {
109
+ /**
110
+ * What moved the view:
111
+ * - `"gesture"`: a wheel zoom, a drag or touch pan, a pinch, a double-click.
112
+ * - `"key"`: a keyboard shortcut or pan key.
113
+ * - `"command"`: a call to the handle or the context (`fit`, `zoomTo`, `frame`, `setView`),
114
+ * which includes the toolbar's buttons.
115
+ * - `"measure"`: the opening view, and a resize re-anchoring the view.
116
+ */
117
+ cause: "gesture" | "key" | "command" | "measure";
118
+ /** The measured viewport, in CSS pixels, at the moment of the change. */
119
+ box: Box;
120
+ }
121
+
98
122
  /** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */
99
123
  export interface StageContext {
100
124
  /** The view in effect — the controlled `view`, or the opening view while that is `null`. */
@@ -170,8 +194,13 @@ export interface ImageStageProps {
170
194
  * view is kept on first measure, only clamped to the legal range.
171
195
  */
172
196
  view: StageView | null;
173
- /** Called with every view change: gestures, keys, toolbar, and viewport resizes. */
174
- onView: (view: StageView) => void;
197
+ /**
198
+ * Called with every view change: gestures, keys, toolbar, and viewport resizes. The second
199
+ * argument says why and carries the measured viewport; a one-argument callback ignores it.
200
+ * A `null` `view` that the stage has already measured is re-opened and reported again, with
201
+ * cause `"measure"`.
202
+ */
203
+ onView: (view: StageView, change: StageViewChange) => void;
175
204
  /** Layers, each `absolute inset-0` and sized by the stage. */
176
205
  children: ReactNode;
177
206
  /** Rendered floating over the bottom-left, outside the transform. */
@@ -208,8 +237,11 @@ export interface ImageStageProps {
208
237
  style?: CSSProperties;
209
238
  /** Where the pointer is over the image, in image pixels, or `null` when it is outside. */
210
239
  onHover?: (point: Point | null) => void;
211
- /** A press on the background that was not a pan — how a layer hears "deselect". */
212
- onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>) => void;
240
+ /**
241
+ * A press on the background that was not a pan — how a layer hears "deselect". `point` is
242
+ * where it landed, in image coordinates (the pixel-centre convention, unclamped).
243
+ */
244
+ onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>, point: Point) => void;
213
245
  /** The legal scale range; see `clampView`. */
214
246
  clamp?: ClampOptions;
215
247
  /** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */
@@ -224,10 +256,17 @@ export interface ImageStageProps {
224
256
  label?: string;
225
257
  /**
226
258
  * How a `null` view opens: `"auto"` (the default) at 1:1 when the image fits the viewport
227
- * and fit otherwise; `"fit"` always fit, for a viewer that should show the whole frame
259
+ * (inside the `fit` margin) and fit otherwise; `"fit"` always fit, for a viewer that should show the whole frame
228
260
  * whatever its size.
229
261
  */
230
262
  initialView?: "auto" | "fit" | undefined;
263
+ /**
264
+ * The margin and upscale cap of every fit: `initialView="fit"`, the handle's and the
265
+ * context's `fit()`, the `0` key, the double-click toggle, the toolbar's Fit button, and
266
+ * `isFit` / `data-fit`. Defaults to filling the viewport edge to edge, upscaling freely.
267
+ * Each field is read by value, so an inline object does not re-fit the view.
268
+ */
269
+ fit?: FitOptions | undefined;
231
270
  /** The stage's controls for code outside it; see `StageHandle`. */
232
271
  ref?: Ref<StageHandle> | undefined;
233
272
  }
@@ -237,6 +276,10 @@ export interface ImageStageProps {
237
276
  * size, so an overlay drawn in image coordinates stays registered with the photograph at
238
277
  * any zoom and window size. Layers read the transform through `useStage`.
239
278
  *
279
+ * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while
280
+ * the view changes and for 150 ms after, so a pan stays on the compositor and the layer
281
+ * re-rasterises sharp once the view settles.
282
+ *
240
283
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
241
284
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
242
285
  * or absent.
@@ -262,9 +305,11 @@ export function ImageStage({
262
305
  panKeys = true,
263
306
  label = "Image canvas",
264
307
  initialView: opening = "auto",
308
+ fit: fitOptions,
265
309
  ref,
266
310
  }: ImageStageProps) {
267
311
  const viewportRef = useRef<HTMLDivElement | null>(null);
312
+ const boxRef = useRef<HTMLDivElement | null>(null);
268
313
  const [box, setBox] = useState<Box>({ width: 0, height: 0 });
269
314
  // The measured size, readable synchronously — `setBox`'s updater must stay pure, and the
270
315
  // resize handler needs the *previous* box to re-anchor the view against.
@@ -275,30 +320,95 @@ export function ImageStage({
275
320
 
276
321
  // What the handlers attached once (and the stable callbacks below) read: the props and
277
322
  // box of the last commit, so none of them closes over stale values.
278
- const latestRef = useRef({ view, box, image, clamp, onView, opening });
323
+ const fitOpts = useMemo<FitOptions>(
324
+ () => ({ padding: fitOptions?.padding, upscale: fitOptions?.upscale }),
325
+ [fitOptions?.padding, fitOptions?.upscale],
326
+ );
327
+ const effective = useMemo(
328
+ () => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW),
329
+ [view, box, image, opening, fitOpts],
330
+ );
331
+
332
+ const latestRef = useRef({
333
+ view,
334
+ effective: UNMEASURED_VIEW,
335
+ box,
336
+ image,
337
+ clamp,
338
+ onView,
339
+ opening,
340
+ fitOpts,
341
+ });
279
342
  useLayoutEffect(() => {
280
- latestRef.current = { view, box, image, clamp, onView, opening };
343
+ latestRef.current = {
344
+ view,
345
+ effective,
346
+ box,
347
+ image,
348
+ clamp,
349
+ onView,
350
+ opening,
351
+ fitOpts,
352
+ };
281
353
  });
354
+ /** Whether the opening view of the current `null` view has been reported. */
355
+ const openedRef = useRef(false);
282
356
  /** The view to come back to when a double-click leaves fit. */
283
357
  const previousRef = useRef<StageView | null>(null);
284
358
  const dragRef = useRef<Drag | null>(null);
285
359
  /** The touches down now, by pointer id, in client coordinates. */
286
360
  const touchesRef = useRef(new Map<number, Point>());
287
361
  /** The two-finger gesture in progress, from the moment the second finger went down. */
288
- const pinchRef = useRef<{ distance: number; centre: Point; view: StageView } | null>(null);
362
+ const pinchRef = useRef<{
363
+ distance: number;
364
+ centre: Point;
365
+ view: StageView;
366
+ } | null>(null);
289
367
  /** The registry the stage's layers answer hit-tests through. */
290
368
  const [hits] = useState(() => createHitRegistry<StagePointerEvent>());
291
369
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
292
370
 
293
- const effective = useMemo(
294
- () => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW),
295
- [view, box, image, opening],
371
+ // `will-change: transform` (and `data-moving`) on the transformed box while the view moves, set
372
+ // on the element itself so a pan costs no React render; see `MOVING_SETTLE_MS`.
373
+ useEffect(() => {
374
+ const element = boxRef.current;
375
+ if (!element) return;
376
+ element.style.willChange = "transform";
377
+ element.dataset["moving"] = "";
378
+ const timer = setTimeout(() => {
379
+ element.style.willChange = "";
380
+ delete element.dataset["moving"];
381
+ }, MOVING_SETTLE_MS);
382
+ return () => clearTimeout(timer);
383
+ }, [effective.scale, effective.tx, effective.ty]);
384
+
385
+ /** Report a view with its cause and the viewport it was made for (the measured one by default). */
386
+ const emit = useCallback((next: StageView, cause: StageViewChange["cause"], box?: Box) => {
387
+ const { box: b, onView: report } = latestRef.current;
388
+ report(next, { cause, box: box ?? b });
389
+ }, []);
390
+
391
+ const commit = useCallback(
392
+ (next: StageView, cause: StageViewChange["cause"] = "command") => {
393
+ const { box: b, image: i, clamp: c } = latestRef.current;
394
+ emit(b.width > 0 ? clampView(next, b, i, c) : next, cause);
395
+ },
396
+ [emit],
296
397
  );
297
398
 
298
- const commit = useCallback((next: StageView) => {
299
- const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
300
- report(b.width > 0 ? clampView(next, b, i, c) : next);
301
- }, []);
399
+ // A `null` view the stage has already measured: `measure` only fires when the size changes,
400
+ // so without this the opening view was drawn but never reported, and the pane stayed on a
401
+ // view the app did not hold. Once per null period; a non-null view re-arms it.
402
+ useEffect(() => {
403
+ if (view !== null) {
404
+ openedRef.current = false;
405
+ return;
406
+ }
407
+ if (box.width > 0 && !openedRef.current) {
408
+ openedRef.current = true;
409
+ emit(openingView(opening, box, image, fitOpts), "measure");
410
+ }
411
+ }, [view, box, image, opening, fitOpts, emit]);
302
412
 
303
413
  /*
304
414
  * The viewport, measured and observed from the moment it mounts (a callback ref with a
@@ -313,54 +423,63 @@ export function ImageStage({
313
423
  * as **passive**, which makes `preventDefault` in a synthetic handler a no-op — the page
314
424
  * would scroll behind the canvas while you zoom, which reads as the zoom being broken.
315
425
  */
316
- const attachViewport = useCallback((element: HTMLDivElement | null) => {
317
- viewportRef.current = element;
318
- if (!element) return;
319
-
320
- const measure = ({ width, height }: Box) => {
321
- if (!(width > 0) || !(height > 0)) return;
322
- const current = measuredRef.current;
323
- if (current.width === width && current.height === height) return;
324
- const next = { width, height };
325
- measuredRef.current = next;
326
- setBox(next);
327
- const { view: v, image: i, clamp: c, onView: report, opening: o } = latestRef.current;
328
- if (v === null) report(openingView(o, next, i));
329
- // The first measurement: there is no previous viewport to re-anchor against, so the
330
- // caller's view is kept — only made legal for this one.
331
- else if (!(current.width > 0)) report(clampView(v, next, i, c));
332
- else report(preserveCenter(v, current, next, i, c));
333
- };
426
+ const attachViewport = useCallback(
427
+ (element: HTMLDivElement | null) => {
428
+ viewportRef.current = element;
429
+ if (!element) return;
430
+
431
+ const measure = ({ width, height }: Box) => {
432
+ if (!(width > 0) || !(height > 0)) return;
433
+ const current = measuredRef.current;
434
+ if (current.width === width && current.height === height) return;
435
+ const next = { width, height };
436
+ measuredRef.current = next;
437
+ setBox(next);
438
+ const { view: v, image: i, clamp: c, opening: o, fitOpts: f } = latestRef.current;
439
+ if (v === null) {
440
+ openedRef.current = true;
441
+ emit(openingView(o, next, i, f), "measure", next);
442
+ }
443
+ // The first measurement: there is no previous viewport to re-anchor against, so the
444
+ // caller's view is kept — only made legal for this one.
445
+ else if (!(current.width > 0)) emit(clampView(v, next, i, c), "measure", next);
446
+ else emit(preserveCenter(v, current, next, i, c, f), "measure", next);
447
+ };
334
448
 
335
- // Synchronously, so the first paint already has the right view — and as the *content*
336
- // box, which is what the observer reports; measuring the border box here re-anchored
337
- // the view by the border's width as soon as the observer's first report arrived.
338
- measure(contentSize(element));
339
- const observer = new ResizeObserver((entries) => {
340
- const entry = entries[0];
341
- if (entry) measure(entry.contentRect);
342
- });
343
- observer.observe(element);
344
-
345
- const onWheel = (event: WheelEvent) => {
346
- event.preventDefault();
347
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
348
- if (v === null || !(b.width > 0)) return;
349
- const origin = viewportOrigin(element);
350
- const [min, max] = scaleRange(b, i, c);
351
- const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
352
- const scale = Math.min(max, Math.max(min, v.scale * factor));
353
- const anchor = { x: event.clientX - origin.x, y: event.clientY - origin.y };
354
- report(clampView(zoomAbout(v, scale, anchor), b, i, c));
355
- };
356
- element.addEventListener("wheel", onWheel, { passive: false });
449
+ // Synchronously, so the first paint already has the right view — and as the *content*
450
+ // box, which is what the observer reports; measuring the border box here re-anchored
451
+ // the view by the border's width as soon as the observer's first report arrived.
452
+ measure(contentSize(element));
453
+ const observer = new ResizeObserver((entries) => {
454
+ const entry = entries[0];
455
+ if (entry) measure(entry.contentRect);
456
+ });
457
+ observer.observe(element);
458
+
459
+ const onWheel = (event: WheelEvent) => {
460
+ event.preventDefault();
461
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
462
+ if (!(b.width > 0)) return;
463
+ const origin = viewportOrigin(element);
464
+ const [min, max] = scaleRange(b, i, c);
465
+ const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
466
+ const scale = Math.min(max, Math.max(min, v.scale * factor));
467
+ const anchor = {
468
+ x: event.clientX - origin.x,
469
+ y: event.clientY - origin.y,
470
+ };
471
+ emit(clampView(zoomAbout(v, scale, anchor), b, i, c), "gesture");
472
+ };
473
+ element.addEventListener("wheel", onWheel, { passive: false });
357
474
 
358
- return () => {
359
- observer.disconnect();
360
- element.removeEventListener("wheel", onWheel);
361
- viewportRef.current = null;
362
- };
363
- }, []);
475
+ return () => {
476
+ observer.disconnect();
477
+ element.removeEventListener("wheel", onWheel);
478
+ viewportRef.current = null;
479
+ };
480
+ },
481
+ [emit],
482
+ );
364
483
 
365
484
  /* Space is a *modifier*, not a command: held, it turns any press into a pan, which is the
366
485
  * one gesture that has to work no matter which layer is under the cursor. */
@@ -385,49 +504,60 @@ export function ImageStage({
385
504
 
386
505
  const clientToImage = useCallback((p: Point): Point => {
387
506
  const element = viewportRef.current;
388
- const { view: v } = latestRef.current;
389
- if (!element || v === null) return { x: 0, y: 0 };
507
+ const { view: held, effective: v, box: b } = latestRef.current;
508
+ // Unmeasured and uncontrolled: there is no view to convert with yet.
509
+ if (!element || (held === null && !(b.width > 0))) return { x: 0, y: 0 };
390
510
  const origin = viewportOrigin(element);
391
511
  return toImage(v, { x: p.x - origin.x, y: p.y - origin.y });
392
512
  }, []);
393
513
 
394
514
  const imageToClient = useCallback((p: Point): Point => {
395
515
  const element = viewportRef.current;
396
- const { view: v } = latestRef.current;
397
- if (!element || v === null) return { x: 0, y: 0 };
516
+ const { view: held, effective: v, box: b } = latestRef.current;
517
+ // Unmeasured and uncontrolled: there is no view to convert with yet.
518
+ if (!element || (held === null && !(b.width > 0))) return { x: 0, y: 0 };
398
519
  const origin = viewportOrigin(element);
399
520
  const local = toScreen(v, p);
400
521
  return { x: local.x + origin.x, y: local.y + origin.y };
401
522
  }, []);
402
523
 
403
- const fit = useCallback(() => {
404
- const { box: b, image: i, view: v, onView: report } = latestRef.current;
405
- if (!(b.width > 0)) return;
406
- if (v !== null && !isFit(v, b, i)) previousRef.current = v;
407
- report(fitView(b, i));
408
- }, []);
409
-
410
- const zoomTo = useCallback((scale: number, anchor?: Point) => {
411
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
412
- const element = viewportRef.current;
413
- if (v === null || !(b.width > 0) || !element) return;
414
- const origin = viewportOrigin(element);
415
- const local = anchor
416
- ? { x: anchor.x - origin.x, y: anchor.y - origin.y }
417
- : { x: b.width / 2, y: b.height / 2 };
418
- const [min, max] = scaleRange(b, i, c);
419
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
420
- }, []);
524
+ const fitBy = useCallback(
525
+ (cause: StageViewChange["cause"]) => {
526
+ const { box: b, image: i, view: v, fitOpts: f } = latestRef.current;
527
+ if (!(b.width > 0)) return;
528
+ if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
529
+ emit(fitView(b, i, f), cause);
530
+ },
531
+ [emit],
532
+ );
533
+ const fit = useCallback(() => fitBy("command"), [fitBy]);
421
534
 
422
- const frame = useCallback((rect: Rect, pad?: number) => {
423
- const { box: b, image: i, onView: report } = latestRef.current;
424
- if (!(b.width > 0)) return;
425
- report(frameRect(b, i, rect, pad));
426
- }, []);
535
+ const zoomBy = useCallback(
536
+ (cause: StageViewChange["cause"], scale: number, anchor?: Point) => {
537
+ const { effective: v, box: b, image: i, clamp: c } = latestRef.current;
538
+ const element = viewportRef.current;
539
+ if (!(b.width > 0) || !element) return;
540
+ const origin = viewportOrigin(element);
541
+ const local = anchor ? { x: anchor.x - origin.x, y: anchor.y - origin.y } : { x: b.width / 2, y: b.height / 2 };
542
+ const [min, max] = scaleRange(b, i, c);
543
+ emit(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c), cause);
544
+ },
545
+ [emit],
546
+ );
547
+ const zoomTo = useCallback((scale: number, anchor?: Point) => zoomBy("command", scale, anchor), [zoomBy]);
548
+
549
+ const frame = useCallback(
550
+ (rect: Rect, pad?: number) => {
551
+ const { box: b, image: i } = latestRef.current;
552
+ if (!(b.width > 0)) return;
553
+ emit(frameRect(b, i, rect, pad), "command");
554
+ },
555
+ [emit],
556
+ );
427
557
 
428
558
  useImperativeHandle(ref, () => ({ frame, fit, zoomTo }), [frame, fit, zoomTo]);
429
559
 
430
- const atFit = box.width > 0 && isFit(effective, box, image);
560
+ const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);
431
561
 
432
562
  const context = useMemo<StageContext>(
433
563
  () => ({
@@ -446,25 +576,11 @@ export function ImageStage({
446
576
  panning,
447
577
  panMode,
448
578
  }),
449
- [
450
- effective,
451
- commit,
452
- image,
453
- box,
454
- clientToImage,
455
- imageToClient,
456
- frame,
457
- fit,
458
- zoomTo,
459
- atFit,
460
- panning,
461
- panMode,
462
- ],
579
+ [effective, commit, image, box, clientToImage, imageToClient, frame, fit, zoomTo, atFit, panning, panMode],
463
580
  );
464
581
 
465
582
  /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */
466
- const hitRadius = (event: { pointerType: string }) =>
467
- imageLengthFor(effective, event.pointerType === "touch" ? TOUCH_RADIUS : POINTER_RADIUS);
583
+ const hitRadius = (event: { pointerType: string }) => imageLengthFor(effective, hitRadiusPx(event.pointerType));
468
584
 
469
585
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
470
586
  const routePress = (event: ReactPointerEvent<HTMLDivElement>) =>
@@ -528,7 +644,7 @@ export function ImageStage({
528
644
  // During a pan the pointer is holding the image, not pointing at a pixel.
529
645
  onHover?.(null);
530
646
  hits.clearHover();
531
- commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy });
647
+ commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy }, "gesture");
532
648
  };
533
649
 
534
650
  const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
@@ -536,7 +652,9 @@ export function ImageStage({
536
652
  if (origin?.touch) return; // a touch ends through `touchEnd`
537
653
  dragRef.current = null;
538
654
  setPanning(false);
539
- if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
655
+ if (origin && !origin.moved && event.button === 0) {
656
+ onBackgroundClick?.(event, clientToImage({ x: event.clientX, y: event.clientY }));
657
+ }
540
658
  };
541
659
 
542
660
  /*
@@ -604,6 +722,7 @@ export function ImageStage({
604
722
  { x: mid.x - origin.x, y: mid.y - origin.y },
605
723
  scaleRange(box, image, clamp),
606
724
  ),
725
+ "gesture",
607
726
  );
608
727
  return;
609
728
  }
@@ -616,7 +735,7 @@ export function ImageStage({
616
735
  if (!drag.pan) return;
617
736
  setPanning(true);
618
737
  onHover?.(null);
619
- commit({ scale: effective.scale, tx: drag.tx + dx, ty: drag.ty + dy });
738
+ commit({ scale: effective.scale, tx: drag.tx + dx, ty: drag.ty + dy }, "gesture");
620
739
  };
621
740
 
622
741
  const touchEnd = (event: ReactPointerEvent<HTMLDivElement>, cancelled: boolean) => {
@@ -646,7 +765,7 @@ export function ImageStage({
646
765
  dragRef.current = null;
647
766
  setPanning(false);
648
767
  if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
649
- if (!routePress(event)) onBackgroundClick?.(event);
768
+ if (!routePress(event)) onBackgroundClick?.(event, clientToImage({ x: event.clientX, y: event.clientY }));
650
769
  };
651
770
 
652
771
  /*
@@ -659,14 +778,14 @@ export function ImageStage({
659
778
  if (atFit) {
660
779
  const restore = previousRef.current;
661
780
  if (restore) {
662
- onView(clampView(restore, box, image, clamp));
781
+ emit(clampView(restore, box, image, clamp), "gesture");
663
782
  } else {
664
- zoomTo(1, { x: event.clientX, y: event.clientY });
783
+ zoomBy("gesture", 1, { x: event.clientX, y: event.clientY });
665
784
  }
666
785
  return;
667
786
  }
668
787
  previousRef.current = effective;
669
- onView(fitView(box, image));
788
+ emit(fitView(box, image, fitOpts), "gesture");
670
789
  };
671
790
 
672
791
  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -676,33 +795,33 @@ export function ImageStage({
676
795
  switch (event.key) {
677
796
  case "+":
678
797
  case "=":
679
- zoomTo(Math.min(max, effective.scale * 1.5));
798
+ zoomBy("key", Math.min(max, effective.scale * 1.5));
680
799
  break;
681
800
  case "-":
682
801
  case "_":
683
- zoomTo(Math.max(min, effective.scale / 1.5));
802
+ zoomBy("key", Math.max(min, effective.scale / 1.5));
684
803
  break;
685
804
  case "0":
686
- fit();
805
+ fitBy("key");
687
806
  break;
688
807
  case "1":
689
- zoomTo(1);
808
+ zoomBy("key", 1);
690
809
  break;
691
810
  case "ArrowLeft":
692
811
  if (!panKeys) return;
693
- commit({ ...effective, tx: effective.tx + nudge });
812
+ commit({ ...effective, tx: effective.tx + nudge }, "key");
694
813
  break;
695
814
  case "ArrowRight":
696
815
  if (!panKeys) return;
697
- commit({ ...effective, tx: effective.tx - nudge });
816
+ commit({ ...effective, tx: effective.tx - nudge }, "key");
698
817
  break;
699
818
  case "ArrowUp":
700
819
  if (!panKeys) return;
701
- commit({ ...effective, ty: effective.ty + nudge });
820
+ commit({ ...effective, ty: effective.ty + nudge }, "key");
702
821
  break;
703
822
  case "ArrowDown":
704
823
  if (!panKeys) return;
705
- commit({ ...effective, ty: effective.ty - nudge });
824
+ commit({ ...effective, ty: effective.ty - nudge }, "key");
706
825
  break;
707
826
  default:
708
827
  return;
@@ -749,6 +868,7 @@ export function ImageStage({
749
868
  >
750
869
  {/* One transformed box holding every layer, laid out at the image's own pixel size. */}
751
870
  <div
871
+ ref={boxRef}
752
872
  data-stage
753
873
  className="absolute top-0 left-0 origin-top-left"
754
874
  style={{
@@ -783,8 +903,8 @@ export function ImageStage({
783
903
  }
784
904
 
785
905
  /** The view a `null` view opens at, by the `initialView` policy. */
786
- function openingView(opening: "auto" | "fit", box: Box, image: Box): StageView {
787
- return opening === "fit" ? fitView(box, image) : initialView(box, image);
906
+ function openingView(opening: "auto" | "fit", box: Box, image: Box, fit: FitOptions): StageView {
907
+ return opening === "fit" ? fitView(box, image, fit) : initialView(box, image, fit);
788
908
  }
789
909
 
790
910
  function hoverPoint(
@@ -795,7 +915,10 @@ function hoverPoint(
795
915
  ): Point | null {
796
916
  if (!element) return null;
797
917
  const origin = viewportOrigin(element);
798
- const p = toImage(view, { x: event.clientX - origin.x, y: event.clientY - origin.y });
918
+ const p = toImage(view, {
919
+ x: event.clientX - origin.x,
920
+ y: event.clientY - origin.y,
921
+ });
799
922
  return insideImage(p, image) ? p : null;
800
923
  }
801
924