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