react-zoom-pan-pinch 4.1.1 → 4.2.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
@@ -152,6 +152,8 @@ function handleSetupAnimation(contextInstance, animationName, animationTime, cal
152
152
  contextInstance.animationResolve = null;
153
153
  callback(lastStep);
154
154
  resolve === null || resolve === void 0 ? void 0 : resolve();
155
+ // A resize seen while this animation ran aligns its final state.
156
+ contextInstance.flushResizeAlignment();
155
157
  }
156
158
  else {
157
159
  callback(step);
@@ -211,8 +213,8 @@ function animate(contextInstance, targetState, animationTime, animationName) {
211
213
 
212
214
  /* eslint-disable no-param-reassign */
213
215
  function getComponentsSizes(wrapperComponent, contentComponent, newScale) {
214
- var wrapperWidth = wrapperComponent.offsetWidth;
215
- var wrapperHeight = wrapperComponent.offsetHeight;
216
+ var wrapperWidth = wrapperComponent.clientWidth;
217
+ var wrapperHeight = wrapperComponent.clientHeight;
216
218
  var contentWidth = contentComponent.offsetWidth;
217
219
  var contentHeight = contentComponent.offsetHeight;
218
220
  var newContentWidth = contentWidth * newScale;
@@ -345,15 +347,21 @@ var isPanningStartAllowed = function (contextInstance, event) {
345
347
  var excluded = contextInstance.setup.panning.excluded;
346
348
  var isInitialized = contextInstance.isInitialized, wrapperComponent = contextInstance.wrapperComponent;
347
349
  var target = event.target;
348
- var targetIsShadowDom = "shadowRoot" in target && "composedPath" in event;
349
- var isWrapperChild = targetIsShadowDom
350
- ? event.composedPath().some(function (el) {
351
- if (!(el instanceof Element)) {
352
- return false;
353
- }
354
- return wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(el);
355
- })
356
- : wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(target);
350
+ // `composedPath()` also lists the nodes inside a shadow root (#371) and the
351
+ // real target in another window (portal, popup) whose nodes fail an
352
+ // `instanceof Element` check from this realm (#290, PR #552): only
353
+ // duck-typed node checks are safe here.
354
+ var isElementNode = function (node) {
355
+ return !!node &&
356
+ typeof node === "object" &&
357
+ node.nodeType === 1 &&
358
+ typeof node.contains === "function";
359
+ };
360
+ var isWrapperChild = typeof event.composedPath === "function"
361
+ ? event
362
+ .composedPath()
363
+ .some(function (node) { return isElementNode(node) && !!(wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(node)); })
364
+ : !!(wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(target));
357
365
  var isAllowed = isInitialized && target && isWrapperChild;
358
366
  if (!isAllowed)
359
367
  return false;
@@ -403,10 +411,10 @@ function handlePanToBounds(contextInstance) {
403
411
  var xChanged = positionX > maxPositionX || positionX < minPositionX;
404
412
  var yChanged = positionY > maxPositionY || positionY < minPositionY;
405
413
  var mousePosX = positionX > maxPositionX
406
- ? wrapperComponent.offsetWidth
414
+ ? wrapperComponent.clientWidth
407
415
  : contextInstance.setup.minPositionX || 0;
408
416
  var mousePosY = positionY > maxPositionY
409
- ? wrapperComponent.offsetHeight
417
+ ? wrapperComponent.clientHeight
410
418
  : contextInstance.setup.minPositionY || 0;
411
419
  var _d = handleCalculateZoomPositions(contextInstance, mousePosX, mousePosY, scale, contextInstance.bounds, limitToBounds || centerZoomedOut), x = _d.x, y = _d.y;
412
420
  return {
@@ -469,8 +477,8 @@ var isVelocityCalculationAllowed = function (contextInstance) {
469
477
  return false;
470
478
  if (!limitToBounds)
471
479
  return true;
472
- var contentOverflows = wrapperComponent.offsetWidth < contentComponent.offsetWidth * scale ||
473
- wrapperComponent.offsetHeight < contentComponent.offsetHeight * scale;
480
+ var contentOverflows = wrapperComponent.clientWidth < contentComponent.offsetWidth * scale ||
481
+ wrapperComponent.clientHeight < contentComponent.offsetHeight * scale;
474
482
  return contentOverflows;
475
483
  };
476
484
  var isVelocityAllowed = function (contextInstance) {
@@ -516,7 +524,7 @@ function getVelocityPosition(newPosition, startPosition, currentPosition, isLock
516
524
  /* eslint-disable no-param-reassign */
517
525
  function getSizeMultiplier(wrapperComponent) {
518
526
  var defaultMultiplier = 1;
519
- var value = wrapperComponent.offsetWidth / window.innerWidth;
527
+ var value = wrapperComponent.clientWidth / window.innerWidth;
520
528
  if (Number.isNaN(value)) {
521
529
  return defaultMultiplier;
522
530
  }
@@ -583,8 +591,8 @@ function handleVelocityPanning(contextInstance) {
583
591
  var finalAnimationTime = Math.max(moveAnimationTime, alignAnimationTime);
584
592
  var paddingValueX = getPaddingValue(contextInstance, sizeX);
585
593
  var paddingValueY = getPaddingValue(contextInstance, sizeY);
586
- var paddingX = (paddingValueX * wrapperComponent.offsetWidth) / 100;
587
- var paddingY = (paddingValueY * wrapperComponent.offsetHeight) / 100;
594
+ var paddingX = (paddingValueX * wrapperComponent.clientWidth) / 100;
595
+ var paddingY = (paddingValueY * wrapperComponent.clientHeight) / 100;
588
596
  var maxTargetX = maxPositionX + paddingX;
589
597
  var minTargetX = minPositionX - paddingX;
590
598
  var maxTargetY = maxPositionY + paddingY;
@@ -617,7 +625,8 @@ function handlePanningStart(contextInstance, event) {
617
625
  contextInstance.panStartPosition = { x: positionX, y: positionY };
618
626
  handleCancelAnimation(contextInstance);
619
627
  handleCalculateBounds(contextInstance, scale);
620
- if (window.TouchEvent !== undefined && event instanceof TouchEvent) {
628
+ // Duck-typed: a TouchEvent from another window fails `instanceof` (#290).
629
+ if ("touches" in event) {
621
630
  handleTouchPanningSetup(contextInstance, event);
622
631
  }
623
632
  else {
@@ -631,6 +640,12 @@ function handleAlignToBounds(contextInstance, customAnimationTime) {
631
640
  var isDisabled = disabled || scale < minScale || (!sizeX && !sizeY);
632
641
  if (isDisabled)
633
642
  return;
643
+ // The content or the wrapper changed size during the gesture (the resize
644
+ // observer postpones its bounds refresh, see `handleResizeAlignment`):
645
+ // align against the current limits so this single animation lands right.
646
+ if (contextInstance.isResizeAlignmentPending) {
647
+ handleCalculateBounds(contextInstance, scale);
648
+ }
634
649
  var targetState = handlePanToBounds(contextInstance);
635
650
  if (!targetState)
636
651
  return;
@@ -669,8 +684,13 @@ function handlePanningEnd(contextInstance, velocityDisabled) {
669
684
  }
670
685
  contextInstance.isAnimating = false;
671
686
  contextInstance.animation = null;
672
- var wrapperWidth = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.offsetWidth) || 0;
673
- var wrapperHeight = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.offsetHeight) || 0;
687
+ // See `handleAlignToBounds`: the velocity animation clamps against
688
+ // `bounds`, so they must reflect a size change seen during the pan.
689
+ if (contextInstance.isResizeAlignmentPending) {
690
+ handleCalculateBounds(contextInstance, scale);
691
+ }
692
+ var wrapperWidth = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.clientWidth) || 0;
693
+ var wrapperHeight = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.clientHeight) || 0;
674
694
  var contentWidth = ((contentComponent === null || contentComponent === void 0 ? void 0 : contentComponent.offsetWidth) || 0) * scale;
675
695
  var contentHeight = ((contentComponent === null || contentComponent === void 0 ? void 0 : contentComponent.offsetHeight) || 0) * scale;
676
696
  var isContentOverflowing = !contextInstance.setup.limitToBounds ||
@@ -708,8 +728,8 @@ function handleAlignToScaleBounds(contextInstance, mousePositionX, mousePosition
708
728
  }
709
729
  if (isDisabled || !wrapperComponent || !contextInstance.mounted)
710
730
  return;
711
- var mouseX = mousePositionX || wrapperComponent.offsetWidth / 2;
712
- var mouseY = mousePositionY || wrapperComponent.offsetHeight / 2;
731
+ var mouseX = mousePositionX || wrapperComponent.clientWidth / 2;
732
+ var mouseY = mousePositionY || wrapperComponent.clientHeight / 2;
713
733
  var targetScale = scale < minScale ? minScale : maxScale;
714
734
  var targetState = handleZoomToPoint(contextInstance, targetScale, mouseX, mouseY);
715
735
  if (targetState) {
@@ -789,6 +809,7 @@ var initialSetup = {
789
809
  limitToBounds: true,
790
810
  centerZoomedOut: false,
791
811
  centerOnInit: false,
812
+ fitOnInit: false,
792
813
  disablePadding: false,
793
814
  smooth: true,
794
815
  detached: false,
@@ -825,6 +846,14 @@ var initialSetup = {
825
846
  allowPanning: true,
826
847
  excluded: [],
827
848
  },
849
+ keyboard: {
850
+ disabled: true,
851
+ panStep: 50,
852
+ zoomStep: 0.25,
853
+ animationTime: 100,
854
+ animationType: "easeOut",
855
+ excluded: [],
856
+ },
828
857
  doubleClick: {
829
858
  disabled: false,
830
859
  step: 0.7,
@@ -954,8 +983,8 @@ function handleZoomToViewCenter(contextInstance, delta, step, animationTime, ani
954
983
  return Promise.resolve();
955
984
  }
956
985
  var effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
957
- var wrapperWidth = wrapperComponent.offsetWidth;
958
- var wrapperHeight = wrapperComponent.offsetHeight;
986
+ var wrapperWidth = wrapperComponent.clientWidth;
987
+ var wrapperHeight = wrapperComponent.clientHeight;
959
988
  var mouseX = (wrapperWidth / 2 - positionX) / scale;
960
989
  var mouseY = (wrapperHeight / 2 - positionY) / scale;
961
990
  var newScale = handleCalculateButtonZoom(contextInstance, delta, step);
@@ -966,13 +995,82 @@ function handleZoomToViewCenter(contextInstance, delta, step, animationTime, ani
966
995
  }
967
996
  return runZoomAnimation(contextInstance, targetState, effectiveAnimationTime, animationType);
968
997
  }
998
+ /**
999
+ * Runs a programmatic pan: fires `onPanningStart`/`onPanning`, animates to
1000
+ * `targetState` and fires `onPanningStop` once the animation time has
1001
+ * elapsed. Resolves when the animation has finished (or was interrupted).
1002
+ */
1003
+ function runPanAnimation(contextInstance, targetState, animationTime, animationType) {
1004
+ var _a, _b;
1005
+ var wrapperComponent = contextInstance.wrapperComponent;
1006
+ var _c = contextInstance.props, onPanningStart = _c.onPanningStart, onPanning = _c.onPanning, onPanningStop = _c.onPanningStop;
1007
+ var event = new MouseEvent("mousemove", { bubbles: true });
1008
+ var ctx = getContext(contextInstance);
1009
+ handleCallback(ctx, event, onPanningStart);
1010
+ handleCallback(ctx, event, onPanning);
1011
+ var done = animate(contextInstance, targetState, animationTime, animationType);
1012
+ 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);
1013
+ if (win) {
1014
+ win.setTimeout(function () {
1015
+ if (!contextInstance.mounted)
1016
+ return;
1017
+ handleCallback(getContext(contextInstance), event, onPanningStop);
1018
+ }, animationTime);
1019
+ }
1020
+ return done;
1021
+ }
1022
+ /**
1023
+ * Scale and centred position that fit the whole content into the wrapper
1024
+ * (`contain`) or fill the wrapper with it (`cover`) (#252).
1025
+ *
1026
+ * The fit scale is capped by `minFitScale`/`maxFitScale` first and by the
1027
+ * wrapper's own `minScale`/`maxScale` second — with the default `minScale` of
1028
+ * 1 the content is never shrunk, so lower `minScale` to fit large content.
1029
+ * Returns `null` until both elements have a size.
1030
+ */
1031
+ function calculateFitToView(contextInstance, mode, minFitScale, maxFitScale) {
1032
+ if (mode === void 0) { mode = "contain"; }
1033
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup;
1034
+ if (!wrapperComponent || !contentComponent)
1035
+ return null;
1036
+ var contentWidth = contentComponent.offsetWidth;
1037
+ var contentHeight = contentComponent.offsetHeight;
1038
+ var wrapperWidth = wrapperComponent.clientWidth;
1039
+ var wrapperHeight = wrapperComponent.clientHeight;
1040
+ if (!contentWidth || !contentHeight || !wrapperWidth || !wrapperHeight) {
1041
+ return null;
1042
+ }
1043
+ var ratioX = wrapperWidth / contentWidth;
1044
+ var ratioY = wrapperHeight / contentHeight;
1045
+ var scale = mode === "cover" ? Math.max(ratioX, ratioY) : Math.min(ratioX, ratioY);
1046
+ if (maxFitScale !== undefined)
1047
+ scale = Math.min(scale, maxFitScale);
1048
+ if (minFitScale !== undefined)
1049
+ scale = Math.max(scale, minFitScale);
1050
+ scale = checkZoomBounds(scale, setup.minScale, setup.maxScale, 0, false);
1051
+ return getCenterPosition(scale, wrapperComponent, contentComponent);
1052
+ }
969
1053
  function resetTransformations(contextInstance, animationTime, animationType, onResetTransformation) {
970
1054
  var setup = contextInstance.setup, wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
971
- var limitToBounds = setup.limitToBounds, centerOnInit = setup.centerOnInit;
1055
+ var limitToBounds = setup.limitToBounds, centerOnInit = setup.centerOnInit, fitOnInit = setup.fitOnInit;
972
1056
  var initialTransformation = createState(contextInstance.props);
973
1057
  var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
974
1058
  if (!wrapperComponent)
975
1059
  return Promise.resolve();
1060
+ // With `fitOnInit` the initial layout is the fitted one, so that is what a
1061
+ // reset returns to (#252).
1062
+ if (fitOnInit) {
1063
+ var fitted = calculateFitToView(contextInstance, fitOnInit === "cover" ? "cover" : "contain");
1064
+ if (fitted) {
1065
+ if (scale === fitted.scale &&
1066
+ positionX === fitted.positionX &&
1067
+ positionY === fitted.positionY) {
1068
+ return Promise.resolve();
1069
+ }
1070
+ onResetTransformation === null || onResetTransformation === void 0 ? void 0 : onResetTransformation();
1071
+ return runZoomAnimation(contextInstance, fitted, animationTime, animationType);
1072
+ }
1073
+ }
976
1074
  var targetPositionX = initialTransformation.positionX;
977
1075
  var targetPositionY = initialTransformation.positionY;
978
1076
  if (centerOnInit && contentComponent) {
@@ -1049,8 +1147,8 @@ function calculateZoomToRect(contextInstance, rect, customZoom, customOffsetX, c
1049
1147
  var nodeTop = nodeOffset.y;
1050
1148
  var nodeWidth = rect.width / state.scale;
1051
1149
  var nodeHeight = rect.height / state.scale;
1052
- var scaleX = wrapperComponent.offsetWidth / nodeWidth;
1053
- var scaleY = wrapperComponent.offsetHeight / nodeHeight;
1150
+ var scaleX = wrapperComponent.clientWidth / nodeWidth;
1151
+ var scaleY = wrapperComponent.clientHeight / nodeHeight;
1054
1152
  var targetScale = customZoom || Math.min(scaleX, scaleY);
1055
1153
  if (maxFitScale !== undefined) {
1056
1154
  targetScale = Math.min(targetScale, maxFitScale);
@@ -1242,6 +1340,52 @@ var zoomToElement = function (contextInstance) {
1242
1340
  return animate(contextInstance, targetState, (_c = options.animationTime) !== null && _c !== void 0 ? _c : animationTime, (_d = options.animationType) !== null && _d !== void 0 ? _d : animationType);
1243
1341
  };
1244
1342
  };
1343
+ /**
1344
+ * Fits the whole content into the viewport (`contain`, default) or fills the
1345
+ * viewport with it (`cover`), centred. Honours the wrapper's
1346
+ * `minScale`/`maxScale`; lower `minScale` to let large content shrink (#252).
1347
+ */
1348
+ var fitToView = function (contextInstance) {
1349
+ return function (options) {
1350
+ var _a, _b, _c;
1351
+ if (options === void 0) { options = {}; }
1352
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup;
1353
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
1354
+ return Promise.resolve();
1355
+ }
1356
+ var targetState = calculateFitToView(contextInstance, (_a = options.mode) !== null && _a !== void 0 ? _a : "contain", options.minScale, options.maxScale);
1357
+ if (!targetState)
1358
+ return Promise.resolve();
1359
+ var animationTime = setup.zoomAnimation.disabled
1360
+ ? 0
1361
+ : (_b = options.animationTime) !== null && _b !== void 0 ? _b : 200;
1362
+ return runZoomAnimation(contextInstance, targetState, animationTime, (_c = options.animationType) !== null && _c !== void 0 ? _c : "easeOut");
1363
+ };
1364
+ };
1365
+ /**
1366
+ * Pans by a pixel delta (positive x moves the content right), limited to the
1367
+ * bounds when `limitToBounds` is on. Backs the keyboard arrows and is handy
1368
+ * for directional buttons (#254, #527).
1369
+ */
1370
+ var panBy = function (contextInstance) {
1371
+ return function (deltaX, deltaY, animationTime, animationType) {
1372
+ if (animationTime === void 0) { animationTime = 200; }
1373
+ if (animationType === void 0) { animationType = "easeOut"; }
1374
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup, state = contextInstance.state;
1375
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
1376
+ return Promise.resolve();
1377
+ }
1378
+ if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY)) {
1379
+ return Promise.resolve();
1380
+ }
1381
+ var bounds = handleCalculateBounds(contextInstance, state.scale);
1382
+ var _a = getMouseBoundedPosition(state.positionX + deltaX, state.positionY + deltaY, bounds, setup.limitToBounds, 0, 0, wrapperComponent), x = _a.x, y = _a.y;
1383
+ if (x === state.positionX && y === state.positionY) {
1384
+ return Promise.resolve();
1385
+ }
1386
+ return runPanAnimation(contextInstance, { scale: state.scale, positionX: x, positionY: y }, animationTime, animationType);
1387
+ };
1388
+ };
1245
1389
 
1246
1390
  var getControls = function (contextInstance) {
1247
1391
  return {
@@ -1256,6 +1400,8 @@ var getControls = function (contextInstance) {
1256
1400
  zoomToPoint: zoomToPoint(contextInstance),
1257
1401
  clientToContent: clientToContent(contextInstance),
1258
1402
  contentToClient: contentToClient(contextInstance),
1403
+ fitToView: fitToView(contextInstance),
1404
+ panBy: panBy(contextInstance),
1259
1405
  };
1260
1406
  };
1261
1407
  var getState = function (contextInstance) {
@@ -1364,8 +1510,8 @@ var getMatrixTransformStyles = function (x, y, scale) {
1364
1510
  var getCenterPosition = function (scale, wrapperComponent, contentComponent) {
1365
1511
  var contentWidth = contentComponent.offsetWidth * scale;
1366
1512
  var contentHeight = contentComponent.offsetHeight * scale;
1367
- var centerPositionX = (wrapperComponent.offsetWidth - contentWidth) / 2;
1368
- var centerPositionY = (wrapperComponent.offsetHeight - contentHeight) / 2;
1513
+ var centerPositionX = (wrapperComponent.clientWidth - contentWidth) / 2;
1514
+ var centerPositionY = (wrapperComponent.clientHeight - contentHeight) / 2;
1369
1515
  return {
1370
1516
  scale: scale,
1371
1517
  positionX: centerPositionX,
@@ -1405,6 +1551,270 @@ function mergeRefs(refs) {
1405
1551
  */
1406
1552
  var useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
1407
1553
 
1554
+ /**
1555
+ * Keys handled by the keyboard navigation (#254). Arrows pan by
1556
+ * `keyboard.panStep`, plus/minus zoom by `keyboard.zoomStep`, `0` resets.
1557
+ */
1558
+ var KEYBOARD_KEYS = {
1559
+ panLeft: ["ArrowLeft"],
1560
+ panRight: ["ArrowRight"],
1561
+ panUp: ["ArrowUp"],
1562
+ panDown: ["ArrowDown"],
1563
+ zoomIn: ["+", "="],
1564
+ zoomOut: ["-", "_"],
1565
+ reset: ["0"],
1566
+ };
1567
+ var isHandledKey = function (key) {
1568
+ return Object.values(KEYBOARD_KEYS).some(function (keys) {
1569
+ return keys.includes(key);
1570
+ });
1571
+ };
1572
+ /**
1573
+ * Wrapper `keydown` handler. Returns `true` when the key was consumed (and
1574
+ * its default action prevented), `false` when it was left to the browser.
1575
+ *
1576
+ * Ignored on purpose: modifier combos (ctrl/cmd/alt, so browser shortcuts
1577
+ * such as cmd+0 / cmd+- keep working), editable targets (typing in an input
1578
+ * inside the content) and `keyboard.excluded` targets.
1579
+ */
1580
+ function handleKeyboardNavigation(contextInstance, event) {
1581
+ var _a = contextInstance.setup, disabled = _a.disabled, keyboard = _a.keyboard, panning = _a.panning;
1582
+ if (disabled || keyboard.disabled)
1583
+ return false;
1584
+ if (event.defaultPrevented)
1585
+ return false;
1586
+ if (event.ctrlKey || event.metaKey || event.altKey)
1587
+ return false;
1588
+ if (!isHandledKey(event.key))
1589
+ return false;
1590
+ var target = event.target;
1591
+ if (isEditableTarget(target))
1592
+ return false;
1593
+ if (target &&
1594
+ typeof target.matches === "function" &&
1595
+ isExcludedNode(target, keyboard.excluded)) {
1596
+ return false;
1597
+ }
1598
+ var panStep = keyboard.panStep, zoomStep = keyboard.zoomStep, animationTime = keyboard.animationTime, animationType = keyboard.animationType;
1599
+ var controls = getControls(contextInstance);
1600
+ var key = event.key;
1601
+ // Arrow keys move the *viewport*, like scrolling: pressing left reveals
1602
+ // content on the left, so the content itself shifts right (position grows).
1603
+ var stepX = panning.lockAxisX ? 0 : panStep;
1604
+ var stepY = panning.lockAxisY ? 0 : panStep;
1605
+ if (key === "ArrowLeft") {
1606
+ controls.panBy(stepX, 0, animationTime, animationType);
1607
+ }
1608
+ else if (key === "ArrowRight") {
1609
+ controls.panBy(-stepX, 0, animationTime, animationType);
1610
+ }
1611
+ else if (key === "ArrowUp") {
1612
+ controls.panBy(0, stepY, animationTime, animationType);
1613
+ }
1614
+ else if (key === "ArrowDown") {
1615
+ controls.panBy(0, -stepY, animationTime, animationType);
1616
+ }
1617
+ else if (key === "+" || key === "=") {
1618
+ controls.zoomIn(zoomStep, animationTime, animationType);
1619
+ }
1620
+ else if (key === "-" || key === "_") {
1621
+ controls.zoomOut(zoomStep, animationTime, animationType);
1622
+ }
1623
+ else if (key === "0") {
1624
+ controls.resetTransform(animationTime, animationType);
1625
+ }
1626
+ if (event.cancelable) {
1627
+ event.preventDefault();
1628
+ }
1629
+ // Consumed: hosts that forward key presses (Storybook's manager, app-level
1630
+ // shortcuts) must not also act on them.
1631
+ event.stopPropagation();
1632
+ return true;
1633
+ }
1634
+
1635
+ var measureSizes = function (wrapperComponent, contentComponent) { return ({
1636
+ wrapperWidth: wrapperComponent.offsetWidth,
1637
+ wrapperHeight: wrapperComponent.offsetHeight,
1638
+ contentWidth: contentComponent.offsetWidth,
1639
+ contentHeight: contentComponent.offsetHeight,
1640
+ }); };
1641
+ var hasSizeChanged = function (previous, current) {
1642
+ return !previous ||
1643
+ previous.wrapperWidth !== current.wrapperWidth ||
1644
+ previous.wrapperHeight !== current.wrapperHeight ||
1645
+ previous.contentWidth !== current.contentWidth ||
1646
+ previous.contentHeight !== current.contentHeight;
1647
+ };
1648
+ /**
1649
+ * A pointer is physically held: a mouse/touch pan or a pinch. The bounds
1650
+ * belong to that gesture until it is released (moving the content under a
1651
+ * held cursor is what feels like a jump).
1652
+ */
1653
+ var isPointerGestureActive = function (contextInstance) { return contextInstance.isPanning || contextInstance.isPinching; };
1654
+ /**
1655
+ * Any gesture is in progress: a held pointer, or a wheel sequence whose stop
1656
+ * timers have not fired yet.
1657
+ */
1658
+ var isGestureActive = function (contextInstance) {
1659
+ return isPointerGestureActive(contextInstance) ||
1660
+ contextInstance.wheelStopEventTimer !== null ||
1661
+ contextInstance.wheelAnimationTimer !== null;
1662
+ };
1663
+ /**
1664
+ * Recomputes the bounds for the current scale and content/wrapper sizes and
1665
+ * returns the state the transform has to move to so it sits inside them.
1666
+ * Returns `null` when the transform is already inside the bounds or when
1667
+ * nothing limits it (`limitToBounds` and `centerZoomedOut` both off).
1668
+ *
1669
+ * The bounds are stored on the instance as a side effect, so gestures that
1670
+ * follow a resize clamp against the fresh sizes even when no move is needed.
1671
+ */
1672
+ function calculateResizeAlignment(contextInstance) {
1673
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup, state = contextInstance.state;
1674
+ if (!wrapperComponent || !contentComponent)
1675
+ return null;
1676
+ var bounds = handleCalculateBounds(contextInstance, state.scale);
1677
+ // Same rule as the post-pan alignment (`handlePanToBounds`).
1678
+ var limitToBounds = setup.limitToBounds, centerZoomedOut = setup.centerZoomedOut;
1679
+ if (!limitToBounds && !centerZoomedOut)
1680
+ return null;
1681
+ var _a = getMouseBoundedPosition(state.positionX, state.positionY, bounds, true, 0, 0, wrapperComponent), x = _a.x, y = _a.y;
1682
+ // `boundLimiter` rounds to two decimals; compare against the same rounding
1683
+ // so an in-bounds transform never starts a zero-length animation.
1684
+ var isAligned = x === roundNumber(state.positionX, 2) &&
1685
+ y === roundNumber(state.positionY, 2);
1686
+ if (isAligned)
1687
+ return null;
1688
+ return { scale: state.scale, positionX: x, positionY: y };
1689
+ }
1690
+ var stopResizeTracking = function (contextInstance) {
1691
+ contextInstance.animation = null;
1692
+ contextInstance.animationFrame = null;
1693
+ contextInstance.isAnimating = false;
1694
+ contextInstance.resizeAnimation = null;
1695
+ };
1696
+ /**
1697
+ * Eases the transform towards the current bounds, frame by frame, until it
1698
+ * rests on them.
1699
+ *
1700
+ * The bounds are re-read every frame, so a size that keeps changing (a CSS
1701
+ * height transition, a layout settling over several frames) is followed
1702
+ * smoothly — the content edge trails the moving bound by a few pixels
1703
+ * instead of lagging behind a stale target and bursting after it. Each
1704
+ * frame closes a fixed fraction of the remaining gap (exponential
1705
+ * smoothing), tuned so a one-off step still settles within
1706
+ * `autoAlignment.animationTime`.
1707
+ */
1708
+ function startResizeTracking(contextInstance) {
1709
+ var animationTime = contextInstance.setup.autoAlignment.animationTime;
1710
+ // Over 99% of a step is covered after `animationTime`; the sub-pixel rest
1711
+ // snaps (see `isSettled`).
1712
+ var tau = Math.max(animationTime / 5, 1);
1713
+ handleCancelAnimation(contextInstance);
1714
+ var lastFrameTime = Date.now();
1715
+ var track = function () {
1716
+ if (!contextInstance.mounted || contextInstance.animation !== track) {
1717
+ return;
1718
+ }
1719
+ var now = Date.now();
1720
+ var frameTime = Math.max(now - lastFrameTime, 1);
1721
+ lastFrameTime = now;
1722
+ var targetState = calculateResizeAlignment(contextInstance);
1723
+ if (!targetState) {
1724
+ // Back inside the bounds (the content grew again).
1725
+ stopResizeTracking(contextInstance);
1726
+ return;
1727
+ }
1728
+ var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
1729
+ var factor = 1 - Math.exp(-frameTime / tau);
1730
+ var x = positionX + (targetState.positionX - positionX) * factor;
1731
+ var y = positionY + (targetState.positionY - positionY) * factor;
1732
+ var isSettled = Math.abs(targetState.positionX - x) < 0.5 &&
1733
+ Math.abs(targetState.positionY - y) < 0.5;
1734
+ if (isSettled) {
1735
+ x = targetState.positionX;
1736
+ y = targetState.positionY;
1737
+ }
1738
+ contextInstance.isAnimating = !isSettled;
1739
+ contextInstance.setState(scale, x, y);
1740
+ if (isSettled) {
1741
+ stopResizeTracking(contextInstance);
1742
+ return;
1743
+ }
1744
+ contextInstance.animationFrame = requestAnimationFrame(track);
1745
+ };
1746
+ contextInstance.animation = track;
1747
+ contextInstance.resizeAnimation = track;
1748
+ contextInstance.animationResolve = null;
1749
+ contextInstance.animationFrame = requestAnimationFrame(track);
1750
+ }
1751
+ /**
1752
+ * Brings the transform back into the bounds after the content or the
1753
+ * wrapper changed size — immediately: a move still in flight (inertia, an
1754
+ * alignment, a programmatic animation) is cancelled and a trackpad sequence
1755
+ * simply continues against the fresh bounds, so a layout that collapses
1756
+ * while the user scrolls aligns right away.
1757
+ *
1758
+ * Two things are left alone. A pointer that is still held owns the bounds
1759
+ * until it is released (replacing them mid-drag makes the next move clamp
1760
+ * against a new limit and jump under the cursor); the release then aligns
1761
+ * against the fresh bounds (`handleAlignToBounds`). And an animation that is
1762
+ * bringing the scale back inside `minScale`/`maxScale` must finish, because
1763
+ * the tracking only moves the position. Both come back here afterwards via
1764
+ * `flushResizeAlignment`.
1765
+ */
1766
+ function handleResizeAlignment(contextInstance) {
1767
+ if (contextInstance.setup.disabled) {
1768
+ // Nothing may move, but the next gesture must see the right limits.
1769
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
1770
+ return;
1771
+ }
1772
+ if (isPointerGestureActive(contextInstance)) {
1773
+ contextInstance.isResizeAlignmentPending = true;
1774
+ return;
1775
+ }
1776
+ var isOwnAnimation = contextInstance.animation !== null &&
1777
+ contextInstance.animation === contextInstance.resizeAnimation;
1778
+ if (contextInstance.animation && !isOwnAnimation) {
1779
+ var scale = contextInstance.state.scale;
1780
+ var _a = contextInstance.setup, minScale = _a.minScale, maxScale = _a.maxScale;
1781
+ if (scale < minScale || scale > maxScale) {
1782
+ contextInstance.isResizeAlignmentPending = true;
1783
+ return;
1784
+ }
1785
+ handleCancelAnimation(contextInstance);
1786
+ }
1787
+ var targetState = calculateResizeAlignment(contextInstance);
1788
+ if (!targetState) {
1789
+ if (isOwnAnimation)
1790
+ stopResizeTracking(contextInstance);
1791
+ return;
1792
+ }
1793
+ // The tracking loop re-reads the bounds itself; it just keeps running.
1794
+ if (isOwnAnimation)
1795
+ return;
1796
+ if (contextInstance.setup.autoAlignment.animationTime === 0) {
1797
+ contextInstance.setState(targetState.scale, targetState.positionX, targetState.positionY);
1798
+ return;
1799
+ }
1800
+ startResizeTracking(contextInstance);
1801
+ }
1802
+ /**
1803
+ * Entry point for the size observer: ignores notifications that carry no
1804
+ * size change (the observer's initial delivery, style-only changes) and
1805
+ * aligns on the ones that do.
1806
+ */
1807
+ function handleSizeChange(contextInstance) {
1808
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
1809
+ if (!wrapperComponent || !contentComponent)
1810
+ return;
1811
+ var sizes = measureSizes(wrapperComponent, contentComponent);
1812
+ if (!hasSizeChanged(contextInstance.measuredSizes, sizes))
1813
+ return;
1814
+ contextInstance.measuredSizes = sizes;
1815
+ handleResizeAlignment(contextInstance);
1816
+ }
1817
+
1408
1818
  var isWheelAllowed = function (contextInstance, event) {
1409
1819
  var _a = contextInstance.setup.wheel, disabled = _a.disabled, wheelDisabled = _a.wheelDisabled, touchPadDisabled = _a.touchPadDisabled, excluded = _a.excluded;
1410
1820
  var isInitialized = contextInstance.isInitialized, isPanning = contextInstance.isPanning;
@@ -1630,6 +2040,7 @@ var handleWheelStop = function (contextInstance, event) {
1630
2040
  return;
1631
2041
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
1632
2042
  contextInstance.wheelAnimationTimer = null;
2043
+ contextInstance.flushResizeAlignment();
1633
2044
  }, wheelAnimationTime);
1634
2045
  // Wheel stop event
1635
2046
  var hasStoppedZooming = handleWheelZoomStop(contextInstance, event);
@@ -1641,6 +2052,7 @@ var handleWheelStop = function (contextInstance, event) {
1641
2052
  contextInstance.wheelStopEventTimer = null;
1642
2053
  handleCallback(getContext(contextInstance), event, onWheelStop);
1643
2054
  handleCallback(getContext(contextInstance), event, onZoomStop);
2055
+ contextInstance.flushResizeAlignment();
1644
2056
  }, wheelStopEventTime);
1645
2057
  }
1646
2058
  };
@@ -1650,8 +2062,13 @@ var handleWheelPanningStart = function (contextInstance, event) {
1650
2062
  handleCancelAnimation(contextInstance);
1651
2063
  if (!contextInstance.wheelStopEventTimer) {
1652
2064
  // 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);
2065
+ // content size, not the ones measured at mount (#396, #433). Only at the
2066
+ // start of a wheel sequence though — mid-sequence the gesture owns them
2067
+ // (see `handleResizeAlignment`), otherwise a content resize would make
2068
+ // the next event clamp against a new limit and jump.
2069
+ if (!contextInstance.wheelAnimationTimer) {
2070
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
2071
+ }
1655
2072
  handleCallback(getContext(contextInstance), event, onWheelStart);
1656
2073
  handleCallback(getContext(contextInstance), event, onPanningStart);
1657
2074
  }
@@ -1665,6 +2082,7 @@ var handleWheelPanningStop = function (contextInstance, event) {
1665
2082
  return;
1666
2083
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
1667
2084
  contextInstance.wheelAnimationTimer = null;
2085
+ contextInstance.flushResizeAlignment();
1668
2086
  }, wheelAnimationTime);
1669
2087
  // Wheel stop event
1670
2088
  var hasStoppedZooming = handleWheelZoomStop(contextInstance, event);
@@ -1676,6 +2094,7 @@ var handleWheelPanningStop = function (contextInstance, event) {
1676
2094
  contextInstance.wheelStopEventTimer = null;
1677
2095
  handleCallback(getContext(contextInstance), event, onWheelStop);
1678
2096
  handleCallback(getContext(contextInstance), event, onPanningStop);
2097
+ contextInstance.flushResizeAlignment();
1679
2098
  }, wheelStopEventTime);
1680
2099
  }
1681
2100
  };
@@ -1873,8 +2292,20 @@ var ZoomPanPinch = /** @class */ (function () {
1873
2292
  this.animationResolve = null;
1874
2293
  // init helpers
1875
2294
  this.initObserverTimer = null;
2295
+ // `centerOnInit`/`fitOnInit` wait for content that has no size yet
2296
+ this.isInitialLayoutPending = false;
2297
+ // resize helpers: last measured sizes and an alignment postponed until the
2298
+ // running animation settles
2299
+ this.measuredSizes = null;
2300
+ this.isResizeAlignmentPending = false;
2301
+ // The alignment animation started by a resize, so further size changes can
2302
+ // retarget it instead of waiting for it (compared by identity to
2303
+ // `animation`, which is null once it has finished).
2304
+ this.resizeAnimation = null;
1876
2305
  // key press
1877
2306
  this.pressedKeys = {};
2307
+ // text selection lock while a gesture is active (#467)
2308
+ this.selectionLock = null;
1878
2309
  this.mount = function () {
1879
2310
  _this.mounted = true;
1880
2311
  _this.initializeWindowEvents();
@@ -1890,7 +2321,12 @@ var ZoomPanPinch = /** @class */ (function () {
1890
2321
  // Setup first: bounds depend on the new props (min/max positions,
1891
2322
  // centerZoomedOut, disablePadding).
1892
2323
  _this.setup = createSetup(newProps);
1893
- if (_this.wrapperComponent && _this.contentComponent) {
2324
+ // A gesture owns the bounds until it ends (see `handleResizeAlignment`):
2325
+ // replacing them mid-drag makes the next move clamp against a new limit
2326
+ // and jump. The gesture start recalculates them anyway.
2327
+ if (_this.wrapperComponent &&
2328
+ _this.contentComponent &&
2329
+ !isGestureActive(_this)) {
1894
2330
  handleCalculateBounds(_this, _this.state.scale);
1895
2331
  }
1896
2332
  };
@@ -1944,7 +2380,12 @@ var ZoomPanPinch = /** @class */ (function () {
1944
2380
  _this.cleanupWrapperEvents();
1945
2381
  _this.clearTimers();
1946
2382
  handleCancelAnimation(_this);
2383
+ _this.unlockTextSelection();
1947
2384
  (_e = _this.observer) === null || _e === void 0 ? void 0 : _e.disconnect();
2385
+ _this.observer = undefined;
2386
+ _this.isInitialLayoutPending = false;
2387
+ _this.isResizeAlignmentPending = false;
2388
+ _this.resizeAnimation = null;
1948
2389
  };
1949
2390
  this.cleanupWrapperEvents = function () {
1950
2391
  var wrapper = _this.wrapperComponent;
@@ -1953,6 +2394,7 @@ var ZoomPanPinch = /** @class */ (function () {
1953
2394
  var passive = makePassiveEventOption();
1954
2395
  wrapper.removeEventListener("wheel", _this.onWheelZoom, passive);
1955
2396
  wrapper.removeEventListener("dblclick", _this.onDoubleClick, passive);
2397
+ wrapper.removeEventListener("keydown", _this.onKeyboardNavigation, passive);
1956
2398
  wrapper.removeEventListener("touchstart", _this.onTouchPanningStart, passive);
1957
2399
  wrapper.removeEventListener("touchmove", _this.onTouchPanning, passive);
1958
2400
  wrapper.removeEventListener("touchend", _this.onTouchPanningStop, passive);
@@ -1962,44 +2404,88 @@ var ZoomPanPinch = /** @class */ (function () {
1962
2404
  var passive = makePassiveEventOption();
1963
2405
  wrapper.addEventListener("wheel", _this.onWheelZoom, passive);
1964
2406
  wrapper.addEventListener("dblclick", _this.onDoubleClick, passive);
2407
+ wrapper.addEventListener("keydown", _this.onKeyboardNavigation, passive);
1965
2408
  wrapper.addEventListener("touchstart", _this.onTouchPanningStart, passive);
1966
2409
  wrapper.addEventListener("touchmove", _this.onTouchPanning, passive);
1967
2410
  wrapper.addEventListener("touchend", _this.onTouchPanningStop, passive);
1968
2411
  };
1969
- this.handleInitialize = function (contentComponent) {
1970
- var _a;
1971
- var centerOnInit = _this.setup.centerOnInit;
2412
+ this.handleInitialize = function () {
2413
+ var _a = _this.setup, centerOnInit = _a.centerOnInit, fitOnInit = _a.fitOnInit;
1972
2414
  _this.applyTransformation();
1973
2415
  _this.onInitCallbacks.forEach(function (callback) { return callback(getContext(_this)); });
1974
- if (centerOnInit) {
1975
- _this.setCenter();
1976
- (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1977
- _this.observer = new ResizeObserver(function () {
1978
- var _a;
1979
- var currentWidth = contentComponent.offsetWidth;
1980
- var currentHeight = contentComponent.offsetHeight;
1981
- if (currentWidth > 0 || currentHeight > 0) {
1982
- _this.onInitCallbacks.forEach(function (callback) {
1983
- return callback(getContext(_this));
1984
- });
1985
- _this.setCenter();
1986
- (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1987
- }
1988
- });
1989
- // TODO: CHANGE to first interaction?
1990
- // if nothing about the contentComponent has changed after 5 seconds, disconnect the observer
2416
+ if (centerOnInit || fitOnInit) {
2417
+ var applied = _this.applyInitialLayout();
2418
+ // Content without a size yet (an image still loading) gets its layout
2419
+ // applied again by `onSizeChange` once it has one. Once a real layout
2420
+ // exists, stop waiting after 5 seconds so a later resize aligns instead
2421
+ // of re-centring. Until then keep waiting: in a hidden tab the observer
2422
+ // may not deliver for a long time and the first layout must still be
2423
+ // the fitted/centred one.
2424
+ _this.isInitialLayoutPending = true;
1991
2425
  if (_this.initObserverTimer)
1992
2426
  clearTimeout(_this.initObserverTimer);
1993
- _this.initObserverTimer = setTimeout(function () {
1994
- var _a;
1995
- _this.initObserverTimer = null;
1996
- (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1997
- }, 5000);
1998
- // Start observing the target node for configured mutations
1999
- _this.observer.observe(contentComponent);
2427
+ if (applied) {
2428
+ _this.initObserverTimer = setTimeout(function () {
2429
+ _this.initObserverTimer = null;
2430
+ _this.isInitialLayoutPending = false;
2431
+ }, 5000);
2432
+ }
2000
2433
  }
2001
2434
  };
2002
2435
  /// ///////
2436
+ // Size changes
2437
+ /// ///////
2438
+ // One observer for the whole lifetime of the instance: it finishes the
2439
+ // initial layout for late-sized content and, after that, keeps the
2440
+ // transform inside the bounds whenever the content or the wrapper changes
2441
+ // size (children re-rendering with another size, images loading, the
2442
+ // viewport resizing).
2443
+ this.observeSizes = function (wrapperComponent, contentComponent) {
2444
+ var _a;
2445
+ (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
2446
+ _this.observer = undefined;
2447
+ _this.measuredSizes = measureSizes(wrapperComponent, contentComponent);
2448
+ if (typeof ResizeObserver === "undefined")
2449
+ return;
2450
+ _this.observer = new ResizeObserver(_this.onSizeChange);
2451
+ _this.observer.observe(wrapperComponent);
2452
+ _this.observer.observe(contentComponent);
2453
+ };
2454
+ this.onSizeChange = function () {
2455
+ var _a = _this, wrapperComponent = _a.wrapperComponent, contentComponent = _a.contentComponent;
2456
+ if (!_this.mounted || !wrapperComponent || !contentComponent)
2457
+ return;
2458
+ if (_this.isInitialLayoutPending) {
2459
+ // Both boxes must be laid out: a wrapper that is sized late (hidden
2460
+ // tab, collapsed panel) would otherwise get a fit against a 0px box.
2461
+ var hasSize = (contentComponent.offsetWidth > 0 ||
2462
+ contentComponent.offsetHeight > 0) &&
2463
+ wrapperComponent.clientWidth > 0 &&
2464
+ wrapperComponent.clientHeight > 0;
2465
+ if (!hasSize)
2466
+ return;
2467
+ _this.isInitialLayoutPending = false;
2468
+ if (_this.initObserverTimer)
2469
+ clearTimeout(_this.initObserverTimer);
2470
+ _this.initObserverTimer = null;
2471
+ _this.onInitCallbacks.forEach(function (callback) { return callback(getContext(_this)); });
2472
+ _this.applyInitialLayout();
2473
+ _this.measuredSizes = measureSizes(wrapperComponent, contentComponent);
2474
+ handleCalculateBounds(_this, _this.state.scale);
2475
+ return;
2476
+ }
2477
+ handleSizeChange(_this);
2478
+ };
2479
+ // Called once a gesture or an animation has ended, so a resize seen while
2480
+ // it ran is checked against the settled state (it may postpone itself
2481
+ // again when another gesture or animation is still running).
2482
+ this.flushResizeAlignment = function () {
2483
+ if (!_this.isResizeAlignmentPending)
2484
+ return;
2485
+ _this.isResizeAlignmentPending = false;
2486
+ handleResizeAlignment(_this);
2487
+ };
2488
+ /// ///////
2003
2489
  // Zoom
2004
2490
  /// ///////
2005
2491
  this.onWheelZoom = function (event) {
@@ -2048,9 +2534,11 @@ var ZoomPanPinch = /** @class */ (function () {
2048
2534
  // Pan
2049
2535
  /// ///////
2050
2536
  this.onPanningStart = function (event) {
2051
- var disabled = _this.setup.disabled;
2537
+ var _a = _this.setup, disabled = _a.disabled, panning = _a.panning;
2052
2538
  var onPanningStart = _this.props.onPanningStart;
2053
- if (disabled)
2539
+ // With panning off the mousedown is not ours: no pan state, no
2540
+ // preventDefault, and native text selection keeps working (#467).
2541
+ if (disabled || panning.disabled)
2054
2542
  return;
2055
2543
  _this.syncModifierKeys(event);
2056
2544
  var isAllowed = isPanningStartAllowed(_this, event);
@@ -2071,6 +2559,8 @@ var ZoomPanPinch = /** @class */ (function () {
2071
2559
  event.stopPropagation();
2072
2560
  handleCancelAnimation(_this);
2073
2561
  handlePanningStart(_this, event);
2562
+ _this.lockTextSelection();
2563
+ _this.focusForKeyboard();
2074
2564
  handleCallback(getContext(_this), event, onPanningStart);
2075
2565
  };
2076
2566
  this.onPanning = function (event) {
@@ -2102,8 +2592,10 @@ var ZoomPanPinch = /** @class */ (function () {
2102
2592
  var velocityDisabled = _this.setup.panning.velocityDisabled;
2103
2593
  var onPanningStop = _this.props.onPanningStop;
2104
2594
  if (_this.isPanning) {
2595
+ _this.unlockTextSelection();
2105
2596
  handlePanningEnd(_this, velocityDisabled);
2106
2597
  handleCallback(getContext(_this), event, onPanningStop);
2598
+ _this.flushResizeAlignment();
2107
2599
  }
2108
2600
  };
2109
2601
  /// ///////
@@ -2141,6 +2633,7 @@ var ZoomPanPinch = /** @class */ (function () {
2141
2633
  if (_this.pinchStartScale) {
2142
2634
  handlePinchStop(_this);
2143
2635
  handleCallback(getContext(_this), event, onPinchStop);
2636
+ _this.flushResizeAlignment();
2144
2637
  }
2145
2638
  };
2146
2639
  /// ///////
@@ -2167,10 +2660,12 @@ var ZoomPanPinch = /** @class */ (function () {
2167
2660
  var isPinchAction = touches.length === 2;
2168
2661
  var isAllowed = isPanningStartAllowed(_this, event);
2169
2662
  if (isPanningAction) {
2170
- if (!isAllowed)
2663
+ if (!isAllowed || _this.setup.panning.disabled)
2171
2664
  return;
2172
2665
  handleCancelAnimation(_this);
2173
2666
  handlePanningStart(_this, event);
2667
+ _this.lockTextSelection();
2668
+ _this.focusForKeyboard();
2174
2669
  handleCallback(getContext(_this), event, onPanningStart);
2175
2670
  }
2176
2671
  if (isPinchAction) {
@@ -2232,6 +2727,8 @@ var ZoomPanPinch = /** @class */ (function () {
2232
2727
  _this.isPanning = false;
2233
2728
  _this.startCoords = null;
2234
2729
  }
2730
+ _this.unlockTextSelection();
2731
+ _this.flushResizeAlignment();
2235
2732
  };
2236
2733
  // Iframe focus problem (e.g. Storybook):
2237
2734
  //
@@ -2284,6 +2781,78 @@ var ZoomPanPinch = /** @class */ (function () {
2284
2781
  }
2285
2782
  return Boolean(keys.every(function (key) { return _this.pressedKeys[key]; }));
2286
2783
  };
2784
+ /// ///////
2785
+ // Keyboard
2786
+ /// ///////
2787
+ this.onKeyboardNavigation = function (event) {
2788
+ handleKeyboardNavigation(_this, event);
2789
+ };
2790
+ // A pan start cancels the mousedown, which also cancels the focus the
2791
+ // click would have given the wrapper — so with keyboard navigation on,
2792
+ // focus it explicitly or the arrow keys never reach it.
2793
+ this.focusForKeyboard = function () {
2794
+ var _a;
2795
+ var wrapper = _this.wrapperComponent;
2796
+ if (!wrapper || _this.setup.keyboard.disabled)
2797
+ return;
2798
+ var active = (_a = wrapper.ownerDocument) === null || _a === void 0 ? void 0 : _a.activeElement;
2799
+ if (active && wrapper.contains(active))
2800
+ return;
2801
+ if (typeof wrapper.focus === "function") {
2802
+ wrapper.focus({ preventScroll: true });
2803
+ }
2804
+ };
2805
+ /// ///////
2806
+ // Text selection (#467)
2807
+ /// ///////
2808
+ // The stylesheet no longer disables text selection globally, so users can
2809
+ // select and copy content. While a pan gesture is active the wrapper gets
2810
+ // an inline `user-select: none` so the drag does not also select text.
2811
+ this.lockTextSelection = function () {
2812
+ var wrapper = _this.wrapperComponent;
2813
+ if (!wrapper || _this.selectionLock)
2814
+ return;
2815
+ _this.selectionLock = {
2816
+ userSelect: wrapper.style.userSelect,
2817
+ webkitUserSelect: wrapper.style.webkitUserSelect,
2818
+ };
2819
+ wrapper.style.userSelect = "none";
2820
+ wrapper.style.webkitUserSelect = "none";
2821
+ };
2822
+ this.unlockTextSelection = function () {
2823
+ var lock = _this.selectionLock;
2824
+ _this.selectionLock = null;
2825
+ var wrapper = _this.wrapperComponent;
2826
+ if (!wrapper || !lock)
2827
+ return;
2828
+ wrapper.style.userSelect = lock.userSelect;
2829
+ wrapper.style.webkitUserSelect = lock.webkitUserSelect;
2830
+ };
2831
+ /// ///////
2832
+ // Initial layout
2833
+ /// ///////
2834
+ // `fitOnInit` wins over `centerOnInit` (a fit is always centred). Falls
2835
+ // back to centring while the content has no size yet; `onSizeChange`
2836
+ // re-runs this once it does. Returns whether both boxes had a size, i.e.
2837
+ // whether this was a real initial layout.
2838
+ this.applyInitialLayout = function () {
2839
+ var fitOnInit = _this.setup.fitOnInit;
2840
+ var _a = _this, wrapperComponent = _a.wrapperComponent, contentComponent = _a.contentComponent;
2841
+ var hasSizes = !!wrapperComponent &&
2842
+ !!contentComponent &&
2843
+ wrapperComponent.clientWidth > 0 &&
2844
+ wrapperComponent.clientHeight > 0 &&
2845
+ (contentComponent.offsetWidth > 0 || contentComponent.offsetHeight > 0);
2846
+ if (fitOnInit) {
2847
+ var fitted = calculateFitToView(_this, fitOnInit === "cover" ? "cover" : "contain");
2848
+ if (fitted) {
2849
+ _this.setState(fitted.scale, fitted.positionX, fitted.positionY);
2850
+ return hasSizes;
2851
+ }
2852
+ }
2853
+ _this.setCenter();
2854
+ return hasSizes;
2855
+ };
2287
2856
  this.setCenter = function () {
2288
2857
  if (_this.wrapperComponent && _this.contentComponent) {
2289
2858
  var targetState = getCenterPosition(_this.state.scale, _this.wrapperComponent, _this.contentComponent);
@@ -2376,7 +2945,8 @@ var ZoomPanPinch = /** @class */ (function () {
2376
2945
  _this.contentComponent = contentComponent;
2377
2946
  handleCalculateBounds(_this, _this.state.scale);
2378
2947
  _this.handleInitializeWrapperEvents(wrapperComponent);
2379
- _this.handleInitialize(contentComponent);
2948
+ _this.handleInitialize();
2949
+ _this.observeSizes(wrapperComponent, contentComponent);
2380
2950
  _this.initializeWindowEvents();
2381
2951
  _this.isInitialized = true;
2382
2952
  var ctx = getContext(_this);
@@ -2684,12 +3254,13 @@ function styleInject(css, ref) {
2684
3254
  }
2685
3255
  }
2686
3256
 
2687
- var css_248z = ".transform-component-module_wrapper__SPB86 {\n position: relative;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n overflow: hidden;\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Safari */\n -khtml-user-select: none; /* Konqueror HTML */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Edge */\n user-select: none;\n margin: 0;\n padding: 0;\n transform: translate3d(0, 0, 0);\n}\n.transform-component-module_content__FBWxo {\n display: flex;\n flex-wrap: wrap;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n margin: 0;\n padding: 0;\n transform-origin: 0% 0%;\n}\n.transform-component-module_content__FBWxo img {\n pointer-events: none;\n}\n.transform-component-module_infiniteGrid__Z-aP3 {\n position: absolute;\n inset: 0;\n pointer-events: none;\n background-image: radial-gradient(\n circle,\n rgba(0, 0, 0, 0.12) 1px,\n transparent 1px\n );\n background-size: 20px 20px;\n background-position: 0 0;\n}\n";
3257
+ var css_248z = ".transform-component-module_wrapper__SPB86 {\n position: relative;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n overflow: hidden;\n -webkit-touch-callout: none; /* iOS Safari */\n /* Text stays selectable (#467); the instance applies an inline lock\n only while a pan gesture is active. */\n margin: 0;\n padding: 0;\n transform: translate3d(0, 0, 0);\n}\n.transform-component-module_content__FBWxo {\n display: flex;\n flex-wrap: wrap;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n margin: 0;\n padding: 0;\n transform-origin: 0% 0%;\n}\n.transform-component-module_content__FBWxo img {\n pointer-events: none;\n}\n.transform-component-module_infiniteGrid__Z-aP3 {\n position: absolute;\n inset: 0;\n pointer-events: none;\n background-image: radial-gradient(\n circle,\n rgba(0, 0, 0, 0.12) 1px,\n transparent 1px\n );\n background-size: 20px 20px;\n background-position: 0 0;\n}\n";
2688
3258
  var styles = {"wrapper":"transform-component-module_wrapper__SPB86","content":"transform-component-module_content__FBWxo","infiniteGrid":"transform-component-module_infiniteGrid__Z-aP3"};
2689
3259
  styleInject(css_248z);
2690
3260
 
2691
3261
  var TransformComponent = function (_a) {
2692
- var children = _a.children, _b = _a.wrapperClass, wrapperClass = _b === void 0 ? "" : _b, _c = _a.contentClass, contentClass = _c === void 0 ? "" : _c, wrapperStyle = _a.wrapperStyle, contentStyle = _a.contentStyle, _d = _a.wrapperProps, wrapperProps = _d === void 0 ? {} : _d, _e = _a.contentProps, contentProps = _e === void 0 ? {} : _e, _f = _a.infinite, infinite = _f === void 0 ? false : _f;
3262
+ var _b;
3263
+ var children = _a.children, _c = _a.wrapperClass, wrapperClass = _c === void 0 ? "" : _c, _d = _a.contentClass, contentClass = _d === void 0 ? "" : _d, wrapperStyle = _a.wrapperStyle, contentStyle = _a.contentStyle, _e = _a.wrapperProps, wrapperProps = _e === void 0 ? {} : _e, _f = _a.contentProps, contentProps = _f === void 0 ? {} : _f, _g = _a.infinite, infinite = _g === void 0 ? false : _g;
2693
3264
  var instance = React.useContext(Context);
2694
3265
  var init = instance.init, cleanupWindowEvents = instance.cleanupWindowEvents;
2695
3266
  var wrapperRef = React.useRef(null);
@@ -2722,7 +3293,13 @@ var TransformComponent = function (_a) {
2722
3293
  sync();
2723
3294
  return instance.onChange(sync);
2724
3295
  }, [infinite, instance]);
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({
3296
+ // Keyboard navigation (#254) needs a focus target; `wrapperProps.tabIndex`
3297
+ // still wins because it is spread afterwards.
3298
+ var keyboardEnabled = !((_b = instance.setup.keyboard) === null || _b === void 0 ? void 0 : _b.disabled);
3299
+ return (jsxRuntime.jsxs("div", __assign({
3300
+ // The wrapper is a keyboard-operated widget when navigation is on.
3301
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
3302
+ tabIndex: keyboardEnabled ? 0 : undefined }, 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
3303
  // Inline so the zoom anchor survives environments where the
2727
3304
  // stylesheet is not applied, e.g. a shadow root (#371, #444).
2728
3305
  transformOrigin: "0 0" }, contentStyle), { transform: getTransformStyles(instance.state.positionX, instance.state.positionY, instance.state.scale) }) }, { children: children }))] })));
@@ -2784,8 +3361,8 @@ var Virtualize = React.forwardRef(function (_a, ref) {
2784
3361
  scale: instance.state.scale,
2785
3362
  positionX: instance.state.positionX,
2786
3363
  positionY: instance.state.positionY,
2787
- viewportWidth: wrapper.offsetWidth,
2788
- viewportHeight: wrapper.offsetHeight,
3364
+ viewportWidth: wrapper.clientWidth,
3365
+ viewportHeight: wrapper.clientHeight,
2789
3366
  margin: margin,
2790
3367
  threshold: threshold,
2791
3368
  });