motion-dom 14.5.0 → 14.7.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 (104) hide show
  1. package/dist/cjs/index.js +706 -632
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/AsyncMotionValueAnimation.mjs +3 -6
  4. package/dist/es/animation/AsyncMotionValueAnimation.mjs.map +1 -1
  5. package/dist/es/animation/JSAnimation.mjs +18 -30
  6. package/dist/es/animation/JSAnimation.mjs.map +1 -1
  7. package/dist/es/animation/NativeAnimation.mjs +14 -8
  8. package/dist/es/animation/NativeAnimation.mjs.map +1 -1
  9. package/dist/es/animation/animate/effects.mjs +5 -2
  10. package/dist/es/animation/animate/effects.mjs.map +1 -1
  11. package/dist/es/animation/generators/inertia.mjs +3 -2
  12. package/dist/es/animation/generators/inertia.mjs.map +1 -1
  13. package/dist/es/animation/generators/spring.mjs +50 -52
  14. package/dist/es/animation/generators/spring.mjs.map +1 -1
  15. package/dist/es/animation/interfaces/visual-element-target.mjs +1 -1
  16. package/dist/es/animation/interfaces/visual-element-target.mjs.map +1 -1
  17. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +7 -15
  18. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs.map +1 -1
  19. package/dist/es/animation/keyframes/KeyframesResolver.mjs.map +1 -1
  20. package/dist/es/animation/keyframes/utils/unit-conversion.mjs +8 -7
  21. package/dist/es/animation/keyframes/utils/unit-conversion.mjs.map +1 -1
  22. package/dist/es/animation/optimized-appear/data-id.mjs +1 -3
  23. package/dist/es/animation/optimized-appear/data-id.mjs.map +1 -1
  24. package/dist/es/animation/utils/can-animate.mjs +1 -0
  25. package/dist/es/animation/utils/can-animate.mjs.map +1 -1
  26. package/dist/es/animation/utils/css-variables-conversion.mjs +2 -1
  27. package/dist/es/animation/utils/css-variables-conversion.mjs.map +1 -1
  28. package/dist/es/animation/utils/is-transition-defined.mjs +1 -0
  29. package/dist/es/animation/utils/is-transition-defined.mjs.map +1 -1
  30. package/dist/es/animation/waapi/supports/waapi.mjs +8 -2
  31. package/dist/es/animation/waapi/supports/waapi.mjs.map +1 -1
  32. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +44 -21
  33. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -1
  34. package/dist/es/animation/waapi/utils/accelerated-values.mjs +4 -1
  35. package/dist/es/animation/waapi/utils/accelerated-values.mjs.map +1 -1
  36. package/dist/es/effects/style/transform.mjs +4 -20
  37. package/dist/es/effects/style/transform.mjs.map +1 -1
  38. package/dist/es/frameloop/process-frame.mjs +42 -0
  39. package/dist/es/frameloop/process-frame.mjs.map +1 -0
  40. package/dist/es/frameloop/render-step.mjs +15 -1
  41. package/dist/es/frameloop/render-step.mjs.map +1 -1
  42. package/dist/es/gestures/drag/VisualElementDragControls.mjs +94 -67
  43. package/dist/es/gestures/drag/VisualElementDragControls.mjs.map +1 -1
  44. package/dist/es/gestures/pan/PanSession.mjs +28 -39
  45. package/dist/es/gestures/pan/PanSession.mjs.map +1 -1
  46. package/dist/es/index.mjs +4 -2
  47. package/dist/es/index.mjs.map +1 -1
  48. package/dist/es/layout/LayoutAnimationBuilder.mjs +2 -2
  49. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  50. package/dist/es/projection/animation/mix-values.mjs +3 -11
  51. package/dist/es/projection/animation/mix-values.mjs.map +1 -1
  52. package/dist/es/projection/geometry/delta-apply.mjs +10 -6
  53. package/dist/es/projection/geometry/delta-apply.mjs.map +1 -1
  54. package/dist/es/projection/geometry/delta-calc.mjs +2 -2
  55. package/dist/es/projection/geometry/delta-calc.mjs.map +1 -1
  56. package/dist/es/projection/geometry/delta-remove.mjs +2 -2
  57. package/dist/es/projection/geometry/delta-remove.mjs.map +1 -1
  58. package/dist/es/projection/node/DocumentProjectionNode.mjs +8 -3
  59. package/dist/es/projection/node/DocumentProjectionNode.mjs.map +1 -1
  60. package/dist/es/projection/node/HTMLProjectionNode.mjs +5 -6
  61. package/dist/es/projection/node/HTMLProjectionNode.mjs.map +1 -1
  62. package/dist/es/projection/node/create-projection-node.mjs +158 -148
  63. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  64. package/dist/es/projection/node/root.mjs +6 -0
  65. package/dist/es/projection/node/root.mjs.map +1 -0
  66. package/dist/es/projection/styles/default-scale-correctors.mjs +3 -4
  67. package/dist/es/projection/styles/default-scale-correctors.mjs.map +1 -1
  68. package/dist/es/projection/styles/transform.mjs +12 -16
  69. package/dist/es/projection/styles/transform.mjs.map +1 -1
  70. package/dist/es/projection/utils/has-transform.mjs +16 -2
  71. package/dist/es/projection/utils/has-transform.mjs.map +1 -1
  72. package/dist/es/render/VisualElement.mjs +20 -37
  73. package/dist/es/render/VisualElement.mjs.map +1 -1
  74. package/dist/es/render/dom/parse-transform.mjs +6 -17
  75. package/dist/es/render/dom/parse-transform.mjs.map +1 -1
  76. package/dist/es/render/html/HTMLVisualElement.mjs +2 -1
  77. package/dist/es/render/html/HTMLVisualElement.mjs.map +1 -1
  78. package/dist/es/render/html/utils/build-transform.mjs +25 -29
  79. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  80. package/dist/es/render/utils/animation-state.mjs +58 -15
  81. package/dist/es/render/utils/animation-state.mjs.map +1 -1
  82. package/dist/es/render/utils/variant-props.mjs +1 -1
  83. package/dist/es/render/utils/variant-props.mjs.map +1 -1
  84. package/dist/es/utils/interpolate.mjs +2 -1
  85. package/dist/es/utils/interpolate.mjs.map +1 -1
  86. package/dist/es/utils/mix/color.mjs +2 -1
  87. package/dist/es/utils/mix/color.mjs.map +1 -1
  88. package/dist/es/utils/mix/complex.mjs +4 -4
  89. package/dist/es/utils/mix/complex.mjs.map +1 -1
  90. package/dist/es/utils/resolve-elements.mjs.map +1 -1
  91. package/dist/es/value/index.mjs +13 -34
  92. package/dist/es/value/index.mjs.map +1 -1
  93. package/dist/es/value/types/color/hex.mjs +13 -26
  94. package/dist/es/value/types/color/hex.mjs.map +1 -1
  95. package/dist/es/value/types/complex/index.mjs +1 -1
  96. package/dist/es/value/types/complex/index.mjs.map +1 -1
  97. package/dist/index.d.ts +111 -30
  98. package/dist/motion-dom.dev.js +690 -625
  99. package/dist/motion-dom.js +1 -1
  100. package/dist/size-rollup-motion-value.js +1 -1
  101. package/dist/size-rollup-motion-value.js.map +1 -1
  102. package/dist/size-rollup-style-effect.js +1 -1
  103. package/dist/size-rollup-style-effect.js.map +1 -1
  104. package/package.json +4 -3
@@ -135,34 +135,21 @@
135
135
  ")",
136
136
  };
137
137
 
138
+ /**
139
+ * #FF0000 has two characters per channel, #F00 one, which is doubled.
140
+ */
141
+ const channel = (v, i, size) => {
142
+ const c = v.substring(1 + i * size, 1 + (i + 1) * size);
143
+ return size > 1 ? c : c + c;
144
+ };
138
145
  function parseHex(v) {
139
- let r = "";
140
- let g = "";
141
- let b = "";
142
- let a = "";
143
- // If we have 6 characters, ie #FF0000
144
- if (v.length > 5) {
145
- r = v.substring(1, 3);
146
- g = v.substring(3, 5);
147
- b = v.substring(5, 7);
148
- a = v.substring(7, 9);
149
- // Or we have 3 characters, ie #F00
150
- }
151
- else {
152
- r = v.substring(1, 2);
153
- g = v.substring(2, 3);
154
- b = v.substring(3, 4);
155
- a = v.substring(4, 5);
156
- r += r;
157
- g += g;
158
- b += b;
159
- a += a;
160
- }
146
+ const size = v.length > 5 ? 2 : 1;
147
+ const alpha = channel(v, 3, size);
161
148
  return {
162
- red: parseInt(r, 16),
163
- green: parseInt(g, 16),
164
- blue: parseInt(b, 16),
165
- alpha: a ? parseInt(a, 16) / 255 : 1,
149
+ red: parseInt(channel(v, 0, size), 16),
150
+ green: parseInt(channel(v, 1, size), 16),
151
+ blue: parseInt(channel(v, 2, size), 16),
152
+ alpha: alpha ? parseInt(alpha, 16) / 255 : 1,
166
153
  };
167
154
  }
168
155
  const hex = {
@@ -539,7 +526,6 @@
539
526
  return orderedOrigin;
540
527
  }
541
528
  const mixComplex = (origin, target) => {
542
- const template = complex.createTransformer(target);
543
529
  const originStats = analyseComplexValue(origin);
544
530
  const targetStats = analyseComplexValue(target);
545
531
  const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length &&
@@ -552,7 +538,7 @@
552
538
  !originStats.values.length)) {
553
539
  return mixVisibility(origin, target);
554
540
  }
555
- return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
541
+ return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), buildTransformer(targetStats));
556
542
  }
557
543
  else {
558
544
  motionUtils.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different");
@@ -621,6 +607,11 @@
621
607
  */
622
608
  let isProcessing = false;
623
609
  let flushNextFrame = false;
610
+ /**
611
+ * The callback currently running. If it schedules itself with `immediate`
612
+ * it's left in place, so as before it doesn't run again this step.
613
+ */
614
+ let running;
624
615
  /**
625
616
  * A set of processes which were marked keepAlive when scheduled.
626
617
  * A keepAlive process is always also held by a frame queue until
@@ -638,7 +629,7 @@
638
629
  nextFrame.add(callback);
639
630
  runNextFrame();
640
631
  }
641
- callback(latestFrameData);
632
+ (running = callback)(latestFrameData);
642
633
  }
643
634
  const step = {
644
635
  /**
@@ -649,6 +640,14 @@
649
640
  const queue = addToCurrentFrame ? thisFrame : nextFrame;
650
641
  if (keepAlive)
651
642
  toKeepAlive.add(callback);
643
+ /**
644
+ * A callback scheduled with `immediate` during processing may
645
+ * already have run this step (for instance, a value it reads was
646
+ * changed by a later callback). Re-adding moves it to the end of
647
+ * the queue, so it runs again. The running callback is excluded,
648
+ * so one that re-schedules itself can't loop forever.
649
+ */
650
+ addToCurrentFrame && callback !== running && queue.delete(callback);
652
651
  queue.add(callback);
653
652
  return callback;
654
653
  },
@@ -683,6 +682,7 @@
683
682
  // Clear the frame so no callbacks remain. This is to avoid
684
683
  // memory leaks should this render step not run for a while.
685
684
  thisFrame.clear();
685
+ running = undefined;
686
686
  isProcessing = false;
687
687
  if (flushNextFrame) {
688
688
  flushNextFrame = false;
@@ -830,37 +830,31 @@
830
830
  };
831
831
  }
832
832
 
833
- const springDefaults = {
834
- // Default spring physics
835
- stiffness: 100,
836
- damping: 10,
837
- mass: 1.0,
838
- // Default duration/bounce-based options
839
- duration: 800, // in ms
840
- bounce: 0.3,
841
- visualDuration: 0.3, // in seconds
842
- // Rest thresholds
843
- restSpeed: {
844
- granular: 0.01,
845
- default: 2,
846
- },
847
- restDelta: {
848
- granular: 0.005,
849
- default: 0.5,
850
- },
851
- // Limits
852
- minDuration: 0.01, // in seconds
853
- maxDuration: 10.0, // in seconds
854
- minDamping: 0.05,
855
- };
833
+ // Default spring physics
834
+ const defaultStiffness = 100;
835
+ const defaultDamping = 10;
836
+ const defaultMass = 1.0;
837
+ // Default duration/bounce-based options
838
+ const defaultDuration = 800; // in ms
839
+ const defaultBounce = 0.3;
840
+ const defaultVisualDuration = 0.3; // in seconds
841
+ // Rest thresholds
842
+ const restSpeedGranular = 0.01;
843
+ const restSpeedDefault = 2;
844
+ const restDeltaGranular = 0.005;
845
+ const restDeltaDefault = 0.5;
846
+ // Limits
847
+ const minDuration = 0.01; // in seconds
848
+ const maxDuration = 10.0; // in seconds
849
+ const minDamping = 0.05;
856
850
  /**
857
851
  * Maps bounce to a damping ratio as SwiftUI does: 0 is critically damped, and
858
852
  * it approaches undamped towards 1 and infinitely overdamped towards -1. Both
859
853
  * ends are limited so the spring still moves and settles.
860
854
  */
861
855
  const bounceToDampingRatio = (bounce) => bounce < 0
862
- ? 1 / Math.max(1 + bounce, springDefaults.minDamping)
863
- : Math.max(1 - bounce, springDefaults.minDamping);
856
+ ? 1 / Math.max(1 + bounce, minDamping)
857
+ : Math.max(1 - bounce, minDamping);
864
858
  /**
865
859
  * Scales an overdamped spring's undamped frequency so that, at its defining
866
860
  * time, it has as far left to go as the critically damped spring that's
@@ -903,12 +897,12 @@
903
897
  * ignore inherited velocity and only resolve without valid physics. Returns
904
898
  * NaN physics when the root search doesn't converge.
905
899
  */
906
- function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, }) {
900
+ function findSpring({ duration = defaultDuration, bounce = defaultBounce, }) {
907
901
  let envelope;
908
902
  let derivative;
909
- motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
903
+ motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
910
904
  const dampingRatio = bounceToDampingRatio(bounce);
911
- duration = motionUtils.clamp(springDefaults.minDuration, springDefaults.maxDuration, motionUtils.millisecondsToSeconds(duration));
905
+ duration = motionUtils.clamp(minDuration, maxDuration, motionUtils.millisecondsToSeconds(duration));
912
906
  if (dampingRatio < 1) {
913
907
  /**
914
908
  * Underdamped spring
@@ -993,9 +987,9 @@
993
987
  const validMass = resolvePhysics(options.mass);
994
988
  const springOptions = {
995
989
  ...options,
996
- stiffness: validStiffness ?? springDefaults.stiffness,
997
- damping: validDamping ?? springDefaults.damping,
998
- mass: validMass ?? springDefaults.mass,
990
+ stiffness: validStiffness ?? defaultStiffness,
991
+ damping: validDamping ?? defaultDamping,
992
+ mass: validMass ?? defaultMass,
999
993
  isResolvedFromDuration: false,
1000
994
  // stiffness/damping/mass overrides duration/bounce
1001
995
  isTimeDefined: (validStiffness ?? validDamping ?? validMass) === undefined &&
@@ -1023,13 +1017,13 @@
1023
1017
  */
1024
1018
  if (!isValidPhysics(springOptions.stiffness) ||
1025
1019
  !isValidPhysics(springOptions.damping, true)) {
1026
- springOptions.stiffness = springDefaults.stiffness;
1027
- springOptions.damping = springDefaults.damping;
1020
+ springOptions.stiffness = defaultStiffness;
1021
+ springOptions.damping = defaultDamping;
1028
1022
  }
1029
1023
  }
1030
1024
  return springOptions;
1031
1025
  }
1032
- function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
1026
+ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce = defaultBounce) {
1033
1027
  const options = typeof optionsOrVisualDuration !== "object"
1034
1028
  ? {
1035
1029
  visualDuration: optionsOrVisualDuration,
@@ -1079,14 +1073,10 @@
1079
1073
  const isGranularScale = Math.abs(s.delta) < 5;
1080
1074
  s.restSpeed =
1081
1075
  options.restSpeed ||
1082
- (isGranularScale
1083
- ? springDefaults.restSpeed.granular
1084
- : springDefaults.restSpeed.default);
1076
+ (isGranularScale ? restSpeedGranular : restSpeedDefault);
1085
1077
  s.restDelta =
1086
1078
  options.restDelta ||
1087
- (isGranularScale
1088
- ? springDefaults.restDelta.granular
1089
- : springDefaults.restDelta.default);
1079
+ (isGranularScale ? restDeltaGranular : restDeltaDefault);
1090
1080
  };
1091
1081
  setRestThresholds();
1092
1082
  let resolveSpring;
@@ -1155,11 +1145,16 @@
1155
1145
  * dampedAngularFreq * t passes 300, both terms decay at the damping
1156
1146
  * rate. Heavily overdamped drag springs (dragElastic: 0,
1157
1147
  * dragTransition) rely on this to settle almost at once rather than
1158
- * creep at stiffness / damping. Negative bounce needs the exact
1159
- * curve, so time-defined springs are exempt.
1160
- */
1161
- const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;
1162
- const decayAt = (rate, t) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);
1148
+ * creep at stiffness / damping. It only applies when reached within
1149
+ * 300ms (a dampedAngularFreq of 1 rad/ms), so it reads as a stiff
1150
+ * spring snapping into place: any later and it cuts off a slow spring
1151
+ * that's visibly still moving (#1207). Negative bounce needs the
1152
+ * exact curve, so time-defined springs are exempt.
1153
+ */
1154
+ const limit = dampedAngularFreq < 1 || isTimeDefined
1155
+ ? Infinity
1156
+ : 300 / dampedAngularFreq;
1157
+ const decayAt = (rate, t) => Math.exp(t > limit ? (decay - rate) * limit - decay * t : -rate * t);
1163
1158
  const c = { S: 0, F: 0 };
1164
1159
  update = () => {
1165
1160
  const P = (s.velocity + decay * s.delta) / dampedAngularFreq;
@@ -1214,13 +1209,15 @@
1214
1209
  };
1215
1210
  return generator;
1216
1211
  }
1217
- spring.applyToOptions = (options) => {
1218
- const generatorOptions = createGeneratorEasing(options, 100, spring);
1219
- options.ease = generatorOptions.ease;
1220
- options.duration = motionUtils.secondsToMilliseconds(generatorOptions.duration);
1221
- options.type = "keyframes";
1222
- return options;
1223
- };
1212
+ const spring = /* @__PURE__ */ Object.assign(springGenerator, {
1213
+ applyToOptions: (options) => {
1214
+ const generatorOptions = createGeneratorEasing(options, 100, springGenerator);
1215
+ options.ease = generatorOptions.ease;
1216
+ options.duration = motionUtils.secondsToMilliseconds(generatorOptions.duration);
1217
+ options.type = "keyframes";
1218
+ return options;
1219
+ },
1220
+ });
1224
1221
 
1225
1222
  function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {
1226
1223
  const origin = keyframes[0];
@@ -1238,7 +1235,7 @@
1238
1235
  };
1239
1236
  let amplitude = power * velocity;
1240
1237
  const ideal = origin + amplitude;
1241
- const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
1238
+ const target = modifyTarget ? modifyTarget(ideal) : ideal;
1242
1239
  /**
1243
1240
  * If the target has changed we need to re-calculate the amplitude, otherwise
1244
1241
  * the animation will start from the wrong position.
@@ -1249,7 +1246,8 @@
1249
1246
  const applyFriction = (t) => {
1250
1247
  const delta = calcDelta(t);
1251
1248
  state.done = Math.abs(delta) <= restDelta;
1252
- state.value = state.done ? target : target + delta;
1249
+ // target + delta can be off from origin by a float error at t = 0
1250
+ state.value = state.done ? target : t ? target + delta : origin;
1253
1251
  };
1254
1252
  /**
1255
1253
  * Ideally this would resolve for t in a stateless way, we could
@@ -1695,17 +1693,12 @@
1695
1693
  this.generator = generator;
1696
1694
  }
1697
1695
  updateTime(timestamp) {
1698
- const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;
1699
- // Update currentTime
1700
- if (this.holdTime !== null) {
1701
- this.currentTime = this.holdTime;
1702
- }
1703
- else {
1704
- // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1705
- // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1706
- // example.
1707
- this.currentTime = animationTime;
1708
- }
1696
+ // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1697
+ // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1698
+ // example.
1699
+ this.currentTime =
1700
+ this.holdTime ??
1701
+ Math.round(timestamp - this.startTime) * this.playbackSpeed;
1709
1702
  }
1710
1703
  tick(timestamp, sample = false) {
1711
1704
  const { generator, totalDuration, calculatedDuration } = this;
@@ -1746,10 +1739,17 @@
1746
1739
  }
1747
1740
  const state = this.generate(this.currentTime, isInDelayPhase);
1748
1741
  let { done } = state;
1749
- if (!isInDelayPhase && calculatedDuration !== null) {
1742
+ /**
1743
+ * A generator that takes longer than maxGeneratorDuration to finish
1744
+ * has an Infinity duration, so played forwards it finishes when it
1745
+ * says it's done.
1746
+ */
1747
+ if (!isInDelayPhase) {
1750
1748
  done =
1751
1749
  this.playbackSpeed >= 0
1752
- ? this.currentTime >= totalDuration
1750
+ ? calculatedDuration < Infinity
1751
+ ? this.currentTime >= totalDuration
1752
+ : done
1753
1753
  : this.currentTime <= 0;
1754
1754
  }
1755
1755
  const isAnimationFinished = this.holdTime === null &&
@@ -1855,20 +1855,11 @@
1855
1855
  }
1856
1856
  return state;
1857
1857
  }
1858
- /**
1859
- * Allows the returned animation to be awaited or promise-chained. Currently
1860
- * resolves when the animation finishes at all but in a future update could/should
1861
- * reject if its cancels.
1862
- */
1863
- then(resolve, reject) {
1864
- return this.finished.then(resolve, reject);
1865
- }
1866
1858
  get duration() {
1867
1859
  return motionUtils.millisecondsToSeconds(this.calculatedDuration);
1868
1860
  }
1869
1861
  get iterationDuration() {
1870
- const { delay = 0 } = this.options || {};
1871
- return this.duration + motionUtils.millisecondsToSeconds(delay);
1862
+ return this.duration + motionUtils.millisecondsToSeconds(this.options.delay ?? 0);
1872
1863
  }
1873
1864
  get time() {
1874
1865
  return motionUtils.millisecondsToSeconds(this.currentTime);
@@ -1972,14 +1963,9 @@
1972
1963
  }
1973
1964
  teardown() {
1974
1965
  this.state = "idle";
1975
- this.stopDriver();
1976
- this.startTime = this.holdTime = null;
1977
- }
1978
- stopDriver() {
1979
- if (!this.driver)
1980
- return;
1981
- this.driver.stop();
1966
+ this.driver?.stop();
1982
1967
  this.driver = undefined;
1968
+ this.startTime = this.holdTime = null;
1983
1969
  }
1984
1970
  sample(sampleTime) {
1985
1971
  this.startTime = 0;
@@ -2236,23 +2222,15 @@
2236
2222
  if (!transform || transform === "none") {
2237
2223
  return defaultTransformValue(name);
2238
2224
  }
2239
- const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);
2240
- let parsers;
2241
- let match;
2242
- if (matrix3dMatch) {
2243
- parsers = matrix3dParsers;
2244
- match = matrix3dMatch;
2245
- }
2246
- else {
2247
- const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u);
2248
- parsers = matrix2dParsers;
2249
- match = matrix2dMatch;
2250
- }
2225
+ const match = transform.match(/^matrix(3d)?\(([-\d.e\s,]+)\)$/u);
2251
2226
  if (!match) {
2252
2227
  return defaultTransformValue(name);
2253
2228
  }
2254
- const valueParser = parsers[name];
2255
- const values = match[1].split(",").map(convertTransformToNumber);
2229
+ const valueParser = (match[1] ? matrix3dParsers : matrix2dParsers)[name];
2230
+ /**
2231
+ * parseFloat skips leading whitespace and stops at trailing whitespace.
2232
+ */
2233
+ const values = match[2].split(",").map((v) => parseFloat(v));
2256
2234
  return typeof valueParser === "function"
2257
2235
  ? valueParser(values)
2258
2236
  : values[valueParser];
@@ -2261,9 +2239,6 @@
2261
2239
  const { transform = "none" } = getComputedStyle(instance);
2262
2240
  return parseValueFromTransform(transform, name);
2263
2241
  };
2264
- function convertTransformToNumber(value) {
2265
- return parseFloat(value.trim());
2266
- }
2267
2242
 
2268
2243
  /**
2269
2244
  * Generate a list of every possible transform key.
@@ -2302,7 +2277,7 @@
2302
2277
 
2303
2278
  const isNumOrPxType = (v) => v === number || v === px;
2304
2279
  const transformKeys = new Set(["x", "y", "z"]);
2305
- const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
2280
+ const nonTranslationalTransformKeys = /* @__PURE__ */ transformPropOrder.filter((key) => !transformKeys.has(key));
2306
2281
  /**
2307
2282
  * Reset any bounding box-changing transforms so the element can be
2308
2283
  * measured. Returns the values to restore. Values already at their
@@ -2344,6 +2319,8 @@
2344
2319
  ? size
2345
2320
  : size - parseFloat(paddingStart) - parseFloat(paddingEnd);
2346
2321
  }
2322
+ const transformX = ({ transform }) => parseValueFromTransform(transform, "x");
2323
+ const transformY = ({ transform }) => parseValueFromTransform(transform, "y");
2347
2324
  const positionalValues = {
2348
2325
  // Dimensions
2349
2326
  width: ({ width, paddingLeft = "0", paddingRight = "0", boxSizing }, measureBox) => measureDimension(width, measureBox, "x", paddingLeft, paddingRight, boxSizing),
@@ -2358,13 +2335,12 @@
2358
2335
  const { x } = measureBox();
2359
2336
  return parseFloat(left) + (x.max - x.min);
2360
2337
  },
2361
- // Transform
2362
- x: ({ transform }) => parseValueFromTransform(transform, "x"),
2363
- y: ({ transform }) => parseValueFromTransform(transform, "y"),
2338
+ // Transform, including translate longform names
2339
+ x: transformX,
2340
+ y: transformY,
2341
+ translateX: transformX,
2342
+ translateY: transformY,
2364
2343
  };
2365
- // Alias translate longform names
2366
- positionalValues.translateX = positionalValues.x;
2367
- positionalValues.translateY = positionalValues.y;
2368
2344
 
2369
2345
  const toResolve = new Set();
2370
2346
  let isScheduled = false;
@@ -2665,7 +2641,9 @@
2665
2641
  this.isPseudoElement = Boolean(pseudoElement);
2666
2642
  this.allowFlatten = allowFlatten;
2667
2643
  this.options = options;
2668
- motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2644
+ typeof process !== "undefined" &&
2645
+ "development" !== "production" &&
2646
+ motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2669
2647
  const transition = applyGeneratorOptions(options);
2670
2648
  this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
2671
2649
  if (transition.autoplay === false) {
@@ -2675,9 +2653,7 @@
2675
2653
  this.finishedTime = this.time;
2676
2654
  if (!pseudoElement) {
2677
2655
  const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
2678
- if (this.updateMotionValue) {
2679
- this.updateMotionValue(keyframe);
2680
- }
2656
+ this.updateMotionValue?.(keyframe);
2681
2657
  /**
2682
2658
  * If we can, we want to commit the final style as set by the user,
2683
2659
  * rather than the computed keyframe value supplied by the animation.
@@ -2718,18 +2694,24 @@
2718
2694
  if (this.isStopped)
2719
2695
  return;
2720
2696
  this.isStopped = true;
2721
- const { state } = this;
2722
- if (state === "idle" || state === "finished") {
2697
+ /**
2698
+ * Before its finish event, a finished animation (an instant one is
2699
+ * as soon as it starts) is still showing its end, so it's stopped
2700
+ * like a running one. Otherwise that event would apply its end
2701
+ * over whatever animates the value next.
2702
+ */
2703
+ if (this.state === "idle" || this.finishedTime !== null)
2723
2704
  return;
2724
- }
2725
2705
  if (this.updateMotionValue) {
2726
2706
  this.updateMotionValue();
2727
2707
  }
2728
2708
  else {
2729
2709
  this.commitStyles();
2730
2710
  }
2731
- if (!this.isPseudoElement)
2711
+ if (!this.isPseudoElement) {
2712
+ this.animation.onfinish = null;
2732
2713
  this.cancel();
2714
+ }
2733
2715
  }
2734
2716
  /**
2735
2717
  * WAAPI doesn't natively have any interruption capabilities.
@@ -2992,6 +2974,7 @@
2992
2974
  if (!isOriginAnimatable || !isTargetAnimatable) {
2993
2975
  // Only build the message when we're going to warn
2994
2976
  isOriginAnimatable !== isTargetAnimatable &&
2977
+ "development" !== "production" &&
2995
2978
  motionUtils.warning(false, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable");
2996
2979
  return false;
2997
2980
  }
@@ -3006,13 +2989,16 @@
3006
2989
 
3007
2990
  /**
3008
2991
  * A list of values that can be hardware-accelerated.
2992
+ *
2993
+ * Colors aren't included: WAAPI mixes them in sRGB, but JS animations
2994
+ * (and the sampler that estimates a WAAPI value on interrupt) mix them
2995
+ * in linear color space, so interrupting one would visibly jump.
3009
2996
  */
3010
2997
  const acceleratedValues = new Set([
3011
2998
  "opacity",
3012
2999
  "clipPath",
3013
3000
  "filter",
3014
3001
  "transform",
3015
- "backgroundColor",
3016
3002
  ]);
3017
3003
 
3018
3004
  const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;
@@ -3038,7 +3024,13 @@
3038
3024
  "borderBottomColor",
3039
3025
  "borderLeftColor",
3040
3026
  ]);
3041
- const supportsWaapi = /*@__PURE__*/ motionUtils.memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
3027
+ /**
3028
+ * WAAPI runs on the browser's clock, so on a manual clock every animation
3029
+ * runs in JS where processFrame can drive it. Set the flag before starting
3030
+ * animations: running WAAPI animations stay on the browser's clock.
3031
+ */
3032
+ const supportsWaapi = () => !motionUtils.MotionGlobalConfig.useManualTiming &&
3033
+ Object.hasOwnProperty.call(Element.prototype, "animate");
3042
3034
  function supportsBrowserAnimation(options) {
3043
3035
  const { motionValue, name, repeatDelay, repeatType, damping, type, keyframes, } = options;
3044
3036
  /**
@@ -3098,6 +3090,20 @@
3098
3090
  transformPerspective: "perspective",
3099
3091
  };
3100
3092
  const numTransforms = transformPropOrder.length;
3093
+ /**
3094
+ * Cache of `translateX(`-style openers so each transform function is a few
3095
+ * string concatenations rather than a template.
3096
+ */
3097
+ const openers = {};
3098
+ /**
3099
+ * A transform function, e.g. `translateX(10px)` for `x: 10`.
3100
+ */
3101
+ const transformFunction = (key, value, valueAsType = getValueAsType(value, transformValueTypes[key])) => (openers[key] || (openers[key] = (translateAlias[key] || key) + "(")) + valueAsType + ")";
3102
+ /**
3103
+ * Whether a transform value is at its default, so can be left out.
3104
+ */
3105
+ const isDefaultTransform = (key, value) => (typeof value === "number" ? value : parseFloat(value)) ===
3106
+ (key.startsWith("scale") ? 1 : 0);
3101
3107
  /**
3102
3108
  * Build a CSS transform style from individual x/y/scale etc properties.
3103
3109
  *
@@ -3107,7 +3113,6 @@
3107
3113
  function buildTransform$1(latestValues, transform, transformTemplate) {
3108
3114
  // The transform string we're going to build into.
3109
3115
  let transformString = "";
3110
- let transformIsDefault = true;
3111
3116
  /**
3112
3117
  * Loop over all possible transforms in order, adding the ones that
3113
3118
  * are present to the transform string.
@@ -3117,24 +3122,11 @@
3117
3122
  const value = latestValues[key];
3118
3123
  if (value === undefined)
3119
3124
  continue;
3120
- let valueIsDefault = true;
3121
- if (typeof value === "number") {
3122
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3123
- }
3124
- else {
3125
- const parsed = parseFloat(value);
3126
- valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
3127
- }
3128
- if (!valueIsDefault || transformTemplate) {
3129
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
3130
- if (!valueIsDefault) {
3131
- transformIsDefault = false;
3132
- const transformName = translateAlias[key] || key;
3133
- transformString += `${transformName}(${valueAsType}) `;
3134
- }
3135
- if (transformTemplate) {
3136
- transform[key] = valueAsType;
3137
- }
3125
+ const valueAsType = transformTemplate &&
3126
+ (transform[key] = getValueAsType(value, numberValueTypes[key]));
3127
+ if (!isDefaultTransform(key, value)) {
3128
+ transformString +=
3129
+ transformFunction(key, value, valueAsType || undefined) + " ";
3138
3130
  }
3139
3131
  }
3140
3132
  // `pathRotation` composes onto `rotate` as a separate additive term so
@@ -3142,19 +3134,14 @@
3142
3134
  // `transformPropOrder`.
3143
3135
  const pathRotation = latestValues.pathRotation;
3144
3136
  if (pathRotation) {
3145
- transformIsDefault = false;
3146
- transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
3137
+ transformString += transformFunction("rotate", pathRotation);
3147
3138
  }
3148
3139
  transformString = transformString.trim();
3149
3140
  // If we have a custom `transform` template, pass our transform values and
3150
3141
  // generated transformString to that before returning
3151
- if (transformTemplate) {
3152
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
3153
- }
3154
- else if (transformIsDefault) {
3155
- transformString = "none";
3156
- }
3157
- return transformString;
3142
+ return transformTemplate
3143
+ ? transformTemplate(transform, transformString)
3144
+ : transformString || "none";
3158
3145
  }
3159
3146
 
3160
3147
  const transformGroups = new WeakMap();
@@ -3496,27 +3483,30 @@
3496
3483
  return values;
3497
3484
  };
3498
3485
  /**
3499
- * Build the transform at a timestamp. Unlike buildTransform, every key
3500
- * is written, even at its default, so each keyframe has the same list
3501
- * of functions and the browser interpolates them one by one.
3486
+ * Build a transform from values in transformPropOrder. For a keyframe,
3487
+ * every key is written, even at its default, so each keyframe has the
3488
+ * same list of functions and the browser interpolates them one by one.
3489
+ * As an inline style, defaults are left out, as buildTransform does.
3502
3490
  */
3503
- const compose = (timestamp, settled) => {
3491
+ const toTransform = (values, isStyle) => {
3504
3492
  let transform = "";
3505
- const values = valuesAt(timestamp, settled);
3506
3493
  for (const key in values) {
3507
- transform +=
3508
- (translateAlias[key] || key) +
3509
- "(" +
3510
- getValueAsType(values[key], numberValueTypes[key]) +
3511
- ") ";
3494
+ const value = values[key];
3495
+ if (!isStyle || !isDefaultTransform(key, value)) {
3496
+ transform += transformFunction(key, value) + " ";
3497
+ }
3512
3498
  }
3513
- return transform || "none";
3499
+ return (isStyle ? transform.trim() : transform) || "none";
3514
3500
  };
3501
+ /**
3502
+ * Build the transform at a timestamp.
3503
+ */
3504
+ const compose = (timestamp, settled) => toTransform(valuesAt(timestamp, settled));
3515
3505
  /**
3516
3506
  * Write the transform as an inline style, as the renderer would.
3517
3507
  */
3518
3508
  const commit = (values = valuesAt()) => {
3519
- element.style.transform = buildTransform$1(values, {});
3509
+ element.style.transform = toTransform(values, true);
3520
3510
  };
3521
3511
  /**
3522
3512
  * Cancel the WAAPI animations, by default first committing the
@@ -3527,6 +3517,13 @@
3527
3517
  segments.forEach(({ animation }) => animation.cancel());
3528
3518
  segments = [];
3529
3519
  };
3520
+ /**
3521
+ * A WAAPI animation that add() starts by setting its startTime. Playing
3522
+ * it first, as element.animate() does, would leave WebKit holding that
3523
+ * play's ready time once startTime ends the play, and it uses that for
3524
+ * the next updatePlaybackRate(), so the animation would jump.
3525
+ */
3526
+ const create = (keyframes, options) => new Animation(new KeyframeEffect(element, keyframes, options));
3530
3527
  const add = (animation, offset, end = Infinity) => {
3531
3528
  const segment = { animation, offset, end };
3532
3529
  animation.startTime = time.now() + offset;
@@ -3719,7 +3716,7 @@
3719
3716
  commit(valuesAt(from, settled));
3720
3717
  keyframes = null;
3721
3718
  }
3722
- return element.animate(keyframes, {
3719
+ return create(keyframes, {
3723
3720
  ...options,
3724
3721
  duration: to - from,
3725
3722
  easing: easing || "linear",
@@ -3809,9 +3806,7 @@
3809
3806
  * empty animations that end with them.
3810
3807
  */
3811
3808
  ends.forEach((trackEnd) => trackEnd < end - 1 &&
3812
- add(element.animate(null, {
3813
- duration: trackEnd - now,
3814
- }), 0, trackEnd - now));
3809
+ add(create(null, { duration: trackEnd - now }), 0, trackEnd - now));
3815
3810
  }
3816
3811
  if (cycle) {
3817
3812
  /**
@@ -3885,12 +3880,29 @@
3885
3880
  if (isDone)
3886
3881
  continue;
3887
3882
  const local = elapsed - offset;
3888
- if (rate) {
3883
+ if (rate &&
3884
+ animation.updatePlaybackRate &&
3885
+ animation.playState === "running" &&
3886
+ Math.abs(Number(animation.currentTime) - local) < 20) {
3887
+ /**
3888
+ * Only the speed changed. Setting playbackRate and
3889
+ * startTime restarts a running compositor animation, which
3890
+ * can render the underlying value for a frame.
3891
+ */
3892
+ animation.playbackRate !== rate &&
3893
+ animation.updatePlaybackRate(rate);
3894
+ }
3895
+ else if (rate) {
3889
3896
  animation.playbackRate = rate;
3890
3897
  animation.startTime = now - local / rate;
3891
3898
  }
3892
3899
  else {
3893
- animation.pause();
3900
+ /**
3901
+ * Hold it without pause(), whose pending pause setting
3902
+ * currentTime would end at once, leaving WebKit holding its
3903
+ * ready time (see create()).
3904
+ */
3905
+ animation.startTime = null;
3894
3906
  animation.currentTime = local;
3895
3907
  }
3896
3908
  }
@@ -4081,9 +4093,8 @@
4081
4093
  * If we can't animate this value with the resolved keyframes
4082
4094
  * then we should complete it immediately.
4083
4095
  */
4084
- let canAnimateValue = true;
4085
- if (!canAnimate(keyframes, name, type, velocity)) {
4086
- canAnimateValue = false;
4096
+ const canAnimateValue = canAnimate(keyframes, name, type, velocity);
4097
+ if (!canAnimateValue) {
4087
4098
  if (motionUtils.MotionGlobalConfig.instantAnimations || !delay) {
4088
4099
  onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe));
4089
4100
  }
@@ -4227,9 +4238,7 @@
4227
4238
  this.animation.complete();
4228
4239
  }
4229
4240
  cancel() {
4230
- if (this._animation) {
4231
- this.animation.cancel();
4232
- }
4241
+ this._animation?.cancel();
4233
4242
  this.keyframeResolver?.cancel();
4234
4243
  }
4235
4244
  }
@@ -4412,7 +4421,7 @@
4412
4421
  this.setCurrent(v);
4413
4422
  // Update update subscribers
4414
4423
  if (this.current !== this.prev) {
4415
- this.notifyChange();
4424
+ this.dirty();
4416
4425
  if (this.dependents) {
4417
4426
  for (const dependent of this.dependents) {
4418
4427
  dependent.dirty();
@@ -4550,12 +4559,9 @@
4550
4559
  * @public
4551
4560
  */
4552
4561
  set(v) {
4553
- if (!this.passiveEffect) {
4554
- this.updateAndNotify(v);
4555
- }
4556
- else {
4557
- this.passiveEffect(v, this.updateAndNotify);
4558
- }
4562
+ this.passiveEffect
4563
+ ? this.passiveEffect(v, this.updateAndNotify)
4564
+ : this.updateAndNotify(v);
4559
4565
  }
4560
4566
  setWithVelocity(prev, current, delta) {
4561
4567
  this.set(current);
@@ -4572,13 +4578,9 @@
4572
4578
  this.prev = v;
4573
4579
  this.prevUpdatedAt = this.prevFrameValue = undefined;
4574
4580
  endAnimation && this.stop();
4575
- if (this.stopPassiveEffect)
4576
- this.stopPassiveEffect();
4581
+ this.stopPassiveEffect?.();
4577
4582
  }
4578
4583
  dirty() {
4579
- this.notifyChange();
4580
- }
4581
- notifyChange() {
4582
4584
  const { current, changeSubscriber } = this;
4583
4585
  /**
4584
4586
  * One or the other exists. Subscribing during the direct
@@ -4593,15 +4595,10 @@
4593
4595
  }
4594
4596
  }
4595
4597
  addDependent(dependent) {
4596
- if (!this.dependents) {
4597
- this.dependents = new Set();
4598
- }
4599
- this.dependents.add(dependent);
4598
+ (this.dependents || (this.dependents = new Set())).add(dependent);
4600
4599
  }
4601
4600
  removeDependent(dependent) {
4602
- if (this.dependents) {
4603
- this.dependents.delete(dependent);
4604
- }
4601
+ this.dependents?.delete(dependent);
4605
4602
  }
4606
4603
  /**
4607
4604
  * Returns the latest state of `MotionValue`
@@ -4611,9 +4608,7 @@
4611
4608
  * @public
4612
4609
  */
4613
4610
  get() {
4614
- if (collectMotionValues.current) {
4615
- collectMotionValues.current.push(this);
4616
- }
4611
+ collectMotionValues.current?.push(this);
4617
4612
  /**
4618
4613
  * A value animating on the compositor isn't updated every frame,
4619
4614
  * so read it from its animation.
@@ -4679,7 +4674,7 @@
4679
4674
  isComplete = true;
4680
4675
  this.events.animationComplete?.notify();
4681
4676
  if (this.animation === animation)
4682
- this.clearAnimation();
4677
+ this.animation = undefined;
4683
4678
  resolve();
4684
4679
  });
4685
4680
  if (!isComplete)
@@ -4695,11 +4690,10 @@
4695
4690
  stop() {
4696
4691
  if (this.animation) {
4697
4692
  this.animation.stop();
4698
- if (this.events.animationCancel) {
4699
- this.events.animationCancel.notify();
4700
- }
4693
+ this.events.animationCancel?.notify();
4701
4694
  }
4702
- this.clearAnimation();
4695
+ // Assign rather than delete to keep the object's shape stable
4696
+ this.animation = undefined;
4703
4697
  }
4704
4698
  /**
4705
4699
  * Returns `true` if this value is currently animating.
@@ -4709,10 +4703,6 @@
4709
4703
  isAnimating() {
4710
4704
  return !!this.animation;
4711
4705
  }
4712
- clearAnimation() {
4713
- // Assign rather than delete to keep the object's shape stable
4714
- this.animation = undefined;
4715
- }
4716
4706
  /**
4717
4707
  * Destroy and clean up subscribers to this `MotionValue`.
4718
4708
  *
@@ -4727,9 +4717,7 @@
4727
4717
  this.events.destroy?.notify();
4728
4718
  this.clearListeners();
4729
4719
  this.stop();
4730
- if (this.stopPassiveEffect) {
4731
- this.stopPassiveEffect();
4732
- }
4720
+ this.stopPassiveEffect?.();
4733
4721
  }
4734
4722
  }
4735
4723
  function motionValue(init, options) {
@@ -4807,6 +4795,7 @@
4807
4795
  "repeatDelay",
4808
4796
  "from",
4809
4797
  "elapsed",
4798
+ "out",
4810
4799
  ]);
4811
4800
  /**
4812
4801
  * Decide whether a transition is defined on a given Transition.
@@ -5229,12 +5218,8 @@
5229
5218
  }
5230
5219
  }
5231
5220
 
5232
- function camelToDash(str) {
5233
- return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`);
5234
- }
5235
-
5236
5221
  const optimizedAppearDataId = "framerAppearId";
5237
- const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
5222
+ const optimizedAppearDataAttribute = "data-framer-appear-id";
5238
5223
 
5239
5224
  function getOptimisedAppearId(visualElement) {
5240
5225
  return visualElement.props[optimizedAppearDataAttribute];
@@ -5281,7 +5266,7 @@
5281
5266
  }
5282
5267
  const valueTransition = {
5283
5268
  delay,
5284
- ...getValueTransition(transition || {}, key),
5269
+ ...getValueTransition(animationTypeState?.out[key] || transition || {}, key),
5285
5270
  };
5286
5271
  if (skipAnimations)
5287
5272
  valueTransition.skipAnimations = true;
@@ -5451,8 +5436,9 @@
5451
5436
  }
5452
5437
 
5453
5438
  class DOMKeyframesResolver extends KeyframeResolver {
5454
- constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
5455
- super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
5439
+ constructor() {
5440
+ super(...arguments);
5441
+ this.isAsync = true;
5456
5442
  }
5457
5443
  /**
5458
5444
  * Keyframes that don't need reading from the DOM, or measuring,
@@ -5480,7 +5466,7 @@
5480
5466
  }
5481
5467
  readKeyframes() {
5482
5468
  const { unresolvedKeyframes, element, name } = this;
5483
- if (!element || !element.current)
5469
+ if (!element?.current)
5484
5470
  return;
5485
5471
  super.readKeyframes();
5486
5472
  /**
@@ -5575,11 +5561,10 @@
5575
5561
  }
5576
5562
  measureInitialState() {
5577
5563
  const { element, unresolvedKeyframes, name } = this;
5578
- if (!element || !element.current)
5564
+ if (!element?.current)
5579
5565
  return;
5580
- if (name === "height") {
5566
+ if (name === "height")
5581
5567
  this.suspendedScrollY = window.pageYOffset;
5582
- }
5583
5568
  this.measuredOrigin = this.measure();
5584
5569
  unresolvedKeyframes[0] = this.measuredOrigin;
5585
5570
  // Set final key frame to measure after next render
@@ -5590,7 +5575,7 @@
5590
5575
  }
5591
5576
  measureEndState() {
5592
5577
  const { element, unresolvedKeyframes } = this;
5593
- if (!element || !element.current)
5578
+ if (!element?.current)
5594
5579
  return;
5595
5580
  this.motionValue?.jump(this.measuredOrigin, false);
5596
5581
  const finalKeyframeIndex = unresolvedKeyframes.length - 1;
@@ -5599,14 +5584,6 @@
5599
5584
  if (finalKeyframe !== null && this.finalKeyframe === undefined) {
5600
5585
  this.finalKeyframe = finalKeyframe;
5601
5586
  }
5602
- // If we removed transform values, reapply them before the next render
5603
- if (this.removedTransforms?.length) {
5604
- this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
5605
- element
5606
- .getValue(unsetTransformName)
5607
- .set(unsetTransformValue);
5608
- });
5609
- }
5610
5587
  this.resolveNoneKeyframes();
5611
5588
  }
5612
5589
  }
@@ -5711,7 +5688,8 @@
5711
5688
  */
5712
5689
  const effects = [];
5713
5690
  function addEffect(effect) {
5714
- motionUtils.invariant(typeof effect.test === "function" && typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5691
+ motionUtils.invariant(typeof effect.test === "function" &&
5692
+ typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5715
5693
  removeEffect(effect);
5716
5694
  effects.unshift(effect);
5717
5695
  }
@@ -6038,11 +6016,6 @@
6038
6016
  });
6039
6017
  }
6040
6018
 
6041
- /**
6042
- * Cache of `translateX(`-style openers so each render is a few string
6043
- * concatenations rather than a template per transform.
6044
- */
6045
- const openers = {};
6046
6019
  function buildTransform(state) {
6047
6020
  let transform = "";
6048
6021
  const { transformKeys: keys = [], transformValues: values = {} } = state;
@@ -6055,14 +6028,8 @@
6055
6028
  const value = values[key].getCurrent();
6056
6029
  if (value === undefined)
6057
6030
  continue;
6058
- const parsed = typeof value === "number" ? value : parseFloat(value);
6059
- if (parsed !== (key.startsWith("scale") ? 1 : 0)) {
6060
- transform +=
6061
- (transform && " ") +
6062
- (openers[key] ||
6063
- (openers[key] = (translateAlias[key] || key) + "(")) +
6064
- getValueAsType(value, transformValueTypes[key]) +
6065
- ")";
6031
+ if (!isDefaultTransform(key, value)) {
6032
+ transform += (transform && " ") + transformFunction(key, value);
6066
6033
  }
6067
6034
  }
6068
6035
  // See build-transform.ts: additive `rotate()` so user `rotate` isn't
@@ -6070,10 +6037,7 @@
6070
6037
  const pathRotation = state.get("pathRotation")?.get();
6071
6038
  if (pathRotation) {
6072
6039
  transform +=
6073
- (transform && " ") +
6074
- "rotate(" +
6075
- getValueAsType(pathRotation, transformValueTypes.pathRotation) +
6076
- ")";
6040
+ (transform && " ") + transformFunction("rotate", pathRotation);
6077
6041
  }
6078
6042
  return transform || "none";
6079
6043
  }
@@ -6162,6 +6126,10 @@
6162
6126
  const styleEffect =
6163
6127
  /*@__PURE__*/ createSelectorEffect(styleSubjectEffect);
6164
6128
 
6129
+ function camelToDash(str) {
6130
+ return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`);
6131
+ }
6132
+
6165
6133
  function buildHTMLStyles(state, latestValues, transformTemplate) {
6166
6134
  const { style, vars, transformOrigin } = state;
6167
6135
  // Track whether we encounter any transform or transformOrigin values.
@@ -6472,10 +6440,24 @@
6472
6440
  !isIdentityScale(scaleX) ||
6473
6441
  !isIdentityScale(scaleY));
6474
6442
  }
6443
+ /**
6444
+ * Rotations and skews, which projection can't correct for.
6445
+ */
6446
+ const angleTransforms = [
6447
+ "rotate",
6448
+ "rotateX",
6449
+ "rotateY",
6450
+ "rotateZ",
6451
+ "skewX",
6452
+ "skewY",
6453
+ ];
6475
6454
  function hasTransform(values) {
6476
6455
  return (hasScale(values) ||
6477
6456
  has2DTranslate(values) ||
6478
- values.z ||
6457
+ hasDistortingTransform(values));
6458
+ }
6459
+ function hasDistortingTransform(values) {
6460
+ return (values.z ||
6479
6461
  values.rotate ||
6480
6462
  values.rotateX ||
6481
6463
  values.rotateY ||
@@ -6528,6 +6510,11 @@
6528
6510
  * in a tree upon our box before then calculating how to project it into our desired viewport-relative box
6529
6511
  *
6530
6512
  * This is the final nested loop within updateLayoutDelta for future refactoring
6513
+ *
6514
+ * isSharedTransition is true for a shared layout animation in page space, which
6515
+ * also applies ancestor scroll and transforms. Or it's the layoutRoot a shared
6516
+ * animation is relative to, so only transforms of ancestors not shared with it
6517
+ * (or above it) are applied.
6531
6518
  */
6532
6519
  function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
6533
6520
  const treeLength = treePath.length;
@@ -6544,13 +6531,10 @@
6544
6531
  * TODO: Prefer to remove this, but currently we have motion components with
6545
6532
  * display: contents in Framer.
6546
6533
  */
6547
- const { visualElement } = node.options;
6548
- if (visualElement &&
6549
- visualElement.props.style &&
6550
- visualElement.props.style.display === "contents") {
6534
+ if (node.options.visualElement?.props.style?.display === "contents") {
6551
6535
  continue;
6552
6536
  }
6553
- if (isSharedTransition &&
6537
+ if (isSharedTransition === true &&
6554
6538
  node.options.layoutScroll &&
6555
6539
  node.scroll &&
6556
6540
  node !== node.root) {
@@ -6564,7 +6548,9 @@
6564
6548
  // Apply each ancestor's calculated delta into this component's recorded layout box
6565
6549
  applyBoxDelta(box, delta);
6566
6550
  }
6567
- if (isSharedTransition && hasTransform(node.latestValues)) {
6551
+ if (isSharedTransition &&
6552
+ (isSharedTransition.path?.[i] || isSharedTransition) !== node &&
6553
+ hasTransform(node.latestValues)) {
6568
6554
  transformBox(box, node.latestValues, node.layout?.layoutBox);
6569
6555
  }
6570
6556
  }
@@ -6737,6 +6723,41 @@
6737
6723
  const { schedule: microtask, cancel: cancelMicrotask } =
6738
6724
  /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
6739
6725
 
6726
+ /**
6727
+ * Process a frame now, for driving Motion from a loop other than
6728
+ * window.requestAnimationFrame, like an XRSession's during an immersive
6729
+ * WebXR session. Wherever window.requestAnimationFrame does fire, Motion
6730
+ * keeps processing frames from it too.
6731
+ *
6732
+ * `timestamp` defaults to now. For a timeline you control, set
6733
+ * `MotionGlobalConfig.useManualTiming = true` and pass each frame's time in
6734
+ * milliseconds.
6735
+ *
6736
+ * Animations Motion hands to the browser (WAAPI), like `opacity` or
6737
+ * `transform` on an HTML or SVG element, follow the browser's clock. With
6738
+ * `useManualTiming` on, Motion runs those in JS instead, except for
6739
+ * `motion/mini`, view transitions and optimized appear animations, and
6740
+ * colours only the browser can mix, like `oklch()`, which jump to their end.
6741
+ *
6742
+ * Ignored when called inside a frame.
6743
+ */
6744
+ const processFrame = (timestamp = time.now()) => {
6745
+ if (frameData.isProcessing)
6746
+ return;
6747
+ const delta = timestamp - frameData.timestamp;
6748
+ // Clamp like the requestAnimationFrame loop, unless the timeline is ours
6749
+ frameData.delta = motionUtils.MotionGlobalConfig.useManualTiming
6750
+ ? delta
6751
+ : Math.max(Math.min(delta, 40), 1);
6752
+ time.set((frameData.timestamp = timestamp));
6753
+ frameData.isProcessing = true;
6754
+ // frameSteps' keys are in stepsOrder
6755
+ for (const step in frameSteps) {
6756
+ frameSteps[step].process(frameData);
6757
+ }
6758
+ frameData.isProcessing = false;
6759
+ };
6760
+
6740
6761
  function animateSingleValue(value, keyframes, options) {
6741
6762
  const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
6742
6763
  motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options));
@@ -6803,15 +6824,6 @@
6803
6824
  const asNumber = (v) => typeof v === "number" ? v : parseFloat(v);
6804
6825
 
6805
6826
  const numBorders = cornerRadiusProps.length;
6806
- const mixedTransforms = [
6807
- "rotate",
6808
- "rotateX",
6809
- "rotateY",
6810
- "rotateZ",
6811
- "skewX",
6812
- "skewY",
6813
- ];
6814
- const numMixedTransforms = mixedTransforms.length;
6815
6827
  const isPx = (value) => typeof value === "number" || px.test(value);
6816
6828
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
6817
6829
  if (shouldCrossfadeOpacity) {
@@ -6849,8 +6861,8 @@
6849
6861
  * Mix rotation and skew. These can't be projected, so mix them every
6850
6862
  * frame rather than leaving them frozen at the animation-start snapshot.
6851
6863
  */
6852
- for (let i = 0; i < numMixedTransforms; i++) {
6853
- const key = mixedTransforms[i];
6864
+ for (let i = 0; i < angleTransforms.length; i++) {
6865
+ const key = angleTransforms[i];
6854
6866
  if (follow[key] || lead[key]) {
6855
6867
  target[key] = mixNumber$1(follow[key] || 0, lead[key] || 0, progress);
6856
6868
  }
@@ -6933,8 +6945,8 @@
6933
6945
  }
6934
6946
  }
6935
6947
  function calcBoxDelta(delta, source, target, origin) {
6936
- calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);
6937
- calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);
6948
+ calcAxisDelta(delta.x, source.x, target.x, origin?.originX);
6949
+ calcAxisDelta(delta.y, source.y, target.y, origin?.originY);
6938
6950
  }
6939
6951
  function calcRelativeAxis(target, relative, parent, anchor = 0) {
6940
6952
  const anchorPoint = anchor
@@ -7004,8 +7016,8 @@
7004
7016
  * and acts as a bridge between motion values and removeAxisDelta
7005
7017
  */
7006
7018
  function removeBoxTransforms(box, transforms, originBox, sourceBox) {
7007
- removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);
7008
- removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);
7019
+ removeAxisTransforms(box.x, transforms, xKeys, originBox?.x, sourceBox?.x);
7020
+ removeAxisTransforms(box.y, transforms, yKeys, originBox?.y, sourceBox?.y);
7009
7021
  }
7010
7022
 
7011
7023
  const createAxisDelta = () => ({
@@ -7203,10 +7215,9 @@
7203
7215
  };
7204
7216
 
7205
7217
  const defaultScaleCorrectors = {
7206
- borderRadius: {
7207
- ...correctBorderRadius,
7208
- applyTo: [...cornerRadiusProps],
7209
- },
7218
+ borderRadius: /* @__PURE__ */ Object.assign({}, correctBorderRadius, {
7219
+ applyTo: /* @__PURE__ */ cornerRadiusProps.slice(),
7220
+ }),
7210
7221
  borderTopLeftRadius: correctBorderRadius,
7211
7222
  borderTopRightRadius: correctBorderRadius,
7212
7223
  borderBottomLeftRadius: correctBorderRadius,
@@ -7236,24 +7247,18 @@
7236
7247
  transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7237
7248
  }
7238
7249
  if (latestTransform) {
7239
- const { transformPerspective, rotate, pathRotation, rotateX, rotateY, rotateZ, skewX, skewY, } = latestTransform;
7250
+ const { transformPerspective } = latestTransform;
7240
7251
  if (transformPerspective)
7241
7252
  transform = `perspective(${transformPerspective}px) ${transform}`;
7242
- if (rotate)
7243
- transform += `rotate(${rotate}deg) `;
7244
- // Additive `rotate()` so user `rotate` isn't clobbered.
7245
- if (pathRotation)
7246
- transform += `rotate(${pathRotation}deg) `;
7247
- if (rotateX)
7248
- transform += `rotateX(${rotateX}deg) `;
7249
- if (rotateY)
7250
- transform += `rotateY(${rotateY}deg) `;
7251
- if (rotateZ)
7252
- transform += `rotateZ(${rotateZ}deg) `;
7253
- if (skewX)
7254
- transform += `skewX(${skewX}deg) `;
7255
- if (skewY)
7256
- transform += `skewY(${skewY}deg) `;
7253
+ for (let i = 0; i < angleTransforms.length; i++) {
7254
+ const key = angleTransforms[i];
7255
+ const value = latestTransform[key];
7256
+ if (value)
7257
+ transform += `${key}(${value}deg) `;
7258
+ // Additive `rotate()` so user `rotate` isn't clobbered.
7259
+ if (!i && latestTransform.pathRotation)
7260
+ transform += `rotate(${latestTransform.pathRotation}deg) `;
7261
+ }
7257
7262
  }
7258
7263
  /**
7259
7264
  * Apply scale to match the size of the element to the size we want it.
@@ -7311,20 +7316,15 @@
7311
7316
  hasEverUpdated: false,
7312
7317
  };
7313
7318
 
7314
- /**
7315
- * Correctors registered via addScaleCorrector before projection loaded
7316
- * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
7317
- */
7318
- Object.assign(scaleCorrectors, {
7319
- ...defaultScaleCorrectors,
7320
- ...scaleCorrectors,
7321
- });
7322
7319
  const metrics = {
7323
7320
  nodes: 0,
7324
7321
  calculatedTargetDeltas: 0,
7325
7322
  calculatedProjections: 0,
7326
7323
  };
7327
- const transformAxes = ["", "X", "Y", "Z"];
7324
+ /**
7325
+ * Transforms that distort an element's layout, so must be reset before measuring.
7326
+ */
7327
+ const distortingTransforms = ["z", "skew", "skewZ"];
7328
7328
  /**
7329
7329
  * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
7330
7330
  * which has a noticeable difference in spring animations
@@ -7361,6 +7361,16 @@
7361
7361
  }
7362
7362
  }
7363
7363
  function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
7364
+ /**
7365
+ * Correctors registered via addScaleCorrector before projection loaded
7366
+ * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
7367
+ * Applied here rather than at module scope so bundlers can drop projection
7368
+ * when it's unused.
7369
+ */
7370
+ Object.assign(scaleCorrectors, {
7371
+ ...defaultScaleCorrectors,
7372
+ ...scaleCorrectors,
7373
+ });
7364
7374
  return class ProjectionNode {
7365
7375
  constructor(latestValues = {}, parent = defaultParent?.()) {
7366
7376
  /**
@@ -7522,8 +7532,7 @@
7522
7532
  return this.eventHandlers.get(name).add(handler);
7523
7533
  }
7524
7534
  notifyListeners(name, ...args) {
7525
- const subscriptionManager = this.eventHandlers.get(name);
7526
- subscriptionManager && subscriptionManager.notify(...args);
7535
+ this.eventHandlers.get(name)?.notify(...args);
7527
7536
  }
7528
7537
  hasListeners(name) {
7529
7538
  return this.eventHandlers.has(name);
@@ -7541,7 +7550,7 @@
7541
7550
  visualElement.mount(instance);
7542
7551
  }
7543
7552
  this.root.nodes.add(this);
7544
- this.parent && this.parent.children.add(this);
7553
+ this.parent?.children.add(this);
7545
7554
  if (this.root.hasTreeAnimated && (layout || layoutId)) {
7546
7555
  this.isLayoutDirty = true;
7547
7556
  }
@@ -7559,7 +7568,7 @@
7559
7568
  return;
7560
7569
  innerWidth = newInnerWidth;
7561
7570
  this.root.updateBlockedByResize = true;
7562
- cancelDelay && cancelDelay();
7571
+ cancelDelay?.();
7563
7572
  cancelDelay = delay(resizeUnblockUpdate, 250);
7564
7573
  if (globalProjectionState.hasAnimatedSinceResize) {
7565
7574
  globalProjectionState.hasAnimatedSinceResize = false;
@@ -7650,9 +7659,7 @@
7650
7659
  if (!hasLayoutChanged) {
7651
7660
  finishAnimation(this);
7652
7661
  }
7653
- if (this.isLead() && this.options.onExitComplete) {
7654
- this.options.onExitComplete();
7655
- }
7662
+ this.isLead() && this.options.onExitComplete?.();
7656
7663
  }
7657
7664
  this.targetLayout = newLayout;
7658
7665
  });
@@ -7660,9 +7667,8 @@
7660
7667
  unmount() {
7661
7668
  this.options.layoutId && this.willUpdate();
7662
7669
  this.root.nodes.remove(this);
7663
- const stack = this.getStack();
7664
- stack && stack.remove(this);
7665
- this.parent && this.parent.children.delete(this);
7670
+ this.getStack()?.remove(this);
7671
+ this.parent?.children.delete(this);
7666
7672
  this.instance = undefined;
7667
7673
  this.eventHandlers.clear();
7668
7674
  this.hasLayoutListener = false;
@@ -7683,7 +7689,7 @@
7683
7689
  if (this.isUpdateBlocked())
7684
7690
  return;
7685
7691
  this.isUpdating = true;
7686
- this.nodes && this.nodes.forEach(resetSkewAndRotation);
7692
+ this.nodes?.forEach(resetSkewAndRotation);
7687
7693
  this.animationId++;
7688
7694
  }
7689
7695
  getTransformTemplate() {
@@ -7693,7 +7699,7 @@
7693
7699
  willUpdate(shouldNotifyListeners = true) {
7694
7700
  this.root.hasTreeAnimated = true;
7695
7701
  if (this.root.isUpdateBlocked()) {
7696
- this.options.onExitComplete && this.options.onExitComplete();
7702
+ this.options.onExitComplete?.();
7697
7703
  return;
7698
7704
  }
7699
7705
  /**
@@ -7910,24 +7916,23 @@
7910
7916
  this.projectionDelta = undefined;
7911
7917
  this.notifyListeners("measure", this.layout.layoutBox);
7912
7918
  const { visualElement } = this.options;
7913
- visualElement &&
7914
- visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);
7919
+ visualElement?.notify("LayoutMeasure", this.layout.layoutBox, prevLayout?.layoutBox);
7915
7920
  }
7916
7921
  updateScroll(phase = "measure") {
7917
- let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
7918
- if (this.scroll &&
7919
- this.scroll.animationId === this.root.animationId &&
7920
- this.scroll.phase === phase) {
7921
- needsMeasurement = false;
7922
- }
7923
- if (needsMeasurement && this.instance) {
7924
- const isRoot = checkIsScrollRoot(this.instance);
7922
+ const { scroll, instance } = this;
7923
+ const { animationId } = this.root;
7924
+ if (this.options.layoutScroll &&
7925
+ instance &&
7926
+ !(scroll &&
7927
+ scroll.animationId === animationId &&
7928
+ scroll.phase === phase)) {
7929
+ const isRoot = checkIsScrollRoot(instance);
7925
7930
  this.scroll = {
7926
- animationId: this.root.animationId,
7931
+ animationId,
7927
7932
  phase,
7928
7933
  isRoot,
7929
- offset: measureScroll(this.instance),
7930
- wasRoot: this.scroll ? this.scroll.isRoot : isRoot,
7934
+ offset: measureScroll(instance),
7935
+ wasRoot: scroll ? scroll.isRoot : isRoot,
7931
7936
  };
7932
7937
  }
7933
7938
  }
@@ -8017,10 +8022,10 @@
8017
8022
  }
8018
8023
  return boxWithoutScroll;
8019
8024
  }
8020
- applyTransform(box, transformOnly = false, output) {
8025
+ applyTransform(box, transformOnly = false, output, skipOwnTransform, start = 0) {
8021
8026
  const withTransforms = output || createBox();
8022
8027
  copyBoxInto(withTransforms, box);
8023
- for (let i = 0; i < this.path.length; i++) {
8028
+ for (let i = start; i < this.path.length; i++) {
8024
8029
  const node = this.path[i];
8025
8030
  if (!transformOnly &&
8026
8031
  node.options.layoutScroll &&
@@ -8033,7 +8038,7 @@
8033
8038
  continue;
8034
8039
  transformBox(withTransforms, node.latestValues, node.layout?.layoutBox);
8035
8040
  }
8036
- if (hasTransform(this.latestValues)) {
8041
+ if (!skipOwnTransform && hasTransform(this.latestValues)) {
8037
8042
  transformBox(withTransforms, this.latestValues, this.layout?.layoutBox);
8038
8043
  }
8039
8044
  return withTransforms;
@@ -8168,7 +8173,11 @@
8168
8173
  }
8169
8174
  else if (this.targetDelta) {
8170
8175
  if (Boolean(this.resumingFrom)) {
8171
- this.applyTransform(this.layout.layoutBox, false, this.target);
8176
+ /**
8177
+ * Own transforms are applied later, in applyTransformsToTarget,
8178
+ * so only apply ancestor transforms here or they'd be doubled.
8179
+ */
8180
+ this.applyTransform(this.layout.layoutBox, false, this.target, true);
8172
8181
  }
8173
8182
  else {
8174
8183
  copyBoxInto(this.target, this.layout.layoutBox);
@@ -8188,8 +8197,13 @@
8188
8197
  this.attemptToResolveRelativeTarget = false;
8189
8198
  if (this.options.layoutAnchor !== false &&
8190
8199
  relativeParent &&
8191
- Boolean(relativeParent.resumingFrom) ===
8192
- Boolean(this.resumingFrom) &&
8200
+ (!relativeParent.resumingFrom === !this.resumingFrom ||
8201
+ /**
8202
+ * Shared layout animations within a layoutRoot
8203
+ * animate relative to it.
8204
+ */
8205
+ (relativeParent.options.layoutRoot &&
8206
+ !relativeParent.resumingFrom)) &&
8193
8207
  !relativeParent.options.layoutScroll &&
8194
8208
  relativeParent.target &&
8195
8209
  this.animationProgress !== 1) {
@@ -8269,7 +8283,7 @@
8269
8283
  * If this section of the tree isn't animating we can
8270
8284
  * delete our target sources for the following frame.
8271
8285
  */
8272
- this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||
8286
+ this.isTreeAnimating = Boolean(this.parent?.isTreeAnimating ||
8273
8287
  this.currentAnimation ||
8274
8288
  this.pendingAnimation);
8275
8289
  if (!this.isTreeAnimating) {
@@ -8290,8 +8304,17 @@
8290
8304
  /**
8291
8305
  * Apply all the parent deltas to this box to produce the corrected box. This
8292
8306
  * is the layout box, as it will appear on screen as a result of the transforms of its parents.
8307
+ *
8308
+ * A shared target is usually in page space, so ancestor transforms are applied
8309
+ * too. But a target relative to a parent that isn't itself shared (like a
8310
+ * layoutRoot) is in that parent's layout space. So the transforms of the
8311
+ * parent and its ancestors, which move both elements alike, are skipped,
8312
+ * but those of other ancestors (between it and either element) apply.
8293
8313
  */
8294
- applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
8314
+ applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared &&
8315
+ (lead.relativeTarget && !lead.relativeParent.resumingFrom
8316
+ ? lead.relativeParent
8317
+ : true));
8295
8318
  /**
8296
8319
  * If this layer needs to perform scale correction but doesn't have a target,
8297
8320
  * use the layout as the target.
@@ -8358,8 +8381,7 @@
8358
8381
  scheduleRender(notifyAll = true) {
8359
8382
  this.options.visualElement?.scheduleRender();
8360
8383
  if (notifyAll) {
8361
- const stack = this.getStack();
8362
- stack && stack.scheduleRender();
8384
+ this.getStack()?.scheduleRender();
8363
8385
  }
8364
8386
  if (this.resumingFrom && !this.resumingFrom.instance) {
8365
8387
  this.resumingFrom = undefined;
@@ -8381,9 +8403,7 @@
8381
8403
  }
8382
8404
  this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
8383
8405
  const relativeLayout = createBox();
8384
- const snapshotSource = snapshot ? snapshot.source : undefined;
8385
- const layoutSource = this.layout ? this.layout.source : undefined;
8386
- const isSharedLayoutAnimation = snapshotSource !== layoutSource;
8406
+ const isSharedLayoutAnimation = snapshot?.source !== this.layout?.source;
8387
8407
  const stack = this.getStack();
8388
8408
  const isOnlyMember = !stack || stack.members.length <= 1;
8389
8409
  const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&
@@ -8398,19 +8418,11 @@
8398
8418
  this.mixTargetDelta = (latest) => {
8399
8419
  const progress = latest / 1000;
8400
8420
  const point = interpolate?.(progress);
8421
+ mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8422
+ mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8401
8423
  if (point) {
8402
8424
  targetDelta.x.translate = point.x;
8403
- targetDelta.x.scale = mixNumber$1(delta.x.scale, 1, progress);
8404
- targetDelta.x.origin = delta.x.origin;
8405
- targetDelta.x.originPoint = delta.x.originPoint;
8406
8425
  targetDelta.y.translate = point.y;
8407
- targetDelta.y.scale = mixNumber$1(delta.y.scale, 1, progress);
8408
- targetDelta.y.origin = delta.y.origin;
8409
- targetDelta.y.originPoint = delta.y.originPoint;
8410
- }
8411
- else {
8412
- mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8413
- mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8414
8426
  }
8415
8427
  this.setTargetDelta(targetDelta);
8416
8428
  if (this.relativeTarget &&
@@ -8436,7 +8448,7 @@
8436
8448
  this.animationValues = mixedValues;
8437
8449
  mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
8438
8450
  }
8439
- if (point && point.rotate !== undefined) {
8451
+ if (point?.rotate !== undefined) {
8440
8452
  // Dedicated `pathRotation` channel, not `rotate`, so an
8441
8453
  // animating `rotate` is composed with, never clobbered.
8442
8454
  if (!this.animationValues)
@@ -8501,7 +8513,7 @@
8501
8513
  }
8502
8514
  finishAnimation() {
8503
8515
  if (this.currentAnimation) {
8504
- this.mixTargetDelta && this.mixTargetDelta(animationTarget);
8516
+ this.mixTargetDelta?.(animationTarget);
8505
8517
  this.currentAnimation.stop();
8506
8518
  }
8507
8519
  this.completeAnimation();
@@ -8521,13 +8533,11 @@
8521
8533
  this.layout &&
8522
8534
  layout &&
8523
8535
  shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {
8536
+ const { layoutBox } = this.layout;
8537
+ const leadTarget = target;
8524
8538
  target = this.target || createBox();
8525
- const xLength = calcLength(this.layout.layoutBox.x);
8526
- target.x.min = lead.target.x.min;
8527
- target.x.max = target.x.min + xLength;
8528
- const yLength = calcLength(this.layout.layoutBox.y);
8529
- target.y.min = lead.target.y.min;
8530
- target.y.max = target.y.min + yLength;
8539
+ alignAxis(target.x, leadTarget.x, layoutBox.x);
8540
+ alignAxis(target.y, leadTarget.y, layoutBox.y);
8531
8541
  }
8532
8542
  copyBoxInto(targetWithTransforms, target);
8533
8543
  /**
@@ -8552,8 +8562,8 @@
8552
8562
  stack.add(node);
8553
8563
  const config = node.options.initialPromotionConfig;
8554
8564
  node.promote({
8555
- transition: config ? config.transition : undefined,
8556
- preserveFollowOpacity: config && config.shouldPreserveFollowOpacity
8565
+ transition: config?.transition,
8566
+ preserveFollowOpacity: config?.shouldPreserveFollowOpacity
8557
8567
  ? config.shouldPreserveFollowOpacity(node)
8558
8568
  : undefined,
8559
8569
  });
@@ -8576,9 +8586,7 @@
8576
8586
  return this.root.sharedNodes.get(layoutId);
8577
8587
  }
8578
8588
  promote({ needsReset, transition, preserveFollowOpacity, } = {}) {
8579
- const stack = this.getStack();
8580
- if (stack)
8581
- stack.promote(this, preserveFollowOpacity);
8589
+ this.getStack()?.promote(this, preserveFollowOpacity);
8582
8590
  if (needsReset) {
8583
8591
  this.projectionDelta = undefined;
8584
8592
  this.needsReset = true;
@@ -8587,45 +8595,27 @@
8587
8595
  this.setOptions({ transition });
8588
8596
  }
8589
8597
  relegate() {
8590
- const stack = this.getStack();
8591
- if (stack) {
8592
- return stack.relegate(this);
8593
- }
8594
- else {
8595
- return false;
8596
- }
8598
+ return this.getStack()?.relegate(this) || false;
8597
8599
  }
8598
8600
  resetSkewAndRotation() {
8599
8601
  const { visualElement } = this.options;
8600
8602
  if (!visualElement)
8601
8603
  return;
8602
- // If there's no detected skew or rotation values, we can early return without a forced render.
8603
- let hasDistortingTransform = false;
8604
8604
  /**
8605
8605
  * An unrolled check for rotation values. Most elements don't have any rotation and
8606
- * skipping the nested loop and new object creation is 50% faster.
8606
+ * skipping the loop and new object creation is 50% faster.
8607
+ * If there's no distorting values, we don't need to do any more.
8607
8608
  */
8608
8609
  const { latestValues } = visualElement;
8609
- if (latestValues.z ||
8610
- latestValues.rotate ||
8611
- latestValues.rotateX ||
8612
- latestValues.rotateY ||
8613
- latestValues.rotateZ ||
8614
- latestValues.skewX ||
8615
- latestValues.skewY) {
8616
- hasDistortingTransform = true;
8617
- }
8618
- // If there's no distorting values, we don't need to do any more.
8619
- if (!hasDistortingTransform)
8610
+ if (!hasDistortingTransform(latestValues))
8620
8611
  return;
8621
8612
  const resetValues = {};
8622
- if (latestValues.z) {
8623
- resetDistortingTransform("z", visualElement, resetValues, this.animationValues);
8624
- }
8625
8613
  // Check the skew and rotate value of all axes and reset to 0
8626
- for (let i = 0; i < transformAxes.length; i++) {
8627
- resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8628
- resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8614
+ for (let i = 0; i < distortingTransforms.length; i++) {
8615
+ resetDistortingTransform(distortingTransforms[i], visualElement, resetValues, this.animationValues);
8616
+ }
8617
+ for (let i = 0; i < angleTransforms.length; i++) {
8618
+ resetDistortingTransform(angleTransforms[i], visualElement, resetValues, this.animationValues);
8629
8619
  }
8630
8620
  // Force a render of this element to apply the transform with all skews and rotations
8631
8621
  // set to 0.
@@ -8645,7 +8635,13 @@
8645
8635
  styleProp) {
8646
8636
  if (!this.instance || this.isSVG)
8647
8637
  return;
8648
- if (!this.isVisible) {
8638
+ const lead = this.getLead();
8639
+ /**
8640
+ * Without crossfade, a new lead hides the previous one, as it's
8641
+ * usually unmounting. One that gave its layoutId away keeps
8642
+ * rendering, so only hide nodes that follow another.
8643
+ */
8644
+ if (!this.isVisible && lead !== this) {
8649
8645
  targetStyle.visibility = "hidden";
8650
8646
  return;
8651
8647
  }
@@ -8661,9 +8657,10 @@
8661
8657
  : "none";
8662
8658
  return;
8663
8659
  }
8664
- const lead = this.getLead();
8665
8660
  if (!this.projectionDelta || !this.layout || !lead.target) {
8666
- if (this.options.layoutId) {
8661
+ if (this.options.layoutId || this.needsShow) {
8662
+ this.needsShow = false;
8663
+ targetStyle.visibility = "";
8667
8664
  targetStyle.opacity =
8668
8665
  this.latestValues.opacity !== undefined
8669
8666
  ? this.latestValues.opacity
@@ -8797,52 +8794,49 @@
8797
8794
  const isShared = snapshot.source !== node.layout.source;
8798
8795
  // TODO Maybe we want to also resize the layout snapshot so we don't trigger
8799
8796
  // animations for instance if layout="size" and an element has only changed position
8800
- if (animationType === "size") {
8801
- eachAxis((axis) => {
8802
- const axisSnapshot = isShared
8803
- ? snapshot.measuredBox[axis]
8804
- : snapshot.layoutBox[axis];
8805
- const length = calcLength(axisSnapshot);
8806
- axisSnapshot.min = layout[axis].min;
8807
- axisSnapshot.max = axisSnapshot.min + length;
8808
- });
8809
- }
8810
- else if (animationType === "x" || animationType === "y") {
8811
- const snapAxis = animationType === "x" ? "y" : "x";
8812
- copyAxisInto(isShared
8813
- ? snapshot.measuredBox[snapAxis]
8814
- : snapshot.layoutBox[snapAxis], layout[snapAxis]);
8815
- }
8816
- else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8817
- eachAxis((axis) => {
8818
- const axisSnapshot = isShared
8819
- ? snapshot.measuredBox[axis]
8820
- : snapshot.layoutBox[axis];
8821
- const length = calcLength(layout[axis]);
8822
- axisSnapshot.max = axisSnapshot.min + length;
8823
- /**
8824
- * Ensure relative target gets resized and rerendererd
8825
- */
8826
- if (node.relativeTarget && !node.currentAnimation) {
8827
- node.isProjectionDirty = true;
8828
- node.relativeTarget[axis].max =
8829
- node.relativeTarget[axis].min + length;
8830
- }
8831
- });
8832
- }
8797
+ const resizeSnapshot = (box, to) => {
8798
+ if (animationType === "size") {
8799
+ eachAxis((axis) => {
8800
+ const length = calcLength(box[axis]);
8801
+ box[axis].min = to[axis].min;
8802
+ box[axis].max = box[axis].min + length;
8803
+ });
8804
+ }
8805
+ else if (animationType === "x" || animationType === "y") {
8806
+ const snapAxis = animationType === "x" ? "y" : "x";
8807
+ copyAxisInto(box[snapAxis], to[snapAxis]);
8808
+ }
8809
+ else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8810
+ eachAxis((axis) => {
8811
+ const length = calcLength(to[axis]);
8812
+ box[axis].max = box[axis].min + length;
8813
+ /**
8814
+ * Ensure relative target gets resized and rerendererd
8815
+ */
8816
+ if (node.relativeTarget && !node.currentAnimation) {
8817
+ node.isProjectionDirty = true;
8818
+ node.relativeTarget[axis].max =
8819
+ node.relativeTarget[axis].min + length;
8820
+ }
8821
+ });
8822
+ }
8823
+ };
8824
+ const snapshotBox = isShared ? snapshot.measuredBox : snapshot.layoutBox;
8825
+ resizeSnapshot(snapshotBox, layout);
8833
8826
  const layoutDelta = createDelta();
8834
8827
  calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);
8835
8828
  const visualDelta = createDelta();
8836
- if (isShared) {
8837
- calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
8838
- }
8839
- else {
8840
- calcBoxDelta(visualDelta, layout, snapshot.layoutBox);
8841
- }
8829
+ calcBoxDelta(visualDelta, isShared ? node.applyTransform(measuredLayout, true) : layout, snapshotBox);
8842
8830
  const hasLayoutChanged = !isDeltaZero(layoutDelta);
8843
8831
  let hasRelativeLayoutChanged = false;
8844
- if (!node.resumeFrom) {
8845
- const relativeParent = node.getClosestProjectingParent();
8832
+ const relativeParent = node.getClosestProjectingParent();
8833
+ /**
8834
+ * A snapshot resumed from another element is only relative to this
8835
+ * node's relativeParent if it's a layoutRoot that contains both.
8836
+ */
8837
+ if (!node.resumeFrom ||
8838
+ (relativeParent?.options.layoutRoot &&
8839
+ node.resumeFrom.path.includes(relativeParent))) {
8846
8840
  /**
8847
8841
  * If the relativeParent is itself resuming from a different element then
8848
8842
  * the relative snapshot is not relavent
@@ -8851,10 +8845,22 @@
8851
8845
  const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
8852
8846
  if (parentSnapshot && parentLayout) {
8853
8847
  const anchor = node.options.layoutAnchor || undefined;
8848
+ /**
8849
+ * A shared snapshot includes the transforms of the old
8850
+ * element's ancestors below the layoutRoot, as they
8851
+ * aren't shared with the new element.
8852
+ */
8854
8853
  const relativeSnapshot = createBox();
8855
- calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8854
+ calcRelativePosition(relativeSnapshot, isShared
8855
+ ? node.resumeFrom.applyTransform(snapshot.layoutBox, true, undefined, true, relativeParent.depth + 1)
8856
+ : snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8856
8857
  const relativeLayout = createBox();
8857
8858
  calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox, anchor);
8859
+ /**
8860
+ * A shared snapshot is resized in page space, above, so
8861
+ * resize it relative to the layoutRoot too.
8862
+ */
8863
+ isShared && resizeSnapshot(relativeSnapshot, relativeLayout);
8858
8864
  if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {
8859
8865
  hasRelativeLayoutChanged = true;
8860
8866
  }
@@ -8876,8 +8882,7 @@
8876
8882
  });
8877
8883
  }
8878
8884
  else if (node.isLead()) {
8879
- const { onExitComplete } = node.options;
8880
- onExitComplete && onExitComplete();
8885
+ node.options.onExitComplete?.();
8881
8886
  }
8882
8887
  /**
8883
8888
  * Clearing transition
@@ -8937,10 +8942,13 @@
8937
8942
  * A dragged node doesn't layout animate, so it jumps to its new layout. Shift
8938
8943
  * its descendants' snapshots by the same amount, so they only animate layout
8939
8944
  * changes relative to it, rather than lagging behind.
8945
+ *
8946
+ * If its drag ended since the snapshot (e.g. drag disabled from onDrag), it
8947
+ * layout animates again, so its descendants mustn't follow its jump.
8940
8948
  */
8941
8949
  function followDraggedAncestor(node) {
8942
8950
  const { snapshot, dragAncestor } = node;
8943
- const to = dragAncestor?.layout;
8951
+ const to = dragAncestor?.isAnimationBlocked && dragAncestor.layout;
8944
8952
  if (!snapshot || !to || node.resumeFrom || node.isAnimationBlocked)
8945
8953
  return;
8946
8954
  const from = dragAncestor.dragSnapshot;
@@ -8980,7 +8988,7 @@
8980
8988
  }
8981
8989
  function resetTransformStyle(node) {
8982
8990
  const { visualElement } = node.options;
8983
- if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {
8991
+ if (visualElement?.getProps().onBeforeLayoutMeasure) {
8984
8992
  visualElement.notify("BeforeLayoutMeasure");
8985
8993
  }
8986
8994
  node.resetTransform();
@@ -9014,7 +9022,7 @@
9014
9022
  mixAxis(output.y, from.y, to.y, p);
9015
9023
  }
9016
9024
  function hasOpacityCrossfade(node) {
9017
- return (node.animationValues && node.animationValues.opacityExit !== undefined);
9025
+ return node.animationValues?.opacityExit !== undefined;
9018
9026
  }
9019
9027
  const defaultLayoutTransition = {
9020
9028
  duration: 0.45,
@@ -9040,6 +9048,13 @@
9040
9048
  roundAxis(box.x);
9041
9049
  roundAxis(box.y);
9042
9050
  }
9051
+ /**
9052
+ * Align an axis to the start of another, keeping the length of a layout axis.
9053
+ * The length is read first, as output can be the layout axis itself.
9054
+ */
9055
+ function alignAxis(output, from, layout) {
9056
+ output.max = calcLength(layout) + (output.min = from.min);
9057
+ }
9043
9058
  function shouldAnimatePositionOnly(animationType, snapshot, layout) {
9044
9059
  return (animationType === "position" ||
9045
9060
  (animationType === "preserve-aspect" &&
@@ -9054,11 +9069,16 @@
9054
9069
  return () => target.removeEventListener(eventName, handler, options);
9055
9070
  }
9056
9071
 
9057
- const DocumentProjectionNode = createProjectionNode({
9072
+ const DocumentProjectionNode =
9073
+ /* @__PURE__ */ createProjectionNode({
9058
9074
  attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
9059
9075
  measureScroll: () => ({
9060
- x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0,
9061
- y: document.documentElement.scrollTop || document.body?.scrollTop || 0,
9076
+ x: document.documentElement.scrollLeft ||
9077
+ document.body?.scrollLeft ||
9078
+ 0,
9079
+ y: document.documentElement.scrollTop ||
9080
+ document.body?.scrollTop ||
9081
+ 0,
9062
9082
  }),
9063
9083
  checkIsScrollRoot: () => true,
9064
9084
  });
@@ -9066,7 +9086,9 @@
9066
9086
  const rootProjectionNode = {
9067
9087
  current: undefined,
9068
9088
  };
9069
- const HTMLProjectionNode = createProjectionNode({
9089
+
9090
+ const HTMLProjectionNode =
9091
+ /* @__PURE__ */ createProjectionNode({
9070
9092
  measureScroll: (instance) => ({
9071
9093
  x: instance.scrollLeft,
9072
9094
  y: instance.scrollTop,
@@ -9083,7 +9105,7 @@
9083
9105
  resetTransform: (instance, value) => {
9084
9106
  instance.style.transform = value !== undefined ? value : "none";
9085
9107
  },
9086
- checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9108
+ checkIsScrollRoot: (instance) => window.getComputedStyle(instance).position === "fixed",
9087
9109
  });
9088
9110
 
9089
9111
  const visualElementStore = new WeakMap();
@@ -9110,7 +9132,7 @@
9110
9132
  "whileDrag",
9111
9133
  "exit",
9112
9134
  ];
9113
- const variantProps = ["initial", ...variantPriorityOrder];
9135
+ const variantProps = /* @__PURE__ */ ["initial"].concat(variantPriorityOrder);
9114
9136
 
9115
9137
  function isControllingVariants(props) {
9116
9138
  if (isAnimationControls(props.animate))
@@ -9369,9 +9391,7 @@
9369
9391
  }
9370
9392
  this.current = instance;
9371
9393
  visualElementStore.set(instance, this);
9372
- if (this.projection && !this.projection.instance) {
9373
- this.projection.mount(instance);
9374
- }
9394
+ this.projection?.instance || this.projection?.mount(instance);
9375
9395
  /**
9376
9396
  * Join the closest variant node above, so its variant changes
9377
9397
  * propagate here, unless inherit={false} cuts the chain.
@@ -9417,12 +9437,12 @@
9417
9437
  this.hasBeenMounted = true;
9418
9438
  }
9419
9439
  unmount() {
9420
- this.projection && this.projection.unmount();
9440
+ this.projection?.unmount();
9421
9441
  cancelFrame(this.notifyUpdate);
9422
9442
  cancelFrame(this.render);
9423
9443
  this.valueSubscriptions.forEach((remove) => remove());
9424
9444
  this.valueSubscriptions.clear();
9425
- this.removeFromVariantTree && this.removeFromVariantTree();
9445
+ this.removeFromVariantTree?.();
9426
9446
  this.parent?.removeChild(this);
9427
9447
  for (const key in this.events) {
9428
9448
  this.events[key].clear();
@@ -9438,17 +9458,14 @@
9438
9458
  }
9439
9459
  addChild(child) {
9440
9460
  this.children.add(child);
9441
- this.enteringChildren ?? (this.enteringChildren = new Set());
9442
- this.enteringChildren.add(child);
9461
+ (this.enteringChildren || (this.enteringChildren = new Set())).add(child);
9443
9462
  }
9444
9463
  removeChild(child) {
9445
9464
  this.children.delete(child);
9446
- this.enteringChildren && this.enteringChildren.delete(child);
9465
+ this.enteringChildren?.delete(child);
9447
9466
  }
9448
9467
  bindToMotionValue(key, value) {
9449
- if (this.valueSubscriptions.has(key)) {
9450
- this.valueSubscriptions.get(key)();
9451
- }
9468
+ this.valueSubscriptions.get(key)?.();
9452
9469
  if (value.accelerate &&
9453
9470
  acceleratedValues.has(key) &&
9454
9471
  this.current instanceof HTMLElement) {
@@ -9490,8 +9507,7 @@
9490
9507
  }
9491
9508
  this.valueSubscriptions.set(key, () => {
9492
9509
  removeOnChange();
9493
- if (removeSyncCheck)
9494
- removeSyncCheck();
9510
+ removeSyncCheck?.();
9495
9511
  // Defer to MotionValue.on("change") auto-stop so React 19 remounts
9496
9512
  // can resubscribe before the animation is cancelled (#3315).
9497
9513
  });
@@ -9584,10 +9600,8 @@
9584
9600
  */
9585
9601
  for (let i = 0; i < propEventHandlers.length; i++) {
9586
9602
  const key = propEventHandlers[i];
9587
- if (this.propEventSubscriptions[key]) {
9588
- this.propEventSubscriptions[key]();
9589
- delete this.propEventSubscriptions[key];
9590
- }
9603
+ this.propEventSubscriptions[key]?.();
9604
+ delete this.propEventSubscriptions[key];
9591
9605
  const listenerName = ("on" + key);
9592
9606
  const listener = props[listenerName];
9593
9607
  if (listener) {
@@ -9595,9 +9609,7 @@
9595
9609
  }
9596
9610
  }
9597
9611
  this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues);
9598
- if (this.handleChildMotionValue) {
9599
- this.handleChildMotionValue();
9600
- }
9612
+ this.handleChildMotionValue?.();
9601
9613
  }
9602
9614
  getProps() {
9603
9615
  return this.props;
@@ -9606,7 +9618,7 @@
9606
9618
  * Returns the variant definition with a given name.
9607
9619
  */
9608
9620
  getVariant(name) {
9609
- return this.props.variants ? this.props.variants[name] : undefined;
9621
+ return this.props.variants?.[name];
9610
9622
  }
9611
9623
  /**
9612
9624
  * Returns the defined default transition on this component.
@@ -9644,11 +9656,8 @@
9644
9656
  */
9645
9657
  removeValue(key) {
9646
9658
  this.values.delete(key);
9647
- const unsubscribe = this.valueSubscriptions.get(key);
9648
- if (unsubscribe) {
9649
- unsubscribe();
9650
- this.valueSubscriptions.delete(key);
9651
- }
9659
+ this.valueSubscriptions.get(key)?.();
9660
+ this.valueSubscriptions.delete(key);
9652
9661
  delete this.latestValues[key];
9653
9662
  this.removeValueFromRenderState(key, this.renderState);
9654
9663
  }
@@ -9659,10 +9668,10 @@
9659
9668
  return this.values.has(key);
9660
9669
  }
9661
9670
  getValue(key, defaultValue) {
9662
- if (this.props.values && this.props.values[key]) {
9663
- return this.props.values[key];
9664
- }
9665
- let value = this.values.get(key);
9671
+ let value = this.props.values?.[key];
9672
+ if (value)
9673
+ return value;
9674
+ value = this.values.get(key);
9666
9675
  if (value === undefined && defaultValue !== undefined) {
9667
9676
  value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
9668
9677
  owner: this,
@@ -9712,15 +9721,11 @@
9712
9721
  this.baseTarget[key] = value;
9713
9722
  }
9714
9723
  on(eventName, callback) {
9715
- if (!this.events[eventName]) {
9716
- this.events[eventName] = new motionUtils.SubscriptionManager();
9717
- }
9718
- return this.events[eventName].add(callback);
9724
+ return (this.events[eventName] ||
9725
+ (this.events[eventName] = new motionUtils.SubscriptionManager())).add(callback);
9719
9726
  }
9720
9727
  notify(eventName, ...args) {
9721
- if (this.events[eventName]) {
9722
- this.events[eventName].notify(...args);
9723
- }
9728
+ this.events[eventName]?.notify(...args);
9724
9729
  }
9725
9730
  scheduleRenderMicrotask() {
9726
9731
  microtask.render(this.render);
@@ -9886,7 +9891,7 @@
9886
9891
  let ancestor = element.parentElement;
9887
9892
  while (ancestor) {
9888
9893
  const node = layoutNodes.get(ancestor);
9889
- if (node && node.instance)
9894
+ if (node?.instance)
9890
9895
  return node;
9891
9896
  ancestor = ancestor.parentElement;
9892
9897
  }
@@ -10152,7 +10157,7 @@
10152
10157
  hasSurvivor &&
10153
10158
  !newMemberIds.has(layoutId)) {
10154
10159
  if (restore && restore.parent.isConnected) {
10155
- restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10160
+ restore.parent.insertBefore(element, restore.next?.parentNode === restore.parent
10156
10161
  ? restore.next
10157
10162
  : null);
10158
10163
  node.isPresent = false;
@@ -10357,10 +10362,6 @@
10357
10362
  * Scroll positions of scrollable ancestors and window.
10358
10363
  */
10359
10364
  this.scrollPositions = new Map();
10360
- /**
10361
- * Cleanup function for scroll listeners.
10362
- */
10363
- this.removeScrollListeners = null;
10364
10365
  this.onElementScroll = (event) => {
10365
10366
  this.handleScroll(event.target);
10366
10367
  };
@@ -10388,10 +10389,10 @@
10388
10389
  this.history.push({ ...point, timestamp: time.now() });
10389
10390
  const { onStart, onMove } = this.handlers;
10390
10391
  if (!isPanStarted) {
10391
- onStart && onStart(this.lastMoveEvent, info);
10392
+ onStart?.(this.lastMoveEvent, info);
10392
10393
  this.startEvent = this.lastMoveEvent;
10393
10394
  }
10394
- onMove && onMove(this.lastMoveEvent, info);
10395
+ onMove?.(this.lastMoveEvent, info);
10395
10396
  };
10396
10397
  this.handlePointerMove = (event, info) => {
10397
10398
  /**
@@ -10416,17 +10417,15 @@
10416
10417
  // Resume animation if dragSnapToOrigin is set OR if no drag started (user just clicked)
10417
10418
  // This ensures constraint animations continue when interrupted by a click
10418
10419
  if (this.dragSnapToOrigin || !this.startEvent) {
10419
- resumeAnimation && resumeAnimation();
10420
+ resumeAnimation?.();
10420
10421
  }
10421
10422
  if (!(this.lastMoveEvent && this.lastMoveEventInfo))
10422
10423
  return;
10423
10424
  const panInfo = getPanInfo(event.type === "pointercancel"
10424
10425
  ? this.lastMoveEventInfo
10425
10426
  : transformPoint(info, this.transformPagePoint), this.history);
10426
- if (this.startEvent && onEnd) {
10427
- onEnd(event, panInfo);
10428
- }
10429
- onSessionEnd && onSessionEnd(event, panInfo);
10427
+ this.startEvent && onEnd?.(event, panInfo);
10428
+ onSessionEnd?.(event, panInfo);
10430
10429
  };
10431
10430
  // If we have more than one touch, don't start detecting this gesture
10432
10431
  if (!isPrimaryPointer(event))
@@ -10439,8 +10438,13 @@
10439
10438
  const info = extractEventInfo(event);
10440
10439
  const initialInfo = transformPoint(info, this.transformPagePoint);
10441
10440
  const { point } = initialInfo;
10442
- const { timestamp } = frameData;
10443
- this.history = [{ ...point, timestamp }];
10441
+ /**
10442
+ * Stamp the origin with time.now(), not frameData.timestamp: when
10443
+ * the frameloop is idle, frameData.timestamp is from the last frame
10444
+ * that ran, which can be seconds old, and a fast flick from a
10445
+ * standstill would then report near-zero velocity. See #1747.
10446
+ */
10447
+ this.history = [{ ...point, timestamp: time.now() }];
10444
10448
  const { onSessionStart } = handlers;
10445
10449
  onSessionStart &&
10446
10450
  onSessionStart(event, getPanInfo(initialInfo, this.history));
@@ -10464,30 +10468,19 @@
10464
10468
  const style = getComputedStyle(current);
10465
10469
  if (overflowStyles.has(style.overflowX) ||
10466
10470
  overflowStyles.has(style.overflowY)) {
10467
- this.scrollPositions.set(current, {
10468
- x: current.scrollLeft,
10469
- y: current.scrollTop,
10470
- });
10471
+ this.scrollPositions.set(current, getScroll(current));
10471
10472
  }
10472
10473
  current = current.parentElement;
10473
10474
  }
10474
10475
  // Track window scroll
10475
- this.scrollPositions.set(window, {
10476
- x: window.scrollX,
10477
- y: window.scrollY,
10478
- });
10476
+ this.scrollPositions.set(window, getScroll(window));
10477
+ this.removeScrollListeners = motionUtils.pipe(
10479
10478
  // Capture listener catches element scroll events as they bubble
10480
- window.addEventListener("scroll", this.onElementScroll, {
10479
+ addDomEvent(window, "scroll", this.onElementScroll, {
10481
10480
  capture: true,
10482
- });
10481
+ }),
10483
10482
  // Direct window scroll listener (window scroll doesn't bubble)
10484
- window.addEventListener("scroll", this.onWindowScroll);
10485
- this.removeScrollListeners = () => {
10486
- window.removeEventListener("scroll", this.onElementScroll, {
10487
- capture: true,
10488
- });
10489
- window.removeEventListener("scroll", this.onWindowScroll);
10490
- };
10483
+ addDomEvent(window, "scroll", this.onWindowScroll, {}));
10491
10484
  }
10492
10485
  /**
10493
10486
  * Handle scroll compensation during drag.
@@ -10500,12 +10493,7 @@
10500
10493
  if (!initial)
10501
10494
  return;
10502
10495
  const isWindow = target === window;
10503
- const current = isWindow
10504
- ? { x: window.scrollX, y: window.scrollY }
10505
- : {
10506
- x: target.scrollLeft,
10507
- y: target.scrollTop,
10508
- };
10496
+ const current = getScroll(target);
10509
10497
  const delta = { x: current.x - initial.x, y: current.y - initial.y };
10510
10498
  if (delta.x === 0 && delta.y === 0)
10511
10499
  return;
@@ -10530,12 +10518,18 @@
10530
10518
  this.handlers = handlers;
10531
10519
  }
10532
10520
  end() {
10533
- this.removeListeners && this.removeListeners();
10534
- this.removeScrollListeners && this.removeScrollListeners();
10521
+ this.removeListeners?.();
10522
+ this.removeScrollListeners?.();
10535
10523
  this.scrollPositions.clear();
10536
10524
  cancelFrame(this.updatePoint);
10537
10525
  }
10538
10526
  }
10527
+ const getScroll = (target) => target === window
10528
+ ? { x: window.scrollX, y: window.scrollY }
10529
+ : {
10530
+ x: target.scrollLeft,
10531
+ y: target.scrollTop,
10532
+ };
10539
10533
  function transformPoint(info, transformPagePoint) {
10540
10534
  return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
10541
10535
  }
@@ -10792,6 +10786,25 @@
10792
10786
  : dragElastic[label] || 0;
10793
10787
  }
10794
10788
 
10789
+ /**
10790
+ * Re-read the scroll of the projection's ancestors, and return that of the
10791
+ * `layoutScroll` ones as a key that changes when any of them scroll.
10792
+ *
10793
+ * Clear the cached scroll first so `updateScroll` bypasses its
10794
+ * per-animationId cache and re-reads the live value.
10795
+ */
10796
+ function measureScroll(projection) {
10797
+ let key = "";
10798
+ for (const node of projection.path) {
10799
+ node.scroll = undefined;
10800
+ node.updateScroll();
10801
+ const { scroll } = node;
10802
+ if (node !== projection.root && scroll) {
10803
+ key += scroll.offset.x + "," + scroll.offset.y + ",";
10804
+ }
10805
+ }
10806
+ return key;
10807
+ }
10795
10808
  const elementDragControls = new WeakMap();
10796
10809
  class VisualElementDragControls {
10797
10810
  constructor(visualElement, readProps = () => visualElement.getProps()) {
@@ -10823,8 +10836,7 @@
10823
10836
  /**
10824
10837
  * Don't start dragging if this component is exiting
10825
10838
  */
10826
- const { presenceContext } = this.visualElement;
10827
- if (presenceContext && presenceContext.isPresent === false)
10839
+ if (this.visualElement.presenceContext?.isPresent === false)
10828
10840
  return;
10829
10841
  const onSessionStart = (event) => {
10830
10842
  if (snapToCursor)
@@ -10835,8 +10847,7 @@
10835
10847
  // Attempt to grab the global drag gesture lock - maybe make this part of PanSession
10836
10848
  const { drag, dragPropagation, onDragStart } = this.getProps();
10837
10849
  if (drag && !dragPropagation) {
10838
- if (this.openDragLock)
10839
- this.openDragLock();
10850
+ this.openDragLock?.();
10840
10851
  this.openDragLock = setDragLock(drag);
10841
10852
  // If we don 't have the lock, don't start dragging
10842
10853
  if (!this.openDragLock)
@@ -10847,9 +10858,10 @@
10847
10858
  this.isDragging = true;
10848
10859
  this.currentDirection = null;
10849
10860
  this.resolveConstraints();
10850
- if (this.visualElement.projection) {
10851
- this.visualElement.projection.isAnimationBlocked = true;
10852
- this.visualElement.projection.target = undefined;
10861
+ const { projection } = this.visualElement;
10862
+ if (projection) {
10863
+ projection.isAnimationBlocked = true;
10864
+ projection.target = undefined;
10853
10865
  }
10854
10866
  /**
10855
10867
  * Record gesture origin and pointer offset
@@ -10871,13 +10883,11 @@
10871
10883
  current = parseFloat(current);
10872
10884
  }
10873
10885
  else if (percent.test(current)) {
10874
- const { projection } = this.visualElement;
10875
- if (projection && projection.layout) {
10876
- const measuredAxis = projection.layout.layoutBox[axis];
10877
- if (measuredAxis) {
10878
- const length = calcLength(measuredAxis);
10879
- current = length * (parseFloat(current) / 100);
10880
- }
10886
+ const measuredAxis = projection?.layout?.layoutBox[axis];
10887
+ if (measuredAxis) {
10888
+ current =
10889
+ calcLength(measuredAxis) *
10890
+ (parseFloat(current) / 100);
10881
10891
  }
10882
10892
  }
10883
10893
  this.originPoint[axis] = current;
@@ -10887,8 +10897,7 @@
10887
10897
  frame.update(() => onDragStart(event, info), false, true);
10888
10898
  }
10889
10899
  addValueToWillChange(this.visualElement, "transform");
10890
- const { animationState } = this.visualElement;
10891
- animationState && animationState.setActive("whileDrag", true);
10900
+ this.visualElement.animationState?.setActive("whileDrag", true);
10892
10901
  };
10893
10902
  const onMove = (event, info) => {
10894
10903
  this.latestPointerEvent = event;
@@ -10911,8 +10920,8 @@
10911
10920
  onDirectionLock && onDirectionLock(this.currentDirection);
10912
10921
  }
10913
10922
  // Update each point with the latest position
10914
- this.updateAxis("x", info.point, offset);
10915
- this.updateAxis("y", info.point, offset);
10923
+ this.updateAxis("x", offset);
10924
+ this.updateAxis("y", offset);
10916
10925
  /**
10917
10926
  * Ideally we would leave the renderer to fire naturally at the end of
10918
10927
  * this frame but if the element is about to change layout as the result
@@ -10956,7 +10965,11 @@
10956
10965
  element: this.visualElement.current,
10957
10966
  });
10958
10967
  }
10959
- stop(event, panInfo) {
10968
+ /**
10969
+ * @param dragAxes - The axes to animate on release, if not the `drag`
10970
+ * prop's, e.g. when drag was disabled mid-gesture.
10971
+ */
10972
+ stop(event, panInfo, dragAxes) {
10960
10973
  const finalEvent = event || this.latestPointerEvent;
10961
10974
  const finalPanInfo = panInfo || this.latestPanInfo;
10962
10975
  const isDragging = this.isDragging;
@@ -10964,7 +10977,7 @@
10964
10977
  if (!isDragging || !finalPanInfo || !finalEvent)
10965
10978
  return;
10966
10979
  const { velocity } = finalPanInfo;
10967
- this.startAnimation(velocity);
10980
+ this.startAnimation(velocity, dragAxes);
10968
10981
  const { onDragEnd } = this.getProps();
10969
10982
  if (onDragEnd) {
10970
10983
  frame.postRender(() => onDragEnd(finalEvent, finalPanInfo));
@@ -10977,12 +10990,11 @@
10977
10990
  projection.isAnimationBlocked = false;
10978
10991
  }
10979
10992
  this.endPanSession();
10980
- const { dragPropagation } = this.getProps();
10981
- if (!dragPropagation && this.openDragLock) {
10993
+ if (!this.getProps().dragPropagation && this.openDragLock) {
10982
10994
  this.openDragLock();
10983
10995
  this.openDragLock = null;
10984
10996
  }
10985
- animationState && animationState.setActive("whileDrag", false);
10997
+ animationState?.setActive("whileDrag", false);
10986
10998
  }
10987
10999
  /**
10988
11000
  * Clean up the pan session without modifying other drag state.
@@ -10990,31 +11002,42 @@
10990
11002
  * without affecting projection animations or drag locks.
10991
11003
  */
10992
11004
  endPanSession() {
10993
- this.panSession && this.panSession.end();
11005
+ this.panSession?.end();
10994
11006
  this.panSession = undefined;
10995
11007
  }
10996
- updateAxis(axis, _point, offset) {
10997
- const { drag } = this.getProps();
11008
+ updateAxis(axis, offset) {
11009
+ /**
11010
+ * Read drag per axis: a callback fired while updating the x axis
11011
+ * can synchronously re-render with new props.
11012
+ */
11013
+ const { drag } = this.readProps();
10998
11014
  // If we're not dragging this axis, do an early return.
10999
11015
  if (!offset || !shouldDrag(axis, drag, this.currentDirection))
11000
11016
  return;
11001
11017
  const axisValue = this.getAxisMotionValue(axis);
11002
11018
  let next = this.originPoint[axis] + offset[axis];
11003
11019
  // Apply constraints
11004
- if (this.constraints && this.constraints[axis]) {
11005
- next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
11020
+ const constraints = this.constraints && this.constraints[axis];
11021
+ if (constraints) {
11022
+ next = applyConstraints(next, constraints, this.elastic[axis]);
11006
11023
  }
11007
11024
  axisValue.set(next);
11008
11025
  }
11009
11026
  resolveConstraints() {
11010
11027
  const { dragConstraints, dragElastic } = this.getProps();
11011
- const layout = this.visualElement.projection &&
11012
- !this.visualElement.projection.layout
11013
- ? this.visualElement.projection.measure(false)
11014
- : this.visualElement.projection?.layout;
11028
+ const { projection } = this.visualElement;
11029
+ const layout = projection && (projection.layout || projection.measure(false));
11015
11030
  const prevConstraints = this.constraints;
11016
11031
  if (isElementConstraints(dragConstraints)) {
11017
- if (!this.constraints) {
11032
+ /**
11033
+ * Ref constraints are measured with the layout. Scrolling a
11034
+ * `layoutScroll` ancestor since can move the element relative
11035
+ * to them without a layout measurement, so measure them again
11036
+ * (#2024). Otherwise keep them: they and the layout can both
11037
+ * have moved on the page since, e.g. when content above grows.
11038
+ */
11039
+ if (!this.constraints ||
11040
+ this.scroll !== measureScroll(projection)) {
11018
11041
  this.constraints = this.resolveRefConstraints();
11019
11042
  }
11020
11043
  }
@@ -11057,21 +11080,20 @@
11057
11080
  if (!projection || !projection.layout)
11058
11081
  return false;
11059
11082
  /**
11060
- * Refresh the root scroll offset so the constraint's viewport box
11061
- * translates to correct page coordinates. The scroll captured at
11062
- * drag mount can be stale if the document was scrolled afterwards —
11063
- * e.g. via the browser restoring scroll on refresh, or an ancestor
11064
- * layout effect running after this element's mount (#2829).
11065
- *
11066
- * Clear the cached scroll first so `updateScroll` bypasses its
11067
- * per-animationId cache and re-reads the live value.
11083
+ * Refresh the scroll offsets of the root and `layoutScroll`
11084
+ * ancestors so the constraint's viewport box translates to the
11085
+ * layout's coordinates. The scroll captured when the layout was
11086
+ * measured can be stale if they've scrolled since — e.g. via the
11087
+ * browser restoring scroll on refresh, or an ancestor layout effect
11088
+ * running after this element's mount (#2829).
11068
11089
  */
11069
- if (projection.root) {
11070
- projection.root.scroll = undefined;
11071
- projection.root.updateScroll();
11072
- }
11090
+ this.scroll = measureScroll(projection);
11073
11091
  const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
11074
- let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
11092
+ /**
11093
+ * layoutBox removes the scroll of `layoutScroll` ancestors, so
11094
+ * remove it from the constraints box too.
11095
+ */
11096
+ let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, projection.removeElementScroll(constraintsBox));
11075
11097
  /**
11076
11098
  * If there's an onMeasureDragConstraints listener we call it and
11077
11099
  * if different constraints are returned, set constraints to that
@@ -11085,14 +11107,14 @@
11085
11107
  }
11086
11108
  return measuredConstraints;
11087
11109
  }
11088
- startAnimation(velocity) {
11110
+ startAnimation(velocity, dragAxes) {
11089
11111
  const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();
11090
11112
  const constraints = this.constraints || {};
11091
11113
  const momentumAnimations = eachAxis((axis) => {
11092
- if (!shouldDrag(axis, drag, this.currentDirection)) {
11114
+ if (!shouldDrag(axis, dragAxes || drag, this.currentDirection)) {
11093
11115
  return;
11094
11116
  }
11095
- let transition = (constraints && constraints[axis]) || {};
11117
+ let transition = constraints[axis] || {};
11096
11118
  if (dragSnapToOrigin === true ||
11097
11119
  dragSnapToOrigin === axis)
11098
11120
  transition = { min: 0, max: 0 };
@@ -11198,7 +11220,7 @@
11198
11220
  this.visualElement.current.style.transform = transformTemplate
11199
11221
  ? transformTemplate({}, "")
11200
11222
  : "none";
11201
- projection.root && projection.root.updateScroll();
11223
+ projection.root?.updateScroll();
11202
11224
  projection.updateLayout();
11203
11225
  /**
11204
11226
  * Reset constraints so resolveConstraints() will recalculate them
@@ -11275,8 +11297,8 @@
11275
11297
  };
11276
11298
  const { projection } = this.visualElement;
11277
11299
  const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
11278
- if (projection && !projection.layout) {
11279
- projection.root && projection.root.updateScroll();
11300
+ if (!projection.layout) {
11301
+ projection.root?.updateScroll();
11280
11302
  projection.updateLayout();
11281
11303
  }
11282
11304
  frame.read(measureDragConstraints);
@@ -11292,9 +11314,15 @@
11292
11314
  const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => {
11293
11315
  if (this.isDragging && hasLayoutChanged) {
11294
11316
  eachAxis((axis) => {
11295
- const motionValue = this.getAxisMotionValue(axis);
11296
- if (!motionValue)
11317
+ /**
11318
+ * Only compensate axes this gesture drags. A
11319
+ * non-drag axis follows its layout instead, as
11320
+ * nothing would ever move it back (e.g. snapping
11321
+ * to origin only animates drag axes).
11322
+ */
11323
+ if (!shouldDrag(axis, this.getProps().drag, this.currentDirection))
11297
11324
  return;
11325
+ const motionValue = this.getAxisMotionValue(axis);
11298
11326
  this.originPoint[axis] += delta[axis].translate;
11299
11327
  motionValue.set(motionValue.get() + delta[axis].translate);
11300
11328
  });
@@ -11305,22 +11333,14 @@
11305
11333
  stopResizeListener();
11306
11334
  stopPointerListener();
11307
11335
  stopMeasureLayoutListener();
11308
- stopLayoutUpdateListener && stopLayoutUpdateListener();
11309
- stopResizeObservers && stopResizeObservers();
11336
+ stopLayoutUpdateListener();
11337
+ stopResizeObservers?.();
11310
11338
  };
11311
11339
  }
11312
11340
  getProps() {
11313
11341
  const props = this.readProps();
11314
- const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
11315
- return {
11316
- ...props,
11317
- drag,
11318
- dragDirectionLock,
11319
- dragPropagation,
11320
- dragConstraints,
11321
- dragElastic,
11322
- dragMomentum,
11323
- };
11342
+ const { dragElastic = defaultElastic, dragMomentum = true } = props;
11343
+ return { ...props, dragElastic, dragMomentum };
11324
11344
  }
11325
11345
  }
11326
11346
  /**
@@ -13655,6 +13675,12 @@
13655
13675
  }
13656
13676
 
13657
13677
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
13678
+ /**
13679
+ * The transition a value uses when it leaves a state (#1725): the state's
13680
+ * own transition when `out: true`, or the `out` transition itself.
13681
+ * Value-specific keys are resolved by animateTarget.
13682
+ */
13683
+ const getOutTransition = (transition) => transition?.out === true ? transition : transition?.out;
13658
13684
  /**
13659
13685
  * Diffs the element's animation props (one layer per AnimationType, highest
13660
13686
  * priority wins each value) against the previous call and starts animations
@@ -13676,13 +13702,18 @@
13676
13702
  let wasReset = false;
13677
13703
  function animateChanges(changedActiveType) {
13678
13704
  const { props, parent, manuallyAnimateOnMount } = visualElement;
13705
+ const { initial } = props;
13679
13706
  const isMounting = isInitialRender || wasReset;
13680
13707
  const animations = [];
13708
+ const resolveInitial = (definition = initial) => (typeof definition !== "boolean" &&
13709
+ resolveVariant(visualElement, Array.isArray(definition) ? definition[0] : definition, visualElement.presenceContext?.custom)) ||
13710
+ undefined;
13681
13711
  /**
13682
- * Values removed from a type. A lower-priority type that defines
13683
- * them animates them back, otherwise they fall back to a base target.
13712
+ * Values removed from a type, mapped to the out transition of the
13713
+ * state they're leaving. A lower-priority type that defines them
13714
+ * animates them back, otherwise they fall back to a base target.
13684
13715
  */
13685
- const removedKeys = new Set();
13716
+ const removedKeys = new Map();
13686
13717
  /**
13687
13718
  * Values claimed by active, higher-priority types.
13688
13719
  */
@@ -13700,6 +13731,13 @@
13700
13731
  do
13701
13732
  source = source.props.inherit !== false && source.parent;
13702
13733
  while (source && !source.isControllingVariants);
13734
+ /**
13735
+ * Mounting leaves initial, so values use its out transition. Like the
13736
+ * other types, variant children inherit initial's label.
13737
+ */
13738
+ const initialOut = isMounting &&
13739
+ getOutTransition(resolveInitial(initial ?? (source && source.props.initial))
13740
+ ?.transition);
13703
13741
  reversePriorityOrder.forEach((type, i) => {
13704
13742
  const typeState = state[type];
13705
13743
  const ownProp = props[type];
@@ -13711,8 +13749,6 @@
13711
13749
  : undefined;
13712
13750
  const propIsVariant = isVariantLabel(prop);
13713
13751
  const activeDelta = type === changedActiveType ? typeState.isActive : null;
13714
- if (activeDelta === false)
13715
- removedVariantIndex = i;
13716
13752
  /**
13717
13753
  * Inherited labels are animated by the parent through
13718
13754
  * variantChildren, unless this element mounted after its parent.
@@ -13727,6 +13763,13 @@
13727
13763
  typeof prop === "boolean") {
13728
13764
  return;
13729
13765
  }
13766
+ /**
13767
+ * Set after the skip above, so deactivating a type that has nothing
13768
+ * to animate (e.g. whileTap with no prop) doesn't re-run the variants
13769
+ * below it.
13770
+ */
13771
+ if (activeDelta === false)
13772
+ removedVariantIndex = i;
13730
13773
  /**
13731
13774
  * Don't re-resolve a running exit: a changed custom would start
13732
13775
  * new value animations that stop the originals, leaving the exit
@@ -13746,6 +13789,7 @@
13746
13789
  let handledRemovedValues = false;
13747
13790
  const definitionList = Array.isArray(prop) ? prop : [prop];
13748
13791
  let resolvedValues = {};
13792
+ let out;
13749
13793
  if (activeDelta !== false) {
13750
13794
  for (const definition of definitionList) {
13751
13795
  const { transition, transitionEnd, ...target } = resolveVariant(visualElement, definition, getTypeCustom(visualElement, type)) || {};
@@ -13754,6 +13798,11 @@
13754
13798
  ...target,
13755
13799
  ...transitionEnd,
13756
13800
  };
13801
+ /**
13802
+ * One out transition per type. With a list of labels,
13803
+ * the last one that sets out applies to all its values.
13804
+ */
13805
+ out = getOutTransition(transition) || out;
13757
13806
  }
13758
13807
  }
13759
13808
  const { prevResolvedValues } = typeState;
@@ -13769,13 +13818,18 @@
13769
13818
  const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
13770
13819
  ? !shallowCompare(next, prev) || variantDidChange
13771
13820
  : next !== prev;
13772
- if (valueHasChanged &&
13773
- (next === undefined || next === null)) {
13774
- removedKeys.add(key);
13821
+ let outTransition;
13822
+ if (valueHasChanged && (next === undefined || next === null)) {
13823
+ /**
13824
+ * The highest-priority state a value leaves wins.
13825
+ */
13826
+ removedKeys.has(key) ||
13827
+ removedKeys.set(key, typeState.prevOut);
13775
13828
  }
13776
13829
  else if (valueHasChanged ||
13777
13830
  (next !== undefined && removedKeys.has(key))) {
13778
13831
  shouldAnimateType = true;
13832
+ outTransition = removedKeys.get(key) || initialOut;
13779
13833
  if (removedKeys.delete(key))
13780
13834
  handledRemovedValues = true;
13781
13835
  typeState.needsAnimating[key] = true;
@@ -13786,9 +13840,11 @@
13786
13840
  else {
13787
13841
  typeState.protectedKeys[key] = true;
13788
13842
  }
13843
+ typeState.out[key] = outTransition;
13789
13844
  }
13790
13845
  typeState.prevProp = prop;
13791
13846
  typeState.prevResolvedValues = resolvedValues;
13847
+ typeState.prevOut = out;
13792
13848
  if (typeState.isActive) {
13793
13849
  encounteredKeys = { ...encounteredKeys, ...resolvedValues };
13794
13850
  }
@@ -13819,14 +13875,17 @@
13819
13875
  * longer defines a value it once did, it stays where it is.
13820
13876
  */
13821
13877
  if (removedKeys.size) {
13822
- const { initial } = props;
13823
13878
  const fallbackAnimation = {};
13824
- const resolvedInitial = typeof initial !== "boolean" &&
13825
- resolveVariant(visualElement, Array.isArray(initial) ? initial[0] : initial, visualElement.presenceContext?.custom);
13826
- if (resolvedInitial && resolvedInitial.transition) {
13827
- fallbackAnimation.transition = resolvedInitial.transition;
13828
- }
13829
- removedKeys.forEach((key) => {
13879
+ const resolvedInitial = resolveInitial();
13880
+ let fallbackTransition = resolvedInitial?.transition;
13881
+ removedKeys.forEach((outTransition, key) => {
13882
+ if (outTransition) {
13883
+ fallbackTransition = {
13884
+ ...(fallbackTransition ||
13885
+ visualElement.getDefaultTransition()),
13886
+ [key]: outTransition,
13887
+ };
13888
+ }
13830
13889
  const motionValue = visualElement.getValue(key);
13831
13890
  if (motionValue)
13832
13891
  motionValue.liveStyle = true;
@@ -13857,6 +13916,9 @@
13857
13916
  visualElement.baseTarget[key] = motionValue?.get();
13858
13917
  }
13859
13918
  });
13919
+ if (fallbackTransition) {
13920
+ fallbackAnimation.transition = fallbackTransition;
13921
+ }
13860
13922
  animations.push({ animation: fallbackAnimation });
13861
13923
  }
13862
13924
  const blockAnimation = (isMounting && visualElement.blockInitialAnimation) ||
@@ -13916,6 +13978,7 @@
13916
13978
  protectedKeys: {},
13917
13979
  needsAnimating: {},
13918
13980
  prevResolvedValues: {},
13981
+ out: {},
13919
13982
  };
13920
13983
  }
13921
13984
  return state;
@@ -14082,6 +14145,7 @@
14082
14145
  exports.buildSVGAttrs = buildSVGAttrs;
14083
14146
  exports.buildSVGPath = buildSVGPath;
14084
14147
  exports.buildTransform = buildTransform$1;
14148
+ exports.buildTransformer = buildTransformer;
14085
14149
  exports.calcAxisDelta = calcAxisDelta;
14086
14150
  exports.calcBoxDelta = calcBoxDelta;
14087
14151
  exports.calcChildStagger = calcChildStagger;
@@ -14236,6 +14300,7 @@
14236
14300
  exports.positionalKeys = positionalKeys;
14237
14301
  exports.prefersReducedMotion = prefersReducedMotion;
14238
14302
  exports.press = press;
14303
+ exports.processFrame = processFrame;
14239
14304
  exports.progressPercentage = progressPercentage;
14240
14305
  exports.propEffect = propEffect;
14241
14306
  exports.propagateDirtyNodes = propagateDirtyNodes;