motion-dom 14.6.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 (85) hide show
  1. package/dist/cjs/index.js +564 -579
  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 +4 -4
  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 +40 -44
  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/utils/can-animate.mjs +1 -0
  21. package/dist/es/animation/utils/can-animate.mjs.map +1 -1
  22. package/dist/es/animation/utils/css-variables-conversion.mjs +2 -1
  23. package/dist/es/animation/utils/css-variables-conversion.mjs.map +1 -1
  24. package/dist/es/animation/utils/is-transition-defined.mjs +1 -0
  25. package/dist/es/animation/utils/is-transition-defined.mjs.map +1 -1
  26. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +44 -21
  27. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -1
  28. package/dist/es/animation/waapi/utils/accelerated-values.mjs +4 -1
  29. package/dist/es/animation/waapi/utils/accelerated-values.mjs.map +1 -1
  30. package/dist/es/effects/style/transform.mjs +4 -20
  31. package/dist/es/effects/style/transform.mjs.map +1 -1
  32. package/dist/es/gestures/drag/VisualElementDragControls.mjs +78 -61
  33. package/dist/es/gestures/drag/VisualElementDragControls.mjs.map +1 -1
  34. package/dist/es/gestures/pan/PanSession.mjs +28 -39
  35. package/dist/es/gestures/pan/PanSession.mjs.map +1 -1
  36. package/dist/es/index.mjs +1 -1
  37. package/dist/es/layout/LayoutAnimationBuilder.mjs +2 -2
  38. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  39. package/dist/es/projection/animation/mix-values.mjs +3 -11
  40. package/dist/es/projection/animation/mix-values.mjs.map +1 -1
  41. package/dist/es/projection/geometry/delta-apply.mjs +10 -6
  42. package/dist/es/projection/geometry/delta-apply.mjs.map +1 -1
  43. package/dist/es/projection/geometry/delta-calc.mjs +2 -2
  44. package/dist/es/projection/geometry/delta-calc.mjs.map +1 -1
  45. package/dist/es/projection/geometry/delta-remove.mjs +2 -2
  46. package/dist/es/projection/geometry/delta-remove.mjs.map +1 -1
  47. package/dist/es/projection/node/HTMLProjectionNode.mjs +1 -1
  48. package/dist/es/projection/node/HTMLProjectionNode.mjs.map +1 -1
  49. package/dist/es/projection/node/create-projection-node.mjs +138 -137
  50. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  51. package/dist/es/projection/styles/transform.mjs +12 -16
  52. package/dist/es/projection/styles/transform.mjs.map +1 -1
  53. package/dist/es/projection/utils/has-transform.mjs +16 -2
  54. package/dist/es/projection/utils/has-transform.mjs.map +1 -1
  55. package/dist/es/render/VisualElement.mjs +20 -37
  56. package/dist/es/render/VisualElement.mjs.map +1 -1
  57. package/dist/es/render/dom/parse-transform.mjs +6 -17
  58. package/dist/es/render/dom/parse-transform.mjs.map +1 -1
  59. package/dist/es/render/html/HTMLVisualElement.mjs +2 -1
  60. package/dist/es/render/html/HTMLVisualElement.mjs.map +1 -1
  61. package/dist/es/render/html/utils/build-transform.mjs +25 -29
  62. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  63. package/dist/es/render/utils/animation-state.mjs +57 -13
  64. package/dist/es/render/utils/animation-state.mjs.map +1 -1
  65. package/dist/es/utils/interpolate.mjs +2 -1
  66. package/dist/es/utils/interpolate.mjs.map +1 -1
  67. package/dist/es/utils/mix/color.mjs +2 -1
  68. package/dist/es/utils/mix/color.mjs.map +1 -1
  69. package/dist/es/utils/mix/complex.mjs +4 -4
  70. package/dist/es/utils/mix/complex.mjs.map +1 -1
  71. package/dist/es/utils/resolve-elements.mjs.map +1 -1
  72. package/dist/es/value/index.mjs +13 -34
  73. package/dist/es/value/index.mjs.map +1 -1
  74. package/dist/es/value/types/color/hex.mjs +13 -26
  75. package/dist/es/value/types/color/hex.mjs.map +1 -1
  76. package/dist/es/value/types/complex/index.mjs +1 -1
  77. package/dist/es/value/types/complex/index.mjs.map +1 -1
  78. package/dist/index.d.ts +72 -21
  79. package/dist/motion-dom.dev.js +548 -572
  80. package/dist/motion-dom.js +1 -1
  81. package/dist/size-rollup-motion-value.js +1 -1
  82. package/dist/size-rollup-motion-value.js.map +1 -1
  83. package/dist/size-rollup-style-effect.js +1 -1
  84. package/dist/size-rollup-style-effect.js.map +1 -1
  85. package/package.json +4 -3
package/dist/cjs/index.js CHANGED
@@ -135,34 +135,21 @@ const rgba = {
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 = {
@@ -437,7 +424,8 @@ const getColorType = (v) => colorTypes.find((type) => type.test(v));
437
424
  function asRGBA(color) {
438
425
  const type = getColorType(color);
439
426
  if (!type) {
440
- motionUtils.warning(false, `'${color}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable");
427
+ process.env.NODE_ENV !== "production" &&
428
+ motionUtils.warning(false, `'${color}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable");
441
429
  return false;
442
430
  }
443
431
  let model = type.parse(color);
@@ -539,7 +527,6 @@ function matchOrder(origin, target) {
539
527
  return orderedOrigin;
540
528
  }
541
529
  const mixComplex = (origin, target) => {
542
- const template = complex.createTransformer(target);
543
530
  const originStats = analyseComplexValue(origin);
544
531
  const targetStats = analyseComplexValue(target);
545
532
  const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length &&
@@ -552,10 +539,11 @@ const mixComplex = (origin, target) => {
552
539
  !originStats.values.length)) {
553
540
  return mixVisibility(origin, target);
554
541
  }
555
- return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
542
+ return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), buildTransformer(targetStats));
556
543
  }
557
544
  else {
558
- 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");
545
+ process.env.NODE_ENV !== "production" &&
546
+ 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");
559
547
  return mixImmediate(origin, target);
560
548
  }
561
549
  };
@@ -844,37 +832,31 @@ function createGeneratorEasing(options, scale = 100, createGenerator) {
844
832
  };
845
833
  }
846
834
 
847
- const springDefaults = {
848
- // Default spring physics
849
- stiffness: 100,
850
- damping: 10,
851
- mass: 1.0,
852
- // Default duration/bounce-based options
853
- duration: 800, // in ms
854
- bounce: 0.3,
855
- visualDuration: 0.3, // in seconds
856
- // Rest thresholds
857
- restSpeed: {
858
- granular: 0.01,
859
- default: 2,
860
- },
861
- restDelta: {
862
- granular: 0.005,
863
- default: 0.5,
864
- },
865
- // Limits
866
- minDuration: 0.01, // in seconds
867
- maxDuration: 10.0, // in seconds
868
- minDamping: 0.05,
869
- };
835
+ // Default spring physics
836
+ const defaultStiffness = 100;
837
+ const defaultDamping = 10;
838
+ const defaultMass = 1.0;
839
+ // Default duration/bounce-based options
840
+ const defaultDuration = 800; // in ms
841
+ const defaultBounce = 0.3;
842
+ const defaultVisualDuration = 0.3; // in seconds
843
+ // Rest thresholds
844
+ const restSpeedGranular = 0.01;
845
+ const restSpeedDefault = 2;
846
+ const restDeltaGranular = 0.005;
847
+ const restDeltaDefault = 0.5;
848
+ // Limits
849
+ const minDuration = 0.01; // in seconds
850
+ const maxDuration = 10.0; // in seconds
851
+ const minDamping = 0.05;
870
852
  /**
871
853
  * Maps bounce to a damping ratio as SwiftUI does: 0 is critically damped, and
872
854
  * it approaches undamped towards 1 and infinitely overdamped towards -1. Both
873
855
  * ends are limited so the spring still moves and settles.
874
856
  */
875
857
  const bounceToDampingRatio = (bounce) => bounce < 0
876
- ? 1 / Math.max(1 + bounce, springDefaults.minDamping)
877
- : Math.max(1 - bounce, springDefaults.minDamping);
858
+ ? 1 / Math.max(1 + bounce, minDamping)
859
+ : Math.max(1 - bounce, minDamping);
878
860
  /**
879
861
  * Scales an overdamped spring's undamped frequency so that, at its defining
880
862
  * time, it has as far left to go as the critically damped spring that's
@@ -917,12 +899,13 @@ const safeMin = 0.001;
917
899
  * ignore inherited velocity and only resolve without valid physics. Returns
918
900
  * NaN physics when the root search doesn't converge.
919
901
  */
920
- function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, }) {
902
+ function findSpring({ duration = defaultDuration, bounce = defaultBounce, }) {
921
903
  let envelope;
922
904
  let derivative;
923
- motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
905
+ process.env.NODE_ENV !== "production" &&
906
+ motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
924
907
  const dampingRatio = bounceToDampingRatio(bounce);
925
- duration = motionUtils.clamp(springDefaults.minDuration, springDefaults.maxDuration, motionUtils.millisecondsToSeconds(duration));
908
+ duration = motionUtils.clamp(minDuration, maxDuration, motionUtils.millisecondsToSeconds(duration));
926
909
  if (dampingRatio < 1) {
927
910
  /**
928
911
  * Underdamped spring
@@ -1007,9 +990,9 @@ function getSpringOptions(options) {
1007
990
  const validMass = resolvePhysics(options.mass);
1008
991
  const springOptions = {
1009
992
  ...options,
1010
- stiffness: validStiffness ?? springDefaults.stiffness,
1011
- damping: validDamping ?? springDefaults.damping,
1012
- mass: validMass ?? springDefaults.mass,
993
+ stiffness: validStiffness ?? defaultStiffness,
994
+ damping: validDamping ?? defaultDamping,
995
+ mass: validMass ?? defaultMass,
1013
996
  isResolvedFromDuration: false,
1014
997
  // stiffness/damping/mass overrides duration/bounce
1015
998
  isTimeDefined: (validStiffness ?? validDamping ?? validMass) === undefined &&
@@ -1037,13 +1020,13 @@ function getSpringOptions(options) {
1037
1020
  */
1038
1021
  if (!isValidPhysics(springOptions.stiffness) ||
1039
1022
  !isValidPhysics(springOptions.damping, true)) {
1040
- springOptions.stiffness = springDefaults.stiffness;
1041
- springOptions.damping = springDefaults.damping;
1023
+ springOptions.stiffness = defaultStiffness;
1024
+ springOptions.damping = defaultDamping;
1042
1025
  }
1043
1026
  }
1044
1027
  return springOptions;
1045
1028
  }
1046
- function springGenerator(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
1029
+ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce = defaultBounce) {
1047
1030
  const options = typeof optionsOrVisualDuration !== "object"
1048
1031
  ? {
1049
1032
  visualDuration: optionsOrVisualDuration,
@@ -1093,14 +1076,10 @@ function springGenerator(optionsOrVisualDuration = springDefaults.visualDuration
1093
1076
  const isGranularScale = Math.abs(s.delta) < 5;
1094
1077
  s.restSpeed =
1095
1078
  options.restSpeed ||
1096
- (isGranularScale
1097
- ? springDefaults.restSpeed.granular
1098
- : springDefaults.restSpeed.default);
1079
+ (isGranularScale ? restSpeedGranular : restSpeedDefault);
1099
1080
  s.restDelta =
1100
1081
  options.restDelta ||
1101
- (isGranularScale
1102
- ? springDefaults.restDelta.granular
1103
- : springDefaults.restDelta.default);
1082
+ (isGranularScale ? restDeltaGranular : restDeltaDefault);
1104
1083
  };
1105
1084
  setRestThresholds();
1106
1085
  let resolveSpring;
@@ -1169,11 +1148,16 @@ function springGenerator(optionsOrVisualDuration = springDefaults.visualDuration
1169
1148
  * dampedAngularFreq * t passes 300, both terms decay at the damping
1170
1149
  * rate. Heavily overdamped drag springs (dragElastic: 0,
1171
1150
  * dragTransition) rely on this to settle almost at once rather than
1172
- * creep at stiffness / damping. Negative bounce needs the exact
1173
- * curve, so time-defined springs are exempt.
1174
- */
1175
- const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;
1176
- const decayAt = (rate, t) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);
1151
+ * creep at stiffness / damping. It only applies when reached within
1152
+ * 300ms (a dampedAngularFreq of 1 rad/ms), so it reads as a stiff
1153
+ * spring snapping into place: any later and it cuts off a slow spring
1154
+ * that's visibly still moving (#1207). Negative bounce needs the
1155
+ * exact curve, so time-defined springs are exempt.
1156
+ */
1157
+ const limit = dampedAngularFreq < 1 || isTimeDefined
1158
+ ? Infinity
1159
+ : 300 / dampedAngularFreq;
1160
+ const decayAt = (rate, t) => Math.exp(t > limit ? (decay - rate) * limit - decay * t : -rate * t);
1177
1161
  const c = { S: 0, F: 0 };
1178
1162
  update = () => {
1179
1163
  const P = (s.velocity + decay * s.delta) / dampedAngularFreq;
@@ -1254,7 +1238,7 @@ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, b
1254
1238
  };
1255
1239
  let amplitude = power * velocity;
1256
1240
  const ideal = origin + amplitude;
1257
- const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
1241
+ const target = modifyTarget ? modifyTarget(ideal) : ideal;
1258
1242
  /**
1259
1243
  * If the target has changed we need to re-calculate the amplitude, otherwise
1260
1244
  * the animation will start from the wrong position.
@@ -1265,7 +1249,8 @@ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, b
1265
1249
  const applyFriction = (t) => {
1266
1250
  const delta = calcDelta(t);
1267
1251
  state.done = Math.abs(delta) <= restDelta;
1268
- state.value = state.done ? target : target + delta;
1252
+ // target + delta can be off from origin by a float error at t = 0
1253
+ state.value = state.done ? target : t ? target + delta : origin;
1269
1254
  };
1270
1255
  /**
1271
1256
  * Ideally this would resolve for t in a stateless way, we could
@@ -1359,7 +1344,8 @@ function createMixers(output, ease, customMixer) {
1359
1344
  */
1360
1345
  function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
1361
1346
  const inputLength = input.length;
1362
- motionUtils.invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length");
1347
+ process.env.NODE_ENV !== "production" &&
1348
+ motionUtils.invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length");
1363
1349
  /**
1364
1350
  * If we're only provided a single input, we can just make a function
1365
1351
  * that returns the output.
@@ -1712,17 +1698,12 @@ class JSAnimation extends WithPromise {
1712
1698
  this.generator = generator;
1713
1699
  }
1714
1700
  updateTime(timestamp) {
1715
- const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;
1716
- // Update currentTime
1717
- if (this.holdTime !== null) {
1718
- this.currentTime = this.holdTime;
1719
- }
1720
- else {
1721
- // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1722
- // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1723
- // example.
1724
- this.currentTime = animationTime;
1725
- }
1701
+ // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1702
+ // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1703
+ // example.
1704
+ this.currentTime =
1705
+ this.holdTime ??
1706
+ Math.round(timestamp - this.startTime) * this.playbackSpeed;
1726
1707
  }
1727
1708
  tick(timestamp, sample = false) {
1728
1709
  const { generator, totalDuration, calculatedDuration } = this;
@@ -1763,10 +1744,17 @@ class JSAnimation extends WithPromise {
1763
1744
  }
1764
1745
  const state = this.generate(this.currentTime, isInDelayPhase);
1765
1746
  let { done } = state;
1766
- if (!isInDelayPhase && calculatedDuration !== null) {
1747
+ /**
1748
+ * A generator that takes longer than maxGeneratorDuration to finish
1749
+ * has an Infinity duration, so played forwards it finishes when it
1750
+ * says it's done.
1751
+ */
1752
+ if (!isInDelayPhase) {
1767
1753
  done =
1768
1754
  this.playbackSpeed >= 0
1769
- ? this.currentTime >= totalDuration
1755
+ ? calculatedDuration < Infinity
1756
+ ? this.currentTime >= totalDuration
1757
+ : done
1770
1758
  : this.currentTime <= 0;
1771
1759
  }
1772
1760
  const isAnimationFinished = this.holdTime === null &&
@@ -1872,20 +1860,11 @@ class JSAnimation extends WithPromise {
1872
1860
  }
1873
1861
  return state;
1874
1862
  }
1875
- /**
1876
- * Allows the returned animation to be awaited or promise-chained. Currently
1877
- * resolves when the animation finishes at all but in a future update could/should
1878
- * reject if its cancels.
1879
- */
1880
- then(resolve, reject) {
1881
- return this.finished.then(resolve, reject);
1882
- }
1883
1863
  get duration() {
1884
1864
  return motionUtils.millisecondsToSeconds(this.calculatedDuration);
1885
1865
  }
1886
1866
  get iterationDuration() {
1887
- const { delay = 0 } = this.options || {};
1888
- return this.duration + motionUtils.millisecondsToSeconds(delay);
1867
+ return this.duration + motionUtils.millisecondsToSeconds(this.options.delay ?? 0);
1889
1868
  }
1890
1869
  get time() {
1891
1870
  return motionUtils.millisecondsToSeconds(this.currentTime);
@@ -1989,14 +1968,9 @@ class JSAnimation extends WithPromise {
1989
1968
  }
1990
1969
  teardown() {
1991
1970
  this.state = "idle";
1992
- this.stopDriver();
1993
- this.startTime = this.holdTime = null;
1994
- }
1995
- stopDriver() {
1996
- if (!this.driver)
1997
- return;
1998
- this.driver.stop();
1971
+ this.driver?.stop();
1999
1972
  this.driver = undefined;
1973
+ this.startTime = this.holdTime = null;
2000
1974
  }
2001
1975
  sample(sampleTime) {
2002
1976
  this.startTime = 0;
@@ -2253,23 +2227,15 @@ function parseValueFromTransform(transform, name) {
2253
2227
  if (!transform || transform === "none") {
2254
2228
  return defaultTransformValue(name);
2255
2229
  }
2256
- const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);
2257
- let parsers;
2258
- let match;
2259
- if (matrix3dMatch) {
2260
- parsers = matrix3dParsers;
2261
- match = matrix3dMatch;
2262
- }
2263
- else {
2264
- const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u);
2265
- parsers = matrix2dParsers;
2266
- match = matrix2dMatch;
2267
- }
2230
+ const match = transform.match(/^matrix(3d)?\(([-\d.e\s,]+)\)$/u);
2268
2231
  if (!match) {
2269
2232
  return defaultTransformValue(name);
2270
2233
  }
2271
- const valueParser = parsers[name];
2272
- const values = match[1].split(",").map(convertTransformToNumber);
2234
+ const valueParser = (match[1] ? matrix3dParsers : matrix2dParsers)[name];
2235
+ /**
2236
+ * parseFloat skips leading whitespace and stops at trailing whitespace.
2237
+ */
2238
+ const values = match[2].split(",").map((v) => parseFloat(v));
2273
2239
  return typeof valueParser === "function"
2274
2240
  ? valueParser(values)
2275
2241
  : values[valueParser];
@@ -2278,9 +2244,6 @@ const readTransformValue = (instance, name) => {
2278
2244
  const { transform = "none" } = getComputedStyle(instance);
2279
2245
  return parseValueFromTransform(transform, name);
2280
2246
  };
2281
- function convertTransformToNumber(value) {
2282
- return parseFloat(value.trim());
2283
- }
2284
2247
 
2285
2248
  /**
2286
2249
  * Generate a list of every possible transform key.
@@ -2683,7 +2646,9 @@ class NativeAnimation extends WithPromise {
2683
2646
  this.isPseudoElement = Boolean(pseudoElement);
2684
2647
  this.allowFlatten = allowFlatten;
2685
2648
  this.options = options;
2686
- motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2649
+ typeof process !== "undefined" &&
2650
+ process.env.NODE_ENV !== "production" &&
2651
+ motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2687
2652
  const transition = applyGeneratorOptions(options);
2688
2653
  this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
2689
2654
  if (transition.autoplay === false) {
@@ -2693,9 +2658,7 @@ class NativeAnimation extends WithPromise {
2693
2658
  this.finishedTime = this.time;
2694
2659
  if (!pseudoElement) {
2695
2660
  const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
2696
- if (this.updateMotionValue) {
2697
- this.updateMotionValue(keyframe);
2698
- }
2661
+ this.updateMotionValue?.(keyframe);
2699
2662
  /**
2700
2663
  * If we can, we want to commit the final style as set by the user,
2701
2664
  * rather than the computed keyframe value supplied by the animation.
@@ -3016,6 +2979,7 @@ function canAnimate(keyframes, name, type, velocity) {
3016
2979
  if (!isOriginAnimatable || !isTargetAnimatable) {
3017
2980
  // Only build the message when we're going to warn
3018
2981
  isOriginAnimatable !== isTargetAnimatable &&
2982
+ process.env.NODE_ENV !== "production" &&
3019
2983
  motionUtils.warning(false, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable");
3020
2984
  return false;
3021
2985
  }
@@ -3030,13 +2994,16 @@ function makeAnimationInstant(options) {
3030
2994
 
3031
2995
  /**
3032
2996
  * A list of values that can be hardware-accelerated.
2997
+ *
2998
+ * Colors aren't included: WAAPI mixes them in sRGB, but JS animations
2999
+ * (and the sampler that estimates a WAAPI value on interrupt) mix them
3000
+ * in linear color space, so interrupting one would visibly jump.
3033
3001
  */
3034
3002
  const acceleratedValues = new Set([
3035
3003
  "opacity",
3036
3004
  "clipPath",
3037
3005
  "filter",
3038
3006
  "transform",
3039
- "backgroundColor",
3040
3007
  ]);
3041
3008
 
3042
3009
  const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;
@@ -3128,6 +3095,20 @@ const translateAlias = {
3128
3095
  transformPerspective: "perspective",
3129
3096
  };
3130
3097
  const numTransforms = transformPropOrder.length;
3098
+ /**
3099
+ * Cache of `translateX(`-style openers so each transform function is a few
3100
+ * string concatenations rather than a template.
3101
+ */
3102
+ const openers = {};
3103
+ /**
3104
+ * A transform function, e.g. `translateX(10px)` for `x: 10`.
3105
+ */
3106
+ const transformFunction = (key, value, valueAsType = getValueAsType(value, transformValueTypes[key])) => (openers[key] || (openers[key] = (translateAlias[key] || key) + "(")) + valueAsType + ")";
3107
+ /**
3108
+ * Whether a transform value is at its default, so can be left out.
3109
+ */
3110
+ const isDefaultTransform = (key, value) => (typeof value === "number" ? value : parseFloat(value)) ===
3111
+ (key.startsWith("scale") ? 1 : 0);
3131
3112
  /**
3132
3113
  * Build a CSS transform style from individual x/y/scale etc properties.
3133
3114
  *
@@ -3137,7 +3118,6 @@ const numTransforms = transformPropOrder.length;
3137
3118
  function buildTransform$1(latestValues, transform, transformTemplate) {
3138
3119
  // The transform string we're going to build into.
3139
3120
  let transformString = "";
3140
- let transformIsDefault = true;
3141
3121
  /**
3142
3122
  * Loop over all possible transforms in order, adding the ones that
3143
3123
  * are present to the transform string.
@@ -3147,24 +3127,11 @@ function buildTransform$1(latestValues, transform, transformTemplate) {
3147
3127
  const value = latestValues[key];
3148
3128
  if (value === undefined)
3149
3129
  continue;
3150
- let valueIsDefault = true;
3151
- if (typeof value === "number") {
3152
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3153
- }
3154
- else {
3155
- const parsed = parseFloat(value);
3156
- valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
3157
- }
3158
- if (!valueIsDefault || transformTemplate) {
3159
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
3160
- if (!valueIsDefault) {
3161
- transformIsDefault = false;
3162
- const transformName = translateAlias[key] || key;
3163
- transformString += `${transformName}(${valueAsType}) `;
3164
- }
3165
- if (transformTemplate) {
3166
- transform[key] = valueAsType;
3167
- }
3130
+ const valueAsType = transformTemplate &&
3131
+ (transform[key] = getValueAsType(value, numberValueTypes[key]));
3132
+ if (!isDefaultTransform(key, value)) {
3133
+ transformString +=
3134
+ transformFunction(key, value, valueAsType || undefined) + " ";
3168
3135
  }
3169
3136
  }
3170
3137
  // `pathRotation` composes onto `rotate` as a separate additive term so
@@ -3172,19 +3139,14 @@ function buildTransform$1(latestValues, transform, transformTemplate) {
3172
3139
  // `transformPropOrder`.
3173
3140
  const pathRotation = latestValues.pathRotation;
3174
3141
  if (pathRotation) {
3175
- transformIsDefault = false;
3176
- transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
3142
+ transformString += transformFunction("rotate", pathRotation);
3177
3143
  }
3178
3144
  transformString = transformString.trim();
3179
3145
  // If we have a custom `transform` template, pass our transform values and
3180
3146
  // generated transformString to that before returning
3181
- if (transformTemplate) {
3182
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
3183
- }
3184
- else if (transformIsDefault) {
3185
- transformString = "none";
3186
- }
3187
- return transformString;
3147
+ return transformTemplate
3148
+ ? transformTemplate(transform, transformString)
3149
+ : transformString || "none";
3188
3150
  }
3189
3151
 
3190
3152
  const transformGroups = new WeakMap();
@@ -3526,27 +3488,30 @@ function createGroup(owner) {
3526
3488
  return values;
3527
3489
  };
3528
3490
  /**
3529
- * Build the transform at a timestamp. Unlike buildTransform, every key
3530
- * is written, even at its default, so each keyframe has the same list
3531
- * of functions and the browser interpolates them one by one.
3491
+ * Build a transform from values in transformPropOrder. For a keyframe,
3492
+ * every key is written, even at its default, so each keyframe has the
3493
+ * same list of functions and the browser interpolates them one by one.
3494
+ * As an inline style, defaults are left out, as buildTransform does.
3532
3495
  */
3533
- const compose = (timestamp, settled) => {
3496
+ const toTransform = (values, isStyle) => {
3534
3497
  let transform = "";
3535
- const values = valuesAt(timestamp, settled);
3536
3498
  for (const key in values) {
3537
- transform +=
3538
- (translateAlias[key] || key) +
3539
- "(" +
3540
- getValueAsType(values[key], numberValueTypes[key]) +
3541
- ") ";
3499
+ const value = values[key];
3500
+ if (!isStyle || !isDefaultTransform(key, value)) {
3501
+ transform += transformFunction(key, value) + " ";
3502
+ }
3542
3503
  }
3543
- return transform || "none";
3504
+ return (isStyle ? transform.trim() : transform) || "none";
3544
3505
  };
3506
+ /**
3507
+ * Build the transform at a timestamp.
3508
+ */
3509
+ const compose = (timestamp, settled) => toTransform(valuesAt(timestamp, settled));
3545
3510
  /**
3546
3511
  * Write the transform as an inline style, as the renderer would.
3547
3512
  */
3548
3513
  const commit = (values = valuesAt()) => {
3549
- element.style.transform = buildTransform$1(values, {});
3514
+ element.style.transform = toTransform(values, true);
3550
3515
  };
3551
3516
  /**
3552
3517
  * Cancel the WAAPI animations, by default first committing the
@@ -3557,6 +3522,13 @@ function createGroup(owner) {
3557
3522
  segments.forEach(({ animation }) => animation.cancel());
3558
3523
  segments = [];
3559
3524
  };
3525
+ /**
3526
+ * A WAAPI animation that add() starts by setting its startTime. Playing
3527
+ * it first, as element.animate() does, would leave WebKit holding that
3528
+ * play's ready time once startTime ends the play, and it uses that for
3529
+ * the next updatePlaybackRate(), so the animation would jump.
3530
+ */
3531
+ const create = (keyframes, options) => new Animation(new KeyframeEffect(element, keyframes, options));
3560
3532
  const add = (animation, offset, end = Infinity) => {
3561
3533
  const segment = { animation, offset, end };
3562
3534
  animation.startTime = time.now() + offset;
@@ -3749,7 +3721,7 @@ function createGroup(owner) {
3749
3721
  commit(valuesAt(from, settled));
3750
3722
  keyframes = null;
3751
3723
  }
3752
- return element.animate(keyframes, {
3724
+ return create(keyframes, {
3753
3725
  ...options,
3754
3726
  duration: to - from,
3755
3727
  easing: easing || "linear",
@@ -3839,9 +3811,7 @@ function createGroup(owner) {
3839
3811
  * empty animations that end with them.
3840
3812
  */
3841
3813
  ends.forEach((trackEnd) => trackEnd < end - 1 &&
3842
- add(element.animate(null, {
3843
- duration: trackEnd - now,
3844
- }), 0, trackEnd - now));
3814
+ add(create(null, { duration: trackEnd - now }), 0, trackEnd - now));
3845
3815
  }
3846
3816
  if (cycle) {
3847
3817
  /**
@@ -3915,12 +3885,29 @@ function createGroup(owner) {
3915
3885
  if (isDone)
3916
3886
  continue;
3917
3887
  const local = elapsed - offset;
3918
- if (rate) {
3888
+ if (rate &&
3889
+ animation.updatePlaybackRate &&
3890
+ animation.playState === "running" &&
3891
+ Math.abs(Number(animation.currentTime) - local) < 20) {
3892
+ /**
3893
+ * Only the speed changed. Setting playbackRate and
3894
+ * startTime restarts a running compositor animation, which
3895
+ * can render the underlying value for a frame.
3896
+ */
3897
+ animation.playbackRate !== rate &&
3898
+ animation.updatePlaybackRate(rate);
3899
+ }
3900
+ else if (rate) {
3919
3901
  animation.playbackRate = rate;
3920
3902
  animation.startTime = now - local / rate;
3921
3903
  }
3922
3904
  else {
3923
- animation.pause();
3905
+ /**
3906
+ * Hold it without pause(), whose pending pause setting
3907
+ * currentTime would end at once, leaving WebKit holding its
3908
+ * ready time (see create()).
3909
+ */
3910
+ animation.startTime = null;
3924
3911
  animation.currentTime = local;
3925
3912
  }
3926
3913
  }
@@ -4111,9 +4098,8 @@ class AsyncMotionValueAnimation extends WithPromise {
4111
4098
  * If we can't animate this value with the resolved keyframes
4112
4099
  * then we should complete it immediately.
4113
4100
  */
4114
- let canAnimateValue = true;
4115
- if (!canAnimate(keyframes, name, type, velocity)) {
4116
- canAnimateValue = false;
4101
+ const canAnimateValue = canAnimate(keyframes, name, type, velocity);
4102
+ if (!canAnimateValue) {
4117
4103
  if (motionUtils.MotionGlobalConfig.instantAnimations || !delay) {
4118
4104
  onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe));
4119
4105
  }
@@ -4257,9 +4243,7 @@ class AsyncMotionValueAnimation extends WithPromise {
4257
4243
  this.animation.complete();
4258
4244
  }
4259
4245
  cancel() {
4260
- if (this._animation) {
4261
- this.animation.cancel();
4262
- }
4246
+ this._animation?.cancel();
4263
4247
  this.keyframeResolver?.cancel();
4264
4248
  }
4265
4249
  }
@@ -4442,7 +4426,7 @@ class MotionValue {
4442
4426
  this.setCurrent(v);
4443
4427
  // Update update subscribers
4444
4428
  if (this.current !== this.prev) {
4445
- this.notifyChange();
4429
+ this.dirty();
4446
4430
  if (this.dependents) {
4447
4431
  for (const dependent of this.dependents) {
4448
4432
  dependent.dirty();
@@ -4580,12 +4564,9 @@ class MotionValue {
4580
4564
  * @public
4581
4565
  */
4582
4566
  set(v) {
4583
- if (!this.passiveEffect) {
4584
- this.updateAndNotify(v);
4585
- }
4586
- else {
4587
- this.passiveEffect(v, this.updateAndNotify);
4588
- }
4567
+ this.passiveEffect
4568
+ ? this.passiveEffect(v, this.updateAndNotify)
4569
+ : this.updateAndNotify(v);
4589
4570
  }
4590
4571
  setWithVelocity(prev, current, delta) {
4591
4572
  this.set(current);
@@ -4602,13 +4583,9 @@ class MotionValue {
4602
4583
  this.prev = v;
4603
4584
  this.prevUpdatedAt = this.prevFrameValue = undefined;
4604
4585
  endAnimation && this.stop();
4605
- if (this.stopPassiveEffect)
4606
- this.stopPassiveEffect();
4586
+ this.stopPassiveEffect?.();
4607
4587
  }
4608
4588
  dirty() {
4609
- this.notifyChange();
4610
- }
4611
- notifyChange() {
4612
4589
  const { current, changeSubscriber } = this;
4613
4590
  /**
4614
4591
  * One or the other exists. Subscribing during the direct
@@ -4623,15 +4600,10 @@ class MotionValue {
4623
4600
  }
4624
4601
  }
4625
4602
  addDependent(dependent) {
4626
- if (!this.dependents) {
4627
- this.dependents = new Set();
4628
- }
4629
- this.dependents.add(dependent);
4603
+ (this.dependents || (this.dependents = new Set())).add(dependent);
4630
4604
  }
4631
4605
  removeDependent(dependent) {
4632
- if (this.dependents) {
4633
- this.dependents.delete(dependent);
4634
- }
4606
+ this.dependents?.delete(dependent);
4635
4607
  }
4636
4608
  /**
4637
4609
  * Returns the latest state of `MotionValue`
@@ -4641,9 +4613,7 @@ class MotionValue {
4641
4613
  * @public
4642
4614
  */
4643
4615
  get() {
4644
- if (collectMotionValues.current) {
4645
- collectMotionValues.current.push(this);
4646
- }
4616
+ collectMotionValues.current?.push(this);
4647
4617
  /**
4648
4618
  * A value animating on the compositor isn't updated every frame,
4649
4619
  * so read it from its animation.
@@ -4709,7 +4679,7 @@ class MotionValue {
4709
4679
  isComplete = true;
4710
4680
  this.events.animationComplete?.notify();
4711
4681
  if (this.animation === animation)
4712
- this.clearAnimation();
4682
+ this.animation = undefined;
4713
4683
  resolve();
4714
4684
  });
4715
4685
  if (!isComplete)
@@ -4725,11 +4695,10 @@ class MotionValue {
4725
4695
  stop() {
4726
4696
  if (this.animation) {
4727
4697
  this.animation.stop();
4728
- if (this.events.animationCancel) {
4729
- this.events.animationCancel.notify();
4730
- }
4698
+ this.events.animationCancel?.notify();
4731
4699
  }
4732
- this.clearAnimation();
4700
+ // Assign rather than delete to keep the object's shape stable
4701
+ this.animation = undefined;
4733
4702
  }
4734
4703
  /**
4735
4704
  * Returns `true` if this value is currently animating.
@@ -4739,10 +4708,6 @@ class MotionValue {
4739
4708
  isAnimating() {
4740
4709
  return !!this.animation;
4741
4710
  }
4742
- clearAnimation() {
4743
- // Assign rather than delete to keep the object's shape stable
4744
- this.animation = undefined;
4745
- }
4746
4711
  /**
4747
4712
  * Destroy and clean up subscribers to this `MotionValue`.
4748
4713
  *
@@ -4757,9 +4722,7 @@ class MotionValue {
4757
4722
  this.events.destroy?.notify();
4758
4723
  this.clearListeners();
4759
4724
  this.stop();
4760
- if (this.stopPassiveEffect) {
4761
- this.stopPassiveEffect();
4762
- }
4725
+ this.stopPassiveEffect?.();
4763
4726
  }
4764
4727
  }
4765
4728
  function motionValue(init, options) {
@@ -4837,6 +4800,7 @@ const orchestrationKeys = new Set([
4837
4800
  "repeatDelay",
4838
4801
  "from",
4839
4802
  "elapsed",
4803
+ "out",
4840
4804
  ]);
4841
4805
  /**
4842
4806
  * Decide whether a transition is defined on a given Transition.
@@ -5148,7 +5112,8 @@ function parseCSSVariable(current) {
5148
5112
  }
5149
5113
  const maxDepth = 4;
5150
5114
  function getVariableValue(current, element, depth = 1) {
5151
- motionUtils.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth");
5115
+ process.env.NODE_ENV !== "production" &&
5116
+ motionUtils.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth");
5152
5117
  const [token, fallback] = parseCSSVariable(current);
5153
5118
  // No CSS variable detected
5154
5119
  if (!token)
@@ -5307,7 +5272,7 @@ function animateTarget(visualElement, targetAndTransition, { delay = 0, transiti
5307
5272
  }
5308
5273
  const valueTransition = {
5309
5274
  delay,
5310
- ...getValueTransition(transition || {}, key),
5275
+ ...getValueTransition(animationTypeState?.out[key] || transition || {}, key),
5311
5276
  };
5312
5277
  if (skipAnimations)
5313
5278
  valueTransition.skipAnimations = true;
@@ -5477,8 +5442,9 @@ function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, n
5477
5442
  }
5478
5443
 
5479
5444
  class DOMKeyframesResolver extends KeyframeResolver {
5480
- constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
5481
- super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
5445
+ constructor() {
5446
+ super(...arguments);
5447
+ this.isAsync = true;
5482
5448
  }
5483
5449
  /**
5484
5450
  * Keyframes that don't need reading from the DOM, or measuring,
@@ -5506,7 +5472,7 @@ class DOMKeyframesResolver extends KeyframeResolver {
5506
5472
  }
5507
5473
  readKeyframes() {
5508
5474
  const { unresolvedKeyframes, element, name } = this;
5509
- if (!element || !element.current)
5475
+ if (!element?.current)
5510
5476
  return;
5511
5477
  super.readKeyframes();
5512
5478
  /**
@@ -5601,11 +5567,10 @@ class DOMKeyframesResolver extends KeyframeResolver {
5601
5567
  }
5602
5568
  measureInitialState() {
5603
5569
  const { element, unresolvedKeyframes, name } = this;
5604
- if (!element || !element.current)
5570
+ if (!element?.current)
5605
5571
  return;
5606
- if (name === "height") {
5572
+ if (name === "height")
5607
5573
  this.suspendedScrollY = window.pageYOffset;
5608
- }
5609
5574
  this.measuredOrigin = this.measure();
5610
5575
  unresolvedKeyframes[0] = this.measuredOrigin;
5611
5576
  // Set final key frame to measure after next render
@@ -5616,7 +5581,7 @@ class DOMKeyframesResolver extends KeyframeResolver {
5616
5581
  }
5617
5582
  measureEndState() {
5618
5583
  const { element, unresolvedKeyframes } = this;
5619
- if (!element || !element.current)
5584
+ if (!element?.current)
5620
5585
  return;
5621
5586
  this.motionValue?.jump(this.measuredOrigin, false);
5622
5587
  const finalKeyframeIndex = unresolvedKeyframes.length - 1;
@@ -5625,14 +5590,6 @@ class DOMKeyframesResolver extends KeyframeResolver {
5625
5590
  if (finalKeyframe !== null && this.finalKeyframe === undefined) {
5626
5591
  this.finalKeyframe = finalKeyframe;
5627
5592
  }
5628
- // If we removed transform values, reapply them before the next render
5629
- if (this.removedTransforms?.length) {
5630
- this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
5631
- element
5632
- .getValue(unsetTransformName)
5633
- .set(unsetTransformValue);
5634
- });
5635
- }
5636
5593
  this.resolveNoneKeyframes();
5637
5594
  }
5638
5595
  }
@@ -5737,7 +5694,9 @@ const supportsPartialKeyframes = /*@__PURE__*/ motionUtils.memo(() => {
5737
5694
  */
5738
5695
  const effects = [];
5739
5696
  function addEffect(effect) {
5740
- motionUtils.invariant(typeof effect.test === "function" && typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5697
+ process.env.NODE_ENV !== "production" &&
5698
+ motionUtils.invariant(typeof effect.test === "function" &&
5699
+ typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5741
5700
  removeEffect(effect);
5742
5701
  effects.unshift(effect);
5743
5702
  }
@@ -5824,7 +5783,8 @@ function animateEffectSubject(effect, subject, keyframes, transition, element) {
5824
5783
  initial =
5825
5784
  firstKeyframe(target) ??
5826
5785
  effect.read(subject, key, target);
5827
- motionUtils.invariant(initial !== undefined, `"${key}" can't be read from the animated subject. Provide [from, to] keyframes.`, "effect-unreadable-value");
5786
+ process.env.NODE_ENV !== "production" &&
5787
+ motionUtils.invariant(initial !== undefined, `"${key}" can't be read from the animated subject. Provide [from, to] keyframes.`, "effect-unreadable-value");
5828
5788
  }
5829
5789
  value = motionValue(initial, { owner: element });
5830
5790
  effect(subject, { [key]: value });
@@ -6064,11 +6024,6 @@ function createEffect(addValue, { step, ...options } = {}) {
6064
6024
  });
6065
6025
  }
6066
6026
 
6067
- /**
6068
- * Cache of `translateX(`-style openers so each render is a few string
6069
- * concatenations rather than a template per transform.
6070
- */
6071
- const openers = {};
6072
6027
  function buildTransform(state) {
6073
6028
  let transform = "";
6074
6029
  const { transformKeys: keys = [], transformValues: values = {} } = state;
@@ -6081,14 +6036,8 @@ function buildTransform(state) {
6081
6036
  const value = values[key].getCurrent();
6082
6037
  if (value === undefined)
6083
6038
  continue;
6084
- const parsed = typeof value === "number" ? value : parseFloat(value);
6085
- if (parsed !== (key.startsWith("scale") ? 1 : 0)) {
6086
- transform +=
6087
- (transform && " ") +
6088
- (openers[key] ||
6089
- (openers[key] = (translateAlias[key] || key) + "(")) +
6090
- getValueAsType(value, transformValueTypes[key]) +
6091
- ")";
6039
+ if (!isDefaultTransform(key, value)) {
6040
+ transform += (transform && " ") + transformFunction(key, value);
6092
6041
  }
6093
6042
  }
6094
6043
  // See build-transform.ts: additive `rotate()` so user `rotate` isn't
@@ -6096,10 +6045,7 @@ function buildTransform(state) {
6096
6045
  const pathRotation = state.get("pathRotation")?.get();
6097
6046
  if (pathRotation) {
6098
6047
  transform +=
6099
- (transform && " ") +
6100
- "rotate(" +
6101
- getValueAsType(pathRotation, transformValueTypes.pathRotation) +
6102
- ")";
6048
+ (transform && " ") + transformFunction("rotate", pathRotation);
6103
6049
  }
6104
6050
  return transform || "none";
6105
6051
  }
@@ -6502,10 +6448,24 @@ function hasScale({ scale, scaleX, scaleY }) {
6502
6448
  !isIdentityScale(scaleX) ||
6503
6449
  !isIdentityScale(scaleY));
6504
6450
  }
6451
+ /**
6452
+ * Rotations and skews, which projection can't correct for.
6453
+ */
6454
+ const angleTransforms = [
6455
+ "rotate",
6456
+ "rotateX",
6457
+ "rotateY",
6458
+ "rotateZ",
6459
+ "skewX",
6460
+ "skewY",
6461
+ ];
6505
6462
  function hasTransform(values) {
6506
6463
  return (hasScale(values) ||
6507
6464
  has2DTranslate(values) ||
6508
- values.z ||
6465
+ hasDistortingTransform(values));
6466
+ }
6467
+ function hasDistortingTransform(values) {
6468
+ return (values.z ||
6509
6469
  values.rotate ||
6510
6470
  values.rotateX ||
6511
6471
  values.rotateY ||
@@ -6558,6 +6518,11 @@ const TREE_SCALE_SNAP_MAX = 1.0000000000001;
6558
6518
  * in a tree upon our box before then calculating how to project it into our desired viewport-relative box
6559
6519
  *
6560
6520
  * This is the final nested loop within updateLayoutDelta for future refactoring
6521
+ *
6522
+ * isSharedTransition is true for a shared layout animation in page space, which
6523
+ * also applies ancestor scroll and transforms. Or it's the layoutRoot a shared
6524
+ * animation is relative to, so only transforms of ancestors not shared with it
6525
+ * (or above it) are applied.
6561
6526
  */
6562
6527
  function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
6563
6528
  const treeLength = treePath.length;
@@ -6574,13 +6539,10 @@ function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
6574
6539
  * TODO: Prefer to remove this, but currently we have motion components with
6575
6540
  * display: contents in Framer.
6576
6541
  */
6577
- const { visualElement } = node.options;
6578
- if (visualElement &&
6579
- visualElement.props.style &&
6580
- visualElement.props.style.display === "contents") {
6542
+ if (node.options.visualElement?.props.style?.display === "contents") {
6581
6543
  continue;
6582
6544
  }
6583
- if (isSharedTransition &&
6545
+ if (isSharedTransition === true &&
6584
6546
  node.options.layoutScroll &&
6585
6547
  node.scroll &&
6586
6548
  node !== node.root) {
@@ -6594,7 +6556,9 @@ function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
6594
6556
  // Apply each ancestor's calculated delta into this component's recorded layout box
6595
6557
  applyBoxDelta(box, delta);
6596
6558
  }
6597
- if (isSharedTransition && hasTransform(node.latestValues)) {
6559
+ if (isSharedTransition &&
6560
+ (isSharedTransition.path?.[i] || isSharedTransition) !== node &&
6561
+ hasTransform(node.latestValues)) {
6598
6562
  transformBox(box, node.latestValues, node.layout?.layoutBox);
6599
6563
  }
6600
6564
  }
@@ -6868,15 +6832,6 @@ function resolveMotionValue(value) {
6868
6832
  const asNumber = (v) => typeof v === "number" ? v : parseFloat(v);
6869
6833
 
6870
6834
  const numBorders = cornerRadiusProps.length;
6871
- const mixedTransforms = [
6872
- "rotate",
6873
- "rotateX",
6874
- "rotateY",
6875
- "rotateZ",
6876
- "skewX",
6877
- "skewY",
6878
- ];
6879
- const numMixedTransforms = mixedTransforms.length;
6880
6835
  const isPx = (value) => typeof value === "number" || px.test(value);
6881
6836
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
6882
6837
  if (shouldCrossfadeOpacity) {
@@ -6914,8 +6869,8 @@ function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnl
6914
6869
  * Mix rotation and skew. These can't be projected, so mix them every
6915
6870
  * frame rather than leaving them frozen at the animation-start snapshot.
6916
6871
  */
6917
- for (let i = 0; i < numMixedTransforms; i++) {
6918
- const key = mixedTransforms[i];
6872
+ for (let i = 0; i < angleTransforms.length; i++) {
6873
+ const key = angleTransforms[i];
6919
6874
  if (follow[key] || lead[key]) {
6920
6875
  target[key] = mixNumber$1(follow[key] || 0, lead[key] || 0, progress);
6921
6876
  }
@@ -6998,8 +6953,8 @@ function calcAxisDelta(delta, source, target, origin = 0.5) {
6998
6953
  }
6999
6954
  }
7000
6955
  function calcBoxDelta(delta, source, target, origin) {
7001
- calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);
7002
- calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);
6956
+ calcAxisDelta(delta.x, source.x, target.x, origin?.originX);
6957
+ calcAxisDelta(delta.y, source.y, target.y, origin?.originY);
7003
6958
  }
7004
6959
  function calcRelativeAxis(target, relative, parent, anchor = 0) {
7005
6960
  const anchorPoint = anchor
@@ -7069,8 +7024,8 @@ const yKeys = ["y", "scaleY", "originY"];
7069
7024
  * and acts as a bridge between motion values and removeAxisDelta
7070
7025
  */
7071
7026
  function removeBoxTransforms(box, transforms, originBox, sourceBox) {
7072
- removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);
7073
- removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);
7027
+ removeAxisTransforms(box.x, transforms, xKeys, originBox?.x, sourceBox?.x);
7028
+ removeAxisTransforms(box.y, transforms, yKeys, originBox?.y, sourceBox?.y);
7074
7029
  }
7075
7030
 
7076
7031
  const createAxisDelta = () => ({
@@ -7300,24 +7255,18 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
7300
7255
  transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7301
7256
  }
7302
7257
  if (latestTransform) {
7303
- const { transformPerspective, rotate, pathRotation, rotateX, rotateY, rotateZ, skewX, skewY, } = latestTransform;
7258
+ const { transformPerspective } = latestTransform;
7304
7259
  if (transformPerspective)
7305
7260
  transform = `perspective(${transformPerspective}px) ${transform}`;
7306
- if (rotate)
7307
- transform += `rotate(${rotate}deg) `;
7308
- // Additive `rotate()` so user `rotate` isn't clobbered.
7309
- if (pathRotation)
7310
- transform += `rotate(${pathRotation}deg) `;
7311
- if (rotateX)
7312
- transform += `rotateX(${rotateX}deg) `;
7313
- if (rotateY)
7314
- transform += `rotateY(${rotateY}deg) `;
7315
- if (rotateZ)
7316
- transform += `rotateZ(${rotateZ}deg) `;
7317
- if (skewX)
7318
- transform += `skewX(${skewX}deg) `;
7319
- if (skewY)
7320
- transform += `skewY(${skewY}deg) `;
7261
+ for (let i = 0; i < angleTransforms.length; i++) {
7262
+ const key = angleTransforms[i];
7263
+ const value = latestTransform[key];
7264
+ if (value)
7265
+ transform += `${key}(${value}deg) `;
7266
+ // Additive `rotate()` so user `rotate` isn't clobbered.
7267
+ if (!i && latestTransform.pathRotation)
7268
+ transform += `rotate(${latestTransform.pathRotation}deg) `;
7269
+ }
7321
7270
  }
7322
7271
  /**
7323
7272
  * Apply scale to match the size of the element to the size we want it.
@@ -7380,7 +7329,10 @@ const metrics = {
7380
7329
  calculatedTargetDeltas: 0,
7381
7330
  calculatedProjections: 0,
7382
7331
  };
7383
- const transformAxes = ["", "X", "Y", "Z"];
7332
+ /**
7333
+ * Transforms that distort an element's layout, so must be reset before measuring.
7334
+ */
7335
+ const distortingTransforms = ["z", "skew", "skewZ"];
7384
7336
  /**
7385
7337
  * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
7386
7338
  * which has a noticeable difference in spring animations
@@ -7588,8 +7540,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7588
7540
  return this.eventHandlers.get(name).add(handler);
7589
7541
  }
7590
7542
  notifyListeners(name, ...args) {
7591
- const subscriptionManager = this.eventHandlers.get(name);
7592
- subscriptionManager && subscriptionManager.notify(...args);
7543
+ this.eventHandlers.get(name)?.notify(...args);
7593
7544
  }
7594
7545
  hasListeners(name) {
7595
7546
  return this.eventHandlers.has(name);
@@ -7607,7 +7558,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7607
7558
  visualElement.mount(instance);
7608
7559
  }
7609
7560
  this.root.nodes.add(this);
7610
- this.parent && this.parent.children.add(this);
7561
+ this.parent?.children.add(this);
7611
7562
  if (this.root.hasTreeAnimated && (layout || layoutId)) {
7612
7563
  this.isLayoutDirty = true;
7613
7564
  }
@@ -7625,7 +7576,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7625
7576
  return;
7626
7577
  innerWidth = newInnerWidth;
7627
7578
  this.root.updateBlockedByResize = true;
7628
- cancelDelay && cancelDelay();
7579
+ cancelDelay?.();
7629
7580
  cancelDelay = delay(resizeUnblockUpdate, 250);
7630
7581
  if (globalProjectionState.hasAnimatedSinceResize) {
7631
7582
  globalProjectionState.hasAnimatedSinceResize = false;
@@ -7716,9 +7667,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7716
7667
  if (!hasLayoutChanged) {
7717
7668
  finishAnimation(this);
7718
7669
  }
7719
- if (this.isLead() && this.options.onExitComplete) {
7720
- this.options.onExitComplete();
7721
- }
7670
+ this.isLead() && this.options.onExitComplete?.();
7722
7671
  }
7723
7672
  this.targetLayout = newLayout;
7724
7673
  });
@@ -7726,9 +7675,8 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7726
7675
  unmount() {
7727
7676
  this.options.layoutId && this.willUpdate();
7728
7677
  this.root.nodes.remove(this);
7729
- const stack = this.getStack();
7730
- stack && stack.remove(this);
7731
- this.parent && this.parent.children.delete(this);
7678
+ this.getStack()?.remove(this);
7679
+ this.parent?.children.delete(this);
7732
7680
  this.instance = undefined;
7733
7681
  this.eventHandlers.clear();
7734
7682
  this.hasLayoutListener = false;
@@ -7749,7 +7697,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7749
7697
  if (this.isUpdateBlocked())
7750
7698
  return;
7751
7699
  this.isUpdating = true;
7752
- this.nodes && this.nodes.forEach(resetSkewAndRotation);
7700
+ this.nodes?.forEach(resetSkewAndRotation);
7753
7701
  this.animationId++;
7754
7702
  }
7755
7703
  getTransformTemplate() {
@@ -7759,7 +7707,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7759
7707
  willUpdate(shouldNotifyListeners = true) {
7760
7708
  this.root.hasTreeAnimated = true;
7761
7709
  if (this.root.isUpdateBlocked()) {
7762
- this.options.onExitComplete && this.options.onExitComplete();
7710
+ this.options.onExitComplete?.();
7763
7711
  return;
7764
7712
  }
7765
7713
  /**
@@ -7976,24 +7924,23 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
7976
7924
  this.projectionDelta = undefined;
7977
7925
  this.notifyListeners("measure", this.layout.layoutBox);
7978
7926
  const { visualElement } = this.options;
7979
- visualElement &&
7980
- visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);
7927
+ visualElement?.notify("LayoutMeasure", this.layout.layoutBox, prevLayout?.layoutBox);
7981
7928
  }
7982
7929
  updateScroll(phase = "measure") {
7983
- let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
7984
- if (this.scroll &&
7985
- this.scroll.animationId === this.root.animationId &&
7986
- this.scroll.phase === phase) {
7987
- needsMeasurement = false;
7988
- }
7989
- if (needsMeasurement && this.instance) {
7990
- const isRoot = checkIsScrollRoot(this.instance);
7930
+ const { scroll, instance } = this;
7931
+ const { animationId } = this.root;
7932
+ if (this.options.layoutScroll &&
7933
+ instance &&
7934
+ !(scroll &&
7935
+ scroll.animationId === animationId &&
7936
+ scroll.phase === phase)) {
7937
+ const isRoot = checkIsScrollRoot(instance);
7991
7938
  this.scroll = {
7992
- animationId: this.root.animationId,
7939
+ animationId,
7993
7940
  phase,
7994
7941
  isRoot,
7995
- offset: measureScroll(this.instance),
7996
- wasRoot: this.scroll ? this.scroll.isRoot : isRoot,
7942
+ offset: measureScroll(instance),
7943
+ wasRoot: scroll ? scroll.isRoot : isRoot,
7997
7944
  };
7998
7945
  }
7999
7946
  }
@@ -8083,10 +8030,10 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8083
8030
  }
8084
8031
  return boxWithoutScroll;
8085
8032
  }
8086
- applyTransform(box, transformOnly = false, output, skipOwnTransform) {
8033
+ applyTransform(box, transformOnly = false, output, skipOwnTransform, start = 0) {
8087
8034
  const withTransforms = output || createBox();
8088
8035
  copyBoxInto(withTransforms, box);
8089
- for (let i = 0; i < this.path.length; i++) {
8036
+ for (let i = start; i < this.path.length; i++) {
8090
8037
  const node = this.path[i];
8091
8038
  if (!transformOnly &&
8092
8039
  node.options.layoutScroll &&
@@ -8258,8 +8205,13 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8258
8205
  this.attemptToResolveRelativeTarget = false;
8259
8206
  if (this.options.layoutAnchor !== false &&
8260
8207
  relativeParent &&
8261
- Boolean(relativeParent.resumingFrom) ===
8262
- Boolean(this.resumingFrom) &&
8208
+ (!relativeParent.resumingFrom === !this.resumingFrom ||
8209
+ /**
8210
+ * Shared layout animations within a layoutRoot
8211
+ * animate relative to it.
8212
+ */
8213
+ (relativeParent.options.layoutRoot &&
8214
+ !relativeParent.resumingFrom)) &&
8263
8215
  !relativeParent.options.layoutScroll &&
8264
8216
  relativeParent.target &&
8265
8217
  this.animationProgress !== 1) {
@@ -8339,7 +8291,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8339
8291
  * If this section of the tree isn't animating we can
8340
8292
  * delete our target sources for the following frame.
8341
8293
  */
8342
- this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||
8294
+ this.isTreeAnimating = Boolean(this.parent?.isTreeAnimating ||
8343
8295
  this.currentAnimation ||
8344
8296
  this.pendingAnimation);
8345
8297
  if (!this.isTreeAnimating) {
@@ -8360,8 +8312,17 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8360
8312
  /**
8361
8313
  * Apply all the parent deltas to this box to produce the corrected box. This
8362
8314
  * is the layout box, as it will appear on screen as a result of the transforms of its parents.
8315
+ *
8316
+ * A shared target is usually in page space, so ancestor transforms are applied
8317
+ * too. But a target relative to a parent that isn't itself shared (like a
8318
+ * layoutRoot) is in that parent's layout space. So the transforms of the
8319
+ * parent and its ancestors, which move both elements alike, are skipped,
8320
+ * but those of other ancestors (between it and either element) apply.
8363
8321
  */
8364
- applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
8322
+ applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared &&
8323
+ (lead.relativeTarget && !lead.relativeParent.resumingFrom
8324
+ ? lead.relativeParent
8325
+ : true));
8365
8326
  /**
8366
8327
  * If this layer needs to perform scale correction but doesn't have a target,
8367
8328
  * use the layout as the target.
@@ -8428,8 +8389,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8428
8389
  scheduleRender(notifyAll = true) {
8429
8390
  this.options.visualElement?.scheduleRender();
8430
8391
  if (notifyAll) {
8431
- const stack = this.getStack();
8432
- stack && stack.scheduleRender();
8392
+ this.getStack()?.scheduleRender();
8433
8393
  }
8434
8394
  if (this.resumingFrom && !this.resumingFrom.instance) {
8435
8395
  this.resumingFrom = undefined;
@@ -8451,9 +8411,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8451
8411
  }
8452
8412
  this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
8453
8413
  const relativeLayout = createBox();
8454
- const snapshotSource = snapshot ? snapshot.source : undefined;
8455
- const layoutSource = this.layout ? this.layout.source : undefined;
8456
- const isSharedLayoutAnimation = snapshotSource !== layoutSource;
8414
+ const isSharedLayoutAnimation = snapshot?.source !== this.layout?.source;
8457
8415
  const stack = this.getStack();
8458
8416
  const isOnlyMember = !stack || stack.members.length <= 1;
8459
8417
  const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&
@@ -8468,19 +8426,11 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8468
8426
  this.mixTargetDelta = (latest) => {
8469
8427
  const progress = latest / 1000;
8470
8428
  const point = interpolate?.(progress);
8429
+ mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8430
+ mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8471
8431
  if (point) {
8472
8432
  targetDelta.x.translate = point.x;
8473
- targetDelta.x.scale = mixNumber$1(delta.x.scale, 1, progress);
8474
- targetDelta.x.origin = delta.x.origin;
8475
- targetDelta.x.originPoint = delta.x.originPoint;
8476
8433
  targetDelta.y.translate = point.y;
8477
- targetDelta.y.scale = mixNumber$1(delta.y.scale, 1, progress);
8478
- targetDelta.y.origin = delta.y.origin;
8479
- targetDelta.y.originPoint = delta.y.originPoint;
8480
- }
8481
- else {
8482
- mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8483
- mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8484
8434
  }
8485
8435
  this.setTargetDelta(targetDelta);
8486
8436
  if (this.relativeTarget &&
@@ -8506,7 +8456,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8506
8456
  this.animationValues = mixedValues;
8507
8457
  mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
8508
8458
  }
8509
- if (point && point.rotate !== undefined) {
8459
+ if (point?.rotate !== undefined) {
8510
8460
  // Dedicated `pathRotation` channel, not `rotate`, so an
8511
8461
  // animating `rotate` is composed with, never clobbered.
8512
8462
  if (!this.animationValues)
@@ -8571,7 +8521,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8571
8521
  }
8572
8522
  finishAnimation() {
8573
8523
  if (this.currentAnimation) {
8574
- this.mixTargetDelta && this.mixTargetDelta(animationTarget);
8524
+ this.mixTargetDelta?.(animationTarget);
8575
8525
  this.currentAnimation.stop();
8576
8526
  }
8577
8527
  this.completeAnimation();
@@ -8591,13 +8541,11 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8591
8541
  this.layout &&
8592
8542
  layout &&
8593
8543
  shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {
8544
+ const { layoutBox } = this.layout;
8545
+ const leadTarget = target;
8594
8546
  target = this.target || createBox();
8595
- const xLength = calcLength(this.layout.layoutBox.x);
8596
- target.x.min = lead.target.x.min;
8597
- target.x.max = target.x.min + xLength;
8598
- const yLength = calcLength(this.layout.layoutBox.y);
8599
- target.y.min = lead.target.y.min;
8600
- target.y.max = target.y.min + yLength;
8547
+ alignAxis(target.x, leadTarget.x, layoutBox.x);
8548
+ alignAxis(target.y, leadTarget.y, layoutBox.y);
8601
8549
  }
8602
8550
  copyBoxInto(targetWithTransforms, target);
8603
8551
  /**
@@ -8622,8 +8570,8 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8622
8570
  stack.add(node);
8623
8571
  const config = node.options.initialPromotionConfig;
8624
8572
  node.promote({
8625
- transition: config ? config.transition : undefined,
8626
- preserveFollowOpacity: config && config.shouldPreserveFollowOpacity
8573
+ transition: config?.transition,
8574
+ preserveFollowOpacity: config?.shouldPreserveFollowOpacity
8627
8575
  ? config.shouldPreserveFollowOpacity(node)
8628
8576
  : undefined,
8629
8577
  });
@@ -8646,9 +8594,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8646
8594
  return this.root.sharedNodes.get(layoutId);
8647
8595
  }
8648
8596
  promote({ needsReset, transition, preserveFollowOpacity, } = {}) {
8649
- const stack = this.getStack();
8650
- if (stack)
8651
- stack.promote(this, preserveFollowOpacity);
8597
+ this.getStack()?.promote(this, preserveFollowOpacity);
8652
8598
  if (needsReset) {
8653
8599
  this.projectionDelta = undefined;
8654
8600
  this.needsReset = true;
@@ -8657,45 +8603,27 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8657
8603
  this.setOptions({ transition });
8658
8604
  }
8659
8605
  relegate() {
8660
- const stack = this.getStack();
8661
- if (stack) {
8662
- return stack.relegate(this);
8663
- }
8664
- else {
8665
- return false;
8666
- }
8606
+ return this.getStack()?.relegate(this) || false;
8667
8607
  }
8668
8608
  resetSkewAndRotation() {
8669
8609
  const { visualElement } = this.options;
8670
8610
  if (!visualElement)
8671
8611
  return;
8672
- // If there's no detected skew or rotation values, we can early return without a forced render.
8673
- let hasDistortingTransform = false;
8674
8612
  /**
8675
8613
  * An unrolled check for rotation values. Most elements don't have any rotation and
8676
- * skipping the nested loop and new object creation is 50% faster.
8614
+ * skipping the loop and new object creation is 50% faster.
8615
+ * If there's no distorting values, we don't need to do any more.
8677
8616
  */
8678
8617
  const { latestValues } = visualElement;
8679
- if (latestValues.z ||
8680
- latestValues.rotate ||
8681
- latestValues.rotateX ||
8682
- latestValues.rotateY ||
8683
- latestValues.rotateZ ||
8684
- latestValues.skewX ||
8685
- latestValues.skewY) {
8686
- hasDistortingTransform = true;
8687
- }
8688
- // If there's no distorting values, we don't need to do any more.
8689
- if (!hasDistortingTransform)
8618
+ if (!hasDistortingTransform(latestValues))
8690
8619
  return;
8691
8620
  const resetValues = {};
8692
- if (latestValues.z) {
8693
- resetDistortingTransform("z", visualElement, resetValues, this.animationValues);
8694
- }
8695
8621
  // Check the skew and rotate value of all axes and reset to 0
8696
- for (let i = 0; i < transformAxes.length; i++) {
8697
- resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8698
- resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8622
+ for (let i = 0; i < distortingTransforms.length; i++) {
8623
+ resetDistortingTransform(distortingTransforms[i], visualElement, resetValues, this.animationValues);
8624
+ }
8625
+ for (let i = 0; i < angleTransforms.length; i++) {
8626
+ resetDistortingTransform(angleTransforms[i], visualElement, resetValues, this.animationValues);
8699
8627
  }
8700
8628
  // Force a render of this element to apply the transform with all skews and rotations
8701
8629
  // set to 0.
@@ -8715,7 +8643,13 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8715
8643
  styleProp) {
8716
8644
  if (!this.instance || this.isSVG)
8717
8645
  return;
8718
- if (!this.isVisible) {
8646
+ const lead = this.getLead();
8647
+ /**
8648
+ * Without crossfade, a new lead hides the previous one, as it's
8649
+ * usually unmounting. One that gave its layoutId away keeps
8650
+ * rendering, so only hide nodes that follow another.
8651
+ */
8652
+ if (!this.isVisible && lead !== this) {
8719
8653
  targetStyle.visibility = "hidden";
8720
8654
  return;
8721
8655
  }
@@ -8731,9 +8665,10 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8731
8665
  : "none";
8732
8666
  return;
8733
8667
  }
8734
- const lead = this.getLead();
8735
8668
  if (!this.projectionDelta || !this.layout || !lead.target) {
8736
- if (this.options.layoutId) {
8669
+ if (this.options.layoutId || this.needsShow) {
8670
+ this.needsShow = false;
8671
+ targetStyle.visibility = "";
8737
8672
  targetStyle.opacity =
8738
8673
  this.latestValues.opacity !== undefined
8739
8674
  ? this.latestValues.opacity
@@ -8867,52 +8802,49 @@ function notifyLayoutUpdate(node) {
8867
8802
  const isShared = snapshot.source !== node.layout.source;
8868
8803
  // TODO Maybe we want to also resize the layout snapshot so we don't trigger
8869
8804
  // animations for instance if layout="size" and an element has only changed position
8870
- if (animationType === "size") {
8871
- eachAxis((axis) => {
8872
- const axisSnapshot = isShared
8873
- ? snapshot.measuredBox[axis]
8874
- : snapshot.layoutBox[axis];
8875
- const length = calcLength(axisSnapshot);
8876
- axisSnapshot.min = layout[axis].min;
8877
- axisSnapshot.max = axisSnapshot.min + length;
8878
- });
8879
- }
8880
- else if (animationType === "x" || animationType === "y") {
8881
- const snapAxis = animationType === "x" ? "y" : "x";
8882
- copyAxisInto(isShared
8883
- ? snapshot.measuredBox[snapAxis]
8884
- : snapshot.layoutBox[snapAxis], layout[snapAxis]);
8885
- }
8886
- else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8887
- eachAxis((axis) => {
8888
- const axisSnapshot = isShared
8889
- ? snapshot.measuredBox[axis]
8890
- : snapshot.layoutBox[axis];
8891
- const length = calcLength(layout[axis]);
8892
- axisSnapshot.max = axisSnapshot.min + length;
8893
- /**
8894
- * Ensure relative target gets resized and rerendererd
8895
- */
8896
- if (node.relativeTarget && !node.currentAnimation) {
8897
- node.isProjectionDirty = true;
8898
- node.relativeTarget[axis].max =
8899
- node.relativeTarget[axis].min + length;
8900
- }
8901
- });
8902
- }
8805
+ const resizeSnapshot = (box, to) => {
8806
+ if (animationType === "size") {
8807
+ eachAxis((axis) => {
8808
+ const length = calcLength(box[axis]);
8809
+ box[axis].min = to[axis].min;
8810
+ box[axis].max = box[axis].min + length;
8811
+ });
8812
+ }
8813
+ else if (animationType === "x" || animationType === "y") {
8814
+ const snapAxis = animationType === "x" ? "y" : "x";
8815
+ copyAxisInto(box[snapAxis], to[snapAxis]);
8816
+ }
8817
+ else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8818
+ eachAxis((axis) => {
8819
+ const length = calcLength(to[axis]);
8820
+ box[axis].max = box[axis].min + length;
8821
+ /**
8822
+ * Ensure relative target gets resized and rerendererd
8823
+ */
8824
+ if (node.relativeTarget && !node.currentAnimation) {
8825
+ node.isProjectionDirty = true;
8826
+ node.relativeTarget[axis].max =
8827
+ node.relativeTarget[axis].min + length;
8828
+ }
8829
+ });
8830
+ }
8831
+ };
8832
+ const snapshotBox = isShared ? snapshot.measuredBox : snapshot.layoutBox;
8833
+ resizeSnapshot(snapshotBox, layout);
8903
8834
  const layoutDelta = createDelta();
8904
8835
  calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);
8905
8836
  const visualDelta = createDelta();
8906
- if (isShared) {
8907
- calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
8908
- }
8909
- else {
8910
- calcBoxDelta(visualDelta, layout, snapshot.layoutBox);
8911
- }
8837
+ calcBoxDelta(visualDelta, isShared ? node.applyTransform(measuredLayout, true) : layout, snapshotBox);
8912
8838
  const hasLayoutChanged = !isDeltaZero(layoutDelta);
8913
8839
  let hasRelativeLayoutChanged = false;
8914
- if (!node.resumeFrom) {
8915
- const relativeParent = node.getClosestProjectingParent();
8840
+ const relativeParent = node.getClosestProjectingParent();
8841
+ /**
8842
+ * A snapshot resumed from another element is only relative to this
8843
+ * node's relativeParent if it's a layoutRoot that contains both.
8844
+ */
8845
+ if (!node.resumeFrom ||
8846
+ (relativeParent?.options.layoutRoot &&
8847
+ node.resumeFrom.path.includes(relativeParent))) {
8916
8848
  /**
8917
8849
  * If the relativeParent is itself resuming from a different element then
8918
8850
  * the relative snapshot is not relavent
@@ -8921,10 +8853,22 @@ function notifyLayoutUpdate(node) {
8921
8853
  const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
8922
8854
  if (parentSnapshot && parentLayout) {
8923
8855
  const anchor = node.options.layoutAnchor || undefined;
8856
+ /**
8857
+ * A shared snapshot includes the transforms of the old
8858
+ * element's ancestors below the layoutRoot, as they
8859
+ * aren't shared with the new element.
8860
+ */
8924
8861
  const relativeSnapshot = createBox();
8925
- calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8862
+ calcRelativePosition(relativeSnapshot, isShared
8863
+ ? node.resumeFrom.applyTransform(snapshot.layoutBox, true, undefined, true, relativeParent.depth + 1)
8864
+ : snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8926
8865
  const relativeLayout = createBox();
8927
8866
  calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox, anchor);
8867
+ /**
8868
+ * A shared snapshot is resized in page space, above, so
8869
+ * resize it relative to the layoutRoot too.
8870
+ */
8871
+ isShared && resizeSnapshot(relativeSnapshot, relativeLayout);
8928
8872
  if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {
8929
8873
  hasRelativeLayoutChanged = true;
8930
8874
  }
@@ -8946,8 +8890,7 @@ function notifyLayoutUpdate(node) {
8946
8890
  });
8947
8891
  }
8948
8892
  else if (node.isLead()) {
8949
- const { onExitComplete } = node.options;
8950
- onExitComplete && onExitComplete();
8893
+ node.options.onExitComplete?.();
8951
8894
  }
8952
8895
  /**
8953
8896
  * Clearing transition
@@ -9053,7 +8996,7 @@ function syncRelativeLayout(node) {
9053
8996
  }
9054
8997
  function resetTransformStyle(node) {
9055
8998
  const { visualElement } = node.options;
9056
- if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {
8999
+ if (visualElement?.getProps().onBeforeLayoutMeasure) {
9057
9000
  visualElement.notify("BeforeLayoutMeasure");
9058
9001
  }
9059
9002
  node.resetTransform();
@@ -9087,7 +9030,7 @@ function mixBox(output, from, to, p) {
9087
9030
  mixAxis(output.y, from.y, to.y, p);
9088
9031
  }
9089
9032
  function hasOpacityCrossfade(node) {
9090
- return (node.animationValues && node.animationValues.opacityExit !== undefined);
9033
+ return node.animationValues?.opacityExit !== undefined;
9091
9034
  }
9092
9035
  const defaultLayoutTransition = {
9093
9036
  duration: 0.45,
@@ -9113,6 +9056,13 @@ function roundBox(box) {
9113
9056
  roundAxis(box.x);
9114
9057
  roundAxis(box.y);
9115
9058
  }
9059
+ /**
9060
+ * Align an axis to the start of another, keeping the length of a layout axis.
9061
+ * The length is read first, as output can be the layout axis itself.
9062
+ */
9063
+ function alignAxis(output, from, layout) {
9064
+ output.max = calcLength(layout) + (output.min = from.min);
9065
+ }
9116
9066
  function shouldAnimatePositionOnly(animationType, snapshot, layout) {
9117
9067
  return (animationType === "position" ||
9118
9068
  (animationType === "preserve-aspect" &&
@@ -9163,7 +9113,7 @@ const HTMLProjectionNode =
9163
9113
  resetTransform: (instance, value) => {
9164
9114
  instance.style.transform = value !== undefined ? value : "none";
9165
9115
  },
9166
- checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9116
+ checkIsScrollRoot: (instance) => window.getComputedStyle(instance).position === "fixed",
9167
9117
  });
9168
9118
 
9169
9119
  const visualElementStore = new WeakMap();
@@ -9449,9 +9399,7 @@ class VisualElement {
9449
9399
  }
9450
9400
  this.current = instance;
9451
9401
  visualElementStore.set(instance, this);
9452
- if (this.projection && !this.projection.instance) {
9453
- this.projection.mount(instance);
9454
- }
9402
+ this.projection?.instance || this.projection?.mount(instance);
9455
9403
  /**
9456
9404
  * Join the closest variant node above, so its variant changes
9457
9405
  * propagate here, unless inherit={false} cuts the chain.
@@ -9497,12 +9445,12 @@ class VisualElement {
9497
9445
  this.hasBeenMounted = true;
9498
9446
  }
9499
9447
  unmount() {
9500
- this.projection && this.projection.unmount();
9448
+ this.projection?.unmount();
9501
9449
  cancelFrame(this.notifyUpdate);
9502
9450
  cancelFrame(this.render);
9503
9451
  this.valueSubscriptions.forEach((remove) => remove());
9504
9452
  this.valueSubscriptions.clear();
9505
- this.removeFromVariantTree && this.removeFromVariantTree();
9453
+ this.removeFromVariantTree?.();
9506
9454
  this.parent?.removeChild(this);
9507
9455
  for (const key in this.events) {
9508
9456
  this.events[key].clear();
@@ -9518,17 +9466,14 @@ class VisualElement {
9518
9466
  }
9519
9467
  addChild(child) {
9520
9468
  this.children.add(child);
9521
- this.enteringChildren ?? (this.enteringChildren = new Set());
9522
- this.enteringChildren.add(child);
9469
+ (this.enteringChildren || (this.enteringChildren = new Set())).add(child);
9523
9470
  }
9524
9471
  removeChild(child) {
9525
9472
  this.children.delete(child);
9526
- this.enteringChildren && this.enteringChildren.delete(child);
9473
+ this.enteringChildren?.delete(child);
9527
9474
  }
9528
9475
  bindToMotionValue(key, value) {
9529
- if (this.valueSubscriptions.has(key)) {
9530
- this.valueSubscriptions.get(key)();
9531
- }
9476
+ this.valueSubscriptions.get(key)?.();
9532
9477
  if (value.accelerate &&
9533
9478
  acceleratedValues.has(key) &&
9534
9479
  this.current instanceof HTMLElement) {
@@ -9570,8 +9515,7 @@ class VisualElement {
9570
9515
  }
9571
9516
  this.valueSubscriptions.set(key, () => {
9572
9517
  removeOnChange();
9573
- if (removeSyncCheck)
9574
- removeSyncCheck();
9518
+ removeSyncCheck?.();
9575
9519
  // Defer to MotionValue.on("change") auto-stop so React 19 remounts
9576
9520
  // can resubscribe before the animation is cancelled (#3315).
9577
9521
  });
@@ -9664,10 +9608,8 @@ class VisualElement {
9664
9608
  */
9665
9609
  for (let i = 0; i < propEventHandlers.length; i++) {
9666
9610
  const key = propEventHandlers[i];
9667
- if (this.propEventSubscriptions[key]) {
9668
- this.propEventSubscriptions[key]();
9669
- delete this.propEventSubscriptions[key];
9670
- }
9611
+ this.propEventSubscriptions[key]?.();
9612
+ delete this.propEventSubscriptions[key];
9671
9613
  const listenerName = ("on" + key);
9672
9614
  const listener = props[listenerName];
9673
9615
  if (listener) {
@@ -9675,9 +9617,7 @@ class VisualElement {
9675
9617
  }
9676
9618
  }
9677
9619
  this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues);
9678
- if (this.handleChildMotionValue) {
9679
- this.handleChildMotionValue();
9680
- }
9620
+ this.handleChildMotionValue?.();
9681
9621
  }
9682
9622
  getProps() {
9683
9623
  return this.props;
@@ -9686,7 +9626,7 @@ class VisualElement {
9686
9626
  * Returns the variant definition with a given name.
9687
9627
  */
9688
9628
  getVariant(name) {
9689
- return this.props.variants ? this.props.variants[name] : undefined;
9629
+ return this.props.variants?.[name];
9690
9630
  }
9691
9631
  /**
9692
9632
  * Returns the defined default transition on this component.
@@ -9724,11 +9664,8 @@ class VisualElement {
9724
9664
  */
9725
9665
  removeValue(key) {
9726
9666
  this.values.delete(key);
9727
- const unsubscribe = this.valueSubscriptions.get(key);
9728
- if (unsubscribe) {
9729
- unsubscribe();
9730
- this.valueSubscriptions.delete(key);
9731
- }
9667
+ this.valueSubscriptions.get(key)?.();
9668
+ this.valueSubscriptions.delete(key);
9732
9669
  delete this.latestValues[key];
9733
9670
  this.removeValueFromRenderState(key, this.renderState);
9734
9671
  }
@@ -9739,10 +9676,10 @@ class VisualElement {
9739
9676
  return this.values.has(key);
9740
9677
  }
9741
9678
  getValue(key, defaultValue) {
9742
- if (this.props.values && this.props.values[key]) {
9743
- return this.props.values[key];
9744
- }
9745
- let value = this.values.get(key);
9679
+ let value = this.props.values?.[key];
9680
+ if (value)
9681
+ return value;
9682
+ value = this.values.get(key);
9746
9683
  if (value === undefined && defaultValue !== undefined) {
9747
9684
  value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
9748
9685
  owner: this,
@@ -9792,15 +9729,11 @@ class VisualElement {
9792
9729
  this.baseTarget[key] = value;
9793
9730
  }
9794
9731
  on(eventName, callback) {
9795
- if (!this.events[eventName]) {
9796
- this.events[eventName] = new motionUtils.SubscriptionManager();
9797
- }
9798
- return this.events[eventName].add(callback);
9732
+ return (this.events[eventName] ||
9733
+ (this.events[eventName] = new motionUtils.SubscriptionManager())).add(callback);
9799
9734
  }
9800
9735
  notify(eventName, ...args) {
9801
- if (this.events[eventName]) {
9802
- this.events[eventName].notify(...args);
9803
- }
9736
+ this.events[eventName]?.notify(...args);
9804
9737
  }
9805
9738
  scheduleRenderMicrotask() {
9806
9739
  microtask.render(this.render);
@@ -9892,7 +9825,8 @@ class HTMLVisualElement extends DOMVisualElement {
9892
9825
  * HTML/SVG element (a class instance, an imperative handle) there's
9893
9826
  * nothing for Motion to style, measure or attach gestures to. #2777
9894
9827
  */
9895
- motionUtils.invariant(Boolean(instance.style), "motion.create() components must forward their ref to a HTML or SVG element", "custom-component-ref");
9828
+ process.env.NODE_ENV !== "production" &&
9829
+ motionUtils.invariant(Boolean(instance.style), "motion.create() components must forward their ref to a HTML or SVG element", "custom-component-ref");
9896
9830
  super.mount(instance);
9897
9831
  }
9898
9832
  readValueFromInstance(instance, key) {
@@ -9966,7 +9900,7 @@ function getProjectionParent(element) {
9966
9900
  let ancestor = element.parentElement;
9967
9901
  while (ancestor) {
9968
9902
  const node = layoutNodes.get(ancestor);
9969
- if (node && node.instance)
9903
+ if (node?.instance)
9970
9904
  return node;
9971
9905
  ancestor = ancestor.parentElement;
9972
9906
  }
@@ -10232,7 +10166,7 @@ class LayoutAnimationBuilder {
10232
10166
  hasSurvivor &&
10233
10167
  !newMemberIds.has(layoutId)) {
10234
10168
  if (restore && restore.parent.isConnected) {
10235
- restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10169
+ restore.parent.insertBefore(element, restore.next?.parentNode === restore.parent
10236
10170
  ? restore.next
10237
10171
  : null);
10238
10172
  node.isPresent = false;
@@ -10437,10 +10371,6 @@ class PanSession {
10437
10371
  * Scroll positions of scrollable ancestors and window.
10438
10372
  */
10439
10373
  this.scrollPositions = new Map();
10440
- /**
10441
- * Cleanup function for scroll listeners.
10442
- */
10443
- this.removeScrollListeners = null;
10444
10374
  this.onElementScroll = (event) => {
10445
10375
  this.handleScroll(event.target);
10446
10376
  };
@@ -10468,10 +10398,10 @@ class PanSession {
10468
10398
  this.history.push({ ...point, timestamp: time.now() });
10469
10399
  const { onStart, onMove } = this.handlers;
10470
10400
  if (!isPanStarted) {
10471
- onStart && onStart(this.lastMoveEvent, info);
10401
+ onStart?.(this.lastMoveEvent, info);
10472
10402
  this.startEvent = this.lastMoveEvent;
10473
10403
  }
10474
- onMove && onMove(this.lastMoveEvent, info);
10404
+ onMove?.(this.lastMoveEvent, info);
10475
10405
  };
10476
10406
  this.handlePointerMove = (event, info) => {
10477
10407
  /**
@@ -10496,17 +10426,15 @@ class PanSession {
10496
10426
  // Resume animation if dragSnapToOrigin is set OR if no drag started (user just clicked)
10497
10427
  // This ensures constraint animations continue when interrupted by a click
10498
10428
  if (this.dragSnapToOrigin || !this.startEvent) {
10499
- resumeAnimation && resumeAnimation();
10429
+ resumeAnimation?.();
10500
10430
  }
10501
10431
  if (!(this.lastMoveEvent && this.lastMoveEventInfo))
10502
10432
  return;
10503
10433
  const panInfo = getPanInfo(event.type === "pointercancel"
10504
10434
  ? this.lastMoveEventInfo
10505
10435
  : transformPoint(info, this.transformPagePoint), this.history);
10506
- if (this.startEvent && onEnd) {
10507
- onEnd(event, panInfo);
10508
- }
10509
- onSessionEnd && onSessionEnd(event, panInfo);
10436
+ this.startEvent && onEnd?.(event, panInfo);
10437
+ onSessionEnd?.(event, panInfo);
10510
10438
  };
10511
10439
  // If we have more than one touch, don't start detecting this gesture
10512
10440
  if (!isPrimaryPointer(event))
@@ -10519,8 +10447,13 @@ class PanSession {
10519
10447
  const info = extractEventInfo(event);
10520
10448
  const initialInfo = transformPoint(info, this.transformPagePoint);
10521
10449
  const { point } = initialInfo;
10522
- const { timestamp } = frameData;
10523
- this.history = [{ ...point, timestamp }];
10450
+ /**
10451
+ * Stamp the origin with time.now(), not frameData.timestamp: when
10452
+ * the frameloop is idle, frameData.timestamp is from the last frame
10453
+ * that ran, which can be seconds old, and a fast flick from a
10454
+ * standstill would then report near-zero velocity. See #1747.
10455
+ */
10456
+ this.history = [{ ...point, timestamp: time.now() }];
10524
10457
  const { onSessionStart } = handlers;
10525
10458
  onSessionStart &&
10526
10459
  onSessionStart(event, getPanInfo(initialInfo, this.history));
@@ -10544,30 +10477,19 @@ class PanSession {
10544
10477
  const style = getComputedStyle(current);
10545
10478
  if (overflowStyles.has(style.overflowX) ||
10546
10479
  overflowStyles.has(style.overflowY)) {
10547
- this.scrollPositions.set(current, {
10548
- x: current.scrollLeft,
10549
- y: current.scrollTop,
10550
- });
10480
+ this.scrollPositions.set(current, getScroll(current));
10551
10481
  }
10552
10482
  current = current.parentElement;
10553
10483
  }
10554
10484
  // Track window scroll
10555
- this.scrollPositions.set(window, {
10556
- x: window.scrollX,
10557
- y: window.scrollY,
10558
- });
10485
+ this.scrollPositions.set(window, getScroll(window));
10486
+ this.removeScrollListeners = motionUtils.pipe(
10559
10487
  // Capture listener catches element scroll events as they bubble
10560
- window.addEventListener("scroll", this.onElementScroll, {
10488
+ addDomEvent(window, "scroll", this.onElementScroll, {
10561
10489
  capture: true,
10562
- });
10490
+ }),
10563
10491
  // Direct window scroll listener (window scroll doesn't bubble)
10564
- window.addEventListener("scroll", this.onWindowScroll);
10565
- this.removeScrollListeners = () => {
10566
- window.removeEventListener("scroll", this.onElementScroll, {
10567
- capture: true,
10568
- });
10569
- window.removeEventListener("scroll", this.onWindowScroll);
10570
- };
10492
+ addDomEvent(window, "scroll", this.onWindowScroll, {}));
10571
10493
  }
10572
10494
  /**
10573
10495
  * Handle scroll compensation during drag.
@@ -10580,12 +10502,7 @@ class PanSession {
10580
10502
  if (!initial)
10581
10503
  return;
10582
10504
  const isWindow = target === window;
10583
- const current = isWindow
10584
- ? { x: window.scrollX, y: window.scrollY }
10585
- : {
10586
- x: target.scrollLeft,
10587
- y: target.scrollTop,
10588
- };
10505
+ const current = getScroll(target);
10589
10506
  const delta = { x: current.x - initial.x, y: current.y - initial.y };
10590
10507
  if (delta.x === 0 && delta.y === 0)
10591
10508
  return;
@@ -10610,12 +10527,18 @@ class PanSession {
10610
10527
  this.handlers = handlers;
10611
10528
  }
10612
10529
  end() {
10613
- this.removeListeners && this.removeListeners();
10614
- this.removeScrollListeners && this.removeScrollListeners();
10530
+ this.removeListeners?.();
10531
+ this.removeScrollListeners?.();
10615
10532
  this.scrollPositions.clear();
10616
10533
  cancelFrame(this.updatePoint);
10617
10534
  }
10618
10535
  }
10536
+ const getScroll = (target) => target === window
10537
+ ? { x: window.scrollX, y: window.scrollY }
10538
+ : {
10539
+ x: target.scrollLeft,
10540
+ y: target.scrollTop,
10541
+ };
10619
10542
  function transformPoint(info, transformPagePoint) {
10620
10543
  return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
10621
10544
  }
@@ -10872,6 +10795,25 @@ function resolvePointElastic(dragElastic, label) {
10872
10795
  : dragElastic[label] || 0;
10873
10796
  }
10874
10797
 
10798
+ /**
10799
+ * Re-read the scroll of the projection's ancestors, and return that of the
10800
+ * `layoutScroll` ones as a key that changes when any of them scroll.
10801
+ *
10802
+ * Clear the cached scroll first so `updateScroll` bypasses its
10803
+ * per-animationId cache and re-reads the live value.
10804
+ */
10805
+ function measureScroll(projection) {
10806
+ let key = "";
10807
+ for (const node of projection.path) {
10808
+ node.scroll = undefined;
10809
+ node.updateScroll();
10810
+ const { scroll } = node;
10811
+ if (node !== projection.root && scroll) {
10812
+ key += scroll.offset.x + "," + scroll.offset.y + ",";
10813
+ }
10814
+ }
10815
+ return key;
10816
+ }
10875
10817
  const elementDragControls = new WeakMap();
10876
10818
  class VisualElementDragControls {
10877
10819
  constructor(visualElement, readProps = () => visualElement.getProps()) {
@@ -10903,8 +10845,7 @@ class VisualElementDragControls {
10903
10845
  /**
10904
10846
  * Don't start dragging if this component is exiting
10905
10847
  */
10906
- const { presenceContext } = this.visualElement;
10907
- if (presenceContext && presenceContext.isPresent === false)
10848
+ if (this.visualElement.presenceContext?.isPresent === false)
10908
10849
  return;
10909
10850
  const onSessionStart = (event) => {
10910
10851
  if (snapToCursor)
@@ -10915,8 +10856,7 @@ class VisualElementDragControls {
10915
10856
  // Attempt to grab the global drag gesture lock - maybe make this part of PanSession
10916
10857
  const { drag, dragPropagation, onDragStart } = this.getProps();
10917
10858
  if (drag && !dragPropagation) {
10918
- if (this.openDragLock)
10919
- this.openDragLock();
10859
+ this.openDragLock?.();
10920
10860
  this.openDragLock = setDragLock(drag);
10921
10861
  // If we don 't have the lock, don't start dragging
10922
10862
  if (!this.openDragLock)
@@ -10927,9 +10867,10 @@ class VisualElementDragControls {
10927
10867
  this.isDragging = true;
10928
10868
  this.currentDirection = null;
10929
10869
  this.resolveConstraints();
10930
- if (this.visualElement.projection) {
10931
- this.visualElement.projection.isAnimationBlocked = true;
10932
- this.visualElement.projection.target = undefined;
10870
+ const { projection } = this.visualElement;
10871
+ if (projection) {
10872
+ projection.isAnimationBlocked = true;
10873
+ projection.target = undefined;
10933
10874
  }
10934
10875
  /**
10935
10876
  * Record gesture origin and pointer offset
@@ -10951,13 +10892,11 @@ class VisualElementDragControls {
10951
10892
  current = parseFloat(current);
10952
10893
  }
10953
10894
  else if (percent.test(current)) {
10954
- const { projection } = this.visualElement;
10955
- if (projection && projection.layout) {
10956
- const measuredAxis = projection.layout.layoutBox[axis];
10957
- if (measuredAxis) {
10958
- const length = calcLength(measuredAxis);
10959
- current = length * (parseFloat(current) / 100);
10960
- }
10895
+ const measuredAxis = projection?.layout?.layoutBox[axis];
10896
+ if (measuredAxis) {
10897
+ current =
10898
+ calcLength(measuredAxis) *
10899
+ (parseFloat(current) / 100);
10961
10900
  }
10962
10901
  }
10963
10902
  this.originPoint[axis] = current;
@@ -10967,8 +10906,7 @@ class VisualElementDragControls {
10967
10906
  frame.update(() => onDragStart(event, info), false, true);
10968
10907
  }
10969
10908
  addValueToWillChange(this.visualElement, "transform");
10970
- const { animationState } = this.visualElement;
10971
- animationState && animationState.setActive("whileDrag", true);
10909
+ this.visualElement.animationState?.setActive("whileDrag", true);
10972
10910
  };
10973
10911
  const onMove = (event, info) => {
10974
10912
  this.latestPointerEvent = event;
@@ -10991,8 +10929,8 @@ class VisualElementDragControls {
10991
10929
  onDirectionLock && onDirectionLock(this.currentDirection);
10992
10930
  }
10993
10931
  // Update each point with the latest position
10994
- this.updateAxis("x", info.point, offset);
10995
- this.updateAxis("y", info.point, offset);
10932
+ this.updateAxis("x", offset);
10933
+ this.updateAxis("y", offset);
10996
10934
  /**
10997
10935
  * Ideally we would leave the renderer to fire naturally at the end of
10998
10936
  * this frame but if the element is about to change layout as the result
@@ -11061,12 +10999,11 @@ class VisualElementDragControls {
11061
10999
  projection.isAnimationBlocked = false;
11062
11000
  }
11063
11001
  this.endPanSession();
11064
- const { dragPropagation } = this.getProps();
11065
- if (!dragPropagation && this.openDragLock) {
11002
+ if (!this.getProps().dragPropagation && this.openDragLock) {
11066
11003
  this.openDragLock();
11067
11004
  this.openDragLock = null;
11068
11005
  }
11069
- animationState && animationState.setActive("whileDrag", false);
11006
+ animationState?.setActive("whileDrag", false);
11070
11007
  }
11071
11008
  /**
11072
11009
  * Clean up the pan session without modifying other drag state.
@@ -11074,31 +11011,42 @@ class VisualElementDragControls {
11074
11011
  * without affecting projection animations or drag locks.
11075
11012
  */
11076
11013
  endPanSession() {
11077
- this.panSession && this.panSession.end();
11014
+ this.panSession?.end();
11078
11015
  this.panSession = undefined;
11079
11016
  }
11080
- updateAxis(axis, _point, offset) {
11081
- const { drag } = this.getProps();
11017
+ updateAxis(axis, offset) {
11018
+ /**
11019
+ * Read drag per axis: a callback fired while updating the x axis
11020
+ * can synchronously re-render with new props.
11021
+ */
11022
+ const { drag } = this.readProps();
11082
11023
  // If we're not dragging this axis, do an early return.
11083
11024
  if (!offset || !shouldDrag(axis, drag, this.currentDirection))
11084
11025
  return;
11085
11026
  const axisValue = this.getAxisMotionValue(axis);
11086
11027
  let next = this.originPoint[axis] + offset[axis];
11087
11028
  // Apply constraints
11088
- if (this.constraints && this.constraints[axis]) {
11089
- next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
11029
+ const constraints = this.constraints && this.constraints[axis];
11030
+ if (constraints) {
11031
+ next = applyConstraints(next, constraints, this.elastic[axis]);
11090
11032
  }
11091
11033
  axisValue.set(next);
11092
11034
  }
11093
11035
  resolveConstraints() {
11094
11036
  const { dragConstraints, dragElastic } = this.getProps();
11095
- const layout = this.visualElement.projection &&
11096
- !this.visualElement.projection.layout
11097
- ? this.visualElement.projection.measure(false)
11098
- : this.visualElement.projection?.layout;
11037
+ const { projection } = this.visualElement;
11038
+ const layout = projection && (projection.layout || projection.measure(false));
11099
11039
  const prevConstraints = this.constraints;
11100
11040
  if (isElementConstraints(dragConstraints)) {
11101
- if (!this.constraints) {
11041
+ /**
11042
+ * Ref constraints are measured with the layout. Scrolling a
11043
+ * `layoutScroll` ancestor since can move the element relative
11044
+ * to them without a layout measurement, so measure them again
11045
+ * (#2024). Otherwise keep them: they and the layout can both
11046
+ * have moved on the page since, e.g. when content above grows.
11047
+ */
11048
+ if (!this.constraints ||
11049
+ this.scroll !== measureScroll(projection)) {
11102
11050
  this.constraints = this.resolveRefConstraints();
11103
11051
  }
11104
11052
  }
@@ -11135,27 +11083,27 @@ class VisualElementDragControls {
11135
11083
  if (!isElementConstraints(constraints))
11136
11084
  return false;
11137
11085
  const constraintsElement = resolveConstraintsElement(constraints);
11138
- motionUtils.invariant(!!constraintsElement, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref");
11086
+ process.env.NODE_ENV !== "production" &&
11087
+ motionUtils.invariant(!!constraintsElement, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref");
11139
11088
  const { projection } = this.visualElement;
11140
11089
  // TODO
11141
11090
  if (!projection || !projection.layout)
11142
11091
  return false;
11143
11092
  /**
11144
- * Refresh the root scroll offset so the constraint's viewport box
11145
- * translates to correct page coordinates. The scroll captured at
11146
- * drag mount can be stale if the document was scrolled afterwards —
11147
- * e.g. via the browser restoring scroll on refresh, or an ancestor
11148
- * layout effect running after this element's mount (#2829).
11149
- *
11150
- * Clear the cached scroll first so `updateScroll` bypasses its
11151
- * per-animationId cache and re-reads the live value.
11093
+ * Refresh the scroll offsets of the root and `layoutScroll`
11094
+ * ancestors so the constraint's viewport box translates to the
11095
+ * layout's coordinates. The scroll captured when the layout was
11096
+ * measured can be stale if they've scrolled since — e.g. via the
11097
+ * browser restoring scroll on refresh, or an ancestor layout effect
11098
+ * running after this element's mount (#2829).
11152
11099
  */
11153
- if (projection.root) {
11154
- projection.root.scroll = undefined;
11155
- projection.root.updateScroll();
11156
- }
11100
+ this.scroll = measureScroll(projection);
11157
11101
  const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
11158
- let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
11102
+ /**
11103
+ * layoutBox removes the scroll of `layoutScroll` ancestors, so
11104
+ * remove it from the constraints box too.
11105
+ */
11106
+ let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, projection.removeElementScroll(constraintsBox));
11159
11107
  /**
11160
11108
  * If there's an onMeasureDragConstraints listener we call it and
11161
11109
  * if different constraints are returned, set constraints to that
@@ -11176,7 +11124,7 @@ class VisualElementDragControls {
11176
11124
  if (!shouldDrag(axis, dragAxes || drag, this.currentDirection)) {
11177
11125
  return;
11178
11126
  }
11179
- let transition = (constraints && constraints[axis]) || {};
11127
+ let transition = constraints[axis] || {};
11180
11128
  if (dragSnapToOrigin === true ||
11181
11129
  dragSnapToOrigin === axis)
11182
11130
  transition = { min: 0, max: 0 };
@@ -11282,7 +11230,7 @@ class VisualElementDragControls {
11282
11230
  this.visualElement.current.style.transform = transformTemplate
11283
11231
  ? transformTemplate({}, "")
11284
11232
  : "none";
11285
- projection.root && projection.root.updateScroll();
11233
+ projection.root?.updateScroll();
11286
11234
  projection.updateLayout();
11287
11235
  /**
11288
11236
  * Reset constraints so resolveConstraints() will recalculate them
@@ -11359,8 +11307,8 @@ class VisualElementDragControls {
11359
11307
  };
11360
11308
  const { projection } = this.visualElement;
11361
11309
  const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
11362
- if (projection && !projection.layout) {
11363
- projection.root && projection.root.updateScroll();
11310
+ if (!projection.layout) {
11311
+ projection.root?.updateScroll();
11364
11312
  projection.updateLayout();
11365
11313
  }
11366
11314
  frame.read(measureDragConstraints);
@@ -11395,22 +11343,14 @@ class VisualElementDragControls {
11395
11343
  stopResizeListener();
11396
11344
  stopPointerListener();
11397
11345
  stopMeasureLayoutListener();
11398
- stopLayoutUpdateListener && stopLayoutUpdateListener();
11399
- stopResizeObservers && stopResizeObservers();
11346
+ stopLayoutUpdateListener();
11347
+ stopResizeObservers?.();
11400
11348
  };
11401
11349
  }
11402
11350
  getProps() {
11403
11351
  const props = this.readProps();
11404
- const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
11405
- return {
11406
- ...props,
11407
- drag,
11408
- dragDirectionLock,
11409
- dragPropagation,
11410
- dragConstraints,
11411
- dragElastic,
11412
- dragMomentum,
11413
- };
11352
+ const { dragElastic = defaultElastic, dragMomentum = true } = props;
11353
+ return { ...props, dragElastic, dragMomentum };
11414
11354
  }
11415
11355
  }
11416
11356
  /**
@@ -13745,6 +13685,12 @@ function shallowCompare(next, prev) {
13745
13685
  }
13746
13686
 
13747
13687
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
13688
+ /**
13689
+ * The transition a value uses when it leaves a state (#1725): the state's
13690
+ * own transition when `out: true`, or the `out` transition itself.
13691
+ * Value-specific keys are resolved by animateTarget.
13692
+ */
13693
+ const getOutTransition = (transition) => transition?.out === true ? transition : transition?.out;
13748
13694
  /**
13749
13695
  * Diffs the element's animation props (one layer per AnimationType, highest
13750
13696
  * priority wins each value) against the previous call and starts animations
@@ -13766,13 +13712,18 @@ function createAnimationState(visualElement) {
13766
13712
  let wasReset = false;
13767
13713
  function animateChanges(changedActiveType) {
13768
13714
  const { props, parent, manuallyAnimateOnMount } = visualElement;
13715
+ const { initial } = props;
13769
13716
  const isMounting = isInitialRender || wasReset;
13770
13717
  const animations = [];
13718
+ const resolveInitial = (definition = initial) => (typeof definition !== "boolean" &&
13719
+ resolveVariant(visualElement, Array.isArray(definition) ? definition[0] : definition, visualElement.presenceContext?.custom)) ||
13720
+ undefined;
13771
13721
  /**
13772
- * Values removed from a type. A lower-priority type that defines
13773
- * them animates them back, otherwise they fall back to a base target.
13722
+ * Values removed from a type, mapped to the out transition of the
13723
+ * state they're leaving. A lower-priority type that defines them
13724
+ * animates them back, otherwise they fall back to a base target.
13774
13725
  */
13775
- const removedKeys = new Set();
13726
+ const removedKeys = new Map();
13776
13727
  /**
13777
13728
  * Values claimed by active, higher-priority types.
13778
13729
  */
@@ -13790,6 +13741,13 @@ function createAnimationState(visualElement) {
13790
13741
  do
13791
13742
  source = source.props.inherit !== false && source.parent;
13792
13743
  while (source && !source.isControllingVariants);
13744
+ /**
13745
+ * Mounting leaves initial, so values use its out transition. Like the
13746
+ * other types, variant children inherit initial's label.
13747
+ */
13748
+ const initialOut = isMounting &&
13749
+ getOutTransition(resolveInitial(initial ?? (source && source.props.initial))
13750
+ ?.transition);
13793
13751
  reversePriorityOrder.forEach((type, i) => {
13794
13752
  const typeState = state[type];
13795
13753
  const ownProp = props[type];
@@ -13801,8 +13759,6 @@ function createAnimationState(visualElement) {
13801
13759
  : undefined;
13802
13760
  const propIsVariant = isVariantLabel(prop);
13803
13761
  const activeDelta = type === changedActiveType ? typeState.isActive : null;
13804
- if (activeDelta === false)
13805
- removedVariantIndex = i;
13806
13762
  /**
13807
13763
  * Inherited labels are animated by the parent through
13808
13764
  * variantChildren, unless this element mounted after its parent.
@@ -13817,6 +13773,13 @@ function createAnimationState(visualElement) {
13817
13773
  typeof prop === "boolean") {
13818
13774
  return;
13819
13775
  }
13776
+ /**
13777
+ * Set after the skip above, so deactivating a type that has nothing
13778
+ * to animate (e.g. whileTap with no prop) doesn't re-run the variants
13779
+ * below it.
13780
+ */
13781
+ if (activeDelta === false)
13782
+ removedVariantIndex = i;
13820
13783
  /**
13821
13784
  * Don't re-resolve a running exit: a changed custom would start
13822
13785
  * new value animations that stop the originals, leaving the exit
@@ -13836,6 +13799,7 @@ function createAnimationState(visualElement) {
13836
13799
  let handledRemovedValues = false;
13837
13800
  const definitionList = Array.isArray(prop) ? prop : [prop];
13838
13801
  let resolvedValues = {};
13802
+ let out;
13839
13803
  if (activeDelta !== false) {
13840
13804
  for (const definition of definitionList) {
13841
13805
  const { transition, transitionEnd, ...target } = resolveVariant(visualElement, definition, getTypeCustom(visualElement, type)) || {};
@@ -13844,6 +13808,11 @@ function createAnimationState(visualElement) {
13844
13808
  ...target,
13845
13809
  ...transitionEnd,
13846
13810
  };
13811
+ /**
13812
+ * One out transition per type. With a list of labels,
13813
+ * the last one that sets out applies to all its values.
13814
+ */
13815
+ out = getOutTransition(transition) || out;
13847
13816
  }
13848
13817
  }
13849
13818
  const { prevResolvedValues } = typeState;
@@ -13859,12 +13828,18 @@ function createAnimationState(visualElement) {
13859
13828
  const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
13860
13829
  ? !shallowCompare(next, prev) || variantDidChange
13861
13830
  : next !== prev;
13831
+ let outTransition;
13862
13832
  if (valueHasChanged && (next === undefined || next === null)) {
13863
- removedKeys.add(key);
13833
+ /**
13834
+ * The highest-priority state a value leaves wins.
13835
+ */
13836
+ removedKeys.has(key) ||
13837
+ removedKeys.set(key, typeState.prevOut);
13864
13838
  }
13865
13839
  else if (valueHasChanged ||
13866
13840
  (next !== undefined && removedKeys.has(key))) {
13867
13841
  shouldAnimateType = true;
13842
+ outTransition = removedKeys.get(key) || initialOut;
13868
13843
  if (removedKeys.delete(key))
13869
13844
  handledRemovedValues = true;
13870
13845
  typeState.needsAnimating[key] = true;
@@ -13875,9 +13850,11 @@ function createAnimationState(visualElement) {
13875
13850
  else {
13876
13851
  typeState.protectedKeys[key] = true;
13877
13852
  }
13853
+ typeState.out[key] = outTransition;
13878
13854
  }
13879
13855
  typeState.prevProp = prop;
13880
13856
  typeState.prevResolvedValues = resolvedValues;
13857
+ typeState.prevOut = out;
13881
13858
  if (typeState.isActive) {
13882
13859
  encounteredKeys = { ...encounteredKeys, ...resolvedValues };
13883
13860
  }
@@ -13908,14 +13885,17 @@ function createAnimationState(visualElement) {
13908
13885
  * longer defines a value it once did, it stays where it is.
13909
13886
  */
13910
13887
  if (removedKeys.size) {
13911
- const { initial } = props;
13912
13888
  const fallbackAnimation = {};
13913
- const resolvedInitial = typeof initial !== "boolean" &&
13914
- resolveVariant(visualElement, Array.isArray(initial) ? initial[0] : initial, visualElement.presenceContext?.custom);
13915
- if (resolvedInitial && resolvedInitial.transition) {
13916
- fallbackAnimation.transition = resolvedInitial.transition;
13917
- }
13918
- removedKeys.forEach((key) => {
13889
+ const resolvedInitial = resolveInitial();
13890
+ let fallbackTransition = resolvedInitial?.transition;
13891
+ removedKeys.forEach((outTransition, key) => {
13892
+ if (outTransition) {
13893
+ fallbackTransition = {
13894
+ ...(fallbackTransition ||
13895
+ visualElement.getDefaultTransition()),
13896
+ [key]: outTransition,
13897
+ };
13898
+ }
13919
13899
  const motionValue = visualElement.getValue(key);
13920
13900
  if (motionValue)
13921
13901
  motionValue.liveStyle = true;
@@ -13947,6 +13927,9 @@ function createAnimationState(visualElement) {
13947
13927
  visualElement.baseTarget[key] = motionValue?.get();
13948
13928
  }
13949
13929
  });
13930
+ if (fallbackTransition) {
13931
+ fallbackAnimation.transition = fallbackTransition;
13932
+ }
13950
13933
  animations.push({ animation: fallbackAnimation });
13951
13934
  }
13952
13935
  const blockAnimation = (isMounting && visualElement.blockInitialAnimation) ||
@@ -14006,6 +13989,7 @@ function createState() {
14006
13989
  protectedKeys: {},
14007
13990
  needsAnimating: {},
14008
13991
  prevResolvedValues: {},
13992
+ out: {},
14009
13993
  };
14010
13994
  }
14011
13995
  return state;
@@ -14172,6 +14156,7 @@ exports.buildProjectionTransform = buildProjectionTransform;
14172
14156
  exports.buildSVGAttrs = buildSVGAttrs;
14173
14157
  exports.buildSVGPath = buildSVGPath;
14174
14158
  exports.buildTransform = buildTransform$1;
14159
+ exports.buildTransformer = buildTransformer;
14175
14160
  exports.calcAxisDelta = calcAxisDelta;
14176
14161
  exports.calcBoxDelta = calcBoxDelta;
14177
14162
  exports.calcChildStagger = calcChildStagger;