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
@@ -135,34 +135,21 @@
135
135
  ")",
136
136
  };
137
137
 
138
+ /**
139
+ * #FF0000 has two characters per channel, #F00 one, which is doubled.
140
+ */
141
+ const channel = (v, i, size) => {
142
+ const c = v.substring(1 + i * size, 1 + (i + 1) * size);
143
+ return size > 1 ? c : c + c;
144
+ };
138
145
  function parseHex(v) {
139
- let r = "";
140
- let g = "";
141
- let b = "";
142
- let a = "";
143
- // If we have 6 characters, ie #FF0000
144
- if (v.length > 5) {
145
- r = v.substring(1, 3);
146
- g = v.substring(3, 5);
147
- b = v.substring(5, 7);
148
- a = v.substring(7, 9);
149
- // Or we have 3 characters, ie #F00
150
- }
151
- else {
152
- r = v.substring(1, 2);
153
- g = v.substring(2, 3);
154
- b = v.substring(3, 4);
155
- a = v.substring(4, 5);
156
- r += r;
157
- g += g;
158
- b += b;
159
- a += a;
160
- }
146
+ const size = v.length > 5 ? 2 : 1;
147
+ const alpha = channel(v, 3, size);
161
148
  return {
162
- red: parseInt(r, 16),
163
- green: parseInt(g, 16),
164
- blue: parseInt(b, 16),
165
- alpha: a ? parseInt(a, 16) / 255 : 1,
149
+ red: parseInt(channel(v, 0, size), 16),
150
+ green: parseInt(channel(v, 1, size), 16),
151
+ blue: parseInt(channel(v, 2, size), 16),
152
+ alpha: alpha ? parseInt(alpha, 16) / 255 : 1,
166
153
  };
167
154
  }
168
155
  const hex = {
@@ -539,7 +526,6 @@
539
526
  return orderedOrigin;
540
527
  }
541
528
  const mixComplex = (origin, target) => {
542
- const template = complex.createTransformer(target);
543
529
  const originStats = analyseComplexValue(origin);
544
530
  const targetStats = analyseComplexValue(target);
545
531
  const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length &&
@@ -552,7 +538,7 @@
552
538
  !originStats.values.length)) {
553
539
  return mixVisibility(origin, target);
554
540
  }
555
- return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
541
+ return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), buildTransformer(targetStats));
556
542
  }
557
543
  else {
558
544
  motionUtils.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different");
@@ -844,37 +830,31 @@
844
830
  };
845
831
  }
846
832
 
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
- };
833
+ // Default spring physics
834
+ const defaultStiffness = 100;
835
+ const defaultDamping = 10;
836
+ const defaultMass = 1.0;
837
+ // Default duration/bounce-based options
838
+ const defaultDuration = 800; // in ms
839
+ const defaultBounce = 0.3;
840
+ const defaultVisualDuration = 0.3; // in seconds
841
+ // Rest thresholds
842
+ const restSpeedGranular = 0.01;
843
+ const restSpeedDefault = 2;
844
+ const restDeltaGranular = 0.005;
845
+ const restDeltaDefault = 0.5;
846
+ // Limits
847
+ const minDuration = 0.01; // in seconds
848
+ const maxDuration = 10.0; // in seconds
849
+ const minDamping = 0.05;
870
850
  /**
871
851
  * Maps bounce to a damping ratio as SwiftUI does: 0 is critically damped, and
872
852
  * it approaches undamped towards 1 and infinitely overdamped towards -1. Both
873
853
  * ends are limited so the spring still moves and settles.
874
854
  */
875
855
  const bounceToDampingRatio = (bounce) => bounce < 0
876
- ? 1 / Math.max(1 + bounce, springDefaults.minDamping)
877
- : Math.max(1 - bounce, springDefaults.minDamping);
856
+ ? 1 / Math.max(1 + bounce, minDamping)
857
+ : Math.max(1 - bounce, minDamping);
878
858
  /**
879
859
  * Scales an overdamped spring's undamped frequency so that, at its defining
880
860
  * time, it has as far left to go as the critically damped spring that's
@@ -917,12 +897,12 @@
917
897
  * ignore inherited velocity and only resolve without valid physics. Returns
918
898
  * NaN physics when the root search doesn't converge.
919
899
  */
920
- function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, }) {
900
+ function findSpring({ duration = defaultDuration, bounce = defaultBounce, }) {
921
901
  let envelope;
922
902
  let derivative;
923
- motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
903
+ motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
924
904
  const dampingRatio = bounceToDampingRatio(bounce);
925
- duration = motionUtils.clamp(springDefaults.minDuration, springDefaults.maxDuration, motionUtils.millisecondsToSeconds(duration));
905
+ duration = motionUtils.clamp(minDuration, maxDuration, motionUtils.millisecondsToSeconds(duration));
926
906
  if (dampingRatio < 1) {
927
907
  /**
928
908
  * Underdamped spring
@@ -1007,9 +987,9 @@
1007
987
  const validMass = resolvePhysics(options.mass);
1008
988
  const springOptions = {
1009
989
  ...options,
1010
- stiffness: validStiffness ?? springDefaults.stiffness,
1011
- damping: validDamping ?? springDefaults.damping,
1012
- mass: validMass ?? springDefaults.mass,
990
+ stiffness: validStiffness ?? defaultStiffness,
991
+ damping: validDamping ?? defaultDamping,
992
+ mass: validMass ?? defaultMass,
1013
993
  isResolvedFromDuration: false,
1014
994
  // stiffness/damping/mass overrides duration/bounce
1015
995
  isTimeDefined: (validStiffness ?? validDamping ?? validMass) === undefined &&
@@ -1037,13 +1017,13 @@
1037
1017
  */
1038
1018
  if (!isValidPhysics(springOptions.stiffness) ||
1039
1019
  !isValidPhysics(springOptions.damping, true)) {
1040
- springOptions.stiffness = springDefaults.stiffness;
1041
- springOptions.damping = springDefaults.damping;
1020
+ springOptions.stiffness = defaultStiffness;
1021
+ springOptions.damping = defaultDamping;
1042
1022
  }
1043
1023
  }
1044
1024
  return springOptions;
1045
1025
  }
1046
- function springGenerator(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
1026
+ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce = defaultBounce) {
1047
1027
  const options = typeof optionsOrVisualDuration !== "object"
1048
1028
  ? {
1049
1029
  visualDuration: optionsOrVisualDuration,
@@ -1093,14 +1073,10 @@
1093
1073
  const isGranularScale = Math.abs(s.delta) < 5;
1094
1074
  s.restSpeed =
1095
1075
  options.restSpeed ||
1096
- (isGranularScale
1097
- ? springDefaults.restSpeed.granular
1098
- : springDefaults.restSpeed.default);
1076
+ (isGranularScale ? restSpeedGranular : restSpeedDefault);
1099
1077
  s.restDelta =
1100
1078
  options.restDelta ||
1101
- (isGranularScale
1102
- ? springDefaults.restDelta.granular
1103
- : springDefaults.restDelta.default);
1079
+ (isGranularScale ? restDeltaGranular : restDeltaDefault);
1104
1080
  };
1105
1081
  setRestThresholds();
1106
1082
  let resolveSpring;
@@ -1169,11 +1145,16 @@
1169
1145
  * dampedAngularFreq * t passes 300, both terms decay at the damping
1170
1146
  * rate. Heavily overdamped drag springs (dragElastic: 0,
1171
1147
  * 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);
1148
+ * creep at stiffness / damping. It only applies when reached within
1149
+ * 300ms (a dampedAngularFreq of 1 rad/ms), so it reads as a stiff
1150
+ * spring snapping into place: any later and it cuts off a slow spring
1151
+ * that's visibly still moving (#1207). Negative bounce needs the
1152
+ * exact curve, so time-defined springs are exempt.
1153
+ */
1154
+ const limit = dampedAngularFreq < 1 || isTimeDefined
1155
+ ? Infinity
1156
+ : 300 / dampedAngularFreq;
1157
+ const decayAt = (rate, t) => Math.exp(t > limit ? (decay - rate) * limit - decay * t : -rate * t);
1177
1158
  const c = { S: 0, F: 0 };
1178
1159
  update = () => {
1179
1160
  const P = (s.velocity + decay * s.delta) / dampedAngularFreq;
@@ -1254,7 +1235,7 @@
1254
1235
  };
1255
1236
  let amplitude = power * velocity;
1256
1237
  const ideal = origin + amplitude;
1257
- const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
1238
+ const target = modifyTarget ? modifyTarget(ideal) : ideal;
1258
1239
  /**
1259
1240
  * If the target has changed we need to re-calculate the amplitude, otherwise
1260
1241
  * the animation will start from the wrong position.
@@ -1265,7 +1246,8 @@
1265
1246
  const applyFriction = (t) => {
1266
1247
  const delta = calcDelta(t);
1267
1248
  state.done = Math.abs(delta) <= restDelta;
1268
- state.value = state.done ? target : target + delta;
1249
+ // target + delta can be off from origin by a float error at t = 0
1250
+ state.value = state.done ? target : t ? target + delta : origin;
1269
1251
  };
1270
1252
  /**
1271
1253
  * Ideally this would resolve for t in a stateless way, we could
@@ -1711,17 +1693,12 @@
1711
1693
  this.generator = generator;
1712
1694
  }
1713
1695
  updateTime(timestamp) {
1714
- const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;
1715
- // Update currentTime
1716
- if (this.holdTime !== null) {
1717
- this.currentTime = this.holdTime;
1718
- }
1719
- else {
1720
- // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1721
- // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1722
- // example.
1723
- this.currentTime = animationTime;
1724
- }
1696
+ // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1697
+ // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1698
+ // example.
1699
+ this.currentTime =
1700
+ this.holdTime ??
1701
+ Math.round(timestamp - this.startTime) * this.playbackSpeed;
1725
1702
  }
1726
1703
  tick(timestamp, sample = false) {
1727
1704
  const { generator, totalDuration, calculatedDuration } = this;
@@ -1762,10 +1739,17 @@
1762
1739
  }
1763
1740
  const state = this.generate(this.currentTime, isInDelayPhase);
1764
1741
  let { done } = state;
1765
- if (!isInDelayPhase && calculatedDuration !== null) {
1742
+ /**
1743
+ * A generator that takes longer than maxGeneratorDuration to finish
1744
+ * has an Infinity duration, so played forwards it finishes when it
1745
+ * says it's done.
1746
+ */
1747
+ if (!isInDelayPhase) {
1766
1748
  done =
1767
1749
  this.playbackSpeed >= 0
1768
- ? this.currentTime >= totalDuration
1750
+ ? calculatedDuration < Infinity
1751
+ ? this.currentTime >= totalDuration
1752
+ : done
1769
1753
  : this.currentTime <= 0;
1770
1754
  }
1771
1755
  const isAnimationFinished = this.holdTime === null &&
@@ -1871,20 +1855,11 @@
1871
1855
  }
1872
1856
  return state;
1873
1857
  }
1874
- /**
1875
- * Allows the returned animation to be awaited or promise-chained. Currently
1876
- * resolves when the animation finishes at all but in a future update could/should
1877
- * reject if its cancels.
1878
- */
1879
- then(resolve, reject) {
1880
- return this.finished.then(resolve, reject);
1881
- }
1882
1858
  get duration() {
1883
1859
  return motionUtils.millisecondsToSeconds(this.calculatedDuration);
1884
1860
  }
1885
1861
  get iterationDuration() {
1886
- const { delay = 0 } = this.options || {};
1887
- return this.duration + motionUtils.millisecondsToSeconds(delay);
1862
+ return this.duration + motionUtils.millisecondsToSeconds(this.options.delay ?? 0);
1888
1863
  }
1889
1864
  get time() {
1890
1865
  return motionUtils.millisecondsToSeconds(this.currentTime);
@@ -1988,14 +1963,9 @@
1988
1963
  }
1989
1964
  teardown() {
1990
1965
  this.state = "idle";
1991
- this.stopDriver();
1992
- this.startTime = this.holdTime = null;
1993
- }
1994
- stopDriver() {
1995
- if (!this.driver)
1996
- return;
1997
- this.driver.stop();
1966
+ this.driver?.stop();
1998
1967
  this.driver = undefined;
1968
+ this.startTime = this.holdTime = null;
1999
1969
  }
2000
1970
  sample(sampleTime) {
2001
1971
  this.startTime = 0;
@@ -2252,23 +2222,15 @@
2252
2222
  if (!transform || transform === "none") {
2253
2223
  return defaultTransformValue(name);
2254
2224
  }
2255
- const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);
2256
- let parsers;
2257
- let match;
2258
- if (matrix3dMatch) {
2259
- parsers = matrix3dParsers;
2260
- match = matrix3dMatch;
2261
- }
2262
- else {
2263
- const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u);
2264
- parsers = matrix2dParsers;
2265
- match = matrix2dMatch;
2266
- }
2225
+ const match = transform.match(/^matrix(3d)?\(([-\d.e\s,]+)\)$/u);
2267
2226
  if (!match) {
2268
2227
  return defaultTransformValue(name);
2269
2228
  }
2270
- const valueParser = parsers[name];
2271
- const values = match[1].split(",").map(convertTransformToNumber);
2229
+ const valueParser = (match[1] ? matrix3dParsers : matrix2dParsers)[name];
2230
+ /**
2231
+ * parseFloat skips leading whitespace and stops at trailing whitespace.
2232
+ */
2233
+ const values = match[2].split(",").map((v) => parseFloat(v));
2272
2234
  return typeof valueParser === "function"
2273
2235
  ? valueParser(values)
2274
2236
  : values[valueParser];
@@ -2277,9 +2239,6 @@
2277
2239
  const { transform = "none" } = getComputedStyle(instance);
2278
2240
  return parseValueFromTransform(transform, name);
2279
2241
  };
2280
- function convertTransformToNumber(value) {
2281
- return parseFloat(value.trim());
2282
- }
2283
2242
 
2284
2243
  /**
2285
2244
  * Generate a list of every possible transform key.
@@ -2682,7 +2641,9 @@
2682
2641
  this.isPseudoElement = Boolean(pseudoElement);
2683
2642
  this.allowFlatten = allowFlatten;
2684
2643
  this.options = options;
2685
- motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2644
+ typeof process !== "undefined" &&
2645
+ "development" !== "production" &&
2646
+ motionUtils.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
2686
2647
  const transition = applyGeneratorOptions(options);
2687
2648
  this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
2688
2649
  if (transition.autoplay === false) {
@@ -2692,9 +2653,7 @@
2692
2653
  this.finishedTime = this.time;
2693
2654
  if (!pseudoElement) {
2694
2655
  const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
2695
- if (this.updateMotionValue) {
2696
- this.updateMotionValue(keyframe);
2697
- }
2656
+ this.updateMotionValue?.(keyframe);
2698
2657
  /**
2699
2658
  * If we can, we want to commit the final style as set by the user,
2700
2659
  * rather than the computed keyframe value supplied by the animation.
@@ -3015,6 +2974,7 @@
3015
2974
  if (!isOriginAnimatable || !isTargetAnimatable) {
3016
2975
  // Only build the message when we're going to warn
3017
2976
  isOriginAnimatable !== isTargetAnimatable &&
2977
+ "development" !== "production" &&
3018
2978
  motionUtils.warning(false, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable");
3019
2979
  return false;
3020
2980
  }
@@ -3029,13 +2989,16 @@
3029
2989
 
3030
2990
  /**
3031
2991
  * A list of values that can be hardware-accelerated.
2992
+ *
2993
+ * Colors aren't included: WAAPI mixes them in sRGB, but JS animations
2994
+ * (and the sampler that estimates a WAAPI value on interrupt) mix them
2995
+ * in linear color space, so interrupting one would visibly jump.
3032
2996
  */
3033
2997
  const acceleratedValues = new Set([
3034
2998
  "opacity",
3035
2999
  "clipPath",
3036
3000
  "filter",
3037
3001
  "transform",
3038
- "backgroundColor",
3039
3002
  ]);
3040
3003
 
3041
3004
  const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;
@@ -3127,6 +3090,20 @@
3127
3090
  transformPerspective: "perspective",
3128
3091
  };
3129
3092
  const numTransforms = transformPropOrder.length;
3093
+ /**
3094
+ * Cache of `translateX(`-style openers so each transform function is a few
3095
+ * string concatenations rather than a template.
3096
+ */
3097
+ const openers = {};
3098
+ /**
3099
+ * A transform function, e.g. `translateX(10px)` for `x: 10`.
3100
+ */
3101
+ const transformFunction = (key, value, valueAsType = getValueAsType(value, transformValueTypes[key])) => (openers[key] || (openers[key] = (translateAlias[key] || key) + "(")) + valueAsType + ")";
3102
+ /**
3103
+ * Whether a transform value is at its default, so can be left out.
3104
+ */
3105
+ const isDefaultTransform = (key, value) => (typeof value === "number" ? value : parseFloat(value)) ===
3106
+ (key.startsWith("scale") ? 1 : 0);
3130
3107
  /**
3131
3108
  * Build a CSS transform style from individual x/y/scale etc properties.
3132
3109
  *
@@ -3136,7 +3113,6 @@
3136
3113
  function buildTransform$1(latestValues, transform, transformTemplate) {
3137
3114
  // The transform string we're going to build into.
3138
3115
  let transformString = "";
3139
- let transformIsDefault = true;
3140
3116
  /**
3141
3117
  * Loop over all possible transforms in order, adding the ones that
3142
3118
  * are present to the transform string.
@@ -3146,24 +3122,11 @@
3146
3122
  const value = latestValues[key];
3147
3123
  if (value === undefined)
3148
3124
  continue;
3149
- let valueIsDefault = true;
3150
- if (typeof value === "number") {
3151
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3152
- }
3153
- else {
3154
- const parsed = parseFloat(value);
3155
- valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
3156
- }
3157
- if (!valueIsDefault || transformTemplate) {
3158
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
3159
- if (!valueIsDefault) {
3160
- transformIsDefault = false;
3161
- const transformName = translateAlias[key] || key;
3162
- transformString += `${transformName}(${valueAsType}) `;
3163
- }
3164
- if (transformTemplate) {
3165
- transform[key] = valueAsType;
3166
- }
3125
+ const valueAsType = transformTemplate &&
3126
+ (transform[key] = getValueAsType(value, numberValueTypes[key]));
3127
+ if (!isDefaultTransform(key, value)) {
3128
+ transformString +=
3129
+ transformFunction(key, value, valueAsType || undefined) + " ";
3167
3130
  }
3168
3131
  }
3169
3132
  // `pathRotation` composes onto `rotate` as a separate additive term so
@@ -3171,19 +3134,14 @@
3171
3134
  // `transformPropOrder`.
3172
3135
  const pathRotation = latestValues.pathRotation;
3173
3136
  if (pathRotation) {
3174
- transformIsDefault = false;
3175
- transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
3137
+ transformString += transformFunction("rotate", pathRotation);
3176
3138
  }
3177
3139
  transformString = transformString.trim();
3178
3140
  // If we have a custom `transform` template, pass our transform values and
3179
3141
  // generated transformString to that before returning
3180
- if (transformTemplate) {
3181
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
3182
- }
3183
- else if (transformIsDefault) {
3184
- transformString = "none";
3185
- }
3186
- return transformString;
3142
+ return transformTemplate
3143
+ ? transformTemplate(transform, transformString)
3144
+ : transformString || "none";
3187
3145
  }
3188
3146
 
3189
3147
  const transformGroups = new WeakMap();
@@ -3525,27 +3483,30 @@
3525
3483
  return values;
3526
3484
  };
3527
3485
  /**
3528
- * Build the transform at a timestamp. Unlike buildTransform, every key
3529
- * is written, even at its default, so each keyframe has the same list
3530
- * of functions and the browser interpolates them one by one.
3486
+ * Build a transform from values in transformPropOrder. For a keyframe,
3487
+ * every key is written, even at its default, so each keyframe has the
3488
+ * same list of functions and the browser interpolates them one by one.
3489
+ * As an inline style, defaults are left out, as buildTransform does.
3531
3490
  */
3532
- const compose = (timestamp, settled) => {
3491
+ const toTransform = (values, isStyle) => {
3533
3492
  let transform = "";
3534
- const values = valuesAt(timestamp, settled);
3535
3493
  for (const key in values) {
3536
- transform +=
3537
- (translateAlias[key] || key) +
3538
- "(" +
3539
- getValueAsType(values[key], numberValueTypes[key]) +
3540
- ") ";
3494
+ const value = values[key];
3495
+ if (!isStyle || !isDefaultTransform(key, value)) {
3496
+ transform += transformFunction(key, value) + " ";
3497
+ }
3541
3498
  }
3542
- return transform || "none";
3499
+ return (isStyle ? transform.trim() : transform) || "none";
3543
3500
  };
3501
+ /**
3502
+ * Build the transform at a timestamp.
3503
+ */
3504
+ const compose = (timestamp, settled) => toTransform(valuesAt(timestamp, settled));
3544
3505
  /**
3545
3506
  * Write the transform as an inline style, as the renderer would.
3546
3507
  */
3547
3508
  const commit = (values = valuesAt()) => {
3548
- element.style.transform = buildTransform$1(values, {});
3509
+ element.style.transform = toTransform(values, true);
3549
3510
  };
3550
3511
  /**
3551
3512
  * Cancel the WAAPI animations, by default first committing the
@@ -3556,6 +3517,13 @@
3556
3517
  segments.forEach(({ animation }) => animation.cancel());
3557
3518
  segments = [];
3558
3519
  };
3520
+ /**
3521
+ * A WAAPI animation that add() starts by setting its startTime. Playing
3522
+ * it first, as element.animate() does, would leave WebKit holding that
3523
+ * play's ready time once startTime ends the play, and it uses that for
3524
+ * the next updatePlaybackRate(), so the animation would jump.
3525
+ */
3526
+ const create = (keyframes, options) => new Animation(new KeyframeEffect(element, keyframes, options));
3559
3527
  const add = (animation, offset, end = Infinity) => {
3560
3528
  const segment = { animation, offset, end };
3561
3529
  animation.startTime = time.now() + offset;
@@ -3748,7 +3716,7 @@
3748
3716
  commit(valuesAt(from, settled));
3749
3717
  keyframes = null;
3750
3718
  }
3751
- return element.animate(keyframes, {
3719
+ return create(keyframes, {
3752
3720
  ...options,
3753
3721
  duration: to - from,
3754
3722
  easing: easing || "linear",
@@ -3838,9 +3806,7 @@
3838
3806
  * empty animations that end with them.
3839
3807
  */
3840
3808
  ends.forEach((trackEnd) => trackEnd < end - 1 &&
3841
- add(element.animate(null, {
3842
- duration: trackEnd - now,
3843
- }), 0, trackEnd - now));
3809
+ add(create(null, { duration: trackEnd - now }), 0, trackEnd - now));
3844
3810
  }
3845
3811
  if (cycle) {
3846
3812
  /**
@@ -3914,12 +3880,29 @@
3914
3880
  if (isDone)
3915
3881
  continue;
3916
3882
  const local = elapsed - offset;
3917
- if (rate) {
3883
+ if (rate &&
3884
+ animation.updatePlaybackRate &&
3885
+ animation.playState === "running" &&
3886
+ Math.abs(Number(animation.currentTime) - local) < 20) {
3887
+ /**
3888
+ * Only the speed changed. Setting playbackRate and
3889
+ * startTime restarts a running compositor animation, which
3890
+ * can render the underlying value for a frame.
3891
+ */
3892
+ animation.playbackRate !== rate &&
3893
+ animation.updatePlaybackRate(rate);
3894
+ }
3895
+ else if (rate) {
3918
3896
  animation.playbackRate = rate;
3919
3897
  animation.startTime = now - local / rate;
3920
3898
  }
3921
3899
  else {
3922
- animation.pause();
3900
+ /**
3901
+ * Hold it without pause(), whose pending pause setting
3902
+ * currentTime would end at once, leaving WebKit holding its
3903
+ * ready time (see create()).
3904
+ */
3905
+ animation.startTime = null;
3923
3906
  animation.currentTime = local;
3924
3907
  }
3925
3908
  }
@@ -4110,9 +4093,8 @@
4110
4093
  * If we can't animate this value with the resolved keyframes
4111
4094
  * then we should complete it immediately.
4112
4095
  */
4113
- let canAnimateValue = true;
4114
- if (!canAnimate(keyframes, name, type, velocity)) {
4115
- canAnimateValue = false;
4096
+ const canAnimateValue = canAnimate(keyframes, name, type, velocity);
4097
+ if (!canAnimateValue) {
4116
4098
  if (motionUtils.MotionGlobalConfig.instantAnimations || !delay) {
4117
4099
  onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe));
4118
4100
  }
@@ -4256,9 +4238,7 @@
4256
4238
  this.animation.complete();
4257
4239
  }
4258
4240
  cancel() {
4259
- if (this._animation) {
4260
- this.animation.cancel();
4261
- }
4241
+ this._animation?.cancel();
4262
4242
  this.keyframeResolver?.cancel();
4263
4243
  }
4264
4244
  }
@@ -4441,7 +4421,7 @@
4441
4421
  this.setCurrent(v);
4442
4422
  // Update update subscribers
4443
4423
  if (this.current !== this.prev) {
4444
- this.notifyChange();
4424
+ this.dirty();
4445
4425
  if (this.dependents) {
4446
4426
  for (const dependent of this.dependents) {
4447
4427
  dependent.dirty();
@@ -4579,12 +4559,9 @@
4579
4559
  * @public
4580
4560
  */
4581
4561
  set(v) {
4582
- if (!this.passiveEffect) {
4583
- this.updateAndNotify(v);
4584
- }
4585
- else {
4586
- this.passiveEffect(v, this.updateAndNotify);
4587
- }
4562
+ this.passiveEffect
4563
+ ? this.passiveEffect(v, this.updateAndNotify)
4564
+ : this.updateAndNotify(v);
4588
4565
  }
4589
4566
  setWithVelocity(prev, current, delta) {
4590
4567
  this.set(current);
@@ -4601,13 +4578,9 @@
4601
4578
  this.prev = v;
4602
4579
  this.prevUpdatedAt = this.prevFrameValue = undefined;
4603
4580
  endAnimation && this.stop();
4604
- if (this.stopPassiveEffect)
4605
- this.stopPassiveEffect();
4581
+ this.stopPassiveEffect?.();
4606
4582
  }
4607
4583
  dirty() {
4608
- this.notifyChange();
4609
- }
4610
- notifyChange() {
4611
4584
  const { current, changeSubscriber } = this;
4612
4585
  /**
4613
4586
  * One or the other exists. Subscribing during the direct
@@ -4622,15 +4595,10 @@
4622
4595
  }
4623
4596
  }
4624
4597
  addDependent(dependent) {
4625
- if (!this.dependents) {
4626
- this.dependents = new Set();
4627
- }
4628
- this.dependents.add(dependent);
4598
+ (this.dependents || (this.dependents = new Set())).add(dependent);
4629
4599
  }
4630
4600
  removeDependent(dependent) {
4631
- if (this.dependents) {
4632
- this.dependents.delete(dependent);
4633
- }
4601
+ this.dependents?.delete(dependent);
4634
4602
  }
4635
4603
  /**
4636
4604
  * Returns the latest state of `MotionValue`
@@ -4640,9 +4608,7 @@
4640
4608
  * @public
4641
4609
  */
4642
4610
  get() {
4643
- if (collectMotionValues.current) {
4644
- collectMotionValues.current.push(this);
4645
- }
4611
+ collectMotionValues.current?.push(this);
4646
4612
  /**
4647
4613
  * A value animating on the compositor isn't updated every frame,
4648
4614
  * so read it from its animation.
@@ -4708,7 +4674,7 @@
4708
4674
  isComplete = true;
4709
4675
  this.events.animationComplete?.notify();
4710
4676
  if (this.animation === animation)
4711
- this.clearAnimation();
4677
+ this.animation = undefined;
4712
4678
  resolve();
4713
4679
  });
4714
4680
  if (!isComplete)
@@ -4724,11 +4690,10 @@
4724
4690
  stop() {
4725
4691
  if (this.animation) {
4726
4692
  this.animation.stop();
4727
- if (this.events.animationCancel) {
4728
- this.events.animationCancel.notify();
4729
- }
4693
+ this.events.animationCancel?.notify();
4730
4694
  }
4731
- this.clearAnimation();
4695
+ // Assign rather than delete to keep the object's shape stable
4696
+ this.animation = undefined;
4732
4697
  }
4733
4698
  /**
4734
4699
  * Returns `true` if this value is currently animating.
@@ -4738,10 +4703,6 @@
4738
4703
  isAnimating() {
4739
4704
  return !!this.animation;
4740
4705
  }
4741
- clearAnimation() {
4742
- // Assign rather than delete to keep the object's shape stable
4743
- this.animation = undefined;
4744
- }
4745
4706
  /**
4746
4707
  * Destroy and clean up subscribers to this `MotionValue`.
4747
4708
  *
@@ -4756,9 +4717,7 @@
4756
4717
  this.events.destroy?.notify();
4757
4718
  this.clearListeners();
4758
4719
  this.stop();
4759
- if (this.stopPassiveEffect) {
4760
- this.stopPassiveEffect();
4761
- }
4720
+ this.stopPassiveEffect?.();
4762
4721
  }
4763
4722
  }
4764
4723
  function motionValue(init, options) {
@@ -4836,6 +4795,7 @@
4836
4795
  "repeatDelay",
4837
4796
  "from",
4838
4797
  "elapsed",
4798
+ "out",
4839
4799
  ]);
4840
4800
  /**
4841
4801
  * Decide whether a transition is defined on a given Transition.
@@ -5306,7 +5266,7 @@
5306
5266
  }
5307
5267
  const valueTransition = {
5308
5268
  delay,
5309
- ...getValueTransition(transition || {}, key),
5269
+ ...getValueTransition(animationTypeState?.out[key] || transition || {}, key),
5310
5270
  };
5311
5271
  if (skipAnimations)
5312
5272
  valueTransition.skipAnimations = true;
@@ -5476,8 +5436,9 @@
5476
5436
  }
5477
5437
 
5478
5438
  class DOMKeyframesResolver extends KeyframeResolver {
5479
- constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
5480
- super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
5439
+ constructor() {
5440
+ super(...arguments);
5441
+ this.isAsync = true;
5481
5442
  }
5482
5443
  /**
5483
5444
  * Keyframes that don't need reading from the DOM, or measuring,
@@ -5505,7 +5466,7 @@
5505
5466
  }
5506
5467
  readKeyframes() {
5507
5468
  const { unresolvedKeyframes, element, name } = this;
5508
- if (!element || !element.current)
5469
+ if (!element?.current)
5509
5470
  return;
5510
5471
  super.readKeyframes();
5511
5472
  /**
@@ -5600,11 +5561,10 @@
5600
5561
  }
5601
5562
  measureInitialState() {
5602
5563
  const { element, unresolvedKeyframes, name } = this;
5603
- if (!element || !element.current)
5564
+ if (!element?.current)
5604
5565
  return;
5605
- if (name === "height") {
5566
+ if (name === "height")
5606
5567
  this.suspendedScrollY = window.pageYOffset;
5607
- }
5608
5568
  this.measuredOrigin = this.measure();
5609
5569
  unresolvedKeyframes[0] = this.measuredOrigin;
5610
5570
  // Set final key frame to measure after next render
@@ -5615,7 +5575,7 @@
5615
5575
  }
5616
5576
  measureEndState() {
5617
5577
  const { element, unresolvedKeyframes } = this;
5618
- if (!element || !element.current)
5578
+ if (!element?.current)
5619
5579
  return;
5620
5580
  this.motionValue?.jump(this.measuredOrigin, false);
5621
5581
  const finalKeyframeIndex = unresolvedKeyframes.length - 1;
@@ -5624,14 +5584,6 @@
5624
5584
  if (finalKeyframe !== null && this.finalKeyframe === undefined) {
5625
5585
  this.finalKeyframe = finalKeyframe;
5626
5586
  }
5627
- // If we removed transform values, reapply them before the next render
5628
- if (this.removedTransforms?.length) {
5629
- this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
5630
- element
5631
- .getValue(unsetTransformName)
5632
- .set(unsetTransformValue);
5633
- });
5634
- }
5635
5587
  this.resolveNoneKeyframes();
5636
5588
  }
5637
5589
  }
@@ -5736,7 +5688,8 @@
5736
5688
  */
5737
5689
  const effects = [];
5738
5690
  function addEffect(effect) {
5739
- motionUtils.invariant(typeof effect.test === "function" && typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5691
+ motionUtils.invariant(typeof effect.test === "function" &&
5692
+ typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
5740
5693
  removeEffect(effect);
5741
5694
  effects.unshift(effect);
5742
5695
  }
@@ -6063,11 +6016,6 @@
6063
6016
  });
6064
6017
  }
6065
6018
 
6066
- /**
6067
- * Cache of `translateX(`-style openers so each render is a few string
6068
- * concatenations rather than a template per transform.
6069
- */
6070
- const openers = {};
6071
6019
  function buildTransform(state) {
6072
6020
  let transform = "";
6073
6021
  const { transformKeys: keys = [], transformValues: values = {} } = state;
@@ -6080,14 +6028,8 @@
6080
6028
  const value = values[key].getCurrent();
6081
6029
  if (value === undefined)
6082
6030
  continue;
6083
- const parsed = typeof value === "number" ? value : parseFloat(value);
6084
- if (parsed !== (key.startsWith("scale") ? 1 : 0)) {
6085
- transform +=
6086
- (transform && " ") +
6087
- (openers[key] ||
6088
- (openers[key] = (translateAlias[key] || key) + "(")) +
6089
- getValueAsType(value, transformValueTypes[key]) +
6090
- ")";
6031
+ if (!isDefaultTransform(key, value)) {
6032
+ transform += (transform && " ") + transformFunction(key, value);
6091
6033
  }
6092
6034
  }
6093
6035
  // See build-transform.ts: additive `rotate()` so user `rotate` isn't
@@ -6095,10 +6037,7 @@
6095
6037
  const pathRotation = state.get("pathRotation")?.get();
6096
6038
  if (pathRotation) {
6097
6039
  transform +=
6098
- (transform && " ") +
6099
- "rotate(" +
6100
- getValueAsType(pathRotation, transformValueTypes.pathRotation) +
6101
- ")";
6040
+ (transform && " ") + transformFunction("rotate", pathRotation);
6102
6041
  }
6103
6042
  return transform || "none";
6104
6043
  }
@@ -6501,10 +6440,24 @@
6501
6440
  !isIdentityScale(scaleX) ||
6502
6441
  !isIdentityScale(scaleY));
6503
6442
  }
6443
+ /**
6444
+ * Rotations and skews, which projection can't correct for.
6445
+ */
6446
+ const angleTransforms = [
6447
+ "rotate",
6448
+ "rotateX",
6449
+ "rotateY",
6450
+ "rotateZ",
6451
+ "skewX",
6452
+ "skewY",
6453
+ ];
6504
6454
  function hasTransform(values) {
6505
6455
  return (hasScale(values) ||
6506
6456
  has2DTranslate(values) ||
6507
- values.z ||
6457
+ hasDistortingTransform(values));
6458
+ }
6459
+ function hasDistortingTransform(values) {
6460
+ return (values.z ||
6508
6461
  values.rotate ||
6509
6462
  values.rotateX ||
6510
6463
  values.rotateY ||
@@ -6557,6 +6510,11 @@
6557
6510
  * in a tree upon our box before then calculating how to project it into our desired viewport-relative box
6558
6511
  *
6559
6512
  * This is the final nested loop within updateLayoutDelta for future refactoring
6513
+ *
6514
+ * isSharedTransition is true for a shared layout animation in page space, which
6515
+ * also applies ancestor scroll and transforms. Or it's the layoutRoot a shared
6516
+ * animation is relative to, so only transforms of ancestors not shared with it
6517
+ * (or above it) are applied.
6560
6518
  */
6561
6519
  function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
6562
6520
  const treeLength = treePath.length;
@@ -6573,13 +6531,10 @@
6573
6531
  * TODO: Prefer to remove this, but currently we have motion components with
6574
6532
  * display: contents in Framer.
6575
6533
  */
6576
- const { visualElement } = node.options;
6577
- if (visualElement &&
6578
- visualElement.props.style &&
6579
- visualElement.props.style.display === "contents") {
6534
+ if (node.options.visualElement?.props.style?.display === "contents") {
6580
6535
  continue;
6581
6536
  }
6582
- if (isSharedTransition &&
6537
+ if (isSharedTransition === true &&
6583
6538
  node.options.layoutScroll &&
6584
6539
  node.scroll &&
6585
6540
  node !== node.root) {
@@ -6593,7 +6548,9 @@
6593
6548
  // Apply each ancestor's calculated delta into this component's recorded layout box
6594
6549
  applyBoxDelta(box, delta);
6595
6550
  }
6596
- if (isSharedTransition && hasTransform(node.latestValues)) {
6551
+ if (isSharedTransition &&
6552
+ (isSharedTransition.path?.[i] || isSharedTransition) !== node &&
6553
+ hasTransform(node.latestValues)) {
6597
6554
  transformBox(box, node.latestValues, node.layout?.layoutBox);
6598
6555
  }
6599
6556
  }
@@ -6867,15 +6824,6 @@
6867
6824
  const asNumber = (v) => typeof v === "number" ? v : parseFloat(v);
6868
6825
 
6869
6826
  const numBorders = cornerRadiusProps.length;
6870
- const mixedTransforms = [
6871
- "rotate",
6872
- "rotateX",
6873
- "rotateY",
6874
- "rotateZ",
6875
- "skewX",
6876
- "skewY",
6877
- ];
6878
- const numMixedTransforms = mixedTransforms.length;
6879
6827
  const isPx = (value) => typeof value === "number" || px.test(value);
6880
6828
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
6881
6829
  if (shouldCrossfadeOpacity) {
@@ -6913,8 +6861,8 @@
6913
6861
  * Mix rotation and skew. These can't be projected, so mix them every
6914
6862
  * frame rather than leaving them frozen at the animation-start snapshot.
6915
6863
  */
6916
- for (let i = 0; i < numMixedTransforms; i++) {
6917
- const key = mixedTransforms[i];
6864
+ for (let i = 0; i < angleTransforms.length; i++) {
6865
+ const key = angleTransforms[i];
6918
6866
  if (follow[key] || lead[key]) {
6919
6867
  target[key] = mixNumber$1(follow[key] || 0, lead[key] || 0, progress);
6920
6868
  }
@@ -6997,8 +6945,8 @@
6997
6945
  }
6998
6946
  }
6999
6947
  function calcBoxDelta(delta, source, target, origin) {
7000
- calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);
7001
- calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);
6948
+ calcAxisDelta(delta.x, source.x, target.x, origin?.originX);
6949
+ calcAxisDelta(delta.y, source.y, target.y, origin?.originY);
7002
6950
  }
7003
6951
  function calcRelativeAxis(target, relative, parent, anchor = 0) {
7004
6952
  const anchorPoint = anchor
@@ -7068,8 +7016,8 @@
7068
7016
  * and acts as a bridge between motion values and removeAxisDelta
7069
7017
  */
7070
7018
  function removeBoxTransforms(box, transforms, originBox, sourceBox) {
7071
- removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);
7072
- removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);
7019
+ removeAxisTransforms(box.x, transforms, xKeys, originBox?.x, sourceBox?.x);
7020
+ removeAxisTransforms(box.y, transforms, yKeys, originBox?.y, sourceBox?.y);
7073
7021
  }
7074
7022
 
7075
7023
  const createAxisDelta = () => ({
@@ -7299,24 +7247,18 @@
7299
7247
  transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7300
7248
  }
7301
7249
  if (latestTransform) {
7302
- const { transformPerspective, rotate, pathRotation, rotateX, rotateY, rotateZ, skewX, skewY, } = latestTransform;
7250
+ const { transformPerspective } = latestTransform;
7303
7251
  if (transformPerspective)
7304
7252
  transform = `perspective(${transformPerspective}px) ${transform}`;
7305
- if (rotate)
7306
- transform += `rotate(${rotate}deg) `;
7307
- // Additive `rotate()` so user `rotate` isn't clobbered.
7308
- if (pathRotation)
7309
- transform += `rotate(${pathRotation}deg) `;
7310
- if (rotateX)
7311
- transform += `rotateX(${rotateX}deg) `;
7312
- if (rotateY)
7313
- transform += `rotateY(${rotateY}deg) `;
7314
- if (rotateZ)
7315
- transform += `rotateZ(${rotateZ}deg) `;
7316
- if (skewX)
7317
- transform += `skewX(${skewX}deg) `;
7318
- if (skewY)
7319
- transform += `skewY(${skewY}deg) `;
7253
+ for (let i = 0; i < angleTransforms.length; i++) {
7254
+ const key = angleTransforms[i];
7255
+ const value = latestTransform[key];
7256
+ if (value)
7257
+ transform += `${key}(${value}deg) `;
7258
+ // Additive `rotate()` so user `rotate` isn't clobbered.
7259
+ if (!i && latestTransform.pathRotation)
7260
+ transform += `rotate(${latestTransform.pathRotation}deg) `;
7261
+ }
7320
7262
  }
7321
7263
  /**
7322
7264
  * Apply scale to match the size of the element to the size we want it.
@@ -7379,7 +7321,10 @@
7379
7321
  calculatedTargetDeltas: 0,
7380
7322
  calculatedProjections: 0,
7381
7323
  };
7382
- const transformAxes = ["", "X", "Y", "Z"];
7324
+ /**
7325
+ * Transforms that distort an element's layout, so must be reset before measuring.
7326
+ */
7327
+ const distortingTransforms = ["z", "skew", "skewZ"];
7383
7328
  /**
7384
7329
  * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
7385
7330
  * which has a noticeable difference in spring animations
@@ -7587,8 +7532,7 @@
7587
7532
  return this.eventHandlers.get(name).add(handler);
7588
7533
  }
7589
7534
  notifyListeners(name, ...args) {
7590
- const subscriptionManager = this.eventHandlers.get(name);
7591
- subscriptionManager && subscriptionManager.notify(...args);
7535
+ this.eventHandlers.get(name)?.notify(...args);
7592
7536
  }
7593
7537
  hasListeners(name) {
7594
7538
  return this.eventHandlers.has(name);
@@ -7606,7 +7550,7 @@
7606
7550
  visualElement.mount(instance);
7607
7551
  }
7608
7552
  this.root.nodes.add(this);
7609
- this.parent && this.parent.children.add(this);
7553
+ this.parent?.children.add(this);
7610
7554
  if (this.root.hasTreeAnimated && (layout || layoutId)) {
7611
7555
  this.isLayoutDirty = true;
7612
7556
  }
@@ -7624,7 +7568,7 @@
7624
7568
  return;
7625
7569
  innerWidth = newInnerWidth;
7626
7570
  this.root.updateBlockedByResize = true;
7627
- cancelDelay && cancelDelay();
7571
+ cancelDelay?.();
7628
7572
  cancelDelay = delay(resizeUnblockUpdate, 250);
7629
7573
  if (globalProjectionState.hasAnimatedSinceResize) {
7630
7574
  globalProjectionState.hasAnimatedSinceResize = false;
@@ -7715,9 +7659,7 @@
7715
7659
  if (!hasLayoutChanged) {
7716
7660
  finishAnimation(this);
7717
7661
  }
7718
- if (this.isLead() && this.options.onExitComplete) {
7719
- this.options.onExitComplete();
7720
- }
7662
+ this.isLead() && this.options.onExitComplete?.();
7721
7663
  }
7722
7664
  this.targetLayout = newLayout;
7723
7665
  });
@@ -7725,9 +7667,8 @@
7725
7667
  unmount() {
7726
7668
  this.options.layoutId && this.willUpdate();
7727
7669
  this.root.nodes.remove(this);
7728
- const stack = this.getStack();
7729
- stack && stack.remove(this);
7730
- this.parent && this.parent.children.delete(this);
7670
+ this.getStack()?.remove(this);
7671
+ this.parent?.children.delete(this);
7731
7672
  this.instance = undefined;
7732
7673
  this.eventHandlers.clear();
7733
7674
  this.hasLayoutListener = false;
@@ -7748,7 +7689,7 @@
7748
7689
  if (this.isUpdateBlocked())
7749
7690
  return;
7750
7691
  this.isUpdating = true;
7751
- this.nodes && this.nodes.forEach(resetSkewAndRotation);
7692
+ this.nodes?.forEach(resetSkewAndRotation);
7752
7693
  this.animationId++;
7753
7694
  }
7754
7695
  getTransformTemplate() {
@@ -7758,7 +7699,7 @@
7758
7699
  willUpdate(shouldNotifyListeners = true) {
7759
7700
  this.root.hasTreeAnimated = true;
7760
7701
  if (this.root.isUpdateBlocked()) {
7761
- this.options.onExitComplete && this.options.onExitComplete();
7702
+ this.options.onExitComplete?.();
7762
7703
  return;
7763
7704
  }
7764
7705
  /**
@@ -7975,24 +7916,23 @@
7975
7916
  this.projectionDelta = undefined;
7976
7917
  this.notifyListeners("measure", this.layout.layoutBox);
7977
7918
  const { visualElement } = this.options;
7978
- visualElement &&
7979
- visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);
7919
+ visualElement?.notify("LayoutMeasure", this.layout.layoutBox, prevLayout?.layoutBox);
7980
7920
  }
7981
7921
  updateScroll(phase = "measure") {
7982
- let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
7983
- if (this.scroll &&
7984
- this.scroll.animationId === this.root.animationId &&
7985
- this.scroll.phase === phase) {
7986
- needsMeasurement = false;
7987
- }
7988
- if (needsMeasurement && this.instance) {
7989
- const isRoot = checkIsScrollRoot(this.instance);
7922
+ const { scroll, instance } = this;
7923
+ const { animationId } = this.root;
7924
+ if (this.options.layoutScroll &&
7925
+ instance &&
7926
+ !(scroll &&
7927
+ scroll.animationId === animationId &&
7928
+ scroll.phase === phase)) {
7929
+ const isRoot = checkIsScrollRoot(instance);
7990
7930
  this.scroll = {
7991
- animationId: this.root.animationId,
7931
+ animationId,
7992
7932
  phase,
7993
7933
  isRoot,
7994
- offset: measureScroll(this.instance),
7995
- wasRoot: this.scroll ? this.scroll.isRoot : isRoot,
7934
+ offset: measureScroll(instance),
7935
+ wasRoot: scroll ? scroll.isRoot : isRoot,
7996
7936
  };
7997
7937
  }
7998
7938
  }
@@ -8082,10 +8022,10 @@
8082
8022
  }
8083
8023
  return boxWithoutScroll;
8084
8024
  }
8085
- applyTransform(box, transformOnly = false, output, skipOwnTransform) {
8025
+ applyTransform(box, transformOnly = false, output, skipOwnTransform, start = 0) {
8086
8026
  const withTransforms = output || createBox();
8087
8027
  copyBoxInto(withTransforms, box);
8088
- for (let i = 0; i < this.path.length; i++) {
8028
+ for (let i = start; i < this.path.length; i++) {
8089
8029
  const node = this.path[i];
8090
8030
  if (!transformOnly &&
8091
8031
  node.options.layoutScroll &&
@@ -8257,8 +8197,13 @@
8257
8197
  this.attemptToResolveRelativeTarget = false;
8258
8198
  if (this.options.layoutAnchor !== false &&
8259
8199
  relativeParent &&
8260
- Boolean(relativeParent.resumingFrom) ===
8261
- Boolean(this.resumingFrom) &&
8200
+ (!relativeParent.resumingFrom === !this.resumingFrom ||
8201
+ /**
8202
+ * Shared layout animations within a layoutRoot
8203
+ * animate relative to it.
8204
+ */
8205
+ (relativeParent.options.layoutRoot &&
8206
+ !relativeParent.resumingFrom)) &&
8262
8207
  !relativeParent.options.layoutScroll &&
8263
8208
  relativeParent.target &&
8264
8209
  this.animationProgress !== 1) {
@@ -8338,7 +8283,7 @@
8338
8283
  * If this section of the tree isn't animating we can
8339
8284
  * delete our target sources for the following frame.
8340
8285
  */
8341
- this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||
8286
+ this.isTreeAnimating = Boolean(this.parent?.isTreeAnimating ||
8342
8287
  this.currentAnimation ||
8343
8288
  this.pendingAnimation);
8344
8289
  if (!this.isTreeAnimating) {
@@ -8359,8 +8304,17 @@
8359
8304
  /**
8360
8305
  * Apply all the parent deltas to this box to produce the corrected box. This
8361
8306
  * is the layout box, as it will appear on screen as a result of the transforms of its parents.
8307
+ *
8308
+ * A shared target is usually in page space, so ancestor transforms are applied
8309
+ * too. But a target relative to a parent that isn't itself shared (like a
8310
+ * layoutRoot) is in that parent's layout space. So the transforms of the
8311
+ * parent and its ancestors, which move both elements alike, are skipped,
8312
+ * but those of other ancestors (between it and either element) apply.
8362
8313
  */
8363
- applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
8314
+ applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared &&
8315
+ (lead.relativeTarget && !lead.relativeParent.resumingFrom
8316
+ ? lead.relativeParent
8317
+ : true));
8364
8318
  /**
8365
8319
  * If this layer needs to perform scale correction but doesn't have a target,
8366
8320
  * use the layout as the target.
@@ -8427,8 +8381,7 @@
8427
8381
  scheduleRender(notifyAll = true) {
8428
8382
  this.options.visualElement?.scheduleRender();
8429
8383
  if (notifyAll) {
8430
- const stack = this.getStack();
8431
- stack && stack.scheduleRender();
8384
+ this.getStack()?.scheduleRender();
8432
8385
  }
8433
8386
  if (this.resumingFrom && !this.resumingFrom.instance) {
8434
8387
  this.resumingFrom = undefined;
@@ -8450,9 +8403,7 @@
8450
8403
  }
8451
8404
  this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
8452
8405
  const relativeLayout = createBox();
8453
- const snapshotSource = snapshot ? snapshot.source : undefined;
8454
- const layoutSource = this.layout ? this.layout.source : undefined;
8455
- const isSharedLayoutAnimation = snapshotSource !== layoutSource;
8406
+ const isSharedLayoutAnimation = snapshot?.source !== this.layout?.source;
8456
8407
  const stack = this.getStack();
8457
8408
  const isOnlyMember = !stack || stack.members.length <= 1;
8458
8409
  const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&
@@ -8467,19 +8418,11 @@
8467
8418
  this.mixTargetDelta = (latest) => {
8468
8419
  const progress = latest / 1000;
8469
8420
  const point = interpolate?.(progress);
8421
+ mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8422
+ mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8470
8423
  if (point) {
8471
8424
  targetDelta.x.translate = point.x;
8472
- targetDelta.x.scale = mixNumber$1(delta.x.scale, 1, progress);
8473
- targetDelta.x.origin = delta.x.origin;
8474
- targetDelta.x.originPoint = delta.x.originPoint;
8475
8425
  targetDelta.y.translate = point.y;
8476
- targetDelta.y.scale = mixNumber$1(delta.y.scale, 1, progress);
8477
- targetDelta.y.origin = delta.y.origin;
8478
- targetDelta.y.originPoint = delta.y.originPoint;
8479
- }
8480
- else {
8481
- mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8482
- mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
8483
8426
  }
8484
8427
  this.setTargetDelta(targetDelta);
8485
8428
  if (this.relativeTarget &&
@@ -8505,7 +8448,7 @@
8505
8448
  this.animationValues = mixedValues;
8506
8449
  mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
8507
8450
  }
8508
- if (point && point.rotate !== undefined) {
8451
+ if (point?.rotate !== undefined) {
8509
8452
  // Dedicated `pathRotation` channel, not `rotate`, so an
8510
8453
  // animating `rotate` is composed with, never clobbered.
8511
8454
  if (!this.animationValues)
@@ -8570,7 +8513,7 @@
8570
8513
  }
8571
8514
  finishAnimation() {
8572
8515
  if (this.currentAnimation) {
8573
- this.mixTargetDelta && this.mixTargetDelta(animationTarget);
8516
+ this.mixTargetDelta?.(animationTarget);
8574
8517
  this.currentAnimation.stop();
8575
8518
  }
8576
8519
  this.completeAnimation();
@@ -8590,13 +8533,11 @@
8590
8533
  this.layout &&
8591
8534
  layout &&
8592
8535
  shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {
8536
+ const { layoutBox } = this.layout;
8537
+ const leadTarget = target;
8593
8538
  target = this.target || createBox();
8594
- const xLength = calcLength(this.layout.layoutBox.x);
8595
- target.x.min = lead.target.x.min;
8596
- target.x.max = target.x.min + xLength;
8597
- const yLength = calcLength(this.layout.layoutBox.y);
8598
- target.y.min = lead.target.y.min;
8599
- target.y.max = target.y.min + yLength;
8539
+ alignAxis(target.x, leadTarget.x, layoutBox.x);
8540
+ alignAxis(target.y, leadTarget.y, layoutBox.y);
8600
8541
  }
8601
8542
  copyBoxInto(targetWithTransforms, target);
8602
8543
  /**
@@ -8621,8 +8562,8 @@
8621
8562
  stack.add(node);
8622
8563
  const config = node.options.initialPromotionConfig;
8623
8564
  node.promote({
8624
- transition: config ? config.transition : undefined,
8625
- preserveFollowOpacity: config && config.shouldPreserveFollowOpacity
8565
+ transition: config?.transition,
8566
+ preserveFollowOpacity: config?.shouldPreserveFollowOpacity
8626
8567
  ? config.shouldPreserveFollowOpacity(node)
8627
8568
  : undefined,
8628
8569
  });
@@ -8645,9 +8586,7 @@
8645
8586
  return this.root.sharedNodes.get(layoutId);
8646
8587
  }
8647
8588
  promote({ needsReset, transition, preserveFollowOpacity, } = {}) {
8648
- const stack = this.getStack();
8649
- if (stack)
8650
- stack.promote(this, preserveFollowOpacity);
8589
+ this.getStack()?.promote(this, preserveFollowOpacity);
8651
8590
  if (needsReset) {
8652
8591
  this.projectionDelta = undefined;
8653
8592
  this.needsReset = true;
@@ -8656,45 +8595,27 @@
8656
8595
  this.setOptions({ transition });
8657
8596
  }
8658
8597
  relegate() {
8659
- const stack = this.getStack();
8660
- if (stack) {
8661
- return stack.relegate(this);
8662
- }
8663
- else {
8664
- return false;
8665
- }
8598
+ return this.getStack()?.relegate(this) || false;
8666
8599
  }
8667
8600
  resetSkewAndRotation() {
8668
8601
  const { visualElement } = this.options;
8669
8602
  if (!visualElement)
8670
8603
  return;
8671
- // If there's no detected skew or rotation values, we can early return without a forced render.
8672
- let hasDistortingTransform = false;
8673
8604
  /**
8674
8605
  * An unrolled check for rotation values. Most elements don't have any rotation and
8675
- * skipping the nested loop and new object creation is 50% faster.
8606
+ * skipping the loop and new object creation is 50% faster.
8607
+ * If there's no distorting values, we don't need to do any more.
8676
8608
  */
8677
8609
  const { latestValues } = visualElement;
8678
- if (latestValues.z ||
8679
- latestValues.rotate ||
8680
- latestValues.rotateX ||
8681
- latestValues.rotateY ||
8682
- latestValues.rotateZ ||
8683
- latestValues.skewX ||
8684
- latestValues.skewY) {
8685
- hasDistortingTransform = true;
8686
- }
8687
- // If there's no distorting values, we don't need to do any more.
8688
- if (!hasDistortingTransform)
8610
+ if (!hasDistortingTransform(latestValues))
8689
8611
  return;
8690
8612
  const resetValues = {};
8691
- if (latestValues.z) {
8692
- resetDistortingTransform("z", visualElement, resetValues, this.animationValues);
8693
- }
8694
8613
  // Check the skew and rotate value of all axes and reset to 0
8695
- for (let i = 0; i < transformAxes.length; i++) {
8696
- resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8697
- resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
8614
+ for (let i = 0; i < distortingTransforms.length; i++) {
8615
+ resetDistortingTransform(distortingTransforms[i], visualElement, resetValues, this.animationValues);
8616
+ }
8617
+ for (let i = 0; i < angleTransforms.length; i++) {
8618
+ resetDistortingTransform(angleTransforms[i], visualElement, resetValues, this.animationValues);
8698
8619
  }
8699
8620
  // Force a render of this element to apply the transform with all skews and rotations
8700
8621
  // set to 0.
@@ -8714,7 +8635,13 @@
8714
8635
  styleProp) {
8715
8636
  if (!this.instance || this.isSVG)
8716
8637
  return;
8717
- if (!this.isVisible) {
8638
+ const lead = this.getLead();
8639
+ /**
8640
+ * Without crossfade, a new lead hides the previous one, as it's
8641
+ * usually unmounting. One that gave its layoutId away keeps
8642
+ * rendering, so only hide nodes that follow another.
8643
+ */
8644
+ if (!this.isVisible && lead !== this) {
8718
8645
  targetStyle.visibility = "hidden";
8719
8646
  return;
8720
8647
  }
@@ -8730,9 +8657,10 @@
8730
8657
  : "none";
8731
8658
  return;
8732
8659
  }
8733
- const lead = this.getLead();
8734
8660
  if (!this.projectionDelta || !this.layout || !lead.target) {
8735
- if (this.options.layoutId) {
8661
+ if (this.options.layoutId || this.needsShow) {
8662
+ this.needsShow = false;
8663
+ targetStyle.visibility = "";
8736
8664
  targetStyle.opacity =
8737
8665
  this.latestValues.opacity !== undefined
8738
8666
  ? this.latestValues.opacity
@@ -8866,52 +8794,49 @@
8866
8794
  const isShared = snapshot.source !== node.layout.source;
8867
8795
  // TODO Maybe we want to also resize the layout snapshot so we don't trigger
8868
8796
  // animations for instance if layout="size" and an element has only changed position
8869
- if (animationType === "size") {
8870
- eachAxis((axis) => {
8871
- const axisSnapshot = isShared
8872
- ? snapshot.measuredBox[axis]
8873
- : snapshot.layoutBox[axis];
8874
- const length = calcLength(axisSnapshot);
8875
- axisSnapshot.min = layout[axis].min;
8876
- axisSnapshot.max = axisSnapshot.min + length;
8877
- });
8878
- }
8879
- else if (animationType === "x" || animationType === "y") {
8880
- const snapAxis = animationType === "x" ? "y" : "x";
8881
- copyAxisInto(isShared
8882
- ? snapshot.measuredBox[snapAxis]
8883
- : snapshot.layoutBox[snapAxis], layout[snapAxis]);
8884
- }
8885
- else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8886
- eachAxis((axis) => {
8887
- const axisSnapshot = isShared
8888
- ? snapshot.measuredBox[axis]
8889
- : snapshot.layoutBox[axis];
8890
- const length = calcLength(layout[axis]);
8891
- axisSnapshot.max = axisSnapshot.min + length;
8892
- /**
8893
- * Ensure relative target gets resized and rerendererd
8894
- */
8895
- if (node.relativeTarget && !node.currentAnimation) {
8896
- node.isProjectionDirty = true;
8897
- node.relativeTarget[axis].max =
8898
- node.relativeTarget[axis].min + length;
8899
- }
8900
- });
8901
- }
8797
+ const resizeSnapshot = (box, to) => {
8798
+ if (animationType === "size") {
8799
+ eachAxis((axis) => {
8800
+ const length = calcLength(box[axis]);
8801
+ box[axis].min = to[axis].min;
8802
+ box[axis].max = box[axis].min + length;
8803
+ });
8804
+ }
8805
+ else if (animationType === "x" || animationType === "y") {
8806
+ const snapAxis = animationType === "x" ? "y" : "x";
8807
+ copyAxisInto(box[snapAxis], to[snapAxis]);
8808
+ }
8809
+ else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
8810
+ eachAxis((axis) => {
8811
+ const length = calcLength(to[axis]);
8812
+ box[axis].max = box[axis].min + length;
8813
+ /**
8814
+ * Ensure relative target gets resized and rerendererd
8815
+ */
8816
+ if (node.relativeTarget && !node.currentAnimation) {
8817
+ node.isProjectionDirty = true;
8818
+ node.relativeTarget[axis].max =
8819
+ node.relativeTarget[axis].min + length;
8820
+ }
8821
+ });
8822
+ }
8823
+ };
8824
+ const snapshotBox = isShared ? snapshot.measuredBox : snapshot.layoutBox;
8825
+ resizeSnapshot(snapshotBox, layout);
8902
8826
  const layoutDelta = createDelta();
8903
8827
  calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);
8904
8828
  const visualDelta = createDelta();
8905
- if (isShared) {
8906
- calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
8907
- }
8908
- else {
8909
- calcBoxDelta(visualDelta, layout, snapshot.layoutBox);
8910
- }
8829
+ calcBoxDelta(visualDelta, isShared ? node.applyTransform(measuredLayout, true) : layout, snapshotBox);
8911
8830
  const hasLayoutChanged = !isDeltaZero(layoutDelta);
8912
8831
  let hasRelativeLayoutChanged = false;
8913
- if (!node.resumeFrom) {
8914
- const relativeParent = node.getClosestProjectingParent();
8832
+ const relativeParent = node.getClosestProjectingParent();
8833
+ /**
8834
+ * A snapshot resumed from another element is only relative to this
8835
+ * node's relativeParent if it's a layoutRoot that contains both.
8836
+ */
8837
+ if (!node.resumeFrom ||
8838
+ (relativeParent?.options.layoutRoot &&
8839
+ node.resumeFrom.path.includes(relativeParent))) {
8915
8840
  /**
8916
8841
  * If the relativeParent is itself resuming from a different element then
8917
8842
  * the relative snapshot is not relavent
@@ -8920,10 +8845,22 @@
8920
8845
  const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
8921
8846
  if (parentSnapshot && parentLayout) {
8922
8847
  const anchor = node.options.layoutAnchor || undefined;
8848
+ /**
8849
+ * A shared snapshot includes the transforms of the old
8850
+ * element's ancestors below the layoutRoot, as they
8851
+ * aren't shared with the new element.
8852
+ */
8923
8853
  const relativeSnapshot = createBox();
8924
- calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8854
+ calcRelativePosition(relativeSnapshot, isShared
8855
+ ? node.resumeFrom.applyTransform(snapshot.layoutBox, true, undefined, true, relativeParent.depth + 1)
8856
+ : snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
8925
8857
  const relativeLayout = createBox();
8926
8858
  calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox, anchor);
8859
+ /**
8860
+ * A shared snapshot is resized in page space, above, so
8861
+ * resize it relative to the layoutRoot too.
8862
+ */
8863
+ isShared && resizeSnapshot(relativeSnapshot, relativeLayout);
8927
8864
  if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {
8928
8865
  hasRelativeLayoutChanged = true;
8929
8866
  }
@@ -8945,8 +8882,7 @@
8945
8882
  });
8946
8883
  }
8947
8884
  else if (node.isLead()) {
8948
- const { onExitComplete } = node.options;
8949
- onExitComplete && onExitComplete();
8885
+ node.options.onExitComplete?.();
8950
8886
  }
8951
8887
  /**
8952
8888
  * Clearing transition
@@ -9052,7 +8988,7 @@
9052
8988
  }
9053
8989
  function resetTransformStyle(node) {
9054
8990
  const { visualElement } = node.options;
9055
- if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {
8991
+ if (visualElement?.getProps().onBeforeLayoutMeasure) {
9056
8992
  visualElement.notify("BeforeLayoutMeasure");
9057
8993
  }
9058
8994
  node.resetTransform();
@@ -9086,7 +9022,7 @@
9086
9022
  mixAxis(output.y, from.y, to.y, p);
9087
9023
  }
9088
9024
  function hasOpacityCrossfade(node) {
9089
- return (node.animationValues && node.animationValues.opacityExit !== undefined);
9025
+ return node.animationValues?.opacityExit !== undefined;
9090
9026
  }
9091
9027
  const defaultLayoutTransition = {
9092
9028
  duration: 0.45,
@@ -9112,6 +9048,13 @@
9112
9048
  roundAxis(box.x);
9113
9049
  roundAxis(box.y);
9114
9050
  }
9051
+ /**
9052
+ * Align an axis to the start of another, keeping the length of a layout axis.
9053
+ * The length is read first, as output can be the layout axis itself.
9054
+ */
9055
+ function alignAxis(output, from, layout) {
9056
+ output.max = calcLength(layout) + (output.min = from.min);
9057
+ }
9115
9058
  function shouldAnimatePositionOnly(animationType, snapshot, layout) {
9116
9059
  return (animationType === "position" ||
9117
9060
  (animationType === "preserve-aspect" &&
@@ -9162,7 +9105,7 @@
9162
9105
  resetTransform: (instance, value) => {
9163
9106
  instance.style.transform = value !== undefined ? value : "none";
9164
9107
  },
9165
- checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9108
+ checkIsScrollRoot: (instance) => window.getComputedStyle(instance).position === "fixed",
9166
9109
  });
9167
9110
 
9168
9111
  const visualElementStore = new WeakMap();
@@ -9448,9 +9391,7 @@
9448
9391
  }
9449
9392
  this.current = instance;
9450
9393
  visualElementStore.set(instance, this);
9451
- if (this.projection && !this.projection.instance) {
9452
- this.projection.mount(instance);
9453
- }
9394
+ this.projection?.instance || this.projection?.mount(instance);
9454
9395
  /**
9455
9396
  * Join the closest variant node above, so its variant changes
9456
9397
  * propagate here, unless inherit={false} cuts the chain.
@@ -9496,12 +9437,12 @@
9496
9437
  this.hasBeenMounted = true;
9497
9438
  }
9498
9439
  unmount() {
9499
- this.projection && this.projection.unmount();
9440
+ this.projection?.unmount();
9500
9441
  cancelFrame(this.notifyUpdate);
9501
9442
  cancelFrame(this.render);
9502
9443
  this.valueSubscriptions.forEach((remove) => remove());
9503
9444
  this.valueSubscriptions.clear();
9504
- this.removeFromVariantTree && this.removeFromVariantTree();
9445
+ this.removeFromVariantTree?.();
9505
9446
  this.parent?.removeChild(this);
9506
9447
  for (const key in this.events) {
9507
9448
  this.events[key].clear();
@@ -9517,17 +9458,14 @@
9517
9458
  }
9518
9459
  addChild(child) {
9519
9460
  this.children.add(child);
9520
- this.enteringChildren ?? (this.enteringChildren = new Set());
9521
- this.enteringChildren.add(child);
9461
+ (this.enteringChildren || (this.enteringChildren = new Set())).add(child);
9522
9462
  }
9523
9463
  removeChild(child) {
9524
9464
  this.children.delete(child);
9525
- this.enteringChildren && this.enteringChildren.delete(child);
9465
+ this.enteringChildren?.delete(child);
9526
9466
  }
9527
9467
  bindToMotionValue(key, value) {
9528
- if (this.valueSubscriptions.has(key)) {
9529
- this.valueSubscriptions.get(key)();
9530
- }
9468
+ this.valueSubscriptions.get(key)?.();
9531
9469
  if (value.accelerate &&
9532
9470
  acceleratedValues.has(key) &&
9533
9471
  this.current instanceof HTMLElement) {
@@ -9569,8 +9507,7 @@
9569
9507
  }
9570
9508
  this.valueSubscriptions.set(key, () => {
9571
9509
  removeOnChange();
9572
- if (removeSyncCheck)
9573
- removeSyncCheck();
9510
+ removeSyncCheck?.();
9574
9511
  // Defer to MotionValue.on("change") auto-stop so React 19 remounts
9575
9512
  // can resubscribe before the animation is cancelled (#3315).
9576
9513
  });
@@ -9663,10 +9600,8 @@
9663
9600
  */
9664
9601
  for (let i = 0; i < propEventHandlers.length; i++) {
9665
9602
  const key = propEventHandlers[i];
9666
- if (this.propEventSubscriptions[key]) {
9667
- this.propEventSubscriptions[key]();
9668
- delete this.propEventSubscriptions[key];
9669
- }
9603
+ this.propEventSubscriptions[key]?.();
9604
+ delete this.propEventSubscriptions[key];
9670
9605
  const listenerName = ("on" + key);
9671
9606
  const listener = props[listenerName];
9672
9607
  if (listener) {
@@ -9674,9 +9609,7 @@
9674
9609
  }
9675
9610
  }
9676
9611
  this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues);
9677
- if (this.handleChildMotionValue) {
9678
- this.handleChildMotionValue();
9679
- }
9612
+ this.handleChildMotionValue?.();
9680
9613
  }
9681
9614
  getProps() {
9682
9615
  return this.props;
@@ -9685,7 +9618,7 @@
9685
9618
  * Returns the variant definition with a given name.
9686
9619
  */
9687
9620
  getVariant(name) {
9688
- return this.props.variants ? this.props.variants[name] : undefined;
9621
+ return this.props.variants?.[name];
9689
9622
  }
9690
9623
  /**
9691
9624
  * Returns the defined default transition on this component.
@@ -9723,11 +9656,8 @@
9723
9656
  */
9724
9657
  removeValue(key) {
9725
9658
  this.values.delete(key);
9726
- const unsubscribe = this.valueSubscriptions.get(key);
9727
- if (unsubscribe) {
9728
- unsubscribe();
9729
- this.valueSubscriptions.delete(key);
9730
- }
9659
+ this.valueSubscriptions.get(key)?.();
9660
+ this.valueSubscriptions.delete(key);
9731
9661
  delete this.latestValues[key];
9732
9662
  this.removeValueFromRenderState(key, this.renderState);
9733
9663
  }
@@ -9738,10 +9668,10 @@
9738
9668
  return this.values.has(key);
9739
9669
  }
9740
9670
  getValue(key, defaultValue) {
9741
- if (this.props.values && this.props.values[key]) {
9742
- return this.props.values[key];
9743
- }
9744
- let value = this.values.get(key);
9671
+ let value = this.props.values?.[key];
9672
+ if (value)
9673
+ return value;
9674
+ value = this.values.get(key);
9745
9675
  if (value === undefined && defaultValue !== undefined) {
9746
9676
  value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
9747
9677
  owner: this,
@@ -9791,15 +9721,11 @@
9791
9721
  this.baseTarget[key] = value;
9792
9722
  }
9793
9723
  on(eventName, callback) {
9794
- if (!this.events[eventName]) {
9795
- this.events[eventName] = new motionUtils.SubscriptionManager();
9796
- }
9797
- return this.events[eventName].add(callback);
9724
+ return (this.events[eventName] ||
9725
+ (this.events[eventName] = new motionUtils.SubscriptionManager())).add(callback);
9798
9726
  }
9799
9727
  notify(eventName, ...args) {
9800
- if (this.events[eventName]) {
9801
- this.events[eventName].notify(...args);
9802
- }
9728
+ this.events[eventName]?.notify(...args);
9803
9729
  }
9804
9730
  scheduleRenderMicrotask() {
9805
9731
  microtask.render(this.render);
@@ -9965,7 +9891,7 @@
9965
9891
  let ancestor = element.parentElement;
9966
9892
  while (ancestor) {
9967
9893
  const node = layoutNodes.get(ancestor);
9968
- if (node && node.instance)
9894
+ if (node?.instance)
9969
9895
  return node;
9970
9896
  ancestor = ancestor.parentElement;
9971
9897
  }
@@ -10231,7 +10157,7 @@
10231
10157
  hasSurvivor &&
10232
10158
  !newMemberIds.has(layoutId)) {
10233
10159
  if (restore && restore.parent.isConnected) {
10234
- restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10160
+ restore.parent.insertBefore(element, restore.next?.parentNode === restore.parent
10235
10161
  ? restore.next
10236
10162
  : null);
10237
10163
  node.isPresent = false;
@@ -10436,10 +10362,6 @@
10436
10362
  * Scroll positions of scrollable ancestors and window.
10437
10363
  */
10438
10364
  this.scrollPositions = new Map();
10439
- /**
10440
- * Cleanup function for scroll listeners.
10441
- */
10442
- this.removeScrollListeners = null;
10443
10365
  this.onElementScroll = (event) => {
10444
10366
  this.handleScroll(event.target);
10445
10367
  };
@@ -10467,10 +10389,10 @@
10467
10389
  this.history.push({ ...point, timestamp: time.now() });
10468
10390
  const { onStart, onMove } = this.handlers;
10469
10391
  if (!isPanStarted) {
10470
- onStart && onStart(this.lastMoveEvent, info);
10392
+ onStart?.(this.lastMoveEvent, info);
10471
10393
  this.startEvent = this.lastMoveEvent;
10472
10394
  }
10473
- onMove && onMove(this.lastMoveEvent, info);
10395
+ onMove?.(this.lastMoveEvent, info);
10474
10396
  };
10475
10397
  this.handlePointerMove = (event, info) => {
10476
10398
  /**
@@ -10495,17 +10417,15 @@
10495
10417
  // Resume animation if dragSnapToOrigin is set OR if no drag started (user just clicked)
10496
10418
  // This ensures constraint animations continue when interrupted by a click
10497
10419
  if (this.dragSnapToOrigin || !this.startEvent) {
10498
- resumeAnimation && resumeAnimation();
10420
+ resumeAnimation?.();
10499
10421
  }
10500
10422
  if (!(this.lastMoveEvent && this.lastMoveEventInfo))
10501
10423
  return;
10502
10424
  const panInfo = getPanInfo(event.type === "pointercancel"
10503
10425
  ? this.lastMoveEventInfo
10504
10426
  : transformPoint(info, this.transformPagePoint), this.history);
10505
- if (this.startEvent && onEnd) {
10506
- onEnd(event, panInfo);
10507
- }
10508
- onSessionEnd && onSessionEnd(event, panInfo);
10427
+ this.startEvent && onEnd?.(event, panInfo);
10428
+ onSessionEnd?.(event, panInfo);
10509
10429
  };
10510
10430
  // If we have more than one touch, don't start detecting this gesture
10511
10431
  if (!isPrimaryPointer(event))
@@ -10518,8 +10438,13 @@
10518
10438
  const info = extractEventInfo(event);
10519
10439
  const initialInfo = transformPoint(info, this.transformPagePoint);
10520
10440
  const { point } = initialInfo;
10521
- const { timestamp } = frameData;
10522
- this.history = [{ ...point, timestamp }];
10441
+ /**
10442
+ * Stamp the origin with time.now(), not frameData.timestamp: when
10443
+ * the frameloop is idle, frameData.timestamp is from the last frame
10444
+ * that ran, which can be seconds old, and a fast flick from a
10445
+ * standstill would then report near-zero velocity. See #1747.
10446
+ */
10447
+ this.history = [{ ...point, timestamp: time.now() }];
10523
10448
  const { onSessionStart } = handlers;
10524
10449
  onSessionStart &&
10525
10450
  onSessionStart(event, getPanInfo(initialInfo, this.history));
@@ -10543,30 +10468,19 @@
10543
10468
  const style = getComputedStyle(current);
10544
10469
  if (overflowStyles.has(style.overflowX) ||
10545
10470
  overflowStyles.has(style.overflowY)) {
10546
- this.scrollPositions.set(current, {
10547
- x: current.scrollLeft,
10548
- y: current.scrollTop,
10549
- });
10471
+ this.scrollPositions.set(current, getScroll(current));
10550
10472
  }
10551
10473
  current = current.parentElement;
10552
10474
  }
10553
10475
  // Track window scroll
10554
- this.scrollPositions.set(window, {
10555
- x: window.scrollX,
10556
- y: window.scrollY,
10557
- });
10476
+ this.scrollPositions.set(window, getScroll(window));
10477
+ this.removeScrollListeners = motionUtils.pipe(
10558
10478
  // Capture listener catches element scroll events as they bubble
10559
- window.addEventListener("scroll", this.onElementScroll, {
10479
+ addDomEvent(window, "scroll", this.onElementScroll, {
10560
10480
  capture: true,
10561
- });
10481
+ }),
10562
10482
  // Direct window scroll listener (window scroll doesn't bubble)
10563
- window.addEventListener("scroll", this.onWindowScroll);
10564
- this.removeScrollListeners = () => {
10565
- window.removeEventListener("scroll", this.onElementScroll, {
10566
- capture: true,
10567
- });
10568
- window.removeEventListener("scroll", this.onWindowScroll);
10569
- };
10483
+ addDomEvent(window, "scroll", this.onWindowScroll, {}));
10570
10484
  }
10571
10485
  /**
10572
10486
  * Handle scroll compensation during drag.
@@ -10579,12 +10493,7 @@
10579
10493
  if (!initial)
10580
10494
  return;
10581
10495
  const isWindow = target === window;
10582
- const current = isWindow
10583
- ? { x: window.scrollX, y: window.scrollY }
10584
- : {
10585
- x: target.scrollLeft,
10586
- y: target.scrollTop,
10587
- };
10496
+ const current = getScroll(target);
10588
10497
  const delta = { x: current.x - initial.x, y: current.y - initial.y };
10589
10498
  if (delta.x === 0 && delta.y === 0)
10590
10499
  return;
@@ -10609,12 +10518,18 @@
10609
10518
  this.handlers = handlers;
10610
10519
  }
10611
10520
  end() {
10612
- this.removeListeners && this.removeListeners();
10613
- this.removeScrollListeners && this.removeScrollListeners();
10521
+ this.removeListeners?.();
10522
+ this.removeScrollListeners?.();
10614
10523
  this.scrollPositions.clear();
10615
10524
  cancelFrame(this.updatePoint);
10616
10525
  }
10617
10526
  }
10527
+ const getScroll = (target) => target === window
10528
+ ? { x: window.scrollX, y: window.scrollY }
10529
+ : {
10530
+ x: target.scrollLeft,
10531
+ y: target.scrollTop,
10532
+ };
10618
10533
  function transformPoint(info, transformPagePoint) {
10619
10534
  return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
10620
10535
  }
@@ -10871,6 +10786,25 @@
10871
10786
  : dragElastic[label] || 0;
10872
10787
  }
10873
10788
 
10789
+ /**
10790
+ * Re-read the scroll of the projection's ancestors, and return that of the
10791
+ * `layoutScroll` ones as a key that changes when any of them scroll.
10792
+ *
10793
+ * Clear the cached scroll first so `updateScroll` bypasses its
10794
+ * per-animationId cache and re-reads the live value.
10795
+ */
10796
+ function measureScroll(projection) {
10797
+ let key = "";
10798
+ for (const node of projection.path) {
10799
+ node.scroll = undefined;
10800
+ node.updateScroll();
10801
+ const { scroll } = node;
10802
+ if (node !== projection.root && scroll) {
10803
+ key += scroll.offset.x + "," + scroll.offset.y + ",";
10804
+ }
10805
+ }
10806
+ return key;
10807
+ }
10874
10808
  const elementDragControls = new WeakMap();
10875
10809
  class VisualElementDragControls {
10876
10810
  constructor(visualElement, readProps = () => visualElement.getProps()) {
@@ -10902,8 +10836,7 @@
10902
10836
  /**
10903
10837
  * Don't start dragging if this component is exiting
10904
10838
  */
10905
- const { presenceContext } = this.visualElement;
10906
- if (presenceContext && presenceContext.isPresent === false)
10839
+ if (this.visualElement.presenceContext?.isPresent === false)
10907
10840
  return;
10908
10841
  const onSessionStart = (event) => {
10909
10842
  if (snapToCursor)
@@ -10914,8 +10847,7 @@
10914
10847
  // Attempt to grab the global drag gesture lock - maybe make this part of PanSession
10915
10848
  const { drag, dragPropagation, onDragStart } = this.getProps();
10916
10849
  if (drag && !dragPropagation) {
10917
- if (this.openDragLock)
10918
- this.openDragLock();
10850
+ this.openDragLock?.();
10919
10851
  this.openDragLock = setDragLock(drag);
10920
10852
  // If we don 't have the lock, don't start dragging
10921
10853
  if (!this.openDragLock)
@@ -10926,9 +10858,10 @@
10926
10858
  this.isDragging = true;
10927
10859
  this.currentDirection = null;
10928
10860
  this.resolveConstraints();
10929
- if (this.visualElement.projection) {
10930
- this.visualElement.projection.isAnimationBlocked = true;
10931
- this.visualElement.projection.target = undefined;
10861
+ const { projection } = this.visualElement;
10862
+ if (projection) {
10863
+ projection.isAnimationBlocked = true;
10864
+ projection.target = undefined;
10932
10865
  }
10933
10866
  /**
10934
10867
  * Record gesture origin and pointer offset
@@ -10950,13 +10883,11 @@
10950
10883
  current = parseFloat(current);
10951
10884
  }
10952
10885
  else if (percent.test(current)) {
10953
- const { projection } = this.visualElement;
10954
- if (projection && projection.layout) {
10955
- const measuredAxis = projection.layout.layoutBox[axis];
10956
- if (measuredAxis) {
10957
- const length = calcLength(measuredAxis);
10958
- current = length * (parseFloat(current) / 100);
10959
- }
10886
+ const measuredAxis = projection?.layout?.layoutBox[axis];
10887
+ if (measuredAxis) {
10888
+ current =
10889
+ calcLength(measuredAxis) *
10890
+ (parseFloat(current) / 100);
10960
10891
  }
10961
10892
  }
10962
10893
  this.originPoint[axis] = current;
@@ -10966,8 +10897,7 @@
10966
10897
  frame.update(() => onDragStart(event, info), false, true);
10967
10898
  }
10968
10899
  addValueToWillChange(this.visualElement, "transform");
10969
- const { animationState } = this.visualElement;
10970
- animationState && animationState.setActive("whileDrag", true);
10900
+ this.visualElement.animationState?.setActive("whileDrag", true);
10971
10901
  };
10972
10902
  const onMove = (event, info) => {
10973
10903
  this.latestPointerEvent = event;
@@ -10990,8 +10920,8 @@
10990
10920
  onDirectionLock && onDirectionLock(this.currentDirection);
10991
10921
  }
10992
10922
  // Update each point with the latest position
10993
- this.updateAxis("x", info.point, offset);
10994
- this.updateAxis("y", info.point, offset);
10923
+ this.updateAxis("x", offset);
10924
+ this.updateAxis("y", offset);
10995
10925
  /**
10996
10926
  * Ideally we would leave the renderer to fire naturally at the end of
10997
10927
  * this frame but if the element is about to change layout as the result
@@ -11060,12 +10990,11 @@
11060
10990
  projection.isAnimationBlocked = false;
11061
10991
  }
11062
10992
  this.endPanSession();
11063
- const { dragPropagation } = this.getProps();
11064
- if (!dragPropagation && this.openDragLock) {
10993
+ if (!this.getProps().dragPropagation && this.openDragLock) {
11065
10994
  this.openDragLock();
11066
10995
  this.openDragLock = null;
11067
10996
  }
11068
- animationState && animationState.setActive("whileDrag", false);
10997
+ animationState?.setActive("whileDrag", false);
11069
10998
  }
11070
10999
  /**
11071
11000
  * Clean up the pan session without modifying other drag state.
@@ -11073,31 +11002,42 @@
11073
11002
  * without affecting projection animations or drag locks.
11074
11003
  */
11075
11004
  endPanSession() {
11076
- this.panSession && this.panSession.end();
11005
+ this.panSession?.end();
11077
11006
  this.panSession = undefined;
11078
11007
  }
11079
- updateAxis(axis, _point, offset) {
11080
- const { drag } = this.getProps();
11008
+ updateAxis(axis, offset) {
11009
+ /**
11010
+ * Read drag per axis: a callback fired while updating the x axis
11011
+ * can synchronously re-render with new props.
11012
+ */
11013
+ const { drag } = this.readProps();
11081
11014
  // If we're not dragging this axis, do an early return.
11082
11015
  if (!offset || !shouldDrag(axis, drag, this.currentDirection))
11083
11016
  return;
11084
11017
  const axisValue = this.getAxisMotionValue(axis);
11085
11018
  let next = this.originPoint[axis] + offset[axis];
11086
11019
  // Apply constraints
11087
- if (this.constraints && this.constraints[axis]) {
11088
- next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
11020
+ const constraints = this.constraints && this.constraints[axis];
11021
+ if (constraints) {
11022
+ next = applyConstraints(next, constraints, this.elastic[axis]);
11089
11023
  }
11090
11024
  axisValue.set(next);
11091
11025
  }
11092
11026
  resolveConstraints() {
11093
11027
  const { dragConstraints, dragElastic } = this.getProps();
11094
- const layout = this.visualElement.projection &&
11095
- !this.visualElement.projection.layout
11096
- ? this.visualElement.projection.measure(false)
11097
- : this.visualElement.projection?.layout;
11028
+ const { projection } = this.visualElement;
11029
+ const layout = projection && (projection.layout || projection.measure(false));
11098
11030
  const prevConstraints = this.constraints;
11099
11031
  if (isElementConstraints(dragConstraints)) {
11100
- if (!this.constraints) {
11032
+ /**
11033
+ * Ref constraints are measured with the layout. Scrolling a
11034
+ * `layoutScroll` ancestor since can move the element relative
11035
+ * to them without a layout measurement, so measure them again
11036
+ * (#2024). Otherwise keep them: they and the layout can both
11037
+ * have moved on the page since, e.g. when content above grows.
11038
+ */
11039
+ if (!this.constraints ||
11040
+ this.scroll !== measureScroll(projection)) {
11101
11041
  this.constraints = this.resolveRefConstraints();
11102
11042
  }
11103
11043
  }
@@ -11140,21 +11080,20 @@
11140
11080
  if (!projection || !projection.layout)
11141
11081
  return false;
11142
11082
  /**
11143
- * Refresh the root scroll offset so the constraint's viewport box
11144
- * translates to correct page coordinates. The scroll captured at
11145
- * drag mount can be stale if the document was scrolled afterwards —
11146
- * e.g. via the browser restoring scroll on refresh, or an ancestor
11147
- * layout effect running after this element's mount (#2829).
11148
- *
11149
- * Clear the cached scroll first so `updateScroll` bypasses its
11150
- * per-animationId cache and re-reads the live value.
11083
+ * Refresh the scroll offsets of the root and `layoutScroll`
11084
+ * ancestors so the constraint's viewport box translates to the
11085
+ * layout's coordinates. The scroll captured when the layout was
11086
+ * measured can be stale if they've scrolled since — e.g. via the
11087
+ * browser restoring scroll on refresh, or an ancestor layout effect
11088
+ * running after this element's mount (#2829).
11151
11089
  */
11152
- if (projection.root) {
11153
- projection.root.scroll = undefined;
11154
- projection.root.updateScroll();
11155
- }
11090
+ this.scroll = measureScroll(projection);
11156
11091
  const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
11157
- let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
11092
+ /**
11093
+ * layoutBox removes the scroll of `layoutScroll` ancestors, so
11094
+ * remove it from the constraints box too.
11095
+ */
11096
+ let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, projection.removeElementScroll(constraintsBox));
11158
11097
  /**
11159
11098
  * If there's an onMeasureDragConstraints listener we call it and
11160
11099
  * if different constraints are returned, set constraints to that
@@ -11175,7 +11114,7 @@
11175
11114
  if (!shouldDrag(axis, dragAxes || drag, this.currentDirection)) {
11176
11115
  return;
11177
11116
  }
11178
- let transition = (constraints && constraints[axis]) || {};
11117
+ let transition = constraints[axis] || {};
11179
11118
  if (dragSnapToOrigin === true ||
11180
11119
  dragSnapToOrigin === axis)
11181
11120
  transition = { min: 0, max: 0 };
@@ -11281,7 +11220,7 @@
11281
11220
  this.visualElement.current.style.transform = transformTemplate
11282
11221
  ? transformTemplate({}, "")
11283
11222
  : "none";
11284
- projection.root && projection.root.updateScroll();
11223
+ projection.root?.updateScroll();
11285
11224
  projection.updateLayout();
11286
11225
  /**
11287
11226
  * Reset constraints so resolveConstraints() will recalculate them
@@ -11358,8 +11297,8 @@
11358
11297
  };
11359
11298
  const { projection } = this.visualElement;
11360
11299
  const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
11361
- if (projection && !projection.layout) {
11362
- projection.root && projection.root.updateScroll();
11300
+ if (!projection.layout) {
11301
+ projection.root?.updateScroll();
11363
11302
  projection.updateLayout();
11364
11303
  }
11365
11304
  frame.read(measureDragConstraints);
@@ -11394,22 +11333,14 @@
11394
11333
  stopResizeListener();
11395
11334
  stopPointerListener();
11396
11335
  stopMeasureLayoutListener();
11397
- stopLayoutUpdateListener && stopLayoutUpdateListener();
11398
- stopResizeObservers && stopResizeObservers();
11336
+ stopLayoutUpdateListener();
11337
+ stopResizeObservers?.();
11399
11338
  };
11400
11339
  }
11401
11340
  getProps() {
11402
11341
  const props = this.readProps();
11403
- const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
11404
- return {
11405
- ...props,
11406
- drag,
11407
- dragDirectionLock,
11408
- dragPropagation,
11409
- dragConstraints,
11410
- dragElastic,
11411
- dragMomentum,
11412
- };
11342
+ const { dragElastic = defaultElastic, dragMomentum = true } = props;
11343
+ return { ...props, dragElastic, dragMomentum };
11413
11344
  }
11414
11345
  }
11415
11346
  /**
@@ -13744,6 +13675,12 @@
13744
13675
  }
13745
13676
 
13746
13677
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
13678
+ /**
13679
+ * The transition a value uses when it leaves a state (#1725): the state's
13680
+ * own transition when `out: true`, or the `out` transition itself.
13681
+ * Value-specific keys are resolved by animateTarget.
13682
+ */
13683
+ const getOutTransition = (transition) => transition?.out === true ? transition : transition?.out;
13747
13684
  /**
13748
13685
  * Diffs the element's animation props (one layer per AnimationType, highest
13749
13686
  * priority wins each value) against the previous call and starts animations
@@ -13765,13 +13702,18 @@
13765
13702
  let wasReset = false;
13766
13703
  function animateChanges(changedActiveType) {
13767
13704
  const { props, parent, manuallyAnimateOnMount } = visualElement;
13705
+ const { initial } = props;
13768
13706
  const isMounting = isInitialRender || wasReset;
13769
13707
  const animations = [];
13708
+ const resolveInitial = (definition = initial) => (typeof definition !== "boolean" &&
13709
+ resolveVariant(visualElement, Array.isArray(definition) ? definition[0] : definition, visualElement.presenceContext?.custom)) ||
13710
+ undefined;
13770
13711
  /**
13771
- * Values removed from a type. A lower-priority type that defines
13772
- * them animates them back, otherwise they fall back to a base target.
13712
+ * Values removed from a type, mapped to the out transition of the
13713
+ * state they're leaving. A lower-priority type that defines them
13714
+ * animates them back, otherwise they fall back to a base target.
13773
13715
  */
13774
- const removedKeys = new Set();
13716
+ const removedKeys = new Map();
13775
13717
  /**
13776
13718
  * Values claimed by active, higher-priority types.
13777
13719
  */
@@ -13789,6 +13731,13 @@
13789
13731
  do
13790
13732
  source = source.props.inherit !== false && source.parent;
13791
13733
  while (source && !source.isControllingVariants);
13734
+ /**
13735
+ * Mounting leaves initial, so values use its out transition. Like the
13736
+ * other types, variant children inherit initial's label.
13737
+ */
13738
+ const initialOut = isMounting &&
13739
+ getOutTransition(resolveInitial(initial ?? (source && source.props.initial))
13740
+ ?.transition);
13792
13741
  reversePriorityOrder.forEach((type, i) => {
13793
13742
  const typeState = state[type];
13794
13743
  const ownProp = props[type];
@@ -13800,8 +13749,6 @@
13800
13749
  : undefined;
13801
13750
  const propIsVariant = isVariantLabel(prop);
13802
13751
  const activeDelta = type === changedActiveType ? typeState.isActive : null;
13803
- if (activeDelta === false)
13804
- removedVariantIndex = i;
13805
13752
  /**
13806
13753
  * Inherited labels are animated by the parent through
13807
13754
  * variantChildren, unless this element mounted after its parent.
@@ -13816,6 +13763,13 @@
13816
13763
  typeof prop === "boolean") {
13817
13764
  return;
13818
13765
  }
13766
+ /**
13767
+ * Set after the skip above, so deactivating a type that has nothing
13768
+ * to animate (e.g. whileTap with no prop) doesn't re-run the variants
13769
+ * below it.
13770
+ */
13771
+ if (activeDelta === false)
13772
+ removedVariantIndex = i;
13819
13773
  /**
13820
13774
  * Don't re-resolve a running exit: a changed custom would start
13821
13775
  * new value animations that stop the originals, leaving the exit
@@ -13835,6 +13789,7 @@
13835
13789
  let handledRemovedValues = false;
13836
13790
  const definitionList = Array.isArray(prop) ? prop : [prop];
13837
13791
  let resolvedValues = {};
13792
+ let out;
13838
13793
  if (activeDelta !== false) {
13839
13794
  for (const definition of definitionList) {
13840
13795
  const { transition, transitionEnd, ...target } = resolveVariant(visualElement, definition, getTypeCustom(visualElement, type)) || {};
@@ -13843,6 +13798,11 @@
13843
13798
  ...target,
13844
13799
  ...transitionEnd,
13845
13800
  };
13801
+ /**
13802
+ * One out transition per type. With a list of labels,
13803
+ * the last one that sets out applies to all its values.
13804
+ */
13805
+ out = getOutTransition(transition) || out;
13846
13806
  }
13847
13807
  }
13848
13808
  const { prevResolvedValues } = typeState;
@@ -13858,12 +13818,18 @@
13858
13818
  const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
13859
13819
  ? !shallowCompare(next, prev) || variantDidChange
13860
13820
  : next !== prev;
13821
+ let outTransition;
13861
13822
  if (valueHasChanged && (next === undefined || next === null)) {
13862
- removedKeys.add(key);
13823
+ /**
13824
+ * The highest-priority state a value leaves wins.
13825
+ */
13826
+ removedKeys.has(key) ||
13827
+ removedKeys.set(key, typeState.prevOut);
13863
13828
  }
13864
13829
  else if (valueHasChanged ||
13865
13830
  (next !== undefined && removedKeys.has(key))) {
13866
13831
  shouldAnimateType = true;
13832
+ outTransition = removedKeys.get(key) || initialOut;
13867
13833
  if (removedKeys.delete(key))
13868
13834
  handledRemovedValues = true;
13869
13835
  typeState.needsAnimating[key] = true;
@@ -13874,9 +13840,11 @@
13874
13840
  else {
13875
13841
  typeState.protectedKeys[key] = true;
13876
13842
  }
13843
+ typeState.out[key] = outTransition;
13877
13844
  }
13878
13845
  typeState.prevProp = prop;
13879
13846
  typeState.prevResolvedValues = resolvedValues;
13847
+ typeState.prevOut = out;
13880
13848
  if (typeState.isActive) {
13881
13849
  encounteredKeys = { ...encounteredKeys, ...resolvedValues };
13882
13850
  }
@@ -13907,14 +13875,17 @@
13907
13875
  * longer defines a value it once did, it stays where it is.
13908
13876
  */
13909
13877
  if (removedKeys.size) {
13910
- const { initial } = props;
13911
13878
  const fallbackAnimation = {};
13912
- const resolvedInitial = typeof initial !== "boolean" &&
13913
- resolveVariant(visualElement, Array.isArray(initial) ? initial[0] : initial, visualElement.presenceContext?.custom);
13914
- if (resolvedInitial && resolvedInitial.transition) {
13915
- fallbackAnimation.transition = resolvedInitial.transition;
13916
- }
13917
- removedKeys.forEach((key) => {
13879
+ const resolvedInitial = resolveInitial();
13880
+ let fallbackTransition = resolvedInitial?.transition;
13881
+ removedKeys.forEach((outTransition, key) => {
13882
+ if (outTransition) {
13883
+ fallbackTransition = {
13884
+ ...(fallbackTransition ||
13885
+ visualElement.getDefaultTransition()),
13886
+ [key]: outTransition,
13887
+ };
13888
+ }
13918
13889
  const motionValue = visualElement.getValue(key);
13919
13890
  if (motionValue)
13920
13891
  motionValue.liveStyle = true;
@@ -13945,6 +13916,9 @@
13945
13916
  visualElement.baseTarget[key] = motionValue?.get();
13946
13917
  }
13947
13918
  });
13919
+ if (fallbackTransition) {
13920
+ fallbackAnimation.transition = fallbackTransition;
13921
+ }
13948
13922
  animations.push({ animation: fallbackAnimation });
13949
13923
  }
13950
13924
  const blockAnimation = (isMounting && visualElement.blockInitialAnimation) ||
@@ -14004,6 +13978,7 @@
14004
13978
  protectedKeys: {},
14005
13979
  needsAnimating: {},
14006
13980
  prevResolvedValues: {},
13981
+ out: {},
14007
13982
  };
14008
13983
  }
14009
13984
  return state;
@@ -14170,6 +14145,7 @@
14170
14145
  exports.buildSVGAttrs = buildSVGAttrs;
14171
14146
  exports.buildSVGPath = buildSVGPath;
14172
14147
  exports.buildTransform = buildTransform$1;
14148
+ exports.buildTransformer = buildTransformer;
14173
14149
  exports.calcAxisDelta = calcAxisDelta;
14174
14150
  exports.calcBoxDelta = calcBoxDelta;
14175
14151
  exports.calcChildStagger = calcChildStagger;