@vitavision/stage2d 0.9.0 → 0.11.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
 
@@ -224,10 +233,17 @@ export interface ImageStageProps {
224
233
  label?: string;
225
234
  /**
226
235
  * 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
236
+ * (inside the `fit` margin) and fit otherwise; `"fit"` always fit, for a viewer that should show the whole frame
228
237
  * whatever its size.
229
238
  */
230
239
  initialView?: "auto" | "fit" | undefined;
240
+ /**
241
+ * The margin and upscale cap of every fit: `initialView="fit"`, the handle's and the
242
+ * context's `fit()`, the `0` key, the double-click toggle, the toolbar's Fit button, and
243
+ * `isFit` / `data-fit`. Defaults to filling the viewport edge to edge, upscaling freely.
244
+ * Each field is read by value, so an inline object does not re-fit the view.
245
+ */
246
+ fit?: FitOptions | undefined;
231
247
  /** The stage's controls for code outside it; see `StageHandle`. */
232
248
  ref?: Ref<StageHandle> | undefined;
233
249
  }
@@ -237,6 +253,10 @@ export interface ImageStageProps {
237
253
  * size, so an overlay drawn in image coordinates stays registered with the photograph at
238
254
  * any zoom and window size. Layers read the transform through `useStage`.
239
255
  *
256
+ * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while
257
+ * the view changes and for 150 ms after, so a pan stays on the compositor and the layer
258
+ * re-rasterises sharp once the view settles.
259
+ *
240
260
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
241
261
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
242
262
  * or absent.
@@ -262,9 +282,11 @@ export function ImageStage({
262
282
  panKeys = true,
263
283
  label = "Image canvas",
264
284
  initialView: opening = "auto",
285
+ fit: fitOptions,
265
286
  ref,
266
287
  }: ImageStageProps) {
267
288
  const viewportRef = useRef<HTMLDivElement | null>(null);
289
+ const boxRef = useRef<HTMLDivElement | null>(null);
268
290
  const [box, setBox] = useState<Box>({ width: 0, height: 0 });
269
291
  // The measured size, readable synchronously — `setBox`'s updater must stay pure, and the
270
292
  // resize handler needs the *previous* box to re-anchor the view against.
@@ -275,9 +297,13 @@ export function ImageStage({
275
297
 
276
298
  // What the handlers attached once (and the stable callbacks below) read: the props and
277
299
  // box of the last commit, so none of them closes over stale values.
278
- const latestRef = useRef({ view, box, image, clamp, onView, opening });
300
+ const fitOpts = useMemo<FitOptions>(
301
+ () => ({ padding: fitOptions?.padding, upscale: fitOptions?.upscale }),
302
+ [fitOptions?.padding, fitOptions?.upscale],
303
+ );
304
+ const latestRef = useRef({ view, box, image, clamp, onView, opening, fitOpts });
279
305
  useLayoutEffect(() => {
280
- latestRef.current = { view, box, image, clamp, onView, opening };
306
+ latestRef.current = { view, box, image, clamp, onView, opening, fitOpts };
281
307
  });
282
308
  /** The view to come back to when a double-click leaves fit. */
283
309
  const previousRef = useRef<StageView | null>(null);
@@ -291,10 +317,24 @@ export function ImageStage({
291
317
  const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);
292
318
 
293
319
  const effective = useMemo(
294
- () => view ?? (box.width > 0 ? openingView(opening, box, image) : UNMEASURED_VIEW),
295
- [view, box, image, opening],
320
+ () => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW),
321
+ [view, box, image, opening, fitOpts],
296
322
  );
297
323
 
324
+ // `will-change: transform` (and `data-moving`) on the transformed box while the view moves, set
325
+ // on the element itself so a pan costs no React render; see `MOVING_SETTLE_MS`.
326
+ useEffect(() => {
327
+ const element = boxRef.current;
328
+ if (!element) return;
329
+ element.style.willChange = "transform";
330
+ element.dataset["moving"] = "";
331
+ const timer = setTimeout(() => {
332
+ element.style.willChange = "";
333
+ delete element.dataset["moving"];
334
+ }, MOVING_SETTLE_MS);
335
+ return () => clearTimeout(timer);
336
+ }, [effective.scale, effective.tx, effective.ty]);
337
+
298
338
  const commit = useCallback((next: StageView) => {
299
339
  const { box: b, image: i, clamp: c, onView: report } = latestRef.current;
300
340
  report(b.width > 0 ? clampView(next, b, i, c) : next);
@@ -324,12 +364,12 @@ export function ImageStage({
324
364
  const next = { width, height };
325
365
  measuredRef.current = next;
326
366
  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));
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));
329
369
  // The first measurement: there is no previous viewport to re-anchor against, so the
330
370
  // caller's view is kept — only made legal for this one.
331
371
  else if (!(current.width > 0)) report(clampView(v, next, i, c));
332
- else report(preserveCenter(v, current, next, i, c));
372
+ else report(preserveCenter(v, current, next, i, c, f));
333
373
  };
334
374
 
335
375
  // Synchronously, so the first paint already has the right view — and as the *content*
@@ -401,10 +441,10 @@ export function ImageStage({
401
441
  }, []);
402
442
 
403
443
  const fit = useCallback(() => {
404
- const { box: b, image: i, view: v, onView: report } = latestRef.current;
444
+ const { box: b, image: i, view: v, onView: report, fitOpts: f } = latestRef.current;
405
445
  if (!(b.width > 0)) return;
406
- if (v !== null && !isFit(v, b, i)) previousRef.current = v;
407
- report(fitView(b, i));
446
+ if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;
447
+ report(fitView(b, i, f));
408
448
  }, []);
409
449
 
410
450
  const zoomTo = useCallback((scale: number, anchor?: Point) => {
@@ -427,7 +467,7 @@ export function ImageStage({
427
467
 
428
468
  useImperativeHandle(ref, () => ({ frame, fit, zoomTo }), [frame, fit, zoomTo]);
429
469
 
430
- const atFit = box.width > 0 && isFit(effective, box, image);
470
+ const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);
431
471
 
432
472
  const context = useMemo<StageContext>(
433
473
  () => ({
@@ -464,7 +504,7 @@ export function ImageStage({
464
504
 
465
505
  /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */
466
506
  const hitRadius = (event: { pointerType: string }) =>
467
- imageLengthFor(effective, event.pointerType === "touch" ? TOUCH_RADIUS : POINTER_RADIUS);
507
+ imageLengthFor(effective, hitRadiusPx(event.pointerType));
468
508
 
469
509
  /** Offer a press to the items under it, topmost first; whether one claimed it. */
470
510
  const routePress = (event: ReactPointerEvent<HTMLDivElement>) =>
@@ -666,7 +706,7 @@ export function ImageStage({
666
706
  return;
667
707
  }
668
708
  previousRef.current = effective;
669
- onView(fitView(box, image));
709
+ onView(fitView(box, image, fitOpts));
670
710
  };
671
711
 
672
712
  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -749,6 +789,7 @@ export function ImageStage({
749
789
  >
750
790
  {/* One transformed box holding every layer, laid out at the image's own pixel size. */}
751
791
  <div
792
+ ref={boxRef}
752
793
  data-stage
753
794
  className="absolute top-0 left-0 origin-top-left"
754
795
  style={{
@@ -783,8 +824,8 @@ export function ImageStage({
783
824
  }
784
825
 
785
826
  /** 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);
827
+ function openingView(opening: "auto" | "fit", box: Box, image: Box, fit: FitOptions): StageView {
828
+ return opening === "fit" ? fitView(box, image, fit) : initialView(box, image, fit);
788
829
  }
789
830
 
790
831
  function hoverPoint(
@@ -21,6 +21,8 @@ import type { PointerEvent as ReactPointerEvent } from "react";
21
21
 
22
22
  import type { Point } from "../measureGeometry";
23
23
  import { useStage } from "./ImageStage";
24
+ import { hitRadiusPx } from "./gesture";
25
+ import { watchTouch } from "./touchWatch";
24
26
  import { imageViewBox } from "./view";
25
27
 
26
28
  /** What a drag does as the pointer moves and when it is released, in image coordinates. */
@@ -34,6 +36,13 @@ export interface StageDrag {
34
36
  onEnd?: ((point: Point, event: PointerEvent, moved: boolean) => void) | undefined;
35
37
  /** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag. */
36
38
  onCancel?: (() => void) | undefined;
39
+ /**
40
+ * Claim a touch that starts this gesture, as a mouse press is claimed: the stage neither
41
+ * pans nor pinches from it. Without it a touch is only watched (see `StageSurface`), so
42
+ * return `true` for a gesture a finger must own, such as moving a selected shape. Ignored for
43
+ * a mouse or pen.
44
+ */
45
+ claimsTouch?: boolean | undefined;
37
46
  }
38
47
 
39
48
  /** How far a press may travel and still be a click, in screen pixels. */
@@ -94,6 +103,12 @@ export function useStageDrag(): (event: ReactPointerEvent<Element>, drag: StageD
94
103
  export interface StagePress {
95
104
  /** Where, in image coordinates. */
96
105
  point: Point;
106
+ /** Where, in client coordinates, for anchoring a tooltip or a menu. */
107
+ client: Point;
108
+ /** The press is a touch: act on its release (see `StageSurface`), and expect a fingertip's tolerance. */
109
+ touch: boolean;
110
+ /** The hit-test tolerance for this pointer, in screen pixels: 12 for a touch, 6 otherwise. Pass it to `useStageHitTest`. */
111
+ radius: number;
97
112
  /** Shift was held. */
98
113
  shiftKey: boolean;
99
114
  /** Alt / Option was held. */
@@ -107,12 +122,21 @@ export interface StageSurfaceProps {
107
122
  /**
108
123
  * What a press means. Return a `StageDrag` to claim it (a click is a drag that never
109
124
  * moved), or nothing to decline it: a declined press reaches the stage, which pans.
125
+ *
126
+ * **For a touch, act in `onEnd` when `moved` is `false` (a tap), not here.** The press may
127
+ * become a pan or the first finger of a pinch, so nothing should happen until the finger
128
+ * lifts. Return `claimsTouch: true` for a gesture the finger must own.
110
129
  */
111
130
  onPress: (press: StagePress) => StageDrag | null | undefined | void;
112
131
  /** The cursor over the image while no drag is in flight, e.g. `crosshair` for a draw tool. */
113
132
  cursor?: string | undefined;
114
- /** Where the pointer is over the image while no drag is in flight, for hover feedback. */
133
+ /** Where the mouse is over the image while no drag is in flight, for hover feedback. Not called for a touch. */
115
134
  onHover?: ((point: Point) => void) | undefined;
135
+ /**
136
+ * A double click or double tap on the surface. When given, the surface handles it and the
137
+ * stage's double-click-to-fit does not run; leave it out to keep the fit.
138
+ */
139
+ onDoubleClick?: ((point: Point) => void) | undefined;
116
140
  }
117
141
 
118
142
  /**
@@ -120,32 +144,74 @@ export interface StageSurfaceProps {
120
144
  * that have their own small targets (handles, strokes). Each press is offered to `onPress`
121
145
  * unless the hand tool or a held space bar make it a pan; a declined press pans.
122
146
  *
123
- * The surface draws nothing. It carries `data-dragging` while a drag it started is in
124
- * flight.
147
+ * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on
148
+ * `window`, so the stage does not pan from it.
149
+ *
150
+ * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface
151
+ * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)
152
+ * and a second finger still pinches. The drag then sees:
153
+ * - `onMove`, only once the finger has left the tap slop;
154
+ * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;
155
+ * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).
156
+ *
157
+ * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
158
+ *
159
+ * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
125
160
  */
126
- export function StageSurface({ onPress, cursor, onHover }: StageSurfaceProps) {
161
+ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageSurfaceProps) {
127
162
  const stage = useStage();
128
163
  const start = useStageDrag();
129
164
  const [dragging, setDragging] = useState(false);
165
+ const watchRef = useRef<(() => void) | null>(null);
166
+
167
+ // A touch still being watched when the surface goes away is cancelled, not left listening.
168
+ useEffect(() => () => watchRef.current?.(), []);
130
169
 
131
170
  const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {
132
- if (event.button !== 0 || stage.panMode) return;
171
+ const touch = event.pointerType === "touch";
172
+ if (stage.panMode || (!touch && event.button !== 0)) return;
173
+ // A second finger turns the first one's gesture into a pinch; the watch cancels itself on it.
174
+ if (touch && watchRef.current) return;
175
+ const client = { x: event.clientX, y: event.clientY };
133
176
  const drag = onPress({
134
- point: stage.toImage({ x: event.clientX, y: event.clientY }),
177
+ point: stage.toImage(client),
178
+ client,
179
+ touch,
180
+ radius: hitRadiusPx(event.pointerType),
135
181
  shiftKey: event.shiftKey,
136
182
  altKey: event.altKey,
137
183
  metaKey: event.metaKey || event.ctrlKey,
138
184
  });
139
185
  if (!drag) return; // Declined: the stage pans.
186
+ const finish = () => setDragging(false);
140
187
  setDragging(true);
188
+ if (touch && !drag.claimsTouch) {
189
+ // Watched, not claimed: the press goes on to the stage.
190
+ const release = () => {
191
+ watchRef.current = null;
192
+ finish();
193
+ };
194
+ watchRef.current = watchTouch(event, {
195
+ onMove: (e) => drag.onMove?.(stage.toImage({ x: e.clientX, y: e.clientY }), e),
196
+ onEnd: (e, moved) => {
197
+ release();
198
+ drag.onEnd?.(stage.toImage({ x: e.clientX, y: e.clientY }), e, moved);
199
+ },
200
+ onCancel: () => {
201
+ release();
202
+ drag.onCancel?.();
203
+ },
204
+ });
205
+ return;
206
+ }
141
207
  start(event, {
142
208
  onMove: drag.onMove,
143
209
  onEnd: (point, e, moved) => {
144
- setDragging(false);
210
+ finish();
145
211
  drag.onEnd?.(point, e, moved);
146
212
  },
147
213
  onCancel: () => {
148
- setDragging(false);
214
+ finish();
149
215
  drag.onCancel?.();
150
216
  },
151
217
  });
@@ -169,7 +235,12 @@ export function StageSurface({ onPress, cursor, onHover }: StageSurfaceProps) {
169
235
  style={{ cursor: stage.panMode ? undefined : cursor }}
170
236
  onPointerDown={onPointerDown}
171
237
  onPointerMove={(event) => {
172
- if (!dragging) onHover?.(stage.toImage({ x: event.clientX, y: event.clientY }));
238
+ if (!dragging && event.pointerType !== "touch") onHover?.(stage.toImage({ x: event.clientX, y: event.clientY }));
239
+ }}
240
+ onDoubleClick={(event) => {
241
+ if (!onDoubleClick) return;
242
+ event.stopPropagation();
243
+ onDoubleClick(stage.toImage({ x: event.clientX, y: event.clientY }));
173
244
  }}
174
245
  />
175
246
  </svg>
@@ -16,6 +16,21 @@ export const TAP_SLOP = 3;
16
16
  /** The longest a touch may last and still be a tap, in milliseconds. */
17
17
  export const TAP_MS = 500;
18
18
 
19
+ /** The pointer's tolerance for hover and presses, in screen pixels: a mouse or pen. */
20
+ export const POINTER_RADIUS_PX = 6;
21
+ /** The pointer's tolerance for a touch, in screen pixels: a fingertip is fatter. */
22
+ export const TOUCH_RADIUS_PX = 12;
23
+
24
+ /**
25
+ * The hit-test tolerance for a pointer, in screen pixels.
26
+ *
27
+ * @param pointerType - `PointerEvent.pointerType`.
28
+ * @returns 12 for `"touch"`, 6 otherwise.
29
+ */
30
+ export function hitRadiusPx(pointerType: string): number {
31
+ return pointerType === "touch" ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX;
32
+ }
33
+
19
34
  const BUTTON_CODE: Record<StageMouseButton, number> = { left: 0, middle: 1, right: 2 };
20
35
 
21
36
  /**
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Watching a touch without claiming it.
3
+ *
4
+ * A layer that claims a touch (`stopPropagation` plus pointer capture) takes it from the stage,
5
+ * so a second finger can no longer pinch and a drag can no longer pan. A layer that only wants
6
+ * to know whether the touch was a tap leaves the press alone and follows its pointer on
7
+ * `window`, where the moves and the release arrive whoever captured the pointer.
8
+ */
9
+
10
+ import { TAP_SLOP, isTap } from "./gesture";
11
+
12
+ /** What a watched touch reports. */
13
+ export interface TouchWatch {
14
+ /** The finger has left the tap slop, and moved again. Not called for a finger that stays put. */
15
+ onMove?: ((event: PointerEvent) => void) | undefined;
16
+ /**
17
+ * The finger lifted. `moved` is whether it ever left the tap slop; `tap` whether it was a
18
+ * tap (it stayed put and was quick).
19
+ */
20
+ onEnd: (event: PointerEvent, moved: boolean, tap: boolean) => void;
21
+ /** The browser took the touch (`pointercancel`), a second finger landed, or the watch was cancelled. */
22
+ onCancel?: (() => void) | undefined;
23
+ }
24
+
25
+ /** The press a watch begins from. */
26
+ export interface TouchOrigin {
27
+ /** `PointerEvent.pointerId`. */
28
+ pointerId: number;
29
+ /** Client x of the press. */
30
+ clientX: number;
31
+ /** Client y of the press. */
32
+ clientY: number;
33
+ /** `PointerEvent.timeStamp` of the press. */
34
+ timeStamp: number;
35
+ }
36
+
37
+ /**
38
+ * Follow one touch on `window` until it lifts. A second touch landing, or `pointercancel`,
39
+ * cancels the watch and leaves the touches to the stage.
40
+ *
41
+ * @param origin - The `pointerdown` of the touch.
42
+ * @param watch - What to report.
43
+ * @returns A function that cancels the watch (calling `onCancel`); a no-op once it has ended.
44
+ */
45
+ export function watchTouch(origin: TouchOrigin, watch: TouchWatch): () => void {
46
+ const id = origin.pointerId;
47
+ let moved = false;
48
+ let done = false;
49
+ const travel = (e: PointerEvent) => Math.hypot(e.clientX - origin.clientX, e.clientY - origin.clientY);
50
+
51
+ const stop = () => {
52
+ done = true;
53
+ window.removeEventListener("pointermove", move);
54
+ window.removeEventListener("pointerup", up);
55
+ window.removeEventListener("pointercancel", cancelEvent);
56
+ window.removeEventListener("pointerdown", other);
57
+ };
58
+ const cancel = () => {
59
+ if (done) return;
60
+ stop();
61
+ watch.onCancel?.();
62
+ };
63
+ function move(e: PointerEvent) {
64
+ if (e.pointerId !== id) return;
65
+ if (!moved && travel(e) > TAP_SLOP) moved = true;
66
+ if (moved) watch.onMove?.(e);
67
+ }
68
+ function up(e: PointerEvent) {
69
+ if (e.pointerId !== id) return;
70
+ stop();
71
+ if (!moved && travel(e) > TAP_SLOP) moved = true;
72
+ watch.onEnd(e, moved, isTap(moved ? Infinity : travel(e), e.timeStamp - origin.timeStamp));
73
+ }
74
+ function cancelEvent(e: PointerEvent) {
75
+ if (e.pointerId === id) cancel();
76
+ }
77
+ function other(e: PointerEvent) {
78
+ if (e.pointerId !== id && e.pointerType === "touch") cancel();
79
+ }
80
+ window.addEventListener("pointermove", move);
81
+ window.addEventListener("pointerup", up);
82
+ window.addEventListener("pointercancel", cancelEvent);
83
+ window.addEventListener("pointerdown", other);
84
+ return cancel;
85
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Whether the device's primary pointer is coarse (a finger), for sizing a press target that
3
+ * must exist before any pointer event says which pointer is coming.
4
+ */
5
+
6
+ import { useSyncExternalStore } from "react";
7
+
8
+ const QUERY = "(pointer: coarse)";
9
+
10
+ function mediaList(): MediaQueryList | null {
11
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(QUERY) : null;
12
+ }
13
+
14
+ function subscribe(onChange: () => void): () => void {
15
+ const list = mediaList();
16
+ list?.addEventListener("change", onChange);
17
+ return () => list?.removeEventListener("change", onChange);
18
+ }
19
+
20
+ const snapshot = () => mediaList()?.matches ?? false;
21
+
22
+ /**
23
+ * Whether `(pointer: coarse)` matches: the primary pointer is a finger. `false` on the server
24
+ * and wherever `matchMedia` is missing.
25
+ *
26
+ * @returns `true` on a touch-first device.
27
+ */
28
+ export function useCoarsePointer(): boolean {
29
+ return useSyncExternalStore(subscribe, snapshot, () => false);
30
+ }
@@ -105,21 +105,61 @@ const SCALE_EPSILON = 1e-3;
105
105
  /** Absolute tolerance for "is this the same offset", in CSS pixels. */
106
106
  const OFFSET_EPSILON = 0.5;
107
107
 
108
- /** The scale at which the whole image is just visible inside `box`. */
109
- export function fitScale(box: Box, image: Box): number {
108
+ /** How `fitScale` and `fitView` treat the margin and a small image. */
109
+ export interface FitOptions {
110
+ /**
111
+ * A margin on each side of the fitted image, in CSS pixels. Defaults to 0: the image fills
112
+ * the box edge to edge. A margin that leaves no room (the box is smaller than twice the
113
+ * padding) is ignored.
114
+ */
115
+ padding?: number | undefined;
116
+ /**
117
+ * Whether fit may magnify a small image past 1:1. On by default; `false` caps the fit scale
118
+ * at 1, so a small image opens at its own size, centred.
119
+ */
120
+ upscale?: boolean | undefined;
121
+ }
122
+
123
+ /**
124
+ * The scale at which the whole image is just visible inside `box`.
125
+ *
126
+ * @param box - The viewport, in CSS pixels.
127
+ * @param image - The image, in image pixels.
128
+ * @param options - A margin and an upscale cap; the defaults fill the box edge to edge.
129
+ * @returns CSS pixels per image pixel; `1` for a degenerate box or image.
130
+ */
131
+ export function fitScale(box: Box, image: Box, options: FitOptions = {}): number {
110
132
  if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;
111
- return Math.min(box.width / image.width, box.height / image.height);
133
+ const pad = Math.max(0, options.padding ?? 0);
134
+ const room = box.width > 2 * pad && box.height > 2 * pad ? pad : 0;
135
+ const scale = Math.min((box.width - 2 * room) / image.width, (box.height - 2 * room) / image.height);
136
+ return options.upscale === false ? Math.min(1, scale) : scale;
112
137
  }
113
138
 
114
- /** Fit, centred — the view a viewer opens at and the one `0` returns to. */
115
- export function fitView(box: Box, image: Box): StageView {
116
- const scale = fitScale(box, image);
139
+ /**
140
+ * Fit, centred: the view a viewer opens at and the one `0` returns to.
141
+ *
142
+ * @param box - The viewport, in CSS pixels.
143
+ * @param image - The image, in image pixels.
144
+ * @param options - A margin and an upscale cap; see `FitOptions`.
145
+ * @returns The view.
146
+ */
147
+ export function fitView(box: Box, image: Box, options: FitOptions = {}): StageView {
148
+ const scale = fitScale(box, image, options);
117
149
  return centred(scale, box, image);
118
150
  }
119
151
 
120
- /** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */
121
- export function initialView(box: Box, image: Box): StageView {
122
- return centred(Math.min(1, fitScale(box, image)), box, image);
152
+ /**
153
+ * The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view.
154
+ *
155
+ * @param box - The viewport, in CSS pixels.
156
+ * @param image - The image, in image pixels.
157
+ * @param options - Only `padding` matters here (the image must fit inside the margin to open
158
+ * at 1:1, and "otherwise fit" is the padded fit); it never magnifies, so `upscale` is moot.
159
+ * @returns The view.
160
+ */
161
+ export function initialView(box: Box, image: Box, options: FitOptions = {}): StageView {
162
+ return centred(Math.min(1, fitScale(box, image, { padding: options.padding })), box, image);
123
163
  }
124
164
 
125
165
  function centred(scale: number, box: Box, image: Box): StageView {
@@ -130,9 +170,9 @@ function centred(scale: number, box: Box, image: Box): StageView {
130
170
  };
131
171
  }
132
172
 
133
- /** Whether `view` is (indistinguishably) the fit view for this box and image. */
134
- export function isFit(view: StageView, box: Box, image: Box): boolean {
135
- const fit = fitView(box, image);
173
+ /** Whether `view` is (indistinguishably) the fit view for this box, image and `FitOptions`. */
174
+ export function isFit(view: StageView, box: Box, image: Box, options: FitOptions = {}): boolean {
175
+ const fit = fitView(box, image, options);
136
176
  return (
137
177
  Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON &&
138
178
  Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON &&
@@ -274,9 +314,10 @@ export function preserveCenter(
274
314
  to: Box,
275
315
  image: Box,
276
316
  options: ClampOptions = {},
317
+ fit: FitOptions = {},
277
318
  ): StageView {
278
- if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);
279
- if (isFit(view, from, image)) return fitView(to, image);
319
+ if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);
320
+ if (isFit(view, from, image, fit)) return fitView(to, image, fit);
280
321
 
281
322
  const centre = toImage(view, { x: from.width / 2, y: from.height / 2 });
282
323
  return clampView(