react-zoom-pan-pinch 4.0.6 → 4.1.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.
@@ -1,4 +1,9 @@
1
- import { ReactZoomPanPinchContext, ReactZoomPanPinchState } from "../../models";
1
+ import {
2
+ PositionType,
3
+ ReactZoomPanPinchContext,
4
+ ReactZoomPanPinchState,
5
+ StateType,
6
+ } from "../../models";
2
7
  import { animations } from "../animations/animations.constants";
3
8
  import { handleZoomToPoint } from "../zoom/zoom.logic";
4
9
  import { animate } from "../animations/animations.utils";
@@ -15,6 +20,13 @@ import {
15
20
  getMouseBoundedPosition,
16
21
  } from "../bounds/bounds.utils";
17
22
 
23
+ export type RectLike = {
24
+ x: number;
25
+ y: number;
26
+ width: number;
27
+ height: number;
28
+ };
29
+
18
30
  export const handleCalculateButtonZoom = (
19
31
  contextInstance: ReactZoomPanPinchContext,
20
32
  delta: number,
@@ -22,16 +34,17 @@ export const handleCalculateButtonZoom = (
22
34
  ): number => {
23
35
  const { scale } = contextInstance.state;
24
36
  const { wrapperComponent, setup } = contextInstance;
25
- const { maxScale, minScale, zoomAnimation, smooth } = setup;
37
+ const { maxScale, minScale, zoomAnimation } = setup;
26
38
  const { size } = zoomAnimation;
27
39
 
28
40
  if (!wrapperComponent) {
29
41
  throw new Error("Wrapper is not mounted");
30
42
  }
31
43
 
32
- const targetScale = smooth
33
- ? scale * Math.exp(delta * step)
34
- : scale + delta * step;
44
+ // `step` is an absolute scale increment for zoomIn/zoomOut and double
45
+ // click: zoomIn(0.25) from 1 lands on 1.25. The `smooth` option only
46
+ // shapes wheel/trackpad deltas (#545, #431).
47
+ const targetScale = scale + delta * step;
35
48
 
36
49
  const newScale = checkZoomBounds(
37
50
  roundNumber(targetScale, 3),
@@ -43,18 +56,56 @@ export const handleCalculateButtonZoom = (
43
56
  return newScale;
44
57
  };
45
58
 
59
+ /**
60
+ * Runs a programmatic zoom: fires `onZoomStart`/`onZoom`, animates to
61
+ * `targetState` and fires `onZoomStop` once the animation time has elapsed.
62
+ * Resolves when the animation has finished (or was interrupted).
63
+ */
64
+ export function runZoomAnimation(
65
+ contextInstance: ReactZoomPanPinchContext,
66
+ targetState: StateType,
67
+ animationTime: number,
68
+ animationType: keyof typeof animations,
69
+ ): Promise<void> {
70
+ const { wrapperComponent } = contextInstance;
71
+ const { onZoomStart, onZoom, onZoomStop } = contextInstance.props;
72
+ const event = new MouseEvent("mousemove", { bubbles: true });
73
+ const ctx = getContext(contextInstance);
74
+ handleCallback(ctx, event, onZoomStart);
75
+ handleCallback(ctx, event, onZoom);
76
+ const done = animate(
77
+ contextInstance,
78
+ targetState,
79
+ animationTime,
80
+ animationType,
81
+ );
82
+ const win =
83
+ wrapperComponent?.ownerDocument?.defaultView ??
84
+ (typeof window !== "undefined" ? window : null);
85
+ if (win) {
86
+ win.setTimeout(() => {
87
+ if (!contextInstance.mounted) return;
88
+ handleCallback(getContext(contextInstance), event, onZoomStop);
89
+ }, animationTime);
90
+ }
91
+ return done;
92
+ }
93
+
46
94
  export function handleZoomToViewCenter(
47
95
  contextInstance: ReactZoomPanPinchContext,
48
96
  delta: number,
49
97
  step: number,
50
98
  animationTime: number,
51
99
  animationType: keyof typeof animations,
52
- ): void {
100
+ ): Promise<void> {
53
101
  const { wrapperComponent } = contextInstance;
54
102
  const { scale, positionX, positionY } = contextInstance.state;
55
103
  const { zoomAnimation } = contextInstance.setup;
56
104
 
57
- if (!wrapperComponent) return console.error("No WrapperComponent found");
105
+ if (!wrapperComponent) {
106
+ console.error("No WrapperComponent found");
107
+ return Promise.resolve();
108
+ }
58
109
 
59
110
  const effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
60
111
 
@@ -73,26 +124,18 @@ export function handleZoomToViewCenter(
73
124
  );
74
125
 
75
126
  if (!targetState) {
76
- return console.error(
127
+ console.error(
77
128
  "Error during zoom event. New transformation state was not calculated.",
78
129
  );
130
+ return Promise.resolve();
79
131
  }
80
132
 
81
- const { onZoomStart, onZoom, onZoomStop } = contextInstance.props;
82
- const event = new MouseEvent("mousemove", { bubbles: true });
83
- const ctx = getContext(contextInstance);
84
- handleCallback(ctx, event, onZoomStart);
85
- handleCallback(ctx, event, onZoom);
86
- animate(contextInstance, targetState, effectiveAnimationTime, animationType);
87
- const win =
88
- wrapperComponent.ownerDocument?.defaultView ??
89
- (typeof window !== "undefined" ? window : null);
90
- if (win) {
91
- win.setTimeout(() => {
92
- if (!contextInstance.mounted) return;
93
- handleCallback(getContext(contextInstance), event, onZoomStop);
94
- }, effectiveAnimationTime);
95
- }
133
+ return runZoomAnimation(
134
+ contextInstance,
135
+ targetState,
136
+ effectiveAnimationTime,
137
+ animationType,
138
+ );
96
139
  }
97
140
 
98
141
  export function resetTransformations(
@@ -100,13 +143,13 @@ export function resetTransformations(
100
143
  animationTime: number,
101
144
  animationType: keyof typeof animations,
102
145
  onResetTransformation?: () => void,
103
- ): void {
146
+ ): Promise<void> {
104
147
  const { setup, wrapperComponent, contentComponent } = contextInstance;
105
148
  const { limitToBounds, centerOnInit } = setup;
106
149
  const initialTransformation = createState(contextInstance.props);
107
150
  const { scale, positionX, positionY } = contextInstance.state;
108
151
 
109
- if (!wrapperComponent) return;
152
+ if (!wrapperComponent) return Promise.resolve();
110
153
 
111
154
  let targetPositionX = initialTransformation.positionX;
112
155
  let targetPositionY = initialTransformation.positionY;
@@ -147,35 +190,51 @@ export function resetTransformations(
147
190
  positionX === initialTransformation.positionX &&
148
191
  positionY === initialTransformation.positionY
149
192
  ) {
150
- return;
193
+ return Promise.resolve();
151
194
  }
152
195
 
153
196
  onResetTransformation?.();
154
197
 
155
- const { onZoomStart, onZoom, onZoomStop } = contextInstance.props;
156
- const event = new MouseEvent("mousemove", { bubbles: true });
157
- const ctx = getContext(contextInstance);
158
- handleCallback(ctx, event, onZoomStart);
159
- handleCallback(ctx, event, onZoom);
160
- animate(contextInstance, newState, animationTime, animationType);
161
- const win =
162
- wrapperComponent.ownerDocument?.defaultView ??
163
- (typeof window !== "undefined" ? window : null);
164
- if (win) {
165
- win.setTimeout(() => {
166
- if (!contextInstance.mounted) return;
167
- handleCallback(getContext(contextInstance), event, onZoomStop);
168
- }, animationTime);
198
+ return runZoomAnimation(
199
+ contextInstance,
200
+ newState,
201
+ animationTime,
202
+ animationType,
203
+ );
204
+ }
205
+
206
+ const toRect = (target: HTMLElement | RectLike): RectLike => {
207
+ if ("getBoundingClientRect" in target) {
208
+ const rect = target.getBoundingClientRect();
209
+ return {
210
+ x: rect.left,
211
+ y: rect.top,
212
+ width: rect.width,
213
+ height: rect.height,
214
+ };
169
215
  }
216
+ return target;
217
+ };
218
+
219
+ /**
220
+ * Smallest client rect containing every node (#388).
221
+ */
222
+ export function getUnionRect(nodes: HTMLElement[]): RectLike {
223
+ const rects = nodes.map(toRect);
224
+ const left = Math.min(...rects.map((r) => r.x));
225
+ const top = Math.min(...rects.map((r) => r.y));
226
+ const right = Math.max(...rects.map((r) => r.x + r.width));
227
+ const bottom = Math.max(...rects.map((r) => r.y + r.height));
228
+ return { x: left, y: top, width: right - left, height: bottom - top };
170
229
  }
171
230
 
172
231
  export function getOffset(
173
- element: HTMLElement,
232
+ element: HTMLElement | RectLike,
174
233
  wrapper: HTMLElement,
175
234
  content: HTMLElement,
176
235
  state: ReactZoomPanPinchState,
177
236
  ) {
178
- const offset = element.getBoundingClientRect();
237
+ const offset = toRect(element);
179
238
  const wrapperOffset = wrapper.getBoundingClientRect();
180
239
  const contentOffset = content.getBoundingClientRect();
181
240
 
@@ -188,36 +247,46 @@ export function getOffset(
188
247
  };
189
248
  }
190
249
 
191
- export function calculateZoomToNode(
250
+ /**
251
+ * Transform that frames the client-space `rect` in the viewport.
252
+ *
253
+ * `customZoom` forces the scale; otherwise the rect is fitted and the fit
254
+ * scale is capped by `minFitScale`/`maxFitScale` (#515) before the wrapper's
255
+ * own `minScale`/`maxScale` apply.
256
+ */
257
+ export function calculateZoomToRect(
192
258
  contextInstance: ReactZoomPanPinchContext,
193
- node: HTMLElement,
259
+ rect: RectLike,
194
260
  customZoom?: number,
195
261
  customOffsetX = 0,
196
262
  customOffsetY = 0,
263
+ minFitScale?: number,
264
+ maxFitScale?: number,
197
265
  ): { positionX: number; positionY: number; scale: number } {
198
266
  const { wrapperComponent, contentComponent, state } = contextInstance;
199
267
  const { limitToBounds, minScale, maxScale } = contextInstance.setup;
200
268
  if (!wrapperComponent || !contentComponent) return state;
201
269
 
202
270
  const wrapperRect = wrapperComponent.getBoundingClientRect();
203
- const nodeRect = node.getBoundingClientRect();
204
- const nodeOffset = getOffset(node, wrapperComponent, contentComponent, state);
271
+ const nodeOffset = getOffset(rect, wrapperComponent, contentComponent, state);
205
272
 
206
273
  const nodeLeft = nodeOffset.x;
207
274
  const nodeTop = nodeOffset.y;
208
- const nodeWidth = nodeRect.width / state.scale;
209
- const nodeHeight = nodeRect.height / state.scale;
275
+ const nodeWidth = rect.width / state.scale;
276
+ const nodeHeight = rect.height / state.scale;
210
277
 
211
278
  const scaleX = wrapperComponent.offsetWidth / nodeWidth;
212
279
  const scaleY = wrapperComponent.offsetHeight / nodeHeight;
213
280
 
214
- const newScale = checkZoomBounds(
215
- customZoom || Math.min(scaleX, scaleY),
216
- minScale,
217
- maxScale,
218
- 0,
219
- false,
220
- );
281
+ let targetScale = customZoom || Math.min(scaleX, scaleY);
282
+ if (maxFitScale !== undefined) {
283
+ targetScale = Math.min(targetScale, maxFitScale);
284
+ }
285
+ if (minFitScale !== undefined) {
286
+ targetScale = Math.max(targetScale, minFitScale);
287
+ }
288
+
289
+ const newScale = checkZoomBounds(targetScale, minScale, maxScale, 0, false);
221
290
 
222
291
  const offsetX = (wrapperRect.width - nodeWidth * newScale) / 2;
223
292
  const offsetY = (wrapperRect.height - nodeHeight * newScale) / 2;
@@ -241,3 +310,61 @@ export function calculateZoomToNode(
241
310
 
242
311
  return { positionX: x, positionY: y, scale: newScale };
243
312
  }
313
+
314
+ export function calculateZoomToNode(
315
+ contextInstance: ReactZoomPanPinchContext,
316
+ node: HTMLElement,
317
+ customZoom?: number,
318
+ customOffsetX = 0,
319
+ customOffsetY = 0,
320
+ minFitScale?: number,
321
+ maxFitScale?: number,
322
+ ): { positionX: number; positionY: number; scale: number } {
323
+ return calculateZoomToRect(
324
+ contextInstance,
325
+ toRect(node),
326
+ customZoom,
327
+ customOffsetX,
328
+ customOffsetY,
329
+ minFitScale,
330
+ maxFitScale,
331
+ );
332
+ }
333
+
334
+ /**
335
+ * Client (viewport) coordinates → unscaled content coordinates (#378).
336
+ * Returns `{ x: 0, y: 0 }` before the wrapper is mounted.
337
+ */
338
+ export function clientToContentPoint(
339
+ contextInstance: ReactZoomPanPinchContext,
340
+ clientX: number,
341
+ clientY: number,
342
+ ): PositionType {
343
+ const { wrapperComponent, state } = contextInstance;
344
+ if (!wrapperComponent) return { x: 0, y: 0 };
345
+
346
+ const rect = wrapperComponent.getBoundingClientRect();
347
+ return {
348
+ x: (clientX - rect.left - state.positionX) / state.scale,
349
+ y: (clientY - rect.top - state.positionY) / state.scale,
350
+ };
351
+ }
352
+
353
+ /**
354
+ * Unscaled content coordinates → client (viewport) coordinates.
355
+ * Returns `{ x: 0, y: 0 }` before the wrapper is mounted.
356
+ */
357
+ export function contentToClientPoint(
358
+ contextInstance: ReactZoomPanPinchContext,
359
+ x: number,
360
+ y: number,
361
+ ): PositionType {
362
+ const { wrapperComponent, state } = contextInstance;
363
+ if (!wrapperComponent) return { x: 0, y: 0 };
364
+
365
+ const rect = wrapperComponent.getBoundingClientRect();
366
+ return {
367
+ x: rect.left + state.positionX + x * state.scale,
368
+ y: rect.top + state.positionY + y * state.scale,
369
+ };
370
+ }
@@ -107,6 +107,11 @@ export class ZoomPanPinch {
107
107
  // animations helpers
108
108
  public isAnimating = false;
109
109
  public animation: AnimationType | null = null;
110
+ public animationFrame: number | null = null;
111
+ // Settles the promise returned by the running programmatic animation.
112
+ public animationResolve: (() => void) | null = null;
113
+ // init helpers
114
+ public initObserverTimer: ReturnType<typeof setTimeout> | null = null;
110
115
  // key press
111
116
  public pressedKeys: { [key: string]: boolean } = {};
112
117
 
@@ -117,19 +122,38 @@ export class ZoomPanPinch {
117
122
  }
118
123
 
119
124
  mount = () => {
125
+ this.mounted = true;
120
126
  this.initializeWindowEvents();
121
127
  };
122
128
 
129
+ // Marks the instance as gone so pending timers, animation frames and
130
+ // callbacks scheduled before unmount become no-ops.
123
131
  unmount = () => {
132
+ this.mounted = false;
124
133
  this.cleanupWindowEvents();
125
134
  };
126
135
 
127
136
  update = (newProps: ReactZoomPanPinchProps) => {
128
137
  this.props = newProps;
138
+ // Setup first: bounds depend on the new props (min/max positions,
139
+ // centerZoomedOut, disablePadding).
140
+ this.setup = createSetup(newProps);
129
141
  if (this.wrapperComponent && this.contentComponent) {
130
142
  handleCalculateBounds(this, this.state.scale);
131
143
  }
132
- this.setup = createSetup(newProps);
144
+ };
145
+
146
+ clearTimers = (): void => {
147
+ if (this.wheelStopEventTimer) clearTimeout(this.wheelStopEventTimer);
148
+ if (this.wheelAnimationTimer) clearTimeout(this.wheelAnimationTimer);
149
+ if (this.doubleClickStopEventTimer) {
150
+ clearTimeout(this.doubleClickStopEventTimer);
151
+ }
152
+ if (this.initObserverTimer) clearTimeout(this.initObserverTimer);
153
+ this.wheelStopEventTimer = null;
154
+ this.wheelAnimationTimer = null;
155
+ this.doubleClickStopEventTimer = null;
156
+ this.initObserverTimer = null;
133
157
  };
134
158
 
135
159
  initializeWindowEvents = (): void => {
@@ -180,7 +204,6 @@ export class ZoomPanPinch {
180
204
  currentWindow?.removeEventListener("keyup", this.setKeyUnPressed, passive);
181
205
  currentWindow?.removeEventListener("keydown", this.setKeyPressed, passive);
182
206
  currentWindow?.removeEventListener("blur", this.handleWindowBlur);
183
- document.removeEventListener("mouseleave", this.clearPanning, passive);
184
207
  this.wrapperComponent?.removeEventListener(
185
208
  "wheel",
186
209
  this.onWheelPanning,
@@ -196,10 +219,28 @@ export class ZoomPanPinch {
196
219
  this.setKeyPressed,
197
220
  passive,
198
221
  );
222
+ this.cleanupWrapperEvents();
223
+ this.clearTimers();
199
224
  handleCancelAnimation(this);
200
225
  this.observer?.disconnect();
201
226
  };
202
227
 
228
+ cleanupWrapperEvents = (): void => {
229
+ const wrapper = this.wrapperComponent;
230
+ if (!wrapper) return;
231
+ const passive = makePassiveEventOption();
232
+
233
+ wrapper.removeEventListener("wheel", this.onWheelZoom, passive);
234
+ wrapper.removeEventListener("dblclick", this.onDoubleClick, passive);
235
+ wrapper.removeEventListener(
236
+ "touchstart",
237
+ this.onTouchPanningStart,
238
+ passive,
239
+ );
240
+ wrapper.removeEventListener("touchmove", this.onTouchPanning, passive);
241
+ wrapper.removeEventListener("touchend", this.onTouchPanningStop, passive);
242
+ };
243
+
203
244
  handleInitializeWrapperEvents = (wrapper: HTMLDivElement): void => {
204
245
  // Zooming events on wrapper
205
246
  const passive = makePassiveEventOption();
@@ -218,6 +259,7 @@ export class ZoomPanPinch {
218
259
 
219
260
  if (centerOnInit) {
220
261
  this.setCenter();
262
+ this.observer?.disconnect();
221
263
  this.observer = new ResizeObserver(() => {
222
264
  const currentWidth = contentComponent.offsetWidth;
223
265
  const currentHeight = contentComponent.offsetHeight;
@@ -234,7 +276,9 @@ export class ZoomPanPinch {
234
276
 
235
277
  // TODO: CHANGE to first interaction?
236
278
  // if nothing about the contentComponent has changed after 5 seconds, disconnect the observer
237
- setTimeout(() => {
279
+ if (this.initObserverTimer) clearTimeout(this.initObserverTimer);
280
+ this.initObserverTimer = setTimeout(() => {
281
+ this.initObserverTimer = null;
238
282
  this.observer?.disconnect();
239
283
  }, 5000);
240
284
 
@@ -435,6 +479,9 @@ export class ZoomPanPinch {
435
479
  const isDoubleTap = this.lastTouch && +new Date() - this.lastTouch < 200;
436
480
 
437
481
  if (isDoubleTapAllowed && isDoubleTap && event.touches.length === 1) {
482
+ // Consume the pair so a third quick tap starts a fresh sequence
483
+ // instead of counting as another double tap.
484
+ this.lastTouch = null;
438
485
  this.onDoubleClick(event);
439
486
  } else {
440
487
  this.lastTouch = +new Date();
@@ -697,6 +744,7 @@ export class ZoomPanPinch {
697
744
  wrapperComponent: HTMLDivElement,
698
745
  contentComponent: HTMLDivElement,
699
746
  ): void => {
747
+ this.mounted = true;
700
748
  this.cleanupWindowEvents();
701
749
  this.wrapperComponent = wrapperComponent;
702
750
  this.contentComponent = contentComponent;
@@ -47,7 +47,16 @@ export function handleAlignToBounds(
47
47
 
48
48
  const targetState = handlePanToBounds(contextInstance);
49
49
 
50
- if (targetState) {
50
+ if (!targetState) return;
51
+
52
+ // Nothing to align: starting a 200 ms animation towards the current state
53
+ // would only pin the transform and swallow input that arrives meanwhile
54
+ // (#582).
55
+ const { positionX, positionY } = contextInstance.state;
56
+ const isNoop =
57
+ targetState.positionX === positionX && targetState.positionY === positionY;
58
+
59
+ if (!isNoop) {
51
60
  animate(
52
61
  contextInstance,
53
62
  targetState,
@@ -4,7 +4,11 @@ import {
4
4
  ReactZoomPanPinchContext,
5
5
  ReactZoomPanPinchState,
6
6
  } from "../../models";
7
- import { isExcludedNode } from "../../utils";
7
+ import {
8
+ isDraggableTarget,
9
+ isEditableTarget,
10
+ isExcludedNode,
11
+ } from "../../utils";
8
12
  import { getMouseBoundedPosition } from "../bounds/bounds.utils";
9
13
  import { handleCalculateZoomPositions } from "../zoom/zoom.utils";
10
14
 
@@ -35,11 +39,7 @@ export const isPanningStartAllowed = (
35
39
 
36
40
  if (isExcluded) return false;
37
41
 
38
- if (
39
- target.getAttribute("draggable") === "true" ||
40
- target.getAttribute("contenteditable") === "true" ||
41
- target.isContentEditable
42
- ) {
42
+ if (isDraggableTarget(target) || isEditableTarget(target)) {
43
43
  return false;
44
44
  }
45
45
 
@@ -23,8 +23,14 @@ export const handleWheelStart = (
23
23
  ): void => {
24
24
  const { onWheelStart, onZoomStart } = contextInstance.props;
25
25
 
26
+ // Every wheel event must stop a running animation, not only the first one
27
+ // of a gesture. The alignment animation scheduled by `handleWheelStop`
28
+ // starts after `wheelAnimationTime` (100 ms) while `wheelStopEventTimer`
29
+ // (160 ms) is still pending; guarding the cancel on the stop timer let that
30
+ // animation overwrite the zoom of any wheel event arriving in between (#582).
31
+ handleCancelAnimation(contextInstance);
32
+
26
33
  if (!contextInstance.wheelStopEventTimer) {
27
- handleCancelAnimation(contextInstance);
28
34
  handleCallback(getContext(contextInstance), event, onWheelStart);
29
35
  handleCallback(getContext(contextInstance), event, onZoomStart);
30
36
  }
@@ -128,8 +134,13 @@ export const handleWheelPanningStart = (
128
134
  ): void => {
129
135
  const { onWheelStart, onPanningStart } = contextInstance.props;
130
136
 
137
+ // See `handleWheelStart` (#582): cancel on every event, not only the first.
138
+ handleCancelAnimation(contextInstance);
139
+
131
140
  if (!contextInstance.wheelStopEventTimer) {
132
- handleCancelAnimation(contextInstance);
141
+ // 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);
133
144
  handleCallback(getContext(contextInstance), event, onWheelStart);
134
145
  handleCallback(getContext(contextInstance), event, onPanningStart);
135
146
  }
@@ -14,6 +14,10 @@ export const isWheelAllowed = (
14
14
  const isAllowed = isInitialized && !isPanning && !disabled && target;
15
15
 
16
16
  if (!isAllowed) return false;
17
+ // A purely horizontal wheel/swipe (Magic Mouse, trackpad) carries no zoom
18
+ // intent. Treating its deltaY of 0 as "zoom out" was #168; leaving it
19
+ // unclaimed also lets trackpad panning pick it up.
20
+ if (event.deltaY === 0) return false;
17
21
  // Event ctrlKey detects if touchpad action is executing wheel or pinch gesture
18
22
  if (wheelDisabled && !event.ctrlKey) return false;
19
23
  if (touchPadDisabled && event.ctrlKey) return false;
@@ -3,3 +3,4 @@ export * from "./use-transform-init";
3
3
  export * from "./use-transform-effect";
4
4
  export * from "./use-transform-context";
5
5
  export * from "./use-transform-component";
6
+ export * from "./use-zoom-pan-pinch";
@@ -9,7 +9,7 @@ export function useTransformComponent<T>(
9
9
  ): T {
10
10
  const libraryContext = useTransformContext();
11
11
 
12
- const [transformRender, setTransformRender] = useState<T>(
12
+ const [transformRender, setTransformRender] = useState<T>(() =>
13
13
  callback(getState(libraryContext)),
14
14
  );
15
15
 
@@ -1,4 +1,4 @@
1
- import { useLayoutEffect, useRef } from "react";
1
+ import React, { useLayoutEffect, useRef } from "react";
2
2
 
3
3
  import { initialSetup } from "constants/state.constants";
4
4
  import { ZoomPanPinch } from "core/instance.core";
@@ -7,7 +7,13 @@ import { ReactZoomPanPinchProps, ReactZoomPanPinchRef } from "models";
7
7
  export const useZoomPanPinch = (props?: ReactZoomPanPinchProps) => {
8
8
  const contentRef = useRef<HTMLDivElement>(null);
9
9
  const wrapperRef = useRef<HTMLDivElement>(null);
10
- const instance = useRef(new ZoomPanPinch({ ...initialSetup, ...props }));
10
+ // Lazy so a fresh (immediately discarded) instance is not built on every
11
+ // render.
12
+ const instanceRef = useRef<ZoomPanPinch | null>(null);
13
+ if (instanceRef.current === null) {
14
+ instanceRef.current = new ZoomPanPinch({ ...initialSetup, ...props });
15
+ }
16
+ const instance = instanceRef as React.MutableRefObject<ZoomPanPinch>;
11
17
 
12
18
  const useTransformCallback = useRef<
13
19
  (data: {
@@ -29,7 +35,7 @@ export const useZoomPanPinch = (props?: ReactZoomPanPinchProps) => {
29
35
  });
30
36
 
31
37
  return () => {
32
- inst.cleanupWindowEvents();
38
+ inst.unmount();
33
39
  unmount();
34
40
  };
35
41
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -4,14 +4,32 @@ import { animations } from "../core/animations/animations.constants";
4
4
  import { DeepNonNullable } from "./helpers.model";
5
5
  import {
6
6
  centerView,
7
+ clientToContent,
8
+ contentToClient,
7
9
  resetTransform,
8
10
  setTransform,
9
11
  zoomIn,
10
12
  zoomOut,
11
13
  zoomToElement,
14
+ zoomToPoint,
12
15
  } from "../core/handlers/handlers.logic";
13
16
  import { ZoomPanPinch } from "../core/instance.core";
14
17
 
18
+ export type ZoomToElementTarget = HTMLElement | string;
19
+
20
+ export type ZoomToElementOptions = {
21
+ /** Explicit target scale; when omitted the element(s) are fitted to the viewport. */
22
+ scale?: number;
23
+ /** Lower cap for the automatically computed fit scale. */
24
+ minScale?: number;
25
+ /** Upper cap for the automatically computed fit scale (e.g. stop tiny elements from over-zooming). */
26
+ maxScale?: number;
27
+ animationTime?: number;
28
+ animationType?: keyof typeof animations;
29
+ offsetX?: number;
30
+ offsetY?: number;
31
+ };
32
+
15
33
  export type ReactZoomPanPinchContext = typeof ZoomPanPinch.prototype;
16
34
 
17
35
  export type ReactZoomPanPinchContextState = {
@@ -41,6 +59,9 @@ export type ReactZoomPanPinchHandlers = {
41
59
  resetTransform: ReturnType<typeof resetTransform>;
42
60
  centerView: ReturnType<typeof centerView>;
43
61
  zoomToElement: ReturnType<typeof zoomToElement>;
62
+ zoomToPoint: ReturnType<typeof zoomToPoint>;
63
+ clientToContent: ReturnType<typeof clientToContent>;
64
+ contentToClient: ReturnType<typeof contentToClient>;
44
65
  };
45
66
 
46
67
  export type ReactZoomPanPinchRefProps = {
@@ -10,7 +10,10 @@ import {
10
10
  setTransform,
11
11
  resetTransform,
12
12
  zoomToElement,
13
+ zoomToPoint,
13
14
  centerView,
15
+ clientToContent,
16
+ contentToClient,
14
17
  } from "../core/handlers/handlers.logic";
15
18
 
16
19
  export const getControls = (
@@ -25,6 +28,9 @@ export const getControls = (
25
28
  resetTransform: resetTransform(contextInstance),
26
29
  centerView: centerView(contextInstance),
27
30
  zoomToElement: zoomToElement(contextInstance),
31
+ zoomToPoint: zoomToPoint(contextInstance),
32
+ clientToContent: clientToContent(contextInstance),
33
+ contentToClient: contentToClient(contextInstance),
28
34
  };
29
35
  };
30
36
 
@@ -0,0 +1,11 @@
1
+ import { useEffect, useLayoutEffect } from "react";
2
+
3
+ /**
4
+ * `useLayoutEffect` in the browser, `useEffect` during server rendering.
5
+ *
6
+ * DOM measurements and the initial transform must run before the first paint
7
+ * (otherwise `centerOnInit`, `initialPosition*` and virtualized children flash
8
+ * into place one frame late), but `useLayoutEffect` warns on the server.
9
+ */
10
+ export const useIsomorphicLayoutEffect =
11
+ typeof window !== "undefined" ? useLayoutEffect : useEffect;