react-zoom-pan-pinch 4.3.0 → 4.4.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,40 @@
1
+ .transform-component-module_wrapper__SPB86 {
2
+ position: relative;
3
+ width: -moz-fit-content;
4
+ width: fit-content;
5
+ height: -moz-fit-content;
6
+ height: fit-content;
7
+ overflow: hidden;
8
+ -webkit-touch-callout: none; /* iOS Safari */
9
+ /* Text stays selectable (#467); the instance applies an inline lock
10
+ only while a pan gesture is active. */
11
+ margin: 0;
12
+ padding: 0;
13
+ transform: translate3d(0, 0, 0);
14
+ }
15
+ .transform-component-module_content__FBWxo {
16
+ display: flex;
17
+ flex-wrap: wrap;
18
+ width: -moz-fit-content;
19
+ width: fit-content;
20
+ height: -moz-fit-content;
21
+ height: fit-content;
22
+ margin: 0;
23
+ padding: 0;
24
+ transform-origin: 0% 0%;
25
+ }
26
+ .transform-component-module_content__FBWxo img {
27
+ pointer-events: none;
28
+ }
29
+ .transform-component-module_infiniteGrid__Z-aP3 {
30
+ position: absolute;
31
+ inset: 0;
32
+ pointer-events: none;
33
+ background-image: radial-gradient(
34
+ circle,
35
+ rgba(0, 0, 0, 0.12) 1px,
36
+ transparent 1px
37
+ );
38
+ background-size: 20px 20px;
39
+ background-position: 0 0;
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-zoom-pan-pinch",
3
- "version": "4.3.0",
3
+ "version": "4.4.0",
4
4
  "packageManager": "yarn@4.9.2",
5
5
  "description": "Zoom and pan html elements in easy way.",
6
6
  "author": "prc5",
@@ -3,10 +3,17 @@ import React, { useContext, useEffect, useRef } from "react";
3
3
 
4
4
  import { Context } from "../transform-wrapper/transform-wrapper";
5
5
  import { baseClasses } from "../../constants/state.constants";
6
- import { getTransformStyles } from "../../utils/styles.utils";
6
+ import { getTransformStyles, injectStylesheet } from "../../utils/styles.utils";
7
7
  import { useIsomorphicLayoutEffect } from "../../utils/effect.utils";
8
8
 
9
- import styles from "./transform-component.module.css";
9
+ // Namespace import: only the library build (rollup-plugin-postcss with
10
+ // `inject: false`) exports `stylesheet`. A named import would be a hard
11
+ // error under bundlers that load the CSS module themselves (Vite in
12
+ // Storybook); a missing property is just undefined.
13
+ import * as cssModule from "./transform-component.module.css";
14
+
15
+ const styles = cssModule.default;
16
+ const { stylesheet } = cssModule;
10
17
 
11
18
  type Props = {
12
19
  children: React.ReactNode;
@@ -22,6 +29,16 @@ type Props = {
22
29
  * `limitToBounds={false}` on TransformWrapper for full effect.
23
30
  */
24
31
  infinite?: boolean;
32
+ /**
33
+ * Nonce for the `<style>` the component adds, for a Content Security
34
+ * Policy with `style-src 'nonce-…'`.
35
+ */
36
+ nonce?: string;
37
+ /**
38
+ * Do not add the stylesheet; load `react-zoom-pan-pinch/dist/styles.css`
39
+ * yourself instead (a CSP that allows no inline `<style>`).
40
+ */
41
+ disableStyleInjection?: boolean;
25
42
  };
26
43
 
27
44
  export const TransformComponent: React.FC<Props> = ({
@@ -33,6 +50,8 @@ export const TransformComponent: React.FC<Props> = ({
33
50
  wrapperProps = {},
34
51
  contentProps = {},
35
52
  infinite = false,
53
+ nonce,
54
+ disableStyleInjection = false,
36
55
  }: Props) => {
37
56
  const instance = useContext(Context);
38
57
  const { init, cleanupWindowEvents } = instance;
@@ -47,6 +66,10 @@ export const TransformComponent: React.FC<Props> = ({
47
66
  useIsomorphicLayoutEffect(() => {
48
67
  const wrapper = wrapperRef.current;
49
68
  const content = contentRef.current;
69
+ // Before `init` measures anything: the sizes depend on these rules.
70
+ if (wrapper !== null && !disableStyleInjection) {
71
+ injectStylesheet(wrapper, stylesheet, nonce);
72
+ }
50
73
  if (wrapper !== null && content !== null && init) {
51
74
  init?.(wrapper, content);
52
75
  }
@@ -37,6 +37,7 @@ export const initialSetup: LibrarySetup = {
37
37
  trackPadPanning: {
38
38
  disabled: true,
39
39
  velocityDisabled: false,
40
+ speed: 1,
40
41
  lockAxisX: false,
41
42
  lockAxisY: false,
42
43
  activationKeys: [],
@@ -50,6 +51,8 @@ export const initialSetup: LibrarySetup = {
50
51
  allowLeftClickPan: true,
51
52
  allowMiddleClickPan: true,
52
53
  allowRightClickPan: true,
54
+ suppressClickAfterPan: true,
55
+ releaseAtBounds: false,
53
56
  activationKeys: [],
54
57
  excluded: [],
55
58
  },
@@ -11,6 +11,7 @@ import {
11
11
  isExcludedNode,
12
12
  } from "../../utils";
13
13
  import {
14
+ getResetScale,
14
15
  handleCalculateButtonZoom,
15
16
  resetTransformations,
16
17
  } from "../handlers/handlers.utils";
@@ -46,17 +47,14 @@ export const handleDoubleClickResetMode = (
46
47
  handleDoubleClickStop(contextInstance, event);
47
48
  };
48
49
 
49
- function getDoubleClickScale(
50
- mode: LibrarySetup["doubleClick"]["mode"],
51
- scale: number,
52
- ) {
53
- if (mode === "toggle") {
54
- return scale === 1 ? 1 : -1;
55
- }
56
-
50
+ function getDoubleClickScale(mode: LibrarySetup["doubleClick"]["mode"]) {
57
51
  return mode === "zoomOut" ? -1 : 1;
58
52
  }
59
53
 
54
+ // Scales closer than this count as "at the reset scale": animations and fits
55
+ // land on float values.
56
+ const RESET_SCALE_TOLERANCE = 1e-3;
57
+
60
58
  export function handleDoubleClick(
61
59
  contextInstance: ReactZoomPanPinchContext,
62
60
  event: MouseEvent | TouchEvent,
@@ -76,9 +74,20 @@ export function handleDoubleClick(
76
74
  return handleDoubleClickResetMode(contextInstance, event);
77
75
  }
78
76
 
77
+ // `toggle` (#125): at the reset scale (`initialScale`, or the fitted one
78
+ // with `fitOnInit`) zoom in by `step`; anywhere else go back to the reset
79
+ // state. It used to compare against 1, so with another initial scale the
80
+ // first double click zoomed out, and the way back only stepped out.
81
+ if (mode === "toggle") {
82
+ const resetScale = getResetScale(contextInstance);
83
+ if (Math.abs(scale - resetScale) > RESET_SCALE_TOLERANCE) {
84
+ return handleDoubleClickResetMode(contextInstance, event);
85
+ }
86
+ }
87
+
79
88
  if (!contentComponent) return console.error("No ContentComponent found");
80
89
 
81
- const delta = getDoubleClickScale(mode, contextInstance.state.scale);
90
+ const delta = getDoubleClickScale(mode);
82
91
 
83
92
  const newScale = handleCalculateButtonZoom(contextInstance, delta, step);
84
93
 
@@ -210,6 +210,83 @@ export function calculateFitToView(
210
210
  return getCenterPosition(scale, wrapperComponent, contentComponent);
211
211
  }
212
212
 
213
+ // Share of the free space (wrapper minus scaled content) left before the
214
+ // content for each named initial position (#349).
215
+ const NAMED_POSITION_SHARE = {
216
+ left: 0,
217
+ top: 0,
218
+ center: 0.5,
219
+ right: 1,
220
+ bottom: 1,
221
+ } as const;
222
+
223
+ export function hasNamedInitialPosition(
224
+ contextInstance: ReactZoomPanPinchContext,
225
+ ): boolean {
226
+ const { initialPositionX, initialPositionY } = contextInstance.props;
227
+ return (
228
+ typeof initialPositionX === "string" || typeof initialPositionY === "string"
229
+ );
230
+ }
231
+
232
+ /**
233
+ * Replaces each axis of `target` whose `initialPositionX/Y` is named
234
+ * (`"right"`, `"center"`, `"top"`…) with the position that puts the content
235
+ * there at `target.scale`. Numeric axes are left as they are.
236
+ */
237
+ export function applyNamedInitialPosition(
238
+ contextInstance: ReactZoomPanPinchContext,
239
+ target: StateType,
240
+ ): StateType {
241
+ const { wrapperComponent, contentComponent, props } = contextInstance;
242
+ const { initialPositionX, initialPositionY } = props;
243
+ if (!wrapperComponent || !contentComponent) return target;
244
+
245
+ const place = (
246
+ name: keyof typeof NAMED_POSITION_SHARE,
247
+ wrapperSize: number,
248
+ contentSize: number,
249
+ ) => (wrapperSize - contentSize * target.scale) * NAMED_POSITION_SHARE[name];
250
+
251
+ return {
252
+ scale: target.scale,
253
+ positionX:
254
+ typeof initialPositionX === "string"
255
+ ? place(
256
+ initialPositionX,
257
+ wrapperComponent.clientWidth,
258
+ contentComponent.offsetWidth,
259
+ )
260
+ : target.positionX,
261
+ positionY:
262
+ typeof initialPositionY === "string"
263
+ ? place(
264
+ initialPositionY,
265
+ wrapperComponent.clientHeight,
266
+ contentComponent.offsetHeight,
267
+ )
268
+ : target.positionY,
269
+ };
270
+ }
271
+
272
+ /**
273
+ * The scale `resetTransform` returns to: the fitted one with `fitOnInit`,
274
+ * otherwise `initialScale` (clamped to min/max).
275
+ */
276
+ export function getResetScale(
277
+ contextInstance: ReactZoomPanPinchContext,
278
+ ): number {
279
+ const { fitOnInit } = contextInstance.setup;
280
+ if (fitOnInit) {
281
+ const fitted = calculateFitToView(
282
+ contextInstance,
283
+ fitOnInit === "cover" ? "cover" : "contain",
284
+ );
285
+ if (fitted) return fitted.scale;
286
+ }
287
+ return createState(contextInstance.props).scale;
288
+ }
289
+
213
290
  export function resetTransformations(
214
291
  contextInstance: ReactZoomPanPinchContext,
215
292
  animationTime: number,
@@ -226,11 +303,12 @@ export function resetTransformations(
226
303
  // With `fitOnInit` the initial layout is the fitted one, so that is what a
227
304
  // reset returns to (#252).
228
305
  if (fitOnInit) {
229
- const fitted = calculateFitToView(
306
+ const fit = calculateFitToView(
230
307
  contextInstance,
231
308
  fitOnInit === "cover" ? "cover" : "contain",
232
309
  );
233
- if (fitted) {
310
+ if (fit) {
311
+ const fitted = applyNamedInitialPosition(contextInstance, fit);
234
312
  if (
235
313
  scale === fitted.scale &&
236
314
  positionX === fitted.positionX &&
@@ -261,6 +339,15 @@ export function resetTransformations(
261
339
  targetPositionY = centered.positionY;
262
340
  }
263
341
 
342
+ // Named initial positions win over the centring on their own axis (#349).
343
+ const named = applyNamedInitialPosition(contextInstance, {
344
+ scale: initialTransformation.scale,
345
+ positionX: targetPositionX,
346
+ positionY: targetPositionY,
347
+ });
348
+ targetPositionX = named.positionX;
349
+ targetPositionY = named.positionY;
350
+
264
351
  const newBounds = calculateBounds(
265
352
  contextInstance,
266
353
  initialTransformation.scale,
@@ -8,6 +8,7 @@ import {
8
8
  ReactZoomPanPinchState,
9
9
  ReactZoomPanPinchRef,
10
10
  DeviceType,
11
+ StateType,
11
12
  } from "../models";
12
13
  import {
13
14
  getContext,
@@ -27,8 +28,16 @@ import {
27
28
  measureSizes,
28
29
  } from "./resize/resize.logic";
29
30
  import { MeasuredSizesType } from "./resize/resize.types";
30
- import { calculateFitToView } from "./handlers/handlers.utils";
31
- import { isWheelAllowed, isWheelPanningAllowed } from "./wheel/wheel.utils";
31
+ import {
32
+ applyNamedInitialPosition,
33
+ calculateFitToView,
34
+ hasNamedInitialPosition,
35
+ } from "./handlers/handlers.utils";
36
+ import {
37
+ getWheelPanDelta,
38
+ isWheelAllowed,
39
+ isWheelPanningAllowed,
40
+ } from "./wheel/wheel.utils";
32
41
  import { isPinchAllowed, isPinchStartAllowed } from "./pinch/pinch.utils";
33
42
  import { handleCalculateBounds } from "./bounds/bounds.utils";
34
43
  import {
@@ -39,9 +48,11 @@ import {
39
48
  handleWheelPanningStart,
40
49
  } from "./wheel/wheel.logic";
41
50
  import {
51
+ CLICK_DISTANCE,
42
52
  getPaddingValue,
43
53
  getPanSourcePosition,
44
54
  handleNewPosition,
55
+ isPanBlockedAtBounds,
45
56
  isPanningAllowed,
46
57
  isPanningStartAllowed,
47
58
  } from "./pan/panning.utils";
@@ -98,6 +109,15 @@ export class ZoomPanPinch {
98
109
  public isWheelPanning = false;
99
110
  public startCoords: StartCoordsType = null;
100
111
  public panStartPosition: { x: number; y: number } | null = null;
112
+ // Pointer travel of the running mouse/touch pan: whether it moved at all
113
+ // (the first move decides `releaseAtBounds`, #509) and whether it went
114
+ // past the click distance (the click after it is swallowed, #452).
115
+ public panGesture: {
116
+ startX: number;
117
+ startY: number;
118
+ hasMoved: boolean;
119
+ isDrag: boolean;
120
+ } | null = null;
101
121
  public lastTouch: number | null = null;
102
122
  // pinch helpers
103
123
  public isPinching = false;
@@ -276,6 +296,7 @@ export class ZoomPanPinch {
276
296
  );
277
297
  wrapper.removeEventListener("touchmove", this.onTouchPanning, passive);
278
298
  wrapper.removeEventListener("touchend", this.onTouchPanningStop, passive);
299
+ wrapper.removeEventListener("scroll", this.onWrapperScroll, passive);
279
300
  };
280
301
 
281
302
  handleInitializeWrapperEvents = (wrapper: HTMLDivElement): void => {
@@ -288,6 +309,25 @@ export class ZoomPanPinch {
288
309
  wrapper.addEventListener("touchstart", this.onTouchPanningStart, passive);
289
310
  wrapper.addEventListener("touchmove", this.onTouchPanning, passive);
290
311
  wrapper.addEventListener("touchend", this.onTouchPanningStop, passive);
312
+ wrapper.addEventListener("scroll", this.onWrapperScroll, passive);
313
+ };
314
+
315
+ // The wrapper clips with `overflow: hidden`, but the browser still scrolls
316
+ // it to reveal a focused input (the virtual keyboard on mobile) or for
317
+ // `scrollIntoView`. Nothing in the transform knows about that offset, so
318
+ // the content stayed shifted and could not be panned back (#280, #477).
319
+ // Fold the scroll into the position instead: the target stays in view and
320
+ // the state matches what is on screen.
321
+ onWrapperScroll = (): void => {
322
+ const wrapper = this.wrapperComponent;
323
+ if (!wrapper) return;
324
+ const { scrollLeft, scrollTop } = wrapper;
325
+ if (!scrollLeft && !scrollTop) return;
326
+
327
+ wrapper.scrollLeft = 0;
328
+ wrapper.scrollTop = 0;
329
+ const { scale, positionX, positionY } = this.state;
330
+ this.setState(scale, positionX - scrollLeft, positionY - scrollTop);
291
331
  };
292
332
 
293
333
  handleInitialize = (): void => {
@@ -295,7 +335,7 @@ export class ZoomPanPinch {
295
335
  this.applyTransformation();
296
336
  this.onInitCallbacks.forEach((callback) => callback(getContext(this)));
297
337
 
298
- if (centerOnInit || fitOnInit) {
338
+ if (centerOnInit || fitOnInit || hasNamedInitialPosition(this)) {
299
339
  const applied = this.applyInitialLayout();
300
340
  // Content without a size yet (an image still loading) gets its layout
301
341
  // applied again by `onSizeChange` once it has one. Once a real layout
@@ -399,21 +439,23 @@ export class ZoomPanPinch {
399
439
  onWheelPanning = (event: WheelEvent): void => {
400
440
  const { onPanning } = this.props;
401
441
  const { trackPadPanning } = this.setup;
402
- const { lockAxisX, lockAxisY } = trackPadPanning;
442
+ const { lockAxisX, lockAxisY, speed } = trackPadPanning;
443
+ const wrapper = this.wrapperComponent;
403
444
 
404
445
  this.syncModifierKeys(event);
405
446
 
406
447
  const isAllowed = isWheelPanningAllowed(this, event);
407
448
 
408
- if (!isAllowed) return;
449
+ if (!isAllowed || !wrapper) return;
409
450
 
410
451
  if (event.cancelable) {
411
452
  event.preventDefault();
412
453
  }
413
454
  event.stopPropagation();
414
455
 
415
- const deltaX = lockAxisX ? 0 : event.deltaX;
416
- const deltaY = lockAxisY ? 0 : event.deltaY;
456
+ const delta = getWheelPanDelta(event, wrapper, speed);
457
+ const deltaX = lockAxisX ? 0 : delta.x;
458
+ const deltaY = lockAxisY ? 0 : delta.y;
417
459
 
418
460
  if (!deltaX && !deltaY) return;
419
461
 
@@ -470,6 +512,7 @@ export class ZoomPanPinch {
470
512
 
471
513
  handleCancelAnimation(this);
472
514
  handlePanningStart(this, event);
515
+ this.startPanGesture(event.clientX, event.clientY);
473
516
  this.lockTextSelection();
474
517
  this.focusForKeyboard();
475
518
  handleCallback(getContext(this), event, onPanningStart);
@@ -496,6 +539,11 @@ export class ZoomPanPinch {
496
539
  const keysPressed = this.isPressingKeys(this.setup.panning.activationKeys);
497
540
  if (!keysPressed) return;
498
541
 
542
+ if (this.trackPanGesture(event.clientX, event.clientY)) {
543
+ this.onPanningStop(event);
544
+ return;
545
+ }
546
+
499
547
  if (event.cancelable) {
500
548
  event.preventDefault();
501
549
  }
@@ -506,17 +554,80 @@ export class ZoomPanPinch {
506
554
  };
507
555
 
508
556
  onPanningStop = (event: MouseEvent | TouchEvent): void => {
509
- const { velocityDisabled } = this.setup.panning;
557
+ const { velocityDisabled, suppressClickAfterPan } = this.setup.panning;
510
558
  const { onPanningStop } = this.props;
511
559
 
512
560
  if (this.isPanning) {
561
+ const isDrag = !!this.panGesture?.isDrag;
562
+ this.panGesture = null;
513
563
  this.unlockTextSelection();
514
564
  handlePanningEnd(this, velocityDisabled);
515
565
  handleCallback(getContext(this), event, onPanningStop);
516
566
  this.flushResizeAlignment();
567
+ // Only a mouseup is followed by a click on the content; a released or
568
+ // cancelled gesture (mousemove, mouseleave, touch) is not.
569
+ if (isDrag && suppressClickAfterPan && event.type === "mouseup") {
570
+ this.suppressNextClick();
571
+ }
517
572
  }
518
573
  };
519
574
 
575
+ startPanGesture = (clientX: number, clientY: number): void => {
576
+ this.panGesture = {
577
+ startX: clientX,
578
+ startY: clientY,
579
+ hasMoved: false,
580
+ isDrag: false,
581
+ };
582
+ };
583
+
584
+ // Records the pointer travel of the running pan. Returns true when this is
585
+ // the first move, it heads into a bound the content already rests on and
586
+ // `releaseAtBounds` is on: the caller then ends the pan without claiming
587
+ // the event, so the page scrolls or a parent takes the drag (#509).
588
+ trackPanGesture = (clientX: number, clientY: number): boolean => {
589
+ const gesture = this.panGesture;
590
+ if (!gesture) return false;
591
+
592
+ const dx = clientX - gesture.startX;
593
+ const dy = clientY - gesture.startY;
594
+ if (!dx && !dy) return false;
595
+
596
+ const isFirstMove = !gesture.hasMoved;
597
+ gesture.hasMoved = true;
598
+ if (dx * dx + dy * dy > CLICK_DISTANCE ** 2) gesture.isDrag = true;
599
+
600
+ return (
601
+ isFirstMove &&
602
+ this.setup.panning.releaseAtBounds &&
603
+ isPanBlockedAtBounds(this, dx, dy)
604
+ );
605
+ };
606
+
607
+ // The browser fires `click` right after `mouseup`, in the same task, so a
608
+ // capture listener on the window that removes itself on the next tick
609
+ // swallows exactly that click and nothing later (#452).
610
+ suppressNextClick = (): void => {
611
+ const wrapper = this.wrapperComponent;
612
+ const win = wrapper?.ownerDocument?.defaultView;
613
+ if (!wrapper || !win) return;
614
+
615
+ const swallow = (event: MouseEvent) => {
616
+ const path =
617
+ typeof event.composedPath === "function" ? event.composedPath() : [];
618
+ const isInside =
619
+ path.includes(wrapper) || wrapper.contains(event.target as Node);
620
+ if (!isInside) return;
621
+ event.preventDefault();
622
+ event.stopPropagation();
623
+ };
624
+
625
+ win.addEventListener("click", swallow, { capture: true, once: true });
626
+ win.setTimeout(() => {
627
+ win.removeEventListener("click", swallow, { capture: true });
628
+ }, 0);
629
+ };
630
+
520
631
  /// ///////
521
632
  // Pinch
522
633
  /// ///////
@@ -596,6 +707,7 @@ export class ZoomPanPinch {
596
707
  if (!isAllowed || this.setup.panning.disabled) return;
597
708
  handleCancelAnimation(this);
598
709
  handlePanningStart(this, event);
710
+ this.startPanGesture(touches[0].clientX, touches[0].clientY);
599
711
  this.lockTextSelection();
600
712
  this.focusForKeyboard();
601
713
  handleCallback(getContext(this), event, onPanningStart);
@@ -616,12 +728,18 @@ export class ZoomPanPinch {
616
728
  const isAllowed = isPanningAllowed(this);
617
729
  if (!isAllowed) return;
618
730
 
731
+ const touch = event.touches[0];
732
+ // Not cancelling the first touchmove is what lets the browser scroll.
733
+ if (this.trackPanGesture(touch.clientX, touch.clientY)) {
734
+ this.onPanningStop(event);
735
+ return;
736
+ }
737
+
619
738
  if (event.cancelable) {
620
739
  event.preventDefault();
621
740
  }
622
741
  event.stopPropagation();
623
742
 
624
- const touch = event.touches[0];
625
743
  handlePanning(this, touch.clientX, touch.clientY, DeviceType.TOUCH);
626
744
  handleCallback(getContext(this), event, onPanning);
627
745
  } else if (event.touches.length > 1) {
@@ -666,6 +784,7 @@ export class ZoomPanPinch {
666
784
  if (this.isPanning) {
667
785
  this.isPanning = false;
668
786
  this.startCoords = null;
787
+ this.panGesture = null;
669
788
  }
670
789
  this.unlockTextSelection();
671
790
  this.flushResizeAlignment();
@@ -775,28 +894,31 @@ export class ZoomPanPinch {
775
894
 
776
895
  // `fitOnInit` wins over `centerOnInit` (a fit is always centred). Falls
777
896
  // back to centring while the content has no size yet; `onSizeChange`
778
- // re-runs this once it does. Returns whether both boxes had a size, i.e.
779
- // whether this was a real initial layout.
897
+ // re-runs this once it does. A named `initialPositionX/Y` then places its
898
+ // own axis (#349). Returns whether both boxes had a size, i.e. whether
899
+ // this was a real initial layout.
780
900
  applyInitialLayout = (): boolean => {
781
- const { fitOnInit } = this.setup;
901
+ const { fitOnInit, centerOnInit } = this.setup;
782
902
  const { wrapperComponent, contentComponent } = this;
903
+ if (!wrapperComponent || !contentComponent) return false;
783
904
  const hasSizes =
784
- !!wrapperComponent &&
785
- !!contentComponent &&
786
905
  wrapperComponent.clientWidth > 0 &&
787
906
  wrapperComponent.clientHeight > 0 &&
788
907
  (contentComponent.offsetWidth > 0 || contentComponent.offsetHeight > 0);
789
- if (fitOnInit) {
790
- const fitted = calculateFitToView(
791
- this,
792
- fitOnInit === "cover" ? "cover" : "contain",
793
- );
794
- if (fitted) {
795
- this.setState(fitted.scale, fitted.positionX, fitted.positionY);
796
- return hasSizes;
797
- }
908
+
909
+ const { scale, positionX, positionY } = this.state;
910
+ let target: StateType = { scale, positionX, positionY };
911
+ const fitted = fitOnInit
912
+ ? calculateFitToView(this, fitOnInit === "cover" ? "cover" : "contain")
913
+ : null;
914
+ if (fitted) {
915
+ target = fitted;
916
+ } else if (fitOnInit || centerOnInit) {
917
+ target = getCenterPosition(scale, wrapperComponent, contentComponent);
798
918
  }
799
- this.setCenter();
919
+
920
+ const placed = applyNamedInitialPosition(this, target);
921
+ this.setState(placed.scale, placed.positionX, placed.positionY);
800
922
  return hasSizes;
801
923
  };
802
924
 
@@ -4,6 +4,7 @@ import { ReactZoomPanPinchContext } from "../../models/context.model";
4
4
  import { animate, handleCancelAnimation } from "../animations/animations.utils";
5
5
  import { handleCalculateBounds } from "../bounds/bounds.utils";
6
6
  import {
7
+ CLICK_DISTANCE,
7
8
  getPaddingValue,
8
9
  getPanningClientPosition,
9
10
  handleNewPosition,
@@ -112,7 +113,7 @@ export function handlePanningEnd(
112
113
  // A click is not a fling, but it can still land on content left past
113
114
  // the bounds — e.g. grabbed mid return animation, which the press
114
115
  // cancelled. Finish the return (a no-op inside the bounds).
115
- if (dx * dx + dy * dy <= 25) {
116
+ if (dx * dx + dy * dy <= CLICK_DISTANCE ** 2) {
116
117
  handleAlignToBounds(contextInstance);
117
118
  return;
118
119
  }
@@ -69,6 +69,41 @@ export const isPanningAllowed = (
69
69
  return true;
70
70
  };
71
71
 
72
+ /**
73
+ * Pointer travel in px up to which a press still counts as a click, not a
74
+ * drag: a pan ending within it aligns instead of flinging, and only a pan
75
+ * beyond it swallows the click that follows (#452).
76
+ */
77
+ export const CLICK_DISTANCE = 5;
78
+
79
+ /**
80
+ * Whether a pan moving by (`dx`, `dy`) would push the content further into a
81
+ * bound it already rests on, judged on the dominant axis. With
82
+ * `panning.releaseAtBounds` such a gesture is handed back to the page or the
83
+ * parent (a carousel, page scroll) instead of being claimed (#509).
84
+ */
85
+ export function isPanBlockedAtBounds(
86
+ contextInstance: ReactZoomPanPinchContext,
87
+ dx: number,
88
+ dy: number,
89
+ ): boolean {
90
+ const { bounds, setup, state } = contextInstance;
91
+ if (!bounds || !setup.limitToBounds || (!dx && !dy)) return false;
92
+
93
+ const isHorizontal = Math.abs(dx) >= Math.abs(dy);
94
+ if (isHorizontal ? setup.panning.lockAxisX : setup.panning.lockAxisY) {
95
+ return true;
96
+ }
97
+
98
+ const delta = isHorizontal ? dx : dy;
99
+ const position = isHorizontal ? state.positionX : state.positionY;
100
+ const min = isHorizontal ? bounds.minPositionX : bounds.minPositionY;
101
+ const max = isHorizontal ? bounds.maxPositionX : bounds.maxPositionY;
102
+ // Moving the pointer right/down moves the content towards its max bound.
103
+ // Half a pixel of slack: alignment animations settle on float values.
104
+ return delta > 0 ? position >= max - 0.5 : position <= min + 0.5;
105
+ }
106
+
72
107
  export const getPaddingValue = (
73
108
  contextInstance: ReactZoomPanPinchContext,
74
109
  size: number,