react-zoom-pan-pinch 4.1.1 → 4.3.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.
Files changed (33) hide show
  1. package/README.md +4 -4
  2. package/dist/index.cjs.js +1081 -231
  3. package/dist/index.cjs.js.map +1 -1
  4. package/dist/index.d.ts +99 -3
  5. package/dist/index.esm.js +1082 -232
  6. package/dist/index.esm.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/components/mini-map/mini-map.tsx +386 -171
  9. package/src/components/transform-component/transform-component.module.css +2 -5
  10. package/src/components/transform-component/transform-component.tsx +7 -0
  11. package/src/components/virtualize/virtualize.tsx +2 -2
  12. package/src/constants/state.constants.ts +9 -0
  13. package/src/core/animations/animations.utils.ts +2 -0
  14. package/src/core/bounds/bounds.utils.ts +90 -2
  15. package/src/core/handlers/handlers.logic.ts +85 -0
  16. package/src/core/handlers/handlers.utils.ts +102 -5
  17. package/src/core/instance.core.ts +222 -41
  18. package/src/core/keyboard/keyboard.logic.ts +84 -0
  19. package/src/core/pan/panning.logic.ts +24 -4
  20. package/src/core/pan/panning.utils.ts +95 -36
  21. package/src/core/pan/velocity.logic.ts +11 -4
  22. package/src/core/pan/velocity.utils.ts +2 -2
  23. package/src/core/resize/index.ts +0 -0
  24. package/src/core/resize/resize.logic.ts +245 -0
  25. package/src/core/resize/resize.types.ts +6 -0
  26. package/src/core/wheel/wheel.logic.ts +11 -2
  27. package/src/core/zoom/zoom.logic.ts +2 -2
  28. package/src/hooks/initial-layout.utils.ts +21 -0
  29. package/src/hooks/use-transform-component.tsx +22 -4
  30. package/src/hooks/use-transform-effect.tsx +20 -1
  31. package/src/models/context.model.ts +34 -0
  32. package/src/utils/context.utils.ts +4 -0
  33. package/src/utils/styles.utils.ts +2 -2
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;
@@ -280,6 +282,61 @@ var calculateBounds = function (contextInstance, newScale) {
280
282
  }
281
283
  return bounds;
282
284
  };
285
+ function clamp(v, min, max) {
286
+ return Math.max(min, Math.min(v, max));
287
+ }
288
+ // Based on @aholachek ;)
289
+ // https://twitter.com/chpwn/status/285540192096497664
290
+ // iOS constant = 0.55
291
+ // https://medium.com/@nathangitter/building-fluid-interfaces-ios-swift-9732bb934bf5
292
+ function rubberband(distance, dimension, constant) {
293
+ if (dimension === 0 || Math.abs(dimension) === Infinity)
294
+ return Math.pow(distance, (constant * 5));
295
+ return (distance * dimension * constant) / (dimension + constant * distance);
296
+ }
297
+ /**
298
+ * Furthest a grabbed position is traced back along the rubber band curve, as
299
+ * a fraction of the padding. The curve never reaches the padding itself, so
300
+ * a position at (or past) it has no pointer distance to map back to.
301
+ */
302
+ var MAX_RUBBER_BAND_RATIO = 0.9;
303
+ /**
304
+ * Resistance of the rubber band, the constant UIScrollView uses: past a bound
305
+ * the content moves at 0.55× the pointer and slows down from there.
306
+ */
307
+ var RUBBER_BAND_CONSTANT = 0.55;
308
+ /**
309
+ * Where a pan that was dragged past a bound ends up: `(1 - 1 / (x * c / d + 1)) * d`
310
+ * with `d` = `padding`. It trails the pointer from the first pixel past the
311
+ * bound and approaches — never reaches — `padding` px past it.
312
+ */
313
+ function getRubberBandPosition(position, min, max, padding) {
314
+ if (padding <= 0)
315
+ return clamp(position, min, max);
316
+ if (position < min)
317
+ return min - rubberband(min - position, padding, RUBBER_BAND_CONSTANT);
318
+ if (position > max)
319
+ return max + rubberband(position - max, padding, RUBBER_BAND_CONSTANT);
320
+ return position;
321
+ }
322
+ /**
323
+ * Inverse of `getRubberBandPosition`: the pointer position that puts the
324
+ * content at `position`. Lets a pan that starts inside the padding (grabbed
325
+ * mid return animation, trackpad deltas) continue from where the content is.
326
+ */
327
+ function getRubberBandSource(position, min, max, padding) {
328
+ if (padding <= 0)
329
+ return position;
330
+ var stretch = function (offset) {
331
+ var limited = Math.min(offset, padding * MAX_RUBBER_BAND_RATIO);
332
+ return (limited * padding) / (RUBBER_BAND_CONSTANT * (padding - limited));
333
+ };
334
+ if (position < min)
335
+ return min - stretch(min - position);
336
+ if (position > max)
337
+ return max + stretch(position - max);
338
+ return position;
339
+ }
283
340
  /**
284
341
  * Keeps value between given bounds, used for limiting view to given boundaries
285
342
  * 1# eg. boundLimiter(2, 0, 3, true) => 2
@@ -314,6 +371,23 @@ function getMouseBoundedPosition(positionX, positionY, bounds, limitToBounds, pa
314
371
  var y = boundLimiter(positionY, minPositionY - paddingY, maxPositionY + paddingY, limitToBounds);
315
372
  return { x: x, y: y };
316
373
  }
374
+ /**
375
+ * Bounded position for a pan gesture: free inside the bounds and, inside the
376
+ * padding around them, rubber banded (`rubberBand`) or 1:1 up to its edge.
377
+ */
378
+ function getPanBoundedPosition(positionX, positionY, bounds, limitToBounds, paddingX, paddingY, rubberBand) {
379
+ var minPositionX = bounds.minPositionX, minPositionY = bounds.minPositionY, maxPositionX = bounds.maxPositionX, maxPositionY = bounds.maxPositionY;
380
+ var limit = function (position, min, max, padding) {
381
+ if (limitToBounds && rubberBand && padding > 0) {
382
+ return roundNumber(getRubberBandPosition(position, min, max, padding), 2);
383
+ }
384
+ return boundLimiter(position, min - padding, max + padding, limitToBounds);
385
+ };
386
+ return {
387
+ x: limit(positionX, minPositionX, maxPositionX, paddingX),
388
+ y: limit(positionY, minPositionY, maxPositionY, paddingY),
389
+ };
390
+ }
317
391
 
318
392
  function handleCalculateZoomPositions(contextInstance, mouseX, mouseY, newScale, bounds, limitToBounds) {
319
393
  var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
@@ -345,15 +419,21 @@ var isPanningStartAllowed = function (contextInstance, event) {
345
419
  var excluded = contextInstance.setup.panning.excluded;
346
420
  var isInitialized = contextInstance.isInitialized, wrapperComponent = contextInstance.wrapperComponent;
347
421
  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);
422
+ // `composedPath()` also lists the nodes inside a shadow root (#371) and the
423
+ // real target in another window (portal, popup) whose nodes fail an
424
+ // `instanceof Element` check from this realm (#290, PR #552): only
425
+ // duck-typed node checks are safe here.
426
+ var isElementNode = function (node) {
427
+ return !!node &&
428
+ typeof node === "object" &&
429
+ node.nodeType === 1 &&
430
+ typeof node.contains === "function";
431
+ };
432
+ var isWrapperChild = typeof event.composedPath === "function"
433
+ ? event
434
+ .composedPath()
435
+ .some(function (node) { return isElementNode(node) && !!(wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(node)); })
436
+ : !!(wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.contains(target));
357
437
  var isAllowed = isInitialized && target && isWrapperChild;
358
438
  if (!isAllowed)
359
439
  return false;
@@ -373,8 +453,45 @@ var isPanningAllowed = function (contextInstance) {
373
453
  return false;
374
454
  return true;
375
455
  };
456
+ var getPaddingValue = function (contextInstance, size, explicitScale) {
457
+ var setup = contextInstance.setup, state = contextInstance.state;
458
+ var minScale = setup.minScale, disablePadding = setup.disablePadding, centerZoomedOut = setup.centerZoomedOut;
459
+ var scale = explicitScale !== null && explicitScale !== void 0 ? explicitScale : state.scale;
460
+ if (size > 0 && scale >= minScale && !disablePadding && !centerZoomedOut) {
461
+ return size;
462
+ }
463
+ return 0;
464
+ };
465
+ /**
466
+ * Dragging past the bounds stretches like a rubber band only when the content
467
+ * is going to return to them on release (`autoAlignment`). Without that return
468
+ * the padding is a plain area the content can be left in, so it follows the
469
+ * pointer 1:1 up to its edge.
470
+ */
471
+ function isRubberBandEnabled(contextInstance) {
472
+ var _a = contextInstance.setup, limitToBounds = _a.limitToBounds, autoAlignment = _a.autoAlignment;
473
+ return limitToBounds && !autoAlignment.disabled;
474
+ }
475
+ /**
476
+ * The position a pan continues from. Inside the bounds that is the content
477
+ * position; inside the padding the content trails the pointer (rubber band),
478
+ * so the pointer's own position is traced back from it — otherwise the first
479
+ * move of a pan started there would make the content jump.
480
+ */
481
+ function getPanSourcePosition(contextInstance) {
482
+ var bounds = contextInstance.bounds, setup = contextInstance.setup, state = contextInstance.state;
483
+ var positionX = state.positionX, positionY = state.positionY;
484
+ if (!bounds || !isRubberBandEnabled(contextInstance)) {
485
+ return { x: positionX, y: positionY };
486
+ }
487
+ var _a = setup.autoAlignment, sizeX = _a.sizeX, sizeY = _a.sizeY;
488
+ return {
489
+ x: getRubberBandSource(positionX, bounds.minPositionX, bounds.maxPositionX, getPaddingValue(contextInstance, sizeX)),
490
+ y: getRubberBandSource(positionY, bounds.minPositionY, bounds.maxPositionY, getPaddingValue(contextInstance, sizeY)),
491
+ };
492
+ }
376
493
  var handlePanningSetup = function (contextInstance, event) {
377
- var _a = contextInstance.state, positionX = _a.positionX, positionY = _a.positionY;
494
+ var _a = getPanSourcePosition(contextInstance), positionX = _a.x, positionY = _a.y;
378
495
  contextInstance.isPanning = true;
379
496
  // Panning with mouse
380
497
  var x = event.clientX;
@@ -383,7 +500,7 @@ var handlePanningSetup = function (contextInstance, event) {
383
500
  };
384
501
  var handleTouchPanningSetup = function (contextInstance, event) {
385
502
  var touches = event.touches;
386
- var _a = contextInstance.state, positionX = _a.positionX, positionY = _a.positionY;
503
+ var _a = getPanSourcePosition(contextInstance), positionX = _a.x, positionY = _a.y;
387
504
  contextInstance.isPanning = true;
388
505
  // Panning with touch
389
506
  var oneFingerTouch = touches.length === 1;
@@ -403,10 +520,10 @@ function handlePanToBounds(contextInstance) {
403
520
  var xChanged = positionX > maxPositionX || positionX < minPositionX;
404
521
  var yChanged = positionY > maxPositionY || positionY < minPositionY;
405
522
  var mousePosX = positionX > maxPositionX
406
- ? wrapperComponent.offsetWidth
523
+ ? wrapperComponent.clientWidth
407
524
  : contextInstance.setup.minPositionX || 0;
408
525
  var mousePosY = positionY > maxPositionY
409
- ? wrapperComponent.offsetHeight
526
+ ? wrapperComponent.clientHeight
410
527
  : contextInstance.setup.minPositionY || 0;
411
528
  var _d = handleCalculateZoomPositions(contextInstance, mousePosX, mousePosY, scale, contextInstance.bounds, limitToBounds || centerZoomedOut), x = _d.x, y = _d.y;
412
529
  return {
@@ -424,14 +541,16 @@ function handleNewPosition(contextInstance, newPositionX, newPositionY, paddingV
424
541
  (newPositionX === positionX && newPositionY === positionY)) {
425
542
  return;
426
543
  }
427
- var _b = getMouseBoundedPosition(newPositionX, newPositionY, bounds, limitToBounds, paddingValueX, paddingValueY, wrapperComponent), x = _b.x, y = _b.y;
544
+ var _b = getPanBoundedPosition(newPositionX, newPositionY, bounds, limitToBounds, paddingValueX, paddingValueY, isRubberBandEnabled(contextInstance)), x = _b.x, y = _b.y;
428
545
  contextInstance.setState(scale, x, y);
429
546
  }
430
547
  var getPanningClientPosition = function (contextInstance, clientX, clientY) {
431
- var startCoords = contextInstance.startCoords, state = contextInstance.state;
548
+ var startCoords = contextInstance.startCoords;
432
549
  var panning = contextInstance.setup.panning;
433
550
  var lockAxisX = panning.lockAxisX, lockAxisY = panning.lockAxisY;
434
- var positionX = state.positionX, positionY = state.positionY;
551
+ // A locked axis keeps its place: the source maps back onto the position
552
+ // it has now, also when it rests inside the padding.
553
+ var _a = getPanSourcePosition(contextInstance), positionX = _a.x, positionY = _a.y;
435
554
  if (!startCoords) {
436
555
  return { x: positionX, y: positionY };
437
556
  }
@@ -441,15 +560,6 @@ var getPanningClientPosition = function (contextInstance, clientX, clientY) {
441
560
  var newPositionY = lockAxisY ? positionY : mouseY;
442
561
  return { x: newPositionX, y: newPositionY };
443
562
  };
444
- var getPaddingValue = function (contextInstance, size, explicitScale) {
445
- var setup = contextInstance.setup, state = contextInstance.state;
446
- var minScale = setup.minScale, disablePadding = setup.disablePadding, centerZoomedOut = setup.centerZoomedOut;
447
- var scale = explicitScale !== null && explicitScale !== void 0 ? explicitScale : state.scale;
448
- if (size > 0 && scale >= minScale && !disablePadding && !centerZoomedOut) {
449
- return size;
450
- }
451
- return 0;
452
- };
453
563
 
454
564
  exports.DeviceType = void 0;
455
565
  (function (DeviceType) {
@@ -469,8 +579,8 @@ var isVelocityCalculationAllowed = function (contextInstance) {
469
579
  return false;
470
580
  if (!limitToBounds)
471
581
  return true;
472
- var contentOverflows = wrapperComponent.offsetWidth < contentComponent.offsetWidth * scale ||
473
- wrapperComponent.offsetHeight < contentComponent.offsetHeight * scale;
582
+ var contentOverflows = wrapperComponent.clientWidth < contentComponent.offsetWidth * scale ||
583
+ wrapperComponent.clientHeight < contentComponent.offsetHeight * scale;
474
584
  return contentOverflows;
475
585
  };
476
586
  var isVelocityAllowed = function (contextInstance) {
@@ -516,7 +626,7 @@ function getVelocityPosition(newPosition, startPosition, currentPosition, isLock
516
626
  /* eslint-disable no-param-reassign */
517
627
  function getSizeMultiplier(wrapperComponent) {
518
628
  var defaultMultiplier = 1;
519
- var value = wrapperComponent.offsetWidth / window.innerWidth;
629
+ var value = wrapperComponent.clientWidth / window.innerWidth;
520
630
  if (Number.isNaN(value)) {
521
631
  return defaultMultiplier;
522
632
  }
@@ -583,8 +693,15 @@ function handleVelocityPanning(contextInstance) {
583
693
  var finalAnimationTime = Math.max(moveAnimationTime, alignAnimationTime);
584
694
  var paddingValueX = getPaddingValue(contextInstance, sizeX);
585
695
  var paddingValueY = getPaddingValue(contextInstance, sizeY);
586
- var paddingX = (paddingValueX * wrapperComponent.offsetWidth) / 100;
587
- var paddingY = (paddingValueY * wrapperComponent.offsetHeight) / 100;
696
+ // A fling released inside the rubber band stays within the same stretch a
697
+ // drag could reach (`padding` px), not a share of the wrapper size.
698
+ var isRubberBand = isRubberBandEnabled(contextInstance);
699
+ var paddingX = isRubberBand
700
+ ? paddingValueX
701
+ : (paddingValueX * wrapperComponent.clientWidth) / 100;
702
+ var paddingY = isRubberBand
703
+ ? paddingValueY
704
+ : (paddingValueY * wrapperComponent.clientHeight) / 100;
588
705
  var maxTargetX = maxPositionX + paddingX;
589
706
  var minTargetX = minPositionX - paddingX;
590
707
  var maxTargetY = maxPositionY + paddingY;
@@ -617,7 +734,8 @@ function handlePanningStart(contextInstance, event) {
617
734
  contextInstance.panStartPosition = { x: positionX, y: positionY };
618
735
  handleCancelAnimation(contextInstance);
619
736
  handleCalculateBounds(contextInstance, scale);
620
- if (window.TouchEvent !== undefined && event instanceof TouchEvent) {
737
+ // Duck-typed: a TouchEvent from another window fails `instanceof` (#290).
738
+ if ("touches" in event) {
621
739
  handleTouchPanningSetup(contextInstance, event);
622
740
  }
623
741
  else {
@@ -631,6 +749,12 @@ function handleAlignToBounds(contextInstance, customAnimationTime) {
631
749
  var isDisabled = disabled || scale < minScale || (!sizeX && !sizeY);
632
750
  if (isDisabled)
633
751
  return;
752
+ // The content or the wrapper changed size during the gesture (the resize
753
+ // observer postpones its bounds refresh, see `handleResizeAlignment`):
754
+ // align against the current limits so this single animation lands right.
755
+ if (contextInstance.isResizeAlignmentPending) {
756
+ handleCalculateBounds(contextInstance, scale);
757
+ }
634
758
  var targetState = handlePanToBounds(contextInstance);
635
759
  if (!targetState)
636
760
  return;
@@ -664,13 +788,23 @@ function handlePanningEnd(contextInstance, velocityDisabled) {
664
788
  if (start) {
665
789
  var dx = positionX - start.x;
666
790
  var dy = positionY - start.y;
667
- if (dx * dx + dy * dy <= 25)
791
+ // A click is not a fling, but it can still land on content left past
792
+ // the bounds — e.g. grabbed mid return animation, which the press
793
+ // cancelled. Finish the return (a no-op inside the bounds).
794
+ if (dx * dx + dy * dy <= 25) {
795
+ handleAlignToBounds(contextInstance);
668
796
  return;
797
+ }
669
798
  }
670
799
  contextInstance.isAnimating = false;
671
800
  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;
801
+ // See `handleAlignToBounds`: the velocity animation clamps against
802
+ // `bounds`, so they must reflect a size change seen during the pan.
803
+ if (contextInstance.isResizeAlignmentPending) {
804
+ handleCalculateBounds(contextInstance, scale);
805
+ }
806
+ var wrapperWidth = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.clientWidth) || 0;
807
+ var wrapperHeight = (wrapperComponent === null || wrapperComponent === void 0 ? void 0 : wrapperComponent.clientHeight) || 0;
674
808
  var contentWidth = ((contentComponent === null || contentComponent === void 0 ? void 0 : contentComponent.offsetWidth) || 0) * scale;
675
809
  var contentHeight = ((contentComponent === null || contentComponent === void 0 ? void 0 : contentComponent.offsetHeight) || 0) * scale;
676
810
  var isContentOverflowing = !contextInstance.setup.limitToBounds ||
@@ -708,8 +842,8 @@ function handleAlignToScaleBounds(contextInstance, mousePositionX, mousePosition
708
842
  }
709
843
  if (isDisabled || !wrapperComponent || !contextInstance.mounted)
710
844
  return;
711
- var mouseX = mousePositionX || wrapperComponent.offsetWidth / 2;
712
- var mouseY = mousePositionY || wrapperComponent.offsetHeight / 2;
845
+ var mouseX = mousePositionX || wrapperComponent.clientWidth / 2;
846
+ var mouseY = mousePositionY || wrapperComponent.clientHeight / 2;
713
847
  var targetScale = scale < minScale ? minScale : maxScale;
714
848
  var targetState = handleZoomToPoint(contextInstance, targetScale, mouseX, mouseY);
715
849
  if (targetState) {
@@ -789,6 +923,7 @@ var initialSetup = {
789
923
  limitToBounds: true,
790
924
  centerZoomedOut: false,
791
925
  centerOnInit: false,
926
+ fitOnInit: false,
792
927
  disablePadding: false,
793
928
  smooth: true,
794
929
  detached: false,
@@ -825,6 +960,14 @@ var initialSetup = {
825
960
  allowPanning: true,
826
961
  excluded: [],
827
962
  },
963
+ keyboard: {
964
+ disabled: true,
965
+ panStep: 50,
966
+ zoomStep: 0.25,
967
+ animationTime: 100,
968
+ animationType: "easeOut",
969
+ excluded: [],
970
+ },
828
971
  doubleClick: {
829
972
  disabled: false,
830
973
  step: 0.7,
@@ -954,8 +1097,8 @@ function handleZoomToViewCenter(contextInstance, delta, step, animationTime, ani
954
1097
  return Promise.resolve();
955
1098
  }
956
1099
  var effectiveAnimationTime = zoomAnimation.disabled ? 0 : animationTime;
957
- var wrapperWidth = wrapperComponent.offsetWidth;
958
- var wrapperHeight = wrapperComponent.offsetHeight;
1100
+ var wrapperWidth = wrapperComponent.clientWidth;
1101
+ var wrapperHeight = wrapperComponent.clientHeight;
959
1102
  var mouseX = (wrapperWidth / 2 - positionX) / scale;
960
1103
  var mouseY = (wrapperHeight / 2 - positionY) / scale;
961
1104
  var newScale = handleCalculateButtonZoom(contextInstance, delta, step);
@@ -966,13 +1109,82 @@ function handleZoomToViewCenter(contextInstance, delta, step, animationTime, ani
966
1109
  }
967
1110
  return runZoomAnimation(contextInstance, targetState, effectiveAnimationTime, animationType);
968
1111
  }
1112
+ /**
1113
+ * Runs a programmatic pan: fires `onPanningStart`/`onPanning`, animates to
1114
+ * `targetState` and fires `onPanningStop` once the animation time has
1115
+ * elapsed. Resolves when the animation has finished (or was interrupted).
1116
+ */
1117
+ function runPanAnimation(contextInstance, targetState, animationTime, animationType) {
1118
+ var _a, _b;
1119
+ var wrapperComponent = contextInstance.wrapperComponent;
1120
+ var _c = contextInstance.props, onPanningStart = _c.onPanningStart, onPanning = _c.onPanning, onPanningStop = _c.onPanningStop;
1121
+ var event = new MouseEvent("mousemove", { bubbles: true });
1122
+ var ctx = getContext(contextInstance);
1123
+ handleCallback(ctx, event, onPanningStart);
1124
+ handleCallback(ctx, event, onPanning);
1125
+ var done = animate(contextInstance, targetState, animationTime, animationType);
1126
+ 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);
1127
+ if (win) {
1128
+ win.setTimeout(function () {
1129
+ if (!contextInstance.mounted)
1130
+ return;
1131
+ handleCallback(getContext(contextInstance), event, onPanningStop);
1132
+ }, animationTime);
1133
+ }
1134
+ return done;
1135
+ }
1136
+ /**
1137
+ * Scale and centred position that fit the whole content into the wrapper
1138
+ * (`contain`) or fill the wrapper with it (`cover`) (#252).
1139
+ *
1140
+ * The fit scale is capped by `minFitScale`/`maxFitScale` first and by the
1141
+ * wrapper's own `minScale`/`maxScale` second — with the default `minScale` of
1142
+ * 1 the content is never shrunk, so lower `minScale` to fit large content.
1143
+ * Returns `null` until both elements have a size.
1144
+ */
1145
+ function calculateFitToView(contextInstance, mode, minFitScale, maxFitScale) {
1146
+ if (mode === void 0) { mode = "contain"; }
1147
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup;
1148
+ if (!wrapperComponent || !contentComponent)
1149
+ return null;
1150
+ var contentWidth = contentComponent.offsetWidth;
1151
+ var contentHeight = contentComponent.offsetHeight;
1152
+ var wrapperWidth = wrapperComponent.clientWidth;
1153
+ var wrapperHeight = wrapperComponent.clientHeight;
1154
+ if (!contentWidth || !contentHeight || !wrapperWidth || !wrapperHeight) {
1155
+ return null;
1156
+ }
1157
+ var ratioX = wrapperWidth / contentWidth;
1158
+ var ratioY = wrapperHeight / contentHeight;
1159
+ var scale = mode === "cover" ? Math.max(ratioX, ratioY) : Math.min(ratioX, ratioY);
1160
+ if (maxFitScale !== undefined)
1161
+ scale = Math.min(scale, maxFitScale);
1162
+ if (minFitScale !== undefined)
1163
+ scale = Math.max(scale, minFitScale);
1164
+ scale = checkZoomBounds(scale, setup.minScale, setup.maxScale, 0, false);
1165
+ return getCenterPosition(scale, wrapperComponent, contentComponent);
1166
+ }
969
1167
  function resetTransformations(contextInstance, animationTime, animationType, onResetTransformation) {
970
1168
  var setup = contextInstance.setup, wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
971
- var limitToBounds = setup.limitToBounds, centerOnInit = setup.centerOnInit;
1169
+ var limitToBounds = setup.limitToBounds, centerOnInit = setup.centerOnInit, fitOnInit = setup.fitOnInit;
972
1170
  var initialTransformation = createState(contextInstance.props);
973
1171
  var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
974
1172
  if (!wrapperComponent)
975
1173
  return Promise.resolve();
1174
+ // With `fitOnInit` the initial layout is the fitted one, so that is what a
1175
+ // reset returns to (#252).
1176
+ if (fitOnInit) {
1177
+ var fitted = calculateFitToView(contextInstance, fitOnInit === "cover" ? "cover" : "contain");
1178
+ if (fitted) {
1179
+ if (scale === fitted.scale &&
1180
+ positionX === fitted.positionX &&
1181
+ positionY === fitted.positionY) {
1182
+ return Promise.resolve();
1183
+ }
1184
+ onResetTransformation === null || onResetTransformation === void 0 ? void 0 : onResetTransformation();
1185
+ return runZoomAnimation(contextInstance, fitted, animationTime, animationType);
1186
+ }
1187
+ }
976
1188
  var targetPositionX = initialTransformation.positionX;
977
1189
  var targetPositionY = initialTransformation.positionY;
978
1190
  if (centerOnInit && contentComponent) {
@@ -1049,8 +1261,8 @@ function calculateZoomToRect(contextInstance, rect, customZoom, customOffsetX, c
1049
1261
  var nodeTop = nodeOffset.y;
1050
1262
  var nodeWidth = rect.width / state.scale;
1051
1263
  var nodeHeight = rect.height / state.scale;
1052
- var scaleX = wrapperComponent.offsetWidth / nodeWidth;
1053
- var scaleY = wrapperComponent.offsetHeight / nodeHeight;
1264
+ var scaleX = wrapperComponent.clientWidth / nodeWidth;
1265
+ var scaleY = wrapperComponent.clientHeight / nodeHeight;
1054
1266
  var targetScale = customZoom || Math.min(scaleX, scaleY);
1055
1267
  if (maxFitScale !== undefined) {
1056
1268
  targetScale = Math.min(targetScale, maxFitScale);
@@ -1242,6 +1454,52 @@ var zoomToElement = function (contextInstance) {
1242
1454
  return animate(contextInstance, targetState, (_c = options.animationTime) !== null && _c !== void 0 ? _c : animationTime, (_d = options.animationType) !== null && _d !== void 0 ? _d : animationType);
1243
1455
  };
1244
1456
  };
1457
+ /**
1458
+ * Fits the whole content into the viewport (`contain`, default) or fills the
1459
+ * viewport with it (`cover`), centred. Honours the wrapper's
1460
+ * `minScale`/`maxScale`; lower `minScale` to let large content shrink (#252).
1461
+ */
1462
+ var fitToView = function (contextInstance) {
1463
+ return function (options) {
1464
+ var _a, _b, _c;
1465
+ if (options === void 0) { options = {}; }
1466
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup;
1467
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
1468
+ return Promise.resolve();
1469
+ }
1470
+ var targetState = calculateFitToView(contextInstance, (_a = options.mode) !== null && _a !== void 0 ? _a : "contain", options.minScale, options.maxScale);
1471
+ if (!targetState)
1472
+ return Promise.resolve();
1473
+ var animationTime = setup.zoomAnimation.disabled
1474
+ ? 0
1475
+ : (_b = options.animationTime) !== null && _b !== void 0 ? _b : 200;
1476
+ return runZoomAnimation(contextInstance, targetState, animationTime, (_c = options.animationType) !== null && _c !== void 0 ? _c : "easeOut");
1477
+ };
1478
+ };
1479
+ /**
1480
+ * Pans by a pixel delta (positive x moves the content right), limited to the
1481
+ * bounds when `limitToBounds` is on. Backs the keyboard arrows and is handy
1482
+ * for directional buttons (#254, #527).
1483
+ */
1484
+ var panBy = function (contextInstance) {
1485
+ return function (deltaX, deltaY, animationTime, animationType) {
1486
+ if (animationTime === void 0) { animationTime = 200; }
1487
+ if (animationType === void 0) { animationType = "easeOut"; }
1488
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup, state = contextInstance.state;
1489
+ if (setup.disabled || !wrapperComponent || !contentComponent) {
1490
+ return Promise.resolve();
1491
+ }
1492
+ if (!Number.isFinite(deltaX) || !Number.isFinite(deltaY)) {
1493
+ return Promise.resolve();
1494
+ }
1495
+ var bounds = handleCalculateBounds(contextInstance, state.scale);
1496
+ var _a = getMouseBoundedPosition(state.positionX + deltaX, state.positionY + deltaY, bounds, setup.limitToBounds, 0, 0, wrapperComponent), x = _a.x, y = _a.y;
1497
+ if (x === state.positionX && y === state.positionY) {
1498
+ return Promise.resolve();
1499
+ }
1500
+ return runPanAnimation(contextInstance, { scale: state.scale, positionX: x, positionY: y }, animationTime, animationType);
1501
+ };
1502
+ };
1245
1503
 
1246
1504
  var getControls = function (contextInstance) {
1247
1505
  return {
@@ -1256,6 +1514,8 @@ var getControls = function (contextInstance) {
1256
1514
  zoomToPoint: zoomToPoint(contextInstance),
1257
1515
  clientToContent: clientToContent(contextInstance),
1258
1516
  contentToClient: contentToClient(contextInstance),
1517
+ fitToView: fitToView(contextInstance),
1518
+ panBy: panBy(contextInstance),
1259
1519
  };
1260
1520
  };
1261
1521
  var getState = function (contextInstance) {
@@ -1364,8 +1624,8 @@ var getMatrixTransformStyles = function (x, y, scale) {
1364
1624
  var getCenterPosition = function (scale, wrapperComponent, contentComponent) {
1365
1625
  var contentWidth = contentComponent.offsetWidth * scale;
1366
1626
  var contentHeight = contentComponent.offsetHeight * scale;
1367
- var centerPositionX = (wrapperComponent.offsetWidth - contentWidth) / 2;
1368
- var centerPositionY = (wrapperComponent.offsetHeight - contentHeight) / 2;
1627
+ var centerPositionX = (wrapperComponent.clientWidth - contentWidth) / 2;
1628
+ var centerPositionY = (wrapperComponent.clientHeight - contentHeight) / 2;
1369
1629
  return {
1370
1630
  scale: scale,
1371
1631
  positionX: centerPositionX,
@@ -1373,16 +1633,6 @@ var getCenterPosition = function (scale, wrapperComponent, contentComponent) {
1373
1633
  };
1374
1634
  };
1375
1635
 
1376
- function assignRef(ref, value) {
1377
- if (ref == null)
1378
- return;
1379
- if (typeof ref === "function") {
1380
- ref(value);
1381
- }
1382
- else {
1383
- ref.current = value;
1384
- }
1385
- }
1386
1636
  function mergeRefs(refs) {
1387
1637
  return function (value) {
1388
1638
  refs.forEach(function (ref) {
@@ -1405,6 +1655,270 @@ function mergeRefs(refs) {
1405
1655
  */
1406
1656
  var useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
1407
1657
 
1658
+ /**
1659
+ * Keys handled by the keyboard navigation (#254). Arrows pan by
1660
+ * `keyboard.panStep`, plus/minus zoom by `keyboard.zoomStep`, `0` resets.
1661
+ */
1662
+ var KEYBOARD_KEYS = {
1663
+ panLeft: ["ArrowLeft"],
1664
+ panRight: ["ArrowRight"],
1665
+ panUp: ["ArrowUp"],
1666
+ panDown: ["ArrowDown"],
1667
+ zoomIn: ["+", "="],
1668
+ zoomOut: ["-", "_"],
1669
+ reset: ["0"],
1670
+ };
1671
+ var isHandledKey = function (key) {
1672
+ return Object.values(KEYBOARD_KEYS).some(function (keys) {
1673
+ return keys.includes(key);
1674
+ });
1675
+ };
1676
+ /**
1677
+ * Wrapper `keydown` handler. Returns `true` when the key was consumed (and
1678
+ * its default action prevented), `false` when it was left to the browser.
1679
+ *
1680
+ * Ignored on purpose: modifier combos (ctrl/cmd/alt, so browser shortcuts
1681
+ * such as cmd+0 / cmd+- keep working), editable targets (typing in an input
1682
+ * inside the content) and `keyboard.excluded` targets.
1683
+ */
1684
+ function handleKeyboardNavigation(contextInstance, event) {
1685
+ var _a = contextInstance.setup, disabled = _a.disabled, keyboard = _a.keyboard, panning = _a.panning;
1686
+ if (disabled || keyboard.disabled)
1687
+ return false;
1688
+ if (event.defaultPrevented)
1689
+ return false;
1690
+ if (event.ctrlKey || event.metaKey || event.altKey)
1691
+ return false;
1692
+ if (!isHandledKey(event.key))
1693
+ return false;
1694
+ var target = event.target;
1695
+ if (isEditableTarget(target))
1696
+ return false;
1697
+ if (target &&
1698
+ typeof target.matches === "function" &&
1699
+ isExcludedNode(target, keyboard.excluded)) {
1700
+ return false;
1701
+ }
1702
+ var panStep = keyboard.panStep, zoomStep = keyboard.zoomStep, animationTime = keyboard.animationTime, animationType = keyboard.animationType;
1703
+ var controls = getControls(contextInstance);
1704
+ var key = event.key;
1705
+ // Arrow keys move the *viewport*, like scrolling: pressing left reveals
1706
+ // content on the left, so the content itself shifts right (position grows).
1707
+ var stepX = panning.lockAxisX ? 0 : panStep;
1708
+ var stepY = panning.lockAxisY ? 0 : panStep;
1709
+ if (key === "ArrowLeft") {
1710
+ controls.panBy(stepX, 0, animationTime, animationType);
1711
+ }
1712
+ else if (key === "ArrowRight") {
1713
+ controls.panBy(-stepX, 0, animationTime, animationType);
1714
+ }
1715
+ else if (key === "ArrowUp") {
1716
+ controls.panBy(0, stepY, animationTime, animationType);
1717
+ }
1718
+ else if (key === "ArrowDown") {
1719
+ controls.panBy(0, -stepY, animationTime, animationType);
1720
+ }
1721
+ else if (key === "+" || key === "=") {
1722
+ controls.zoomIn(zoomStep, animationTime, animationType);
1723
+ }
1724
+ else if (key === "-" || key === "_") {
1725
+ controls.zoomOut(zoomStep, animationTime, animationType);
1726
+ }
1727
+ else if (key === "0") {
1728
+ controls.resetTransform(animationTime, animationType);
1729
+ }
1730
+ if (event.cancelable) {
1731
+ event.preventDefault();
1732
+ }
1733
+ // Consumed: hosts that forward key presses (Storybook's manager, app-level
1734
+ // shortcuts) must not also act on them.
1735
+ event.stopPropagation();
1736
+ return true;
1737
+ }
1738
+
1739
+ var measureSizes = function (wrapperComponent, contentComponent) { return ({
1740
+ wrapperWidth: wrapperComponent.offsetWidth,
1741
+ wrapperHeight: wrapperComponent.offsetHeight,
1742
+ contentWidth: contentComponent.offsetWidth,
1743
+ contentHeight: contentComponent.offsetHeight,
1744
+ }); };
1745
+ var hasSizeChanged = function (previous, current) {
1746
+ return !previous ||
1747
+ previous.wrapperWidth !== current.wrapperWidth ||
1748
+ previous.wrapperHeight !== current.wrapperHeight ||
1749
+ previous.contentWidth !== current.contentWidth ||
1750
+ previous.contentHeight !== current.contentHeight;
1751
+ };
1752
+ /**
1753
+ * A pointer is physically held: a mouse/touch pan or a pinch. The bounds
1754
+ * belong to that gesture until it is released (moving the content under a
1755
+ * held cursor is what feels like a jump).
1756
+ */
1757
+ var isPointerGestureActive = function (contextInstance) { return contextInstance.isPanning || contextInstance.isPinching; };
1758
+ /**
1759
+ * Any gesture is in progress: a held pointer, or a wheel sequence whose stop
1760
+ * timers have not fired yet.
1761
+ */
1762
+ var isGestureActive = function (contextInstance) {
1763
+ return isPointerGestureActive(contextInstance) ||
1764
+ contextInstance.wheelStopEventTimer !== null ||
1765
+ contextInstance.wheelAnimationTimer !== null;
1766
+ };
1767
+ /**
1768
+ * Recomputes the bounds for the current scale and content/wrapper sizes and
1769
+ * returns the state the transform has to move to so it sits inside them.
1770
+ * Returns `null` when the transform is already inside the bounds or when
1771
+ * nothing limits it (`limitToBounds` and `centerZoomedOut` both off).
1772
+ *
1773
+ * The bounds are stored on the instance as a side effect, so gestures that
1774
+ * follow a resize clamp against the fresh sizes even when no move is needed.
1775
+ */
1776
+ function calculateResizeAlignment(contextInstance) {
1777
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent, setup = contextInstance.setup, state = contextInstance.state;
1778
+ if (!wrapperComponent || !contentComponent)
1779
+ return null;
1780
+ var bounds = handleCalculateBounds(contextInstance, state.scale);
1781
+ // Same rule as the post-pan alignment (`handlePanToBounds`).
1782
+ var limitToBounds = setup.limitToBounds, centerZoomedOut = setup.centerZoomedOut;
1783
+ if (!limitToBounds && !centerZoomedOut)
1784
+ return null;
1785
+ var _a = getMouseBoundedPosition(state.positionX, state.positionY, bounds, true, 0, 0, wrapperComponent), x = _a.x, y = _a.y;
1786
+ // `boundLimiter` rounds to two decimals; compare against the same rounding
1787
+ // so an in-bounds transform never starts a zero-length animation.
1788
+ var isAligned = x === roundNumber(state.positionX, 2) &&
1789
+ y === roundNumber(state.positionY, 2);
1790
+ if (isAligned)
1791
+ return null;
1792
+ return { scale: state.scale, positionX: x, positionY: y };
1793
+ }
1794
+ var stopResizeTracking = function (contextInstance) {
1795
+ contextInstance.animation = null;
1796
+ contextInstance.animationFrame = null;
1797
+ contextInstance.isAnimating = false;
1798
+ contextInstance.resizeAnimation = null;
1799
+ };
1800
+ /**
1801
+ * Eases the transform towards the current bounds, frame by frame, until it
1802
+ * rests on them.
1803
+ *
1804
+ * The bounds are re-read every frame, so a size that keeps changing (a CSS
1805
+ * height transition, a layout settling over several frames) is followed
1806
+ * smoothly — the content edge trails the moving bound by a few pixels
1807
+ * instead of lagging behind a stale target and bursting after it. Each
1808
+ * frame closes a fixed fraction of the remaining gap (exponential
1809
+ * smoothing), tuned so a one-off step still settles within
1810
+ * `autoAlignment.animationTime`.
1811
+ */
1812
+ function startResizeTracking(contextInstance) {
1813
+ var animationTime = contextInstance.setup.autoAlignment.animationTime;
1814
+ // Over 99% of a step is covered after `animationTime`; the sub-pixel rest
1815
+ // snaps (see `isSettled`).
1816
+ var tau = Math.max(animationTime / 5, 1);
1817
+ handleCancelAnimation(contextInstance);
1818
+ var lastFrameTime = Date.now();
1819
+ var track = function () {
1820
+ if (!contextInstance.mounted || contextInstance.animation !== track) {
1821
+ return;
1822
+ }
1823
+ var now = Date.now();
1824
+ var frameTime = Math.max(now - lastFrameTime, 1);
1825
+ lastFrameTime = now;
1826
+ var targetState = calculateResizeAlignment(contextInstance);
1827
+ if (!targetState) {
1828
+ // Back inside the bounds (the content grew again).
1829
+ stopResizeTracking(contextInstance);
1830
+ return;
1831
+ }
1832
+ var _a = contextInstance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
1833
+ var factor = 1 - Math.exp(-frameTime / tau);
1834
+ var x = positionX + (targetState.positionX - positionX) * factor;
1835
+ var y = positionY + (targetState.positionY - positionY) * factor;
1836
+ var isSettled = Math.abs(targetState.positionX - x) < 0.5 &&
1837
+ Math.abs(targetState.positionY - y) < 0.5;
1838
+ if (isSettled) {
1839
+ x = targetState.positionX;
1840
+ y = targetState.positionY;
1841
+ }
1842
+ contextInstance.isAnimating = !isSettled;
1843
+ contextInstance.setState(scale, x, y);
1844
+ if (isSettled) {
1845
+ stopResizeTracking(contextInstance);
1846
+ return;
1847
+ }
1848
+ contextInstance.animationFrame = requestAnimationFrame(track);
1849
+ };
1850
+ contextInstance.animation = track;
1851
+ contextInstance.resizeAnimation = track;
1852
+ contextInstance.animationResolve = null;
1853
+ contextInstance.animationFrame = requestAnimationFrame(track);
1854
+ }
1855
+ /**
1856
+ * Brings the transform back into the bounds after the content or the
1857
+ * wrapper changed size — immediately: a move still in flight (inertia, an
1858
+ * alignment, a programmatic animation) is cancelled and a trackpad sequence
1859
+ * simply continues against the fresh bounds, so a layout that collapses
1860
+ * while the user scrolls aligns right away.
1861
+ *
1862
+ * Two things are left alone. A pointer that is still held owns the bounds
1863
+ * until it is released (replacing them mid-drag makes the next move clamp
1864
+ * against a new limit and jump under the cursor); the release then aligns
1865
+ * against the fresh bounds (`handleAlignToBounds`). And an animation that is
1866
+ * bringing the scale back inside `minScale`/`maxScale` must finish, because
1867
+ * the tracking only moves the position. Both come back here afterwards via
1868
+ * `flushResizeAlignment`.
1869
+ */
1870
+ function handleResizeAlignment(contextInstance) {
1871
+ if (contextInstance.setup.disabled) {
1872
+ // Nothing may move, but the next gesture must see the right limits.
1873
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
1874
+ return;
1875
+ }
1876
+ if (isPointerGestureActive(contextInstance)) {
1877
+ contextInstance.isResizeAlignmentPending = true;
1878
+ return;
1879
+ }
1880
+ var isOwnAnimation = contextInstance.animation !== null &&
1881
+ contextInstance.animation === contextInstance.resizeAnimation;
1882
+ if (contextInstance.animation && !isOwnAnimation) {
1883
+ var scale = contextInstance.state.scale;
1884
+ var _a = contextInstance.setup, minScale = _a.minScale, maxScale = _a.maxScale;
1885
+ if (scale < minScale || scale > maxScale) {
1886
+ contextInstance.isResizeAlignmentPending = true;
1887
+ return;
1888
+ }
1889
+ handleCancelAnimation(contextInstance);
1890
+ }
1891
+ var targetState = calculateResizeAlignment(contextInstance);
1892
+ if (!targetState) {
1893
+ if (isOwnAnimation)
1894
+ stopResizeTracking(contextInstance);
1895
+ return;
1896
+ }
1897
+ // The tracking loop re-reads the bounds itself; it just keeps running.
1898
+ if (isOwnAnimation)
1899
+ return;
1900
+ if (contextInstance.setup.autoAlignment.animationTime === 0) {
1901
+ contextInstance.setState(targetState.scale, targetState.positionX, targetState.positionY);
1902
+ return;
1903
+ }
1904
+ startResizeTracking(contextInstance);
1905
+ }
1906
+ /**
1907
+ * Entry point for the size observer: ignores notifications that carry no
1908
+ * size change (the observer's initial delivery, style-only changes) and
1909
+ * aligns on the ones that do.
1910
+ */
1911
+ function handleSizeChange(contextInstance) {
1912
+ var wrapperComponent = contextInstance.wrapperComponent, contentComponent = contextInstance.contentComponent;
1913
+ if (!wrapperComponent || !contentComponent)
1914
+ return;
1915
+ var sizes = measureSizes(wrapperComponent, contentComponent);
1916
+ if (!hasSizeChanged(contextInstance.measuredSizes, sizes))
1917
+ return;
1918
+ contextInstance.measuredSizes = sizes;
1919
+ handleResizeAlignment(contextInstance);
1920
+ }
1921
+
1408
1922
  var isWheelAllowed = function (contextInstance, event) {
1409
1923
  var _a = contextInstance.setup.wheel, disabled = _a.disabled, wheelDisabled = _a.wheelDisabled, touchPadDisabled = _a.touchPadDisabled, excluded = _a.excluded;
1410
1924
  var isInitialized = contextInstance.isInitialized, isPanning = contextInstance.isPanning;
@@ -1630,6 +2144,7 @@ var handleWheelStop = function (contextInstance, event) {
1630
2144
  return;
1631
2145
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
1632
2146
  contextInstance.wheelAnimationTimer = null;
2147
+ contextInstance.flushResizeAlignment();
1633
2148
  }, wheelAnimationTime);
1634
2149
  // Wheel stop event
1635
2150
  var hasStoppedZooming = handleWheelZoomStop(contextInstance, event);
@@ -1641,6 +2156,7 @@ var handleWheelStop = function (contextInstance, event) {
1641
2156
  contextInstance.wheelStopEventTimer = null;
1642
2157
  handleCallback(getContext(contextInstance), event, onWheelStop);
1643
2158
  handleCallback(getContext(contextInstance), event, onZoomStop);
2159
+ contextInstance.flushResizeAlignment();
1644
2160
  }, wheelStopEventTime);
1645
2161
  }
1646
2162
  };
@@ -1650,8 +2166,13 @@ var handleWheelPanningStart = function (contextInstance, event) {
1650
2166
  handleCancelAnimation(contextInstance);
1651
2167
  if (!contextInstance.wheelStopEventTimer) {
1652
2168
  // 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);
2169
+ // content size, not the ones measured at mount (#396, #433). Only at the
2170
+ // start of a wheel sequence though — mid-sequence the gesture owns them
2171
+ // (see `handleResizeAlignment`), otherwise a content resize would make
2172
+ // the next event clamp against a new limit and jump.
2173
+ if (!contextInstance.wheelAnimationTimer) {
2174
+ handleCalculateBounds(contextInstance, contextInstance.state.scale);
2175
+ }
1655
2176
  handleCallback(getContext(contextInstance), event, onWheelStart);
1656
2177
  handleCallback(getContext(contextInstance), event, onPanningStart);
1657
2178
  }
@@ -1665,6 +2186,7 @@ var handleWheelPanningStop = function (contextInstance, event) {
1665
2186
  return;
1666
2187
  handleAlignToScaleBounds(contextInstance, event.x, event.y);
1667
2188
  contextInstance.wheelAnimationTimer = null;
2189
+ contextInstance.flushResizeAlignment();
1668
2190
  }, wheelAnimationTime);
1669
2191
  // Wheel stop event
1670
2192
  var hasStoppedZooming = handleWheelZoomStop(contextInstance, event);
@@ -1676,6 +2198,7 @@ var handleWheelPanningStop = function (contextInstance, event) {
1676
2198
  contextInstance.wheelStopEventTimer = null;
1677
2199
  handleCallback(getContext(contextInstance), event, onWheelStop);
1678
2200
  handleCallback(getContext(contextInstance), event, onPanningStop);
2201
+ contextInstance.flushResizeAlignment();
1679
2202
  }, wheelStopEventTime);
1680
2203
  }
1681
2204
  };
@@ -1873,8 +2396,20 @@ var ZoomPanPinch = /** @class */ (function () {
1873
2396
  this.animationResolve = null;
1874
2397
  // init helpers
1875
2398
  this.initObserverTimer = null;
2399
+ // `centerOnInit`/`fitOnInit` wait for content that has no size yet
2400
+ this.isInitialLayoutPending = false;
2401
+ // resize helpers: last measured sizes and an alignment postponed until the
2402
+ // running animation settles
2403
+ this.measuredSizes = null;
2404
+ this.isResizeAlignmentPending = false;
2405
+ // The alignment animation started by a resize, so further size changes can
2406
+ // retarget it instead of waiting for it (compared by identity to
2407
+ // `animation`, which is null once it has finished).
2408
+ this.resizeAnimation = null;
1876
2409
  // key press
1877
2410
  this.pressedKeys = {};
2411
+ // text selection lock while a gesture is active (#467)
2412
+ this.selectionLock = null;
1878
2413
  this.mount = function () {
1879
2414
  _this.mounted = true;
1880
2415
  _this.initializeWindowEvents();
@@ -1890,7 +2425,12 @@ var ZoomPanPinch = /** @class */ (function () {
1890
2425
  // Setup first: bounds depend on the new props (min/max positions,
1891
2426
  // centerZoomedOut, disablePadding).
1892
2427
  _this.setup = createSetup(newProps);
1893
- if (_this.wrapperComponent && _this.contentComponent) {
2428
+ // A gesture owns the bounds until it ends (see `handleResizeAlignment`):
2429
+ // replacing them mid-drag makes the next move clamp against a new limit
2430
+ // and jump. The gesture start recalculates them anyway.
2431
+ if (_this.wrapperComponent &&
2432
+ _this.contentComponent &&
2433
+ !isGestureActive(_this)) {
1894
2434
  handleCalculateBounds(_this, _this.state.scale);
1895
2435
  }
1896
2436
  };
@@ -1944,7 +2484,12 @@ var ZoomPanPinch = /** @class */ (function () {
1944
2484
  _this.cleanupWrapperEvents();
1945
2485
  _this.clearTimers();
1946
2486
  handleCancelAnimation(_this);
2487
+ _this.unlockTextSelection();
1947
2488
  (_e = _this.observer) === null || _e === void 0 ? void 0 : _e.disconnect();
2489
+ _this.observer = undefined;
2490
+ _this.isInitialLayoutPending = false;
2491
+ _this.isResizeAlignmentPending = false;
2492
+ _this.resizeAnimation = null;
1948
2493
  };
1949
2494
  this.cleanupWrapperEvents = function () {
1950
2495
  var wrapper = _this.wrapperComponent;
@@ -1953,6 +2498,7 @@ var ZoomPanPinch = /** @class */ (function () {
1953
2498
  var passive = makePassiveEventOption();
1954
2499
  wrapper.removeEventListener("wheel", _this.onWheelZoom, passive);
1955
2500
  wrapper.removeEventListener("dblclick", _this.onDoubleClick, passive);
2501
+ wrapper.removeEventListener("keydown", _this.onKeyboardNavigation, passive);
1956
2502
  wrapper.removeEventListener("touchstart", _this.onTouchPanningStart, passive);
1957
2503
  wrapper.removeEventListener("touchmove", _this.onTouchPanning, passive);
1958
2504
  wrapper.removeEventListener("touchend", _this.onTouchPanningStop, passive);
@@ -1962,42 +2508,86 @@ var ZoomPanPinch = /** @class */ (function () {
1962
2508
  var passive = makePassiveEventOption();
1963
2509
  wrapper.addEventListener("wheel", _this.onWheelZoom, passive);
1964
2510
  wrapper.addEventListener("dblclick", _this.onDoubleClick, passive);
2511
+ wrapper.addEventListener("keydown", _this.onKeyboardNavigation, passive);
1965
2512
  wrapper.addEventListener("touchstart", _this.onTouchPanningStart, passive);
1966
2513
  wrapper.addEventListener("touchmove", _this.onTouchPanning, passive);
1967
2514
  wrapper.addEventListener("touchend", _this.onTouchPanningStop, passive);
1968
2515
  };
1969
- this.handleInitialize = function (contentComponent) {
1970
- var _a;
1971
- var centerOnInit = _this.setup.centerOnInit;
2516
+ this.handleInitialize = function () {
2517
+ var _a = _this.setup, centerOnInit = _a.centerOnInit, fitOnInit = _a.fitOnInit;
1972
2518
  _this.applyTransformation();
1973
2519
  _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
2520
+ if (centerOnInit || fitOnInit) {
2521
+ var applied = _this.applyInitialLayout();
2522
+ // Content without a size yet (an image still loading) gets its layout
2523
+ // applied again by `onSizeChange` once it has one. Once a real layout
2524
+ // exists, stop waiting after 5 seconds so a later resize aligns instead
2525
+ // of re-centring. Until then keep waiting: in a hidden tab the observer
2526
+ // may not deliver for a long time and the first layout must still be
2527
+ // the fitted/centred one.
2528
+ _this.isInitialLayoutPending = true;
1991
2529
  if (_this.initObserverTimer)
1992
2530
  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);
2531
+ if (applied) {
2532
+ _this.initObserverTimer = setTimeout(function () {
2533
+ _this.initObserverTimer = null;
2534
+ _this.isInitialLayoutPending = false;
2535
+ }, 5000);
2536
+ }
2537
+ }
2538
+ };
2539
+ /// ///////
2540
+ // Size changes
2541
+ /// ///////
2542
+ // One observer for the whole lifetime of the instance: it finishes the
2543
+ // initial layout for late-sized content and, after that, keeps the
2544
+ // transform inside the bounds whenever the content or the wrapper changes
2545
+ // size (children re-rendering with another size, images loading, the
2546
+ // viewport resizing).
2547
+ this.observeSizes = function (wrapperComponent, contentComponent) {
2548
+ var _a;
2549
+ (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
2550
+ _this.observer = undefined;
2551
+ _this.measuredSizes = measureSizes(wrapperComponent, contentComponent);
2552
+ if (typeof ResizeObserver === "undefined")
2553
+ return;
2554
+ _this.observer = new ResizeObserver(_this.onSizeChange);
2555
+ _this.observer.observe(wrapperComponent);
2556
+ _this.observer.observe(contentComponent);
2557
+ };
2558
+ this.onSizeChange = function () {
2559
+ var _a = _this, wrapperComponent = _a.wrapperComponent, contentComponent = _a.contentComponent;
2560
+ if (!_this.mounted || !wrapperComponent || !contentComponent)
2561
+ return;
2562
+ if (_this.isInitialLayoutPending) {
2563
+ // Both boxes must be laid out: a wrapper that is sized late (hidden
2564
+ // tab, collapsed panel) would otherwise get a fit against a 0px box.
2565
+ var hasSize = (contentComponent.offsetWidth > 0 ||
2566
+ contentComponent.offsetHeight > 0) &&
2567
+ wrapperComponent.clientWidth > 0 &&
2568
+ wrapperComponent.clientHeight > 0;
2569
+ if (!hasSize)
2570
+ return;
2571
+ _this.isInitialLayoutPending = false;
2572
+ if (_this.initObserverTimer)
2573
+ clearTimeout(_this.initObserverTimer);
2574
+ _this.initObserverTimer = null;
2575
+ _this.onInitCallbacks.forEach(function (callback) { return callback(getContext(_this)); });
2576
+ _this.applyInitialLayout();
2577
+ _this.measuredSizes = measureSizes(wrapperComponent, contentComponent);
2578
+ handleCalculateBounds(_this, _this.state.scale);
2579
+ return;
2000
2580
  }
2581
+ handleSizeChange(_this);
2582
+ };
2583
+ // Called once a gesture or an animation has ended, so a resize seen while
2584
+ // it ran is checked against the settled state (it may postpone itself
2585
+ // again when another gesture or animation is still running).
2586
+ this.flushResizeAlignment = function () {
2587
+ if (!_this.isResizeAlignmentPending)
2588
+ return;
2589
+ _this.isResizeAlignmentPending = false;
2590
+ handleResizeAlignment(_this);
2001
2591
  };
2002
2592
  /// ///////
2003
2593
  // Zoom
@@ -2029,17 +2619,19 @@ var ZoomPanPinch = /** @class */ (function () {
2029
2619
  event.preventDefault();
2030
2620
  }
2031
2621
  event.stopPropagation();
2032
- var _a = _this.state, positionX = _a.positionX, positionY = _a.positionY;
2033
- var mouseX = positionX - event.deltaX;
2034
- var mouseY = positionY - event.deltaY;
2035
- var newPositionX = lockAxisX ? positionX : mouseX;
2036
- var newPositionY = lockAxisY ? positionY : mouseY;
2037
- var _b = _this.setup.autoAlignment, sizeX = _b.sizeX, sizeY = _b.sizeY;
2622
+ var deltaX = lockAxisX ? 0 : event.deltaX;
2623
+ var deltaY = lockAxisY ? 0 : event.deltaY;
2624
+ if (!deltaX && !deltaY)
2625
+ return;
2626
+ var _a = _this.setup.autoAlignment, sizeX = _a.sizeX, sizeY = _a.sizeY;
2038
2627
  var paddingValueX = getPaddingValue(_this, sizeX);
2039
2628
  var paddingValueY = getPaddingValue(_this, sizeY);
2040
- if (newPositionX === positionX && newPositionY === positionY)
2041
- return;
2042
2629
  handleWheelPanningStart(_this, event);
2630
+ // Deltas add up on the pointer's side of the rubber band, the same way
2631
+ // a drag does, so the content slows down towards the padding limit.
2632
+ var source = getPanSourcePosition(_this);
2633
+ var newPositionX = source.x - deltaX;
2634
+ var newPositionY = source.y - deltaY;
2043
2635
  handleNewPosition(_this, newPositionX, newPositionY, paddingValueX, paddingValueY);
2044
2636
  handleCallback(getContext(_this), event, onPanning);
2045
2637
  handleWheelPanningStop(_this, event);
@@ -2048,9 +2640,11 @@ var ZoomPanPinch = /** @class */ (function () {
2048
2640
  // Pan
2049
2641
  /// ///////
2050
2642
  this.onPanningStart = function (event) {
2051
- var disabled = _this.setup.disabled;
2643
+ var _a = _this.setup, disabled = _a.disabled, panning = _a.panning;
2052
2644
  var onPanningStart = _this.props.onPanningStart;
2053
- if (disabled)
2645
+ // With panning off the mousedown is not ours: no pan state, no
2646
+ // preventDefault, and native text selection keeps working (#467).
2647
+ if (disabled || panning.disabled)
2054
2648
  return;
2055
2649
  _this.syncModifierKeys(event);
2056
2650
  var isAllowed = isPanningStartAllowed(_this, event);
@@ -2071,6 +2665,8 @@ var ZoomPanPinch = /** @class */ (function () {
2071
2665
  event.stopPropagation();
2072
2666
  handleCancelAnimation(_this);
2073
2667
  handlePanningStart(_this, event);
2668
+ _this.lockTextSelection();
2669
+ _this.focusForKeyboard();
2074
2670
  handleCallback(getContext(_this), event, onPanningStart);
2075
2671
  };
2076
2672
  this.onPanning = function (event) {
@@ -2102,8 +2698,10 @@ var ZoomPanPinch = /** @class */ (function () {
2102
2698
  var velocityDisabled = _this.setup.panning.velocityDisabled;
2103
2699
  var onPanningStop = _this.props.onPanningStop;
2104
2700
  if (_this.isPanning) {
2701
+ _this.unlockTextSelection();
2105
2702
  handlePanningEnd(_this, velocityDisabled);
2106
2703
  handleCallback(getContext(_this), event, onPanningStop);
2704
+ _this.flushResizeAlignment();
2107
2705
  }
2108
2706
  };
2109
2707
  /// ///////
@@ -2141,6 +2739,7 @@ var ZoomPanPinch = /** @class */ (function () {
2141
2739
  if (_this.pinchStartScale) {
2142
2740
  handlePinchStop(_this);
2143
2741
  handleCallback(getContext(_this), event, onPinchStop);
2742
+ _this.flushResizeAlignment();
2144
2743
  }
2145
2744
  };
2146
2745
  /// ///////
@@ -2167,10 +2766,12 @@ var ZoomPanPinch = /** @class */ (function () {
2167
2766
  var isPinchAction = touches.length === 2;
2168
2767
  var isAllowed = isPanningStartAllowed(_this, event);
2169
2768
  if (isPanningAction) {
2170
- if (!isAllowed)
2769
+ if (!isAllowed || _this.setup.panning.disabled)
2171
2770
  return;
2172
2771
  handleCancelAnimation(_this);
2173
2772
  handlePanningStart(_this, event);
2773
+ _this.lockTextSelection();
2774
+ _this.focusForKeyboard();
2174
2775
  handleCallback(getContext(_this), event, onPanningStart);
2175
2776
  }
2176
2777
  if (isPinchAction) {
@@ -2232,6 +2833,8 @@ var ZoomPanPinch = /** @class */ (function () {
2232
2833
  _this.isPanning = false;
2233
2834
  _this.startCoords = null;
2234
2835
  }
2836
+ _this.unlockTextSelection();
2837
+ _this.flushResizeAlignment();
2235
2838
  };
2236
2839
  // Iframe focus problem (e.g. Storybook):
2237
2840
  //
@@ -2284,6 +2887,78 @@ var ZoomPanPinch = /** @class */ (function () {
2284
2887
  }
2285
2888
  return Boolean(keys.every(function (key) { return _this.pressedKeys[key]; }));
2286
2889
  };
2890
+ /// ///////
2891
+ // Keyboard
2892
+ /// ///////
2893
+ this.onKeyboardNavigation = function (event) {
2894
+ handleKeyboardNavigation(_this, event);
2895
+ };
2896
+ // A pan start cancels the mousedown, which also cancels the focus the
2897
+ // click would have given the wrapper — so with keyboard navigation on,
2898
+ // focus it explicitly or the arrow keys never reach it.
2899
+ this.focusForKeyboard = function () {
2900
+ var _a;
2901
+ var wrapper = _this.wrapperComponent;
2902
+ if (!wrapper || _this.setup.keyboard.disabled)
2903
+ return;
2904
+ var active = (_a = wrapper.ownerDocument) === null || _a === void 0 ? void 0 : _a.activeElement;
2905
+ if (active && wrapper.contains(active))
2906
+ return;
2907
+ if (typeof wrapper.focus === "function") {
2908
+ wrapper.focus({ preventScroll: true });
2909
+ }
2910
+ };
2911
+ /// ///////
2912
+ // Text selection (#467)
2913
+ /// ///////
2914
+ // The stylesheet no longer disables text selection globally, so users can
2915
+ // select and copy content. While a pan gesture is active the wrapper gets
2916
+ // an inline `user-select: none` so the drag does not also select text.
2917
+ this.lockTextSelection = function () {
2918
+ var wrapper = _this.wrapperComponent;
2919
+ if (!wrapper || _this.selectionLock)
2920
+ return;
2921
+ _this.selectionLock = {
2922
+ userSelect: wrapper.style.userSelect,
2923
+ webkitUserSelect: wrapper.style.webkitUserSelect,
2924
+ };
2925
+ wrapper.style.userSelect = "none";
2926
+ wrapper.style.webkitUserSelect = "none";
2927
+ };
2928
+ this.unlockTextSelection = function () {
2929
+ var lock = _this.selectionLock;
2930
+ _this.selectionLock = null;
2931
+ var wrapper = _this.wrapperComponent;
2932
+ if (!wrapper || !lock)
2933
+ return;
2934
+ wrapper.style.userSelect = lock.userSelect;
2935
+ wrapper.style.webkitUserSelect = lock.webkitUserSelect;
2936
+ };
2937
+ /// ///////
2938
+ // Initial layout
2939
+ /// ///////
2940
+ // `fitOnInit` wins over `centerOnInit` (a fit is always centred). Falls
2941
+ // back to centring while the content has no size yet; `onSizeChange`
2942
+ // re-runs this once it does. Returns whether both boxes had a size, i.e.
2943
+ // whether this was a real initial layout.
2944
+ this.applyInitialLayout = function () {
2945
+ var fitOnInit = _this.setup.fitOnInit;
2946
+ var _a = _this, wrapperComponent = _a.wrapperComponent, contentComponent = _a.contentComponent;
2947
+ var hasSizes = !!wrapperComponent &&
2948
+ !!contentComponent &&
2949
+ wrapperComponent.clientWidth > 0 &&
2950
+ wrapperComponent.clientHeight > 0 &&
2951
+ (contentComponent.offsetWidth > 0 || contentComponent.offsetHeight > 0);
2952
+ if (fitOnInit) {
2953
+ var fitted = calculateFitToView(_this, fitOnInit === "cover" ? "cover" : "contain");
2954
+ if (fitted) {
2955
+ _this.setState(fitted.scale, fitted.positionX, fitted.positionY);
2956
+ return hasSizes;
2957
+ }
2958
+ }
2959
+ _this.setCenter();
2960
+ return hasSizes;
2961
+ };
2287
2962
  this.setCenter = function () {
2288
2963
  if (_this.wrapperComponent && _this.contentComponent) {
2289
2964
  var targetState = getCenterPosition(_this.state.scale, _this.wrapperComponent, _this.contentComponent);
@@ -2376,12 +3051,12 @@ var ZoomPanPinch = /** @class */ (function () {
2376
3051
  _this.contentComponent = contentComponent;
2377
3052
  handleCalculateBounds(_this, _this.state.scale);
2378
3053
  _this.handleInitializeWrapperEvents(wrapperComponent);
2379
- _this.handleInitialize(contentComponent);
3054
+ _this.handleInitialize();
3055
+ _this.observeSizes(wrapperComponent, contentComponent);
2380
3056
  _this.initializeWindowEvents();
2381
3057
  _this.isInitialized = true;
2382
3058
  var ctx = getContext(_this);
2383
3059
  handleCallback(ctx, undefined, _this.props.onInit);
2384
- assignRef(_this.props.ref, ctx);
2385
3060
  };
2386
3061
  this.props = props;
2387
3062
  this.setup = createSetup(this.props);
@@ -2487,174 +3162,307 @@ var useResize = function (ref, onResize, dependencies) {
2487
3162
 
2488
3163
  var previewStyles = {
2489
3164
  position: "absolute",
2490
- zIndex: 2,
3165
+ zIndex: 3,
2491
3166
  top: "0px",
2492
3167
  left: "0px",
2493
3168
  boxSizing: "border-box",
2494
- border: "3px solid red",
3169
+ border: "2px solid red",
2495
3170
  transformOrigin: "0% 0%",
2496
- boxShadow: "rgba(0,0,0,0.2) 0 0 0 10000000px",
2497
3171
  pointerEvents: "none",
2498
3172
  };
3173
+ var wrapperStyles = {
3174
+ position: "absolute",
3175
+ top: "0px",
3176
+ left: "0px",
3177
+ transformOrigin: "0% 0%",
3178
+ boxSizing: "border-box",
3179
+ zIndex: 1,
3180
+ pointerEvents: "none",
3181
+ };
3182
+ var maskStyles = {
3183
+ position: "absolute",
3184
+ top: "0px",
3185
+ left: "0px",
3186
+ zIndex: 2,
3187
+ pointerEvents: "none",
3188
+ display: "block",
3189
+ };
3190
+ var getTouchPoint = function (event) {
3191
+ var _a;
3192
+ var touch = (_a = event.touches[0]) !== null && _a !== void 0 ? _a : event.changedTouches[0];
3193
+ if (!touch)
3194
+ return null;
3195
+ return { x: touch.clientX, y: touch.clientY };
3196
+ };
3197
+ var isInside = function (element, target) {
3198
+ return !!element &&
3199
+ !!target &&
3200
+ (target === element || element.contains(target));
3201
+ };
2499
3202
  var MiniMap = function (_a) {
2500
- var _b = _a.width, width = _b === void 0 ? 200 : _b, _c = _a.height, height = _c === void 0 ? 200 : _c, _d = _a.borderColor, borderColor = _d === void 0 ? "red" : _d, previewStyle = _a.previewStyle, wrapperClassName = _a.wrapperClassName, previewClassName = _a.previewClassName, children = _a.children, _e = _a.panning, panning = _e === void 0 ? true : _e, rest = __rest(_a, ["width", "height", "borderColor", "previewStyle", "wrapperClassName", "previewClassName", "children", "panning"]);
2501
- var _f = React.useState(false), initialized = _f[0], setInitialized = _f[1];
3203
+ var _b = _a.width, width = _b === void 0 ? 200 : _b, _c = _a.height, height = _c === void 0 ? 200 : _c, _d = _a.borderColor, borderColor = _d === void 0 ? "red" : _d, _e = _a.maskColor, maskColor = _e === void 0 ? "rgba(0, 0, 0, 0.2)" : _e, previewStyle = _a.previewStyle, wrapperClassName = _a.wrapperClassName, previewClassName = _a.previewClassName, children = _a.children, _f = _a.panning, panning = _f === void 0 ? true : _f, _g = _a.inversePan, inversePan = _g === void 0 ? false : _g, _h = _a.zoomable, zoomable = _h === void 0 ? false : _h, _j = _a.zoomStep, zoomStep = _j === void 0 ? 0.2 : _j, _k = _a.offsetScale, offsetScale = _k === void 0 ? 5 : _k, onClick = _a.onClick, rest = __rest(_a, ["width", "height", "borderColor", "maskColor", "previewStyle", "wrapperClassName", "previewClassName", "children", "panning", "inversePan", "zoomable", "zoomStep", "offsetScale", "onClick"]);
3204
+ var _l = React.useState(false), initialized = _l[0], setInitialized = _l[1];
2502
3205
  var instance = useTransformContext();
2503
- var _g = React.useState(false), isDown = _g[0], setIsDown = _g[1];
2504
3206
  var mainRef = React.useRef(null);
2505
3207
  var wrapperRef = React.useRef(null);
2506
3208
  var previewRef = React.useRef(null);
3209
+ var maskPathRef = React.useRef(null);
3210
+ var dragRef = React.useRef(null);
3211
+ var layoutRef = React.useRef(null);
3212
+ // Latest props for the document listeners, which are registered once.
3213
+ var optionsRef = React.useRef({ panning: panning, inversePan: inversePan, zoomStep: zoomStep, onClick: onClick });
3214
+ optionsRef.current = { panning: panning, inversePan: inversePan, zoomStep: zoomStep, onClick: onClick };
2507
3215
  var getViewportSize = React.useCallback(function () {
2508
3216
  if (instance.wrapperComponent) {
2509
3217
  var rect = instance.wrapperComponent.getBoundingClientRect();
2510
- return {
2511
- width: rect.width,
2512
- height: rect.height,
2513
- };
3218
+ return { width: rect.width, height: rect.height };
2514
3219
  }
2515
- return {
2516
- width: 0,
2517
- height: 0,
2518
- };
2519
- }, [instance.wrapperComponent]);
3220
+ return { width: 0, height: 0 };
3221
+ }, [instance]);
2520
3222
  var getContentSize = React.useCallback(function () {
2521
3223
  if (instance.contentComponent) {
2522
3224
  var rect = instance.contentComponent.getBoundingClientRect();
2523
- return {
2524
- width: rect.width / instance.state.scale,
2525
- height: rect.height / instance.state.scale,
2526
- };
3225
+ var scale = instance.state.scale;
3226
+ return { width: rect.width / scale, height: rect.height / scale };
2527
3227
  }
2528
- return {
2529
- width: 0,
2530
- height: 0,
2531
- };
2532
- }, [instance.contentComponent, instance.state.scale]);
2533
- var computeMiniMapScale = React.useCallback(function () {
2534
- var contentSize = getContentSize();
2535
- var scaleX = width / contentSize.width;
2536
- var scaleY = height / contentSize.height;
2537
- var scale = scaleY > scaleX ? scaleX : scaleY;
2538
- return scale;
2539
- }, [getContentSize, height, width]);
2540
- var computeMiniMapSize = function () {
2541
- var contentSize = getContentSize();
2542
- var scaleX = width / contentSize.width;
2543
- var scaleY = height / contentSize.height;
2544
- if (scaleY > scaleX) {
2545
- return { width: width, height: contentSize.height * scaleX };
3228
+ return { width: 0, height: 0 };
3229
+ }, [instance]);
3230
+ /**
3231
+ * Like React Flow, the map shows the union of the content and the current
3232
+ * viewport (plus `offsetScale` padding) fitted into the box, so the
3233
+ * viewport indicator never leaves the mini map even when the view is
3234
+ * panned or zoomed past the content.
3235
+ */
3236
+ var computeLayout = React.useCallback(function () {
3237
+ var content = getContentSize();
3238
+ var viewport = getViewportSize();
3239
+ var _a = instance.state, scale = _a.scale, positionX = _a.positionX, positionY = _a.positionY;
3240
+ if (!content.width || !content.height || !width || !height || !scale) {
3241
+ return null;
2546
3242
  }
2547
- return { width: contentSize.width * scaleY, height: height };
2548
- };
2549
- var computeMiniMapStyle = function () {
2550
- var scale = computeMiniMapScale();
2551
- var style = {
2552
- transform: "scale(".concat(scale || 1, ")"),
2553
- transformOrigin: "0% 0%",
2554
- position: "absolute",
2555
- boxSizing: "border-box",
2556
- zIndex: 1,
2557
- // overflow: "hidden",
3243
+ var viewX = -positionX / scale;
3244
+ var viewY = -positionY / scale;
3245
+ var viewWidth = viewport.width / scale;
3246
+ var viewHeight = viewport.height / scale;
3247
+ var minX = Math.min(0, viewX);
3248
+ var minY = Math.min(0, viewY);
3249
+ var maxX = Math.max(content.width, viewX + viewWidth);
3250
+ var maxY = Math.max(content.height, viewY + viewHeight);
3251
+ var boundsWidth = maxX - minX;
3252
+ var boundsHeight = maxY - minY;
3253
+ var viewScale = Math.max(boundsWidth / width, boundsHeight / height);
3254
+ var fitWidth = viewScale * width;
3255
+ var fitHeight = viewScale * height;
3256
+ var offset = offsetScale * viewScale;
3257
+ var originX = minX - (fitWidth - boundsWidth) / 2 - offset;
3258
+ var originY = minY - (fitHeight - boundsHeight) / 2 - offset;
3259
+ var mapScale = width / (fitWidth + offset * 2);
3260
+ return {
3261
+ mapScale: mapScale,
3262
+ originX: originX,
3263
+ originY: originY,
3264
+ contentWidth: content.width,
3265
+ contentHeight: content.height,
3266
+ previewX: (viewX - originX) * mapScale,
3267
+ previewY: (viewY - originY) * mapScale,
3268
+ previewWidth: viewWidth * mapScale,
3269
+ previewHeight: viewHeight * mapScale,
2558
3270
  };
3271
+ }, [getContentSize, getViewportSize, height, instance, offsetScale, width]);
3272
+ var transformMiniMap = React.useCallback(function () {
3273
+ var layout = computeLayout();
3274
+ layoutRef.current = layout;
3275
+ if (!layout)
3276
+ return;
3277
+ var px = function (value) { return "".concat(roundNumber(value, 2), "px"); };
2559
3278
  if (wrapperRef.current) {
2560
- var el = wrapperRef.current.style;
2561
- el.transform = style.transform;
2562
- el.transformOrigin = style.transformOrigin;
2563
- el.position = style.position;
2564
- el.boxSizing = style.boxSizing;
2565
- el.zIndex = String(style.zIndex);
2566
- }
2567
- };
2568
- var transformMiniMap = function () {
2569
- computeMiniMapStyle();
2570
- var miniSize = computeMiniMapSize();
2571
- var wrapSize = getContentSize();
2572
- if (wrapperRef.current) {
2573
- wrapperRef.current.style.width = "".concat(wrapSize.width, "px");
2574
- wrapperRef.current.style.height = "".concat(wrapSize.height, "px");
2575
- }
2576
- if (mainRef.current) {
2577
- mainRef.current.style.width = "".concat(miniSize.width, "px");
2578
- mainRef.current.style.height = "".concat(miniSize.height, "px");
3279
+ var style = wrapperRef.current.style;
3280
+ style.width = px(layout.contentWidth);
3281
+ style.height = px(layout.contentHeight);
3282
+ style.transform = "translate(".concat(px(-layout.originX * layout.mapScale), ", ").concat(px(-layout.originY * layout.mapScale), ") scale(").concat(roundNumber(layout.mapScale, 4), ")");
2579
3283
  }
2580
3284
  if (previewRef.current) {
2581
- var size = getViewportSize();
2582
- var scale = computeMiniMapScale();
2583
- var previewScale = scale * (1 / instance.state.scale);
2584
- var transform = instance.handleTransformStyles(-instance.state.positionX * previewScale, -instance.state.positionY * previewScale, 1);
2585
- previewRef.current.style.transform = transform;
2586
- previewRef.current.style.width = "".concat(size.width * previewScale, "px");
2587
- previewRef.current.style.height = "".concat(size.height * previewScale, "px");
3285
+ var style = previewRef.current.style;
3286
+ style.transform = "translate(".concat(px(layout.previewX), ", ").concat(px(layout.previewY), ")");
3287
+ style.width = px(layout.previewWidth);
3288
+ style.height = px(layout.previewHeight);
2588
3289
  }
2589
- };
2590
- var initialize = function () {
2591
- transformMiniMap();
2592
- };
2593
- useTransformEffect(function () {
2594
- transformMiniMap();
2595
- });
3290
+ if (maskPathRef.current) {
3291
+ var x = roundNumber(layout.previewX, 2);
3292
+ var y = roundNumber(layout.previewY, 2);
3293
+ var w = roundNumber(layout.previewWidth, 2);
3294
+ var h = roundNumber(layout.previewHeight, 2);
3295
+ maskPathRef.current.setAttribute("d", "M0 0H".concat(width, "V").concat(height, "H0Z M").concat(x, " ").concat(y, "h").concat(w, "v").concat(h, "h").concat(-w, "Z"));
3296
+ }
3297
+ }, [computeLayout, height, width]);
3298
+ useTransformEffect(transformMiniMap);
2596
3299
  useTransformInit(function () {
2597
- initialize();
3300
+ transformMiniMap();
2598
3301
  setInitialized(true);
2599
3302
  });
2600
- useResize(instance.contentComponent, initialize, [initialized]);
3303
+ useResize(instance.contentComponent, transformMiniMap, [initialized]);
3304
+ React.useEffect(function () {
3305
+ transformMiniMap();
3306
+ }, [transformMiniMap]);
2601
3307
  React.useEffect(function () {
2602
- var _a, _b;
2603
- var move = function (e) {
3308
+ var element = mainRef.current;
3309
+ if (!element)
3310
+ return;
3311
+ var getMapScale = function () {
2604
3312
  var _a, _b;
2605
- if (panning &&
2606
- isDown &&
2607
- instance.contentComponent &&
2608
- previewRef.current &&
2609
- mainRef.current) {
2610
- var scale = computeMiniMapScale();
2611
- var previewRect = previewRef.current.getBoundingClientRect();
2612
- var mainRect = mainRef.current.getBoundingClientRect();
2613
- var relativeX = (e.clientX - mainRect.left) / scale;
2614
- var relativeY = (e.clientY - mainRect.top) / scale;
2615
- var x = relativeX - previewRect.width / 2;
2616
- var y = relativeY - previewRect.height / 2;
2617
- var instanceWidth = (((_a = instance.wrapperComponent) === null || _a === void 0 ? void 0 : _a.offsetWidth) || 0) * instance.state.scale;
2618
- var instanceHeight = (((_b = instance.wrapperComponent) === null || _b === void 0 ? void 0 : _b.offsetHeight) || 0) * instance.state.scale;
2619
- var limitWidth = instanceWidth - previewRect.width * 2 * instance.state.scale;
2620
- var limitHeight = instanceHeight - previewRect.height * 2 * instance.state.scale;
2621
- var boundedX = boundLimiter(x * instance.state.scale, 0, limitWidth, true);
2622
- var boundedY = boundLimiter(y * instance.state.scale, 0, limitHeight, true);
2623
- instance.setState(instance.state.scale, -boundedX, -boundedY);
2624
- }
3313
+ var layout = (_a = layoutRef.current) !== null && _a !== void 0 ? _a : computeLayout();
3314
+ return (_b = layout === null || layout === void 0 ? void 0 : layout.mapScale) !== null && _b !== void 0 ? _b : 0;
2625
3315
  };
2626
- var setDown = function (e) {
3316
+ var start = function (point, target) {
3317
+ if (!optionsRef.current.panning)
3318
+ return;
3319
+ if (!isInside(element, target))
3320
+ return;
3321
+ if (!instance.wrapperComponent || !instance.contentComponent)
3322
+ return;
3323
+ handleCancelAnimation(instance);
3324
+ dragRef.current = { x: point.x, y: point.y, moved: false };
3325
+ element.style.cursor = "grabbing";
3326
+ };
3327
+ var move = function (point) {
3328
+ var drag = dragRef.current;
3329
+ if (!drag)
3330
+ return;
3331
+ var deltaX = point.x - drag.x;
3332
+ var deltaY = point.y - drag.y;
3333
+ drag.x = point.x;
3334
+ drag.y = point.y;
3335
+ if (!deltaX && !deltaY)
3336
+ return;
3337
+ drag.moved = true;
3338
+ var mapScale = getMapScale();
3339
+ var wrapperComponent = instance.wrapperComponent, contentComponent = instance.contentComponent, setup = instance.setup, state = instance.state;
3340
+ if (!mapScale || !wrapperComponent || !contentComponent)
3341
+ return;
3342
+ // Dragging by one mini map px moves the viewport by 1 / mapScale
3343
+ // content units, so the indicator follows the pointer 1:1.
3344
+ var direction = optionsRef.current.inversePan ? 1 : -1;
3345
+ var moveScale = (direction * state.scale) / mapScale;
3346
+ var nextX = state.positionX + deltaX * moveScale;
3347
+ var nextY = state.positionY + deltaY * moveScale;
3348
+ var bounds = handleCalculateBounds(instance, state.scale);
3349
+ var _a = getMouseBoundedPosition(nextX, nextY, bounds, setup.limitToBounds, 0, 0, wrapperComponent), x = _a.x, y = _a.y;
3350
+ if (x === state.positionX && y === state.positionY)
3351
+ return;
3352
+ instance.setState(state.scale, x, y);
3353
+ };
3354
+ var stop = function (event, point) {
2627
3355
  var _a;
2628
- if (((_a = mainRef.current) === null || _a === void 0 ? void 0 : _a.contains(e.target)) ||
2629
- e.target === mainRef.current) {
2630
- move(e);
2631
- setIsDown(true);
3356
+ var drag = dragRef.current;
3357
+ if (!drag)
3358
+ return;
3359
+ dragRef.current = null;
3360
+ element.style.cursor = optionsRef.current.panning ? "grab" : "";
3361
+ var handleClick = optionsRef.current.onClick;
3362
+ if (drag.moved || !handleClick || !point)
3363
+ return;
3364
+ var layout = (_a = layoutRef.current) !== null && _a !== void 0 ? _a : computeLayout();
3365
+ if (!layout)
3366
+ return;
3367
+ var rect = element.getBoundingClientRect();
3368
+ handleClick(event, {
3369
+ x: layout.originX + (point.x - rect.left) / layout.mapScale,
3370
+ y: layout.originY + (point.y - rect.top) / layout.mapScale,
3371
+ });
3372
+ };
3373
+ var onMouseDown = function (event) {
3374
+ if (event.button !== 0)
3375
+ return;
3376
+ start({ x: event.clientX, y: event.clientY }, event.target);
3377
+ };
3378
+ var onMouseMove = function (event) {
3379
+ if (!dragRef.current)
3380
+ return;
3381
+ // The mouse was released outside the window: end the drag.
3382
+ if (event.buttons === 0) {
3383
+ stop(event, null);
3384
+ return;
2632
3385
  }
3386
+ move({ x: event.clientX, y: event.clientY });
3387
+ };
3388
+ var onMouseUp = function (event) {
3389
+ stop(event, { x: event.clientX, y: event.clientY });
2633
3390
  };
2634
- var setUp = function () {
2635
- setIsDown(false);
3391
+ var onTouchStart = function (event) {
3392
+ if (event.touches.length !== 1)
3393
+ return;
3394
+ var point = getTouchPoint(event);
3395
+ if (point)
3396
+ start(point, event.target);
3397
+ };
3398
+ var onTouchMove = function (event) {
3399
+ if (!dragRef.current)
3400
+ return;
3401
+ if (event.touches.length !== 1) {
3402
+ stop(event, null);
3403
+ return;
3404
+ }
3405
+ var point = getTouchPoint(event);
3406
+ if (point)
3407
+ move(point);
3408
+ };
3409
+ var onTouchEnd = function (event) {
3410
+ stop(event, getTouchPoint(event));
2636
3411
  };
2637
3412
  // Listen on the mini map's own document so it keeps working inside
2638
3413
  // portal windows and iframes.
2639
- var doc = (_b = (_a = mainRef.current) === null || _a === void 0 ? void 0 : _a.ownerDocument) !== null && _b !== void 0 ? _b : document;
2640
- doc.addEventListener("mousedown", setDown);
2641
- doc.addEventListener("mouseup", setUp);
2642
- doc.addEventListener("mousemove", move);
3414
+ var doc = element.ownerDocument;
3415
+ doc.addEventListener("mousedown", onMouseDown);
3416
+ doc.addEventListener("mousemove", onMouseMove);
3417
+ doc.addEventListener("mouseup", onMouseUp);
3418
+ doc.addEventListener("touchstart", onTouchStart);
3419
+ doc.addEventListener("touchmove", onTouchMove);
3420
+ doc.addEventListener("touchend", onTouchEnd);
3421
+ doc.addEventListener("touchcancel", onTouchEnd);
2643
3422
  return function () {
2644
- doc.removeEventListener("mousedown", setDown);
2645
- doc.removeEventListener("mousemove", move);
2646
- doc.removeEventListener("mouseup", setUp);
3423
+ doc.removeEventListener("mousedown", onMouseDown);
3424
+ doc.removeEventListener("mousemove", onMouseMove);
3425
+ doc.removeEventListener("mouseup", onMouseUp);
3426
+ doc.removeEventListener("touchstart", onTouchStart);
3427
+ doc.removeEventListener("touchmove", onTouchMove);
3428
+ doc.removeEventListener("touchend", onTouchEnd);
3429
+ doc.removeEventListener("touchcancel", onTouchEnd);
3430
+ dragRef.current = null;
2647
3431
  };
2648
- }, [computeMiniMapScale, instance, isDown, panning]);
2649
- var wrapperStyle = React.useMemo(function () {
2650
- return {
2651
- position: "relative",
2652
- zIndex: 2,
2653
- // overflow: "hidden",
2654
- userSelect: "none",
3432
+ }, [computeLayout, instance]);
3433
+ React.useEffect(function () {
3434
+ var element = mainRef.current;
3435
+ if (!element || !zoomable)
3436
+ return;
3437
+ var onWheel = function (event) {
3438
+ var wrapperComponent = instance.wrapperComponent, contentComponent = instance.contentComponent, setup = instance.setup, state = instance.state;
3439
+ if (setup.disabled || !wrapperComponent || !contentComponent)
3440
+ return;
3441
+ if (!event.deltaY)
3442
+ return;
3443
+ if (event.cancelable)
3444
+ event.preventDefault();
3445
+ event.stopPropagation();
3446
+ var delta = event.deltaY < 0 ? 1 : -1;
3447
+ var newScale = handleCalculateButtonZoom(instance, delta, optionsRef.current.zoomStep);
3448
+ if (newScale === state.scale)
3449
+ return;
3450
+ // Zoom around the centre of the current viewport.
3451
+ var centerX = (wrapperComponent.offsetWidth / 2 - state.positionX) / state.scale;
3452
+ var centerY = (wrapperComponent.offsetHeight / 2 - state.positionY) / state.scale;
3453
+ handleCancelAnimation(instance);
3454
+ var target = handleZoomToPoint(instance, newScale, centerX, centerY);
3455
+ if (!target)
3456
+ return;
3457
+ instance.setState(target.scale, target.positionX, target.positionY);
2655
3458
  };
2656
- }, []);
2657
- return (jsxRuntime.jsxs("div", __assign({}, rest, { ref: mainRef, style: wrapperStyle, className: "rzpp-mini-map ".concat(rest.className || "").trim() }, { children: [jsxRuntime.jsx("div", __assign({ style: { pointerEvents: "none" }, ref: wrapperRef, className: "rzpp-minimap-wrapper ".concat(wrapperClassName || "").trim() }, { children: children })), jsxRuntime.jsx("div", { className: "rzpp-minimap-preview ".concat(previewClassName || "").trim(), ref: previewRef, style: __assign(__assign(__assign({}, previewStyles), { borderColor: borderColor }), previewStyle) })] })));
3459
+ element.addEventListener("wheel", onWheel, { passive: false });
3460
+ return function () {
3461
+ element.removeEventListener("wheel", onWheel);
3462
+ };
3463
+ }, [instance, zoomable]);
3464
+ var containerStyle = __assign({ position: "relative", zIndex: 2, width: "".concat(width, "px"), height: "".concat(height, "px"), overflow: "hidden", userSelect: "none", WebkitUserSelect: "none", touchAction: "none", cursor: panning ? "grab" : undefined }, rest.style);
3465
+ return (jsxRuntime.jsxs("div", __assign({}, rest, { ref: mainRef, style: containerStyle, className: "rzpp-mini-map ".concat(rest.className || "").trim() }, { children: [jsxRuntime.jsx("div", __assign({ style: wrapperStyles, ref: wrapperRef, className: "rzpp-minimap-wrapper ".concat(wrapperClassName || "").trim() }, { children: children })), jsxRuntime.jsx("svg", __assign({ className: "rzpp-minimap-mask", style: maskStyles, width: width, height: height, viewBox: "0 0 ".concat(width, " ").concat(height), "aria-hidden": "true" }, { children: jsxRuntime.jsx("path", { ref: maskPathRef, fill: maskColor, fillRule: "evenodd", d: "M0 0H".concat(width, "V").concat(height, "H0Z") }) })), jsxRuntime.jsx("div", { className: "rzpp-minimap-preview ".concat(previewClassName || "").trim(), ref: previewRef, style: __assign(__assign(__assign({}, previewStyles), { borderColor: borderColor }), previewStyle) })] })));
2658
3466
  };
2659
3467
 
2660
3468
  function styleInject(css, ref) {
@@ -2684,12 +3492,13 @@ function styleInject(css, ref) {
2684
3492
  }
2685
3493
  }
2686
3494
 
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";
3495
+ 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
3496
  var styles = {"wrapper":"transform-component-module_wrapper__SPB86","content":"transform-component-module_content__FBWxo","infiniteGrid":"transform-component-module_infiniteGrid__Z-aP3"};
2689
3497
  styleInject(css_248z);
2690
3498
 
2691
3499
  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;
3500
+ var _b;
3501
+ 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
3502
  var instance = React.useContext(Context);
2694
3503
  var init = instance.init, cleanupWindowEvents = instance.cleanupWindowEvents;
2695
3504
  var wrapperRef = React.useRef(null);
@@ -2722,7 +3531,13 @@ var TransformComponent = function (_a) {
2722
3531
  sync();
2723
3532
  return instance.onChange(sync);
2724
3533
  }, [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({
3534
+ // Keyboard navigation (#254) needs a focus target; `wrapperProps.tabIndex`
3535
+ // still wins because it is spread afterwards.
3536
+ var keyboardEnabled = !((_b = instance.setup.keyboard) === null || _b === void 0 ? void 0 : _b.disabled);
3537
+ return (jsxRuntime.jsxs("div", __assign({
3538
+ // The wrapper is a keyboard-operated widget when navigation is on.
3539
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
3540
+ 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
3541
  // Inline so the zoom anchor survives environments where the
2727
3542
  // stylesheet is not applied, e.g. a shadow root (#371, #444).
2728
3543
  transformOrigin: "0 0" }, contentStyle), { transform: getTransformStyles(instance.state.positionX, instance.state.positionY, instance.state.scale) }) }, { children: children }))] })));
@@ -2784,8 +3599,8 @@ var Virtualize = React.forwardRef(function (_a, ref) {
2784
3599
  scale: instance.state.scale,
2785
3600
  positionX: instance.state.positionX,
2786
3601
  positionY: instance.state.positionY,
2787
- viewportWidth: wrapper.offsetWidth,
2788
- viewportHeight: wrapper.offsetHeight,
3602
+ viewportWidth: wrapper.clientWidth,
3603
+ viewportHeight: wrapper.clientHeight,
2789
3604
  margin: margin,
2790
3605
  threshold: threshold,
2791
3606
  });
@@ -2870,13 +3685,37 @@ var useTransformInit = function (callback) {
2870
3685
  }, []);
2871
3686
  };
2872
3687
 
3688
+ var takeSnapshot = function (state) { return ({
3689
+ scale: state.scale,
3690
+ positionX: state.positionX,
3691
+ positionY: state.positionY,
3692
+ }); };
3693
+ var isSameSnapshot = function (snapshot, state) {
3694
+ return snapshot !== null &&
3695
+ snapshot.scale === state.scale &&
3696
+ snapshot.positionX === state.positionX &&
3697
+ snapshot.positionY === state.positionY;
3698
+ };
3699
+
2873
3700
  var useTransformEffect = function (callback) {
2874
3701
  var libraryContext = useTransformContext();
3702
+ // Starts as the state the consumer rendered with, so a transform applied
3703
+ // during mount (initialPosition*, centerOnInit, fitOnInit) — which happens
3704
+ // in a layout effect, before this subscription exists — is delivered once.
3705
+ var lastSeen = React.useRef(null);
3706
+ if (lastSeen.current === null) {
3707
+ lastSeen.current = takeSnapshot(libraryContext.state);
3708
+ }
2875
3709
  React.useEffect(function () {
2876
3710
  var unmountCallback;
2877
3711
  var unmount = libraryContext.onChange(function (ref) {
3712
+ lastSeen.current = takeSnapshot(ref.instance.state);
2878
3713
  unmountCallback = callback(getState(ref.instance));
2879
3714
  });
3715
+ if (!isSameSnapshot(lastSeen.current, libraryContext.state)) {
3716
+ lastSeen.current = takeSnapshot(libraryContext.state);
3717
+ unmountCallback = callback(getState(libraryContext));
3718
+ }
2880
3719
  return function () {
2881
3720
  unmount();
2882
3721
  unmountCallback === null || unmountCallback === void 0 ? void 0 : unmountCallback();
@@ -2886,16 +3725,27 @@ var useTransformEffect = function (callback) {
2886
3725
 
2887
3726
  function useTransformComponent(callback) {
2888
3727
  var libraryContext = useTransformContext();
3728
+ var lastSeen = React.useRef(null);
2889
3729
  var _a = React.useState(function () {
3730
+ lastSeen.current = takeSnapshot(libraryContext.state);
2890
3731
  return callback(getState(libraryContext));
2891
3732
  }), transformRender = _a[0], setTransformRender = _a[1];
2892
3733
  React.useEffect(function () {
2893
3734
  var mounted = true;
2894
3735
  var unmount = libraryContext.onChange(function (ref) {
2895
3736
  if (mounted) {
3737
+ lastSeen.current = takeSnapshot(ref.instance.state);
2896
3738
  setTransformRender(callback(getState(ref.instance)));
2897
3739
  }
2898
3740
  });
3741
+ // The instance initializes in a layout effect, so a transform applied on
3742
+ // mount (initialPosition*, centerOnInit, fitOnInit) can land before this
3743
+ // subscription exists. Catch up when the state moved since the last
3744
+ // render; the snapshot check keeps this from re-rendering in a loop.
3745
+ if (!isSameSnapshot(lastSeen.current, libraryContext.state)) {
3746
+ lastSeen.current = takeSnapshot(libraryContext.state);
3747
+ setTransformRender(callback(getState(libraryContext)));
3748
+ }
2899
3749
  return function () {
2900
3750
  unmount();
2901
3751
  mounted = false;