@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.
@@ -19,9 +19,12 @@
19
19
  import { useCallback, useEffect, useRef, useState } from "react";
20
20
  import type { PointerEvent as ReactPointerEvent } from "react";
21
21
 
22
+ import { cn } from "@vitavision/ui";
22
23
  import type { Point } from "../measureGeometry";
23
24
  import { useStage } from "./ImageStage";
24
- import { imageViewBox } from "./view";
25
+ import { hitRadiusPx } from "./gesture";
26
+ import { watchTouch } from "./touchWatch";
27
+ import { clampToImage, imageViewBox, toImage } from "./view";
25
28
 
26
29
  /** What a drag does as the pointer moves and when it is released, in image coordinates. */
27
30
  export interface StageDrag {
@@ -34,6 +37,13 @@ export interface StageDrag {
34
37
  onEnd?: ((point: Point, event: PointerEvent, moved: boolean) => void) | undefined;
35
38
  /** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag. */
36
39
  onCancel?: (() => void) | undefined;
40
+ /**
41
+ * Claim a touch that starts this gesture, as a mouse press is claimed: the stage neither
42
+ * pans nor pinches from it. Without it a touch is only watched (see `StageSurface`), so
43
+ * return `true` for a gesture a finger must own, such as moving a selected shape. Ignored for
44
+ * a mouse or pen.
45
+ */
46
+ claimsTouch?: boolean | undefined;
37
47
  }
38
48
 
39
49
  /** How far a press may travel and still be a click, in screen pixels. */
@@ -94,6 +104,12 @@ export function useStageDrag(): (event: ReactPointerEvent<Element>, drag: StageD
94
104
  export interface StagePress {
95
105
  /** Where, in image coordinates. */
96
106
  point: Point;
107
+ /** Where, in client coordinates, for anchoring a tooltip or a menu. */
108
+ client: Point;
109
+ /** The press is a touch: act on its release (see `StageSurface`), and expect a fingertip's tolerance. */
110
+ touch: boolean;
111
+ /** The hit-test tolerance for this pointer, in screen pixels: 12 for a touch, 6 otherwise. Pass it to `useStageHitTest`. */
112
+ radius: number;
97
113
  /** Shift was held. */
98
114
  shiftKey: boolean;
99
115
  /** Alt / Option was held. */
@@ -107,12 +123,30 @@ export interface StageSurfaceProps {
107
123
  /**
108
124
  * What a press means. Return a `StageDrag` to claim it (a click is a drag that never
109
125
  * moved), or nothing to decline it: a declined press reaches the stage, which pans.
126
+ *
127
+ * **For a touch, act in `onEnd` when `moved` is `false` (a tap), not here.** The press may
128
+ * become a pan or the first finger of a pinch, so nothing should happen until the finger
129
+ * lifts. Return `claimsTouch: true` for a gesture the finger must own.
110
130
  */
111
131
  onPress: (press: StagePress) => StageDrag | null | undefined | void;
112
132
  /** The cursor over the image while no drag is in flight, e.g. `crosshair` for a draw tool. */
113
133
  cursor?: string | undefined;
114
- /** Where the pointer is over the image while no drag is in flight, for hover feedback. */
134
+ /** Where the mouse is over the image while no drag is in flight, for hover feedback. Not called for a touch. */
115
135
  onHover?: ((point: Point) => void) | undefined;
136
+ /**
137
+ * A double click or double tap on the surface. When given, the surface handles it and the
138
+ * stage's double-click-to-fit does not run; leave it out to keep the fit.
139
+ */
140
+ onDoubleClick?: ((point: Point) => void) | undefined;
141
+ /**
142
+ * How far the surface reaches. `"image"` (the default) is the image rectangle: a press in
143
+ * the margin around the image goes to the stage, which pans. `"viewport"` covers everything
144
+ * visible, margin included, so a drawing tool can place a point on the image's border by
145
+ * pressing just outside it; every point the surface then reports (the press, a drag's moves
146
+ * and release, hover, double-click) is clamped to the image's extent, `[-0.5, w - 0.5]` by
147
+ * `[-0.5, h - 0.5]`. `StagePress.client` stays the raw pointer position.
148
+ */
149
+ extent?: "image" | "viewport" | undefined;
116
150
  }
117
151
 
118
152
  /**
@@ -120,32 +154,93 @@ export interface StageSurfaceProps {
120
154
  * that have their own small targets (handles, strokes). Each press is offered to `onPress`
121
155
  * unless the hand tool or a held space bar make it a pan; a declined press pans.
122
156
  *
123
- * The surface draws nothing. It carries `data-dragging` while a drag it started is in
124
- * flight.
157
+ * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on
158
+ * `window`, so the stage does not pan from it.
159
+ *
160
+ * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface
161
+ * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)
162
+ * and a second finger still pinches. The drag then sees:
163
+ * - `onMove`, only once the finger has left the tap slop;
164
+ * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;
165
+ * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).
166
+ *
167
+ * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
168
+ *
169
+ * With `extent="viewport"` the surface also takes presses in the margin around the image, and
170
+ * clamps every reported point to the image.
171
+ *
172
+ * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
125
173
  */
126
- export function StageSurface({ onPress, cursor, onHover }: StageSurfaceProps) {
174
+ export function StageSurface({ onPress, cursor, onHover, onDoubleClick, extent = "image" }: StageSurfaceProps) {
127
175
  const stage = useStage();
128
176
  const start = useStageDrag();
129
177
  const [dragging, setDragging] = useState(false);
178
+ const watchRef = useRef<(() => void) | null>(null);
179
+
180
+ // A touch still being watched when the surface goes away is cancelled, not left listening.
181
+ useEffect(() => () => watchRef.current?.(), []);
182
+
183
+ const viewport = extent === "viewport";
184
+ // The image point under a client position; held to the image only for a viewport-wide surface.
185
+ const pointAt = (client: Point): Point => {
186
+ const p = stage.toImage(client);
187
+ return viewport ? clampToImage(p, stage.image) : p;
188
+ };
189
+ // The visible area in image coordinates, from the view and the measured box, so it follows
190
+ // pan, zoom and resize; the image rectangle until the viewport has been measured.
191
+ const target = (() => {
192
+ const { image, view, box } = stage;
193
+ if (!viewport || !(box.width > 0)) return { x: -0.5, y: -0.5, width: image.width, height: image.height };
194
+ const a = toImage(view, { x: 0, y: 0 });
195
+ const b = toImage(view, { x: box.width, y: box.height });
196
+ return { x: a.x, y: a.y, width: b.x - a.x, height: b.y - a.y };
197
+ })();
130
198
 
131
199
  const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {
132
- if (event.button !== 0 || stage.panMode) return;
200
+ const touch = event.pointerType === "touch";
201
+ if (stage.panMode || (!touch && event.button !== 0)) return;
202
+ // A second finger turns the first one's gesture into a pinch; the watch cancels itself on it.
203
+ if (touch && watchRef.current) return;
204
+ const client = { x: event.clientX, y: event.clientY };
133
205
  const drag = onPress({
134
- point: stage.toImage({ x: event.clientX, y: event.clientY }),
206
+ point: pointAt(client),
207
+ client,
208
+ touch,
209
+ radius: hitRadiusPx(event.pointerType),
135
210
  shiftKey: event.shiftKey,
136
211
  altKey: event.altKey,
137
212
  metaKey: event.metaKey || event.ctrlKey,
138
213
  });
139
214
  if (!drag) return; // Declined: the stage pans.
215
+ const finish = () => setDragging(false);
140
216
  setDragging(true);
217
+ if (touch && !drag.claimsTouch) {
218
+ // Watched, not claimed: the press goes on to the stage.
219
+ const release = () => {
220
+ watchRef.current = null;
221
+ finish();
222
+ };
223
+ watchRef.current = watchTouch(event, {
224
+ onMove: (e) => drag.onMove?.(pointAt({ x: e.clientX, y: e.clientY }), e),
225
+ onEnd: (e, moved) => {
226
+ release();
227
+ drag.onEnd?.(pointAt({ x: e.clientX, y: e.clientY }), e, moved);
228
+ },
229
+ onCancel: () => {
230
+ release();
231
+ drag.onCancel?.();
232
+ },
233
+ });
234
+ return;
235
+ }
141
236
  start(event, {
142
- onMove: drag.onMove,
237
+ onMove: drag.onMove && ((point, e) => drag.onMove?.(viewport ? clampToImage(point, stage.image) : point, e)),
143
238
  onEnd: (point, e, moved) => {
144
- setDragging(false);
145
- drag.onEnd?.(point, e, moved);
239
+ finish();
240
+ drag.onEnd?.(viewport ? clampToImage(point, stage.image) : point, e, moved);
146
241
  },
147
242
  onCancel: () => {
148
- setDragging(false);
243
+ finish();
149
244
  drag.onCancel?.();
150
245
  },
151
246
  });
@@ -154,22 +249,27 @@ export function StageSurface({ onPress, cursor, onHover }: StageSurfaceProps) {
154
249
  return (
155
250
  <svg
156
251
  viewBox={imageViewBox(stage.image)}
157
- className="pointer-events-none absolute inset-0 h-full w-full"
252
+ className={cn("pointer-events-none absolute inset-0 h-full w-full", viewport && "overflow-visible")}
158
253
  data-dragging={dragging ? "" : undefined}
159
254
  aria-hidden
160
255
  >
161
256
  <rect
162
257
  data-stage-surface=""
163
- x={-0.5}
164
- y={-0.5}
165
- width={stage.image.width}
166
- height={stage.image.height}
258
+ x={target.x}
259
+ y={target.y}
260
+ width={target.width}
261
+ height={target.height}
167
262
  fill="transparent"
168
263
  className="pointer-events-auto"
169
264
  style={{ cursor: stage.panMode ? undefined : cursor }}
170
265
  onPointerDown={onPointerDown}
171
266
  onPointerMove={(event) => {
172
- if (!dragging) onHover?.(stage.toImage({ x: event.clientX, y: event.clientY }));
267
+ if (!dragging && event.pointerType !== "touch") onHover?.(pointAt({ x: event.clientX, y: event.clientY }));
268
+ }}
269
+ onDoubleClick={(event) => {
270
+ if (!onDoubleClick) return;
271
+ event.stopPropagation();
272
+ onDoubleClick(pointAt({ x: event.clientX, y: event.clientY }));
173
273
  }}
174
274
  />
175
275
  </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 &&
@@ -171,6 +211,17 @@ export function insideImage(p: Point, image: Box): boolean {
171
211
  );
172
212
  }
173
213
 
214
+ /**
215
+ * An image coordinate held to the image's extent, `[-0.5, w - 0.5] x [-0.5, h - 0.5]` in the
216
+ * pixel-centre convention: the point on the frame's edge nearest to `p`.
217
+ */
218
+ export function clampToImage(p: Point, image: Box): Point {
219
+ return {
220
+ x: Math.min(image.width - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.x)),
221
+ y: Math.min(image.height - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.y)),
222
+ };
223
+ }
224
+
174
225
  /** A length in image pixels that covers `css` screen pixels at this view. */
175
226
  export function imageLengthFor(view: StageView, css: number): number {
176
227
  return view.scale > 0 ? css / view.scale : css;
@@ -194,6 +245,15 @@ export function zoomAbout(view: StageView, scale: number, anchor: Point): StageV
194
245
 
195
246
  /** The scale range `clampView` and `scaleRange` allow. */
196
247
  export interface ClampOptions {
248
+ /**
249
+ * How far the image may be panned. `"cover"` (the default): an axis the image overflows
250
+ * keeps the viewport covered, and an axis it does not fill is centred. `"center"`: any
251
+ * image point may be brought to the viewport's centre and no further, on both axes and at
252
+ * every scale — so a zoom about the pointer keeps the pointer's pixel under it while the
253
+ * image is still smaller than the viewport, and an edge or corner can be worked on in the
254
+ * middle of the screen.
255
+ */
256
+ panBounds?: "cover" | "center" | undefined;
197
257
  /** Lowest scale, as a multiple of fit. Defaults to `MIN_SCALE_VS_FIT`. */
198
258
  minScaleVsFit?: number;
199
259
  /** Highest scale, in CSS pixels per image pixel. Defaults to `MAX_SCALE`. */
@@ -211,10 +271,11 @@ export function scaleRange(box: Box, image: Box, options: ClampOptions = {}): [n
211
271
  /**
212
272
  * Keep the view legal: scale inside its range, and the image never dragged off screen.
213
273
  *
214
- * An axis where the scaled image is smaller than the viewport is centred rather than left
215
- * where a drag put it — free-floating pixels in a grey field is a way to be lost with no
216
- * visible handle to get back. An axis where it is larger is held so the viewport stays
217
- * covered.
274
+ * With the default `panBounds: "cover"`, an axis where the scaled image is smaller than the
275
+ * viewport is centred rather than left where a drag put it — free-floating pixels in a grey
276
+ * field is a way to be lost with no visible handle to get back — and an axis where it is
277
+ * larger is held so the viewport stays covered. With `"center"`, each axis only keeps some
278
+ * image point at or past the viewport's centre.
218
279
  */
219
280
  export function clampView(
220
281
  view: StageView,
@@ -224,13 +285,19 @@ export function clampView(
224
285
  ): StageView {
225
286
  const [min, max] = scaleRange(box, image, options);
226
287
  const scale = clamp(view.scale, min, max);
288
+ const axis = options.panBounds === "center" ? centreAxis : clampAxis;
227
289
  return {
228
290
  scale,
229
- tx: clampAxis(view.tx, box.width, image.width * scale),
230
- ty: clampAxis(view.ty, box.height, image.height * scale),
291
+ tx: axis(view.tx, box.width, image.width * scale),
292
+ ty: axis(view.ty, box.height, image.height * scale),
231
293
  };
232
294
  }
233
295
 
296
+ /** `"center"` bounds: the content's far edge may come to the centre, and its near edge too. */
297
+ function centreAxis(t: number, boxLength: number, contentLength: number): number {
298
+ return clamp(t, boxLength / 2 - contentLength, boxLength / 2);
299
+ }
300
+
234
301
  function clampAxis(t: number, boxLength: number, contentLength: number): number {
235
302
  if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
236
303
  return clamp(t, boxLength - contentLength, 0);
@@ -274,9 +341,10 @@ export function preserveCenter(
274
341
  to: Box,
275
342
  image: Box,
276
343
  options: ClampOptions = {},
344
+ fit: FitOptions = {},
277
345
  ): 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);
346
+ if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);
347
+ if (isFit(view, from, image, fit)) return fitView(to, image, fit);
280
348
 
281
349
  const centre = toImage(view, { x: from.width / 2, y: from.height / 2 });
282
350
  return clampView(
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@ export {
9
9
  type ImageStageProps,
10
10
  type StageContext,
11
11
  type StageHandle,
12
+ type StageViewChange,
12
13
  } from "./components/stage/ImageStage";
13
14
 
14
15
  export type { StageMouseButton } from "./components/stage/gesture";
@@ -56,6 +57,7 @@ export {
56
57
  MAX_SCALE,
57
58
  MIN_SCALE_VS_FIT,
58
59
  PIXEL_CENTRE,
60
+ clampToImage,
59
61
  clampView,
60
62
  fitScale,
61
63
  fitView,
@@ -74,6 +76,7 @@ export {
74
76
  zoomAbout,
75
77
  type Box,
76
78
  type ClampOptions,
79
+ type FitOptions,
77
80
  type Rect,
78
81
  type StageView,
79
82
  } from "./components/stage/view";
@@ -178,6 +181,23 @@ export {
178
181
  type AreaId,
179
182
  type AreaIndex,
180
183
  } from "./components/areaIndex";
184
+ export {
185
+ EllipseSet,
186
+ type EllipseSetItem,
187
+ type EllipseSetProps,
188
+ } from "./components/EllipseSet";
189
+ export {
190
+ buildEllipseIndex,
191
+ ellipseBounds,
192
+ ellipsePath,
193
+ ellipsesInRect,
194
+ nearestEllipse,
195
+ pointInEllipse,
196
+ type Ellipse,
197
+ type EllipseHit,
198
+ type EllipseId,
199
+ type EllipseIndex,
200
+ } from "./components/ellipseIndex";
181
201
  export {
182
202
  GridLayer,
183
203
  type GridEdgeStyle,