@vitavision/stage2d 0.8.1 → 0.10.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.
@@ -254,7 +254,8 @@ export function polylineBounds(points: ArrayLike<number>): Rect | null {
254
254
  return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
255
255
  }
256
256
 
257
- function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {
257
+ /** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */
258
+ export function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {
258
259
  const dx = bx - ax;
259
260
  const dy = by - ay;
260
261
  const len2 = dx * dx + dy * dy;
@@ -262,8 +263,8 @@ function closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: numb
262
263
  return { x: ax + t * dx, y: ay + t * dy };
263
264
  }
264
265
 
265
- /** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */
266
- function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
266
+ /** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). Shared with `areaIndex.ts`. */
267
+ export function segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {
267
268
  const xmin = r.x;
268
269
  const xmax = r.x + r.width;
269
270
  const ymin = r.y;
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The arithmetic of editing a rotated rectangle or ellipse: eight handles, a rotation handle
3
+ * and an interior.
4
+ *
5
+ * A shape is its centre, its size and a rotation, so a resize can be done in the shape's own
6
+ * frame (where its sides are axis-aligned) and the opposite edge stays put whatever the
7
+ * rotation. Kept pure, so the cases that bite are tested without a pointer:
8
+ * - a handle dragged across the shape, or to a point far away;
9
+ * - a shape collapsed below the minimum size;
10
+ * - a rotation about the centre and not about a corner.
11
+ *
12
+ * Everything is in the stage's image coordinates. **Rotation is in radians, positive
13
+ * clockwise on screen** (image `y` points down), zero when the shape's width runs along `x`.
14
+ * A degrees-clockwise value, such as Konva's `rotation`, is `degrees * Math.PI / 180`.
15
+ */
16
+
17
+ import type { Point } from "./measureGeometry";
18
+ import type { RoiHandle } from "./roiEdit";
19
+
20
+ /** A rotated rectangle, or the ellipse inscribed in one. */
21
+ export interface RotatedShape {
22
+ /** Centre x, in image coordinates. */
23
+ cx: number;
24
+ /** Centre y, in image coordinates. */
25
+ cy: number;
26
+ /** Extent along the shape's own x axis: a rectangle's width, an ellipse's full axis `2·rx`. */
27
+ width: number;
28
+ /** Extent along the shape's own y axis: a rectangle's height, an ellipse's full axis `2·ry`. */
29
+ height: number;
30
+ /** Radians, clockwise on screen: the turn from the image's x axis to the shape's own. */
31
+ rotation: number;
32
+ }
33
+
34
+ /**
35
+ * A point of image space in the shape's own frame: origin at its centre, axes along its sides.
36
+ *
37
+ * @param shape - The shape.
38
+ * @param p - A point in image coordinates.
39
+ * @returns The point relative to the shape.
40
+ */
41
+ export function toShapeFrame(shape: RotatedShape, p: Point): Point {
42
+ const c = Math.cos(shape.rotation);
43
+ const s = Math.sin(shape.rotation);
44
+ const dx = p.x - shape.cx;
45
+ const dy = p.y - shape.cy;
46
+ return { x: c * dx + s * dy, y: -s * dx + c * dy };
47
+ }
48
+
49
+ /**
50
+ * A point of the shape's own frame in image space; the inverse of `toShapeFrame`.
51
+ *
52
+ * @param shape - The shape.
53
+ * @param p - A point relative to the shape.
54
+ * @returns The point in image coordinates.
55
+ */
56
+ export function fromShapeFrame(shape: RotatedShape, p: Point): Point {
57
+ const c = Math.cos(shape.rotation);
58
+ const s = Math.sin(shape.rotation);
59
+ return { x: shape.cx + c * p.x - s * p.y, y: shape.cy + s * p.x + c * p.y };
60
+ }
61
+
62
+ /** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */
63
+ function handleDirection(handle: RoiHandle): Point {
64
+ return { x: handle.includes("e") ? 1 : handle.includes("w") ? -1 : 0, y: handle.includes("s") ? 1 : handle.includes("n") ? -1 : 0 };
65
+ }
66
+
67
+ /**
68
+ * Where a handle sits: a corner or the middle of a side, turned with the shape.
69
+ *
70
+ * @param shape - The shape.
71
+ * @param handle - The handle, by compass direction in the shape's own frame.
72
+ * @returns The handle's centre, in image coordinates.
73
+ */
74
+ export function shapeHandlePoint(shape: RotatedShape, handle: RoiHandle): Point {
75
+ const d = handleDirection(handle);
76
+ return fromShapeFrame(shape, { x: (d.x * shape.width) / 2, y: (d.y * shape.height) / 2 });
77
+ }
78
+
79
+ /**
80
+ * Where the rotation handle sits: beyond the middle of the top side, along the shape's own
81
+ * up direction.
82
+ *
83
+ * @param shape - The shape.
84
+ * @param distance - How far past the top side, in image pixels. For a screen-constant handle,
85
+ * pass `useScreenPx()(css)`.
86
+ * @returns The handle's centre, in image coordinates.
87
+ */
88
+ export function rotationHandlePoint(shape: RotatedShape, distance: number): Point {
89
+ return fromShapeFrame(shape, { x: 0, y: -shape.height / 2 - distance });
90
+ }
91
+
92
+ /**
93
+ * Drag a handle to `to`.
94
+ *
95
+ * The dragged side or corner follows the pointer in the shape's own frame and the opposite
96
+ * side or corner stays where it is in the image, which is what makes a handle feel attached.
97
+ * The shape does not flip when dragged through the opposite side: it stops at `minSize`.
98
+ *
99
+ * @param shape - The shape before the drag.
100
+ * @param handle - The handle being dragged.
101
+ * @param to - The pointer, in image coordinates.
102
+ * @param minSize - The smallest extent on either axis, in image pixels.
103
+ * @returns The resized shape: the same rotation, and the opposite side or corner unmoved.
104
+ */
105
+ export function resizeShape(shape: RotatedShape, handle: RoiHandle, to: Point, minSize: number): RotatedShape {
106
+ const d = handleDirection(handle);
107
+ const u = toShapeFrame(shape, to);
108
+ let width = shape.width;
109
+ let height = shape.height;
110
+ let x = 0;
111
+ let y = 0;
112
+ if (d.x !== 0) {
113
+ // The fixed side is at `-d.x · width / 2`; the new extent runs from it to the pointer.
114
+ width = Math.max(minSize, d.x * u.x + shape.width / 2);
115
+ x = -d.x * (shape.width / 2) + (d.x * width) / 2;
116
+ }
117
+ if (d.y !== 0) {
118
+ height = Math.max(minSize, d.y * u.y + shape.height / 2);
119
+ y = -d.y * (shape.height / 2) + (d.y * height) / 2;
120
+ }
121
+ const centre = fromShapeFrame(shape, { x, y });
122
+ return { cx: centre.x, cy: centre.y, width, height, rotation: shape.rotation };
123
+ }
124
+
125
+ /**
126
+ * Turn the shape about its centre so that its rotation handle points at `to`.
127
+ *
128
+ * @param shape - The shape before the drag.
129
+ * @param to - The pointer, in image coordinates.
130
+ * @param snap - Round the rotation to a multiple of this many radians (Shift while dragging
131
+ * rounds to 15°). Defaults to no rounding.
132
+ * @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.
133
+ */
134
+ export function rotateShape(shape: RotatedShape, to: Point, snap = 0): RotatedShape {
135
+ // The handle sits along the shape's own up direction, which is at angle `rotation - π/2`.
136
+ let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;
137
+ if (snap > 0) rotation = Math.round(rotation / snap) * snap;
138
+ return { ...shape, rotation: normalizeAngle(rotation) };
139
+ }
140
+
141
+ /**
142
+ * Move the shape.
143
+ *
144
+ * @param shape - The shape.
145
+ * @param dx - Horizontal shift, in image pixels.
146
+ * @param dy - Vertical shift, in image pixels.
147
+ * @returns The moved shape.
148
+ */
149
+ export function moveShape(shape: RotatedShape, dx: number, dy: number): RotatedShape {
150
+ return { ...shape, cx: shape.cx + dx, cy: shape.cy + dy };
151
+ }
152
+
153
+ /**
154
+ * An angle as the equivalent one in `(-π, π]`.
155
+ *
156
+ * @param angle - Radians.
157
+ * @returns The angle in `(-π, π]`.
158
+ */
159
+ export function normalizeAngle(angle: number): number {
160
+ const turn = 2 * Math.PI;
161
+ let a = angle % turn;
162
+ if (a > Math.PI) a -= turn;
163
+ else if (a <= -Math.PI) a += turn;
164
+ return a;
165
+ }
166
+
167
+ /**
168
+ * The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize
169
+ * cursors to the handle's direction on screen.
170
+ *
171
+ * @param handle - The handle.
172
+ * @param rotation - The shape's rotation, in radians.
173
+ * @returns A CSS `cursor` value.
174
+ */
175
+ export function shapeHandleCursor(handle: RoiHandle, rotation: number): string {
176
+ const d = handleDirection(handle);
177
+ const angle = Math.atan2(d.y, d.x) + rotation;
178
+ const half = ((angle % Math.PI) + Math.PI) % Math.PI;
179
+ return ["ew-resize", "nwse-resize", "ns-resize", "nesw-resize"][Math.round(half / (Math.PI / 4)) % 4]!;
180
+ }
181
+
182
+ /**
183
+ * The shape for a rectangle given as an origin corner, a size and a rotation about that
184
+ * corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.
185
+ *
186
+ * @param corner - The corner the rotation is about, in image coordinates.
187
+ * @param width - Extent along the rotated x axis.
188
+ * @param height - Extent along the rotated y axis.
189
+ * @param rotation - Radians, clockwise on screen.
190
+ * @returns The same rectangle as a `RotatedShape`.
191
+ */
192
+ export function shapeFromCorner(corner: Point, width: number, height: number, rotation: number): RotatedShape {
193
+ const c = Math.cos(rotation);
194
+ const s = Math.sin(rotation);
195
+ return {
196
+ cx: corner.x + (c * width - s * height) / 2,
197
+ cy: corner.y + (s * width + c * height) / 2,
198
+ width,
199
+ height,
200
+ rotation,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;
206
+ * the inverse of `shapeFromCorner`.
207
+ *
208
+ * @param shape - The shape.
209
+ * @returns The corner, in image coordinates.
210
+ */
211
+ export function shapeCorner(shape: RotatedShape): Point {
212
+ return fromShapeFrame(shape, { x: -shape.width / 2, y: -shape.height / 2 });
213
+ }
214
+
215
+ /**
216
+ * Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).
217
+ *
218
+ * @param a - A shape, or `null`.
219
+ * @param b - A shape, or `null`.
220
+ * @param epsilon - The tolerance. Defaults to 1e-6.
221
+ * @returns `true` for two equal shapes, or two `null`s.
222
+ */
223
+ export function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilon = 1e-6): boolean {
224
+ if (a === null || b === null) return a === b;
225
+ return (
226
+ Math.abs(a.cx - b.cx) < epsilon &&
227
+ Math.abs(a.cy - b.cy) < epsilon &&
228
+ Math.abs(a.width - b.width) < epsilon &&
229
+ Math.abs(a.height - b.height) < epsilon &&
230
+ Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon
231
+ );
232
+ }
@@ -46,6 +46,9 @@ 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";
50
+ import { StageHitContext, type StagePointerEvent } from "./hitContext";
51
+ import { createHitRegistry } from "./hitTest";
49
52
  import {
50
53
  clampView,
51
54
  fitView,
@@ -68,9 +71,30 @@ import {
68
71
  const WHEEL_SENSITIVITY = 0.0015;
69
72
  /** How far a press may travel and still count as a click rather than a pan. */
70
73
  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;
71
77
  /** The view before the viewport has been measured — nothing is on screen yet. */
72
78
  const UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };
73
79
 
80
+ /** A press that may become a pan, a click or a tap. */
81
+ interface Drag {
82
+ x: number;
83
+ y: number;
84
+ tx: number;
85
+ ty: number;
86
+ /** Strayed past the click slop at some point, so it is not a click or a tap. */
87
+ moved: boolean;
88
+ /** Whether movement pans the view. */
89
+ pan: boolean;
90
+ /** A touch, which reports a tap rather than a click. */
91
+ touch: boolean;
92
+ /** `timeStamp` of the press. */
93
+ at: number;
94
+ /** The touch's pointer id, or `-1`. */
95
+ pointerId: number;
96
+ }
97
+
74
98
  /** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */
75
99
  export interface StageContext {
76
100
  /** The view in effect — the controlled `view`, or the opening view while that is `null`. */
@@ -158,6 +182,26 @@ export interface ImageStageProps {
158
182
  banner?: ReactNode;
159
183
  /** Force panning regardless of where the press lands (a "hand tool"). */
160
184
  panTool?: boolean;
185
+ /**
186
+ * The mouse buttons that pan on drag, over background no layer claimed. Defaults to
187
+ * `["left", "middle"]`. An app whose left button belongs to the active drawing tool passes
188
+ * `"right"`; the context menu is then suppressed on the stage, since the button's job is
189
+ * to drag. The hand tool and a held space bar still pan with the left button.
190
+ */
191
+ panButton?: StageMouseButton | readonly StageMouseButton[] | undefined;
192
+ /**
193
+ * Whether a double-click toggles fit and the previous view. On by default; turn it off in
194
+ * an app whose tools use double-click, such as closing a polygon.
195
+ */
196
+ doubleClickFit?: boolean | undefined;
197
+ /**
198
+ * What one finger does on background no layer claimed: `"one-finger"` (the default) pans,
199
+ * as the mouse does; `"two-finger"` leaves it to the app's tools and pans only with two.
200
+ * Two fingers always pinch-zoom about their midpoint and pan with it. A tap (a touch that
201
+ * stays put and is short) is a press: a layer's `onItemPress` hears it, or else
202
+ * `onBackgroundClick`.
203
+ */
204
+ touchPan?: "one-finger" | "two-finger" | undefined;
161
205
  /** Merged onto the viewport with `cn`. */
162
206
  className?: string;
163
207
  /** Inline style for the viewport. */
@@ -206,6 +250,9 @@ export function ImageStage({
206
250
  readout,
207
251
  banner,
208
252
  panTool = false,
253
+ panButton,
254
+ doubleClickFit = true,
255
+ touchPan = "one-finger",
209
256
  className,
210
257
  style,
211
258
  onHover,
@@ -234,7 +281,14 @@ export function ImageStage({
234
281
  });
235
282
  /** The view to come back to when a double-click leaves fit. */
236
283
  const previousRef = useRef<StageView | null>(null);
237
- const dragRef = useRef<{ x: number; y: number; tx: number; ty: number; moved: boolean } | null>(null);
284
+ const dragRef = useRef<Drag | null>(null);
285
+ /** The touches down now, by pointer id, in client coordinates. */
286
+ const touchesRef = useRef(new Map<number, Point>());
287
+ /** 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);
289
+ /** The registry the stage's layers answer hit-tests through. */
290
+ const [hits] = useState(() => createHitRegistry<StagePointerEvent>());
291
+ const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
238
292
 
239
293
  const effective = useMemo(
240
294
  () => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW),
@@ -408,15 +462,35 @@ export function ImageStage({
408
462
  ],
409
463
  );
410
464
 
465
+ /** 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);
468
+
469
+ /** Offer a press to the items under it, topmost first; whether one claimed it. */
470
+ const routePress = (event: ReactPointerEvent<HTMLDivElement>) =>
471
+ hits.routePress(clientToImage({ x: event.clientX, y: event.clientY }), hitRadius(event), event);
472
+
411
473
  /*
412
474
  * Panning is the *default* reading of a press, and a layer opts out of it by handling the
413
475
  * event and stopping propagation — so the stage needs to know nothing about ROI handles or
414
476
  * clickable contours, and a layer needs no permission to exist. The predecessor inverted
415
477
  * this: it captured every `pointerdown` unconditionally, which is why its consumers had to
416
478
  * mount interactive layers outside the transform, where they stopped moving with the image.
479
+ *
480
+ * Layers that cannot own an element — a marker among thousands — register with the hit
481
+ * registry instead, and the press reaches them here: after every element-level handler had
482
+ * its say, before the stage reads the press as a pan.
417
483
  */
418
484
  const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
419
- if (event.button !== 0 && event.button !== 1) return;
485
+ if (event.pointerType === "touch") {
486
+ touchDown(event);
487
+ return;
488
+ }
489
+ const primary = event.button === 0;
490
+ if (primary && !panMode && routePress(event)) return;
491
+ // The hand tool and a held space bar pan with the primary button whatever `panButton` says.
492
+ const pan = panButtons.has(event.button) || (primary && panMode);
493
+ if (!pan && !primary) return;
420
494
  event.preventDefault();
421
495
  dragRef.current = {
422
496
  x: event.clientX,
@@ -424,15 +498,27 @@ export function ImageStage({
424
498
  tx: effective.tx,
425
499
  ty: effective.ty,
426
500
  moved: false,
501
+ pan,
502
+ touch: false,
503
+ at: event.timeStamp,
504
+ pointerId: event.pointerId,
427
505
  };
428
- setPanning(true);
506
+ if (pan) setPanning(true);
429
507
  event.currentTarget.setPointerCapture(event.pointerId);
430
508
  };
431
509
 
432
510
  const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
511
+ if (event.pointerType === "touch") {
512
+ touchMove(event);
513
+ return;
514
+ }
433
515
  const origin = dragRef.current;
434
- if (!origin) {
516
+ if (!origin?.pan) {
435
517
  onHover?.(hoverPoint(event, viewportRef.current, effective, image));
518
+ hits.routeHover(clientToImage({ x: event.clientX, y: event.clientY }), hitRadius(event));
519
+ if (origin && !origin.moved && Math.hypot(event.clientX - origin.x, event.clientY - origin.y) > CLICK_SLOP) {
520
+ origin.moved = true;
521
+ }
436
522
  return;
437
523
  }
438
524
  const dx = event.clientX - origin.x;
@@ -441,23 +527,135 @@ export function ImageStage({
441
527
  origin.moved = true;
442
528
  // During a pan the pointer is holding the image, not pointing at a pixel.
443
529
  onHover?.(null);
530
+ hits.clearHover();
444
531
  commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy });
445
532
  };
446
533
 
447
534
  const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
448
535
  const origin = dragRef.current;
536
+ if (origin?.touch) return; // a touch ends through `touchEnd`
449
537
  dragRef.current = null;
450
538
  setPanning(false);
451
539
  if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);
452
540
  };
453
541
 
542
+ /*
543
+ * Touch. The first finger is a pan candidate (if `touchPan` says so) and a tap candidate;
544
+ * the second turns the gesture into a pinch about the fingers' midpoint, which also
545
+ * carries the view with it. A tap is a press and is reported on release, because on
546
+ * `pointerdown` a finger might still be the first of two.
547
+ */
548
+ const touchDown = (event: ReactPointerEvent<HTMLDivElement>) => {
549
+ const touches = touchesRef.current;
550
+ if (touches.size >= 2) return; // a third finger has no job
551
+ event.preventDefault();
552
+ touches.set(event.pointerId, { x: event.clientX, y: event.clientY });
553
+ try {
554
+ event.currentTarget.setPointerCapture(event.pointerId);
555
+ } catch {
556
+ // The touch ended or was taken by the browser before this handler ran. The gesture
557
+ // still works from the events the viewport receives; capture only keeps a drag that
558
+ // leaves the viewport.
559
+ }
560
+ if (touches.size === 1) {
561
+ dragRef.current = {
562
+ x: event.clientX,
563
+ y: event.clientY,
564
+ tx: effective.tx,
565
+ ty: effective.ty,
566
+ moved: false,
567
+ pan: touchPan === "one-finger" || panMode,
568
+ touch: true,
569
+ at: event.timeStamp,
570
+ pointerId: event.pointerId,
571
+ };
572
+ return;
573
+ }
574
+ const [a, b] = [...touches.values()] as [Point, Point];
575
+ const origin = viewportOrigin(event.currentTarget);
576
+ const mid = centroid(a, b);
577
+ pinchRef.current = {
578
+ distance: Math.hypot(a.x - b.x, a.y - b.y),
579
+ centre: { x: mid.x - origin.x, y: mid.y - origin.y },
580
+ view: effective,
581
+ };
582
+ if (dragRef.current) dragRef.current.moved = true; // two fingers are never a tap
583
+ setPanning(true);
584
+ onHover?.(null);
585
+ hits.clearHover();
586
+ };
587
+
588
+ const touchMove = (event: ReactPointerEvent<HTMLDivElement>) => {
589
+ const touches = touchesRef.current;
590
+ if (!touches.has(event.pointerId)) return;
591
+ touches.set(event.pointerId, { x: event.clientX, y: event.clientY });
592
+ const pinch = pinchRef.current;
593
+ if (pinch && touches.size === 2) {
594
+ if (!(box.width > 0)) return;
595
+ const [a, b] = [...touches.values()] as [Point, Point];
596
+ const origin = viewportOrigin(event.currentTarget);
597
+ const mid = centroid(a, b);
598
+ commit(
599
+ pinchView(
600
+ pinch.view,
601
+ pinch.distance,
602
+ pinch.centre,
603
+ Math.hypot(a.x - b.x, a.y - b.y),
604
+ { x: mid.x - origin.x, y: mid.y - origin.y },
605
+ scaleRange(box, image, clamp),
606
+ ),
607
+ );
608
+ return;
609
+ }
610
+ const drag = dragRef.current;
611
+ if (!drag || drag.pointerId !== event.pointerId) return;
612
+ const dx = event.clientX - drag.x;
613
+ const dy = event.clientY - drag.y;
614
+ if (!drag.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;
615
+ drag.moved = true;
616
+ if (!drag.pan) return;
617
+ setPanning(true);
618
+ onHover?.(null);
619
+ commit({ scale: effective.scale, tx: drag.tx + dx, ty: drag.ty + dy });
620
+ };
621
+
622
+ const touchEnd = (event: ReactPointerEvent<HTMLDivElement>, cancelled: boolean) => {
623
+ const touches = touchesRef.current;
624
+ if (!touches.delete(event.pointerId)) return; // already ended (the capture is lost after the release)
625
+ if (pinchRef.current) {
626
+ pinchRef.current = null;
627
+ const rest = [...touches.entries()][0];
628
+ if (rest) {
629
+ // One finger is still down: it carries on as a pan from where it is, never as a tap.
630
+ dragRef.current = {
631
+ x: rest[1].x,
632
+ y: rest[1].y,
633
+ tx: effective.tx,
634
+ ty: effective.ty,
635
+ moved: true,
636
+ pan: touchPan === "one-finger" || panMode,
637
+ touch: true,
638
+ at: event.timeStamp,
639
+ pointerId: rest[0],
640
+ };
641
+ return;
642
+ }
643
+ }
644
+ if (touches.size > 0) return;
645
+ const drag = dragRef.current;
646
+ dragRef.current = null;
647
+ setPanning(false);
648
+ if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;
649
+ if (!routePress(event)) onBackgroundClick?.(event);
650
+ };
651
+
454
652
  /*
455
653
  * Fit ↔ **the view you were just at**, which is the gesture a reader actually wants: a
456
654
  * double-click to see the whole part, another to go back to the corner they were working
457
655
  * in. Toggling against 1:1 instead (the predecessor's behaviour) throws that place away.
458
656
  */
459
657
  const onDoubleClick = (event: ReactPointerEvent<HTMLDivElement>) => {
460
- if (!(box.width > 0)) return;
658
+ if (!doubleClickFit || !(box.width > 0)) return;
461
659
  if (atFit) {
462
660
  const restore = previousRef.current;
463
661
  if (restore) {
@@ -514,65 +712,72 @@ export function ImageStage({
514
712
 
515
713
  return (
516
714
  <ImageStageContext value={context}>
517
- <div
518
- ref={attachViewport}
519
- role="application"
520
- aria-label={label}
521
- tabIndex={0}
522
- style={style}
523
- data-fit={atFit ? "" : undefined}
524
- data-panning={panning ? "" : undefined}
525
- data-pan-mode={panMode ? "" : undefined}
526
- className={cn(
527
- // `@container/stage`: the toolbar and readout collapse by the canvas's own width,
528
- // not the window's — a canvas beside a wide inspector is narrow on a wide screen.
529
- "@container/stage relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none",
530
- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal",
531
- panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default",
532
- className,
533
- )}
534
- onPointerDown={onPointerDown}
535
- onPointerMove={onPointerMove}
536
- onPointerUp={endDrag}
537
- // A drag interrupted by a lost capture — a context menu, a browser gesture, the
538
- // pointer leaving the window — used to leave the drag set, so the next hover panned
539
- // the image with no button held down.
540
- onPointerCancel={endDrag}
541
- onLostPointerCapture={endDrag}
542
- onPointerLeave={() => onHover?.(null)}
543
- onDoubleClick={onDoubleClick}
544
- onKeyDown={onKeyDown}
545
- >
546
- {/* One transformed box holding every layer, laid out at the image's own pixel size. */}
715
+ <StageHitContext value={hits}>
547
716
  <div
548
- data-stage
549
- className="absolute top-0 left-0 origin-top-left"
550
- style={{
551
- width: image.width,
552
- height: image.height,
553
- transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`,
717
+ ref={attachViewport}
718
+ role="application"
719
+ aria-label={label}
720
+ tabIndex={0}
721
+ style={style}
722
+ data-fit={atFit ? "" : undefined}
723
+ data-panning={panning ? "" : undefined}
724
+ data-pan-mode={panMode ? "" : undefined}
725
+ className={cn(
726
+ // `@container/stage`: the toolbar and readout collapse by the canvas's own width,
727
+ // not the window's — a canvas beside a wide inspector is narrow on a wide screen.
728
+ "@container/stage relative h-full w-full touch-none overflow-hidden rounded-control border border-line bg-canvas select-none",
729
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal",
730
+ panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default",
731
+ className,
732
+ )}
733
+ onPointerDown={onPointerDown}
734
+ onPointerMove={onPointerMove}
735
+ onPointerUp={(event) => (event.pointerType === "touch" ? touchEnd(event, false) : endDrag(event))}
736
+ // A drag interrupted by a lost capture — a context menu, a browser gesture, the
737
+ // pointer leaving the window — used to leave the drag set, so the next hover panned
738
+ // the image with no button held down.
739
+ onPointerCancel={(event) => (event.pointerType === "touch" ? touchEnd(event, true) : endDrag(event))}
740
+ onLostPointerCapture={(event) => (event.pointerType === "touch" ? touchEnd(event, true) : endDrag(event))}
741
+ onPointerLeave={() => {
742
+ onHover?.(null);
743
+ hits.clearHover();
554
744
  }}
745
+ onDoubleClick={onDoubleClick}
746
+ // The button's job is to drag; a menu opening at the end of every pan would undo it.
747
+ onContextMenu={panButtons.has(2) ? (event) => event.preventDefault() : undefined}
748
+ onKeyDown={onKeyDown}
555
749
  >
556
- {children}
557
- </div>
750
+ {/* One transformed box holding every layer, laid out at the image's own pixel size. */}
751
+ <div
752
+ data-stage
753
+ className="absolute top-0 left-0 origin-top-left"
754
+ style={{
755
+ width: image.width,
756
+ height: image.height,
757
+ transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`,
758
+ }}
759
+ >
760
+ {children}
761
+ </div>
558
762
 
559
- {banner && <div className="pointer-events-none absolute top-2 left-2 z-10">{banner}</div>}
560
-
561
- {/* One row, not two corners: as separate absolute boxes the toolbar and the readout
562
- overlapped as soon as the canvas was narrower than their combined width, which is
563
- an ordinary window on a two-column workbench. `justify-between` keeps them apart
564
- and lets the readout be the one that gives up room. */}
565
- {(toolbar || readout) && (
566
- // Wraps rather than clips: on a canvas too narrow for both, the readout moves onto
567
- // its own line above the toolbar instead of being truncated to nothing.
568
- <div className="pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2">
569
- <div className="pointer-events-auto max-w-full shrink-0">{toolbar}</div>
570
- <div data-readout-slot="" className="max-w-full min-w-0 truncate">
571
- {readout}
763
+ {banner && <div className="pointer-events-none absolute top-2 left-2 z-10">{banner}</div>}
764
+
765
+ {/* One row, not two corners: as separate absolute boxes the toolbar and the readout
766
+ overlapped as soon as the canvas was narrower than their combined width, which is
767
+ an ordinary window on a two-column workbench. `justify-between` keeps them apart
768
+ and lets the readout be the one that gives up room. */}
769
+ {(toolbar || readout) && (
770
+ // Wraps rather than clips: on a canvas too narrow for both, the readout moves onto
771
+ // its own line above the toolbar instead of being truncated to nothing.
772
+ <div className="pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2">
773
+ <div className="pointer-events-auto max-w-full shrink-0">{toolbar}</div>
774
+ <div data-readout-slot="" className="max-w-full min-w-0 truncate">
775
+ {readout}
776
+ </div>
572
777
  </div>
573
- </div>
574
- )}
575
- </div>
778
+ )}
779
+ </div>
780
+ </StageHitContext>
576
781
  </ImageStageContext>
577
782
  );
578
783
  }