motion-dom 12.7.4 → 12.7.5-alpha.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 (92) hide show
  1. package/dist/cjs/index.js +2946 -475
  2. package/dist/es/animation/AsyncMotionValueAnimation.mjs +178 -0
  3. package/dist/es/animation/GroupAnimation.mjs +6 -15
  4. package/dist/es/animation/JSAnimation.mjs +346 -0
  5. package/dist/es/animation/NativeAnimation.mjs +64 -67
  6. package/dist/es/animation/NativeAnimationExtended.mjs +65 -0
  7. package/dist/es/animation/NativeAnimationWrapper.mjs +14 -0
  8. package/dist/es/animation/drivers/driver-frameloop.mjs +17 -0
  9. package/dist/es/animation/generators/inertia.mjs +87 -0
  10. package/dist/es/animation/generators/keyframes.mjs +49 -0
  11. package/dist/es/animation/generators/spring/defaults.mjs +27 -0
  12. package/dist/es/animation/generators/spring/find.mjs +84 -0
  13. package/dist/es/animation/generators/spring/index.mjs +175 -0
  14. package/dist/es/animation/generators/utils/velocity.mjs +9 -0
  15. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +131 -0
  16. package/dist/es/animation/keyframes/KeyframesResolver.mjs +156 -0
  17. package/dist/es/animation/keyframes/get-final.mjs +3 -4
  18. package/dist/es/animation/keyframes/offsets/default.mjs +9 -0
  19. package/dist/es/animation/keyframes/offsets/fill.mjs +12 -0
  20. package/dist/es/animation/keyframes/offsets/time.mjs +5 -0
  21. package/dist/es/animation/keyframes/utils/apply-px-defaults.mjs +11 -0
  22. package/dist/es/animation/keyframes/utils/fill-wildcards.mjs +7 -0
  23. package/dist/es/animation/keyframes/utils/is-none.mjs +15 -0
  24. package/dist/es/animation/keyframes/utils/make-none-animatable.mjs +30 -0
  25. package/dist/es/animation/keyframes/utils/unit-conversion.mjs +36 -0
  26. package/dist/es/animation/utils/WithPromise.mjs +28 -0
  27. package/dist/es/animation/utils/active-animations.mjs +9 -0
  28. package/dist/es/animation/utils/can-animate.mjs +42 -0
  29. package/dist/es/animation/utils/css-variables-conversion.mjs +41 -0
  30. package/dist/es/animation/utils/is-animatable.mjs +30 -0
  31. package/dist/es/animation/utils/is-css-variable.mjs +15 -0
  32. package/dist/es/animation/utils/replace-transition-type.mjs +18 -0
  33. package/dist/es/animation/waapi/easing/is-supported.mjs +1 -1
  34. package/dist/es/animation/waapi/easing/map-easing.mjs +5 -3
  35. package/dist/es/animation/waapi/start-waapi-animation.mjs +6 -4
  36. package/dist/es/animation/waapi/supports/waapi.mjs +39 -0
  37. package/dist/es/animation/waapi/utils/accelerated-values.mjs +14 -0
  38. package/dist/es/animation/waapi/utils/apply-generator.mjs +2 -1
  39. package/dist/es/animation/waapi/utils/unsupported-easing.mjs +18 -0
  40. package/dist/es/frameloop/batcher.mjs +2 -1
  41. package/dist/es/frameloop/order.mjs +1 -0
  42. package/dist/es/index.mjs +49 -2
  43. package/dist/es/render/dom/is-css-var.mjs +3 -0
  44. package/dist/es/render/dom/parse-transform.mjs +83 -0
  45. package/dist/es/render/dom/style-computed.mjs +10 -0
  46. package/dist/es/render/dom/style-set.mjs +9 -0
  47. package/dist/es/render/utils/keys-position.mjs +13 -0
  48. package/dist/es/render/utils/keys-transform.mjs +28 -0
  49. package/dist/es/scroll/observe.mjs +18 -0
  50. package/dist/es/stats/index.mjs +2 -0
  51. package/dist/es/utils/interpolate.mjs +74 -0
  52. package/dist/es/utils/mix/color.mjs +47 -0
  53. package/dist/es/utils/mix/complex.mjs +92 -0
  54. package/dist/es/utils/mix/immediate.mjs +5 -0
  55. package/dist/es/utils/mix/index.mjs +14 -0
  56. package/dist/es/utils/mix/number.mjs +26 -0
  57. package/dist/es/utils/mix/visibility.mjs +16 -0
  58. package/dist/es/value/index.mjs +3 -1
  59. package/dist/es/value/types/auto.mjs +9 -0
  60. package/dist/es/value/types/color/hex.mjs +40 -0
  61. package/dist/es/value/types/color/hsla-to-rgba.mjs +42 -0
  62. package/dist/es/value/types/color/hsla.mjs +22 -0
  63. package/dist/es/value/types/color/index.mjs +27 -0
  64. package/dist/es/value/types/color/rgba.mjs +25 -0
  65. package/dist/es/value/types/color/utils.mjs +29 -0
  66. package/dist/es/value/types/complex/filter.mjs +30 -0
  67. package/dist/es/value/types/complex/index.mjs +91 -0
  68. package/dist/es/value/types/dimensions.mjs +15 -0
  69. package/dist/es/value/types/int.mjs +8 -0
  70. package/dist/es/value/types/maps/defaults.mjs +30 -0
  71. package/dist/es/value/types/maps/number.mjs +51 -0
  72. package/dist/es/value/types/maps/transform.mjs +31 -0
  73. package/dist/es/value/types/numbers/index.mjs +17 -0
  74. package/dist/es/value/types/numbers/units.mjs +18 -0
  75. package/dist/es/value/types/test.mjs +6 -0
  76. package/dist/es/value/types/utils/animatable-none.mjs +15 -0
  77. package/dist/es/value/types/utils/color-regex.mjs +3 -0
  78. package/dist/es/value/types/utils/find.mjs +15 -0
  79. package/dist/es/value/types/utils/float-regex.mjs +3 -0
  80. package/dist/es/value/types/utils/get-as-type.mjs +10 -0
  81. package/dist/es/value/types/utils/is-nullish.mjs +5 -0
  82. package/dist/es/value/types/utils/sanitize.mjs +5 -0
  83. package/dist/es/value/types/utils/single-color-regex.mjs +3 -0
  84. package/dist/es/view/start.mjs +4 -3
  85. package/dist/index.d.ts +945 -444
  86. package/dist/motion-dom.dev.js +2945 -475
  87. package/dist/motion-dom.js +1 -1
  88. package/package.json +3 -3
  89. package/dist/es/animation/keyframes/hydrate.mjs +0 -26
  90. package/dist/es/animation/waapi/utils/attach-timeline.mjs +0 -6
  91. package/dist/es/render/dom/style.mjs +0 -15
  92. package/dist/es/utils/is-bezier-definition.mjs +0 -3
@@ -1,90 +1,86 @@
1
1
  import { invariant, millisecondsToSeconds, secondsToMilliseconds, noop } from 'motion-utils';
2
- import { style } from '../render/dom/style.mjs';
2
+ import { setStyle } from '../render/dom/style-set.mjs';
3
+ import { supportsScrollTimeline } from '../utils/supports/scroll-timeline.mjs';
3
4
  import { getFinalKeyframe } from './keyframes/get-final.mjs';
4
- import { hydrateKeyframes } from './keyframes/hydrate.mjs';
5
+ import { WithPromise } from './utils/WithPromise.mjs';
5
6
  import { startWaapiAnimation } from './waapi/start-waapi-animation.mjs';
6
7
  import { applyGeneratorOptions } from './waapi/utils/apply-generator.mjs';
7
8
 
8
- const animationMaps = new WeakMap();
9
- const animationMapKey = (name, pseudoElement) => `${name}:${pseudoElement}`;
10
- function getAnimationMap(element) {
11
- const map = animationMaps.get(element) || new Map();
12
- animationMaps.set(element, map);
13
- return map;
14
- }
15
9
  /**
16
10
  * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.
17
11
  */
18
- class NativeAnimation {
12
+ class NativeAnimation extends WithPromise {
19
13
  constructor(options) {
20
- /**
21
- * If we already have an animation, we don't need to instantiate one
22
- * and can just use this as a controls interface.
23
- */
24
- if ("animation" in options) {
25
- this.animation = options.animation;
14
+ super();
15
+ this.finishedTime = null;
16
+ this.isStopped = false;
17
+ if (!options)
26
18
  return;
27
- }
28
- const { element, name, keyframes: unresolvedKeyframes, pseudoElement, allowFlatten = false, } = options;
29
- let { transition } = options;
19
+ const { element, name, keyframes, pseudoElement, allowFlatten = false, finalKeyframe, } = options;
30
20
  this.isPseudoElement = Boolean(pseudoElement);
31
21
  this.allowFlatten = allowFlatten;
32
- /**
33
- * Stop any existing animations on the element before reading existing keyframes.
34
- *
35
- * TODO: Check for VisualElement before using animation state. This is a fallback
36
- * for mini animate(). Do this when implementing NativeAnimationExtended.
37
- */
38
- const animationMap = getAnimationMap(element);
39
- const key = animationMapKey(name, pseudoElement || "");
40
- const currentAnimation = animationMap.get(key);
41
- currentAnimation && currentAnimation.stop();
42
- /**
43
- * TODO: If these keyframes aren't correctly hydrated then we want to throw
44
- * run an instant animation.
45
- */
46
- const keyframes = hydrateKeyframes(element, name, unresolvedKeyframes, pseudoElement);
47
- invariant(typeof transition.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "motion"?`);
48
- transition = applyGeneratorOptions(transition);
22
+ this.options = options;
23
+ invariant(typeof options.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "motion"?`);
24
+ const transition = applyGeneratorOptions(options);
49
25
  this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
50
26
  if (transition.autoplay === false) {
51
27
  this.animation.pause();
52
28
  }
53
- this.removeAnimation = () => animationMap.delete(key);
54
29
  this.animation.onfinish = () => {
30
+ this.finishedTime = this.time;
55
31
  if (!pseudoElement) {
56
- style.set(element, name, getFinalKeyframe(keyframes, transition));
57
- this.cancel();
32
+ const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
33
+ if (this.updateMotionValue) {
34
+ this.updateMotionValue(keyframe);
35
+ }
36
+ else {
37
+ /**
38
+ * If we can, we want to commit the final style as set by the user,
39
+ * rather than the computed keyframe value supplied by the animation.
40
+ */
41
+ setStyle(element, name, keyframe);
42
+ }
43
+ this.animation.cancel();
58
44
  }
45
+ this.notifyFinished();
59
46
  };
60
- /**
61
- * TODO: Check for VisualElement before using animation state.
62
- */
63
- animationMap.set(key, this);
64
47
  }
65
48
  play() {
49
+ if (this.isStopped)
50
+ return;
66
51
  this.animation.play();
52
+ if (this.state === "finished") {
53
+ this.updateFinished();
54
+ }
67
55
  }
68
56
  pause() {
69
57
  this.animation.pause();
70
58
  }
71
59
  complete() {
72
- this.animation.finish();
60
+ this.animation.finish?.();
73
61
  }
74
62
  cancel() {
75
63
  try {
76
64
  this.animation.cancel();
77
65
  }
78
66
  catch (e) { }
79
- this.removeAnimation();
80
67
  }
81
68
  stop() {
69
+ if (this.isStopped)
70
+ return;
71
+ this.isStopped = true;
82
72
  const { state } = this;
83
73
  if (state === "idle" || state === "finished") {
84
74
  return;
85
75
  }
86
- this.commitStyles();
87
- this.cancel();
76
+ if (this.updateMotionValue) {
77
+ this.updateMotionValue();
78
+ }
79
+ else {
80
+ this.commitStyles();
81
+ }
82
+ if (!this.isPseudoElement)
83
+ this.cancel();
88
84
  }
89
85
  /**
90
86
  * WAAPI doesn't natively have any interruption capabilities.
@@ -104,13 +100,14 @@ class NativeAnimation {
104
100
  }
105
101
  }
106
102
  get duration() {
107
- const duration = this.animation.effect?.getComputedTiming().duration || 0;
103
+ const duration = this.animation.effect?.getComputedTiming?.().duration || 0;
108
104
  return millisecondsToSeconds(Number(duration));
109
105
  }
110
106
  get time() {
111
107
  return millisecondsToSeconds(Number(this.animation.currentTime) || 0);
112
108
  }
113
109
  set time(newTime) {
110
+ this.finishedTime = null;
114
111
  this.animation.currentTime = secondsToMilliseconds(newTime);
115
112
  }
116
113
  /**
@@ -121,37 +118,37 @@ class NativeAnimation {
121
118
  return this.animation.playbackRate;
122
119
  }
123
120
  set speed(newSpeed) {
121
+ // Allow backwards playback after finishing
122
+ if (newSpeed < 0)
123
+ this.finishedTime = null;
124
124
  this.animation.playbackRate = newSpeed;
125
125
  }
126
126
  get state() {
127
- return this.animation.playState;
127
+ return this.finishedTime !== null
128
+ ? "finished"
129
+ : this.animation.playState;
128
130
  }
129
131
  get startTime() {
130
132
  return Number(this.animation.startTime);
131
133
  }
132
- get finished() {
133
- return this.animation.finished;
134
- }
135
- flatten() {
136
- if (this.allowFlatten) {
137
- this.animation.effect?.updateTiming({ easing: "linear" });
138
- }
134
+ set startTime(newStartTime) {
135
+ this.animation.startTime = newStartTime;
139
136
  }
140
137
  /**
141
138
  * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
142
139
  */
143
- attachTimeline(timeline) {
144
- this.animation.timeline = timeline;
140
+ attachTimeline({ timeline, observe }) {
141
+ if (this.allowFlatten) {
142
+ this.animation.effect?.updateTiming({ easing: "linear" });
143
+ }
145
144
  this.animation.onfinish = null;
146
- return noop;
147
- }
148
- /**
149
- * Allows the animation to be awaited.
150
- *
151
- * @deprecated Use `finished` instead.
152
- */
153
- then(onResolve, onReject) {
154
- return this.finished.then(onResolve).catch(onReject);
145
+ if (supportsScrollTimeline()) {
146
+ this.animation.timeline = timeline;
147
+ return noop;
148
+ }
149
+ else {
150
+ return observe(this);
151
+ }
155
152
  }
156
153
  }
157
154
 
@@ -0,0 +1,65 @@
1
+ import { secondsToMilliseconds } from 'motion-utils';
2
+ import { JSAnimation } from './JSAnimation.mjs';
3
+ import { NativeAnimation } from './NativeAnimation.mjs';
4
+ import { replaceTransitionType } from './utils/replace-transition-type.mjs';
5
+ import { replaceStringEasing } from './waapi/utils/unsupported-easing.mjs';
6
+
7
+ /**
8
+ * 10ms is chosen here as it strikes a balance between smooth
9
+ * results (more than one keyframe per frame at 60fps) and
10
+ * keyframe quantity.
11
+ */
12
+ const sampleDelta = 10; //ms
13
+ class NativeAnimationExtended extends NativeAnimation {
14
+ constructor(options) {
15
+ /**
16
+ * The base NativeAnimation function only supports a subset
17
+ * of Motion easings, and WAAPI also only supports some
18
+ * easing functions via string/cubic-bezier definitions.
19
+ *
20
+ * This function replaces those unsupported easing functions
21
+ * with a JS easing function. This will later get compiled
22
+ * to a linear() easing function.
23
+ */
24
+ replaceStringEasing(options);
25
+ /**
26
+ * Ensure we replace the transition type with a generator function
27
+ * before passing to WAAPI.
28
+ *
29
+ * TODO: Does this have a better home? It could be shared with
30
+ * JSAnimation.
31
+ */
32
+ replaceTransitionType(options);
33
+ super(options);
34
+ if (options.startTime) {
35
+ this.startTime = options.startTime;
36
+ }
37
+ this.options = options;
38
+ }
39
+ /**
40
+ * WAAPI doesn't natively have any interruption capabilities.
41
+ *
42
+ * Rather than read commited styles back out of the DOM, we can
43
+ * create a renderless JS animation and sample it twice to calculate
44
+ * its current value, "previous" value, and therefore allow
45
+ * Motion to calculate velocity for any subsequent animation.
46
+ */
47
+ updateMotionValue(value) {
48
+ const { motionValue, onUpdate, onComplete, element, ...options } = this.options;
49
+ if (!motionValue)
50
+ return;
51
+ if (value !== undefined) {
52
+ motionValue.set(value);
53
+ return;
54
+ }
55
+ const sampleAnimation = new JSAnimation({
56
+ ...options,
57
+ autoplay: false,
58
+ });
59
+ const sampleTime = secondsToMilliseconds(this.finishedTime ?? this.time);
60
+ motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);
61
+ sampleAnimation.stop();
62
+ }
63
+ }
64
+
65
+ export { NativeAnimationExtended };
@@ -0,0 +1,14 @@
1
+ import { NativeAnimation } from './NativeAnimation.mjs';
2
+
3
+ class NativeAnimationWrapper extends NativeAnimation {
4
+ constructor(animation) {
5
+ super();
6
+ this.animation = animation;
7
+ animation.onfinish = () => {
8
+ this.finishedTime = this.time;
9
+ this.notifyFinished();
10
+ };
11
+ }
12
+ }
13
+
14
+ export { NativeAnimationWrapper };
@@ -0,0 +1,17 @@
1
+ import { time } from '../../frameloop/sync-time.mjs';
2
+ import { frame, cancelFrame, frameData } from '../../frameloop/frame.mjs';
3
+
4
+ const frameloopDriver = (update) => {
5
+ const passTimestamp = ({ timestamp }) => update(timestamp);
6
+ return {
7
+ start: () => frame.update(passTimestamp, true),
8
+ stop: () => cancelFrame(passTimestamp),
9
+ /**
10
+ * If we're processing this frame we can use the
11
+ * framelocked timestamp to keep things in sync.
12
+ */
13
+ now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),
14
+ };
15
+ };
16
+
17
+ export { frameloopDriver };
@@ -0,0 +1,87 @@
1
+ import { spring } from './spring/index.mjs';
2
+ import { calcGeneratorVelocity } from './utils/velocity.mjs';
3
+
4
+ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {
5
+ const origin = keyframes[0];
6
+ const state = {
7
+ done: false,
8
+ value: origin,
9
+ };
10
+ const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);
11
+ const nearestBoundary = (v) => {
12
+ if (min === undefined)
13
+ return max;
14
+ if (max === undefined)
15
+ return min;
16
+ return Math.abs(min - v) < Math.abs(max - v) ? min : max;
17
+ };
18
+ let amplitude = power * velocity;
19
+ const ideal = origin + amplitude;
20
+ const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
21
+ /**
22
+ * If the target has changed we need to re-calculate the amplitude, otherwise
23
+ * the animation will start from the wrong position.
24
+ */
25
+ if (target !== ideal)
26
+ amplitude = target - origin;
27
+ const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
28
+ const calcLatest = (t) => target + calcDelta(t);
29
+ const applyFriction = (t) => {
30
+ const delta = calcDelta(t);
31
+ const latest = calcLatest(t);
32
+ state.done = Math.abs(delta) <= restDelta;
33
+ state.value = state.done ? target : latest;
34
+ };
35
+ /**
36
+ * Ideally this would resolve for t in a stateless way, we could
37
+ * do that by always precalculating the animation but as we know
38
+ * this will be done anyway we can assume that spring will
39
+ * be discovered during that.
40
+ */
41
+ let timeReachedBoundary;
42
+ let spring$1;
43
+ const checkCatchBoundary = (t) => {
44
+ if (!isOutOfBounds(state.value))
45
+ return;
46
+ timeReachedBoundary = t;
47
+ spring$1 = spring({
48
+ keyframes: [state.value, nearestBoundary(state.value)],
49
+ velocity: calcGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000
50
+ damping: bounceDamping,
51
+ stiffness: bounceStiffness,
52
+ restDelta,
53
+ restSpeed,
54
+ });
55
+ };
56
+ checkCatchBoundary(0);
57
+ return {
58
+ calculatedDuration: null,
59
+ next: (t) => {
60
+ /**
61
+ * We need to resolve the friction to figure out if we need a
62
+ * spring but we don't want to do this twice per frame. So here
63
+ * we flag if we updated for this frame and later if we did
64
+ * we can skip doing it again.
65
+ */
66
+ let hasUpdatedFrame = false;
67
+ if (!spring$1 && timeReachedBoundary === undefined) {
68
+ hasUpdatedFrame = true;
69
+ applyFriction(t);
70
+ checkCatchBoundary(t);
71
+ }
72
+ /**
73
+ * If we have a spring and the provided t is beyond the moment the friction
74
+ * animation crossed the min/max boundary, use the spring.
75
+ */
76
+ if (timeReachedBoundary !== undefined && t >= timeReachedBoundary) {
77
+ return spring$1.next(t - timeReachedBoundary);
78
+ }
79
+ else {
80
+ !hasUpdatedFrame && applyFriction(t);
81
+ return state;
82
+ }
83
+ },
84
+ };
85
+ }
86
+
87
+ export { inertia };
@@ -0,0 +1,49 @@
1
+ import { easeInOut, isEasingArray, easingDefinitionToFunction } from 'motion-utils';
2
+ import { interpolate } from '../../utils/interpolate.mjs';
3
+ import { defaultOffset } from '../keyframes/offsets/default.mjs';
4
+ import { convertOffsetToTimes } from '../keyframes/offsets/time.mjs';
5
+
6
+ function defaultEasing(values, easing) {
7
+ return values.map(() => easing || easeInOut).splice(0, values.length - 1);
8
+ }
9
+ function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "easeInOut", }) {
10
+ /**
11
+ * Easing functions can be externally defined as strings. Here we convert them
12
+ * into actual functions.
13
+ */
14
+ const easingFunctions = isEasingArray(ease)
15
+ ? ease.map(easingDefinitionToFunction)
16
+ : easingDefinitionToFunction(ease);
17
+ /**
18
+ * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
19
+ * to reduce GC during animation.
20
+ */
21
+ const state = {
22
+ done: false,
23
+ value: keyframeValues[0],
24
+ };
25
+ /**
26
+ * Create a times array based on the provided 0-1 offsets
27
+ */
28
+ const absoluteTimes = convertOffsetToTimes(
29
+ // Only use the provided offsets if they're the correct length
30
+ // TODO Maybe we should warn here if there's a length mismatch
31
+ times && times.length === keyframeValues.length
32
+ ? times
33
+ : defaultOffset(keyframeValues), duration);
34
+ const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {
35
+ ease: Array.isArray(easingFunctions)
36
+ ? easingFunctions
37
+ : defaultEasing(keyframeValues, easingFunctions),
38
+ });
39
+ return {
40
+ calculatedDuration: duration,
41
+ next: (t) => {
42
+ state.value = mapTimeToKeyframe(t);
43
+ state.done = t >= duration;
44
+ return state;
45
+ },
46
+ };
47
+ }
48
+
49
+ export { defaultEasing, keyframes };
@@ -0,0 +1,27 @@
1
+ const springDefaults = {
2
+ // Default spring physics
3
+ stiffness: 100,
4
+ damping: 10,
5
+ mass: 1.0,
6
+ velocity: 0.0,
7
+ // Default duration/bounce-based options
8
+ duration: 800, // in ms
9
+ bounce: 0.3,
10
+ visualDuration: 0.3, // in seconds
11
+ // Rest thresholds
12
+ restSpeed: {
13
+ granular: 0.01,
14
+ default: 2,
15
+ },
16
+ restDelta: {
17
+ granular: 0.005,
18
+ default: 0.5,
19
+ },
20
+ // Limits
21
+ minDuration: 0.01, // in seconds
22
+ maxDuration: 10.0, // in seconds
23
+ minDamping: 0.05,
24
+ maxDamping: 1,
25
+ };
26
+
27
+ export { springDefaults };
@@ -0,0 +1,84 @@
1
+ import { warning, secondsToMilliseconds, clamp, millisecondsToSeconds } from 'motion-utils';
2
+ import { springDefaults } from './defaults.mjs';
3
+
4
+ const safeMin = 0.001;
5
+ function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass, }) {
6
+ let envelope;
7
+ let derivative;
8
+ warning(duration <= secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less");
9
+ let dampingRatio = 1 - bounce;
10
+ /**
11
+ * Restrict dampingRatio and duration to within acceptable ranges.
12
+ */
13
+ dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);
14
+ duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));
15
+ if (dampingRatio < 1) {
16
+ /**
17
+ * Underdamped spring
18
+ */
19
+ envelope = (undampedFreq) => {
20
+ const exponentialDecay = undampedFreq * dampingRatio;
21
+ const delta = exponentialDecay * duration;
22
+ const a = exponentialDecay - velocity;
23
+ const b = calcAngularFreq(undampedFreq, dampingRatio);
24
+ const c = Math.exp(-delta);
25
+ return safeMin - (a / b) * c;
26
+ };
27
+ derivative = (undampedFreq) => {
28
+ const exponentialDecay = undampedFreq * dampingRatio;
29
+ const delta = exponentialDecay * duration;
30
+ const d = delta * velocity + velocity;
31
+ const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
32
+ const f = Math.exp(-delta);
33
+ const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
34
+ const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
35
+ return (factor * ((d - e) * f)) / g;
36
+ };
37
+ }
38
+ else {
39
+ /**
40
+ * Critically-damped spring
41
+ */
42
+ envelope = (undampedFreq) => {
43
+ const a = Math.exp(-undampedFreq * duration);
44
+ const b = (undampedFreq - velocity) * duration + 1;
45
+ return -safeMin + a * b;
46
+ };
47
+ derivative = (undampedFreq) => {
48
+ const a = Math.exp(-undampedFreq * duration);
49
+ const b = (velocity - undampedFreq) * (duration * duration);
50
+ return a * b;
51
+ };
52
+ }
53
+ const initialGuess = 5 / duration;
54
+ const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
55
+ duration = secondsToMilliseconds(duration);
56
+ if (isNaN(undampedFreq)) {
57
+ return {
58
+ stiffness: springDefaults.stiffness,
59
+ damping: springDefaults.damping,
60
+ duration,
61
+ };
62
+ }
63
+ else {
64
+ const stiffness = Math.pow(undampedFreq, 2) * mass;
65
+ return {
66
+ stiffness,
67
+ damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
68
+ duration,
69
+ };
70
+ }
71
+ }
72
+ const rootIterations = 12;
73
+ function approximateRoot(envelope, derivative, initialGuess) {
74
+ let result = initialGuess;
75
+ for (let i = 1; i < rootIterations; i++) {
76
+ result = result - envelope(result) / derivative(result);
77
+ }
78
+ return result;
79
+ }
80
+ function calcAngularFreq(undampedFreq, dampingRatio) {
81
+ return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
82
+ }
83
+
84
+ export { calcAngularFreq, findSpring };