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.
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import React, { useRef, useImperativeHandle, useEffect, useContext, useLayoutEffect, useState, useCallback, useMemo } from 'react';
1
+ import React, { useLayoutEffect, useEffect, useRef, useImperativeHandle, useContext, useState, useCallback, useMemo } from 'react';
2
2
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
3
 
4
4
  /**
@@ -102,46 +102,63 @@ var animations = {
102
102
  };
103
103
 
104
104
  /* eslint-disable no-param-reassign */
105
- var handleCancelAnimationFrame = function (animation) {
106
- if (typeof animation === "number") {
107
- cancelAnimationFrame(animation);
108
- }
105
+ var settleAnimation = function (contextInstance) {
106
+ var resolve = contextInstance.animationResolve;
107
+ contextInstance.animationResolve = null;
108
+ resolve === null || resolve === void 0 ? void 0 : resolve();
109
109
  };
110
110
  var handleCancelAnimation = function (contextInstance) {
111
- if (!contextInstance.mounted)
112
- return;
113
- handleCancelAnimationFrame(contextInstance.animation);
111
+ if (contextInstance.animationFrame !== null) {
112
+ cancelAnimationFrame(contextInstance.animationFrame);
113
+ }
114
114
  // Clear animation state
115
+ contextInstance.animationFrame = null;
115
116
  contextInstance.isAnimating = false;
116
117
  contextInstance.animation = null;
117
118
  contextInstance.velocity = null;
119
+ // An interrupted animation still settles its promise so callers awaiting
120
+ // `zoomIn()` & co. are never left hanging (#214).
121
+ settleAnimation(contextInstance);
118
122
  };
119
- function handleSetupAnimation(contextInstance, animationName, animationTime, callback) {
120
- if (!contextInstance.mounted)
123
+ function handleSetupAnimation(contextInstance, animationName, animationTime, callback, onFinish) {
124
+ if (!contextInstance.mounted) {
125
+ onFinish === null || onFinish === void 0 ? void 0 : onFinish();
121
126
  return;
127
+ }
122
128
  var startTime = new Date().getTime();
123
129
  var lastStep = 1;
124
130
  // if another animation is active
125
131
  handleCancelAnimation(contextInstance);
126
132
  // new animation
127
- contextInstance.animation = function () {
128
- if (!contextInstance.mounted) {
129
- return handleCancelAnimationFrame(contextInstance.animation);
133
+ var animation = function () {
134
+ // A frame that was already queued when this animation got cancelled or
135
+ // replaced must not run: it would apply a stale target and re-schedule
136
+ // the replacement animation a second time per frame.
137
+ if (!contextInstance.mounted || contextInstance.animation !== animation) {
138
+ return;
130
139
  }
131
140
  var frameTime = new Date().getTime() - startTime;
132
141
  var animationProgress = frameTime / animationTime;
133
142
  var animationType = animations[animationName];
134
143
  var step = animationType(animationProgress);
135
144
  if (frameTime >= animationTime) {
136
- callback(lastStep);
145
+ // Clear before the final step so a callback that starts a new
146
+ // animation (e.g. from onTransform) is not wiped out afterwards.
137
147
  contextInstance.animation = null;
148
+ contextInstance.animationFrame = null;
149
+ var resolve = contextInstance.animationResolve;
150
+ contextInstance.animationResolve = null;
151
+ callback(lastStep);
152
+ resolve === null || resolve === void 0 ? void 0 : resolve();
138
153
  }
139
- else if (contextInstance.animation) {
154
+ else {
140
155
  callback(step);
141
- requestAnimationFrame(contextInstance.animation);
156
+ contextInstance.animationFrame = requestAnimationFrame(animation);
142
157
  }
143
158
  };
144
- requestAnimationFrame(contextInstance.animation);
159
+ contextInstance.animation = animation;
160
+ contextInstance.animationResolve = onFinish !== null && onFinish !== void 0 ? onFinish : null;
161
+ contextInstance.animationFrame = requestAnimationFrame(animation);
145
162
  }
146
163
  function isValidTargetState(targetState) {
147
164
  var scale = targetState.scale, positionX = targetState.positionX, positionY = targetState.positionY;
@@ -152,10 +169,18 @@ function isValidTargetState(targetState) {
152
169
  }
153
170
  return true;
154
171
  }
172
+ /**
173
+ * Animates the transform to `targetState`.
174
+ *
175
+ * Resolves once the final frame has been applied. It also resolves — never
176
+ * rejects — when the animation is interrupted by another animation or a user
177
+ * gesture, when the instance unmounts, or when the target is invalid, so the
178
+ * returned promise is always safe to await (#214).
179
+ */
155
180
  function animate(contextInstance, targetState, animationTime, animationName) {
156
181
  var isValid = isValidTargetState(targetState);
157
182
  if (!contextInstance.mounted || !isValid)
158
- return;
183
+ return Promise.resolve();
159
184
  var setState = contextInstance.setState;
160
185
  var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
161
186
  var scaleDiff = targetState.scale - scale;
@@ -163,8 +188,9 @@ function animate(contextInstance, targetState, animationTime, animationName) {
163
188
  var positionYDiff = targetState.positionY - positionY;
164
189
  if (animationTime === 0) {
165
190
  setState(targetState.scale, targetState.positionX, targetState.positionY);
191
+ return Promise.resolve();
166
192
  }
167
- else {
193
+ return new Promise(function (resolve) {
168
194
  // animation start timestamp
169
195
  handleSetupAnimation(contextInstance, animationName, animationTime, function (step) {
170
196
  if (step !== 1) {
@@ -177,8 +203,8 @@ function animate(contextInstance, targetState, animationTime, animationName) {
177
203
  var newPositionX = positionX + positionXDiff * step;
178
204
  var newPositionY = positionY + positionYDiff * step;
179
205
  setState(newScale, newPositionX, newPositionY);
180
- });
181
- }
206
+ }, resolve);
207
+ });
182
208
  }
183
209
 
184
210
  /* eslint-disable no-param-reassign */
@@ -332,9 +358,7 @@ var isPanningStartAllowed = function (contextInstance, event) {
332
358
  var isExcluded = isExcludedNode(target, excluded);
333
359
  if (isExcluded)
334
360
  return false;
335
- if (target.getAttribute("draggable") === "true" ||
336
- target.getAttribute("contenteditable") === "true" ||
337
- target.isContentEditable) {
361
+ if (isDraggableTarget(target) || isEditableTarget(target)) {
338
362
  return false;
339
363
  }
340
364
  return true;
@@ -606,7 +630,14 @@ function handleAlignToBounds(contextInstance, customAnimationTime) {
606
630
  if (isDisabled)
607
631
  return;
608
632
  var targetState = handlePanToBounds(contextInstance);
609
- if (targetState) {
633
+ if (!targetState)
634
+ return;
635
+ // Nothing to align: starting a 200 ms animation towards the current state
636
+ // would only pin the transform and swallow input that arrives meanwhile
637
+ // (#582).
638
+ var _b = contextInstance.state, positionX = _b.positionX, positionY = _b.positionY;
639
+ var isNoop = targetState.positionX === positionX && targetState.positionY === positionY;
640
+ if (!isNoop) {
610
641
  animate(contextInstance, targetState, customAnimationTime !== null && customAnimationTime !== void 0 ? customAnimationTime : animationTime, animationType);
611
642
  }
612
643
  }
@@ -876,57 +907,70 @@ var createSetup = function (props) {
876
907
  var handleCalculateButtonZoom = function (contextInstance, delta, step) {
877
908
  var scale = contextInstance.state.scale;
878
909
  var wrapperComponent = contextInstance.wrapperComponent, setup = contextInstance.setup;
879
- var maxScale = setup.maxScale, minScale = setup.minScale, zoomAnimation = setup.zoomAnimation, smooth = setup.smooth;
910
+ var maxScale = setup.maxScale, minScale = setup.minScale, zoomAnimation = setup.zoomAnimation;
880
911
  var size = zoomAnimation.size;
881
912
  if (!wrapperComponent) {
882
913
  throw new Error("Wrapper is not mounted");
883
914
  }
884
- var targetScale = smooth
885
- ? scale * Math.exp(delta * step)
886
- : scale + delta * step;
915
+ // `step` is an absolute scale increment for zoomIn/zoomOut and double
916
+ // click: zoomIn(0.25) from 1 lands on 1.25. The `smooth` option only
917
+ // shapes wheel/trackpad deltas (#545, #431).
918
+ var targetScale = scale + delta * step;
887
919
  var newScale = checkZoomBounds(roundNumber(targetScale, 3), minScale, maxScale, size, false);
888
920
  return newScale;
889
921
  };
890
- function handleZoomToViewCenter(contextInstance, delta, step, animationTime, animationType) {
922
+ /**
923
+ * Runs a programmatic zoom: fires `onZoomStart`/`onZoom`, animates to
924
+ * `targetState` and fires `onZoomStop` once the animation time has elapsed.
925
+ * Resolves when the animation has finished (or was interrupted).
926
+ */
927
+ function runZoomAnimation(contextInstance, targetState, animationTime, animationType) {
891
928
  var _a, _b;
892
929
  var wrapperComponent = contextInstance.wrapperComponent;
893
- var _c = contextInstance.state, scale = _c.scale, positionX = _c.positionX, positionY = _c.positionY;
894
- var zoomAnimation = contextInstance.setup.zoomAnimation;
895
- if (!wrapperComponent)
896
- return console.error("No WrapperComponent found");
897
- var effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
898
- var wrapperWidth = wrapperComponent.offsetWidth;
899
- var wrapperHeight = wrapperComponent.offsetHeight;
900
- var mouseX = (wrapperWidth / 2 - positionX) / scale;
901
- var mouseY = (wrapperHeight / 2 - positionY) / scale;
902
- var newScale = handleCalculateButtonZoom(contextInstance, delta, step);
903
- var targetState = handleZoomToPoint(contextInstance, newScale, mouseX, mouseY);
904
- if (!targetState) {
905
- return console.error("Error during zoom event. New transformation state was not calculated.");
906
- }
907
- var _d = contextInstance.props, onZoomStart = _d.onZoomStart, onZoom = _d.onZoom, onZoomStop = _d.onZoomStop;
930
+ var _c = contextInstance.props, onZoomStart = _c.onZoomStart, onZoom = _c.onZoom, onZoomStop = _c.onZoomStop;
908
931
  var event = new MouseEvent("mousemove", { bubbles: true });
909
932
  var ctx = getContext(contextInstance);
910
933
  handleCallback(ctx, event, onZoomStart);
911
934
  handleCallback(ctx, event, onZoom);
912
- animate(contextInstance, targetState, effectiveAnimationTime, animationType);
913
- var win = (_b = (_a = wrapperComponent.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) !== null && _b !== void 0 ? _b : (typeof window !== "undefined" ? window : null);
935
+ var done = animate(contextInstance, targetState, animationTime, animationType);
936
+ var win = (_b = (_a = wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) !== null && _b !== void 0 ? _b : (typeof window !== "undefined" ? window : null);
914
937
  if (win) {
915
938
  win.setTimeout(function () {
916
939
  if (!contextInstance.mounted)
917
940
  return;
918
941
  handleCallback(getContext(contextInstance), event, onZoomStop);
919
- }, effectiveAnimationTime);
942
+ }, animationTime);
943
+ }
944
+ return done;
945
+ }
946
+ function handleZoomToViewCenter(contextInstance, delta, step, animationTime, animationType) {
947
+ var wrapperComponent = contextInstance.wrapperComponent;
948
+ var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
949
+ var zoomAnimation = contextInstance.setup.zoomAnimation;
950
+ if (!wrapperComponent) {
951
+ console.error("No WrapperComponent found");
952
+ return Promise.resolve();
953
+ }
954
+ var effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
955
+ var wrapperWidth = wrapperComponent.offsetWidth;
956
+ var wrapperHeight = wrapperComponent.offsetHeight;
957
+ var mouseX = (wrapperWidth / 2 - positionX) / scale;
958
+ var mouseY = (wrapperHeight / 2 - positionY) / scale;
959
+ var newScale = handleCalculateButtonZoom(contextInstance, delta, step);
960
+ var targetState = handleZoomToPoint(contextInstance, newScale, mouseX, mouseY);
961
+ if (!targetState) {
962
+ console.error("Error during zoom event. New transformation state was not calculated.");
963
+ return Promise.resolve();
920
964
  }
965
+ return runZoomAnimation(contextInstance, targetState, effectiveAnimationTime, animationType);
921
966
  }
922
967
  function resetTransformations(contextInstance, animationTime, animationType, onResetTransformation) {
923
- var _a, _b;
924
968
  var setup = contextInstance.setup, wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
925
969
  var limitToBounds = setup.limitToBounds, centerOnInit = setup.centerOnInit;
926
970
  var initialTransformation = createState(contextInstance.props);
927
- var _c = contextInstance.state, scale = _c.scale, positionX = _c.positionX, positionY = _c.positionY;
971
+ var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
928
972
  if (!wrapperComponent)
929
- return;
973
+ return Promise.resolve();
930
974
  var targetPositionX = initialTransformation.positionX;
931
975
  var targetPositionY = initialTransformation.positionY;
932
976
  if (centerOnInit && contentComponent) {
@@ -944,26 +988,36 @@ function resetTransformations(contextInstance, animationTime, animationType, onR
944
988
  if (scale === initialTransformation.scale &&
945
989
  positionX === initialTransformation.positionX &&
946
990
  positionY === initialTransformation.positionY) {
947
- return;
991
+ return Promise.resolve();
948
992
  }
949
993
  onResetTransformation === null || onResetTransformation === void 0 ? void 0 : onResetTransformation();
950
- var _d = contextInstance.props, onZoomStart = _d.onZoomStart, onZoom = _d.onZoom, onZoomStop = _d.onZoomStop;
951
- var event = new MouseEvent("mousemove", { bubbles: true });
952
- var ctx = getContext(contextInstance);
953
- handleCallback(ctx, event, onZoomStart);
954
- handleCallback(ctx, event, onZoom);
955
- animate(contextInstance, newState, animationTime, animationType);
956
- var win = (_b = (_a = wrapperComponent.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) !== null && _b !== void 0 ? _b : (typeof window !== "undefined" ? window : null);
957
- if (win) {
958
- win.setTimeout(function () {
959
- if (!contextInstance.mounted)
960
- return;
961
- handleCallback(getContext(contextInstance), event, onZoomStop);
962
- }, animationTime);
994
+ return runZoomAnimation(contextInstance, newState, animationTime, animationType);
995
+ }
996
+ var toRect = function (target) {
997
+ if ("getBoundingClientRect" in target) {
998
+ var rect = target.getBoundingClientRect();
999
+ return {
1000
+ x: rect.left,
1001
+ y: rect.top,
1002
+ width: rect.width,
1003
+ height: rect.height,
1004
+ };
963
1005
  }
1006
+ return target;
1007
+ };
1008
+ /**
1009
+ * Smallest client rect containing every node (#388).
1010
+ */
1011
+ function getUnionRect(nodes) {
1012
+ var rects = nodes.map(toRect);
1013
+ var left = Math.min.apply(Math, rects.map(function (r) { return r.x; }));
1014
+ var top = Math.min.apply(Math, rects.map(function (r) { return r.y; }));
1015
+ var right = Math.max.apply(Math, rects.map(function (r) { return r.x + r.width; }));
1016
+ var bottom = Math.max.apply(Math, rects.map(function (r) { return r.y + r.height; }));
1017
+ return { x: left, y: top, width: right - left, height: bottom - top };
964
1018
  }
965
1019
  function getOffset(element, wrapper, content, state) {
966
- var offset = element.getBoundingClientRect();
1020
+ var offset = toRect(element);
967
1021
  var wrapperOffset = wrapper.getBoundingClientRect();
968
1022
  var contentOffset = content.getBoundingClientRect();
969
1023
  var xOff = wrapperOffset.x * state.scale;
@@ -973,7 +1027,14 @@ function getOffset(element, wrapper, content, state) {
973
1027
  y: (offset.y - contentOffset.y + yOff) / state.scale,
974
1028
  };
975
1029
  }
976
- function calculateZoomToNode(contextInstance, node, customZoom, customOffsetX, customOffsetY) {
1030
+ /**
1031
+ * Transform that frames the client-space `rect` in the viewport.
1032
+ *
1033
+ * `customZoom` forces the scale; otherwise the rect is fitted and the fit
1034
+ * scale is capped by `minFitScale`/`maxFitScale` (#515) before the wrapper's
1035
+ * own `minScale`/`maxScale` apply.
1036
+ */
1037
+ function calculateZoomToRect(contextInstance, rect, customZoom, customOffsetX, customOffsetY, minFitScale, maxFitScale) {
977
1038
  if (customOffsetX === void 0) { customOffsetX = 0; }
978
1039
  if (customOffsetY === void 0) { customOffsetY = 0; }
979
1040
  var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, state = contextInstance.state;
@@ -981,15 +1042,21 @@ function calculateZoomToNode(contextInstance, node, customZoom, customOffsetX, c
981
1042
  if (!wrapperComponent || !contentComponent)
982
1043
  return state;
983
1044
  var wrapperRect = wrapperComponent.getBoundingClientRect();
984
- var nodeRect = node.getBoundingClientRect();
985
- var nodeOffset = getOffset(node, wrapperComponent, contentComponent, state);
1045
+ var nodeOffset = getOffset(rect, wrapperComponent, contentComponent, state);
986
1046
  var nodeLeft = nodeOffset.x;
987
1047
  var nodeTop = nodeOffset.y;
988
- var nodeWidth = nodeRect.width / state.scale;
989
- var nodeHeight = nodeRect.height / state.scale;
1048
+ var nodeWidth = rect.width / state.scale;
1049
+ var nodeHeight = rect.height / state.scale;
990
1050
  var scaleX = wrapperComponent.offsetWidth / nodeWidth;
991
1051
  var scaleY = wrapperComponent.offsetHeight / nodeHeight;
992
- var newScale = checkZoomBounds(customZoom || Math.min(scaleX, scaleY), minScale, maxScale, 0, false);
1052
+ var targetScale = customZoom || Math.min(scaleX, scaleY);
1053
+ if (maxFitScale !== undefined) {
1054
+ targetScale = Math.min(targetScale, maxFitScale);
1055
+ }
1056
+ if (minFitScale !== undefined) {
1057
+ targetScale = Math.max(targetScale, minFitScale);
1058
+ }
1059
+ var newScale = checkZoomBounds(targetScale, minScale, maxScale, 0, false);
993
1060
  var offsetX = (wrapperRect.width - nodeWidth * newScale) / 2;
994
1061
  var offsetY = (wrapperRect.height - nodeHeight * newScale) / 2;
995
1062
  var newPositionX = (wrapperRect.left - nodeLeft) * newScale + offsetX + customOffsetX;
@@ -998,13 +1065,41 @@ function calculateZoomToNode(contextInstance, node, customZoom, customOffsetX, c
998
1065
  var _b = getMouseBoundedPosition(newPositionX, newPositionY, bounds, limitToBounds, 0, 0, wrapperComponent), x = _b.x, y = _b.y;
999
1066
  return { positionX: x, positionY: y, scale: newScale };
1000
1067
  }
1068
+ /**
1069
+ * Client (viewport) coordinates → unscaled content coordinates (#378).
1070
+ * Returns `{ x: 0, y: 0 }` before the wrapper is mounted.
1071
+ */
1072
+ function clientToContentPoint(contextInstance, clientX, clientY) {
1073
+ var wrapperComponent = contextInstance.wrapperComponent, state = contextInstance.state;
1074
+ if (!wrapperComponent)
1075
+ return { x: 0, y: 0 };
1076
+ var rect = wrapperComponent.getBoundingClientRect();
1077
+ return {
1078
+ x: (clientX - rect.left - state.positionX) / state.scale,
1079
+ y: (clientY - rect.top - state.positionY) / state.scale,
1080
+ };
1081
+ }
1082
+ /**
1083
+ * Unscaled content coordinates → client (viewport) coordinates.
1084
+ * Returns `{ x: 0, y: 0 }` before the wrapper is mounted.
1085
+ */
1086
+ function contentToClientPoint(contextInstance, x, y) {
1087
+ var wrapperComponent = contextInstance.wrapperComponent, state = contextInstance.state;
1088
+ if (!wrapperComponent)
1089
+ return { x: 0, y: 0 };
1090
+ var rect = wrapperComponent.getBoundingClientRect();
1091
+ return {
1092
+ x: rect.left + state.positionX + x * state.scale,
1093
+ y: rect.top + state.positionY + y * state.scale,
1094
+ };
1095
+ }
1001
1096
 
1002
1097
  var zoomIn = function (contextInstance) {
1003
1098
  return function (step, animationTime, animationType) {
1004
1099
  if (step === void 0) { step = 0.5; }
1005
1100
  if (animationTime === void 0) { animationTime = 300; }
1006
1101
  if (animationType === void 0) { animationType = "easeOut"; }
1007
- handleZoomToViewCenter(contextInstance, 1, step, animationTime, animationType);
1102
+ return handleZoomToViewCenter(contextInstance, 1, step, animationTime, animationType);
1008
1103
  };
1009
1104
  };
1010
1105
  var zoomOut = function (contextInstance) {
@@ -1012,7 +1107,7 @@ var zoomOut = function (contextInstance) {
1012
1107
  if (step === void 0) { step = 0.5; }
1013
1108
  if (animationTime === void 0) { animationTime = 300; }
1014
1109
  if (animationType === void 0) { animationType = "easeOut"; }
1015
- handleZoomToViewCenter(contextInstance, -1, step, animationTime, animationType);
1110
+ return handleZoomToViewCenter(contextInstance, -1, step, animationTime, animationType);
1016
1111
  };
1017
1112
  };
1018
1113
  var setTransform = function (contextInstance) {
@@ -1022,21 +1117,22 @@ var setTransform = function (contextInstance) {
1022
1117
  var _a = contextInstance.state, positionX = _a.positionX, positionY = _a.positionY, scale = _a.scale;
1023
1118
  var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
1024
1119
  var disabled = contextInstance.setup.disabled;
1025
- if (disabled || !wrapperComponent || !contentComponent)
1026
- return;
1120
+ if (disabled || !wrapperComponent || !contentComponent) {
1121
+ return Promise.resolve();
1122
+ }
1027
1123
  var targetState = {
1028
1124
  positionX: Number.isNaN(newPositionX) ? positionX : newPositionX,
1029
1125
  positionY: Number.isNaN(newPositionY) ? positionY : newPositionY,
1030
1126
  scale: Number.isNaN(newScale) ? scale : newScale,
1031
1127
  };
1032
- animate(contextInstance, targetState, animationTime, animationType);
1128
+ return animate(contextInstance, targetState, animationTime, animationType);
1033
1129
  };
1034
1130
  };
1035
1131
  var resetTransform = function (contextInstance) {
1036
1132
  return function (animationTime, animationType) {
1037
1133
  if (animationTime === void 0) { animationTime = 200; }
1038
1134
  if (animationType === void 0) { animationType = "easeOut"; }
1039
- resetTransformations(contextInstance, animationTime, animationType);
1135
+ return resetTransformations(contextInstance, animationTime, animationType);
1040
1136
  };
1041
1137
  };
1042
1138
  var centerView = function (contextInstance) {
@@ -1046,23 +1142,102 @@ var centerView = function (contextInstance) {
1046
1142
  var state = contextInstance.state, wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
1047
1143
  if (wrapperComponent && contentComponent) {
1048
1144
  var targetState = getCenterPosition(scale || state.scale, wrapperComponent, contentComponent);
1049
- animate(contextInstance, targetState, animationTime, animationType);
1145
+ return animate(contextInstance, targetState, animationTime, animationType);
1146
+ }
1147
+ return Promise.resolve();
1148
+ };
1149
+ };
1150
+ /**
1151
+ * Zooms so that the content point currently under the client (viewport)
1152
+ * coordinates `clientX`/`clientY` stays fixed on screen — the same anchoring a
1153
+ * wheel zoom does at the cursor. Useful for click-to-zoom and focal zooms
1154
+ * (#353).
1155
+ */
1156
+ var zoomToPoint = function (contextInstance) {
1157
+ return function (scale, clientX, clientY, animationTime, animationType) {
1158
+ if (animationTime === void 0) { animationTime = 300; }
1159
+ if (animationType === void 0) { animationType = "easeOut"; }
1160
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup;
1161
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
1162
+ return Promise.resolve();
1050
1163
  }
1164
+ var point = clientToContentPoint(contextInstance, clientX, clientY);
1165
+ var targetState = handleZoomToPoint(contextInstance, scale, point.x, point.y);
1166
+ if (!targetState)
1167
+ return Promise.resolve();
1168
+ var effectiveAnimationTime = setup.zoomAnimation.disabled
1169
+ ? 0
1170
+ : animationTime;
1171
+ return runZoomAnimation(contextInstance, targetState, effectiveAnimationTime, animationType);
1172
+ };
1173
+ };
1174
+ /**
1175
+ * Converts client (viewport) coordinates — e.g. `event.clientX/Y` — into
1176
+ * content coordinates: the unscaled position inside `TransformComponent`
1177
+ * regardless of the current pan and zoom (#378).
1178
+ */
1179
+ var clientToContent = function (contextInstance) {
1180
+ return function (clientX, clientY) {
1181
+ return clientToContentPoint(contextInstance, clientX, clientY);
1051
1182
  };
1052
1183
  };
1184
+ /**
1185
+ * Inverse of `clientToContent`: converts unscaled content coordinates into
1186
+ * client (viewport) coordinates for the current transform.
1187
+ */
1188
+ var contentToClient = function (contextInstance) {
1189
+ return function (x, y) {
1190
+ return contentToClientPoint(contextInstance, x, y);
1191
+ };
1192
+ };
1193
+ var resolveTargets = function (contextInstance, node) {
1194
+ var _a;
1195
+ var wrapperComponent = contextInstance.wrapperComponent;
1196
+ if (!wrapperComponent)
1197
+ return [];
1198
+ // Ids are resolved in the wrapper's own root so this works inside portal
1199
+ // windows and iframes (#290) as well as shadow roots (#371).
1200
+ var rootNode = wrapperComponent.getRootNode();
1201
+ var root = rootNode && "getElementById" in rootNode
1202
+ ? rootNode
1203
+ : (_a = wrapperComponent.ownerDocument) !== null && _a !== void 0 ? _a : (typeof document !== "undefined" ? document : null);
1204
+ var list = Array.isArray(node) ? node : [node];
1205
+ return list
1206
+ .map(function (item) {
1207
+ return typeof item === "string"
1208
+ ? root === null || root === void 0 ? void 0 : root.getElementById(item)
1209
+ : item;
1210
+ })
1211
+ .filter(function (element) {
1212
+ return !!element && wrapperComponent.contains(element);
1213
+ });
1214
+ };
1215
+ /**
1216
+ * Zooms and pans so the target element(s) fill the viewport.
1217
+ *
1218
+ * - `node` may be an element, an element id, or an array of either; with
1219
+ * several targets the union of their boxes is framed (#388).
1220
+ * - The second argument is either the target `scale` (legacy positional
1221
+ * form) or an options object. `minScale`/`maxScale` cap the automatically
1222
+ * computed fit scale (#515).
1223
+ */
1053
1224
  var zoomToElement = function (contextInstance) {
1054
- return function (node, scale, animationTime, animationType, offsetX, offsetY) {
1225
+ return function (node, scaleOrOptions, animationTime, animationType, offsetX, offsetY) {
1226
+ var _a, _b, _c, _d;
1055
1227
  if (animationTime === void 0) { animationTime = 600; }
1056
1228
  if (animationType === void 0) { animationType = "easeOut"; }
1057
1229
  if (offsetX === void 0) { offsetX = 0; }
1058
1230
  if (offsetY === void 0) { offsetY = 0; }
1059
1231
  handleCancelAnimation(contextInstance);
1060
- var wrapperComponent = contextInstance.wrapperComponent;
1061
- var target = typeof node === "string" ? document.getElementById(node) : node;
1062
- if (wrapperComponent && target && wrapperComponent.contains(target)) {
1063
- var targetState = calculateZoomToNode(contextInstance, target, scale, offsetX, offsetY);
1064
- animate(contextInstance, targetState, animationTime, animationType);
1232
+ var options = typeof scaleOrOptions === "object" && scaleOrOptions !== null
1233
+ ? scaleOrOptions
1234
+ : { scale: scaleOrOptions };
1235
+ var targets = resolveTargets(contextInstance, node);
1236
+ if (!contextInstance.wrapperComponent || targets.length === 0) {
1237
+ return Promise.resolve();
1065
1238
  }
1239
+ var targetState = calculateZoomToRect(contextInstance, getUnionRect(targets), options.scale, (_a = options.offsetX) !== null && _a !== void 0 ? _a : offsetX, (_b = options.offsetY) !== null && _b !== void 0 ? _b : offsetY, options.minScale, options.maxScale);
1240
+ return animate(contextInstance, targetState, (_c = options.animationTime) !== null && _c !== void 0 ? _c : animationTime, (_d = options.animationType) !== null && _d !== void 0 ? _d : animationType);
1066
1241
  };
1067
1242
  };
1068
1243
 
@@ -1076,6 +1251,9 @@ var getControls = function (contextInstance) {
1076
1251
  resetTransform: resetTransform(contextInstance),
1077
1252
  centerView: centerView(contextInstance),
1078
1253
  zoomToElement: zoomToElement(contextInstance),
1254
+ zoomToPoint: zoomToPoint(contextInstance),
1255
+ clientToContent: clientToContent(contextInstance),
1256
+ contentToClient: contentToClient(contextInstance),
1079
1257
  };
1080
1258
  };
1081
1259
  var getState = function (contextInstance) {
@@ -1119,6 +1297,42 @@ var isExcludedNode = function (node, excluded) {
1119
1297
  return node.matches("".concat(matchPrefix, " ").concat(exclude, ", ").concat(matchPrefix, " .").concat(exclude, ", ").concat(matchPrefix, " ").concat(exclude, " *, ").concat(matchPrefix, " .").concat(exclude, " *"));
1120
1298
  });
1121
1299
  };
1300
+ var EDITABLE_TAGS = new Set(["INPUT", "TEXTAREA", "SELECT", "OPTION"]);
1301
+ var CONTENT_EDITABLE_SELECTOR = '[contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';
1302
+ var DRAGGABLE_SELECTOR = '[draggable="true"]';
1303
+ var asElement = function (node) {
1304
+ // Duck-typed on purpose: `instanceof Element` fails for nodes that belong
1305
+ // to another window (portals, popups), see #290.
1306
+ if (!node || typeof node.closest !== "function") {
1307
+ return null;
1308
+ }
1309
+ return node;
1310
+ };
1311
+ /**
1312
+ * Form controls and contenteditable regions (or anything nested inside them).
1313
+ * Starting a pan or a double-click zoom from these would steal focus and block
1314
+ * native text editing (#437, #544).
1315
+ */
1316
+ var isEditableTarget = function (node) {
1317
+ var element = asElement(node);
1318
+ if (!element)
1319
+ return false;
1320
+ if (EDITABLE_TAGS.has(element.tagName))
1321
+ return true;
1322
+ if (element.isContentEditable)
1323
+ return true;
1324
+ return element.closest(CONTENT_EDITABLE_SELECTOR) !== null;
1325
+ };
1326
+ /**
1327
+ * HTML5 drag sources (or anything nested inside them). A pan started here
1328
+ * would call `preventDefault` on mousedown and cancel the native drag (#460).
1329
+ */
1330
+ var isDraggableTarget = function (node) {
1331
+ var element = asElement(node);
1332
+ if (!element)
1333
+ return false;
1334
+ return element.closest(DRAGGABLE_SELECTOR) !== null;
1335
+ };
1122
1336
  var cancelTimeout = function (timeout) {
1123
1337
  if (timeout) {
1124
1338
  clearTimeout(timeout);
@@ -1180,6 +1394,15 @@ function mergeRefs(refs) {
1180
1394
  };
1181
1395
  }
1182
1396
 
1397
+ /**
1398
+ * `useLayoutEffect` in the browser, `useEffect` during server rendering.
1399
+ *
1400
+ * DOM measurements and the initial transform must run before the first paint
1401
+ * (otherwise `centerOnInit`, `initialPosition*` and virtualized children flash
1402
+ * into place one frame late), but `useLayoutEffect` warns on the server.
1403
+ */
1404
+ var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
1405
+
1183
1406
  var isWheelAllowed = function (contextInstance, event) {
1184
1407
  var _a = contextInstance.setup.wheel, disabled = _a.disabled, wheelDisabled = _a.wheelDisabled, touchPadDisabled = _a.touchPadDisabled, excluded = _a.excluded;
1185
1408
  var isInitialized = contextInstance.isInitialized, isPanning = contextInstance.isPanning;
@@ -1187,6 +1410,11 @@ var isWheelAllowed = function (contextInstance, event) {
1187
1410
  var isAllowed = isInitialized && !isPanning && !disabled && target;
1188
1411
  if (!isAllowed)
1189
1412
  return false;
1413
+ // A purely horizontal wheel/swipe (Magic Mouse, trackpad) carries no zoom
1414
+ // intent. Treating its deltaY of 0 as "zoom out" was #168; leaving it
1415
+ // unclaimed also lets trackpad panning pick it up.
1416
+ if (event.deltaY === 0)
1417
+ return false;
1190
1418
  // Event ctrlKey detects if touchpad action is executing wheel or pinch gesture
1191
1419
  if (wheelDisabled && !event.ctrlKey)
1192
1420
  return false;
@@ -1350,8 +1578,13 @@ var wheelStopEventTime = 160;
1350
1578
  var wheelAnimationTime = 100;
1351
1579
  var handleWheelStart = function (contextInstance, event) {
1352
1580
  var _a = contextInstance.props, onWheelStart = _a.onWheelStart, onZoomStart = _a.onZoomStart;
1581
+ // Every wheel event must stop a running animation, not only the first one
1582
+ // of a gesture. The alignment animation scheduled by `handleWheelStop`
1583
+ // starts after `wheelAnimationTime` (100 ms) while `wheelStopEventTimer`
1584
+ // (160 ms) is still pending; guarding the cancel on the stop timer let that
1585
+ // animation overwrite the zoom of any wheel event arriving in between (#582).
1586
+ handleCancelAnimation(contextInstance);
1353
1587
  if (!contextInstance.wheelStopEventTimer) {
1354
- handleCancelAnimation(contextInstance);
1355
1588
  handleCallback(getContext(contextInstance), event, onWheelStart);
1356
1589
  handleCallback(getContext(contextInstance), event, onZoomStart);
1357
1590
  }
@@ -1411,8 +1644,12 @@ var handleWheelStop = function (contextInstance, event) {
1411
1644
  };
1412
1645
  var handleWheelPanningStart = function (contextInstance, event) {
1413
1646
  var _a = contextInstance.props, onWheelStart = _a.onWheelStart, onPanningStart = _a.onPanningStart;
1647
+ // See `handleWheelStart` (#582): cancel on every event, not only the first.
1648
+ handleCancelAnimation(contextInstance);
1414
1649
  if (!contextInstance.wheelStopEventTimer) {
1415
- handleCancelAnimation(contextInstance);
1650
+ // Same as a mouse pan start: bounds must reflect the current scale and
1651
+ // content size, not the ones measured at mount (#396, #433).
1652
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
1416
1653
  handleCallback(getContext(contextInstance), event, onWheelStart);
1417
1654
  handleCallback(getContext(contextInstance), event, onPanningStart);
1418
1655
  }
@@ -1523,6 +1760,8 @@ var handleDoubleClickStop = function (contextInstance, event) {
1523
1760
  cancelTimeout(contextInstance.doubleClickStopEventTimer);
1524
1761
  contextInstance.doubleClickStopEventTimer = setTimeout(function () {
1525
1762
  contextInstance.doubleClickStopEventTimer = null;
1763
+ if (!contextInstance.mounted)
1764
+ return;
1526
1765
  handleCallback(getContext(contextInstance), event, onZoomStop);
1527
1766
  }, animationTime);
1528
1767
  };
@@ -1581,6 +1820,9 @@ var isDoubleClickAllowed = function (contextInstance, event) {
1581
1820
  var isExcluded = isExcludedNode(target, excluded);
1582
1821
  if (isExcluded)
1583
1822
  return false;
1823
+ // Double-clicking a word inside an input selects it; it must not zoom.
1824
+ if (isEditableTarget(target))
1825
+ return false;
1584
1826
  return true;
1585
1827
  };
1586
1828
 
@@ -1624,20 +1866,46 @@ var ZoomPanPinch = /** @class */ (function () {
1624
1866
  // animations helpers
1625
1867
  this.isAnimating = false;
1626
1868
  this.animation = null;
1869
+ this.animationFrame = null;
1870
+ // Settles the promise returned by the running programmatic animation.
1871
+ this.animationResolve = null;
1872
+ // init helpers
1873
+ this.initObserverTimer = null;
1627
1874
  // key press
1628
1875
  this.pressedKeys = {};
1629
1876
  this.mount = function () {
1877
+ _this.mounted = true;
1630
1878
  _this.initializeWindowEvents();
1631
1879
  };
1880
+ // Marks the instance as gone so pending timers, animation frames and
1881
+ // callbacks scheduled before unmount become no-ops.
1632
1882
  this.unmount = function () {
1883
+ _this.mounted = false;
1633
1884
  _this.cleanupWindowEvents();
1634
1885
  };
1635
1886
  this.update = function (newProps) {
1636
1887
  _this.props = newProps;
1888
+ // Setup first: bounds depend on the new props (min/max positions,
1889
+ // centerZoomedOut, disablePadding).
1890
+ _this.setup = createSetup(newProps);
1637
1891
  if (_this.wrapperComponent && _this.contentComponent) {
1638
1892
  handleCalculateBounds(_this, _this.state.scale);
1639
1893
  }
1640
- _this.setup = createSetup(newProps);
1894
+ };
1895
+ this.clearTimers = function () {
1896
+ if (_this.wheelStopEventTimer)
1897
+ clearTimeout(_this.wheelStopEventTimer);
1898
+ if (_this.wheelAnimationTimer)
1899
+ clearTimeout(_this.wheelAnimationTimer);
1900
+ if (_this.doubleClickStopEventTimer) {
1901
+ clearTimeout(_this.doubleClickStopEventTimer);
1902
+ }
1903
+ if (_this.initObserverTimer)
1904
+ clearTimeout(_this.initObserverTimer);
1905
+ _this.wheelStopEventTimer = null;
1906
+ _this.wheelAnimationTimer = null;
1907
+ _this.doubleClickStopEventTimer = null;
1908
+ _this.initObserverTimer = null;
1641
1909
  };
1642
1910
  this.initializeWindowEvents = function () {
1643
1911
  var _a, _b, _c, _d;
@@ -1668,13 +1936,25 @@ var ZoomPanPinch = /** @class */ (function () {
1668
1936
  currentWindow === null || currentWindow === void 0 ? void 0 : currentWindow.removeEventListener("keyup", _this.setKeyUnPressed, passive);
1669
1937
  currentWindow === null || currentWindow === void 0 ? void 0 : currentWindow.removeEventListener("keydown", _this.setKeyPressed, passive);
1670
1938
  currentWindow === null || currentWindow === void 0 ? void 0 : currentWindow.removeEventListener("blur", _this.handleWindowBlur);
1671
- document.removeEventListener("mouseleave", _this.clearPanning, passive);
1672
1939
  (_b = _this.wrapperComponent) === null || _b === void 0 ? void 0 : _b.removeEventListener("wheel", _this.onWheelPanning, passive);
1673
1940
  (_c = _this.wrapperComponent) === null || _c === void 0 ? void 0 : _c.removeEventListener("keyup", _this.setKeyUnPressed, passive);
1674
1941
  (_d = _this.wrapperComponent) === null || _d === void 0 ? void 0 : _d.removeEventListener("keydown", _this.setKeyPressed, passive);
1942
+ _this.cleanupWrapperEvents();
1943
+ _this.clearTimers();
1675
1944
  handleCancelAnimation(_this);
1676
1945
  (_e = _this.observer) === null || _e === void 0 ? void 0 : _e.disconnect();
1677
1946
  };
1947
+ this.cleanupWrapperEvents = function () {
1948
+ var wrapper = _this.wrapperComponent;
1949
+ if (!wrapper)
1950
+ return;
1951
+ var passive = makePassiveEventOption();
1952
+ wrapper.removeEventListener("wheel", _this.onWheelZoom, passive);
1953
+ wrapper.removeEventListener("dblclick", _this.onDoubleClick, passive);
1954
+ wrapper.removeEventListener("touchstart", _this.onTouchPanningStart, passive);
1955
+ wrapper.removeEventListener("touchmove", _this.onTouchPanning, passive);
1956
+ wrapper.removeEventListener("touchend", _this.onTouchPanningStop, passive);
1957
+ };
1678
1958
  this.handleInitializeWrapperEvents = function (wrapper) {
1679
1959
  // Zooming events on wrapper
1680
1960
  var passive = makePassiveEventOption();
@@ -1685,11 +1965,13 @@ var ZoomPanPinch = /** @class */ (function () {
1685
1965
  wrapper.addEventListener("touchend", _this.onTouchPanningStop, passive);
1686
1966
  };
1687
1967
  this.handleInitialize = function (contentComponent) {
1968
+ var _a;
1688
1969
  var centerOnInit = _this.setup.centerOnInit;
1689
1970
  _this.applyTransformation();
1690
1971
  _this.onInitCallbacks.forEach(function (callback) { return callback(getContext(_this)); });
1691
1972
  if (centerOnInit) {
1692
1973
  _this.setCenter();
1974
+ (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1693
1975
  _this.observer = new ResizeObserver(function () {
1694
1976
  var _a;
1695
1977
  var currentWidth = contentComponent.offsetWidth;
@@ -1704,8 +1986,11 @@ var ZoomPanPinch = /** @class */ (function () {
1704
1986
  });
1705
1987
  // TODO: CHANGE to first interaction?
1706
1988
  // if nothing about the contentComponent has changed after 5 seconds, disconnect the observer
1707
- setTimeout(function () {
1989
+ if (_this.initObserverTimer)
1990
+ clearTimeout(_this.initObserverTimer);
1991
+ _this.initObserverTimer = setTimeout(function () {
1708
1992
  var _a;
1993
+ _this.initObserverTimer = null;
1709
1994
  (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1710
1995
  }, 5000);
1711
1996
  // Start observing the target node for configured mutations
@@ -1867,6 +2152,9 @@ var ZoomPanPinch = /** @class */ (function () {
1867
2152
  var isDoubleTapAllowed = !(doubleClick === null || doubleClick === void 0 ? void 0 : doubleClick.disabled);
1868
2153
  var isDoubleTap = _this.lastTouch && +new Date() - _this.lastTouch < 200;
1869
2154
  if (isDoubleTapAllowed && isDoubleTap && event.touches.length === 1) {
2155
+ // Consume the pair so a third quick tap starts a fresh sequence
2156
+ // instead of counting as another double tap.
2157
+ _this.lastTouch = null;
1870
2158
  _this.onDoubleClick(event);
1871
2159
  }
1872
2160
  else {
@@ -2080,6 +2368,7 @@ var ZoomPanPinch = /** @class */ (function () {
2080
2368
  * Initialization
2081
2369
  */
2082
2370
  this.init = function (wrapperComponent, contentComponent) {
2371
+ _this.mounted = true;
2083
2372
  _this.cleanupWindowEvents();
2084
2373
  _this.wrapperComponent = wrapperComponent;
2085
2374
  _this.contentComponent = contentComponent;
@@ -2107,9 +2396,21 @@ var getContent = function (children, ctx) {
2107
2396
  return children;
2108
2397
  };
2109
2398
  var TransformWrapper = React.forwardRef(function (props, ref) {
2110
- var instance = useRef(new ZoomPanPinch(props)).current;
2399
+ // Lazy so a fresh (immediately discarded) instance is not built on every
2400
+ // render.
2401
+ var instanceRef = useRef(null);
2402
+ if (instanceRef.current === null) {
2403
+ instanceRef.current = new ZoomPanPinch(props);
2404
+ }
2405
+ var instance = instanceRef.current;
2111
2406
  var content = getContent(props.children, getControls(instance));
2112
2407
  useImperativeHandle(ref, function () { return getControls(instance); }, [instance]);
2408
+ useEffect(function () {
2409
+ instance.mount();
2410
+ return function () {
2411
+ instance.unmount();
2412
+ };
2413
+ }, [instance]);
2113
2414
  useEffect(function () {
2114
2415
  instance.update(props);
2115
2416
  }, [instance, props]);
@@ -2119,13 +2420,19 @@ var TransformWrapper = React.forwardRef(function (props, ref) {
2119
2420
  var KeepScale = React.forwardRef(function (props, ref) {
2120
2421
  var localRef = useRef(null);
2121
2422
  var instance = useContext(Context);
2122
- useEffect(function () {
2123
- return instance.onChange(function (ctx) {
2423
+ useIsomorphicLayoutEffect(function () {
2424
+ var applyInverseScale = function (scale) {
2124
2425
  if (localRef.current) {
2125
2426
  var positionX = 0;
2126
2427
  var positionY = 0;
2127
- localRef.current.style.transform = instance.handleTransformStyles(positionX, positionY, 1 / ctx.instance.state.scale);
2428
+ localRef.current.style.transform = instance.handleTransformStyles(positionX, positionY, 1 / scale);
2128
2429
  }
2430
+ };
2431
+ // Apply immediately: an element mounted while already zoomed must not
2432
+ // wait for the next transform change to get its counter-scale.
2433
+ applyInverseScale(instance.state.scale);
2434
+ return instance.onChange(function (ctx) {
2435
+ applyInverseScale(ctx.instance.state.scale);
2129
2436
  });
2130
2437
  }, [instance]);
2131
2438
  return jsx("div", __assign({}, props, { ref: mergeRefs([localRef, ref]) }));
@@ -2192,7 +2499,6 @@ var MiniMap = function (_a) {
2192
2499
  var _f = useState(false), initialized = _f[0], setInitialized = _f[1];
2193
2500
  var instance = useTransformContext();
2194
2501
  var _g = useState(false), isDown = _g[0], setIsDown = _g[1];
2195
- var miniMapInstance = useRef(null);
2196
2502
  var mainRef = useRef(null);
2197
2503
  var wrapperRef = useRef(null);
2198
2504
  var previewRef = useRef(null);
@@ -2291,18 +2597,7 @@ var MiniMap = function (_a) {
2291
2597
  });
2292
2598
  useResize(instance.contentComponent, initialize, [initialized]);
2293
2599
  useEffect(function () {
2294
- return instance.onChange(function (zpp) {
2295
- var scale = computeMiniMapScale();
2296
- if (miniMapInstance.current) {
2297
- miniMapInstance.current.instance.state.scale = zpp.instance.state.scale;
2298
- miniMapInstance.current.instance.state.positionX =
2299
- zpp.instance.state.positionX * scale;
2300
- miniMapInstance.current.instance.state.positionY =
2301
- zpp.instance.state.positionY * scale;
2302
- }
2303
- });
2304
- }, [computeMiniMapScale, instance, miniMapInstance]);
2305
- useEffect(function () {
2600
+ var _a, _b;
2306
2601
  var move = function (e) {
2307
2602
  var _a, _b;
2308
2603
  if (panning &&
@@ -2337,14 +2632,18 @@ var MiniMap = function (_a) {
2337
2632
  var setUp = function () {
2338
2633
  setIsDown(false);
2339
2634
  };
2340
- document.addEventListener("mousedown", setDown);
2341
- document.addEventListener("mouseup", setUp);
2342
- document.addEventListener("mousemove", move);
2635
+ // Listen on the mini map's own document so it keeps working inside
2636
+ // portal windows and iframes.
2637
+ var doc = (_b = (_a = mainRef.current) === null || _a === void 0 ? void 0 : _a.ownerDocument) !== null && _b !== void 0 ? _b : document;
2638
+ doc.addEventListener("mousedown", setDown);
2639
+ doc.addEventListener("mouseup", setUp);
2640
+ doc.addEventListener("mousemove", move);
2343
2641
  return function () {
2344
- document.removeEventListener("mousemove", move);
2345
- document.removeEventListener("mouseup", setUp);
2642
+ doc.removeEventListener("mousedown", setDown);
2643
+ doc.removeEventListener("mousemove", move);
2644
+ doc.removeEventListener("mouseup", setUp);
2346
2645
  };
2347
- });
2646
+ }, [computeMiniMapScale, instance, isDown, panning]);
2348
2647
  var wrapperStyle = useMemo(function () {
2349
2648
  return {
2350
2649
  position: "relative",
@@ -2394,7 +2693,10 @@ var TransformComponent = function (_a) {
2394
2693
  var wrapperRef = useRef(null);
2395
2694
  var contentRef = useRef(null);
2396
2695
  var gridRef = useRef(null);
2397
- useEffect(function () {
2696
+ // Layout effect: the initial transform (initialPosition*, centerOnInit)
2697
+ // and the first visibility check of virtualized children happen before the
2698
+ // browser paints, so nothing jumps into place a frame late.
2699
+ useIsomorphicLayoutEffect(function () {
2398
2700
  var wrapper = wrapperRef.current;
2399
2701
  var content = contentRef.current;
2400
2702
  if (wrapper !== null && content !== null && init) {
@@ -2418,7 +2720,10 @@ var TransformComponent = function (_a) {
2418
2720
  sync();
2419
2721
  return instance.onChange(sync);
2420
2722
  }, [infinite, instance]);
2421
- return (jsxs("div", __assign({}, wrapperProps, { ref: wrapperRef, className: "".concat(baseClasses.wrapperClass, " ").concat(styles.wrapper, " ").concat(wrapperClass), style: wrapperStyle }, { children: [infinite && (jsx("div", { ref: gridRef, className: styles.infiniteGrid, "aria-hidden": true })), jsx("div", __assign({}, contentProps, { ref: contentRef, className: "".concat(baseClasses.contentClass, " ").concat(styles.content, " ").concat(contentClass), style: __assign(__assign({}, contentStyle), { transform: getTransformStyles(instance.state.positionX, instance.state.positionY, instance.state.scale) }) }, { children: children }))] })));
2723
+ return (jsxs("div", __assign({}, wrapperProps, { ref: wrapperRef, className: "".concat(baseClasses.wrapperClass, " ").concat(styles.wrapper, " ").concat(wrapperClass), style: wrapperStyle }, { children: [infinite && (jsx("div", { ref: gridRef, className: styles.infiniteGrid, "aria-hidden": true })), jsx("div", __assign({}, contentProps, { ref: contentRef, className: "".concat(baseClasses.contentClass, " ").concat(styles.content, " ").concat(contentClass), style: __assign(__assign({
2724
+ // Inline so the zoom anchor survives environments where the
2725
+ // stylesheet is not applied, e.g. a shadow root (#371, #444).
2726
+ transformOrigin: "0 0" }, contentStyle), { transform: getTransformStyles(instance.state.positionX, instance.state.positionY, instance.state.scale) }) }, { children: children }))] })));
2422
2727
  };
2423
2728
 
2424
2729
  /**
@@ -2465,31 +2770,41 @@ function isElementVisible(opts) {
2465
2770
  var Virtualize = React.forwardRef(function (_a, ref) {
2466
2771
  var x = _a.x, y = _a.y, width = _a.width, height = _a.height, _b = _a.margin, margin = _b === void 0 ? 0 : _b, _c = _a.threshold, threshold = _c === void 0 ? 0 : _c, _d = _a.placeholder, placeholder = _d === void 0 ? null : _d, onShow = _a.onShow, onHide = _a.onHide, children = _a.children, className = _a.className, style = _a.style;
2467
2772
  var instance = useContext(Context);
2468
- var _e = useState(false), visible = _e[0], setVisible = _e[1];
2773
+ var computeVisible = function () {
2774
+ var wrapper = instance.wrapperComponent;
2775
+ if (!wrapper)
2776
+ return false;
2777
+ return isElementVisible({
2778
+ elementX: x,
2779
+ elementY: y,
2780
+ elementWidth: width,
2781
+ elementHeight: height,
2782
+ scale: instance.state.scale,
2783
+ positionX: instance.state.positionX,
2784
+ positionY: instance.state.positionY,
2785
+ viewportWidth: wrapper.offsetWidth,
2786
+ viewportHeight: wrapper.offsetHeight,
2787
+ margin: margin,
2788
+ threshold: threshold,
2789
+ });
2790
+ };
2791
+ // Elements mounted after the wrapper is initialized (items added to a
2792
+ // canvas at runtime) render their children in the very first commit
2793
+ // instead of one frame later.
2794
+ var _e = useState(computeVisible), visible = _e[0], setVisible = _e[1];
2469
2795
  var visibleRef = useRef(false);
2470
2796
  var onShowRef = useRef(onShow);
2471
2797
  var onHideRef = useRef(onHide);
2472
2798
  onShowRef.current = onShow;
2473
2799
  onHideRef.current = onHide;
2474
- useEffect(function () {
2800
+ // Layout effect so the check triggered by the wrapper's init (also a
2801
+ // layout effect) re-renders before the browser paints.
2802
+ useIsomorphicLayoutEffect(function () {
2475
2803
  var check = function () {
2476
2804
  var _a, _b;
2477
- var wrapper = instance.wrapperComponent;
2478
- if (!wrapper)
2805
+ if (!instance.wrapperComponent)
2479
2806
  return;
2480
- var nowVisible = isElementVisible({
2481
- elementX: x,
2482
- elementY: y,
2483
- elementWidth: width,
2484
- elementHeight: height,
2485
- scale: instance.state.scale,
2486
- positionX: instance.state.positionX,
2487
- positionY: instance.state.positionY,
2488
- viewportWidth: wrapper.offsetWidth,
2489
- viewportHeight: wrapper.offsetHeight,
2490
- margin: margin,
2491
- threshold: threshold,
2492
- });
2807
+ var nowVisible = computeVisible();
2493
2808
  if (nowVisible !== visibleRef.current) {
2494
2809
  visibleRef.current = nowVisible;
2495
2810
  setVisible(nowVisible);
@@ -2569,7 +2884,9 @@ var useTransformEffect = function (callback) {
2569
2884
 
2570
2885
  function useTransformComponent(callback) {
2571
2886
  var libraryContext = useTransformContext();
2572
- var _a = useState(callback(getState(libraryContext))), transformRender = _a[0], setTransformRender = _a[1];
2887
+ var _a = useState(function () {
2888
+ return callback(getState(libraryContext));
2889
+ }), transformRender = _a[0], setTransformRender = _a[1];
2573
2890
  useEffect(function () {
2574
2891
  var mounted = true;
2575
2892
  var unmount = libraryContext.onChange(function (ref) {
@@ -2585,5 +2902,41 @@ function useTransformComponent(callback) {
2585
2902
  return transformRender;
2586
2903
  }
2587
2904
 
2588
- export { Context, DeviceType, KeepScale, MiniMap, TransformComponent, TransformWrapper, Virtualize, getCenterPosition, getMatrixTransformStyles, getTransformStyles, roundScaleForTransform, useControls, useTransformComponent, useTransformContext, useTransformEffect, useTransformInit };
2905
+ var useZoomPanPinch = function (props) {
2906
+ var contentRef = useRef(null);
2907
+ var wrapperRef = useRef(null);
2908
+ // Lazy so a fresh (immediately discarded) instance is not built on every
2909
+ // render.
2910
+ var instanceRef = useRef(null);
2911
+ if (instanceRef.current === null) {
2912
+ instanceRef.current = new ZoomPanPinch(__assign(__assign({}, initialSetup), props));
2913
+ }
2914
+ var instance = instanceRef;
2915
+ var useTransformCallback = useRef(function () { });
2916
+ useLayoutEffect(function () {
2917
+ var inst = instance.current;
2918
+ if (contentRef.current && wrapperRef.current) {
2919
+ inst.init(wrapperRef.current, contentRef.current);
2920
+ }
2921
+ var unmount = inst.onTransform(function (data) {
2922
+ useTransformCallback.current(data);
2923
+ });
2924
+ return function () {
2925
+ inst.unmount();
2926
+ unmount();
2927
+ };
2928
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2929
+ }, []);
2930
+ var useTransform = function (callback) {
2931
+ useTransformCallback.current = callback;
2932
+ };
2933
+ return {
2934
+ contentRef: contentRef,
2935
+ wrapperRef: wrapperRef,
2936
+ instance: instance,
2937
+ useTransform: useTransform,
2938
+ };
2939
+ };
2940
+
2941
+ export { Context, DeviceType, KeepScale, MiniMap, TransformComponent, TransformWrapper, Virtualize, getCenterPosition, getMatrixTransformStyles, getTransformStyles, roundScaleForTransform, useControls, useTransformComponent, useTransformContext, useTransformEffect, useTransformInit, useZoomPanPinch };
2589
2942
  //# sourceMappingURL=index.esm.js.map