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