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
@@ -4,170 +4,15 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MotionDom = {}, global.MotionUtils));
5
5
  })(this, (function (exports, motionUtils) { 'use strict';
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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;
@@ -2694,17 +2732,17 @@
2694
2732
  /**
2695
2733
  * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
2696
2734
  */
2697
- attachTimeline({ timeline, rangeStart, rangeEnd, observe, }) {
2735
+ attachTimeline({ timeline, onAttach, observe,
2736
+ // Deprecated rangeStart/rangeEnd from framer-motion 13.0–13.4. Removed in v14.
2737
+ ...range }) {
2698
2738
  if (this.allowFlatten) {
2699
2739
  this.animation.effect?.updateTiming({ easing: "linear" });
2700
2740
  }
2701
2741
  this.animation.onfinish = null;
2702
2742
  if (timeline && supportsScrollTimeline()) {
2703
2743
  this.animation.timeline = timeline;
2704
- if (rangeStart)
2705
- this.animation.rangeStart = rangeStart;
2706
- if (rangeEnd)
2707
- this.animation.rangeEnd = rangeEnd;
2744
+ Object.assign(this.animation, range);
2745
+ onAttach?.(this.animation);
2708
2746
  return motionUtils.noop;
2709
2747
  }
2710
2748
  else {
@@ -4041,36 +4079,29 @@
4041
4079
  return state;
4042
4080
  }
4043
4081
  function resolveVariantFromProps(props, definition, custom, visualElement) {
4082
+ const resolveFunction = (def) => typeof def === "function"
4083
+ ? def(custom !== undefined ? custom : props.custom, ...getValueState(visualElement))
4084
+ : def;
4044
4085
  /**
4045
- * If the variant definition is a function, resolve.
4046
- */
4047
- if (typeof definition === "function") {
4048
- const [current, velocity] = getValueState(visualElement);
4049
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
4050
- }
4051
- /**
4052
- * If the variant definition is a variant label, or
4053
- * the function returned a variant label, resolve.
4086
+ * Resolve a function, then a variant label (which the function may have
4087
+ * returned), then a function again as the label may point to one. The
4088
+ * final function can only return a target object.
4054
4089
  */
4090
+ definition = resolveFunction(definition);
4055
4091
  if (typeof definition === "string") {
4056
4092
  definition = props.variants && props.variants[definition];
4057
4093
  }
4058
- /**
4059
- * At this point we've resolved both functions and variant labels,
4060
- * but the resolved variant label might itself have been a function.
4061
- * If so, resolve. This can only have returned a valid target object.
4062
- */
4063
- if (typeof definition === "function") {
4064
- const [current, velocity] = getValueState(visualElement);
4065
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
4066
- }
4067
- return definition;
4094
+ return resolveFunction(definition);
4068
4095
  }
4069
4096
 
4070
4097
  function resolveVariant(visualElement, definition, custom) {
4071
- const props = visualElement.getProps();
4072
- return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);
4098
+ return resolveVariantFromProps(visualElement.getProps(), definition, custom, visualElement);
4073
4099
  }
4100
+ /**
4101
+ * Exit variants resolve with AnimatePresence's custom, every other type
4102
+ * with the element's own.
4103
+ */
4104
+ const getTypeCustom = (visualElement, type) => type === "exit" ? visualElement.presenceContext?.custom : undefined;
4074
4105
 
4075
4106
  const positionalKeys = new Set([
4076
4107
  "width",
@@ -4153,7 +4184,7 @@
4153
4184
  * had been set to true in the meantime.
4154
4185
  */
4155
4186
  function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
4156
- const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
4187
+ const shouldBlock = key in protectedKeys && !needsAnimating[key];
4157
4188
  needsAnimating[key] = false;
4158
4189
  return shouldBlock;
4159
4190
  }
@@ -4168,9 +4199,7 @@
4168
4199
  if (transitionOverride)
4169
4200
  transition = transitionOverride;
4170
4201
  const animations = [];
4171
- const animationTypeState = type &&
4172
- visualElement.animationState &&
4173
- visualElement.animationState.getState()[type];
4202
+ const animationTypeState = type && visualElement.animationState?.getState()[type];
4174
4203
  const path = transition?.path;
4175
4204
  if (path) {
4176
4205
  // path mutates `target` to claim x/y; loop below skips them.
@@ -4244,75 +4273,46 @@
4244
4273
  }
4245
4274
 
4246
4275
  function animateVariant(visualElement, variant, options = {}) {
4247
- const resolved = resolveVariant(visualElement, variant, options.type === "exit"
4248
- ? visualElement.presenceContext?.custom
4249
- : undefined);
4250
- let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
4251
- if (options.transitionOverride) {
4252
- transition = options.transitionOverride;
4253
- }
4254
- /**
4255
- * If we have a variant, create a callback that runs it as an animation.
4256
- * Otherwise, we resolve a Promise immediately for a composable no-op.
4257
- */
4258
- const getAnimation = resolved
4259
- ? () => Promise.all(animateTarget(visualElement, resolved, options))
4260
- : () => Promise.resolve();
4261
- /**
4262
- * If we have children, create a callback that runs all their animations.
4263
- * Otherwise, we resolve a Promise immediately for a composable no-op.
4264
- */
4265
- const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size
4266
- ? (forwardDelay = 0) => {
4267
- const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
4268
- return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options);
4269
- }
4270
- : () => Promise.resolve();
4276
+ const resolved = resolveVariant(visualElement, variant, getTypeCustom(visualElement, options.type));
4277
+ const transition = options.transitionOverride ||
4278
+ (resolved?.transition ?? (visualElement.getDefaultTransition() || {}));
4279
+ const getAnimation = () => Promise.all(resolved ? animateTarget(visualElement, resolved, options) : []);
4280
+ const getChildAnimations = (delay = 0) => {
4281
+ const { variantChildren } = visualElement;
4282
+ const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
4283
+ const animations = [];
4284
+ variantChildren?.forEach((child) => {
4285
+ child.notify("AnimationStart", variant);
4286
+ animations.push(animateVariant(child, variant, {
4287
+ ...options,
4288
+ delay: delay +
4289
+ (typeof delayChildren === "function"
4290
+ ? 0
4291
+ : delayChildren) +
4292
+ calcChildStagger(variantChildren, child, delayChildren, staggerChildren, staggerDirection),
4293
+ }).then(() => child.notify("AnimationComplete", variant)));
4294
+ });
4295
+ return Promise.all(animations);
4296
+ };
4271
4297
  /**
4272
- * If the transition explicitly defines a "when" option, we need to resolve either
4273
- * this animation or all children animations before playing the other.
4298
+ * when: "beforeChildren" | "afterChildren" runs this element's animation
4299
+ * and its children's in sequence.
4274
4300
  */
4275
4301
  const { when } = transition;
4276
- if (when) {
4277
- const [first, last] = when === "beforeChildren"
4278
- ? [getAnimation, getChildAnimations]
4279
- : [getChildAnimations, getAnimation];
4280
- return first().then(() => last());
4281
- }
4282
- else {
4283
- return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
4284
- }
4285
- }
4286
- function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
4287
- const animations = [];
4288
- for (const child of visualElement.variantChildren) {
4289
- child.notify("AnimationStart", variant);
4290
- animations.push(animateVariant(child, variant, {
4291
- ...options,
4292
- delay: delay +
4293
- (typeof delayChildren === "function" ? 0 : delayChildren) +
4294
- calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection),
4295
- }).then(() => child.notify("AnimationComplete", variant)));
4296
- }
4297
- return Promise.all(animations);
4302
+ return when
4303
+ ? when === "beforeChildren"
4304
+ ? getAnimation().then(() => getChildAnimations())
4305
+ : getChildAnimations().then(getAnimation)
4306
+ : Promise.all([getAnimation(), getChildAnimations(options.delay)]);
4298
4307
  }
4299
4308
 
4300
4309
  function animateVisualElement(visualElement, definition, options = {}) {
4301
4310
  visualElement.notify("AnimationStart", definition);
4302
- let animation;
4303
- if (Array.isArray(definition)) {
4304
- const animations = definition.map((variant) => animateVariant(visualElement, variant, options));
4305
- animation = Promise.all(animations);
4306
- }
4307
- else if (typeof definition === "string") {
4308
- animation = animateVariant(visualElement, definition, options);
4309
- }
4310
- else {
4311
- const resolvedDefinition = typeof definition === "function"
4312
- ? resolveVariant(visualElement, definition, options.custom)
4313
- : definition;
4314
- animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));
4315
- }
4311
+ const animation = Array.isArray(definition)
4312
+ ? Promise.all(definition.map((variant) => animateVariant(visualElement, variant, options)))
4313
+ : typeof definition === "string"
4314
+ ? animateVariant(visualElement, definition, options)
4315
+ : Promise.all(animateTarget(visualElement, resolveVariant(visualElement, definition, options.custom), options));
4316
4316
  return animation.then(() => {
4317
4317
  visualElement.notify("AnimationComplete", definition);
4318
4318
  });
@@ -4838,7 +4838,12 @@
4838
4838
  const onRemove = () => {
4839
4839
  cancelOnChange();
4840
4840
  render && !computed && this.cancel(render);
4841
- this.values.delete(name);
4841
+ /**
4842
+ * A later set() of the same name has already removed this
4843
+ * entry, so leave the one that replaced it.
4844
+ */
4845
+ this.values.get(name)?.onRemove === onRemove &&
4846
+ this.values.delete(name);
4842
4847
  };
4843
4848
  this.values.set(name, {
4844
4849
  value,
@@ -5317,24 +5322,35 @@
5317
5322
  else if (key.startsWith("attr")) {
5318
5323
  return addAttrValue(element, state, key, value, convertAttrKey(key));
5319
5324
  }
5320
- const handler = isCSSVar(key) || key in element.style ? addStyleValue : addAttrValue;
5325
+ /**
5326
+ * Transforms and origins aren't CSS properties (bar `x`/`y` in some
5327
+ * browsers), so check them by name rather than `key in element.style`.
5328
+ */
5329
+ const handler = transformProps.has(key) ||
5330
+ originProps.has(key) ||
5331
+ isCSSVar(key) ||
5332
+ key in element.style
5333
+ ? addStyleValue
5334
+ : addAttrValue;
5321
5335
  return handler(element, state, key, value);
5322
5336
  };
5323
5337
  /**
5324
5338
  * Reads the current value of `key` from an SVG element as the origin of
5325
5339
  * an animation, as the SVG VisualElement does: transforms start from
5326
5340
  * their defaults, CSS variables and the few CSS-only properties come from
5327
- * computed style
5328
- * and everything else is read from the attribute, dash-cased
5329
- * (`strokeWidth` -> `stroke-width`) or, failing that, as written
5330
- * (`baseFrequency`).
5341
+ * computed style, falling back to the attribute when that's empty (e.g.
5342
+ * the element isn't rendered), and everything else is read from the
5343
+ * attribute, dash-cased (`strokeWidth` -> `stroke-width`) or, failing
5344
+ * that, as written (`baseFrequency`).
5331
5345
  */
5332
5346
  const readSVGValue = (element, key) => {
5333
5347
  if (transformProps.has(key)) {
5334
5348
  return numberValueTypes[key]?.default || 0;
5335
5349
  }
5336
5350
  if (isCSSVar(key) || cssStyleProperties.includes(key)) {
5337
- return readStyleValue(element, key);
5351
+ return (readStyleValue(element, key) ||
5352
+ element.getAttribute(camelToDash(key)) ||
5353
+ 0);
5338
5354
  }
5339
5355
  key = convertAttrKey(key);
5340
5356
  return (element.getAttribute(camelToDash(key)) ??
@@ -6037,6 +6053,10 @@
6037
6053
  return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
6038
6054
  }
6039
6055
 
6056
+ /**
6057
+ * @deprecated Kept because framer-motion 13.0–13.4 import it from
6058
+ * motion-dom with a ^ range. Removed in v14.
6059
+ */
6040
6060
  function observeTimeline(update, timeline) {
6041
6061
  let prevProgress;
6042
6062
  const onFrame = () => {
@@ -6165,8 +6185,7 @@
6165
6185
  this.options.onStop?.();
6166
6186
  };
6167
6187
  this.options = options;
6168
- replaceTransitionType(options);
6169
- this.factory = options.type || keyframes;
6188
+ this.factory = options.type;
6170
6189
  this.generator = this.factory(options);
6171
6190
  const { driver } = options;
6172
6191
  if (driver)
@@ -6267,41 +6286,15 @@
6267
6286
  }
6268
6287
  }
6269
6288
 
6289
+ const asNumber = (v) => typeof v === "number" ? v : parseFloat(v);
6290
+
6270
6291
  /**
6271
- * Create a `MotionValue` that animates to its latest value using any transition type.
6272
- * Can either be a value or track another `MotionValue`.
6273
- *
6274
- * ```jsx
6275
- * const x = motionValue(0)
6276
- * const y = followValue(x, { type: "spring", stiffness: 300 })
6277
- * // or with tween
6278
- * const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
6279
- * ```
6280
- *
6281
- * @param source - Initial value or MotionValue to track
6282
- * @param options - Animation transition options
6283
- * @returns `MotionValue`
6284
- *
6285
- * @public
6286
- */
6287
- function followValue(source, options) {
6288
- const initialValue = isMotionValue(source) ? source.get() : source;
6289
- const value = motionValue(initialValue);
6290
- attachFollow(value, source, options);
6291
- return value;
6292
- }
6293
- /**
6294
- * Attach an animation to a MotionValue that will animate whenever the value changes.
6295
- * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
6296
- *
6297
- * @param value - The MotionValue to animate
6298
- * @param source - Initial value or MotionValue to track
6299
- * @param options - Animation transition options
6300
- * @returns Cleanup function
6301
- *
6302
- * @public
6292
+ * Animate `value` to its latest value with the generator in
6293
+ * `options.type`, tracking `source` if it's a `MotionValue`. Takes a
6294
+ * generator rather than a type name, so spring-only callers don't
6295
+ * bundle every generator.
6303
6296
  */
6304
- function attachFollow(value, source, options = {}) {
6297
+ function follow(value, source, options) {
6305
6298
  const initialValue = value.get();
6306
6299
  let activeAnimation = null;
6307
6300
  let set;
@@ -6319,7 +6312,7 @@
6319
6312
  };
6320
6313
  value.attach((v, safeSet) => {
6321
6314
  set = safeSet;
6322
- const target = asNumber$1(v);
6315
+ const target = asNumber(v);
6323
6316
  if (activeAnimation?.state === "running") {
6324
6317
  /**
6325
6318
  * Steer the running animation rather than replacing it. This
@@ -6330,7 +6323,7 @@
6330
6323
  activeAnimation.setTarget(target, options.velocity);
6331
6324
  return;
6332
6325
  }
6333
- const current = asNumber$1(value.get());
6326
+ const current = asNumber(value.get());
6334
6327
  const velocity = activeAnimation
6335
6328
  ? activeAnimation.getGeneratorVelocity()
6336
6329
  : value.getVelocity();
@@ -6341,8 +6334,6 @@
6341
6334
  const animationOptions = {
6342
6335
  keyframes: [current, target],
6343
6336
  velocity,
6344
- // Default to spring if no type specified (matches useSpring behavior)
6345
- type: "spring",
6346
6337
  restDelta: 0.001,
6347
6338
  restSpeed: 0.01,
6348
6339
  ...options,
@@ -6384,8 +6375,47 @@
6384
6375
  function parseValue(v, unit) {
6385
6376
  return unit ? v + unit : v;
6386
6377
  }
6387
- function asNumber$1(v) {
6388
- return typeof v === "number" ? v : parseFloat(v);
6378
+
6379
+ /**
6380
+ * Create a `MotionValue` that animates to its latest value using any transition type.
6381
+ * Can either be a value or track another `MotionValue`.
6382
+ *
6383
+ * ```jsx
6384
+ * const x = motionValue(0)
6385
+ * const y = followValue(x, { type: "spring", stiffness: 300 })
6386
+ * // or with tween
6387
+ * const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
6388
+ * ```
6389
+ *
6390
+ * @param source - Initial value or MotionValue to track
6391
+ * @param options - Animation transition options
6392
+ * @returns `MotionValue`
6393
+ *
6394
+ * @public
6395
+ */
6396
+ function followValue(source, options) {
6397
+ const initialValue = isMotionValue(source) ? source.get() : source;
6398
+ const value = motionValue(initialValue);
6399
+ attachFollow(value, source, options);
6400
+ return value;
6401
+ }
6402
+ /**
6403
+ * Attach an animation to a MotionValue that will animate whenever the value changes.
6404
+ * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
6405
+ *
6406
+ * @param value - The MotionValue to animate
6407
+ * @param source - Initial value or MotionValue to track
6408
+ * @param options - Animation transition options
6409
+ * @returns Cleanup function
6410
+ *
6411
+ * @public
6412
+ */
6413
+ function attachFollow(value, source, options = {}) {
6414
+ // Default to spring if no type specified (matches useSpring behavior)
6415
+ const transition = { type: "spring", ...options };
6416
+ replaceTransitionType(transition);
6417
+ transition.type = transition.type || keyframes;
6418
+ return follow(value, source, transition);
6389
6419
  }
6390
6420
 
6391
6421
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -6487,7 +6517,9 @@
6487
6517
  * @public
6488
6518
  */
6489
6519
  function springValue(source, options) {
6490
- return followValue(source, { type: "spring", ...options });
6520
+ const value = motionValue(isMotionValue(source) ? source.get() : source);
6521
+ attachSpring(value, source, options);
6522
+ return value;
6491
6523
  }
6492
6524
  /**
6493
6525
  * Attach a spring animation to a MotionValue that will animate whenever the value changes.
@@ -6500,7 +6532,7 @@
6500
6532
  * @public
6501
6533
  */
6502
6534
  function attachSpring(value, source, options) {
6503
- return attachFollow(value, source, { type: "spring", ...options });
6535
+ return follow(value, source, { ...options, type: spring });
6504
6536
  }
6505
6537
 
6506
6538
  /**
@@ -7922,8 +7954,20 @@
7922
7954
  if (this.projection && !this.projection.instance) {
7923
7955
  this.projection.mount(instance);
7924
7956
  }
7925
- if (this.parent && this.isVariantNode && !this.isControllingVariants) {
7926
- this.removeFromVariantTree = this.parent.addVariantChild(this);
7957
+ /**
7958
+ * Join the closest variant node above, so its variant changes
7959
+ * propagate here, unless inherit={false} cuts the chain.
7960
+ */
7961
+ if (this.isVariantNode && !this.isControllingVariants) {
7962
+ let node = this;
7963
+ do
7964
+ node = node.props.inherit !== false && node.parent;
7965
+ while (node && !node.isVariantNode);
7966
+ if (node) {
7967
+ const { variantChildren } = node;
7968
+ variantChildren.add(this);
7969
+ this.removeFromVariantTree = () => variantChildren.delete(this);
7970
+ }
7927
7971
  }
7928
7972
  this.values.forEach((value, key) => this.bindToMotionValue(key, value));
7929
7973
  /**
@@ -8033,9 +8077,11 @@
8033
8077
  }
8034
8078
  sortNodePosition(other) {
8035
8079
  /**
8036
- * If these nodes aren't even of the same type we can't compare their depth.
8080
+ * If either node isn't mounted, or they aren't even of the same type,
8081
+ * we can't compare their document order.
8037
8082
  */
8038
8083
  if (!this.current ||
8084
+ !other.current ||
8039
8085
  !this.sortInstanceNodePosition ||
8040
8086
  this.type !== other.type) {
8041
8087
  return 0;
@@ -8141,24 +8187,6 @@
8141
8187
  getTransformPagePoint() {
8142
8188
  return this.props.transformPagePoint;
8143
8189
  }
8144
- getClosestVariantNode() {
8145
- return this.isVariantNode
8146
- ? this
8147
- : this.parent
8148
- ? this.parent.getClosestVariantNode()
8149
- : undefined;
8150
- }
8151
- /**
8152
- * Add a child visual element to our set of children.
8153
- */
8154
- addVariantChild(child) {
8155
- const closestVariantNode = this.getClosestVariantNode();
8156
- if (closestVariantNode) {
8157
- closestVariantNode.variantChildren &&
8158
- closestVariantNode.variantChildren.add(child);
8159
- return () => closestVariantNode.variantChildren.delete(child);
8160
- }
8161
- }
8162
8190
  /**
8163
8191
  * Add a motion value and bind it to this visual element.
8164
8192
  */
@@ -8170,7 +8198,15 @@
8170
8198
  this.removeValue(key);
8171
8199
  this.bindToMotionValue(key, value);
8172
8200
  this.values.set(key, value);
8173
- this.latestValues[key] = value.get();
8201
+ /**
8202
+ * An animated value with no base value is undefined until the
8203
+ * keyframe resolver reads its origin. Rendering it before then
8204
+ * writes an invalid placeholder (e.g. points="undefined") that
8205
+ * the resolver can read back from the DOM as the origin.
8206
+ */
8207
+ const latest = value.get();
8208
+ if (latest !== undefined)
8209
+ this.latestValues[key] = latest;
8174
8210
  }
8175
8211
  }
8176
8212
  /**
@@ -8198,7 +8234,9 @@
8198
8234
  }
8199
8235
  let value = this.values.get(key);
8200
8236
  if (value === undefined && defaultValue !== undefined) {
8201
- value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this });
8237
+ value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
8238
+ owner: this,
8239
+ });
8202
8240
  this.addValue(key, value);
8203
8241
  }
8204
8242
  return value;
@@ -8243,41 +8281,6 @@
8243
8281
  setBaseTarget(key, value) {
8244
8282
  this.baseTarget[key] = value;
8245
8283
  }
8246
- /**
8247
- * Find the base target for a value thats been removed from all animation
8248
- * props.
8249
- */
8250
- getBaseTarget(key) {
8251
- const { initial } = this.props;
8252
- let valueFromInitial;
8253
- if (typeof initial === "string" || typeof initial === "object") {
8254
- const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom);
8255
- if (variant) {
8256
- valueFromInitial = variant[key];
8257
- }
8258
- }
8259
- /**
8260
- * If this value still exists in the current initial variant, read that.
8261
- */
8262
- if (initial && valueFromInitial !== undefined) {
8263
- return valueFromInitial;
8264
- }
8265
- /**
8266
- * Alternatively, if this VisualElement config has defined a getBaseTarget
8267
- * so we can read the value from an alternative source, try that.
8268
- */
8269
- const target = this.getBaseTargetFromProps(this.props, key);
8270
- if (target !== undefined && !isMotionValue(target))
8271
- return target;
8272
- /**
8273
- * If the value was initially defined on initial, but it doesn't any more,
8274
- * return undefined. Otherwise return the value as initially read from the DOM.
8275
- */
8276
- return this.initialValues[key] !== undefined &&
8277
- valueFromInitial === undefined
8278
- ? undefined
8279
- : this.baseTarget[key];
8280
- }
8281
8284
  on(eventName, callback) {
8282
8285
  if (!this.events[eventName]) {
8283
8286
  this.events[eventName] = new motionUtils.SubscriptionManager();
@@ -8341,105 +8344,26 @@
8341
8344
  this.isMounted = false;
8342
8345
  this.node = node;
8343
8346
  }
8344
- update() { }
8345
- }
8346
-
8347
- function renderHTML(element, { style, vars }, styleProp, projection) {
8348
- const elementStyle = element.style;
8349
- let key;
8350
- for (key in style) {
8351
- // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.
8352
- elementStyle[key] = style[key];
8353
- }
8354
- // Write projection styles directly to element style
8355
- projection?.applyProjectionStyles(elementStyle, styleProp);
8356
- for (key in vars) {
8357
- // Loop over any CSS variables and assign those.
8358
- // They can only be assigned using `setProperty`.
8359
- elementStyle.setProperty(key, vars[key]);
8360
- }
8361
- }
8362
-
8363
- function pixelsToPercent(pixels, axis) {
8364
- if (axis.max === axis.min)
8365
- return 0;
8366
- return (pixels / (axis.max - axis.min)) * 100;
8367
- }
8368
- /**
8369
- * We always correct borderRadius as a percentage rather than pixels to reduce paints.
8370
- * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
8371
- * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
8372
- * borderRadius in both states. If we animate between the two in pixels that will trigger
8373
- * a paint each time. If we animate between the two in percentage we'll avoid a paint.
8374
- */
8375
- const correctBorderRadius = {
8376
- correct: (latest, node) => {
8377
- if (!node.target)
8378
- return latest;
8379
- /**
8380
- * If latest is a string, if it's a percentage we can return immediately as it's
8381
- * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
8382
- */
8383
- if (typeof latest === "string") {
8384
- if (px.test(latest)) {
8385
- latest = parseFloat(latest);
8386
- }
8387
- else {
8388
- return latest;
8389
- }
8390
- }
8391
- /**
8392
- * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
8393
- * pixel value as a percentage of each axis
8394
- */
8395
- const x = pixelsToPercent(latest, node.target.x);
8396
- const y = pixelsToPercent(latest, node.target.y);
8397
- return `${x}% ${y}%`;
8398
- },
8399
- };
8400
-
8401
- const correctBoxShadow = {
8402
- correct: (latest, { treeScale, projectionDelta }) => {
8403
- const original = latest;
8404
- const shadow = complex.parse(latest);
8405
- // TODO: Doesn't support multiple shadows
8406
- if (shadow.length > 5)
8407
- return original;
8408
- const template = complex.createTransformer(latest);
8409
- const offset = typeof shadow[0] !== "number" ? 1 : 0;
8410
- // Calculate the overall context scale
8411
- const xScale = projectionDelta.x.scale * treeScale.x;
8412
- const yScale = projectionDelta.y.scale * treeScale.y;
8413
- shadow[0 + offset] /= xScale;
8414
- shadow[1 + offset] /= yScale;
8415
- /**
8416
- * Ideally we'd correct x and y scales individually, but because blur and
8417
- * spread apply to both we have to take a scale average and apply that instead.
8418
- * We could potentially improve the outcome of this by incorporating the ratio between
8419
- * the two scales.
8420
- */
8421
- const averageScale = mixNumber$1(xScale, yScale, 0.5);
8422
- // Blur
8423
- if (typeof shadow[2 + offset] === "number")
8424
- shadow[2 + offset] /= averageScale;
8425
- // Spread
8426
- if (typeof shadow[3 + offset] === "number")
8427
- shadow[3 + offset] /= averageScale;
8428
- return template(shadow);
8429
- },
8430
- };
8347
+ update() { }
8348
+ }
8431
8349
 
8432
- const scaleCorrectors = {
8433
- borderRadius: {
8434
- ...correctBorderRadius,
8435
- applyTo: [...cornerRadiusProps],
8436
- },
8437
- borderTopLeftRadius: correctBorderRadius,
8438
- borderTopRightRadius: correctBorderRadius,
8439
- borderBottomLeftRadius: correctBorderRadius,
8440
- borderBottomRightRadius: correctBorderRadius,
8441
- boxShadow: correctBoxShadow,
8442
- };
8350
+ function renderHTML(element, { style, vars }, styleProp, projection) {
8351
+ const elementStyle = element.style;
8352
+ let key;
8353
+ for (key in style) {
8354
+ // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.
8355
+ elementStyle[key] = style[key];
8356
+ }
8357
+ // Write projection styles directly to element style
8358
+ projection?.applyProjectionStyles(elementStyle, styleProp);
8359
+ for (key in vars) {
8360
+ // Loop over any CSS variables and assign those.
8361
+ // They can only be assigned using `setProperty`.
8362
+ elementStyle.setProperty(key, vars[key]);
8363
+ }
8364
+ }
8365
+
8366
+ const scaleCorrectors = {};
8443
8367
  function addScaleCorrector(correctors) {
8444
8368
  for (const key in correctors) {
8445
8369
  scaleCorrectors[key] = correctors[key];
@@ -8613,7 +8537,24 @@
8613
8537
  this.measureInstanceViewportBox = createBox;
8614
8538
  }
8615
8539
  getBaseTargetFromProps(props, key) {
8616
- return props[key];
8540
+ /**
8541
+ * An independent transform's base is never an attribute of the same
8542
+ * name, e.g. <rect x> is a position, not a translate. Like HTML it
8543
+ * comes from style, falling back to the transform's default.
8544
+ */
8545
+ return transformProps.has(key)
8546
+ ? super.getBaseTargetFromProps(props, key) ??
8547
+ defaultTransformValue(key)
8548
+ : props[key];
8549
+ }
8550
+ /**
8551
+ * An independent transform's origin is never read from the DOM, so it
8552
+ * starts from its latest or default value and renders on mount.
8553
+ */
8554
+ getDefaultValue(key) {
8555
+ return transformProps.has(key)
8556
+ ? this.latestValues[key] ?? defaultTransformValue(key)
8557
+ : undefined;
8617
8558
  }
8618
8559
  readValueFromInstance(instance, key) {
8619
8560
  if (transformProps.has(key)) {
@@ -8644,34 +8585,6 @@
8644
8585
  }
8645
8586
  }
8646
8587
 
8647
- const numVariantProps = variantProps.length;
8648
- /**
8649
- * Get variant context from a visual element's parent chain.
8650
- * Uses `any` type for visualElement to avoid circular dependencies.
8651
- */
8652
- function getVariantContext(visualElement) {
8653
- if (!visualElement)
8654
- return undefined;
8655
- if (!visualElement.isControllingVariants) {
8656
- const context = visualElement.parent
8657
- ? getVariantContext(visualElement.parent) || {}
8658
- : {};
8659
- if (visualElement.props.initial !== undefined) {
8660
- context.initial = visualElement.props.initial;
8661
- }
8662
- return context;
8663
- }
8664
- const context = {};
8665
- for (let i = 0; i < numVariantProps; i++) {
8666
- const name = variantProps[i];
8667
- const prop = visualElement.props[name];
8668
- if (isVariantLabel(prop) || prop === false) {
8669
- context[name] = prop;
8670
- }
8671
- }
8672
- return context;
8673
- }
8674
-
8675
8588
  function shallowCompare(next, prev) {
8676
8589
  if (!Array.isArray(prev))
8677
8590
  return false;
@@ -8686,332 +8599,211 @@
8686
8599
  }
8687
8600
 
8688
8601
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
8689
- const numAnimationTypes = variantPriorityOrder.length;
8690
- function createAnimateFunction(visualElement) {
8691
- return (animations) => {
8692
- return Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
8693
- };
8694
- }
8602
+ /**
8603
+ * Diffs the element's animation props (one layer per AnimationType, highest
8604
+ * priority wins each value) against the previous call and starts animations
8605
+ * for what changed.
8606
+ *
8607
+ * Uses `any` type for visualElement to avoid circular dependencies. It reads
8608
+ * props, parent, presenceContext, variantChildren, enteringChildren,
8609
+ * manuallyAnimateOnMount, blockInitialAnimation, getValue(),
8610
+ * getBaseTargetFromProps(), baseTarget and initialValues.
8611
+ */
8695
8612
  function createAnimationState(visualElement) {
8696
- let animate = createAnimateFunction(visualElement);
8613
+ let animate = (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
8697
8614
  let state = createState();
8698
8615
  let isInitialRender = true;
8699
8616
  /**
8700
- * Track whether the animation state has been reset (e.g. via StrictMode
8701
- * double-invocation or Suspense unmount/remount). On the first
8702
- * animateChanges() call after a reset we need to behave like the initial
8703
- * render for variant-inheritance checks, even though isInitialRender is
8704
- * already false.
8617
+ * After a reset (StrictMode, Suspense, AnimatePresence re-entry) the next
8618
+ * animateChanges() mounts again, but initial={false} no longer applies.
8705
8619
  */
8706
8620
  let wasReset = false;
8707
- /**
8708
- * This function will be used to reduce the animation definitions for
8709
- * each active animation type into an object of resolved values for it.
8710
- */
8711
- const buildResolvedTypeValues = (type) => (acc, definition) => {
8712
- const resolved = resolveVariant(visualElement, definition, type === "exit"
8713
- ? visualElement.presenceContext?.custom
8714
- : undefined);
8715
- if (resolved) {
8716
- const { transition, transitionEnd, ...target } = resolved;
8717
- acc = { ...acc, ...target, ...transitionEnd };
8718
- }
8719
- return acc;
8720
- };
8721
- /**
8722
- * This just allows us to inject mocked animation functions
8723
- * @internal
8724
- */
8725
- function setAnimateFunction(makeAnimator) {
8726
- animate = makeAnimator(visualElement);
8727
- }
8728
- /**
8729
- * When we receive new props, we need to:
8730
- * 1. Create a list of protected keys for each type. This is a directory of
8731
- * value keys that are currently being "handled" by types of a higher priority
8732
- * so that whenever an animation is played of a given type, these values are
8733
- * protected from being animated.
8734
- * 2. Determine if an animation type needs animating.
8735
- * 3. Determine if any values have been removed from a type and figure out
8736
- * what to animate those to.
8737
- */
8738
8621
  function animateChanges(changedActiveType) {
8739
- const { props } = visualElement;
8740
- const context = getVariantContext(visualElement.parent) || {};
8741
- /**
8742
- * A list of animations that we'll build into as we iterate through the animation
8743
- * types. This will get executed at the end of the function.
8744
- */
8622
+ const { props, parent, manuallyAnimateOnMount } = visualElement;
8623
+ const isMounting = isInitialRender || wasReset;
8745
8624
  const animations = [];
8746
8625
  /**
8747
- * Keep track of which values have been removed. Then, as we hit lower priority
8748
- * animation types, we can check if they contain removed values and animate to that.
8626
+ * Values removed from a type. A lower-priority type that defines
8627
+ * them animates them back, otherwise they fall back to a base target.
8749
8628
  */
8750
8629
  const removedKeys = new Set();
8751
8630
  /**
8752
- * A dictionary of all encountered keys. This is an object to let us build into and
8753
- * copy it without iteration. Each time we hit an animation type we set its protected
8754
- * keys - the keys its not allowed to animate - to the latest version of this object.
8631
+ * Values claimed by active, higher-priority types.
8755
8632
  */
8756
8633
  let encounteredKeys = {};
8757
8634
  /**
8758
- * If a variant has been removed at a given index, and this component is controlling
8759
- * variant animations, we want to ensure lower-priority variants are forced to animate.
8635
+ * Once a type has been deactivated, lower-priority variant labels
8636
+ * re-animate so variant children animate back too.
8760
8637
  */
8761
8638
  let removedVariantIndex = Infinity;
8762
8639
  /**
8763
- * Iterate through all animation types in reverse priority order. For each, we want to
8764
- * detect which values it's handling and whether or not they've changed (and therefore
8765
- * need to be animated). If any values have been removed, we want to detect those in
8766
- * lower priority props and flag for animation.
8640
+ * Variant labels are inherited from the closest variant-controlling
8641
+ * ancestor, unless an element on the way has inherit={false}.
8767
8642
  */
8768
- for (let i = 0; i < numAnimationTypes; i++) {
8769
- const type = reversePriorityOrder[i];
8643
+ let source = visualElement;
8644
+ do
8645
+ source = source.props.inherit !== false && source.parent;
8646
+ while (source && !source.isControllingVariants);
8647
+ reversePriorityOrder.forEach((type, i) => {
8770
8648
  const typeState = state[type];
8771
- const prop = props[type] !== undefined
8772
- ? props[type]
8773
- : context[type];
8649
+ const ownProp = props[type];
8650
+ const inheritedProp = source && source.props[type];
8651
+ const prop = ownProp !== undefined
8652
+ ? ownProp
8653
+ : isVariantLabel(inheritedProp) || inheritedProp === false
8654
+ ? inheritedProp
8655
+ : undefined;
8774
8656
  const propIsVariant = isVariantLabel(prop);
8775
- /**
8776
- * If this type has *just* changed isActive status, set activeDelta
8777
- * to that status. Otherwise set to null.
8778
- */
8779
8657
  const activeDelta = type === changedActiveType ? typeState.isActive : null;
8780
8658
  if (activeDelta === false)
8781
8659
  removedVariantIndex = i;
8782
8660
  /**
8783
- * If this prop is an inherited variant, rather than been set directly on the
8784
- * component itself, we want to make sure we allow the parent to trigger animations.
8785
- *
8786
- * TODO: Can probably change this to a !isControllingVariants check
8787
- */
8788
- let isInherited = prop === context[type] &&
8789
- prop !== props[type] &&
8790
- propIsVariant;
8791
- if (isInherited &&
8792
- (isInitialRender || wasReset) &&
8793
- visualElement.manuallyAnimateOnMount) {
8794
- isInherited = false;
8795
- }
8796
- /**
8797
- * Set all encountered keys so far as the protected keys for this type. This will
8798
- * be any key that has been animated or otherwise handled by active, higher-priority types.
8661
+ * Inherited labels are animated by the parent through
8662
+ * variantChildren, unless this element mounted after its parent.
8799
8663
  */
8664
+ const isInherited = propIsVariant &&
8665
+ ownProp === undefined &&
8666
+ !(isMounting && manuallyAnimateOnMount);
8800
8667
  typeState.protectedKeys = { ...encounteredKeys };
8801
- // Check if we can skip analysing this prop early
8802
- if (
8803
- // If it isn't active and hasn't *just* been set as inactive
8804
- (!typeState.isActive && activeDelta === null) ||
8805
- // If we didn't and don't have any defined prop for this animation type
8668
+ if ((!typeState.isActive && activeDelta === null) ||
8806
8669
  (!prop && !typeState.prevProp) ||
8807
- // Or if the prop doesn't define an animation
8808
8670
  isAnimationControls(prop) ||
8809
8671
  typeof prop === "boolean") {
8810
- continue;
8672
+ return;
8811
8673
  }
8812
8674
  /**
8813
- * If exit is already active and wasn't just activated, skip
8814
- * re-processing to prevent interrupting running exit animations.
8815
- * Re-resolving exit with a changed custom value can start new
8816
- * value animations that stop the originals, leaving the exit
8817
- * animation promise unresolved and the component stuck in the DOM.
8675
+ * Don't re-resolve a running exit: a changed custom would start
8676
+ * new value animations that stop the originals, leaving the exit
8677
+ * promise unresolved and the element stuck in the DOM.
8818
8678
  */
8819
8679
  if (type === "exit" && typeState.isActive && activeDelta !== true) {
8820
- if (typeState.prevResolvedValues) {
8821
- encounteredKeys = {
8822
- ...encounteredKeys,
8823
- ...typeState.prevResolvedValues,
8824
- };
8825
- }
8826
- continue;
8680
+ encounteredKeys = {
8681
+ ...encounteredKeys,
8682
+ ...typeState.prevResolvedValues,
8683
+ };
8684
+ return;
8827
8685
  }
8828
- /**
8829
- * As we go look through the values defined on this type, if we detect
8830
- * a changed value or a value that was removed in a higher priority, we set
8831
- * this to true and add this prop to the animation list.
8832
- */
8833
8686
  const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
8834
8687
  let shouldAnimateType = variantDidChange ||
8835
- // If we're making this variant active, we want to always make it active
8836
- (type === changedActiveType &&
8837
- typeState.isActive &&
8838
- !isInherited &&
8839
- propIsVariant) ||
8840
- // If we removed a higher-priority variant (i is in reverse order)
8841
- (i > removedVariantIndex && propIsVariant);
8688
+ (propIsVariant &&
8689
+ ((activeDelta && !isInherited) || i > removedVariantIndex));
8842
8690
  let handledRemovedValues = false;
8843
- /**
8844
- * As animations can be set as variant lists, variants or target objects, we
8845
- * coerce everything to an array if it isn't one already
8846
- */
8847
8691
  const definitionList = Array.isArray(prop) ? prop : [prop];
8848
- /**
8849
- * Build an object of all the resolved values. We'll use this in the subsequent
8850
- * animateChanges calls to determine whether a value has changed.
8851
- */
8852
- let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {});
8853
- if (activeDelta === false)
8854
- resolvedValues = {};
8855
- /**
8856
- * Now we need to loop through all the keys in the prev prop and this prop,
8857
- * and decide:
8858
- * 1. If the value has changed, and needs animating
8859
- * 2. If it has been removed, and needs adding to the removedKeys set
8860
- * 3. If it has been removed in a higher priority type and needs animating
8861
- * 4. If it hasn't been removed in a higher priority but hasn't changed, and
8862
- * needs adding to the type's protectedKeys list.
8863
- */
8864
- const { prevResolvedValues = {} } = typeState;
8865
- const allKeys = {
8866
- ...prevResolvedValues,
8867
- ...resolvedValues,
8868
- };
8869
- const markToAnimate = (key) => {
8870
- shouldAnimateType = true;
8871
- if (removedKeys.has(key)) {
8872
- handledRemovedValues = true;
8873
- removedKeys.delete(key);
8692
+ let resolvedValues = {};
8693
+ if (activeDelta !== false) {
8694
+ for (const definition of definitionList) {
8695
+ const { transition, transitionEnd, ...target } = resolveVariant(visualElement, definition, getTypeCustom(visualElement, type)) || {};
8696
+ resolvedValues = {
8697
+ ...resolvedValues,
8698
+ ...target,
8699
+ ...transitionEnd,
8700
+ };
8874
8701
  }
8875
- typeState.needsAnimating[key] = true;
8876
- const motionValue = visualElement.getValue(key);
8877
- if (motionValue)
8878
- motionValue.liveStyle = false;
8879
- };
8880
- for (const key in allKeys) {
8702
+ }
8703
+ const { prevResolvedValues } = typeState;
8704
+ for (const key in { ...prevResolvedValues, ...resolvedValues }) {
8705
+ if (key in encounteredKeys)
8706
+ continue;
8881
8707
  const next = resolvedValues[key];
8882
8708
  const prev = prevResolvedValues[key];
8883
- // If we've already handled this we can just skip ahead
8884
- if (encounteredKeys.hasOwnProperty(key))
8885
- continue;
8886
8709
  /**
8887
- * If the value has changed, we probably want to animate it.
8710
+ * Keyframes compare by value, but replay whenever the
8711
+ * variant label changed.
8888
8712
  */
8889
- let valueHasChanged = false;
8890
- if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
8891
- valueHasChanged =
8892
- !shallowCompare(next, prev) || variantDidChange;
8893
- }
8894
- else {
8895
- valueHasChanged = next !== prev;
8896
- }
8897
- if (valueHasChanged) {
8898
- if (next !== undefined && next !== null) {
8899
- // If next is defined and doesn't equal prev, it needs animating
8900
- markToAnimate(key);
8901
- }
8902
- else {
8903
- // If it's undefined, it's been removed.
8904
- removedKeys.add(key);
8905
- }
8713
+ const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
8714
+ ? !shallowCompare(next, prev) || variantDidChange
8715
+ : next !== prev;
8716
+ if (valueHasChanged &&
8717
+ (next === undefined || next === null)) {
8718
+ removedKeys.add(key);
8906
8719
  }
8907
- else if (next !== undefined && removedKeys.has(key)) {
8908
- /**
8909
- * If next hasn't changed and it isn't undefined, we want to check if it's
8910
- * been removed by a higher priority
8911
- */
8912
- markToAnimate(key);
8720
+ else if (valueHasChanged ||
8721
+ (next !== undefined && removedKeys.has(key))) {
8722
+ shouldAnimateType = true;
8723
+ if (removedKeys.delete(key))
8724
+ handledRemovedValues = true;
8725
+ typeState.needsAnimating[key] = true;
8726
+ const motionValue = visualElement.getValue(key);
8727
+ if (motionValue)
8728
+ motionValue.liveStyle = false;
8913
8729
  }
8914
8730
  else {
8915
- /**
8916
- * If it hasn't changed, we add it to the list of protected values
8917
- * to ensure it doesn't get animated.
8918
- */
8919
8731
  typeState.protectedKeys[key] = true;
8920
8732
  }
8921
8733
  }
8922
- /**
8923
- * Update the typeState so next time animateChanges is called we can compare the
8924
- * latest prop and resolvedValues to these.
8925
- */
8926
8734
  typeState.prevProp = prop;
8927
8735
  typeState.prevResolvedValues = resolvedValues;
8928
8736
  if (typeState.isActive) {
8929
8737
  encounteredKeys = { ...encounteredKeys, ...resolvedValues };
8930
8738
  }
8931
- if ((isInitialRender || wasReset) &&
8932
- visualElement.blockInitialAnimation) {
8933
- shouldAnimateType = false;
8934
- }
8935
- /**
8936
- * If this is an inherited prop we want to skip this animation
8937
- * unless the inherited variants haven't changed on this render.
8938
- */
8939
- const willAnimateViaParent = isInherited && variantDidChange;
8940
- const needsAnimating = !willAnimateViaParent || handledRemovedValues;
8941
- if (shouldAnimateType && needsAnimating) {
8942
- animations.push(...definitionList.map((animation) => {
8739
+ if (shouldAnimateType &&
8740
+ (!(isInherited && variantDidChange) || handledRemovedValues)) {
8741
+ for (const animation of definitionList) {
8943
8742
  const options = { type };
8944
8743
  /**
8945
- * If we're performing the initial animation, but we're not
8946
- * rendering at the same time as the variant-controlling parent,
8947
- * we want to use the parent's transition to calculate the stagger.
8744
+ * Elements that mount into an already-mounted parent
8745
+ * animate themselves, staggered by the parent variant's
8746
+ * delayChildren.
8948
8747
  */
8949
8748
  if (typeof animation === "string" &&
8950
- (isInitialRender || wasReset) &&
8951
- !willAnimateViaParent &&
8952
- visualElement.manuallyAnimateOnMount &&
8953
- visualElement.parent) {
8954
- const { parent } = visualElement;
8955
- const parentVariant = resolveVariant(parent, animation);
8956
- if (parent.enteringChildren && parentVariant) {
8957
- const { delayChildren } = parentVariant.transition || {};
8958
- options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);
8959
- }
8749
+ isMounting &&
8750
+ manuallyAnimateOnMount &&
8751
+ parent?.enteringChildren) {
8752
+ const delayChildren = resolveVariant(parent, animation)
8753
+ ?.transition?.delayChildren;
8754
+ options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);
8960
8755
  }
8961
- return {
8962
- animation: animation,
8963
- options,
8964
- };
8965
- }));
8756
+ animations.push({ animation, options });
8757
+ }
8966
8758
  }
8967
- }
8759
+ });
8968
8760
  /**
8969
- * If there are some removed value that haven't been dealt with,
8970
- * we need to create a new animation that falls back either to the value
8971
- * defined in the style prop, or the last read value.
8761
+ * Removed values that no lower-priority type defines animate back to
8762
+ * initial, then style, then the value as first read. If initial no
8763
+ * longer defines a value it once did, it stays where it is.
8972
8764
  */
8973
8765
  if (removedKeys.size) {
8766
+ const { initial } = props;
8974
8767
  const fallbackAnimation = {};
8975
- /**
8976
- * If the initial prop contains a transition we can use that, otherwise
8977
- * allow the animation function to use the visual element's default.
8978
- */
8979
- if (typeof props.initial !== "boolean") {
8980
- const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial)
8981
- ? props.initial[0]
8982
- : props.initial);
8983
- if (initialTransition && initialTransition.transition) {
8984
- fallbackAnimation.transition = initialTransition.transition;
8985
- }
8768
+ const resolvedInitial = typeof initial !== "boolean" &&
8769
+ resolveVariant(visualElement, Array.isArray(initial) ? initial[0] : initial, visualElement.presenceContext?.custom);
8770
+ if (resolvedInitial && resolvedInitial.transition) {
8771
+ fallbackAnimation.transition = resolvedInitial.transition;
8986
8772
  }
8987
8773
  removedKeys.forEach((key) => {
8988
- const fallbackTarget = visualElement.getBaseTarget(key);
8989
8774
  const motionValue = visualElement.getValue(key);
8990
8775
  if (motionValue)
8991
8776
  motionValue.liveStyle = true;
8992
- // @ts-expect-error - @mattgperry to figure if we should do something here
8993
- fallbackAnimation[key] = fallbackTarget ?? null;
8777
+ const fromInitial = resolvedInitial && !Array.isArray(initial)
8778
+ ? resolvedInitial[key]
8779
+ : undefined;
8780
+ const fromProps = visualElement.getBaseTargetFromProps(props, key);
8781
+ fallbackAnimation[key] =
8782
+ (fromInitial !== undefined
8783
+ ? fromInitial
8784
+ : fromProps !== undefined && !isMotionValue(fromProps)
8785
+ ? fromProps
8786
+ : visualElement.initialValues[key] === undefined
8787
+ ? visualElement.baseTarget[key]
8788
+ : undefined) ?? null;
8994
8789
  });
8995
8790
  animations.push({ animation: fallbackAnimation });
8996
8791
  }
8997
- let shouldAnimate = Boolean(animations.length);
8998
- if (isInitialRender &&
8999
- (props.initial === false || props.initial === props.animate) &&
9000
- !visualElement.manuallyAnimateOnMount) {
9001
- shouldAnimate = false;
9002
- }
9003
- isInitialRender = false;
9004
- wasReset = false;
9005
- return shouldAnimate ? animate(animations) : Promise.resolve();
8792
+ const blockAnimation = (isMounting && visualElement.blockInitialAnimation) ||
8793
+ (isInitialRender &&
8794
+ !manuallyAnimateOnMount &&
8795
+ (props.initial === false || props.initial === props.animate));
8796
+ isInitialRender = wasReset = false;
8797
+ return !blockAnimation && animations.length
8798
+ ? animate(animations)
8799
+ : Promise.resolve();
9006
8800
  }
9007
8801
  /**
9008
8802
  * Change whether a certain animation type is active.
9009
8803
  */
9010
8804
  function setActive(type, isActive) {
9011
- // If the active state hasn't changed, we can safely do nothing here
9012
8805
  if (state[type].isActive === isActive)
9013
8806
  return Promise.resolve();
9014
- // Propagate active change to children
9015
8807
  visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive));
9016
8808
  state[type].isActive = isActive;
9017
8809
  const animations = animateChanges(type);
@@ -9023,7 +8815,13 @@
9023
8815
  return {
9024
8816
  animateChanges,
9025
8817
  setActive,
9026
- setAnimateFunction,
8818
+ /**
8819
+ * Allows tests to inject a mocked animate function.
8820
+ * @internal
8821
+ */
8822
+ setAnimateFunction: (makeAnimator) => {
8823
+ animate = makeAnimator(visualElement);
8824
+ },
9027
8825
  getState: () => state,
9028
8826
  reset: () => {
9029
8827
  state = createState();
@@ -9040,24 +8838,45 @@
9040
8838
  }
9041
8839
  return false;
9042
8840
  }
9043
- function createTypeState(isActive = false) {
9044
- return {
9045
- isActive,
9046
- protectedKeys: {},
9047
- needsAnimating: {},
9048
- prevResolvedValues: {},
9049
- };
9050
- }
9051
8841
  function createState() {
9052
- return {
9053
- animate: createTypeState(true),
9054
- whileInView: createTypeState(),
9055
- whileHover: createTypeState(),
9056
- whileTap: createTypeState(),
9057
- whileDrag: createTypeState(),
9058
- whileFocus: createTypeState(),
9059
- exit: createTypeState(),
9060
- };
8842
+ const state = {};
8843
+ for (const type of variantPriorityOrder) {
8844
+ state[type] = {
8845
+ isActive: type === "animate",
8846
+ protectedKeys: {},
8847
+ needsAnimating: {},
8848
+ prevResolvedValues: {},
8849
+ };
8850
+ }
8851
+ return state;
8852
+ }
8853
+
8854
+ const numVariantProps = variantProps.length;
8855
+ /**
8856
+ * Get variant context from a visual element's parent chain.
8857
+ * Uses `any` type for visualElement to avoid circular dependencies.
8858
+ */
8859
+ function getVariantContext(visualElement) {
8860
+ if (!visualElement)
8861
+ return undefined;
8862
+ if (!visualElement.isControllingVariants) {
8863
+ const context = visualElement.parent
8864
+ ? getVariantContext(visualElement.parent) || {}
8865
+ : {};
8866
+ if (visualElement.props.initial !== undefined) {
8867
+ context.initial = visualElement.props.initial;
8868
+ }
8869
+ return context;
8870
+ }
8871
+ const context = {};
8872
+ for (let i = 0; i < numVariantProps; i++) {
8873
+ const name = variantProps[i];
8874
+ const prop = visualElement.props[name];
8875
+ if (isVariantLabel(prop) || prop === false) {
8876
+ context[name] = prop;
8877
+ }
8878
+ }
8879
+ return context;
9061
8880
  }
9062
8881
 
9063
8882
  /**
@@ -9226,6 +9045,75 @@
9226
9045
  return [callback("x"), callback("y")];
9227
9046
  }
9228
9047
 
9048
+ function pixelsToPercent(pixels, axis) {
9049
+ if (axis.max === axis.min)
9050
+ return 0;
9051
+ return (pixels / (axis.max - axis.min)) * 100;
9052
+ }
9053
+ /**
9054
+ * We always correct borderRadius as a percentage rather than pixels to reduce paints.
9055
+ * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
9056
+ * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
9057
+ * borderRadius in both states. If we animate between the two in pixels that will trigger
9058
+ * a paint each time. If we animate between the two in percentage we'll avoid a paint.
9059
+ */
9060
+ const correctBorderRadius = {
9061
+ correct: (latest, node) => {
9062
+ if (!node.target)
9063
+ return latest;
9064
+ /**
9065
+ * If latest is a string, if it's a percentage we can return immediately as it's
9066
+ * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
9067
+ */
9068
+ if (typeof latest === "string") {
9069
+ if (px.test(latest)) {
9070
+ latest = parseFloat(latest);
9071
+ }
9072
+ else {
9073
+ return latest;
9074
+ }
9075
+ }
9076
+ /**
9077
+ * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
9078
+ * pixel value as a percentage of each axis
9079
+ */
9080
+ const x = pixelsToPercent(latest, node.target.x);
9081
+ const y = pixelsToPercent(latest, node.target.y);
9082
+ return `${x}% ${y}%`;
9083
+ },
9084
+ };
9085
+
9086
+ const correctBoxShadow = {
9087
+ correct: (latest, { treeScale, projectionDelta }) => {
9088
+ const original = latest;
9089
+ const shadow = complex.parse(latest);
9090
+ // TODO: Doesn't support multiple shadows
9091
+ if (shadow.length > 5)
9092
+ return original;
9093
+ const template = complex.createTransformer(latest);
9094
+ const offset = typeof shadow[0] !== "number" ? 1 : 0;
9095
+ // Calculate the overall context scale
9096
+ const xScale = projectionDelta.x.scale * treeScale.x;
9097
+ const yScale = projectionDelta.y.scale * treeScale.y;
9098
+ shadow[0 + offset] /= xScale;
9099
+ shadow[1 + offset] /= yScale;
9100
+ /**
9101
+ * Ideally we'd correct x and y scales individually, but because blur and
9102
+ * spread apply to both we have to take a scale average and apply that instead.
9103
+ * We could potentially improve the outcome of this by incorporating the ratio between
9104
+ * the two scales.
9105
+ */
9106
+ const averageScale = mixNumber$1(xScale, yScale, 0.5);
9107
+ // Blur
9108
+ if (typeof shadow[2 + offset] === "number")
9109
+ shadow[2 + offset] /= averageScale;
9110
+ // Spread
9111
+ if (typeof shadow[3 + offset] === "number")
9112
+ shadow[3 + offset] /= averageScale;
9113
+ return template(shadow);
9114
+ },
9115
+ };
9116
+
9229
9117
  function buildProjectionTransform(delta, treeScale, latestTransform) {
9230
9118
  let transform = "";
9231
9119
  /**
@@ -9278,7 +9166,6 @@
9278
9166
  }
9279
9167
 
9280
9168
  const numBorders = cornerRadiusProps.length;
9281
- const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
9282
9169
  const isPx = (value) => typeof value === "number" || px.test(value);
9283
9170
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
9284
9171
  if (shouldCrossfadeOpacity) {
@@ -9477,6 +9364,18 @@
9477
9364
  }
9478
9365
  }
9479
9366
 
9367
+ const defaultScaleCorrectors = {
9368
+ borderRadius: {
9369
+ ...correctBorderRadius,
9370
+ applyTo: [...cornerRadiusProps],
9371
+ },
9372
+ borderTopLeftRadius: correctBorderRadius,
9373
+ borderTopRightRadius: correctBorderRadius,
9374
+ borderBottomLeftRadius: correctBorderRadius,
9375
+ borderBottomRightRadius: correctBorderRadius,
9376
+ boxShadow: correctBoxShadow,
9377
+ };
9378
+
9480
9379
  /**
9481
9380
  * This should only ever be modified on the client otherwise it'll
9482
9381
  * persist through server requests. If we need instanced states we
@@ -9495,6 +9394,14 @@
9495
9394
  hasEverUpdated: false,
9496
9395
  };
9497
9396
 
9397
+ /**
9398
+ * Correctors registered via addScaleCorrector before projection loaded
9399
+ * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
9400
+ */
9401
+ Object.assign(scaleCorrectors, {
9402
+ ...defaultScaleCorrectors,
9403
+ ...scaleCorrectors,
9404
+ });
9498
9405
  const metrics = {
9499
9406
  nodes: 0,
9500
9407
  calculatedTargetDeltas: 0,
@@ -11797,6 +11704,7 @@
11797
11704
  exports.observeTimeline = observeTimeline;
11798
11705
  exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute;
11799
11706
  exports.optimizedAppearDataId = optimizedAppearDataId;
11707
+ exports.originProps = originProps;
11800
11708
  exports.parseAnimateLayoutArgs = parseAnimateLayoutArgs;
11801
11709
  exports.parseCSSVariable = parseCSSVariable;
11802
11710
  exports.parseValueFromTransform = parseValueFromTransform;