react-zoom-pan-pinch 4.1.1 → 4.3.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.
Files changed (33) hide show
  1. package/README.md +4 -4
  2. package/dist/index.cjs.js +1081 -231
  3. package/dist/index.cjs.js.map +1 -1
  4. package/dist/index.d.ts +99 -3
  5. package/dist/index.esm.js +1082 -232
  6. package/dist/index.esm.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/components/mini-map/mini-map.tsx +386 -171
  9. package/src/components/transform-component/transform-component.module.css +2 -5
  10. package/src/components/transform-component/transform-component.tsx +7 -0
  11. package/src/components/virtualize/virtualize.tsx +2 -2
  12. package/src/constants/state.constants.ts +9 -0
  13. package/src/core/animations/animations.utils.ts +2 -0
  14. package/src/core/bounds/bounds.utils.ts +90 -2
  15. package/src/core/handlers/handlers.logic.ts +85 -0
  16. package/src/core/handlers/handlers.utils.ts +102 -5
  17. package/src/core/instance.core.ts +222 -41
  18. package/src/core/keyboard/keyboard.logic.ts +84 -0
  19. package/src/core/pan/panning.logic.ts +24 -4
  20. package/src/core/pan/panning.utils.ts +95 -36
  21. package/src/core/pan/velocity.logic.ts +11 -4
  22. package/src/core/pan/velocity.utils.ts +2 -2
  23. package/src/core/resize/index.ts +0 -0
  24. package/src/core/resize/resize.logic.ts +245 -0
  25. package/src/core/resize/resize.types.ts +6 -0
  26. package/src/core/wheel/wheel.logic.ts +11 -2
  27. package/src/core/zoom/zoom.logic.ts +2 -2
  28. package/src/hooks/initial-layout.utils.ts +21 -0
  29. package/src/hooks/use-transform-component.tsx +22 -4
  30. package/src/hooks/use-transform-effect.tsx +20 -1
  31. package/src/models/context.model.ts +34 -0
  32. package/src/utils/context.utils.ts +4 -0
  33. package/src/utils/styles.utils.ts +2 -2
@@ -70,8 +70,15 @@ export const TransformComponent: React.FC<Props> = ({
70
70
  return instance.onChange(sync);
71
71
  }, [infinite, instance]);
72
72
 
73
+ // Keyboard navigation (#254) needs a focus target; `wrapperProps.tabIndex`
74
+ // still wins because it is spread afterwards.
75
+ const keyboardEnabled = !instance.setup.keyboard?.disabled;
76
+
73
77
  return (
74
78
  <div
79
+ // The wrapper is a keyboard-operated widget when navigation is on.
80
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
81
+ tabIndex={keyboardEnabled ? 0 : undefined}
75
82
  {...wrapperProps}
76
83
  ref={wrapperRef}
77
84
  className={`${baseClasses.wrapperClass} ${styles.wrapper} ${wrapperClass}`}
@@ -81,8 +81,8 @@ export const Virtualize = React.forwardRef<HTMLDivElement, VirtualizeProps>(
81
81
  scale: instance.state.scale,
82
82
  positionX: instance.state.positionX,
83
83
  positionY: instance.state.positionY,
84
- viewportWidth: wrapper.offsetWidth,
85
- viewportHeight: wrapper.offsetHeight,
84
+ viewportWidth: wrapper.clientWidth,
85
+ viewportHeight: wrapper.clientHeight,
86
86
  margin,
87
87
  threshold,
88
88
  });
@@ -22,6 +22,7 @@ export const initialSetup: LibrarySetup = {
22
22
  limitToBounds: true,
23
23
  centerZoomedOut: false,
24
24
  centerOnInit: false,
25
+ fitOnInit: false,
25
26
  disablePadding: false,
26
27
  smooth: true,
27
28
  detached: false,
@@ -58,6 +59,14 @@ export const initialSetup: LibrarySetup = {
58
59
  allowPanning: true,
59
60
  excluded: [],
60
61
  },
62
+ keyboard: {
63
+ disabled: true,
64
+ panStep: 50,
65
+ zoomStep: 0.25,
66
+ animationTime: 100,
67
+ animationType: "easeOut",
68
+ excluded: [],
69
+ },
61
70
  doubleClick: {
62
71
  disabled: false,
63
72
  step: 0.7,
@@ -69,6 +69,8 @@ export function handleSetupAnimation(
69
69
  contextInstance.animationResolve = null;
70
70
  callback(lastStep);
71
71
  resolve?.();
72
+ // A resize seen while this animation ran aligns its final state.
73
+ contextInstance.flushResizeAlignment();
72
74
  } else {
73
75
  callback(step);
74
76
  contextInstance.animationFrame = requestAnimationFrame(animation);
@@ -12,8 +12,8 @@ export function getComponentsSizes(
12
12
  contentComponent: HTMLDivElement,
13
13
  newScale: number,
14
14
  ): ComponentsSizesType {
15
- const wrapperWidth = wrapperComponent.offsetWidth;
16
- const wrapperHeight = wrapperComponent.offsetHeight;
15
+ const wrapperWidth = wrapperComponent.clientWidth;
16
+ const wrapperHeight = wrapperComponent.clientHeight;
17
17
 
18
18
  const contentWidth = contentComponent.offsetWidth;
19
19
  const contentHeight = contentComponent.offsetHeight;
@@ -160,6 +160,61 @@ export function rubberbandIfOutOfBounds(
160
160
  return position;
161
161
  }
162
162
 
163
+ /**
164
+ * Furthest a grabbed position is traced back along the rubber band curve, as
165
+ * a fraction of the padding. The curve never reaches the padding itself, so
166
+ * a position at (or past) it has no pointer distance to map back to.
167
+ */
168
+ const MAX_RUBBER_BAND_RATIO = 0.9;
169
+
170
+ /**
171
+ * Resistance of the rubber band, the constant UIScrollView uses: past a bound
172
+ * the content moves at 0.55× the pointer and slows down from there.
173
+ */
174
+ export const RUBBER_BAND_CONSTANT = 0.55;
175
+
176
+ /**
177
+ * Where a pan that was dragged past a bound ends up: `(1 - 1 / (x * c / d + 1)) * d`
178
+ * with `d` = `padding`. It trails the pointer from the first pixel past the
179
+ * bound and approaches — never reaches — `padding` px past it.
180
+ */
181
+ export function getRubberBandPosition(
182
+ position: number,
183
+ min: number,
184
+ max: number,
185
+ padding: number,
186
+ ): number {
187
+ if (padding <= 0) return clamp(position, min, max);
188
+ if (position < min)
189
+ return min - rubberband(min - position, padding, RUBBER_BAND_CONSTANT);
190
+ if (position > max)
191
+ return max + rubberband(position - max, padding, RUBBER_BAND_CONSTANT);
192
+ return position;
193
+ }
194
+
195
+ /**
196
+ * Inverse of `getRubberBandPosition`: the pointer position that puts the
197
+ * content at `position`. Lets a pan that starts inside the padding (grabbed
198
+ * mid return animation, trackpad deltas) continue from where the content is.
199
+ */
200
+ export function getRubberBandSource(
201
+ position: number,
202
+ min: number,
203
+ max: number,
204
+ padding: number,
205
+ ): number {
206
+ if (padding <= 0) return position;
207
+
208
+ const stretch = (offset: number) => {
209
+ const limited = Math.min(offset, padding * MAX_RUBBER_BAND_RATIO);
210
+ return (limited * padding) / (RUBBER_BAND_CONSTANT * (padding - limited));
211
+ };
212
+
213
+ if (position < min) return min - stretch(min - position);
214
+ if (position > max) return max + stretch(position - max);
215
+ return position;
216
+ }
217
+
163
218
  /**
164
219
  * Keeps value between given bounds, used for limiting view to given boundaries
165
220
  * 1# eg. boundLimiter(2, 0, 3, true) => 2
@@ -224,3 +279,36 @@ export function getMouseBoundedPosition(
224
279
  );
225
280
  return { x, y };
226
281
  }
282
+
283
+ /**
284
+ * Bounded position for a pan gesture: free inside the bounds and, inside the
285
+ * padding around them, rubber banded (`rubberBand`) or 1:1 up to its edge.
286
+ */
287
+ export function getPanBoundedPosition(
288
+ positionX: number,
289
+ positionY: number,
290
+ bounds: BoundsType,
291
+ limitToBounds: boolean,
292
+ paddingX: number,
293
+ paddingY: number,
294
+ rubberBand: boolean,
295
+ ): PositionType {
296
+ const { minPositionX, minPositionY, maxPositionX, maxPositionY } = bounds;
297
+
298
+ const limit = (
299
+ position: number,
300
+ min: number,
301
+ max: number,
302
+ padding: number,
303
+ ) => {
304
+ if (limitToBounds && rubberBand && padding > 0) {
305
+ return roundNumber(getRubberBandPosition(position, min, max, padding), 2);
306
+ }
307
+ return boundLimiter(position, min - padding, max + padding, limitToBounds);
308
+ };
309
+
310
+ return {
311
+ x: limit(positionX, minPositionX, maxPositionX, paddingX),
312
+ y: limit(positionY, minPositionY, maxPositionY, paddingY),
313
+ };
314
+ }
@@ -1,18 +1,25 @@
1
1
  import {
2
+ FitToViewOptions,
2
3
  PositionType,
3
4
  ReactZoomPanPinchContext,
4
5
  ZoomToElementOptions,
5
6
  ZoomToElementTarget,
6
7
  } from "../../models";
7
8
  import {
9
+ calculateFitToView,
8
10
  calculateZoomToRect,
9
11
  clientToContentPoint,
10
12
  contentToClientPoint,
11
13
  getUnionRect,
12
14
  handleZoomToViewCenter,
13
15
  resetTransformations,
16
+ runPanAnimation,
14
17
  runZoomAnimation,
15
18
  } from "./handlers.utils";
19
+ import {
20
+ handleCalculateBounds,
21
+ getMouseBoundedPosition,
22
+ } from "../bounds/bounds.utils";
16
23
  import { animations } from "../animations/animations.constants";
17
24
  import { animate, handleCancelAnimation } from "../animations/animations.utils";
18
25
  import { handleZoomToPoint } from "../zoom/zoom.logic";
@@ -252,3 +259,81 @@ export const zoomToElement =
252
259
  options.animationType ?? animationType,
253
260
  );
254
261
  };
262
+
263
+ /**
264
+ * Fits the whole content into the viewport (`contain`, default) or fills the
265
+ * viewport with it (`cover`), centred. Honours the wrapper's
266
+ * `minScale`/`maxScale`; lower `minScale` to let large content shrink (#252).
267
+ */
268
+ export const fitToView =
269
+ (contextInstance: ReactZoomPanPinchContext) =>
270
+ (options: FitToViewOptions = {}): Promise<void> => {
271
+ const { wrapperComponent, contentComponent, setup } = contextInstance;
272
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
273
+ return Promise.resolve();
274
+ }
275
+
276
+ const targetState = calculateFitToView(
277
+ contextInstance,
278
+ options.mode ?? "contain",
279
+ options.minScale,
280
+ options.maxScale,
281
+ );
282
+ if (!targetState) return Promise.resolve();
283
+
284
+ const animationTime = setup.zoomAnimation.disabled
285
+ ? 0
286
+ : options.animationTime ?? 200;
287
+
288
+ return runZoomAnimation(
289
+ contextInstance,
290
+ targetState,
291
+ animationTime,
292
+ options.animationType ?? "easeOut",
293
+ );
294
+ };
295
+
296
+ /**
297
+ * Pans by a pixel delta (positive x moves the content right), limited to the
298
+ * bounds when `limitToBounds` is on. Backs the keyboard arrows and is handy
299
+ * for directional buttons (#254, #527).
300
+ */
301
+ export const panBy =
302
+ (contextInstance: ReactZoomPanPinchContext) =>
303
+ (
304
+ deltaX: number,
305
+ deltaY: number,
306
+ animationTime = 200,
307
+ animationType: keyof typeof animations = "easeOut",
308
+ ): Promise<void> => {
309
+ const { wrapperComponent, contentComponent, setup, state } =
310
+ contextInstance;
311
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
312
+ return Promise.resolve();
313
+ }
314
+ if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY)) {
315
+ return Promise.resolve();
316
+ }
317
+
318
+ const bounds = handleCalculateBounds(contextInstance, state.scale);
319
+ const { x, y } = getMouseBoundedPosition(
320
+ state.positionX + deltaX,
321
+ state.positionY + deltaY,
322
+ bounds,
323
+ setup.limitToBounds,
324
+ 0,
325
+ 0,
326
+ wrapperComponent,
327
+ );
328
+
329
+ if (x === state.positionX && y === state.positionY) {
330
+ return Promise.resolve();
331
+ }
332
+
333
+ return runPanAnimation(
334
+ contextInstance,
335
+ { scale: state.scale, positionX: x, positionY: y },
336
+ animationTime,
337
+ animationType,
338
+ );
339
+ };
@@ -109,8 +109,8 @@ export function handleZoomToViewCenter(
109
109
 
110
110
  const effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
111
111
 
112
- const wrapperWidth = wrapperComponent.offsetWidth;
113
- const wrapperHeight = wrapperComponent.offsetHeight;
112
+ const wrapperWidth = wrapperComponent.clientWidth;
113
+ const wrapperHeight = wrapperComponent.clientHeight;
114
114
  const mouseX = (wrapperWidth / 2 - positionX) / scale;
115
115
  const mouseY = (wrapperHeight / 2 - positionY) / scale;
116
116
 
@@ -138,6 +138,78 @@ export function handleZoomToViewCenter(
138
138
  );
139
139
  }
140
140
 
141
+ /**
142
+ * Runs a programmatic pan: fires `onPanningStart`/`onPanning`, animates to
143
+ * `targetState` and fires `onPanningStop` once the animation time has
144
+ * elapsed. Resolves when the animation has finished (or was interrupted).
145
+ */
146
+ export function runPanAnimation(
147
+ contextInstance: ReactZoomPanPinchContext,
148
+ targetState: StateType,
149
+ animationTime: number,
150
+ animationType: keyof typeof animations,
151
+ ): Promise<void> {
152
+ const { wrapperComponent } = contextInstance;
153
+ const { onPanningStart, onPanning, onPanningStop } = contextInstance.props;
154
+ const event = new MouseEvent("mousemove", { bubbles: true });
155
+ const ctx = getContext(contextInstance);
156
+ handleCallback(ctx, event, onPanningStart);
157
+ handleCallback(ctx, event, onPanning);
158
+ const done = animate(
159
+ contextInstance,
160
+ targetState,
161
+ animationTime,
162
+ animationType,
163
+ );
164
+ const win =
165
+ wrapperComponent?.ownerDocument?.defaultView ??
166
+ (typeof window !== "undefined" ? window : null);
167
+ if (win) {
168
+ win.setTimeout(() => {
169
+ if (!contextInstance.mounted) return;
170
+ handleCallback(getContext(contextInstance), event, onPanningStop);
171
+ }, animationTime);
172
+ }
173
+ return done;
174
+ }
175
+
176
+ /**
177
+ * Scale and centred position that fit the whole content into the wrapper
178
+ * (`contain`) or fill the wrapper with it (`cover`) (#252).
179
+ *
180
+ * The fit scale is capped by `minFitScale`/`maxFitScale` first and by the
181
+ * wrapper's own `minScale`/`maxScale` second — with the default `minScale` of
182
+ * 1 the content is never shrunk, so lower `minScale` to fit large content.
183
+ * Returns `null` until both elements have a size.
184
+ */
185
+ export function calculateFitToView(
186
+ contextInstance: ReactZoomPanPinchContext,
187
+ mode: "contain" | "cover" = "contain",
188
+ minFitScale?: number,
189
+ maxFitScale?: number,
190
+ ): StateType | null {
191
+ const { wrapperComponent, contentComponent, setup } = contextInstance;
192
+ if (!wrapperComponent || !contentComponent) return null;
193
+
194
+ const contentWidth = contentComponent.offsetWidth;
195
+ const contentHeight = contentComponent.offsetHeight;
196
+ const wrapperWidth = wrapperComponent.clientWidth;
197
+ const wrapperHeight = wrapperComponent.clientHeight;
198
+ if (!contentWidth || !contentHeight || !wrapperWidth || !wrapperHeight) {
199
+ return null;
200
+ }
201
+
202
+ const ratioX = wrapperWidth / contentWidth;
203
+ const ratioY = wrapperHeight / contentHeight;
204
+ let scale =
205
+ mode === "cover" ? Math.max(ratioX, ratioY) : Math.min(ratioX, ratioY);
206
+ if (maxFitScale !== undefined) scale = Math.min(scale, maxFitScale);
207
+ if (minFitScale !== undefined) scale = Math.max(scale, minFitScale);
208
+ scale = checkZoomBounds(scale, setup.minScale, setup.maxScale, 0, false);
209
+
210
+ return getCenterPosition(scale, wrapperComponent, contentComponent);
211
+ }
212
+
141
213
  export function resetTransformations(
142
214
  contextInstance: ReactZoomPanPinchContext,
143
215
  animationTime: number,
@@ -145,12 +217,37 @@ export function resetTransformations(
145
217
  onResetTransformation?: () => void,
146
218
  ): Promise<void> {
147
219
  const { setup, wrapperComponent, contentComponent } = contextInstance;
148
- const { limitToBounds, centerOnInit } = setup;
220
+ const { limitToBounds, centerOnInit, fitOnInit } = setup;
149
221
  const initialTransformation = createState(contextInstance.props);
150
222
  const { scale, positionX, positionY } = contextInstance.state;
151
223
 
152
224
  if (!wrapperComponent) return Promise.resolve();
153
225
 
226
+ // With `fitOnInit` the initial layout is the fitted one, so that is what a
227
+ // reset returns to (#252).
228
+ if (fitOnInit) {
229
+ const fitted = calculateFitToView(
230
+ contextInstance,
231
+ fitOnInit === "cover" ? "cover" : "contain",
232
+ );
233
+ if (fitted) {
234
+ if (
235
+ scale === fitted.scale &&
236
+ positionX === fitted.positionX &&
237
+ positionY === fitted.positionY
238
+ ) {
239
+ return Promise.resolve();
240
+ }
241
+ onResetTransformation?.();
242
+ return runZoomAnimation(
243
+ contextInstance,
244
+ fitted,
245
+ animationTime,
246
+ animationType,
247
+ );
248
+ }
249
+ }
250
+
154
251
  let targetPositionX = initialTransformation.positionX;
155
252
  let targetPositionY = initialTransformation.positionY;
156
253
 
@@ -275,8 +372,8 @@ export function calculateZoomToRect(
275
372
  const nodeWidth = rect.width / state.scale;
276
373
  const nodeHeight = rect.height / state.scale;
277
374
 
278
- const scaleX = wrapperComponent.offsetWidth / nodeWidth;
279
- const scaleY = wrapperComponent.offsetHeight / nodeHeight;
375
+ const scaleX = wrapperComponent.clientWidth / nodeWidth;
376
+ const scaleY = wrapperComponent.clientHeight / nodeHeight;
280
377
 
281
378
  let targetScale = customZoom || Math.min(scaleX, scaleY);
282
379
  if (maxFitScale !== undefined) {