motion-dom 13.4.5 → 13.5.1

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 (73) hide show
  1. package/dist/cjs/index.js +698 -790
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/FollowAnimation.mjs +1 -4
  4. package/dist/es/animation/FollowAnimation.mjs.map +1 -1
  5. package/dist/es/animation/NativeAnimation.mjs +5 -5
  6. package/dist/es/animation/NativeAnimation.mjs.map +1 -1
  7. package/dist/es/animation/drivers/frame.mjs +2 -1
  8. package/dist/es/animation/drivers/frame.mjs.map +1 -1
  9. package/dist/es/animation/generators/spring.mjs +64 -35
  10. package/dist/es/animation/generators/spring.mjs.map +1 -1
  11. package/dist/es/animation/interfaces/visual-element-target.mjs +2 -4
  12. package/dist/es/animation/interfaces/visual-element-target.mjs.map +1 -1
  13. package/dist/es/animation/interfaces/visual-element-variant.mjs +29 -49
  14. package/dist/es/animation/interfaces/visual-element-variant.mjs.map +1 -1
  15. package/dist/es/animation/interfaces/visual-element.mjs +5 -14
  16. package/dist/es/animation/interfaces/visual-element.mjs.map +1 -1
  17. package/dist/es/animation/utils/notify-inspector.mjs +1 -1
  18. package/dist/es/animation/utils/notify-inspector.mjs.map +1 -1
  19. package/dist/es/effects/MotionValueState.mjs +6 -1
  20. package/dist/es/effects/MotionValueState.mjs.map +1 -1
  21. package/dist/es/effects/style/index.mjs +1 -1
  22. package/dist/es/effects/style/index.mjs.map +1 -1
  23. package/dist/es/effects/svg/index.mjs +18 -7
  24. package/dist/es/effects/svg/index.mjs.map +1 -1
  25. package/dist/es/frameloop/batcher.mjs +5 -6
  26. package/dist/es/frameloop/batcher.mjs.map +1 -1
  27. package/dist/es/frameloop/frame-data.mjs +12 -0
  28. package/dist/es/frameloop/frame-data.mjs.map +1 -0
  29. package/dist/es/frameloop/frame.mjs +3 -2
  30. package/dist/es/frameloop/frame.mjs.map +1 -1
  31. package/dist/es/frameloop/sync-time.mjs +1 -1
  32. package/dist/es/frameloop/sync-time.mjs.map +1 -1
  33. package/dist/es/index.mjs +3 -2
  34. package/dist/es/index.mjs.map +1 -1
  35. package/dist/es/layout/LayoutAnimationBuilder.mjs +2 -1
  36. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  37. package/dist/es/projection/animation/mix-values.mjs +1 -1
  38. package/dist/es/projection/animation/mix-values.mjs.map +1 -1
  39. package/dist/es/projection/node/create-projection-node.mjs +11 -1
  40. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  41. package/dist/es/projection/styles/default-scale-correctors.mjs +18 -0
  42. package/dist/es/projection/styles/default-scale-correctors.mjs.map +1 -0
  43. package/dist/es/projection/styles/scale-correction.mjs +1 -14
  44. package/dist/es/projection/styles/scale-correction.mjs.map +1 -1
  45. package/dist/es/projection/utils/each-axis.mjs.map +1 -1
  46. package/dist/es/render/VisualElement.mjs +29 -59
  47. package/dist/es/render/VisualElement.mjs.map +1 -1
  48. package/dist/es/render/svg/SVGVisualElement.mjs +19 -1
  49. package/dist/es/render/svg/SVGVisualElement.mjs.map +1 -1
  50. package/dist/es/render/utils/animation-state.mjs +144 -267
  51. package/dist/es/render/utils/animation-state.mjs.map +1 -1
  52. package/dist/es/render/utils/resolve-dynamic-variants.mjs +7 -3
  53. package/dist/es/render/utils/resolve-dynamic-variants.mjs.map +1 -1
  54. package/dist/es/render/utils/resolve-variants.mjs +8 -19
  55. package/dist/es/render/utils/resolve-variants.mjs.map +1 -1
  56. package/dist/es/scroll/observe.mjs +4 -0
  57. package/dist/es/scroll/observe.mjs.map +1 -1
  58. package/dist/es/value/follow-value.mjs +8 -85
  59. package/dist/es/value/follow-value.mjs.map +1 -1
  60. package/dist/es/value/spring-value.mjs +8 -3
  61. package/dist/es/value/spring-value.mjs.map +1 -1
  62. package/dist/es/value/utils/as-number.mjs +4 -0
  63. package/dist/es/value/utils/as-number.mjs.map +1 -0
  64. package/dist/es/value/utils/follow.mjs +94 -0
  65. package/dist/es/value/utils/follow.mjs.map +1 -0
  66. package/dist/index.d.ts +55 -30
  67. package/dist/motion-dom.dev.js +698 -790
  68. package/dist/motion-dom.js +1 -1
  69. package/dist/size-rollup-motion-value.js +1 -1
  70. package/dist/size-rollup-motion-value.js.map +1 -1
  71. package/dist/size-rollup-style-effect.js +1 -1
  72. package/dist/size-rollup-style-effect.js.map +1 -1
  73. package/package.json +6 -5
package/dist/cjs/index.js CHANGED
@@ -4,170 +4,15 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var motionUtils = require('motion-utils');
6
6
 
7
- const stepsOrder = [
8
- "setup", // Compute
9
- "read", // Read
10
- "resolveKeyframes", // Write/Read/Write/Read
11
- "preUpdate", // Compute
12
- "update", // Compute
13
- "preRender", // Compute
14
- "render", // Write
15
- "postRender", // Compute
16
- ];
17
-
18
- function createRenderStep(runNextFrame) {
19
- /**
20
- * We create and reuse two queues, one to queue jobs for the current frame
21
- * and one for the next. We reuse to avoid triggering GC after x frames.
22
- */
23
- let thisFrame = new Set();
24
- let nextFrame = new Set();
25
- /**
26
- * Track whether we're currently processing jobs in this step. This way
27
- * we can decide whether to schedule new jobs for this frame or next.
28
- */
29
- let isProcessing = false;
30
- let flushNextFrame = false;
31
- /**
32
- * A set of processes which were marked keepAlive when scheduled.
33
- * A keepAlive process is always also held by a frame queue until
34
- * it's cancelled, so a Set has the same lifetime semantics as a
35
- * WeakSet here while being considerably faster to query every frame.
36
- */
37
- const toKeepAlive = new Set();
38
- let latestFrameData = {
39
- delta: 0.0,
40
- timestamp: 0.0,
41
- isProcessing: false,
42
- };
43
- function triggerCallback(callback) {
44
- if (toKeepAlive.has(callback)) {
45
- nextFrame.add(callback);
46
- runNextFrame();
47
- }
48
- callback(latestFrameData);
49
- }
50
- const step = {
51
- /**
52
- * Schedule a process to run on the next frame.
53
- */
54
- schedule: (callback, keepAlive = false, immediate = false) => {
55
- const addToCurrentFrame = immediate && isProcessing;
56
- const queue = addToCurrentFrame ? thisFrame : nextFrame;
57
- if (keepAlive)
58
- toKeepAlive.add(callback);
59
- queue.add(callback);
60
- return callback;
61
- },
62
- /**
63
- * Cancel the provided callback from running on the next frame.
64
- */
65
- cancel: (callback) => {
66
- nextFrame.delete(callback);
67
- toKeepAlive.delete(callback);
68
- },
69
- /**
70
- * Execute all schedule callbacks.
71
- */
72
- process: (frameData) => {
73
- latestFrameData = frameData;
74
- /**
75
- * If we're already processing we've probably been triggered by a flushSync
76
- * inside an existing process. Instead of executing, mark flushNextFrame
77
- * as true and ensure we flush the following frame at the end of this one.
78
- */
79
- if (isProcessing) {
80
- flushNextFrame = true;
81
- return;
82
- }
83
- isProcessing = true;
84
- // Swap this frame and the next to avoid GC
85
- const prevFrame = thisFrame;
86
- thisFrame = nextFrame;
87
- nextFrame = prevFrame;
88
- // Execute this frame
89
- thisFrame.forEach(triggerCallback);
90
- // Clear the frame so no callbacks remain. This is to avoid
91
- // memory leaks should this render step not run for a while.
92
- thisFrame.clear();
93
- isProcessing = false;
94
- if (flushNextFrame) {
95
- flushNextFrame = false;
96
- step.process(frameData);
97
- }
98
- },
99
- };
100
- return step;
101
- }
102
-
103
- const maxElapsed = 40;
104
- function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
105
- let runNextFrame = false;
106
- let useDefaultElapsed = true;
107
- const state = {
108
- delta: 0.0,
109
- timestamp: 0.0,
110
- isProcessing: false,
111
- };
112
- const flagRunNextFrame = () => (runNextFrame = true);
113
- const steps = stepsOrder.reduce((acc, key) => {
114
- acc[key] = createRenderStep(flagRunNextFrame);
115
- return acc;
116
- }, {});
117
- const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps;
118
- const processBatch = () => {
119
- const useManualTiming = motionUtils.MotionGlobalConfig.useManualTiming;
120
- const timestamp = useManualTiming
121
- ? state.timestamp
122
- : performance.now();
123
- runNextFrame = false;
124
- if (!useManualTiming) {
125
- state.delta = useDefaultElapsed
126
- ? 1000 / 60
127
- : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
128
- }
129
- state.timestamp = timestamp;
130
- state.isProcessing = true;
131
- // Unrolled render loop for better per-frame performance
132
- setup.process(state);
133
- read.process(state);
134
- resolveKeyframes.process(state);
135
- preUpdate.process(state);
136
- update.process(state);
137
- preRender.process(state);
138
- render.process(state);
139
- postRender.process(state);
140
- state.isProcessing = false;
141
- if (runNextFrame && allowKeepAlive) {
142
- useDefaultElapsed = false;
143
- scheduleNextBatch(processBatch);
144
- }
145
- };
146
- const wake = () => {
147
- runNextFrame = true;
148
- useDefaultElapsed = true;
149
- if (!state.isProcessing) {
150
- scheduleNextBatch(processBatch);
151
- }
152
- };
153
- const schedule = stepsOrder.reduce((acc, key) => {
154
- const step = steps[key];
155
- acc[key] = (process, keepAlive = false, immediate = false) => {
156
- if (!runNextFrame)
157
- wake();
158
- return step.schedule(process, keepAlive, immediate);
159
- };
160
- return acc;
161
- }, {});
162
- const cancel = (process) => {
163
- for (let i = 0; i < stepsOrder.length; i++) {
164
- steps[stepsOrder[i]].cancel(process);
165
- }
166
- };
167
- return { schedule, cancel, state, steps };
168
- }
169
-
170
- const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : motionUtils.noop, true);
7
+ /**
8
+ * The frameloop's state, kept apart from the frameloop itself so that
9
+ * reading it doesn't bundle the scheduler.
10
+ */
11
+ const frameData = {
12
+ delta: 0.0,
13
+ timestamp: 0.0,
14
+ isProcessing: false,
15
+ };
171
16
 
172
17
  let now;
173
18
  function clearTime() {
@@ -751,6 +596,170 @@ function mix(from, to, p) {
751
596
  return mixer(from, to);
752
597
  }
753
598
 
599
+ const stepsOrder = [
600
+ "setup", // Compute
601
+ "read", // Read
602
+ "resolveKeyframes", // Write/Read/Write/Read
603
+ "preUpdate", // Compute
604
+ "update", // Compute
605
+ "preRender", // Compute
606
+ "render", // Write
607
+ "postRender", // Compute
608
+ ];
609
+
610
+ function createRenderStep(runNextFrame) {
611
+ /**
612
+ * We create and reuse two queues, one to queue jobs for the current frame
613
+ * and one for the next. We reuse to avoid triggering GC after x frames.
614
+ */
615
+ let thisFrame = new Set();
616
+ let nextFrame = new Set();
617
+ /**
618
+ * Track whether we're currently processing jobs in this step. This way
619
+ * we can decide whether to schedule new jobs for this frame or next.
620
+ */
621
+ let isProcessing = false;
622
+ let flushNextFrame = false;
623
+ /**
624
+ * A set of processes which were marked keepAlive when scheduled.
625
+ * A keepAlive process is always also held by a frame queue until
626
+ * it's cancelled, so a Set has the same lifetime semantics as a
627
+ * WeakSet here while being considerably faster to query every frame.
628
+ */
629
+ const toKeepAlive = new Set();
630
+ let latestFrameData = {
631
+ delta: 0.0,
632
+ timestamp: 0.0,
633
+ isProcessing: false,
634
+ };
635
+ function triggerCallback(callback) {
636
+ if (toKeepAlive.has(callback)) {
637
+ nextFrame.add(callback);
638
+ runNextFrame();
639
+ }
640
+ callback(latestFrameData);
641
+ }
642
+ const step = {
643
+ /**
644
+ * Schedule a process to run on the next frame.
645
+ */
646
+ schedule: (callback, keepAlive = false, immediate = false) => {
647
+ const addToCurrentFrame = immediate && isProcessing;
648
+ const queue = addToCurrentFrame ? thisFrame : nextFrame;
649
+ if (keepAlive)
650
+ toKeepAlive.add(callback);
651
+ queue.add(callback);
652
+ return callback;
653
+ },
654
+ /**
655
+ * Cancel the provided callback from running on the next frame.
656
+ */
657
+ cancel: (callback) => {
658
+ nextFrame.delete(callback);
659
+ toKeepAlive.delete(callback);
660
+ },
661
+ /**
662
+ * Execute all schedule callbacks.
663
+ */
664
+ process: (frameData) => {
665
+ latestFrameData = frameData;
666
+ /**
667
+ * If we're already processing we've probably been triggered by a flushSync
668
+ * inside an existing process. Instead of executing, mark flushNextFrame
669
+ * as true and ensure we flush the following frame at the end of this one.
670
+ */
671
+ if (isProcessing) {
672
+ flushNextFrame = true;
673
+ return;
674
+ }
675
+ isProcessing = true;
676
+ // Swap this frame and the next to avoid GC
677
+ const prevFrame = thisFrame;
678
+ thisFrame = nextFrame;
679
+ nextFrame = prevFrame;
680
+ // Execute this frame
681
+ thisFrame.forEach(triggerCallback);
682
+ // Clear the frame so no callbacks remain. This is to avoid
683
+ // memory leaks should this render step not run for a while.
684
+ thisFrame.clear();
685
+ isProcessing = false;
686
+ if (flushNextFrame) {
687
+ flushNextFrame = false;
688
+ step.process(frameData);
689
+ }
690
+ },
691
+ };
692
+ return step;
693
+ }
694
+
695
+ const maxElapsed = 40;
696
+ function createRenderBatcher(scheduleNextBatch, allowKeepAlive, state = {
697
+ delta: 0.0,
698
+ timestamp: 0.0,
699
+ isProcessing: false,
700
+ }) {
701
+ let runNextFrame = false;
702
+ let useDefaultElapsed = true;
703
+ const flagRunNextFrame = () => (runNextFrame = true);
704
+ const steps = stepsOrder.reduce((acc, key) => {
705
+ acc[key] = createRenderStep(flagRunNextFrame);
706
+ return acc;
707
+ }, {});
708
+ const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps;
709
+ const processBatch = () => {
710
+ const useManualTiming = motionUtils.MotionGlobalConfig.useManualTiming;
711
+ const timestamp = useManualTiming
712
+ ? state.timestamp
713
+ : performance.now();
714
+ runNextFrame = false;
715
+ if (!useManualTiming) {
716
+ state.delta = useDefaultElapsed
717
+ ? 1000 / 60
718
+ : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
719
+ }
720
+ state.timestamp = timestamp;
721
+ state.isProcessing = true;
722
+ // Unrolled render loop for better per-frame performance
723
+ setup.process(state);
724
+ read.process(state);
725
+ resolveKeyframes.process(state);
726
+ preUpdate.process(state);
727
+ update.process(state);
728
+ preRender.process(state);
729
+ render.process(state);
730
+ postRender.process(state);
731
+ state.isProcessing = false;
732
+ if (runNextFrame && allowKeepAlive) {
733
+ useDefaultElapsed = false;
734
+ scheduleNextBatch(processBatch);
735
+ }
736
+ };
737
+ const wake = () => {
738
+ runNextFrame = true;
739
+ useDefaultElapsed = true;
740
+ if (!state.isProcessing) {
741
+ scheduleNextBatch(processBatch);
742
+ }
743
+ };
744
+ const schedule = stepsOrder.reduce((acc, key) => {
745
+ const step = steps[key];
746
+ acc[key] = (process, keepAlive = false, immediate = false) => {
747
+ if (!runNextFrame)
748
+ wake();
749
+ return step.schedule(process, keepAlive, immediate);
750
+ };
751
+ return acc;
752
+ }, {});
753
+ const cancel = (process) => {
754
+ for (let i = 0; i < stepsOrder.length; i++) {
755
+ steps[stepsOrder[i]].cancel(process);
756
+ }
757
+ };
758
+ return { schedule, cancel, state, steps };
759
+ }
760
+
761
+ const { schedule: frame, cancel: cancelFrame, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : motionUtils.noop, true, frameData);
762
+
754
763
  const frameloopDriver = (update) => {
755
764
  const passTimestamp = ({ timestamp }) => update(timestamp);
756
765
  return {
@@ -829,8 +838,37 @@ const springDefaults = {
829
838
  minDuration: 0.01, // in seconds
830
839
  maxDuration: 10.0, // in seconds
831
840
  minDamping: 0.05,
832
- maxDamping: 1,
833
841
  };
842
+ /**
843
+ * Maps bounce to a damping ratio as SwiftUI does: 0 is critically damped, and
844
+ * it approaches undamped towards 1 and infinitely overdamped towards -1. Both
845
+ * ends are limited so the spring still moves and settles.
846
+ */
847
+ const bounceToDampingRatio = (bounce) => bounce < 0
848
+ ? 1 / Math.max(1 + bounce, springDefaults.minDamping)
849
+ : Math.max(1 - bounce, springDefaults.minDamping);
850
+ /**
851
+ * Scales an overdamped spring's undamped frequency so that, at its defining
852
+ * time, it has as far left to go as the critically damped spring that's
853
+ * criticalFreqTime radians in by then. A negative bounce then changes the
854
+ * shape of the curve, not when it arrives. 1 at a damping ratio of 1, so
855
+ * there's no jump at a bounce of 0.
856
+ *
857
+ * Solved by Newton on the remaining distance (times fast - slow), which is
858
+ * convex from criticalFreqTime onwards. criticalFreqTime is always below the
859
+ * answer, so it converges from below without overshooting.
860
+ */
861
+ function overdampedFreqScale(dampingRatio, criticalFreqTime) {
862
+ if (!(dampingRatio > 1))
863
+ return 1;
864
+ const root = Math.sqrt(dampingRatio * dampingRatio - 1);
865
+ const slow = dampingRatio - root;
866
+ const fast = dampingRatio + root;
867
+ const target = 2 * root * Math.exp(-criticalFreqTime) * (1 + criticalFreqTime);
868
+ return (approximateRoot((freqTime) => fast * Math.exp(-slow * freqTime) -
869
+ slow * Math.exp(-fast * freqTime) -
870
+ target, (freqTime) => Math.exp(-fast * freqTime) - Math.exp(-slow * freqTime), criticalFreqTime) / criticalFreqTime);
871
+ }
834
872
  function calcAngularFreq(undampedFreq, dampingRatio) {
835
873
  return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
836
874
  }
@@ -855,11 +893,7 @@ function findSpring({ duration = springDefaults.duration, bounce = springDefault
855
893
  let envelope;
856
894
  let derivative;
857
895
  motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
858
- let dampingRatio = 1 - bounce;
859
- /**
860
- * Restrict dampingRatio and duration to within acceptable ranges.
861
- */
862
- dampingRatio = motionUtils.clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);
896
+ const dampingRatio = bounceToDampingRatio(bounce);
863
897
  duration = motionUtils.clamp(springDefaults.minDuration, springDefaults.maxDuration, motionUtils.millisecondsToSeconds(duration));
864
898
  if (dampingRatio < 1) {
865
899
  /**
@@ -888,7 +922,8 @@ function findSpring({ duration = springDefaults.duration, bounce = springDefault
888
922
  }
889
923
  else {
890
924
  /**
891
- * Critically-damped spring
925
+ * Critically-damped spring. Overdamped springs reuse this root,
926
+ * scaled below.
892
927
  */
893
928
  envelope = (undampedFreq) => {
894
929
  const a = Math.exp(-undampedFreq * duration);
@@ -902,7 +937,9 @@ function findSpring({ duration = springDefaults.duration, bounce = springDefault
902
937
  };
903
938
  }
904
939
  const initialGuess = 5 / duration;
905
- const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
940
+ const criticalFreq = approximateRoot(envelope, derivative, initialGuess);
941
+ const undampedFreq = criticalFreq *
942
+ overdampedFreqScale(dampingRatio, criticalFreq * duration);
906
943
  const stiffness = undampedFreq * undampedFreq;
907
944
  return {
908
945
  stiffness,
@@ -952,12 +989,12 @@ function getSpringOptions(options) {
952
989
  };
953
990
  if (springOptions.isTimeDefined) {
954
991
  if (options.visualDuration) {
955
- const root = (2 * Math.PI) / (options.visualDuration * 1.2);
992
+ const dampingRatio = bounceToDampingRatio(options.bounce || 0);
993
+ const root = ((2 * Math.PI) / (options.visualDuration * 1.2)) *
994
+ overdampedFreqScale(dampingRatio, (2 * Math.PI) / 1.2);
956
995
  springOptions.stiffness = root * root;
957
996
  springOptions.damping =
958
- 2 *
959
- motionUtils.clamp(0.05, 1, 1 - (options.bounce || 0)) *
960
- Math.sqrt(springOptions.stiffness);
997
+ 2 * dampingRatio * Math.sqrt(springOptions.stiffness);
961
998
  }
962
999
  else {
963
1000
  Object.assign(springOptions, findSpring(springOptions));
@@ -1092,31 +1129,32 @@ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce
1092
1129
  (undampedAngularFreq * c.C * t - s.velocity);
1093
1130
  }
1094
1131
  else {
1095
- // Overdamped spring
1132
+ /**
1133
+ * Overdamped spring: the sum of a slow and a fast decaying
1134
+ * exponential, so no term can overflow however heavily it's damped.
1135
+ */
1096
1136
  const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
1097
- resolveSpring = (t) => {
1098
- const envelope = Math.exp(-decay * t);
1099
- // When performing sinh or cosh values can hit Infinity so we cap them here
1100
- const freqForT = Math.min(dampedAngularFreq * t, 300);
1101
- return (s.target -
1102
- (envelope *
1103
- ((s.velocity + decay * s.delta) * Math.sinh(freqForT) +
1104
- dampedAngularFreq * s.delta * Math.cosh(freqForT))) /
1105
- dampedAngularFreq);
1106
- };
1107
- // Analytical derivative of overdamped spring (px/ms)
1108
- const c = { P: 0, sinh: 0, cosh: 0 };
1137
+ const slow = decay - dampedAngularFreq;
1138
+ const fast = decay + dampedAngularFreq;
1139
+ /**
1140
+ * Physics-defined springs keep a non-physical limit: once
1141
+ * dampedAngularFreq * t passes 300, both terms decay at the damping
1142
+ * rate. Heavily overdamped drag springs (dragElastic: 0,
1143
+ * dragTransition) rely on this to settle almost at once rather than
1144
+ * creep at stiffness / damping. Negative bounce needs the exact
1145
+ * curve, so time-defined springs are exempt.
1146
+ */
1147
+ const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;
1148
+ const decayAt = (rate, t) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);
1149
+ const c = { S: 0, F: 0 };
1109
1150
  update = () => {
1110
- c.P = (s.velocity + decay * s.delta) / dampedAngularFreq;
1111
- c.sinh = decay * c.P - s.delta * dampedAngularFreq;
1112
- c.cosh = decay * s.delta - c.P * dampedAngularFreq;
1113
- };
1114
- resolveVelocity = (t) => {
1115
- const envelope = Math.exp(-decay * t);
1116
- const freqForT = Math.min(dampedAngularFreq * t, 300);
1117
- return (envelope *
1118
- (c.sinh * Math.sinh(freqForT) + c.cosh * Math.cosh(freqForT)));
1151
+ const P = (s.velocity + decay * s.delta) / dampedAngularFreq;
1152
+ c.S = (s.delta + P) / 2;
1153
+ c.F = (s.delta - P) / 2;
1119
1154
  };
1155
+ resolveSpring = (t) => s.target - c.S * decayAt(slow, t) - c.F * decayAt(fast, t);
1156
+ // Analytical derivative of overdamped spring (px/ms)
1157
+ resolveVelocity = (t) => slow * c.S * decayAt(slow, t) + fast * c.F * decayAt(fast, t);
1120
1158
  }
1121
1159
  update();
1122
1160
  const calculatedDuration = isResolvedFromDuration ? duration || null : null;
@@ -2695,17 +2733,17 @@ class NativeAnimation extends WithPromise {
2695
2733
  /**
2696
2734
  * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
2697
2735
  */
2698
- attachTimeline({ timeline, rangeStart, rangeEnd, observe, }) {
2736
+ attachTimeline({ timeline, onAttach, observe,
2737
+ // Deprecated rangeStart/rangeEnd from framer-motion 13.0–13.4. Removed in v14.
2738
+ ...range }) {
2699
2739
  if (this.allowFlatten) {
2700
2740
  this.animation.effect?.updateTiming({ easing: "linear" });
2701
2741
  }
2702
2742
  this.animation.onfinish = null;
2703
2743
  if (timeline && supportsScrollTimeline()) {
2704
2744
  this.animation.timeline = timeline;
2705
- if (rangeStart)
2706
- this.animation.rangeStart = rangeStart;
2707
- if (rangeEnd)
2708
- this.animation.rangeEnd = rangeEnd;
2745
+ Object.assign(this.animation, range);
2746
+ onAttach?.(this.animation);
2709
2747
  return motionUtils.noop;
2710
2748
  }
2711
2749
  else {
@@ -4042,36 +4080,29 @@ function getValueState(visualElement) {
4042
4080
  return state;
4043
4081
  }
4044
4082
  function resolveVariantFromProps(props, definition, custom, visualElement) {
4083
+ const resolveFunction = (def) => typeof def === "function"
4084
+ ? def(custom !== undefined ? custom : props.custom, ...getValueState(visualElement))
4085
+ : def;
4045
4086
  /**
4046
- * If the variant definition is a function, resolve.
4047
- */
4048
- if (typeof definition === "function") {
4049
- const [current, velocity] = getValueState(visualElement);
4050
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
4051
- }
4052
- /**
4053
- * If the variant definition is a variant label, or
4054
- * the function returned a variant label, resolve.
4087
+ * Resolve a function, then a variant label (which the function may have
4088
+ * returned), then a function again as the label may point to one. The
4089
+ * final function can only return a target object.
4055
4090
  */
4091
+ definition = resolveFunction(definition);
4056
4092
  if (typeof definition === "string") {
4057
4093
  definition = props.variants && props.variants[definition];
4058
4094
  }
4059
- /**
4060
- * At this point we've resolved both functions and variant labels,
4061
- * but the resolved variant label might itself have been a function.
4062
- * If so, resolve. This can only have returned a valid target object.
4063
- */
4064
- if (typeof definition === "function") {
4065
- const [current, velocity] = getValueState(visualElement);
4066
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
4067
- }
4068
- return definition;
4095
+ return resolveFunction(definition);
4069
4096
  }
4070
4097
 
4071
4098
  function resolveVariant(visualElement, definition, custom) {
4072
- const props = visualElement.getProps();
4073
- return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);
4099
+ return resolveVariantFromProps(visualElement.getProps(), definition, custom, visualElement);
4074
4100
  }
4101
+ /**
4102
+ * Exit variants resolve with AnimatePresence's custom, every other type
4103
+ * with the element's own.
4104
+ */
4105
+ const getTypeCustom = (visualElement, type) => type === "exit" ? visualElement.presenceContext?.custom : undefined;
4075
4106
 
4076
4107
  const positionalKeys = new Set([
4077
4108
  "width",
@@ -4154,7 +4185,7 @@ const isBrowser$1 = typeof window !== "undefined";
4154
4185
  * had been set to true in the meantime.
4155
4186
  */
4156
4187
  function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
4157
- const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
4188
+ const shouldBlock = key in protectedKeys && !needsAnimating[key];
4158
4189
  needsAnimating[key] = false;
4159
4190
  return shouldBlock;
4160
4191
  }
@@ -4169,9 +4200,7 @@ function animateTarget(visualElement, targetAndTransition, { delay = 0, transiti
4169
4200
  if (transitionOverride)
4170
4201
  transition = transitionOverride;
4171
4202
  const animations = [];
4172
- const animationTypeState = type &&
4173
- visualElement.animationState &&
4174
- visualElement.animationState.getState()[type];
4203
+ const animationTypeState = type && visualElement.animationState?.getState()[type];
4175
4204
  const path = transition?.path;
4176
4205
  if (path) {
4177
4206
  // path mutates `target` to claim x/y; loop below skips them.
@@ -4245,75 +4274,46 @@ function animateTarget(visualElement, targetAndTransition, { delay = 0, transiti
4245
4274
  }
4246
4275
 
4247
4276
  function animateVariant(visualElement, variant, options = {}) {
4248
- const resolved = resolveVariant(visualElement, variant, options.type === "exit"
4249
- ? visualElement.presenceContext?.custom
4250
- : undefined);
4251
- let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
4252
- if (options.transitionOverride) {
4253
- transition = options.transitionOverride;
4254
- }
4255
- /**
4256
- * If we have a variant, create a callback that runs it as an animation.
4257
- * Otherwise, we resolve a Promise immediately for a composable no-op.
4258
- */
4259
- const getAnimation = resolved
4260
- ? () => Promise.all(animateTarget(visualElement, resolved, options))
4261
- : () => Promise.resolve();
4262
- /**
4263
- * If we have children, create a callback that runs all their animations.
4264
- * Otherwise, we resolve a Promise immediately for a composable no-op.
4265
- */
4266
- const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size
4267
- ? (forwardDelay = 0) => {
4268
- const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
4269
- return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options);
4270
- }
4271
- : () => Promise.resolve();
4277
+ const resolved = resolveVariant(visualElement, variant, getTypeCustom(visualElement, options.type));
4278
+ const transition = options.transitionOverride ||
4279
+ (resolved?.transition ?? (visualElement.getDefaultTransition() || {}));
4280
+ const getAnimation = () => Promise.all(resolved ? animateTarget(visualElement, resolved, options) : []);
4281
+ const getChildAnimations = (delay = 0) => {
4282
+ const { variantChildren } = visualElement;
4283
+ const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
4284
+ const animations = [];
4285
+ variantChildren?.forEach((child) => {
4286
+ child.notify("AnimationStart", variant);
4287
+ animations.push(animateVariant(child, variant, {
4288
+ ...options,
4289
+ delay: delay +
4290
+ (typeof delayChildren === "function"
4291
+ ? 0
4292
+ : delayChildren) +
4293
+ calcChildStagger(variantChildren, child, delayChildren, staggerChildren, staggerDirection),
4294
+ }).then(() => child.notify("AnimationComplete", variant)));
4295
+ });
4296
+ return Promise.all(animations);
4297
+ };
4272
4298
  /**
4273
- * If the transition explicitly defines a "when" option, we need to resolve either
4274
- * this animation or all children animations before playing the other.
4299
+ * when: "beforeChildren" | "afterChildren" runs this element's animation
4300
+ * and its children's in sequence.
4275
4301
  */
4276
4302
  const { when } = transition;
4277
- if (when) {
4278
- const [first, last] = when === "beforeChildren"
4279
- ? [getAnimation, getChildAnimations]
4280
- : [getChildAnimations, getAnimation];
4281
- return first().then(() => last());
4282
- }
4283
- else {
4284
- return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
4285
- }
4286
- }
4287
- function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
4288
- const animations = [];
4289
- for (const child of visualElement.variantChildren) {
4290
- child.notify("AnimationStart", variant);
4291
- animations.push(animateVariant(child, variant, {
4292
- ...options,
4293
- delay: delay +
4294
- (typeof delayChildren === "function" ? 0 : delayChildren) +
4295
- calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection),
4296
- }).then(() => child.notify("AnimationComplete", variant)));
4297
- }
4298
- return Promise.all(animations);
4303
+ return when
4304
+ ? when === "beforeChildren"
4305
+ ? getAnimation().then(() => getChildAnimations())
4306
+ : getChildAnimations().then(getAnimation)
4307
+ : Promise.all([getAnimation(), getChildAnimations(options.delay)]);
4299
4308
  }
4300
4309
 
4301
4310
  function animateVisualElement(visualElement, definition, options = {}) {
4302
4311
  visualElement.notify("AnimationStart", definition);
4303
- let animation;
4304
- if (Array.isArray(definition)) {
4305
- const animations = definition.map((variant) => animateVariant(visualElement, variant, options));
4306
- animation = Promise.all(animations);
4307
- }
4308
- else if (typeof definition === "string") {
4309
- animation = animateVariant(visualElement, definition, options);
4310
- }
4311
- else {
4312
- const resolvedDefinition = typeof definition === "function"
4313
- ? resolveVariant(visualElement, definition, options.custom)
4314
- : definition;
4315
- animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));
4316
- }
4312
+ const animation = Array.isArray(definition)
4313
+ ? Promise.all(definition.map((variant) => animateVariant(visualElement, variant, options)))
4314
+ : typeof definition === "string"
4315
+ ? animateVariant(visualElement, definition, options)
4316
+ : Promise.all(animateTarget(visualElement, resolveVariant(visualElement, definition, options.custom), options));
4317
4317
  return animation.then(() => {
4318
4318
  visualElement.notify("AnimationComplete", definition);
4319
4319
  });
@@ -4839,7 +4839,12 @@ class MotionValueState {
4839
4839
  const onRemove = () => {
4840
4840
  cancelOnChange();
4841
4841
  render && !computed && this.cancel(render);
4842
- this.values.delete(name);
4842
+ /**
4843
+ * A later set() of the same name has already removed this
4844
+ * entry, so leave the one that replaced it.
4845
+ */
4846
+ this.values.get(name)?.onRemove === onRemove &&
4847
+ this.values.delete(name);
4843
4848
  };
4844
4849
  this.values.set(name, {
4845
4850
  value,
@@ -5318,24 +5323,35 @@ const addSVGValue = (element, state, key, value) => {
5318
5323
  else if (key.startsWith("attr")) {
5319
5324
  return addAttrValue(element, state, key, value, convertAttrKey(key));
5320
5325
  }
5321
- const handler = isCSSVar(key) || key in element.style ? addStyleValue : addAttrValue;
5326
+ /**
5327
+ * Transforms and origins aren't CSS properties (bar `x`/`y` in some
5328
+ * browsers), so check them by name rather than `key in element.style`.
5329
+ */
5330
+ const handler = transformProps.has(key) ||
5331
+ originProps.has(key) ||
5332
+ isCSSVar(key) ||
5333
+ key in element.style
5334
+ ? addStyleValue
5335
+ : addAttrValue;
5322
5336
  return handler(element, state, key, value);
5323
5337
  };
5324
5338
  /**
5325
5339
  * Reads the current value of `key` from an SVG element as the origin of
5326
5340
  * an animation, as the SVG VisualElement does: transforms start from
5327
5341
  * their defaults, CSS variables and the few CSS-only properties come from
5328
- * computed style
5329
- * and everything else is read from the attribute, dash-cased
5330
- * (`strokeWidth` -> `stroke-width`) or, failing that, as written
5331
- * (`baseFrequency`).
5342
+ * computed style, falling back to the attribute when that's empty (e.g.
5343
+ * the element isn't rendered), and everything else is read from the
5344
+ * attribute, dash-cased (`strokeWidth` -> `stroke-width`) or, failing
5345
+ * that, as written (`baseFrequency`).
5332
5346
  */
5333
5347
  const readSVGValue = (element, key) => {
5334
5348
  if (transformProps.has(key)) {
5335
5349
  return numberValueTypes[key]?.default || 0;
5336
5350
  }
5337
5351
  if (isCSSVar(key) || cssStyleProperties.includes(key)) {
5338
- return readStyleValue(element, key);
5352
+ return (readStyleValue(element, key) ||
5353
+ element.getAttribute(camelToDash(key)) ||
5354
+ 0);
5339
5355
  }
5340
5356
  key = convertAttrKey(key);
5341
5357
  return (element.getAttribute(camelToDash(key)) ??
@@ -6038,6 +6054,10 @@ function resize(a, b) {
6038
6054
  return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
6039
6055
  }
6040
6056
 
6057
+ /**
6058
+ * @deprecated Kept because framer-motion 13.0–13.4 import it from
6059
+ * motion-dom with a ^ range. Removed in v14.
6060
+ */
6041
6061
  function observeTimeline(update, timeline) {
6042
6062
  let prevProgress;
6043
6063
  const onFrame = () => {
@@ -6166,8 +6186,7 @@ class FollowAnimation extends WithPromise {
6166
6186
  this.options.onStop?.();
6167
6187
  };
6168
6188
  this.options = options;
6169
- replaceTransitionType(options);
6170
- this.factory = options.type || keyframes;
6189
+ this.factory = options.type;
6171
6190
  this.generator = this.factory(options);
6172
6191
  const { driver } = options;
6173
6192
  if (driver)
@@ -6268,41 +6287,15 @@ class FollowAnimation extends WithPromise {
6268
6287
  }
6269
6288
  }
6270
6289
 
6290
+ const asNumber = (v) => typeof v === "number" ? v : parseFloat(v);
6291
+
6271
6292
  /**
6272
- * Create a `MotionValue` that animates to its latest value using any transition type.
6273
- * Can either be a value or track another `MotionValue`.
6274
- *
6275
- * ```jsx
6276
- * const x = motionValue(0)
6277
- * const y = followValue(x, { type: "spring", stiffness: 300 })
6278
- * // or with tween
6279
- * const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
6280
- * ```
6281
- *
6282
- * @param source - Initial value or MotionValue to track
6283
- * @param options - Animation transition options
6284
- * @returns `MotionValue`
6285
- *
6286
- * @public
6287
- */
6288
- function followValue(source, options) {
6289
- const initialValue = isMotionValue(source) ? source.get() : source;
6290
- const value = motionValue(initialValue);
6291
- attachFollow(value, source, options);
6292
- return value;
6293
- }
6294
- /**
6295
- * Attach an animation to a MotionValue that will animate whenever the value changes.
6296
- * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
6297
- *
6298
- * @param value - The MotionValue to animate
6299
- * @param source - Initial value or MotionValue to track
6300
- * @param options - Animation transition options
6301
- * @returns Cleanup function
6302
- *
6303
- * @public
6293
+ * Animate `value` to its latest value with the generator in
6294
+ * `options.type`, tracking `source` if it's a `MotionValue`. Takes a
6295
+ * generator rather than a type name, so spring-only callers don't
6296
+ * bundle every generator.
6304
6297
  */
6305
- function attachFollow(value, source, options = {}) {
6298
+ function follow(value, source, options) {
6306
6299
  const initialValue = value.get();
6307
6300
  let activeAnimation = null;
6308
6301
  let set;
@@ -6320,7 +6313,7 @@ function attachFollow(value, source, options = {}) {
6320
6313
  };
6321
6314
  value.attach((v, safeSet) => {
6322
6315
  set = safeSet;
6323
- const target = asNumber$1(v);
6316
+ const target = asNumber(v);
6324
6317
  if (activeAnimation?.state === "running") {
6325
6318
  /**
6326
6319
  * Steer the running animation rather than replacing it. This
@@ -6331,7 +6324,7 @@ function attachFollow(value, source, options = {}) {
6331
6324
  activeAnimation.setTarget(target, options.velocity);
6332
6325
  return;
6333
6326
  }
6334
- const current = asNumber$1(value.get());
6327
+ const current = asNumber(value.get());
6335
6328
  const velocity = activeAnimation
6336
6329
  ? activeAnimation.getGeneratorVelocity()
6337
6330
  : value.getVelocity();
@@ -6342,8 +6335,6 @@ function attachFollow(value, source, options = {}) {
6342
6335
  const animationOptions = {
6343
6336
  keyframes: [current, target],
6344
6337
  velocity,
6345
- // Default to spring if no type specified (matches useSpring behavior)
6346
- type: "spring",
6347
6338
  restDelta: 0.001,
6348
6339
  restSpeed: 0.01,
6349
6340
  ...options,
@@ -6385,8 +6376,47 @@ function attachFollow(value, source, options = {}) {
6385
6376
  function parseValue(v, unit) {
6386
6377
  return unit ? v + unit : v;
6387
6378
  }
6388
- function asNumber$1(v) {
6389
- return typeof v === "number" ? v : parseFloat(v);
6379
+
6380
+ /**
6381
+ * Create a `MotionValue` that animates to its latest value using any transition type.
6382
+ * Can either be a value or track another `MotionValue`.
6383
+ *
6384
+ * ```jsx
6385
+ * const x = motionValue(0)
6386
+ * const y = followValue(x, { type: "spring", stiffness: 300 })
6387
+ * // or with tween
6388
+ * const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
6389
+ * ```
6390
+ *
6391
+ * @param source - Initial value or MotionValue to track
6392
+ * @param options - Animation transition options
6393
+ * @returns `MotionValue`
6394
+ *
6395
+ * @public
6396
+ */
6397
+ function followValue(source, options) {
6398
+ const initialValue = isMotionValue(source) ? source.get() : source;
6399
+ const value = motionValue(initialValue);
6400
+ attachFollow(value, source, options);
6401
+ return value;
6402
+ }
6403
+ /**
6404
+ * Attach an animation to a MotionValue that will animate whenever the value changes.
6405
+ * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
6406
+ *
6407
+ * @param value - The MotionValue to animate
6408
+ * @param source - Initial value or MotionValue to track
6409
+ * @param options - Animation transition options
6410
+ * @returns Cleanup function
6411
+ *
6412
+ * @public
6413
+ */
6414
+ function attachFollow(value, source, options = {}) {
6415
+ // Default to spring if no type specified (matches useSpring behavior)
6416
+ const transition = { type: "spring", ...options };
6417
+ replaceTransitionType(transition);
6418
+ transition.type = transition.type || keyframes;
6419
+ return follow(value, source, transition);
6390
6420
  }
6391
6421
 
6392
6422
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -6488,7 +6518,9 @@ function mapValue(inputValue, inputRange, outputRange, options) {
6488
6518
  * @public
6489
6519
  */
6490
6520
  function springValue(source, options) {
6491
- return followValue(source, { type: "spring", ...options });
6521
+ const value = motionValue(isMotionValue(source) ? source.get() : source);
6522
+ attachSpring(value, source, options);
6523
+ return value;
6492
6524
  }
6493
6525
  /**
6494
6526
  * Attach a spring animation to a MotionValue that will animate whenever the value changes.
@@ -6501,7 +6533,7 @@ function springValue(source, options) {
6501
6533
  * @public
6502
6534
  */
6503
6535
  function attachSpring(value, source, options) {
6504
- return attachFollow(value, source, { type: "spring", ...options });
6536
+ return follow(value, source, { ...options, type: spring });
6505
6537
  }
6506
6538
 
6507
6539
  /**
@@ -7923,8 +7955,20 @@ class VisualElement {
7923
7955
  if (this.projection && !this.projection.instance) {
7924
7956
  this.projection.mount(instance);
7925
7957
  }
7926
- if (this.parent && this.isVariantNode && !this.isControllingVariants) {
7927
- this.removeFromVariantTree = this.parent.addVariantChild(this);
7958
+ /**
7959
+ * Join the closest variant node above, so its variant changes
7960
+ * propagate here, unless inherit={false} cuts the chain.
7961
+ */
7962
+ if (this.isVariantNode && !this.isControllingVariants) {
7963
+ let node = this;
7964
+ do
7965
+ node = node.props.inherit !== false && node.parent;
7966
+ while (node && !node.isVariantNode);
7967
+ if (node) {
7968
+ const { variantChildren } = node;
7969
+ variantChildren.add(this);
7970
+ this.removeFromVariantTree = () => variantChildren.delete(this);
7971
+ }
7928
7972
  }
7929
7973
  this.values.forEach((value, key) => this.bindToMotionValue(key, value));
7930
7974
  /**
@@ -8034,9 +8078,11 @@ class VisualElement {
8034
8078
  }
8035
8079
  sortNodePosition(other) {
8036
8080
  /**
8037
- * If these nodes aren't even of the same type we can't compare their depth.
8081
+ * If either node isn't mounted, or they aren't even of the same type,
8082
+ * we can't compare their document order.
8038
8083
  */
8039
8084
  if (!this.current ||
8085
+ !other.current ||
8040
8086
  !this.sortInstanceNodePosition ||
8041
8087
  this.type !== other.type) {
8042
8088
  return 0;
@@ -8142,24 +8188,6 @@ class VisualElement {
8142
8188
  getTransformPagePoint() {
8143
8189
  return this.props.transformPagePoint;
8144
8190
  }
8145
- getClosestVariantNode() {
8146
- return this.isVariantNode
8147
- ? this
8148
- : this.parent
8149
- ? this.parent.getClosestVariantNode()
8150
- : undefined;
8151
- }
8152
- /**
8153
- * Add a child visual element to our set of children.
8154
- */
8155
- addVariantChild(child) {
8156
- const closestVariantNode = this.getClosestVariantNode();
8157
- if (closestVariantNode) {
8158
- closestVariantNode.variantChildren &&
8159
- closestVariantNode.variantChildren.add(child);
8160
- return () => closestVariantNode.variantChildren.delete(child);
8161
- }
8162
- }
8163
8191
  /**
8164
8192
  * Add a motion value and bind it to this visual element.
8165
8193
  */
@@ -8171,7 +8199,15 @@ class VisualElement {
8171
8199
  this.removeValue(key);
8172
8200
  this.bindToMotionValue(key, value);
8173
8201
  this.values.set(key, value);
8174
- this.latestValues[key] = value.get();
8202
+ /**
8203
+ * An animated value with no base value is undefined until the
8204
+ * keyframe resolver reads its origin. Rendering it before then
8205
+ * writes an invalid placeholder (e.g. points="undefined") that
8206
+ * the resolver can read back from the DOM as the origin.
8207
+ */
8208
+ const latest = value.get();
8209
+ if (latest !== undefined)
8210
+ this.latestValues[key] = latest;
8175
8211
  }
8176
8212
  }
8177
8213
  /**
@@ -8199,7 +8235,9 @@ class VisualElement {
8199
8235
  }
8200
8236
  let value = this.values.get(key);
8201
8237
  if (value === undefined && defaultValue !== undefined) {
8202
- value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this });
8238
+ value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
8239
+ owner: this,
8240
+ });
8203
8241
  this.addValue(key, value);
8204
8242
  }
8205
8243
  return value;
@@ -8244,41 +8282,6 @@ class VisualElement {
8244
8282
  setBaseTarget(key, value) {
8245
8283
  this.baseTarget[key] = value;
8246
8284
  }
8247
- /**
8248
- * Find the base target for a value thats been removed from all animation
8249
- * props.
8250
- */
8251
- getBaseTarget(key) {
8252
- const { initial } = this.props;
8253
- let valueFromInitial;
8254
- if (typeof initial === "string" || typeof initial === "object") {
8255
- const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom);
8256
- if (variant) {
8257
- valueFromInitial = variant[key];
8258
- }
8259
- }
8260
- /**
8261
- * If this value still exists in the current initial variant, read that.
8262
- */
8263
- if (initial && valueFromInitial !== undefined) {
8264
- return valueFromInitial;
8265
- }
8266
- /**
8267
- * Alternatively, if this VisualElement config has defined a getBaseTarget
8268
- * so we can read the value from an alternative source, try that.
8269
- */
8270
- const target = this.getBaseTargetFromProps(this.props, key);
8271
- if (target !== undefined && !isMotionValue(target))
8272
- return target;
8273
- /**
8274
- * If the value was initially defined on initial, but it doesn't any more,
8275
- * return undefined. Otherwise return the value as initially read from the DOM.
8276
- */
8277
- return this.initialValues[key] !== undefined &&
8278
- valueFromInitial === undefined
8279
- ? undefined
8280
- : this.baseTarget[key];
8281
- }
8282
8285
  on(eventName, callback) {
8283
8286
  if (!this.events[eventName]) {
8284
8287
  this.events[eventName] = new motionUtils.SubscriptionManager();
@@ -8342,105 +8345,26 @@ class Feature {
8342
8345
  this.isMounted = false;
8343
8346
  this.node = node;
8344
8347
  }
8345
- update() { }
8346
- }
8347
-
8348
- function renderHTML(element, { style, vars }, styleProp, projection) {
8349
- const elementStyle = element.style;
8350
- let key;
8351
- for (key in style) {
8352
- // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.
8353
- elementStyle[key] = style[key];
8354
- }
8355
- // Write projection styles directly to element style
8356
- projection?.applyProjectionStyles(elementStyle, styleProp);
8357
- for (key in vars) {
8358
- // Loop over any CSS variables and assign those.
8359
- // They can only be assigned using `setProperty`.
8360
- elementStyle.setProperty(key, vars[key]);
8361
- }
8362
- }
8363
-
8364
- function pixelsToPercent(pixels, axis) {
8365
- if (axis.max === axis.min)
8366
- return 0;
8367
- return (pixels / (axis.max - axis.min)) * 100;
8368
- }
8369
- /**
8370
- * We always correct borderRadius as a percentage rather than pixels to reduce paints.
8371
- * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
8372
- * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
8373
- * borderRadius in both states. If we animate between the two in pixels that will trigger
8374
- * a paint each time. If we animate between the two in percentage we'll avoid a paint.
8375
- */
8376
- const correctBorderRadius = {
8377
- correct: (latest, node) => {
8378
- if (!node.target)
8379
- return latest;
8380
- /**
8381
- * If latest is a string, if it's a percentage we can return immediately as it's
8382
- * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
8383
- */
8384
- if (typeof latest === "string") {
8385
- if (px.test(latest)) {
8386
- latest = parseFloat(latest);
8387
- }
8388
- else {
8389
- return latest;
8390
- }
8391
- }
8392
- /**
8393
- * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
8394
- * pixel value as a percentage of each axis
8395
- */
8396
- const x = pixelsToPercent(latest, node.target.x);
8397
- const y = pixelsToPercent(latest, node.target.y);
8398
- return `${x}% ${y}%`;
8399
- },
8400
- };
8401
-
8402
- const correctBoxShadow = {
8403
- correct: (latest, { treeScale, projectionDelta }) => {
8404
- const original = latest;
8405
- const shadow = complex.parse(latest);
8406
- // TODO: Doesn't support multiple shadows
8407
- if (shadow.length > 5)
8408
- return original;
8409
- const template = complex.createTransformer(latest);
8410
- const offset = typeof shadow[0] !== "number" ? 1 : 0;
8411
- // Calculate the overall context scale
8412
- const xScale = projectionDelta.x.scale * treeScale.x;
8413
- const yScale = projectionDelta.y.scale * treeScale.y;
8414
- shadow[0 + offset] /= xScale;
8415
- shadow[1 + offset] /= yScale;
8416
- /**
8417
- * Ideally we'd correct x and y scales individually, but because blur and
8418
- * spread apply to both we have to take a scale average and apply that instead.
8419
- * We could potentially improve the outcome of this by incorporating the ratio between
8420
- * the two scales.
8421
- */
8422
- const averageScale = mixNumber$1(xScale, yScale, 0.5);
8423
- // Blur
8424
- if (typeof shadow[2 + offset] === "number")
8425
- shadow[2 + offset] /= averageScale;
8426
- // Spread
8427
- if (typeof shadow[3 + offset] === "number")
8428
- shadow[3 + offset] /= averageScale;
8429
- return template(shadow);
8430
- },
8431
- };
8348
+ update() { }
8349
+ }
8432
8350
 
8433
- const scaleCorrectors = {
8434
- borderRadius: {
8435
- ...correctBorderRadius,
8436
- applyTo: [...cornerRadiusProps],
8437
- },
8438
- borderTopLeftRadius: correctBorderRadius,
8439
- borderTopRightRadius: correctBorderRadius,
8440
- borderBottomLeftRadius: correctBorderRadius,
8441
- borderBottomRightRadius: correctBorderRadius,
8442
- boxShadow: correctBoxShadow,
8443
- };
8351
+ function renderHTML(element, { style, vars }, styleProp, projection) {
8352
+ const elementStyle = element.style;
8353
+ let key;
8354
+ for (key in style) {
8355
+ // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.
8356
+ elementStyle[key] = style[key];
8357
+ }
8358
+ // Write projection styles directly to element style
8359
+ projection?.applyProjectionStyles(elementStyle, styleProp);
8360
+ for (key in vars) {
8361
+ // Loop over any CSS variables and assign those.
8362
+ // They can only be assigned using `setProperty`.
8363
+ elementStyle.setProperty(key, vars[key]);
8364
+ }
8365
+ }
8366
+
8367
+ const scaleCorrectors = {};
8444
8368
  function addScaleCorrector(correctors) {
8445
8369
  for (const key in correctors) {
8446
8370
  scaleCorrectors[key] = correctors[key];
@@ -8614,7 +8538,24 @@ class SVGVisualElement extends DOMVisualElement {
8614
8538
  this.measureInstanceViewportBox = createBox;
8615
8539
  }
8616
8540
  getBaseTargetFromProps(props, key) {
8617
- return props[key];
8541
+ /**
8542
+ * An independent transform's base is never an attribute of the same
8543
+ * name, e.g. <rect x> is a position, not a translate. Like HTML it
8544
+ * comes from style, falling back to the transform's default.
8545
+ */
8546
+ return transformProps.has(key)
8547
+ ? super.getBaseTargetFromProps(props, key) ??
8548
+ defaultTransformValue(key)
8549
+ : props[key];
8550
+ }
8551
+ /**
8552
+ * An independent transform's origin is never read from the DOM, so it
8553
+ * starts from its latest or default value and renders on mount.
8554
+ */
8555
+ getDefaultValue(key) {
8556
+ return transformProps.has(key)
8557
+ ? this.latestValues[key] ?? defaultTransformValue(key)
8558
+ : undefined;
8618
8559
  }
8619
8560
  readValueFromInstance(instance, key) {
8620
8561
  if (transformProps.has(key)) {
@@ -8645,34 +8586,6 @@ class SVGVisualElement extends DOMVisualElement {
8645
8586
  }
8646
8587
  }
8647
8588
 
8648
- const numVariantProps = variantProps.length;
8649
- /**
8650
- * Get variant context from a visual element's parent chain.
8651
- * Uses `any` type for visualElement to avoid circular dependencies.
8652
- */
8653
- function getVariantContext(visualElement) {
8654
- if (!visualElement)
8655
- return undefined;
8656
- if (!visualElement.isControllingVariants) {
8657
- const context = visualElement.parent
8658
- ? getVariantContext(visualElement.parent) || {}
8659
- : {};
8660
- if (visualElement.props.initial !== undefined) {
8661
- context.initial = visualElement.props.initial;
8662
- }
8663
- return context;
8664
- }
8665
- const context = {};
8666
- for (let i = 0; i < numVariantProps; i++) {
8667
- const name = variantProps[i];
8668
- const prop = visualElement.props[name];
8669
- if (isVariantLabel(prop) || prop === false) {
8670
- context[name] = prop;
8671
- }
8672
- }
8673
- return context;
8674
- }
8675
-
8676
8589
  function shallowCompare(next, prev) {
8677
8590
  if (!Array.isArray(prev))
8678
8591
  return false;
@@ -8687,332 +8600,211 @@ function shallowCompare(next, prev) {
8687
8600
  }
8688
8601
 
8689
8602
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
8690
- const numAnimationTypes = variantPriorityOrder.length;
8691
- function createAnimateFunction(visualElement) {
8692
- return (animations) => {
8693
- return Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
8694
- };
8695
- }
8603
+ /**
8604
+ * Diffs the element's animation props (one layer per AnimationType, highest
8605
+ * priority wins each value) against the previous call and starts animations
8606
+ * for what changed.
8607
+ *
8608
+ * Uses `any` type for visualElement to avoid circular dependencies. It reads
8609
+ * props, parent, presenceContext, variantChildren, enteringChildren,
8610
+ * manuallyAnimateOnMount, blockInitialAnimation, getValue(),
8611
+ * getBaseTargetFromProps(), baseTarget and initialValues.
8612
+ */
8696
8613
  function createAnimationState(visualElement) {
8697
- let animate = createAnimateFunction(visualElement);
8614
+ let animate = (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
8698
8615
  let state = createState();
8699
8616
  let isInitialRender = true;
8700
8617
  /**
8701
- * Track whether the animation state has been reset (e.g. via StrictMode
8702
- * double-invocation or Suspense unmount/remount). On the first
8703
- * animateChanges() call after a reset we need to behave like the initial
8704
- * render for variant-inheritance checks, even though isInitialRender is
8705
- * already false.
8618
+ * After a reset (StrictMode, Suspense, AnimatePresence re-entry) the next
8619
+ * animateChanges() mounts again, but initial={false} no longer applies.
8706
8620
  */
8707
8621
  let wasReset = false;
8708
- /**
8709
- * This function will be used to reduce the animation definitions for
8710
- * each active animation type into an object of resolved values for it.
8711
- */
8712
- const buildResolvedTypeValues = (type) => (acc, definition) => {
8713
- const resolved = resolveVariant(visualElement, definition, type === "exit"
8714
- ? visualElement.presenceContext?.custom
8715
- : undefined);
8716
- if (resolved) {
8717
- const { transition, transitionEnd, ...target } = resolved;
8718
- acc = { ...acc, ...target, ...transitionEnd };
8719
- }
8720
- return acc;
8721
- };
8722
- /**
8723
- * This just allows us to inject mocked animation functions
8724
- * @internal
8725
- */
8726
- function setAnimateFunction(makeAnimator) {
8727
- animate = makeAnimator(visualElement);
8728
- }
8729
- /**
8730
- * When we receive new props, we need to:
8731
- * 1. Create a list of protected keys for each type. This is a directory of
8732
- * value keys that are currently being "handled" by types of a higher priority
8733
- * so that whenever an animation is played of a given type, these values are
8734
- * protected from being animated.
8735
- * 2. Determine if an animation type needs animating.
8736
- * 3. Determine if any values have been removed from a type and figure out
8737
- * what to animate those to.
8738
- */
8739
8622
  function animateChanges(changedActiveType) {
8740
- const { props } = visualElement;
8741
- const context = getVariantContext(visualElement.parent) || {};
8742
- /**
8743
- * A list of animations that we'll build into as we iterate through the animation
8744
- * types. This will get executed at the end of the function.
8745
- */
8623
+ const { props, parent, manuallyAnimateOnMount } = visualElement;
8624
+ const isMounting = isInitialRender || wasReset;
8746
8625
  const animations = [];
8747
8626
  /**
8748
- * Keep track of which values have been removed. Then, as we hit lower priority
8749
- * animation types, we can check if they contain removed values and animate to that.
8627
+ * Values removed from a type. A lower-priority type that defines
8628
+ * them animates them back, otherwise they fall back to a base target.
8750
8629
  */
8751
8630
  const removedKeys = new Set();
8752
8631
  /**
8753
- * A dictionary of all encountered keys. This is an object to let us build into and
8754
- * copy it without iteration. Each time we hit an animation type we set its protected
8755
- * keys - the keys its not allowed to animate - to the latest version of this object.
8632
+ * Values claimed by active, higher-priority types.
8756
8633
  */
8757
8634
  let encounteredKeys = {};
8758
8635
  /**
8759
- * If a variant has been removed at a given index, and this component is controlling
8760
- * variant animations, we want to ensure lower-priority variants are forced to animate.
8636
+ * Once a type has been deactivated, lower-priority variant labels
8637
+ * re-animate so variant children animate back too.
8761
8638
  */
8762
8639
  let removedVariantIndex = Infinity;
8763
8640
  /**
8764
- * Iterate through all animation types in reverse priority order. For each, we want to
8765
- * detect which values it's handling and whether or not they've changed (and therefore
8766
- * need to be animated). If any values have been removed, we want to detect those in
8767
- * lower priority props and flag for animation.
8641
+ * Variant labels are inherited from the closest variant-controlling
8642
+ * ancestor, unless an element on the way has inherit={false}.
8768
8643
  */
8769
- for (let i = 0; i < numAnimationTypes; i++) {
8770
- const type = reversePriorityOrder[i];
8644
+ let source = visualElement;
8645
+ do
8646
+ source = source.props.inherit !== false && source.parent;
8647
+ while (source && !source.isControllingVariants);
8648
+ reversePriorityOrder.forEach((type, i) => {
8771
8649
  const typeState = state[type];
8772
- const prop = props[type] !== undefined
8773
- ? props[type]
8774
- : context[type];
8650
+ const ownProp = props[type];
8651
+ const inheritedProp = source && source.props[type];
8652
+ const prop = ownProp !== undefined
8653
+ ? ownProp
8654
+ : isVariantLabel(inheritedProp) || inheritedProp === false
8655
+ ? inheritedProp
8656
+ : undefined;
8775
8657
  const propIsVariant = isVariantLabel(prop);
8776
- /**
8777
- * If this type has *just* changed isActive status, set activeDelta
8778
- * to that status. Otherwise set to null.
8779
- */
8780
8658
  const activeDelta = type === changedActiveType ? typeState.isActive : null;
8781
8659
  if (activeDelta === false)
8782
8660
  removedVariantIndex = i;
8783
8661
  /**
8784
- * If this prop is an inherited variant, rather than been set directly on the
8785
- * component itself, we want to make sure we allow the parent to trigger animations.
8786
- *
8787
- * TODO: Can probably change this to a !isControllingVariants check
8788
- */
8789
- let isInherited = prop === context[type] &&
8790
- prop !== props[type] &&
8791
- propIsVariant;
8792
- if (isInherited &&
8793
- (isInitialRender || wasReset) &&
8794
- visualElement.manuallyAnimateOnMount) {
8795
- isInherited = false;
8796
- }
8797
- /**
8798
- * Set all encountered keys so far as the protected keys for this type. This will
8799
- * be any key that has been animated or otherwise handled by active, higher-priority types.
8662
+ * Inherited labels are animated by the parent through
8663
+ * variantChildren, unless this element mounted after its parent.
8800
8664
  */
8665
+ const isInherited = propIsVariant &&
8666
+ ownProp === undefined &&
8667
+ !(isMounting && manuallyAnimateOnMount);
8801
8668
  typeState.protectedKeys = { ...encounteredKeys };
8802
- // Check if we can skip analysing this prop early
8803
- if (
8804
- // If it isn't active and hasn't *just* been set as inactive
8805
- (!typeState.isActive && activeDelta === null) ||
8806
- // If we didn't and don't have any defined prop for this animation type
8669
+ if ((!typeState.isActive && activeDelta === null) ||
8807
8670
  (!prop && !typeState.prevProp) ||
8808
- // Or if the prop doesn't define an animation
8809
8671
  isAnimationControls(prop) ||
8810
8672
  typeof prop === "boolean") {
8811
- continue;
8673
+ return;
8812
8674
  }
8813
8675
  /**
8814
- * If exit is already active and wasn't just activated, skip
8815
- * re-processing to prevent interrupting running exit animations.
8816
- * Re-resolving exit with a changed custom value can start new
8817
- * value animations that stop the originals, leaving the exit
8818
- * animation promise unresolved and the component stuck in the DOM.
8676
+ * Don't re-resolve a running exit: a changed custom would start
8677
+ * new value animations that stop the originals, leaving the exit
8678
+ * promise unresolved and the element stuck in the DOM.
8819
8679
  */
8820
8680
  if (type === "exit" && typeState.isActive && activeDelta !== true) {
8821
- if (typeState.prevResolvedValues) {
8822
- encounteredKeys = {
8823
- ...encounteredKeys,
8824
- ...typeState.prevResolvedValues,
8825
- };
8826
- }
8827
- continue;
8681
+ encounteredKeys = {
8682
+ ...encounteredKeys,
8683
+ ...typeState.prevResolvedValues,
8684
+ };
8685
+ return;
8828
8686
  }
8829
- /**
8830
- * As we go look through the values defined on this type, if we detect
8831
- * a changed value or a value that was removed in a higher priority, we set
8832
- * this to true and add this prop to the animation list.
8833
- */
8834
8687
  const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
8835
8688
  let shouldAnimateType = variantDidChange ||
8836
- // If we're making this variant active, we want to always make it active
8837
- (type === changedActiveType &&
8838
- typeState.isActive &&
8839
- !isInherited &&
8840
- propIsVariant) ||
8841
- // If we removed a higher-priority variant (i is in reverse order)
8842
- (i > removedVariantIndex && propIsVariant);
8689
+ (propIsVariant &&
8690
+ ((activeDelta && !isInherited) || i > removedVariantIndex));
8843
8691
  let handledRemovedValues = false;
8844
- /**
8845
- * As animations can be set as variant lists, variants or target objects, we
8846
- * coerce everything to an array if it isn't one already
8847
- */
8848
8692
  const definitionList = Array.isArray(prop) ? prop : [prop];
8849
- /**
8850
- * Build an object of all the resolved values. We'll use this in the subsequent
8851
- * animateChanges calls to determine whether a value has changed.
8852
- */
8853
- let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {});
8854
- if (activeDelta === false)
8855
- resolvedValues = {};
8856
- /**
8857
- * Now we need to loop through all the keys in the prev prop and this prop,
8858
- * and decide:
8859
- * 1. If the value has changed, and needs animating
8860
- * 2. If it has been removed, and needs adding to the removedKeys set
8861
- * 3. If it has been removed in a higher priority type and needs animating
8862
- * 4. If it hasn't been removed in a higher priority but hasn't changed, and
8863
- * needs adding to the type's protectedKeys list.
8864
- */
8865
- const { prevResolvedValues = {} } = typeState;
8866
- const allKeys = {
8867
- ...prevResolvedValues,
8868
- ...resolvedValues,
8869
- };
8870
- const markToAnimate = (key) => {
8871
- shouldAnimateType = true;
8872
- if (removedKeys.has(key)) {
8873
- handledRemovedValues = true;
8874
- removedKeys.delete(key);
8693
+ let resolvedValues = {};
8694
+ if (activeDelta !== false) {
8695
+ for (const definition of definitionList) {
8696
+ const { transition, transitionEnd, ...target } = resolveVariant(visualElement, definition, getTypeCustom(visualElement, type)) || {};
8697
+ resolvedValues = {
8698
+ ...resolvedValues,
8699
+ ...target,
8700
+ ...transitionEnd,
8701
+ };
8875
8702
  }
8876
- typeState.needsAnimating[key] = true;
8877
- const motionValue = visualElement.getValue(key);
8878
- if (motionValue)
8879
- motionValue.liveStyle = false;
8880
- };
8881
- for (const key in allKeys) {
8703
+ }
8704
+ const { prevResolvedValues } = typeState;
8705
+ for (const key in { ...prevResolvedValues, ...resolvedValues }) {
8706
+ if (key in encounteredKeys)
8707
+ continue;
8882
8708
  const next = resolvedValues[key];
8883
8709
  const prev = prevResolvedValues[key];
8884
- // If we've already handled this we can just skip ahead
8885
- if (encounteredKeys.hasOwnProperty(key))
8886
- continue;
8887
8710
  /**
8888
- * If the value has changed, we probably want to animate it.
8711
+ * Keyframes compare by value, but replay whenever the
8712
+ * variant label changed.
8889
8713
  */
8890
- let valueHasChanged = false;
8891
- if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
8892
- valueHasChanged =
8893
- !shallowCompare(next, prev) || variantDidChange;
8894
- }
8895
- else {
8896
- valueHasChanged = next !== prev;
8897
- }
8898
- if (valueHasChanged) {
8899
- if (next !== undefined && next !== null) {
8900
- // If next is defined and doesn't equal prev, it needs animating
8901
- markToAnimate(key);
8902
- }
8903
- else {
8904
- // If it's undefined, it's been removed.
8905
- removedKeys.add(key);
8906
- }
8714
+ const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
8715
+ ? !shallowCompare(next, prev) || variantDidChange
8716
+ : next !== prev;
8717
+ if (valueHasChanged &&
8718
+ (next === undefined || next === null)) {
8719
+ removedKeys.add(key);
8907
8720
  }
8908
- else if (next !== undefined && removedKeys.has(key)) {
8909
- /**
8910
- * If next hasn't changed and it isn't undefined, we want to check if it's
8911
- * been removed by a higher priority
8912
- */
8913
- markToAnimate(key);
8721
+ else if (valueHasChanged ||
8722
+ (next !== undefined && removedKeys.has(key))) {
8723
+ shouldAnimateType = true;
8724
+ if (removedKeys.delete(key))
8725
+ handledRemovedValues = true;
8726
+ typeState.needsAnimating[key] = true;
8727
+ const motionValue = visualElement.getValue(key);
8728
+ if (motionValue)
8729
+ motionValue.liveStyle = false;
8914
8730
  }
8915
8731
  else {
8916
- /**
8917
- * If it hasn't changed, we add it to the list of protected values
8918
- * to ensure it doesn't get animated.
8919
- */
8920
8732
  typeState.protectedKeys[key] = true;
8921
8733
  }
8922
8734
  }
8923
- /**
8924
- * Update the typeState so next time animateChanges is called we can compare the
8925
- * latest prop and resolvedValues to these.
8926
- */
8927
8735
  typeState.prevProp = prop;
8928
8736
  typeState.prevResolvedValues = resolvedValues;
8929
8737
  if (typeState.isActive) {
8930
8738
  encounteredKeys = { ...encounteredKeys, ...resolvedValues };
8931
8739
  }
8932
- if ((isInitialRender || wasReset) &&
8933
- visualElement.blockInitialAnimation) {
8934
- shouldAnimateType = false;
8935
- }
8936
- /**
8937
- * If this is an inherited prop we want to skip this animation
8938
- * unless the inherited variants haven't changed on this render.
8939
- */
8940
- const willAnimateViaParent = isInherited && variantDidChange;
8941
- const needsAnimating = !willAnimateViaParent || handledRemovedValues;
8942
- if (shouldAnimateType && needsAnimating) {
8943
- animations.push(...definitionList.map((animation) => {
8740
+ if (shouldAnimateType &&
8741
+ (!(isInherited && variantDidChange) || handledRemovedValues)) {
8742
+ for (const animation of definitionList) {
8944
8743
  const options = { type };
8945
8744
  /**
8946
- * If we're performing the initial animation, but we're not
8947
- * rendering at the same time as the variant-controlling parent,
8948
- * we want to use the parent's transition to calculate the stagger.
8745
+ * Elements that mount into an already-mounted parent
8746
+ * animate themselves, staggered by the parent variant's
8747
+ * delayChildren.
8949
8748
  */
8950
8749
  if (typeof animation === "string" &&
8951
- (isInitialRender || wasReset) &&
8952
- !willAnimateViaParent &&
8953
- visualElement.manuallyAnimateOnMount &&
8954
- visualElement.parent) {
8955
- const { parent } = visualElement;
8956
- const parentVariant = resolveVariant(parent, animation);
8957
- if (parent.enteringChildren && parentVariant) {
8958
- const { delayChildren } = parentVariant.transition || {};
8959
- options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);
8960
- }
8750
+ isMounting &&
8751
+ manuallyAnimateOnMount &&
8752
+ parent?.enteringChildren) {
8753
+ const delayChildren = resolveVariant(parent, animation)
8754
+ ?.transition?.delayChildren;
8755
+ options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);
8961
8756
  }
8962
- return {
8963
- animation: animation,
8964
- options,
8965
- };
8966
- }));
8757
+ animations.push({ animation, options });
8758
+ }
8967
8759
  }
8968
- }
8760
+ });
8969
8761
  /**
8970
- * If there are some removed value that haven't been dealt with,
8971
- * we need to create a new animation that falls back either to the value
8972
- * defined in the style prop, or the last read value.
8762
+ * Removed values that no lower-priority type defines animate back to
8763
+ * initial, then style, then the value as first read. If initial no
8764
+ * longer defines a value it once did, it stays where it is.
8973
8765
  */
8974
8766
  if (removedKeys.size) {
8767
+ const { initial } = props;
8975
8768
  const fallbackAnimation = {};
8976
- /**
8977
- * If the initial prop contains a transition we can use that, otherwise
8978
- * allow the animation function to use the visual element's default.
8979
- */
8980
- if (typeof props.initial !== "boolean") {
8981
- const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial)
8982
- ? props.initial[0]
8983
- : props.initial);
8984
- if (initialTransition && initialTransition.transition) {
8985
- fallbackAnimation.transition = initialTransition.transition;
8986
- }
8769
+ const resolvedInitial = typeof initial !== "boolean" &&
8770
+ resolveVariant(visualElement, Array.isArray(initial) ? initial[0] : initial, visualElement.presenceContext?.custom);
8771
+ if (resolvedInitial && resolvedInitial.transition) {
8772
+ fallbackAnimation.transition = resolvedInitial.transition;
8987
8773
  }
8988
8774
  removedKeys.forEach((key) => {
8989
- const fallbackTarget = visualElement.getBaseTarget(key);
8990
8775
  const motionValue = visualElement.getValue(key);
8991
8776
  if (motionValue)
8992
8777
  motionValue.liveStyle = true;
8993
- // @ts-expect-error - @mattgperry to figure if we should do something here
8994
- fallbackAnimation[key] = fallbackTarget ?? null;
8778
+ const fromInitial = resolvedInitial && !Array.isArray(initial)
8779
+ ? resolvedInitial[key]
8780
+ : undefined;
8781
+ const fromProps = visualElement.getBaseTargetFromProps(props, key);
8782
+ fallbackAnimation[key] =
8783
+ (fromInitial !== undefined
8784
+ ? fromInitial
8785
+ : fromProps !== undefined && !isMotionValue(fromProps)
8786
+ ? fromProps
8787
+ : visualElement.initialValues[key] === undefined
8788
+ ? visualElement.baseTarget[key]
8789
+ : undefined) ?? null;
8995
8790
  });
8996
8791
  animations.push({ animation: fallbackAnimation });
8997
8792
  }
8998
- let shouldAnimate = Boolean(animations.length);
8999
- if (isInitialRender &&
9000
- (props.initial === false || props.initial === props.animate) &&
9001
- !visualElement.manuallyAnimateOnMount) {
9002
- shouldAnimate = false;
9003
- }
9004
- isInitialRender = false;
9005
- wasReset = false;
9006
- return shouldAnimate ? animate(animations) : Promise.resolve();
8793
+ const blockAnimation = (isMounting && visualElement.blockInitialAnimation) ||
8794
+ (isInitialRender &&
8795
+ !manuallyAnimateOnMount &&
8796
+ (props.initial === false || props.initial === props.animate));
8797
+ isInitialRender = wasReset = false;
8798
+ return !blockAnimation && animations.length
8799
+ ? animate(animations)
8800
+ : Promise.resolve();
9007
8801
  }
9008
8802
  /**
9009
8803
  * Change whether a certain animation type is active.
9010
8804
  */
9011
8805
  function setActive(type, isActive) {
9012
- // If the active state hasn't changed, we can safely do nothing here
9013
8806
  if (state[type].isActive === isActive)
9014
8807
  return Promise.resolve();
9015
- // Propagate active change to children
9016
8808
  visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive));
9017
8809
  state[type].isActive = isActive;
9018
8810
  const animations = animateChanges(type);
@@ -9024,7 +8816,13 @@ function createAnimationState(visualElement) {
9024
8816
  return {
9025
8817
  animateChanges,
9026
8818
  setActive,
9027
- setAnimateFunction,
8819
+ /**
8820
+ * Allows tests to inject a mocked animate function.
8821
+ * @internal
8822
+ */
8823
+ setAnimateFunction: (makeAnimator) => {
8824
+ animate = makeAnimator(visualElement);
8825
+ },
9028
8826
  getState: () => state,
9029
8827
  reset: () => {
9030
8828
  state = createState();
@@ -9041,24 +8839,45 @@ function checkVariantsDidChange(prev, next) {
9041
8839
  }
9042
8840
  return false;
9043
8841
  }
9044
- function createTypeState(isActive = false) {
9045
- return {
9046
- isActive,
9047
- protectedKeys: {},
9048
- needsAnimating: {},
9049
- prevResolvedValues: {},
9050
- };
9051
- }
9052
8842
  function createState() {
9053
- return {
9054
- animate: createTypeState(true),
9055
- whileInView: createTypeState(),
9056
- whileHover: createTypeState(),
9057
- whileTap: createTypeState(),
9058
- whileDrag: createTypeState(),
9059
- whileFocus: createTypeState(),
9060
- exit: createTypeState(),
9061
- };
8843
+ const state = {};
8844
+ for (const type of variantPriorityOrder) {
8845
+ state[type] = {
8846
+ isActive: type === "animate",
8847
+ protectedKeys: {},
8848
+ needsAnimating: {},
8849
+ prevResolvedValues: {},
8850
+ };
8851
+ }
8852
+ return state;
8853
+ }
8854
+
8855
+ const numVariantProps = variantProps.length;
8856
+ /**
8857
+ * Get variant context from a visual element's parent chain.
8858
+ * Uses `any` type for visualElement to avoid circular dependencies.
8859
+ */
8860
+ function getVariantContext(visualElement) {
8861
+ if (!visualElement)
8862
+ return undefined;
8863
+ if (!visualElement.isControllingVariants) {
8864
+ const context = visualElement.parent
8865
+ ? getVariantContext(visualElement.parent) || {}
8866
+ : {};
8867
+ if (visualElement.props.initial !== undefined) {
8868
+ context.initial = visualElement.props.initial;
8869
+ }
8870
+ return context;
8871
+ }
8872
+ const context = {};
8873
+ for (let i = 0; i < numVariantProps; i++) {
8874
+ const name = variantProps[i];
8875
+ const prop = visualElement.props[name];
8876
+ if (isVariantLabel(prop) || prop === false) {
8877
+ context[name] = prop;
8878
+ }
8879
+ }
8880
+ return context;
9062
8881
  }
9063
8882
 
9064
8883
  /**
@@ -9227,6 +9046,75 @@ function eachAxis(callback) {
9227
9046
  return [callback("x"), callback("y")];
9228
9047
  }
9229
9048
 
9049
+ function pixelsToPercent(pixels, axis) {
9050
+ if (axis.max === axis.min)
9051
+ return 0;
9052
+ return (pixels / (axis.max - axis.min)) * 100;
9053
+ }
9054
+ /**
9055
+ * We always correct borderRadius as a percentage rather than pixels to reduce paints.
9056
+ * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
9057
+ * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
9058
+ * borderRadius in both states. If we animate between the two in pixels that will trigger
9059
+ * a paint each time. If we animate between the two in percentage we'll avoid a paint.
9060
+ */
9061
+ const correctBorderRadius = {
9062
+ correct: (latest, node) => {
9063
+ if (!node.target)
9064
+ return latest;
9065
+ /**
9066
+ * If latest is a string, if it's a percentage we can return immediately as it's
9067
+ * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
9068
+ */
9069
+ if (typeof latest === "string") {
9070
+ if (px.test(latest)) {
9071
+ latest = parseFloat(latest);
9072
+ }
9073
+ else {
9074
+ return latest;
9075
+ }
9076
+ }
9077
+ /**
9078
+ * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
9079
+ * pixel value as a percentage of each axis
9080
+ */
9081
+ const x = pixelsToPercent(latest, node.target.x);
9082
+ const y = pixelsToPercent(latest, node.target.y);
9083
+ return `${x}% ${y}%`;
9084
+ },
9085
+ };
9086
+
9087
+ const correctBoxShadow = {
9088
+ correct: (latest, { treeScale, projectionDelta }) => {
9089
+ const original = latest;
9090
+ const shadow = complex.parse(latest);
9091
+ // TODO: Doesn't support multiple shadows
9092
+ if (shadow.length > 5)
9093
+ return original;
9094
+ const template = complex.createTransformer(latest);
9095
+ const offset = typeof shadow[0] !== "number" ? 1 : 0;
9096
+ // Calculate the overall context scale
9097
+ const xScale = projectionDelta.x.scale * treeScale.x;
9098
+ const yScale = projectionDelta.y.scale * treeScale.y;
9099
+ shadow[0 + offset] /= xScale;
9100
+ shadow[1 + offset] /= yScale;
9101
+ /**
9102
+ * Ideally we'd correct x and y scales individually, but because blur and
9103
+ * spread apply to both we have to take a scale average and apply that instead.
9104
+ * We could potentially improve the outcome of this by incorporating the ratio between
9105
+ * the two scales.
9106
+ */
9107
+ const averageScale = mixNumber$1(xScale, yScale, 0.5);
9108
+ // Blur
9109
+ if (typeof shadow[2 + offset] === "number")
9110
+ shadow[2 + offset] /= averageScale;
9111
+ // Spread
9112
+ if (typeof shadow[3 + offset] === "number")
9113
+ shadow[3 + offset] /= averageScale;
9114
+ return template(shadow);
9115
+ },
9116
+ };
9117
+
9230
9118
  function buildProjectionTransform(delta, treeScale, latestTransform) {
9231
9119
  let transform = "";
9232
9120
  /**
@@ -9279,7 +9167,6 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
9279
9167
  }
9280
9168
 
9281
9169
  const numBorders = cornerRadiusProps.length;
9282
- const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
9283
9170
  const isPx = (value) => typeof value === "number" || px.test(value);
9284
9171
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
9285
9172
  if (shouldCrossfadeOpacity) {
@@ -9478,6 +9365,18 @@ class NodeStack {
9478
9365
  }
9479
9366
  }
9480
9367
 
9368
+ const defaultScaleCorrectors = {
9369
+ borderRadius: {
9370
+ ...correctBorderRadius,
9371
+ applyTo: [...cornerRadiusProps],
9372
+ },
9373
+ borderTopLeftRadius: correctBorderRadius,
9374
+ borderTopRightRadius: correctBorderRadius,
9375
+ borderBottomLeftRadius: correctBorderRadius,
9376
+ borderBottomRightRadius: correctBorderRadius,
9377
+ boxShadow: correctBoxShadow,
9378
+ };
9379
+
9481
9380
  /**
9482
9381
  * This should only ever be modified on the client otherwise it'll
9483
9382
  * persist through server requests. If we need instanced states we
@@ -9496,6 +9395,14 @@ const globalProjectionState = {
9496
9395
  hasEverUpdated: false,
9497
9396
  };
9498
9397
 
9398
+ /**
9399
+ * Correctors registered via addScaleCorrector before projection loaded
9400
+ * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
9401
+ */
9402
+ Object.assign(scaleCorrectors, {
9403
+ ...defaultScaleCorrectors,
9404
+ ...scaleCorrectors,
9405
+ });
9499
9406
  const metrics = {
9500
9407
  nodes: 0,
9501
9408
  calculatedTargetDeltas: 0,
@@ -11798,6 +11705,7 @@ exports.numberValueTypes = numberValueTypes;
11798
11705
  exports.observeTimeline = observeTimeline;
11799
11706
  exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute;
11800
11707
  exports.optimizedAppearDataId = optimizedAppearDataId;
11708
+ exports.originProps = originProps;
11801
11709
  exports.parseAnimateLayoutArgs = parseAnimateLayoutArgs;
11802
11710
  exports.parseCSSVariable = parseCSSVariable;
11803
11711
  exports.parseValueFromTransform = parseValueFromTransform;