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
@@ -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,14 @@
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, }) {
2698
2736
  if (this.allowFlatten) {
2699
2737
  this.animation.effect?.updateTiming({ easing: "linear" });
2700
2738
  }
2701
2739
  this.animation.onfinish = null;
2702
2740
  if (timeline && supportsScrollTimeline()) {
2703
2741
  this.animation.timeline = timeline;
2704
- if (rangeStart)
2705
- this.animation.rangeStart = rangeStart;
2706
- if (rangeEnd)
2707
- this.animation.rangeEnd = rangeEnd;
2742
+ onAttach?.(this.animation);
2708
2743
  return motionUtils.noop;
2709
2744
  }
2710
2745
  else {
@@ -6037,21 +6072,6 @@
6037
6072
  return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
6038
6073
  }
6039
6074
 
6040
- function observeTimeline(update, timeline) {
6041
- let prevProgress;
6042
- const onFrame = () => {
6043
- const { currentTime } = timeline;
6044
- const percentage = currentTime === null ? 0 : currentTime.value;
6045
- const progress = percentage / 100;
6046
- if (prevProgress !== progress) {
6047
- update(progress);
6048
- }
6049
- prevProgress = progress;
6050
- };
6051
- frame.preUpdate(onFrame, true);
6052
- return () => cancelFrame(onFrame);
6053
- }
6054
-
6055
6075
  const statsBuffer = {
6056
6076
  value: null,
6057
6077
  addProjectionMetrics: null,
@@ -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
  /**
@@ -8170,7 +8202,15 @@
8170
8202
  this.removeValue(key);
8171
8203
  this.bindToMotionValue(key, value);
8172
8204
  this.values.set(key, value);
8173
- this.latestValues[key] = value.get();
8205
+ /**
8206
+ * An animated value with no base value is undefined until the
8207
+ * keyframe resolver reads its origin. Rendering it before then
8208
+ * writes an invalid placeholder (e.g. points="undefined") that
8209
+ * the resolver can read back from the DOM as the origin.
8210
+ */
8211
+ const latest = value.get();
8212
+ if (latest !== undefined)
8213
+ this.latestValues[key] = latest;
8174
8214
  }
8175
8215
  }
8176
8216
  /**
@@ -8198,7 +8238,9 @@
8198
8238
  }
8199
8239
  let value = this.values.get(key);
8200
8240
  if (value === undefined && defaultValue !== undefined) {
8201
- value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this });
8241
+ value = motionValue(defaultValue ?? this.getDefaultValue?.(key), {
8242
+ owner: this,
8243
+ });
8202
8244
  this.addValue(key, value);
8203
8245
  }
8204
8246
  return value;
@@ -8360,86 +8402,7 @@
8360
8402
  }
8361
8403
  }
8362
8404
 
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
- };
8431
-
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
- };
8405
+ const scaleCorrectors = {};
8443
8406
  function addScaleCorrector(correctors) {
8444
8407
  for (const key in correctors) {
8445
8408
  scaleCorrectors[key] = correctors[key];
@@ -8613,7 +8576,24 @@
8613
8576
  this.measureInstanceViewportBox = createBox;
8614
8577
  }
8615
8578
  getBaseTargetFromProps(props, key) {
8616
- return props[key];
8579
+ /**
8580
+ * An independent transform's base is never an attribute of the same
8581
+ * name, e.g. <rect x> is a position, not a translate. Like HTML it
8582
+ * comes from style, falling back to the transform's default.
8583
+ */
8584
+ return transformProps.has(key)
8585
+ ? super.getBaseTargetFromProps(props, key) ??
8586
+ defaultTransformValue(key)
8587
+ : props[key];
8588
+ }
8589
+ /**
8590
+ * An independent transform's origin is never read from the DOM, so it
8591
+ * starts from its latest or default value and renders on mount.
8592
+ */
8593
+ getDefaultValue(key) {
8594
+ return transformProps.has(key)
8595
+ ? this.latestValues[key] ?? defaultTransformValue(key)
8596
+ : undefined;
8617
8597
  }
8618
8598
  readValueFromInstance(instance, key) {
8619
8599
  if (transformProps.has(key)) {
@@ -9226,6 +9206,75 @@
9226
9206
  return [callback("x"), callback("y")];
9227
9207
  }
9228
9208
 
9209
+ function pixelsToPercent(pixels, axis) {
9210
+ if (axis.max === axis.min)
9211
+ return 0;
9212
+ return (pixels / (axis.max - axis.min)) * 100;
9213
+ }
9214
+ /**
9215
+ * We always correct borderRadius as a percentage rather than pixels to reduce paints.
9216
+ * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
9217
+ * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
9218
+ * borderRadius in both states. If we animate between the two in pixels that will trigger
9219
+ * a paint each time. If we animate between the two in percentage we'll avoid a paint.
9220
+ */
9221
+ const correctBorderRadius = {
9222
+ correct: (latest, node) => {
9223
+ if (!node.target)
9224
+ return latest;
9225
+ /**
9226
+ * If latest is a string, if it's a percentage we can return immediately as it's
9227
+ * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
9228
+ */
9229
+ if (typeof latest === "string") {
9230
+ if (px.test(latest)) {
9231
+ latest = parseFloat(latest);
9232
+ }
9233
+ else {
9234
+ return latest;
9235
+ }
9236
+ }
9237
+ /**
9238
+ * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
9239
+ * pixel value as a percentage of each axis
9240
+ */
9241
+ const x = pixelsToPercent(latest, node.target.x);
9242
+ const y = pixelsToPercent(latest, node.target.y);
9243
+ return `${x}% ${y}%`;
9244
+ },
9245
+ };
9246
+
9247
+ const correctBoxShadow = {
9248
+ correct: (latest, { treeScale, projectionDelta }) => {
9249
+ const original = latest;
9250
+ const shadow = complex.parse(latest);
9251
+ // TODO: Doesn't support multiple shadows
9252
+ if (shadow.length > 5)
9253
+ return original;
9254
+ const template = complex.createTransformer(latest);
9255
+ const offset = typeof shadow[0] !== "number" ? 1 : 0;
9256
+ // Calculate the overall context scale
9257
+ const xScale = projectionDelta.x.scale * treeScale.x;
9258
+ const yScale = projectionDelta.y.scale * treeScale.y;
9259
+ shadow[0 + offset] /= xScale;
9260
+ shadow[1 + offset] /= yScale;
9261
+ /**
9262
+ * Ideally we'd correct x and y scales individually, but because blur and
9263
+ * spread apply to both we have to take a scale average and apply that instead.
9264
+ * We could potentially improve the outcome of this by incorporating the ratio between
9265
+ * the two scales.
9266
+ */
9267
+ const averageScale = mixNumber$1(xScale, yScale, 0.5);
9268
+ // Blur
9269
+ if (typeof shadow[2 + offset] === "number")
9270
+ shadow[2 + offset] /= averageScale;
9271
+ // Spread
9272
+ if (typeof shadow[3 + offset] === "number")
9273
+ shadow[3 + offset] /= averageScale;
9274
+ return template(shadow);
9275
+ },
9276
+ };
9277
+
9229
9278
  function buildProjectionTransform(delta, treeScale, latestTransform) {
9230
9279
  let transform = "";
9231
9280
  /**
@@ -9278,7 +9327,6 @@
9278
9327
  }
9279
9328
 
9280
9329
  const numBorders = cornerRadiusProps.length;
9281
- const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
9282
9330
  const isPx = (value) => typeof value === "number" || px.test(value);
9283
9331
  function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
9284
9332
  if (shouldCrossfadeOpacity) {
@@ -9477,6 +9525,18 @@
9477
9525
  }
9478
9526
  }
9479
9527
 
9528
+ const defaultScaleCorrectors = {
9529
+ borderRadius: {
9530
+ ...correctBorderRadius,
9531
+ applyTo: [...cornerRadiusProps],
9532
+ },
9533
+ borderTopLeftRadius: correctBorderRadius,
9534
+ borderTopRightRadius: correctBorderRadius,
9535
+ borderBottomLeftRadius: correctBorderRadius,
9536
+ borderBottomRightRadius: correctBorderRadius,
9537
+ boxShadow: correctBoxShadow,
9538
+ };
9539
+
9480
9540
  /**
9481
9541
  * This should only ever be modified on the client otherwise it'll
9482
9542
  * persist through server requests. If we need instanced states we
@@ -9495,6 +9555,14 @@
9495
9555
  hasEverUpdated: false,
9496
9556
  };
9497
9557
 
9558
+ /**
9559
+ * Correctors registered via addScaleCorrector before projection loaded
9560
+ * (e.g. with an async LazyMotion bundle) take precedence over the defaults.
9561
+ */
9562
+ Object.assign(scaleCorrectors, {
9563
+ ...defaultScaleCorrectors,
9564
+ ...scaleCorrectors,
9565
+ });
9498
9566
  const metrics = {
9499
9567
  nodes: 0,
9500
9568
  calculatedTargetDeltas: 0,
@@ -11794,7 +11862,6 @@
11794
11862
  exports.nodeGroup = nodeGroup;
11795
11863
  exports.number = number;
11796
11864
  exports.numberValueTypes = numberValueTypes;
11797
- exports.observeTimeline = observeTimeline;
11798
11865
  exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute;
11799
11866
  exports.optimizedAppearDataId = optimizedAppearDataId;
11800
11867
  exports.parseAnimateLayoutArgs = parseAnimateLayoutArgs;