motion-dom 13.4.5 → 13.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/cjs/index.js +413 -346
  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 +2 -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/utils/notify-inspector.mjs +1 -1
  12. package/dist/es/animation/utils/notify-inspector.mjs.map +1 -1
  13. package/dist/es/frameloop/batcher.mjs +5 -6
  14. package/dist/es/frameloop/batcher.mjs.map +1 -1
  15. package/dist/es/frameloop/frame-data.mjs +12 -0
  16. package/dist/es/frameloop/frame-data.mjs.map +1 -0
  17. package/dist/es/frameloop/frame.mjs +3 -2
  18. package/dist/es/frameloop/frame.mjs.map +1 -1
  19. package/dist/es/frameloop/sync-time.mjs +1 -1
  20. package/dist/es/frameloop/sync-time.mjs.map +1 -1
  21. package/dist/es/index.mjs +2 -2
  22. package/dist/es/layout/LayoutAnimationBuilder.mjs +2 -1
  23. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  24. package/dist/es/projection/animation/mix-values.mjs +1 -1
  25. package/dist/es/projection/animation/mix-values.mjs.map +1 -1
  26. package/dist/es/projection/node/create-projection-node.mjs +11 -1
  27. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  28. package/dist/es/projection/styles/default-scale-correctors.mjs +18 -0
  29. package/dist/es/projection/styles/default-scale-correctors.mjs.map +1 -0
  30. package/dist/es/projection/styles/scale-correction.mjs +1 -14
  31. package/dist/es/projection/styles/scale-correction.mjs.map +1 -1
  32. package/dist/es/projection/utils/each-axis.mjs.map +1 -1
  33. package/dist/es/render/VisualElement.mjs +12 -2
  34. package/dist/es/render/VisualElement.mjs.map +1 -1
  35. package/dist/es/render/svg/SVGVisualElement.mjs +19 -1
  36. package/dist/es/render/svg/SVGVisualElement.mjs.map +1 -1
  37. package/dist/es/value/follow-value.mjs +8 -85
  38. package/dist/es/value/follow-value.mjs.map +1 -1
  39. package/dist/es/value/spring-value.mjs +8 -3
  40. package/dist/es/value/spring-value.mjs.map +1 -1
  41. package/dist/es/value/utils/as-number.mjs +4 -0
  42. package/dist/es/value/utils/as-number.mjs.map +1 -0
  43. package/dist/es/value/utils/follow.mjs +94 -0
  44. package/dist/es/value/utils/follow.mjs.map +1 -0
  45. package/dist/index.d.ts +30 -14
  46. package/dist/motion-dom.dev.js +413 -346
  47. package/dist/motion-dom.js +1 -1
  48. package/dist/size-rollup-motion-value.js +1 -1
  49. package/dist/size-rollup-motion-value.js.map +1 -1
  50. package/dist/size-rollup-style-effect.js +1 -1
  51. package/dist/size-rollup-style-effect.js.map +1 -1
  52. package/package.json +6 -5
  53. package/dist/es/scroll/observe.mjs +0 -19
  54. package/dist/es/scroll/observe.mjs.map +0 -1
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,14 @@ 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, }) {
2699
2737
  if (this.allowFlatten) {
2700
2738
  this.animation.effect?.updateTiming({ easing: "linear" });
2701
2739
  }
2702
2740
  this.animation.onfinish = null;
2703
2741
  if (timeline && supportsScrollTimeline()) {
2704
2742
  this.animation.timeline = timeline;
2705
- if (rangeStart)
2706
- this.animation.rangeStart = rangeStart;
2707
- if (rangeEnd)
2708
- this.animation.rangeEnd = rangeEnd;
2743
+ onAttach?.(this.animation);
2709
2744
  return motionUtils.noop;
2710
2745
  }
2711
2746
  else {
@@ -6038,21 +6073,6 @@ function resize(a, b) {
6038
6073
  return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
6039
6074
  }
6040
6075
 
6041
- function observeTimeline(update, timeline) {
6042
- let prevProgress;
6043
- const onFrame = () => {
6044
- const { currentTime } = timeline;
6045
- const percentage = currentTime === null ? 0 : currentTime.value;
6046
- const progress = percentage / 100;
6047
- if (prevProgress !== progress) {
6048
- update(progress);
6049
- }
6050
- prevProgress = progress;
6051
- };
6052
- frame.preUpdate(onFrame, true);
6053
- return () => cancelFrame(onFrame);
6054
- }
6055
-
6056
6076
  const statsBuffer = {
6057
6077
  value: null,
6058
6078
  addProjectionMetrics: null,
@@ -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
  /**
@@ -8171,7 +8203,15 @@ class VisualElement {
8171
8203
  this.removeValue(key);
8172
8204
  this.bindToMotionValue(key, value);
8173
8205
  this.values.set(key, value);
8174
- this.latestValues[key] = value.get();
8206
+ /**
8207
+ * An animated value with no base value is undefined until the
8208
+ * keyframe resolver reads its origin. Rendering it before then
8209
+ * writes an invalid placeholder (e.g. points="undefined") that
8210
+ * the resolver can read back from the DOM as the origin.
8211
+ */
8212
+ const latest = value.get();
8213
+ if (latest !== undefined)
8214
+ this.latestValues[key] = latest;
8175
8215
  }
8176
8216
  }
8177
8217
  /**
@@ -8199,7 +8239,9 @@ class VisualElement {
8199
8239
  }
8200
8240
  let value = this.values.get(key);
8201
8241
  if (value === undefined && defaultValue !== undefined) {
8202
- value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this });
8242
+ value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
8243
+ owner: this,
8244
+ });
8203
8245
  this.addValue(key, value);
8204
8246
  }
8205
8247
  return value;
@@ -8361,86 +8403,7 @@ function renderHTML(element, { style, vars }, styleProp, projection) {
8361
8403
  }
8362
8404
  }
8363
8405
 
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
- };
8432
-
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
- };
8406
+ const scaleCorrectors = {};
8444
8407
  function addScaleCorrector(correctors) {
8445
8408
  for (const key in correctors) {
8446
8409
  scaleCorrectors[key] = correctors[key];
@@ -8614,7 +8577,24 @@ class SVGVisualElement extends DOMVisualElement {
8614
8577
  this.measureInstanceViewportBox = createBox;
8615
8578
  }
8616
8579
  getBaseTargetFromProps(props, key) {
8617
- return props[key];
8580
+ /**
8581
+ * An independent transform's base is never an attribute of the same
8582
+ * name, e.g. <rect x> is a position, not a translate. Like HTML it
8583
+ * comes from style, falling back to the transform's default.
8584
+ */
8585
+ return transformProps.has(key)
8586
+ ? super.getBaseTargetFromProps(props, key) ??
8587
+ defaultTransformValue(key)
8588
+ : props[key];
8589
+ }
8590
+ /**
8591
+ * An independent transform's origin is never read from the DOM, so it
8592
+ * starts from its latest or default value and renders on mount.
8593
+ */
8594
+ getDefaultValue(key) {
8595
+ return transformProps.has(key)
8596
+ ? this.latestValues[key] ?? defaultTransformValue(key)
8597
+ : undefined;
8618
8598
  }
8619
8599
  readValueFromInstance(instance, key) {
8620
8600
  if (transformProps.has(key)) {
@@ -9227,6 +9207,75 @@ function eachAxis(callback) {
9227
9207
  return [callback("x"), callback("y")];
9228
9208
  }
9229
9209
 
9210
+ function pixelsToPercent(pixels, axis) {
9211
+ if (axis.max === axis.min)
9212
+ return 0;
9213
+ return (pixels / (axis.max - axis.min)) * 100;
9214
+ }
9215
+ /**
9216
+ * We always correct borderRadius as a percentage rather than pixels to reduce paints.
9217
+ * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
9218
+ * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
9219
+ * borderRadius in both states. If we animate between the two in pixels that will trigger
9220
+ * a paint each time. If we animate between the two in percentage we'll avoid a paint.
9221
+ */
9222
+ const correctBorderRadius = {
9223
+ correct: (latest, node) => {
9224
+ if (!node.target)
9225
+ return latest;
9226
+ /**
9227
+ * If latest is a string, if it's a percentage we can return immediately as it's
9228
+ * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
9229
+ */
9230
+ if (typeof latest === "string") {
9231
+ if (px.test(latest)) {
9232
+ latest = parseFloat(latest);
9233
+ }
9234
+ else {
9235
+ return latest;
9236
+ }
9237
+ }
9238
+ /**
9239
+ * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
9240
+ * pixel value as a percentage of each axis
9241
+ */
9242
+ const x = pixelsToPercent(latest, node.target.x);
9243
+ const y = pixelsToPercent(latest, node.target.y);
9244
+ return `${x}% ${y}%`;
9245
+ },
9246
+ };
9247
+
9248
+ const correctBoxShadow = {
9249
+ correct: (latest, { treeScale, projectionDelta }) => {
9250
+ const original = latest;
9251
+ const shadow = complex.parse(latest);
9252
+ // TODO: Doesn't support multiple shadows
9253
+ if (shadow.length > 5)
9254
+ return original;
9255
+ const template = complex.createTransformer(latest);
9256
+ const offset = typeof shadow[0] !== "number" ? 1 : 0;
9257
+ // Calculate the overall context scale
9258
+ const xScale = projectionDelta.x.scale * treeScale.x;
9259
+ const yScale = projectionDelta.y.scale * treeScale.y;
9260
+ shadow[0 + offset] /= xScale;
9261
+ shadow[1 + offset] /= yScale;
9262
+ /**
9263
+ * Ideally we'd correct x and y scales individually, but because blur and
9264
+ * spread apply to both we have to take a scale average and apply that instead.
9265
+ * We could potentially improve the outcome of this by incorporating the ratio between
9266
+ * the two scales.
9267
+ */
9268
+ const averageScale = mixNumber$1(xScale, yScale, 0.5);
9269
+ // Blur
9270
+ if (typeof shadow[2 + offset] === "number")
9271
+ shadow[2 + offset] /= averageScale;
9272
+ // Spread
9273
+ if (typeof shadow[3 + offset] === "number")
9274
+ shadow[3 + offset] /= averageScale;
9275
+ return template(shadow);
9276
+ },
9277
+ };
9278
+
9230
9279
  function buildProjectionTransform(delta, treeScale, latestTransform) {
9231
9280
  let transform = "";
9232
9281
  /**
@@ -9279,7 +9328,6 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
9279
9328
  }
9280
9329
 
9281
9330
  const numBorders = cornerRadiusProps.length;
9282
- const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
9283
9331
  const isPx = (value) => typeof value === "number" || px.test(value);
9284
9332
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
9285
9333
  if (shouldCrossfadeOpacity) {
@@ -9478,6 +9526,18 @@ class NodeStack {
9478
9526
  }
9479
9527
  }
9480
9528
 
9529
+ const defaultScaleCorrectors = {
9530
+ borderRadius: {
9531
+ ...correctBorderRadius,
9532
+ applyTo: [...cornerRadiusProps],
9533
+ },
9534
+ borderTopLeftRadius: correctBorderRadius,
9535
+ borderTopRightRadius: correctBorderRadius,
9536
+ borderBottomLeftRadius: correctBorderRadius,
9537
+ borderBottomRightRadius: correctBorderRadius,
9538
+ boxShadow: correctBoxShadow,
9539
+ };
9540
+
9481
9541
  /**
9482
9542
  * This should only ever be modified on the client otherwise it'll
9483
9543
  * persist through server requests. If we need instanced states we
@@ -9496,6 +9556,14 @@ const globalProjectionState = {
9496
9556
  hasEverUpdated: false,
9497
9557
  };
9498
9558
 
9559
+ /**
9560
+ * Correctors registered via addScaleCorrector before projection loaded
9561
+ * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
9562
+ */
9563
+ Object.assign(scaleCorrectors, {
9564
+ ...defaultScaleCorrectors,
9565
+ ...scaleCorrectors,
9566
+ });
9499
9567
  const metrics = {
9500
9568
  nodes: 0,
9501
9569
  calculatedTargetDeltas: 0,
@@ -11795,7 +11863,6 @@ exports.motionValue = motionValue;
11795
11863
  exports.nodeGroup = nodeGroup;
11796
11864
  exports.number = number;
11797
11865
  exports.numberValueTypes = numberValueTypes;
11798
- exports.observeTimeline = observeTimeline;
11799
11866
  exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute;
11800
11867
  exports.optimizedAppearDataId = optimizedAppearDataId;
11801
11868
  exports.parseAnimateLayoutArgs = parseAnimateLayoutArgs;