@vitavision/stage2d 0.11.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.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * How `AreaSet` groups its regions into batched paths: by appearance (state, role, colours),
3
+ * either one batch per appearance or consecutive runs in item order. Pure, so the keys are
4
+ * unit-tested without a DOM (ADR-0004 rule 1).
5
+ */
6
+
7
+ import { areaPath, type Area, type AreaId } from "./areaIndex";
8
+ import type { OverlayRole } from "./overlayRole";
9
+
10
+ /** An item as batching sees it: a region and its appearance overrides. */
11
+ export interface BatchableArea extends Area {
12
+ role?: OverlayRole | undefined;
13
+ stroke?: string | undefined;
14
+ fill?: string | undefined;
15
+ }
16
+
17
+ /** The regions of one batched path. */
18
+ export interface AreaBatch {
19
+ /** The appearance key; several runs of one appearance share it under `paintOrder: "items"`. */
20
+ key: string;
21
+ /** A unique key for rendering (the appearance key, plus the run number for runs). */
22
+ id: string;
23
+ role: OverlayRole;
24
+ /** The outline colour when the item or the layer set one; `undefined` paints the role. */
25
+ stroke: string | undefined;
26
+ /** The fill colour when an item set one; `undefined` paints the outline colour. */
27
+ fill: string | undefined;
28
+ dim: boolean;
29
+ /** Item positions, ascending. */
30
+ indices: number[];
31
+ /** The outlines, concatenated (without the selected items under `selectionFill: "item"`). */
32
+ d: string;
33
+ /** Each item's own ring, aligned with `indices`, when fills are drawn apart from outlines. */
34
+ fills: string[] | null;
35
+ }
36
+
37
+ /** What decides the batches. */
38
+ export interface AreaBatchOptions {
39
+ /** The role of an item that names none. */
40
+ role: OverlayRole;
41
+ /** The layer's outline colour. */
42
+ stroke: string | undefined;
43
+ /** `"items"` makes batches consecutive runs in item order. */
44
+ paintOrder: "appearance" | "items";
45
+ /** `"evenodd"` gives every item its own fill path. */
46
+ fillRule: "nonzero" | "evenodd";
47
+ /** `"item"` keeps a selected item in its own batch, fill included. */
48
+ selectionFill: "selection" | "item";
49
+ selected: ReadonlySet<AreaId>;
50
+ isDimmed: (id: AreaId) => boolean;
51
+ }
52
+
53
+ /**
54
+ * The appearance key of an item. Without a custom colour it is `dim|role`, as before colours
55
+ * existed; a custom colour appends the outline and fill it was given.
56
+ *
57
+ * @param dim - Whether the item is dimmed.
58
+ * @param role - The item's role.
59
+ * @param stroke - The outline colour, if any.
60
+ * @param fill - The fill colour, if any.
61
+ * @returns The key.
62
+ */
63
+ export function areaBatchKey(dim: boolean, role: OverlayRole, stroke: string | undefined, fill: string | undefined): string {
64
+ const base = `${dim ? 1 : 0}|${role}`;
65
+ return stroke || fill ? `${base}|${stroke ?? ""}|${fill ?? ""}` : base;
66
+ }
67
+
68
+ /**
69
+ * Groups items into batches. Selected items go to `picked` (drawn on top in the selection
70
+ * colour), unless `selectionFill` is `"item"`: then they stay in their batch for the fill and
71
+ * `picked` carries only their outlines.
72
+ *
73
+ * @param items - The regions.
74
+ * @param options - What decides the grouping.
75
+ * @returns The appearance batches in paint order, and the selected overlay.
76
+ */
77
+ export function batchAreas(items: readonly BatchableArea[], options: AreaBatchOptions): { normal: AreaBatch[]; picked: AreaBatch | null } {
78
+ const { role, stroke, paintOrder, fillRule, selectionFill, selected, isDimmed } = options;
79
+ const keepSelected = selectionFill === "item";
80
+ // Fills apart from outlines: needed per item for even-odd, and to leave selected outlines out.
81
+ const separate = fillRule === "evenodd" || keepSelected;
82
+ const byKey = new Map<string, AreaBatch>();
83
+ const runs: AreaBatch[] = [];
84
+ const picked: AreaBatch = { key: "selected", id: "selected", role: "selection", stroke: undefined, fill: undefined, dim: false, indices: [], d: "", fills: fillRule === "evenodd" && !keepSelected ? [] : null };
85
+
86
+ items.forEach((item, i) => {
87
+ const isSelected = selected.has(item.id);
88
+ if (isSelected) {
89
+ const d = areaPath(item.points);
90
+ picked.indices.push(i);
91
+ picked.d += d;
92
+ picked.fills?.push(d);
93
+ if (!keepSelected) return;
94
+ }
95
+ const itemRole = item.role ?? role;
96
+ const itemStroke = item.stroke ?? stroke;
97
+ const dim = isDimmed(item.id);
98
+ const key = areaBatchKey(dim, itemRole, itemStroke, item.fill);
99
+ let batch = paintOrder === "items" ? runs[runs.length - 1] : byKey.get(key);
100
+ if (!batch || batch.key !== key) {
101
+ batch = { key, id: paintOrder === "items" ? `${key}#${runs.length}` : key, role: itemRole, stroke: itemStroke, fill: item.fill, dim, indices: [], d: "", fills: separate ? [] : null };
102
+ byKey.set(key, batch);
103
+ runs.push(batch);
104
+ }
105
+ const d = areaPath(item.points);
106
+ batch.indices.push(i);
107
+ batch.fills?.push(d);
108
+ if (!(isSelected && keepSelected)) batch.d += d;
109
+ });
110
+ return { normal: runs, picked: picked.indices.length > 0 ? picked : null };
111
+ }
@@ -104,6 +104,21 @@ interface Drag {
104
104
  pointerId: number;
105
105
  }
106
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
+
107
122
  /** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */
108
123
  export interface StageContext {
109
124
  /** The view in effect — the controlled `view`, or the opening view while that is `null`. */
@@ -179,8 +194,13 @@ export interface ImageStageProps {
179
194
  * view is kept on first measure, only clamped to the legal range.
180
195
  */
181
196
  view: StageView | null;
182
- /** Called with every view change: gestures, keys, toolbar, and viewport resizes. */
183
- 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;
184
204
  /** Layers, each `absolute inset-0` and sized by the stage. */
185
205
  children: ReactNode;
186
206
  /** Rendered floating over the bottom-left, outside the transform. */
@@ -217,8 +237,11 @@ export interface ImageStageProps {
217
237
  style?: CSSProperties;
218
238
  /** Where the pointer is over the image, in image pixels, or `null` when it is outside. */
219
239
  onHover?: (point: Point | null) => void;
220
- /** A press on the background that was not a pan — how a layer hears "deselect". */
221
- 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;
222
245
  /** The legal scale range; see `clampView`. */
223
246
  clamp?: ClampOptions;
224
247
  /** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */
@@ -301,26 +324,50 @@ export function ImageStage({
301
324
  () => ({ padding: fitOptions?.padding, upscale: fitOptions?.upscale }),
302
325
  [fitOptions?.padding, fitOptions?.upscale],
303
326
  );
304
- const latestRef = useRef({ view, box, image, clamp, onView, opening, fitOpts });
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
+ });
305
342
  useLayoutEffect(() => {
306
- latestRef.current = { view, box, image, clamp, onView, opening, fitOpts };
343
+ latestRef.current = {
344
+ view,
345
+ effective,
346
+ box,
347
+ image,
348
+ clamp,
349
+ onView,
350
+ opening,
351
+ fitOpts,
352
+ };
307
353
  });
354
+ /** Whether the opening view of the current `null` view has been reported. */
355
+ const openedRef = useRef(false);
308
356
  /** The view to come back to when a double-click leaves fit. */
309
357
  const previousRef = useRef<StageView | null>(null);
310
358
  const dragRef = useRef<Drag | null>(null);
311
359
  /** The touches down now, by pointer id, in client coordinates. */
312
360
  const touchesRef = useRef(new Map<number, Point>());
313
361
  /** The two-finger gesture in progress, from the moment the second finger went down. */
314
- 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);
315
367
  /** The registry the stage's layers answer hit-tests through. */
316
368
  const [hits] = useState(() => createHitRegistry<StagePointerEvent>());
317
369
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
318
370
 
319
- const effective = useMemo(
320
- () => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW),
321
- [view, box, image, opening, fitOpts],
322
- );
323
-
324
371
  // `will-change: transform` (and `data-moving`) on the transformed box while the view moves, set
325
372
  // on the element itself so a pan costs no React render; see `MOVING_SETTLE_MS`.
326
373
  useEffect(() => {
@@ -335,11 +382,34 @@ export function ImageStage({
335
382
  return () => clearTimeout(timer);
336
383
  }, [effective.scale, effective.tx, effective.ty]);
337
384
 
338
- const commit = useCallback((next: StageView) => {
339
- const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
340
- report(b.width > 0 ? clampView(next, b, i, c) : next);
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 });
341
389
  }, []);
342
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],
397
+ );
398
+
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]);
412
+
343
413
  /*
344
414
  * The viewport, measured and observed from the moment it mounts (a callback ref with a
345
415
  * cleanup, so the subscription lives exactly as long as the element).
@@ -353,54 +423,63 @@ export function ImageStage({
353
423
  * as **passive**, which makes `preventDefault` in a synthetic handler a no-op — the page
354
424
  * would scroll behind the canvas while you zoom, which reads as the zoom being broken.
355
425
  */
356
- const attachViewport = useCallback((element: HTMLDivElement | null) => {
357
- viewportRef.current = element;
358
- if (!element) return;
359
-
360
- const measure = ({ width, height }: Box) => {
361
- if (!(width > 0) || !(height > 0)) return;
362
- const current = measuredRef.current;
363
- if (current.width === width && current.height === height) return;
364
- const next = { width, height };
365
- measuredRef.current = next;
366
- setBox(next);
367
- const { view: v, image: i, clamp: c, onView: report, opening: o, fitOpts: f } = latestRef.current;
368
- if (v === null) report(openingView(o, next, i, f));
369
- // The first measurement: there is no previous viewport to re-anchor against, so the
370
- // caller's view is kept — only made legal for this one.
371
- else if (!(current.width > 0)) report(clampView(v, next, i, c));
372
- else report(preserveCenter(v, current, next, i, c, f));
373
- };
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
+ };
374
448
 
375
- // Synchronously, so the first paint already has the right view — and as the *content*
376
- // box, which is what the observer reports; measuring the border box here re-anchored
377
- // the view by the border's width as soon as the observer's first report arrived.
378
- measure(contentSize(element));
379
- const observer = new ResizeObserver((entries) => {
380
- const entry = entries[0];
381
- if (entry) measure(entry.contentRect);
382
- });
383
- observer.observe(element);
384
-
385
- const onWheel = (event: WheelEvent) => {
386
- event.preventDefault();
387
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
388
- if (v === null || !(b.width > 0)) return;
389
- const origin = viewportOrigin(element);
390
- const [min, max] = scaleRange(b, i, c);
391
- const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);
392
- const scale = Math.min(max, Math.max(min, v.scale * factor));
393
- const anchor = { x: event.clientX - origin.x, y: event.clientY - origin.y };
394
- report(clampView(zoomAbout(v, scale, anchor), b, i, c));
395
- };
396
- 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 });
397
474
 
398
- return () => {
399
- observer.disconnect();
400
- element.removeEventListener("wheel", onWheel);
401
- viewportRef.current = null;
402
- };
403
- }, []);
475
+ return () => {
476
+ observer.disconnect();
477
+ element.removeEventListener("wheel", onWheel);
478
+ viewportRef.current = null;
479
+ };
480
+ },
481
+ [emit],
482
+ );
404
483
 
405
484
  /* Space is a *modifier*, not a command: held, it turns any press into a pan, which is the
406
485
  * one gesture that has to work no matter which layer is under the cursor. */
@@ -425,45 +504,56 @@ export function ImageStage({
425
504
 
426
505
  const clientToImage = useCallback((p: Point): Point => {
427
506
  const element = viewportRef.current;
428
- const { view: v } = latestRef.current;
429
- 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 };
430
510
  const origin = viewportOrigin(element);
431
511
  return toImage(v, { x: p.x - origin.x, y: p.y - origin.y });
432
512
  }, []);
433
513
 
434
514
  const imageToClient = useCallback((p: Point): Point => {
435
515
  const element = viewportRef.current;
436
- const { view: v } = latestRef.current;
437
- 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 };
438
519
  const origin = viewportOrigin(element);
439
520
  const local = toScreen(v, p);
440
521
  return { x: local.x + origin.x, y: local.y + origin.y };
441
522
  }, []);
442
523
 
443
- const fit = useCallback(() => {
444
- const { box: b, image: i, view: v, onView: report, fitOpts: f } = latestRef.current;
445
- if (!(b.width > 0)) return;
446
- if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
447
- report(fitView(b, i, f));
448
- }, []);
449
-
450
- const zoomTo = useCallback((scale: number, anchor?: Point) => {
451
- const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;
452
- const element = viewportRef.current;
453
- if (v === null || !(b.width > 0) || !element) return;
454
- const origin = viewportOrigin(element);
455
- const local = anchor
456
- ? { x: anchor.x - origin.x, y: anchor.y - origin.y }
457
- : { x: b.width / 2, y: b.height / 2 };
458
- const [min, max] = scaleRange(b, i, c);
459
- report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));
460
- }, []);
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]);
461
534
 
462
- const frame = useCallback((rect: Rect, pad?: number) => {
463
- const { box: b, image: i, onView: report } = latestRef.current;
464
- if (!(b.width > 0)) return;
465
- report(frameRect(b, i, rect, pad));
466
- }, []);
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
+ );
467
557
 
468
558
  useImperativeHandle(ref, () => ({ frame, fit, zoomTo }), [frame, fit, zoomTo]);
469
559
 
@@ -486,25 +576,11 @@ export function ImageStage({
486
576
  panning,
487
577
  panMode,
488
578
  }),
489
- [
490
- effective,
491
- commit,
492
- image,
493
- box,
494
- clientToImage,
495
- imageToClient,
496
- frame,
497
- fit,
498
- zoomTo,
499
- atFit,
500
- panning,
501
- panMode,
502
- ],
579
+ [effective, commit, image, box, clientToImage, imageToClient, frame, fit, zoomTo, atFit, panning, panMode],
503
580
  );
504
581
 
505
582
  /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */
506
- const hitRadius = (event: { pointerType: string }) =>
507
- imageLengthFor(effective, hitRadiusPx(event.pointerType));
583
+ const hitRadius = (event: { pointerType: string }) => imageLengthFor(effective, hitRadiusPx(event.pointerType));
508
584
 
509
585
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
510
586
  const routePress = (event: ReactPointerEvent<HTMLDivElement>) =>
@@ -568,7 +644,7 @@ export function ImageStage({
568
644
  // During a pan the pointer is holding the image, not pointing at a pixel.
569
645
  onHover?.(null);
570
646
  hits.clearHover();
571
- 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");
572
648
  };
573
649
 
574
650
  const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
@@ -576,7 +652,9 @@ export function ImageStage({
576
652
  if (origin?.touch) return; // a touch ends through `touchEnd`
577
653
  dragRef.current = null;
578
654
  setPanning(false);
579
- 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
+ }
580
658
  };
581
659
 
582
660
  /*
@@ -644,6 +722,7 @@ export function ImageStage({
644
722
  { x: mid.x - origin.x, y: mid.y - origin.y },
645
723
  scaleRange(box, image, clamp),
646
724
  ),
725
+ "gesture",
647
726
  );
648
727
  return;
649
728
  }
@@ -656,7 +735,7 @@ export function ImageStage({
656
735
  if (!drag.pan) return;
657
736
  setPanning(true);
658
737
  onHover?.(null);
659
- 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");
660
739
  };
661
740
 
662
741
  const touchEnd = (event: ReactPointerEvent<HTMLDivElement>, cancelled: boolean) => {
@@ -686,7 +765,7 @@ export function ImageStage({
686
765
  dragRef.current = null;
687
766
  setPanning(false);
688
767
  if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
689
- if (!routePress(event)) onBackgroundClick?.(event);
768
+ if (!routePress(event)) onBackgroundClick?.(event, clientToImage({ x: event.clientX, y: event.clientY }));
690
769
  };
691
770
 
692
771
  /*
@@ -699,14 +778,14 @@ export function ImageStage({
699
778
  if (atFit) {
700
779
  const restore = previousRef.current;
701
780
  if (restore) {
702
- onView(clampView(restore, box, image, clamp));
781
+ emit(clampView(restore, box, image, clamp), "gesture");
703
782
  } else {
704
- zoomTo(1, { x: event.clientX, y: event.clientY });
783
+ zoomBy("gesture", 1, { x: event.clientX, y: event.clientY });
705
784
  }
706
785
  return;
707
786
  }
708
787
  previousRef.current = effective;
709
- onView(fitView(box, image, fitOpts));
788
+ emit(fitView(box, image, fitOpts), "gesture");
710
789
  };
711
790
 
712
791
  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -716,33 +795,33 @@ export function ImageStage({
716
795
  switch (event.key) {
717
796
  case "+":
718
797
  case "=":
719
- zoomTo(Math.min(max, effective.scale * 1.5));
798
+ zoomBy("key", Math.min(max, effective.scale * 1.5));
720
799
  break;
721
800
  case "-":
722
801
  case "_":
723
- zoomTo(Math.max(min, effective.scale / 1.5));
802
+ zoomBy("key", Math.max(min, effective.scale / 1.5));
724
803
  break;
725
804
  case "0":
726
- fit();
805
+ fitBy("key");
727
806
  break;
728
807
  case "1":
729
- zoomTo(1);
808
+ zoomBy("key", 1);
730
809
  break;
731
810
  case "ArrowLeft":
732
811
  if (!panKeys) return;
733
- commit({ ...effective, tx: effective.tx + nudge });
812
+ commit({ ...effective, tx: effective.tx + nudge }, "key");
734
813
  break;
735
814
  case "ArrowRight":
736
815
  if (!panKeys) return;
737
- commit({ ...effective, tx: effective.tx - nudge });
816
+ commit({ ...effective, tx: effective.tx - nudge }, "key");
738
817
  break;
739
818
  case "ArrowUp":
740
819
  if (!panKeys) return;
741
- commit({ ...effective, ty: effective.ty + nudge });
820
+ commit({ ...effective, ty: effective.ty + nudge }, "key");
742
821
  break;
743
822
  case "ArrowDown":
744
823
  if (!panKeys) return;
745
- commit({ ...effective, ty: effective.ty - nudge });
824
+ commit({ ...effective, ty: effective.ty - nudge }, "key");
746
825
  break;
747
826
  default:
748
827
  return;
@@ -836,7 +915,10 @@ function hoverPoint(
836
915
  ): Point | null {
837
916
  if (!element) return null;
838
917
  const origin = viewportOrigin(element);
839
- 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
+ });
840
922
  return insideImage(p, image) ? p : null;
841
923
  }
842
924