react-zoom-pan-pinch 4.1.1 → 4.2.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,245 @@
1
+ /* eslint-disable no-param-reassign */
2
+ import { ReactZoomPanPinchContext, StateType } from "../../models";
3
+ import { roundNumber } from "../../utils";
4
+ import { handleCancelAnimation } from "../animations/animations.utils";
5
+ import {
6
+ getMouseBoundedPosition,
7
+ handleCalculateBounds,
8
+ } from "../bounds/bounds.utils";
9
+ import { MeasuredSizesType } from "./resize.types";
10
+
11
+ export const measureSizes = (
12
+ wrapperComponent: HTMLElement,
13
+ contentComponent: HTMLElement,
14
+ ): MeasuredSizesType => ({
15
+ wrapperWidth: wrapperComponent.offsetWidth,
16
+ wrapperHeight: wrapperComponent.offsetHeight,
17
+ contentWidth: contentComponent.offsetWidth,
18
+ contentHeight: contentComponent.offsetHeight,
19
+ });
20
+
21
+ export const hasSizeChanged = (
22
+ previous: MeasuredSizesType | null,
23
+ current: MeasuredSizesType,
24
+ ): boolean =>
25
+ !previous ||
26
+ previous.wrapperWidth !== current.wrapperWidth ||
27
+ previous.wrapperHeight !== current.wrapperHeight ||
28
+ previous.contentWidth !== current.contentWidth ||
29
+ previous.contentHeight !== current.contentHeight;
30
+
31
+ /**
32
+ * A pointer is physically held: a mouse/touch pan or a pinch. The bounds
33
+ * belong to that gesture until it is released (moving the content under a
34
+ * held cursor is what feels like a jump).
35
+ */
36
+ export const isPointerGestureActive = (
37
+ contextInstance: ReactZoomPanPinchContext,
38
+ ): boolean => contextInstance.isPanning || contextInstance.isPinching;
39
+
40
+ /**
41
+ * Any gesture is in progress: a held pointer, or a wheel sequence whose stop
42
+ * timers have not fired yet.
43
+ */
44
+ export const isGestureActive = (
45
+ contextInstance: ReactZoomPanPinchContext,
46
+ ): boolean =>
47
+ isPointerGestureActive(contextInstance) ||
48
+ contextInstance.wheelStopEventTimer !== null ||
49
+ contextInstance.wheelAnimationTimer !== null;
50
+
51
+ /**
52
+ * Recomputes the bounds for the current scale and content/wrapper sizes and
53
+ * returns the state the transform has to move to so it sits inside them.
54
+ * Returns `null` when the transform is already inside the bounds or when
55
+ * nothing limits it (`limitToBounds` and `centerZoomedOut` both off).
56
+ *
57
+ * The bounds are stored on the instance as a side effect, so gestures that
58
+ * follow a resize clamp against the fresh sizes even when no move is needed.
59
+ */
60
+ export function calculateResizeAlignment(
61
+ contextInstance: ReactZoomPanPinchContext,
62
+ ): StateType | null {
63
+ const { wrapperComponent, contentComponent, setup, state } = contextInstance;
64
+ if (!wrapperComponent || !contentComponent) return null;
65
+
66
+ const bounds = handleCalculateBounds(contextInstance, state.scale);
67
+
68
+ // Same rule as the post-pan alignment (`handlePanToBounds`).
69
+ const { limitToBounds, centerZoomedOut } = setup;
70
+ if (!limitToBounds && !centerZoomedOut) return null;
71
+
72
+ const { x, y } = getMouseBoundedPosition(
73
+ state.positionX,
74
+ state.positionY,
75
+ bounds,
76
+ true,
77
+ 0,
78
+ 0,
79
+ wrapperComponent,
80
+ );
81
+
82
+ // `boundLimiter` rounds to two decimals; compare against the same rounding
83
+ // so an in-bounds transform never starts a zero-length animation.
84
+ const isAligned =
85
+ x === roundNumber(state.positionX, 2) &&
86
+ y === roundNumber(state.positionY, 2);
87
+ if (isAligned) return null;
88
+
89
+ return { scale: state.scale, positionX: x, positionY: y };
90
+ }
91
+
92
+ const stopResizeTracking = (contextInstance: ReactZoomPanPinchContext) => {
93
+ contextInstance.animation = null;
94
+ contextInstance.animationFrame = null;
95
+ contextInstance.isAnimating = false;
96
+ contextInstance.resizeAnimation = null;
97
+ };
98
+
99
+ /**
100
+ * Eases the transform towards the current bounds, frame by frame, until it
101
+ * rests on them.
102
+ *
103
+ * The bounds are re-read every frame, so a size that keeps changing (a CSS
104
+ * height transition, a layout settling over several frames) is followed
105
+ * smoothly — the content edge trails the moving bound by a few pixels
106
+ * instead of lagging behind a stale target and bursting after it. Each
107
+ * frame closes a fixed fraction of the remaining gap (exponential
108
+ * smoothing), tuned so a one-off step still settles within
109
+ * `autoAlignment.animationTime`.
110
+ */
111
+ function startResizeTracking(contextInstance: ReactZoomPanPinchContext): void {
112
+ const { animationTime } = contextInstance.setup.autoAlignment;
113
+ // Over 99% of a step is covered after `animationTime`; the sub-pixel rest
114
+ // snaps (see `isSettled`).
115
+ const tau = Math.max(animationTime / 5, 1);
116
+
117
+ handleCancelAnimation(contextInstance);
118
+
119
+ let lastFrameTime = Date.now();
120
+ const track = () => {
121
+ if (!contextInstance.mounted || contextInstance.animation !== track) {
122
+ return;
123
+ }
124
+ const now = Date.now();
125
+ const frameTime = Math.max(now - lastFrameTime, 1);
126
+ lastFrameTime = now;
127
+
128
+ const targetState = calculateResizeAlignment(contextInstance);
129
+ if (!targetState) {
130
+ // Back inside the bounds (the content grew again).
131
+ stopResizeTracking(contextInstance);
132
+ return;
133
+ }
134
+
135
+ const { scale, positionX, positionY } = contextInstance.state;
136
+ const factor = 1 - Math.exp(-frameTime / tau);
137
+ let x = positionX + (targetState.positionX - positionX) * factor;
138
+ let y = positionY + (targetState.positionY - positionY) * factor;
139
+
140
+ const isSettled =
141
+ Math.abs(targetState.positionX - x) < 0.5 &&
142
+ Math.abs(targetState.positionY - y) < 0.5;
143
+ if (isSettled) {
144
+ x = targetState.positionX;
145
+ y = targetState.positionY;
146
+ }
147
+
148
+ contextInstance.isAnimating = !isSettled;
149
+ contextInstance.setState(scale, x, y);
150
+
151
+ if (isSettled) {
152
+ stopResizeTracking(contextInstance);
153
+ return;
154
+ }
155
+ contextInstance.animationFrame = requestAnimationFrame(track);
156
+ };
157
+
158
+ contextInstance.animation = track;
159
+ contextInstance.resizeAnimation = track;
160
+ contextInstance.animationResolve = null;
161
+ contextInstance.animationFrame = requestAnimationFrame(track);
162
+ }
163
+
164
+ /**
165
+ * Brings the transform back into the bounds after the content or the
166
+ * wrapper changed size — immediately: a move still in flight (inertia, an
167
+ * alignment, a programmatic animation) is cancelled and a trackpad sequence
168
+ * simply continues against the fresh bounds, so a layout that collapses
169
+ * while the user scrolls aligns right away.
170
+ *
171
+ * Two things are left alone. A pointer that is still held owns the bounds
172
+ * until it is released (replacing them mid-drag makes the next move clamp
173
+ * against a new limit and jump under the cursor); the release then aligns
174
+ * against the fresh bounds (`handleAlignToBounds`). And an animation that is
175
+ * bringing the scale back inside `minScale`/`maxScale` must finish, because
176
+ * the tracking only moves the position. Both come back here afterwards via
177
+ * `flushResizeAlignment`.
178
+ */
179
+ export function handleResizeAlignment(
180
+ contextInstance: ReactZoomPanPinchContext,
181
+ ): void {
182
+ if (contextInstance.setup.disabled) {
183
+ // Nothing may move, but the next gesture must see the right limits.
184
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
185
+ return;
186
+ }
187
+
188
+ if (isPointerGestureActive(contextInstance)) {
189
+ contextInstance.isResizeAlignmentPending = true;
190
+ return;
191
+ }
192
+
193
+ const isOwnAnimation =
194
+ contextInstance.animation !== null &&
195
+ contextInstance.animation === contextInstance.resizeAnimation;
196
+
197
+ if (contextInstance.animation && !isOwnAnimation) {
198
+ const { scale } = contextInstance.state;
199
+ const { minScale, maxScale } = contextInstance.setup;
200
+ if (scale < minScale || scale > maxScale) {
201
+ contextInstance.isResizeAlignmentPending = true;
202
+ return;
203
+ }
204
+ handleCancelAnimation(contextInstance);
205
+ }
206
+
207
+ const targetState = calculateResizeAlignment(contextInstance);
208
+
209
+ if (!targetState) {
210
+ if (isOwnAnimation) stopResizeTracking(contextInstance);
211
+ return;
212
+ }
213
+
214
+ // The tracking loop re-reads the bounds itself; it just keeps running.
215
+ if (isOwnAnimation) return;
216
+
217
+ if (contextInstance.setup.autoAlignment.animationTime === 0) {
218
+ contextInstance.setState(
219
+ targetState.scale,
220
+ targetState.positionX,
221
+ targetState.positionY,
222
+ );
223
+ return;
224
+ }
225
+
226
+ startResizeTracking(contextInstance);
227
+ }
228
+
229
+ /**
230
+ * Entry point for the size observer: ignores notifications that carry no
231
+ * size change (the observer's initial delivery, style-only changes) and
232
+ * aligns on the ones that do.
233
+ */
234
+ export function handleSizeChange(
235
+ contextInstance: ReactZoomPanPinchContext,
236
+ ): void {
237
+ const { wrapperComponent, contentComponent } = contextInstance;
238
+ if (!wrapperComponent || !contentComponent) return;
239
+
240
+ const sizes = measureSizes(wrapperComponent, contentComponent);
241
+ if (!hasSizeChanged(contextInstance.measuredSizes, sizes)) return;
242
+
243
+ contextInstance.measuredSizes = sizes;
244
+ handleResizeAlignment(contextInstance);
245
+ }
@@ -0,0 +1,6 @@
1
+ export type MeasuredSizesType = {
2
+ wrapperWidth: number;
3
+ wrapperHeight: number;
4
+ contentWidth: number;
5
+ contentHeight: number;
6
+ };
@@ -113,6 +113,7 @@ export const handleWheelStop = (
113
113
  if (!contextInstance.mounted) return;
114
114
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
115
115
  contextInstance.wheelAnimationTimer = null;
116
+ contextInstance.flushResizeAlignment();
116
117
  }, wheelAnimationTime);
117
118
 
118
119
  // Wheel stop event
@@ -124,6 +125,7 @@ export const handleWheelStop = (
124
125
  contextInstance.wheelStopEventTimer = null;
125
126
  handleCallback(getContext(contextInstance), event, onWheelStop);
126
127
  handleCallback(getContext(contextInstance), event, onZoomStop);
128
+ contextInstance.flushResizeAlignment();
127
129
  }, wheelStopEventTime);
128
130
  }
129
131
  };
@@ -139,8 +141,13 @@ export const handleWheelPanningStart = (
139
141
 
140
142
  if (!contextInstance.wheelStopEventTimer) {
141
143
  // Same as a mouse pan start: bounds must reflect the current scale and
142
- // content size, not the ones measured at mount (#396, #433).
143
- handleCalculateBounds(contextInstance, contextInstance.state.scale);
144
+ // content size, not the ones measured at mount (#396, #433). Only at the
145
+ // start of a wheel sequence though — mid-sequence the gesture owns them
146
+ // (see `handleResizeAlignment`), otherwise a content resize would make
147
+ // the next event clamp against a new limit and jump.
148
+ if (!contextInstance.wheelAnimationTimer) {
149
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
150
+ }
144
151
  handleCallback(getContext(contextInstance), event, onWheelStart);
145
152
  handleCallback(getContext(contextInstance), event, onPanningStart);
146
153
  }
@@ -158,6 +165,7 @@ export const handleWheelPanningStop = (
158
165
  if (!contextInstance.mounted) return;
159
166
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
160
167
  contextInstance.wheelAnimationTimer = null;
168
+ contextInstance.flushResizeAlignment();
161
169
  }, wheelAnimationTime);
162
170
 
163
171
  // Wheel stop event
@@ -169,6 +177,7 @@ export const handleWheelPanningStop = (
169
177
  contextInstance.wheelStopEventTimer = null;
170
178
  handleCallback(getContext(contextInstance), event, onWheelStop);
171
179
  handleCallback(getContext(contextInstance), event, onPanningStop);
180
+ contextInstance.flushResizeAlignment();
172
181
  }, wheelStopEventTime);
173
182
  }
174
183
  };
@@ -54,8 +54,8 @@ export function handleAlignToScaleBounds(
54
54
 
55
55
  if (isDisabled || !wrapperComponent || !contextInstance.mounted) return;
56
56
 
57
- const mouseX = mousePositionX || wrapperComponent.offsetWidth / 2;
58
- const mouseY = mousePositionY || wrapperComponent.offsetHeight / 2;
57
+ const mouseX = mousePositionX || wrapperComponent.clientWidth / 2;
58
+ const mouseY = mousePositionY || wrapperComponent.clientHeight / 2;
59
59
 
60
60
  const targetScale = scale < minScale ? minScale : maxScale;
61
61
  const targetState = handleZoomToPoint(
@@ -6,6 +6,8 @@ import {
6
6
  centerView,
7
7
  clientToContent,
8
8
  contentToClient,
9
+ fitToView,
10
+ panBy,
9
11
  resetTransform,
10
12
  setTransform,
11
13
  zoomIn,
@@ -30,6 +32,19 @@ export type ZoomToElementOptions = {
30
32
  offsetY?: number;
31
33
  };
32
34
 
35
+ export type FitToViewMode = "contain" | "cover";
36
+
37
+ export type FitToViewOptions = {
38
+ /** `contain` (default) shows the whole content, `cover` fills the viewport. */
39
+ mode?: FitToViewMode;
40
+ /** Lower cap for the computed fit scale. */
41
+ minScale?: number;
42
+ /** Upper cap for the computed fit scale. */
43
+ maxScale?: number;
44
+ animationTime?: number;
45
+ animationType?: keyof typeof animations;
46
+ };
47
+
33
48
  export type ReactZoomPanPinchContext = typeof ZoomPanPinch.prototype;
34
49
 
35
50
  export type ReactZoomPanPinchContextState = {
@@ -62,6 +77,8 @@ export type ReactZoomPanPinchHandlers = {
62
77
  zoomToPoint: ReturnType<typeof zoomToPoint>;
63
78
  clientToContent: ReturnType<typeof clientToContent>;
64
79
  contentToClient: ReturnType<typeof contentToClient>;
80
+ fitToView: ReturnType<typeof fitToView>;
81
+ panBy: ReturnType<typeof panBy>;
65
82
  };
66
83
 
67
84
  export type ReactZoomPanPinchRefProps = {
@@ -87,6 +104,12 @@ export type ReactZoomPanPinchProps = {
87
104
  limitToBounds?: boolean;
88
105
  centerZoomedOut?: boolean;
89
106
  centerOnInit?: boolean;
107
+ /**
108
+ * Fit the content to the wrapper on init (and again when the content gets
109
+ * its size, e.g. after an image loads). `true`/`"contain"` shows the whole
110
+ * content, `"cover"` fills the wrapper. Honours `minScale`/`maxScale`.
111
+ */
112
+ fitOnInit?: boolean | FitToViewMode;
90
113
  disablePadding?: boolean;
91
114
  customTransform?: (x: number, y: number, scale: number) => string;
92
115
  smooth?: boolean;
@@ -123,6 +146,17 @@ export type ReactZoomPanPinchProps = {
123
146
  activationKeys?: string[] | ((keys: string[]) => boolean);
124
147
  excluded?: string[];
125
148
  };
149
+ keyboard?: {
150
+ /** Keyboard navigation is opt-in. */
151
+ disabled?: boolean;
152
+ /** Pixels moved per arrow key press. */
153
+ panStep?: number;
154
+ /** Scale added/removed per +/- press. */
155
+ zoomStep?: number;
156
+ animationTime?: number;
157
+ animationType?: keyof typeof animations;
158
+ excluded?: string[];
159
+ };
126
160
  doubleClick?: {
127
161
  disabled?: boolean;
128
162
  step?: number;
@@ -14,6 +14,8 @@ import {
14
14
  centerView,
15
15
  clientToContent,
16
16
  contentToClient,
17
+ fitToView,
18
+ panBy,
17
19
  } from "../core/handlers/handlers.logic";
18
20
 
19
21
  export const getControls = (
@@ -31,6 +33,8 @@ export const getControls = (
31
33
  zoomToPoint: zoomToPoint(contextInstance),
32
34
  clientToContent: clientToContent(contextInstance),
33
35
  contentToClient: contentToClient(contextInstance),
36
+ fitToView: fitToView(contextInstance),
37
+ panBy: panBy(contextInstance),
34
38
  };
35
39
  };
36
40
 
@@ -38,8 +38,8 @@ export const getCenterPosition = (
38
38
  const contentWidth = contentComponent.offsetWidth * scale;
39
39
  const contentHeight = contentComponent.offsetHeight * scale;
40
40
 
41
- const centerPositionX = (wrapperComponent.offsetWidth - contentWidth) / 2;
42
- const centerPositionY = (wrapperComponent.offsetHeight - contentHeight) / 2;
41
+ const centerPositionX = (wrapperComponent.clientWidth - contentWidth) / 2;
42
+ const centerPositionY = (wrapperComponent.clientHeight - contentHeight) / 2;
43
43
 
44
44
  return {
45
45
  scale,