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