motion-dom 12.4.11 → 12.6.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.
@@ -0,0 +1,311 @@
1
+ import { warnOnce, SubscriptionManager, velocityPerSecond } from 'motion-utils';
2
+ import { frame } from '../frameloop/frame.mjs';
3
+ import { time } from '../frameloop/sync-time.mjs';
4
+
5
+ /**
6
+ * Maximum time between the value of two frames, beyond which we
7
+ * assume the velocity has since been 0.
8
+ */
9
+ const MAX_VELOCITY_DELTA = 30;
10
+ const isFloat = (value) => {
11
+ return !isNaN(parseFloat(value));
12
+ };
13
+ const collectMotionValues = {
14
+ current: undefined,
15
+ };
16
+ /**
17
+ * `MotionValue` is used to track the state and velocity of motion values.
18
+ *
19
+ * @public
20
+ */
21
+ class MotionValue {
22
+ /**
23
+ * @param init - The initiating value
24
+ * @param config - Optional configuration options
25
+ *
26
+ * - `transformer`: A function to transform incoming values with.
27
+ */
28
+ constructor(init, options = {}) {
29
+ /**
30
+ * This will be replaced by the build step with the latest version number.
31
+ * When MotionValues are provided to motion components, warn if versions are mixed.
32
+ */
33
+ this.version = "12.6.0";
34
+ /**
35
+ * Tracks whether this value can output a velocity. Currently this is only true
36
+ * if the value is numerical, but we might be able to widen the scope here and support
37
+ * other value types.
38
+ *
39
+ * @internal
40
+ */
41
+ this.canTrackVelocity = null;
42
+ /**
43
+ * An object containing a SubscriptionManager for each active event.
44
+ */
45
+ this.events = {};
46
+ this.updateAndNotify = (v, render = true) => {
47
+ const currentTime = time.now();
48
+ /**
49
+ * If we're updating the value during another frame or eventloop
50
+ * than the previous frame, then the we set the previous frame value
51
+ * to current.
52
+ */
53
+ if (this.updatedAt !== currentTime) {
54
+ this.setPrevFrameValue();
55
+ }
56
+ this.prev = this.current;
57
+ this.setCurrent(v);
58
+ // Update update subscribers
59
+ if (this.current !== this.prev && this.events.change) {
60
+ this.events.change.notify(this.current);
61
+ }
62
+ // Update render subscribers
63
+ if (render && this.events.renderRequest) {
64
+ this.events.renderRequest.notify(this.current);
65
+ }
66
+ };
67
+ this.hasAnimated = false;
68
+ this.setCurrent(init);
69
+ this.owner = options.owner;
70
+ }
71
+ setCurrent(current) {
72
+ this.current = current;
73
+ this.updatedAt = time.now();
74
+ if (this.canTrackVelocity === null && current !== undefined) {
75
+ this.canTrackVelocity = isFloat(this.current);
76
+ }
77
+ }
78
+ setPrevFrameValue(prevFrameValue = this.current) {
79
+ this.prevFrameValue = prevFrameValue;
80
+ this.prevUpdatedAt = this.updatedAt;
81
+ }
82
+ /**
83
+ * Adds a function that will be notified when the `MotionValue` is updated.
84
+ *
85
+ * It returns a function that, when called, will cancel the subscription.
86
+ *
87
+ * When calling `onChange` inside a React component, it should be wrapped with the
88
+ * `useEffect` hook. As it returns an unsubscribe function, this should be returned
89
+ * from the `useEffect` function to ensure you don't add duplicate subscribers..
90
+ *
91
+ * ```jsx
92
+ * export const MyComponent = () => {
93
+ * const x = useMotionValue(0)
94
+ * const y = useMotionValue(0)
95
+ * const opacity = useMotionValue(1)
96
+ *
97
+ * useEffect(() => {
98
+ * function updateOpacity() {
99
+ * const maxXY = Math.max(x.get(), y.get())
100
+ * const newOpacity = transform(maxXY, [0, 100], [1, 0])
101
+ * opacity.set(newOpacity)
102
+ * }
103
+ *
104
+ * const unsubscribeX = x.on("change", updateOpacity)
105
+ * const unsubscribeY = y.on("change", updateOpacity)
106
+ *
107
+ * return () => {
108
+ * unsubscribeX()
109
+ * unsubscribeY()
110
+ * }
111
+ * }, [])
112
+ *
113
+ * return <motion.div style={{ x }} />
114
+ * }
115
+ * ```
116
+ *
117
+ * @param subscriber - A function that receives the latest value.
118
+ * @returns A function that, when called, will cancel this subscription.
119
+ *
120
+ * @deprecated
121
+ */
122
+ onChange(subscription) {
123
+ if (process.env.NODE_ENV !== "production") {
124
+ warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
125
+ }
126
+ return this.on("change", subscription);
127
+ }
128
+ on(eventName, callback) {
129
+ if (!this.events[eventName]) {
130
+ this.events[eventName] = new SubscriptionManager();
131
+ }
132
+ const unsubscribe = this.events[eventName].add(callback);
133
+ if (eventName === "change") {
134
+ return () => {
135
+ unsubscribe();
136
+ /**
137
+ * If we have no more change listeners by the start
138
+ * of the next frame, stop active animations.
139
+ */
140
+ frame.read(() => {
141
+ if (!this.events.change.getSize()) {
142
+ this.stop();
143
+ }
144
+ });
145
+ };
146
+ }
147
+ return unsubscribe;
148
+ }
149
+ clearListeners() {
150
+ for (const eventManagers in this.events) {
151
+ this.events[eventManagers].clear();
152
+ }
153
+ }
154
+ /**
155
+ * Attaches a passive effect to the `MotionValue`.
156
+ */
157
+ attach(passiveEffect, stopPassiveEffect) {
158
+ this.passiveEffect = passiveEffect;
159
+ this.stopPassiveEffect = stopPassiveEffect;
160
+ }
161
+ /**
162
+ * Sets the state of the `MotionValue`.
163
+ *
164
+ * @remarks
165
+ *
166
+ * ```jsx
167
+ * const x = useMotionValue(0)
168
+ * x.set(10)
169
+ * ```
170
+ *
171
+ * @param latest - Latest value to set.
172
+ * @param render - Whether to notify render subscribers. Defaults to `true`
173
+ *
174
+ * @public
175
+ */
176
+ set(v, render = true) {
177
+ if (!render || !this.passiveEffect) {
178
+ this.updateAndNotify(v, render);
179
+ }
180
+ else {
181
+ this.passiveEffect(v, this.updateAndNotify);
182
+ }
183
+ }
184
+ setWithVelocity(prev, current, delta) {
185
+ this.set(current);
186
+ this.prev = undefined;
187
+ this.prevFrameValue = prev;
188
+ this.prevUpdatedAt = this.updatedAt - delta;
189
+ }
190
+ /**
191
+ * Set the state of the `MotionValue`, stopping any active animations,
192
+ * effects, and resets velocity to `0`.
193
+ */
194
+ jump(v, endAnimation = true) {
195
+ this.updateAndNotify(v);
196
+ this.prev = v;
197
+ this.prevUpdatedAt = this.prevFrameValue = undefined;
198
+ endAnimation && this.stop();
199
+ if (this.stopPassiveEffect)
200
+ this.stopPassiveEffect();
201
+ }
202
+ /**
203
+ * Returns the latest state of `MotionValue`
204
+ *
205
+ * @returns - The latest state of `MotionValue`
206
+ *
207
+ * @public
208
+ */
209
+ get() {
210
+ if (collectMotionValues.current) {
211
+ collectMotionValues.current.push(this);
212
+ }
213
+ return this.current;
214
+ }
215
+ /**
216
+ * @public
217
+ */
218
+ getPrevious() {
219
+ return this.prev;
220
+ }
221
+ /**
222
+ * Returns the latest velocity of `MotionValue`
223
+ *
224
+ * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
225
+ *
226
+ * @public
227
+ */
228
+ getVelocity() {
229
+ const currentTime = time.now();
230
+ if (!this.canTrackVelocity ||
231
+ this.prevFrameValue === undefined ||
232
+ currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
233
+ return 0;
234
+ }
235
+ const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
236
+ // Casts because of parseFloat's poor typing
237
+ return velocityPerSecond(parseFloat(this.current) -
238
+ parseFloat(this.prevFrameValue), delta);
239
+ }
240
+ /**
241
+ * Registers a new animation to control this `MotionValue`. Only one
242
+ * animation can drive a `MotionValue` at one time.
243
+ *
244
+ * ```jsx
245
+ * value.start()
246
+ * ```
247
+ *
248
+ * @param animation - A function that starts the provided animation
249
+ */
250
+ start(startAnimation) {
251
+ this.stop();
252
+ return new Promise((resolve) => {
253
+ this.hasAnimated = true;
254
+ this.animation = startAnimation(resolve);
255
+ if (this.events.animationStart) {
256
+ this.events.animationStart.notify();
257
+ }
258
+ }).then(() => {
259
+ if (this.events.animationComplete) {
260
+ this.events.animationComplete.notify();
261
+ }
262
+ this.clearAnimation();
263
+ });
264
+ }
265
+ /**
266
+ * Stop the currently active animation.
267
+ *
268
+ * @public
269
+ */
270
+ stop() {
271
+ if (this.animation) {
272
+ this.animation.stop();
273
+ if (this.events.animationCancel) {
274
+ this.events.animationCancel.notify();
275
+ }
276
+ }
277
+ this.clearAnimation();
278
+ }
279
+ /**
280
+ * Returns `true` if this value is currently animating.
281
+ *
282
+ * @public
283
+ */
284
+ isAnimating() {
285
+ return !!this.animation;
286
+ }
287
+ clearAnimation() {
288
+ delete this.animation;
289
+ }
290
+ /**
291
+ * Destroy and clean up subscribers to this `MotionValue`.
292
+ *
293
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
294
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
295
+ * created a `MotionValue` via the `motionValue` function.
296
+ *
297
+ * @public
298
+ */
299
+ destroy() {
300
+ this.clearListeners();
301
+ this.stop();
302
+ if (this.stopPassiveEffect) {
303
+ this.stopPassiveEffect();
304
+ }
305
+ }
306
+ }
307
+ function motionValue(init, options) {
308
+ return new MotionValue(init, options);
309
+ }
310
+
311
+ export { MotionValue, collectMotionValues, motionValue };
@@ -1,12 +1,6 @@
1
1
  import { noop } from 'motion-utils';
2
- import { startViewAnimation } from './start.mjs';
2
+ import { addToQueue } from './queue.mjs';
3
3
 
4
- /**
5
- * TODO:
6
- * - Create view transition on next tick
7
- * - Replace animations with Motion animations
8
- * - Return GroupAnimation on next tick
9
- */
10
4
  class ViewTransitionBuilder {
11
5
  constructor(update, options = {}) {
12
6
  this.currentTarget = "root";
@@ -15,9 +9,12 @@ class ViewTransitionBuilder {
15
9
  this.readyPromise = new Promise((resolve) => {
16
10
  this.notifyReady = resolve;
17
11
  });
18
- queueMicrotask(() => {
19
- startViewAnimation(update, options, this.targets).then((animation) => this.notifyReady(animation));
20
- });
12
+ this.update = update;
13
+ this.options = {
14
+ interrupt: "wait",
15
+ ...options,
16
+ };
17
+ addToQueue(this);
21
18
  }
22
19
  get(selector) {
23
20
  this.currentTarget = selector;
@@ -60,8 +57,8 @@ class ViewTransitionBuilder {
60
57
  return this.readyPromise.then(resolve, reject);
61
58
  }
62
59
  }
63
- function view(update, defaultOptions = {}) {
60
+ function animateView(update, defaultOptions = {}) {
64
61
  return new ViewTransitionBuilder(update, defaultOptions);
65
62
  }
66
63
 
67
- export { ViewTransitionBuilder, view };
64
+ export { ViewTransitionBuilder, animateView };
@@ -0,0 +1,53 @@
1
+ import { removeItem } from 'motion-utils';
2
+ import { microtask } from '../frameloop/microtask.mjs';
3
+ import { startViewAnimation } from './start.mjs';
4
+
5
+ let builders = [];
6
+ let current = null;
7
+ function next() {
8
+ current = null;
9
+ const [nextBuilder] = builders;
10
+ if (nextBuilder)
11
+ start(nextBuilder);
12
+ }
13
+ function start(builder) {
14
+ removeItem(builders, builder);
15
+ current = builder;
16
+ startViewAnimation(builder).then((animation) => {
17
+ builder.notifyReady(animation);
18
+ animation.finished.finally(next);
19
+ });
20
+ }
21
+ function processQueue() {
22
+ var _a;
23
+ /**
24
+ * Iterate backwards over the builders array. We can ignore the
25
+ * "wait" animations. If we have an interrupting animation in the
26
+ * queue then we need to batch all preceeding animations into it.
27
+ * Currently this only batches the update functions but will also
28
+ * need to batch the targets.
29
+ */
30
+ for (let i = builders.length - 1; i >= 0; i--) {
31
+ const builder = builders[i];
32
+ const { interrupt } = builder.options;
33
+ if (interrupt === "immediate") {
34
+ const batchedUpdates = builders.slice(0, i + 1).map((b) => b.update);
35
+ const remaining = builders.slice(i + 1);
36
+ builder.update = () => {
37
+ batchedUpdates.forEach((update) => update());
38
+ };
39
+ // Put the current builder at the front, followed by any "wait" builders
40
+ builders = [builder, ...remaining];
41
+ break;
42
+ }
43
+ }
44
+ if (!current || ((_a = builders[0]) === null || _a === void 0 ? void 0 : _a.options.interrupt) === "immediate") {
45
+ next();
46
+ }
47
+ }
48
+ function addToQueue(builder) {
49
+ builders.push(builder);
50
+ microtask.render(processQueue);
51
+ }
52
+
53
+ export { addToQueue };
@@ -12,7 +12,8 @@ import { getViewAnimations } from './utils/get-view-animations.mjs';
12
12
  import { hasTarget } from './utils/has-target.mjs';
13
13
 
14
14
  const definitionNames = ["layout", "enter", "exit", "new", "old"];
15
- function startViewAnimation(update, defaultOptions, targets) {
15
+ function startViewAnimation(builder) {
16
+ const { update, targets, options: defaultOptions } = builder;
16
17
  if (!document.startViewTransition) {
17
18
  return new Promise(async (resolve) => {
18
19
  await update();