@krate/motion 0.0.0-stage → 0.5.0-rc.17

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,852 @@
1
+ // Animation drivers. A JSAnimation samples a generator on the frame loop and
2
+ // writes the motion value every frame; a NativeAnimation runs opacity,
3
+ // transform, filter and clip-path on the compositor through the Web
4
+ // Animations API (springs become a linear() easing). animateMotionValue
5
+ // picks one for a value from its transition. Ported from motion-dom and
6
+ // framer-motion (MIT, Copyright (c) 2018 Framer B.V.), see NOTICE.
7
+
8
+ import { backInOut, circInOut, anticipate, isBezierDefinition, type Easing } from './easing.js';
9
+ import { cancelFrame, frame, frameData, time } from './frameloop.js';
10
+ import {
11
+ calcGeneratorDuration,
12
+ generateLinearEasing,
13
+ inertia,
14
+ isGenerator,
15
+ keyframes as keyframesGenerator,
16
+ replaceTransitionType,
17
+ type GeneratorFactory,
18
+ type KeyframeGenerator,
19
+ } from './generators.js';
20
+ import type { AnimationPlaybackControls, MotionValue } from './motion-value.js';
21
+ import { camelToDash, isCSSVar, positionalKeys, setStyle, transformProps } from './render.js';
22
+ import { analyseComplexValue, complex, findDimensionValueType, getAnimatableNone, mix, number, px } from './values.js';
23
+ import { clamp, isNumericalString, isZeroValueString, memo, millisecondsToSeconds, MotionGlobalConfig, noop, pipe, secondsToMilliseconds, warnOnce } from './utils.js';
24
+
25
+ export type AnimationGeneratorType = GeneratorFactory | 'decay' | 'spring' | 'keyframes' | 'tween' | 'inertia';
26
+
27
+ export interface Transition {
28
+ type?: AnimationGeneratorType | false;
29
+ duration?: number;
30
+ delay?: number;
31
+ ease?: any;
32
+ times?: number[];
33
+ repeat?: number;
34
+ repeatType?: 'loop' | 'reverse' | 'mirror';
35
+ repeatDelay?: number;
36
+ stiffness?: number;
37
+ damping?: number;
38
+ mass?: number;
39
+ bounce?: number;
40
+ visualDuration?: number;
41
+ restDelta?: number;
42
+ restSpeed?: number;
43
+ velocity?: number;
44
+ power?: number;
45
+ timeConstant?: number;
46
+ bounceDamping?: number;
47
+ bounceStiffness?: number;
48
+ modifyTarget?: (v: number) => number;
49
+ min?: number;
50
+ max?: number;
51
+ from?: any;
52
+ when?: false | 'beforeChildren' | 'afterChildren';
53
+ delayChildren?: number | ((i: number, total: number) => number);
54
+ staggerChildren?: number;
55
+ staggerDirection?: number;
56
+ elapsed?: number;
57
+ inherit?: boolean;
58
+ onUpdate?: (v: any) => void;
59
+ onComplete?: () => void;
60
+ onPlay?: () => void;
61
+ onStop?: () => void;
62
+ default?: Transition;
63
+ [key: string]: any;
64
+ }
65
+
66
+ export interface AnimationOptions extends Transition {
67
+ keyframes: any[];
68
+ name?: string;
69
+ motionValue?: MotionValue;
70
+ element?: any;
71
+ autoplay?: boolean;
72
+ startTime?: number;
73
+ finalKeyframe?: any;
74
+ driver?: Driver;
75
+ isSync?: boolean;
76
+ allowFlatten?: boolean;
77
+ onCancel?: () => void;
78
+ }
79
+
80
+ export interface Driver {
81
+ start(keepAlive?: boolean): void;
82
+ stop(): void;
83
+ now(): number;
84
+ }
85
+
86
+ export const frameloopDriver = (update: (t: number) => void): Driver => {
87
+ const pass = ({ timestamp }: { timestamp: number }): void => update(timestamp);
88
+ return {
89
+ start: (keepAlive = true) => {
90
+ frame.update(pass, keepAlive);
91
+ },
92
+ stop: () => cancelFrame(pass),
93
+ now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),
94
+ };
95
+ };
96
+
97
+ class WithPromise {
98
+ protected _finished!: Promise<void>;
99
+ protected resolve!: () => void;
100
+ constructor() {
101
+ this.updateFinished();
102
+ }
103
+ get finished(): Promise<void> {
104
+ return this._finished;
105
+ }
106
+ updateFinished(): void {
107
+ this._finished = new Promise((r) => {
108
+ this.resolve = r;
109
+ });
110
+ }
111
+ notifyFinished(): void {
112
+ this.resolve();
113
+ }
114
+ then(onResolve: () => void, onReject?: () => void): Promise<void> {
115
+ return this.finished.then(onResolve, onReject);
116
+ }
117
+ }
118
+
119
+ const isNotNull = (v: unknown): boolean => v !== null;
120
+
121
+ export function getFinalKeyframe(frames: any[], { repeat, repeatType = 'loop' }: Transition, finalKeyframe?: any, speed = 1): any {
122
+ const resolved = frames.filter(isNotNull);
123
+ const useFirst = speed < 0 || (repeat && repeatType !== 'loop' && repeat % 2 === 1);
124
+ const index = useFirst ? 0 : resolved.length - 1;
125
+ return !index || finalKeyframe === undefined ? resolved[index] : finalKeyframe;
126
+ }
127
+
128
+ /** Drives a generator on the frame loop with full playback controls. */
129
+ export class JSAnimation extends WithPromise implements AnimationPlaybackControls {
130
+ state = 'idle';
131
+ startTime: number | null = null;
132
+ isStopped = false;
133
+ currentTime = 0;
134
+ holdTime: number | null = null;
135
+ playbackSpeed = 1;
136
+ options: AnimationOptions;
137
+ driver?: Driver;
138
+ generator!: KeyframeGenerator<any>;
139
+ mirroredGenerator?: KeyframeGenerator<any>;
140
+ mixKeyframes?: (v: number) => any;
141
+ calculatedDuration!: number;
142
+ resolvedDuration!: number;
143
+ totalDuration!: number;
144
+
145
+ constructor(options: AnimationOptions) {
146
+ super();
147
+ this.options = options;
148
+ this.initAnimation();
149
+ this.play();
150
+ if (options.autoplay === false) this.pause();
151
+ }
152
+
153
+ stop = (): void => {
154
+ const { motionValue } = this.options;
155
+ if (motionValue && motionValue.updatedAt !== time.now()) this.tick(time.now());
156
+ this.isStopped = true;
157
+ if (this.state === 'idle') return;
158
+ this.teardown();
159
+ this.options.onStop?.();
160
+ };
161
+
162
+ initAnimation(): void {
163
+ const { options } = this;
164
+ replaceTransitionType(options);
165
+ const { type = keyframesGenerator, repeat = 0, repeatDelay = 0, repeatType, velocity = 0 } = options as any;
166
+ let { keyframes } = options;
167
+ const factory: GeneratorFactory = type || keyframesGenerator;
168
+ if (factory !== keyframesGenerator && typeof keyframes[0] !== 'number') {
169
+ this.mixKeyframes = pipe((p: number) => p / 100, mix(keyframes[0], keyframes[1]));
170
+ keyframes = [0, 100];
171
+ }
172
+ const generator = factory({ ...options, keyframes });
173
+ if (repeatType === 'mirror') {
174
+ this.mirroredGenerator = factory({ ...options, keyframes: [...keyframes].reverse(), velocity: -velocity });
175
+ }
176
+ if (generator.calculatedDuration === null) generator.calculatedDuration = calcGeneratorDuration(generator);
177
+ const { calculatedDuration } = generator;
178
+ this.calculatedDuration = calculatedDuration as number;
179
+ this.resolvedDuration = this.calculatedDuration + repeatDelay;
180
+ this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay;
181
+ this.generator = generator;
182
+ }
183
+
184
+ updateTime(timestamp: number): void {
185
+ const t = Math.round(timestamp - (this.startTime as number)) * this.playbackSpeed;
186
+ this.currentTime = this.holdTime !== null ? this.holdTime : t;
187
+ }
188
+
189
+ tick(timestamp: number, sample = false): { done: boolean; value: any } {
190
+ const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration } = this;
191
+ if (this.startTime === null) return generator.next(0);
192
+ const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe } = this.options;
193
+ if (this.speed > 0) this.startTime = Math.min(this.startTime, timestamp);
194
+ else if (this.speed < 0) this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
195
+ if (sample) this.currentTime = timestamp;
196
+ else this.updateTime(timestamp);
197
+ const withoutDelay = this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1);
198
+ const inDelay = this.playbackSpeed >= 0 ? withoutDelay < 0 : withoutDelay > totalDuration;
199
+ this.currentTime = Math.max(withoutDelay, 0);
200
+ if (this.state === 'finished' && this.holdTime === null) this.currentTime = totalDuration;
201
+ let elapsed = this.currentTime;
202
+ let gen = generator;
203
+ if (repeat) {
204
+ const p = Math.min(this.currentTime, totalDuration) / resolvedDuration;
205
+ let iteration = Math.floor(p);
206
+ let iterProgress = p % 1;
207
+ if (!iterProgress && p >= 1) iterProgress = 1;
208
+ if (iterProgress === 1) iteration--;
209
+ iteration = Math.min(iteration, repeat + 1);
210
+ if (iteration % 2) {
211
+ if (repeatType === 'reverse') {
212
+ iterProgress = 1 - iterProgress;
213
+ if (repeatDelay) iterProgress -= repeatDelay / resolvedDuration;
214
+ } else if (repeatType === 'mirror') {
215
+ gen = mirroredGenerator!;
216
+ }
217
+ }
218
+ elapsed = clamp(0, 1, iterProgress) * resolvedDuration;
219
+ }
220
+ const state = inDelay ? { done: false, value: keyframes[0] } : gen.next(elapsed);
221
+ if (mixKeyframes) state.value = mixKeyframes(state.value);
222
+ let { done } = state;
223
+ if (!inDelay && calculatedDuration !== null) {
224
+ done = this.playbackSpeed >= 0 ? this.currentTime >= totalDuration : this.currentTime <= 0;
225
+ }
226
+ const finished = this.holdTime === null && (this.state === 'finished' || (this.state === 'running' && done));
227
+ if (finished && type !== inertia) state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
228
+ if (onUpdate) onUpdate(state.value);
229
+ if (finished) this.finish();
230
+ return state;
231
+ }
232
+
233
+ get duration(): number {
234
+ return millisecondsToSeconds(this.calculatedDuration);
235
+ }
236
+ get iterationDuration(): number {
237
+ return this.duration + millisecondsToSeconds(this.options.delay || 0);
238
+ }
239
+ get time(): number {
240
+ return millisecondsToSeconds(this.currentTime);
241
+ }
242
+ set time(t: number) {
243
+ t = secondsToMilliseconds(t);
244
+ this.currentTime = t;
245
+ if (this.startTime === null || this.holdTime !== null || this.playbackSpeed === 0) this.holdTime = t;
246
+ else if (this.driver) this.startTime = this.driver.now() - t / this.playbackSpeed;
247
+ this.driver?.start(false);
248
+ }
249
+ get speed(): number {
250
+ return this.playbackSpeed;
251
+ }
252
+ set speed(s: number) {
253
+ this.updateTime(time.now());
254
+ const changed = this.playbackSpeed !== s;
255
+ this.playbackSpeed = s;
256
+ if (changed) this.time = millisecondsToSeconds(this.currentTime);
257
+ }
258
+
259
+ play(): void {
260
+ if (this.isStopped) return;
261
+ const { driver = frameloopDriver, startTime } = this.options as any;
262
+ if (!this.driver) this.driver = driver((t: number) => this.tick(t));
263
+ this.options.onPlay?.();
264
+ const now = this.driver!.now();
265
+ if (this.state === 'finished') {
266
+ this.updateFinished();
267
+ this.startTime = now;
268
+ } else if (this.holdTime !== null) {
269
+ this.startTime = now - this.holdTime;
270
+ } else if (!this.startTime) {
271
+ this.startTime = startTime ?? now;
272
+ }
273
+ if (this.state === 'finished' && this.speed < 0) (this.startTime as number) += this.calculatedDuration;
274
+ this.holdTime = null;
275
+ this.state = 'running';
276
+ this.driver!.start();
277
+ }
278
+
279
+ pause(): void {
280
+ this.state = 'paused';
281
+ this.updateTime(time.now());
282
+ this.holdTime = this.currentTime;
283
+ }
284
+
285
+ complete(): void {
286
+ if (this.state !== 'running') this.play();
287
+ this.state = 'finished';
288
+ this.holdTime = null;
289
+ }
290
+
291
+ finish(): void {
292
+ this.notifyFinished();
293
+ this.teardown();
294
+ this.state = 'finished';
295
+ this.options.onComplete?.();
296
+ }
297
+
298
+ cancel(): void {
299
+ this.holdTime = null;
300
+ this.startTime = 0;
301
+ this.tick(0);
302
+ this.teardown();
303
+ this.options.onCancel?.();
304
+ }
305
+
306
+ teardown(): void {
307
+ this.state = 'idle';
308
+ if (this.driver) {
309
+ this.driver.stop();
310
+ this.driver = undefined;
311
+ }
312
+ this.startTime = this.holdTime = null;
313
+ }
314
+
315
+ sample(t: number): { done: boolean; value: any } {
316
+ this.startTime = 0;
317
+ return this.tick(t, true);
318
+ }
319
+
320
+ attachTimeline(timeline: { observe: (a: any) => () => void }): () => void {
321
+ if (this.options.allowFlatten) {
322
+ this.options.type = 'keyframes';
323
+ this.options.ease = 'linear';
324
+ this.initAnimation();
325
+ }
326
+ this.driver?.stop();
327
+ return timeline.observe(this);
328
+ }
329
+ }
330
+
331
+ /** Animates a plain value (legacy `animateValue`). */
332
+ export function animateValue(options: AnimationOptions): JSAnimation {
333
+ return new JSAnimation(options);
334
+ }
335
+
336
+ // WAAPI
337
+
338
+ export const supportsWaapi = (): boolean => typeof Element !== 'undefined' && Object.hasOwnProperty.call(Element.prototype, 'animate');
339
+
340
+ export const supportsLinearEasing = memo(() => {
341
+ try {
342
+ document.createElement('div').animate({ opacity: 0 }, { easing: 'linear(0, 1)' });
343
+ } catch {
344
+ return false;
345
+ }
346
+ return true;
347
+ });
348
+
349
+ export const supportsScrollTimeline = memo(() => typeof window !== 'undefined' && (window as any).ScrollTimeline !== undefined);
350
+
351
+ const cubicBezierAsString = ([a, b, c, d]: readonly number[]): string => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
352
+
353
+ const supportedWaapiEasing: Record<string, string> = {
354
+ linear: 'linear',
355
+ ease: 'ease',
356
+ easeIn: 'ease-in',
357
+ easeOut: 'ease-out',
358
+ easeInOut: 'ease-in-out',
359
+ circIn: cubicBezierAsString([0, 0.65, 0.55, 1]),
360
+ circOut: cubicBezierAsString([0.55, 0, 1, 0.45]),
361
+ backIn: cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),
362
+ backOut: cubicBezierAsString([0.33, 1.53, 0.69, 0.99]),
363
+ };
364
+
365
+ export function mapEasingToNativeEasing(easing: any, duration: number): any {
366
+ if (!easing) return undefined;
367
+ if (typeof easing === 'function') return supportsLinearEasing() ? generateLinearEasing(easing as Easing, duration) : 'ease-out';
368
+ if (isBezierDefinition(easing)) return cubicBezierAsString(easing);
369
+ if (Array.isArray(easing)) return easing.map((e) => mapEasingToNativeEasing(e, duration) || supportedWaapiEasing.easeOut);
370
+ return supportedWaapiEasing[easing];
371
+ }
372
+
373
+ const unsupportedEasing: Record<string, Easing> = { anticipate, backInOut, circInOut };
374
+
375
+ function startWaapiAnimation(el: Element, name: string, frames: any[], { delay = 0, duration = 300, repeat = 0, repeatType = 'loop', ease = 'easeOut', times }: any = {}): Animation {
376
+ const keyframeOptions: Record<string, any> = { [name]: frames };
377
+ if (times) keyframeOptions.offset = times;
378
+ const easing = mapEasingToNativeEasing(ease, duration);
379
+ if (Array.isArray(easing)) keyframeOptions.easing = easing;
380
+ return el.animate(keyframeOptions as any, {
381
+ delay,
382
+ duration,
383
+ easing: !Array.isArray(easing) ? easing : 'linear',
384
+ fill: 'both',
385
+ iterations: repeat + 1,
386
+ direction: repeatType === 'reverse' ? 'alternate' : 'normal',
387
+ });
388
+ }
389
+
390
+ function applyGeneratorOptions({ type, ...options }: any): any {
391
+ if (isGenerator(type) && supportsLinearEasing()) return type.applyToOptions!(options);
392
+ options.duration ??= 300;
393
+ options.ease ??= 'easeOut';
394
+ return options;
395
+ }
396
+
397
+ /** Runs a value on the browser's animation engine (compositor for opacity/transform). */
398
+ export class NativeAnimation extends WithPromise implements AnimationPlaybackControls {
399
+ animation!: Animation;
400
+ finishedTime: number | null = null;
401
+ isStopped = false;
402
+ options!: AnimationOptions;
403
+
404
+ constructor(options: AnimationOptions) {
405
+ super();
406
+ if (typeof options.ease === 'string' && options.ease in unsupportedEasing) options.ease = unsupportedEasing[options.ease];
407
+ replaceTransitionType(options);
408
+ this.options = options;
409
+ const { element, name, keyframes, finalKeyframe, onComplete } = options;
410
+ const transition = applyGeneratorOptions(options);
411
+ this.animation = startWaapiAnimation(element, camelToDash(name!), keyframes, transition);
412
+ if (transition.autoplay === false) this.animation.pause();
413
+ if (options.startTime) this.animation.startTime = options.startTime;
414
+ this.animation.onfinish = () => {
415
+ this.finishedTime = this.time;
416
+ const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
417
+ this.updateMotionValue(keyframe);
418
+ setStyle(element, name!, keyframe);
419
+ this.animation.cancel();
420
+ onComplete?.();
421
+ this.notifyFinished();
422
+ };
423
+ }
424
+
425
+ /** Writes the value back to the motion value; without one, samples the animation for value and velocity. */
426
+ updateMotionValue(value?: any): void {
427
+ const { motionValue, onUpdate: _u, onComplete: _c, element: _e, ...options } = this.options;
428
+ if (!motionValue) return;
429
+ if (value !== undefined) {
430
+ motionValue.set(value);
431
+ return;
432
+ }
433
+ const sampler = new JSAnimation({ ...options, autoplay: false } as AnimationOptions);
434
+ const t = secondsToMilliseconds(this.finishedTime ?? this.time);
435
+ motionValue.setWithVelocity(sampler.sample(t - 10).value, sampler.sample(t).value, 10);
436
+ sampler.stop();
437
+ }
438
+
439
+ play(): void {
440
+ if (this.isStopped) return;
441
+ this.animation.play();
442
+ if (this.state === 'finished') this.updateFinished();
443
+ }
444
+ pause(): void {
445
+ this.animation.pause();
446
+ }
447
+ complete(): void {
448
+ this.animation.finish?.();
449
+ }
450
+ cancel(): void {
451
+ try {
452
+ this.animation.cancel();
453
+ } catch {}
454
+ }
455
+ stop = (): void => {
456
+ if (this.isStopped) return;
457
+ this.isStopped = true;
458
+ const { state } = this;
459
+ if (state === 'idle' || state === 'finished') return;
460
+ this.updateMotionValue();
461
+ this.cancel();
462
+ };
463
+ get duration(): number {
464
+ const d = this.animation.effect?.getComputedTiming?.().duration || 0;
465
+ return millisecondsToSeconds(Number(d));
466
+ }
467
+ get iterationDuration(): number {
468
+ return this.duration + millisecondsToSeconds(this.options.delay || 0);
469
+ }
470
+ get time(): number {
471
+ return millisecondsToSeconds(Number(this.animation.currentTime) || 0);
472
+ }
473
+ set time(t: number) {
474
+ this.finishedTime = null;
475
+ this.animation.currentTime = secondsToMilliseconds(t);
476
+ }
477
+ get speed(): number {
478
+ return this.animation.playbackRate;
479
+ }
480
+ set speed(s: number) {
481
+ if (s < 0) this.finishedTime = null;
482
+ this.animation.playbackRate = s;
483
+ }
484
+ get state(): string {
485
+ return this.finishedTime !== null ? 'finished' : this.animation.playState;
486
+ }
487
+ get startTime(): number {
488
+ return Number(this.animation.startTime);
489
+ }
490
+ set startTime(t: number) {
491
+ this.animation.startTime = t;
492
+ }
493
+ attachTimeline({ timeline, observe }: { timeline?: any; observe: (a: any) => () => void }): () => void {
494
+ if (this.options.allowFlatten) this.animation.effect?.updateTiming({ easing: 'linear' });
495
+ this.animation.onfinish = null;
496
+ if (timeline && supportsScrollTimeline()) {
497
+ (this.animation as any).timeline = timeline;
498
+ return noop as () => void;
499
+ }
500
+ return observe(this);
501
+ }
502
+ }
503
+
504
+ /** Values the compositor can animate without layout or paint. */
505
+ export const acceleratedValues = new Set(['opacity', 'clipPath', 'filter', 'transform']);
506
+
507
+ export function supportsBrowserAnimation(options: AnimationOptions): boolean {
508
+ const { motionValue, name, repeatDelay, repeatType, damping, type } = options;
509
+ const owner = motionValue?.owner;
510
+ const subject = owner?.current;
511
+ if (typeof HTMLElement === 'undefined' || !(subject instanceof HTMLElement)) return false;
512
+ const props = owner.getProps ? owner.getProps() : {};
513
+ return (
514
+ supportsWaapi() &&
515
+ !!name &&
516
+ acceleratedValues.has(name) &&
517
+ (name !== 'transform' || !props.transformTemplate) &&
518
+ !props.onUpdate &&
519
+ !repeatDelay &&
520
+ repeatType !== 'mirror' &&
521
+ damping !== 0 &&
522
+ type !== 'inertia' &&
523
+ type !== inertia
524
+ );
525
+ }
526
+
527
+ /** A group of animations controlled together (the result of animate() on several values). */
528
+ export class GroupAnimation implements AnimationPlaybackControls {
529
+ animations: AnimationPlaybackControls[];
530
+ constructor(animations: Array<AnimationPlaybackControls | undefined>) {
531
+ this.animations = animations.filter(Boolean) as AnimationPlaybackControls[];
532
+ }
533
+ stop = (): void => this.runAll('stop');
534
+ get finished(): Promise<any> {
535
+ return Promise.all(this.animations.map((a) => a.finished));
536
+ }
537
+ getAll<K extends keyof AnimationPlaybackControls>(k: K): any {
538
+ return this.animations[0]?.[k];
539
+ }
540
+ setAll(k: 'time' | 'speed', v: number): void {
541
+ for (const a of this.animations) a[k] = v;
542
+ }
543
+ attachTimeline(timeline: any): () => void {
544
+ const subs = this.animations.map((a) => a.attachTimeline?.(timeline));
545
+ return () => {
546
+ subs.forEach((cancel, i) => {
547
+ if (cancel) cancel();
548
+ this.animations[i].stop();
549
+ });
550
+ };
551
+ }
552
+ get time(): number {
553
+ return this.getAll('time');
554
+ }
555
+ set time(t: number) {
556
+ this.setAll('time', t);
557
+ }
558
+ get speed(): number {
559
+ return this.getAll('speed');
560
+ }
561
+ set speed(s: number) {
562
+ this.setAll('speed', s);
563
+ }
564
+ get state(): string {
565
+ return this.getAll('state');
566
+ }
567
+ get startTime(): number | null {
568
+ return this.getAll('startTime');
569
+ }
570
+ get duration(): number {
571
+ return getMax(this.animations, 'duration');
572
+ }
573
+ get iterationDuration(): number {
574
+ return getMax(this.animations, 'iterationDuration');
575
+ }
576
+ runAll(m: 'play' | 'pause' | 'cancel' | 'complete' | 'stop'): void {
577
+ for (const a of this.animations) a[m]();
578
+ }
579
+ play(): void {
580
+ this.runAll('play');
581
+ }
582
+ pause(): void {
583
+ this.runAll('pause');
584
+ }
585
+ cancel(): void {
586
+ this.runAll('cancel');
587
+ }
588
+ complete(): void {
589
+ this.runAll('complete');
590
+ }
591
+ then(onResolve: () => void, _onReject?: () => void): Promise<void> {
592
+ return this.finished.finally(onResolve).then(() => {});
593
+ }
594
+ }
595
+
596
+ function getMax(animations: AnimationPlaybackControls[], prop: 'duration' | 'iterationDuration'): number {
597
+ let max = 0;
598
+ for (const a of animations) {
599
+ const v = a[prop];
600
+ if (v !== null && v !== undefined && v > max) max = v;
601
+ }
602
+ return max;
603
+ }
604
+
605
+ // Transition resolution
606
+
607
+ const underDampedSpring: Transition = { type: 'spring', stiffness: 500, damping: 25, restSpeed: 10 };
608
+ const criticallyDampedSpring = (target: unknown): Transition => ({
609
+ type: 'spring',
610
+ stiffness: 550,
611
+ damping: target === 0 ? 2 * Math.sqrt(550) : 30,
612
+ restSpeed: 10,
613
+ });
614
+ const keyframesTransition: Transition = { type: 'keyframes', duration: 0.8 };
615
+ const defaultEase: Transition = { type: 'keyframes', ease: [0.25, 0.1, 0.35, 1], duration: 0.3 };
616
+
617
+ /** Motion's default transition for a value: springs for transforms, a short ease otherwise. */
618
+ export function getDefaultTransition(key: string, { keyframes }: { keyframes: any[] }): Transition {
619
+ if (keyframes.length > 2) return keyframesTransition;
620
+ if (transformProps.has(key)) return key.startsWith('scale') ? criticallyDampedSpring(keyframes[1]) : underDampedSpring;
621
+ return defaultEase;
622
+ }
623
+
624
+ /** True when a transition sets anything besides orchestration options. */
625
+ export function isTransitionDefined({
626
+ when: _w,
627
+ delay: _d,
628
+ delayChildren: _dc,
629
+ staggerChildren: _sc,
630
+ staggerDirection: _sd,
631
+ repeat: _r,
632
+ repeatType: _rt,
633
+ repeatDelay: _rd,
634
+ from: _f,
635
+ elapsed: _e,
636
+ ...rest
637
+ }: Transition): boolean {
638
+ return !!Object.keys(rest).length;
639
+ }
640
+
641
+ export function getValueTransition(transition: any, key: string): Transition {
642
+ return transition?.[key] ?? transition?.['default'] ?? transition;
643
+ }
644
+
645
+ export const isAnimatable = (value: any, name?: string): boolean => {
646
+ if (name === 'zIndex') return false;
647
+ if (typeof value === 'number' || Array.isArray(value)) return true;
648
+ return typeof value === 'string' && (complex.test(value) || value === '0') && !value.startsWith('url(');
649
+ };
650
+
651
+ function canAnimate(frames: any[], name?: string, type?: any, velocity?: number): boolean {
652
+ const origin = frames[0];
653
+ if (origin === null) return false;
654
+ if (name === 'display' || name === 'visibility') return true;
655
+ const target = frames[frames.length - 1];
656
+ const a = isAnimatable(origin, name);
657
+ const b = isAnimatable(target, name);
658
+ warnOnce(a === b, `You are trying to animate ${name} from "${origin}" to "${target}". "${a ? target : origin}" is not an animatable value.`);
659
+ if (!a || !b) return false;
660
+ const changed = frames.length === 1 || frames.some((f) => f !== origin);
661
+ return changed || ((type === 'spring' || isGenerator(type)) && !!velocity);
662
+ }
663
+
664
+ const isNone = (v: any): boolean => (typeof v === 'number' ? v === 0 : v !== null ? v === 'none' || v === '0' || isZeroValueString(v) : true);
665
+ const invalidTemplates = new Set(['auto', 'none', '0']);
666
+
667
+ function makeNoneKeyframesAnimatable(frames: any[], indexes: number[], name?: string): void {
668
+ let template: any;
669
+ for (let i = 0; i < frames.length && !template; i++) {
670
+ const f = frames[i];
671
+ if (typeof f === 'string' && !invalidTemplates.has(f) && analyseComplexValue(f).values.length) template = f;
672
+ }
673
+ if (template && name) for (const i of indexes) frames[i] = getAnimatableNone(name, template);
674
+ }
675
+
676
+ const cssVarRegex = /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;
677
+
678
+ /** Resolves `var(--x, fallback)` against an element's computed style. */
679
+ export function getVariableValue(current: string, el: Element, depth = 1): any {
680
+ if (depth > 4) return undefined;
681
+ const m = cssVarRegex.exec(current);
682
+ if (!m) return undefined;
683
+ const [, t1, t2, fallback] = m;
684
+ const resolved = getComputedStyle(el).getPropertyValue(`--${t1 ?? t2}`);
685
+ if (resolved) {
686
+ const trimmed = resolved.trim();
687
+ return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
688
+ }
689
+ return typeof fallback === 'string' && fallback.startsWith('var(--') ? getVariableValue(fallback, el, depth + 1) : fallback;
690
+ }
691
+
692
+ const isNumOrPx = (t: unknown): boolean => t === number || t === px;
693
+
694
+ // The length a width/height/top/left style must have to render the element
695
+ // as it is now (border-box widths include padding and border).
696
+ function measurePositional(el: HTMLElement, name: string): number {
697
+ const cs = getComputedStyle(el);
698
+ const r = el.getBoundingClientRect();
699
+ const f = (v: string): number => parseFloat(v || '0');
700
+ const borderBox = cs.boxSizing === 'border-box';
701
+ switch (name) {
702
+ case 'width':
703
+ return borderBox ? r.width : r.width - f(cs.paddingLeft) - f(cs.paddingRight) - f(cs.borderLeftWidth) - f(cs.borderRightWidth);
704
+ case 'height':
705
+ return borderBox ? r.height : r.height - f(cs.paddingTop) - f(cs.paddingBottom) - f(cs.borderTopWidth) - f(cs.borderBottomWidth);
706
+ case 'top':
707
+ return f(cs.top);
708
+ case 'left':
709
+ return f(cs.left);
710
+ case 'bottom':
711
+ return f(cs.bottom);
712
+ case 'right':
713
+ return f(cs.right);
714
+ }
715
+ return 0;
716
+ }
717
+
718
+ /**
719
+ * Fills null keyframes (read from the value or element), CSS variables and
720
+ * "none" values, and converts between units of width/height/top/left (for
721
+ * instance `height: "auto"`) by measuring the element.
722
+ */
723
+ export function resolveKeyframes(frames: any[], name: string | undefined, value: MotionValue | undefined, element: any): { keyframes: any[]; finalKeyframe?: any } {
724
+ const out = [...frames];
725
+ let finalKeyframe: any;
726
+ if (out[0] === null) {
727
+ const current = value?.get();
728
+ const last = out[out.length - 1];
729
+ if (current !== undefined) out[0] = current;
730
+ else if (element && name && element.readValue) {
731
+ const read = element.readValue(name, last);
732
+ if (read !== undefined && read !== null) out[0] = read;
733
+ }
734
+ if (out[0] === undefined) out[0] = last;
735
+ if (value && current === undefined) value.set(out[0]);
736
+ }
737
+ for (let i = 1; i < out.length; i++) out[i] ??= out[i - 1];
738
+ const el: HTMLElement | undefined = element?.current;
739
+ if (el && typeof el.getBoundingClientRect === 'function') {
740
+ for (let i = 0; i < out.length; i++) {
741
+ let f = out[i];
742
+ if (typeof f === 'string') {
743
+ f = f.trim();
744
+ if (f.startsWith('var(--')) {
745
+ const resolved = getVariableValue(f, el);
746
+ if (resolved !== undefined) out[i] = resolved;
747
+ if (i === out.length - 1) finalKeyframe = f;
748
+ }
749
+ }
750
+ }
751
+ }
752
+ const noneIdx: number[] = [];
753
+ for (let i = 0; i < out.length; i++) if (out[i] === null || isNone(out[i])) noneIdx.push(i);
754
+ if (noneIdx.length) makeNoneKeyframesAnimatable(out, noneIdx, name);
755
+ if (el && name && positionalKeys.has(name) && !transformProps.has(name) && out.length === 2) {
756
+ const [origin, target] = out;
757
+ const ot = findDimensionValueType(origin);
758
+ const tt = findDimensionValueType(target);
759
+ if (ot !== tt) {
760
+ if (isNumOrPx(ot) && isNumOrPx(tt)) {
761
+ for (let i = 0; i < out.length; i++) if (typeof out[i] === 'string') out[i] = parseFloat(out[i]);
762
+ } else if (el instanceof HTMLElement) {
763
+ // Measure: origin as rendered now, target by applying it for a moment.
764
+ const prev = el.style.getPropertyValue(camelToDash(name));
765
+ const scrollY = name === 'height' && typeof window !== 'undefined' ? window.pageYOffset : undefined;
766
+ out[0] = measurePositional(el, name);
767
+ el.style.setProperty(camelToDash(name), typeof target === 'number' ? target + 'px' : String(target));
768
+ const measured = measurePositional(el, name);
769
+ el.style.setProperty(camelToDash(name), prev);
770
+ if (finalKeyframe === undefined && target !== null) finalKeyframe = target;
771
+ out[1] = measured;
772
+ if (scrollY !== undefined) window.scrollTo(0, scrollY);
773
+ }
774
+ }
775
+ }
776
+ return { keyframes: out, finalKeyframe };
777
+ }
778
+
779
+ /** The start function MotionValue.start() runs for one value of a transition. */
780
+ export const animateMotionValue =
781
+ (name: string, value: MotionValue, target: any, transition: Transition = {}, element?: any) =>
782
+ (onComplete: () => void): AnimationPlaybackControls | undefined => {
783
+ const valueTransition: Transition = getValueTransition(transition, name) || {};
784
+ const delay = valueTransition.delay || transition.delay || 0;
785
+ let { elapsed = 0 } = transition;
786
+ elapsed -= secondsToMilliseconds(delay);
787
+ const options: AnimationOptions = {
788
+ keyframes: Array.isArray(target) ? target : [null, target],
789
+ ease: 'easeOut',
790
+ velocity: value.getVelocity(),
791
+ ...valueTransition,
792
+ delay: -elapsed,
793
+ onUpdate: (v: any) => {
794
+ value.set(v);
795
+ if (valueTransition.onUpdate) valueTransition.onUpdate(v);
796
+ },
797
+ onComplete: () => {
798
+ onComplete();
799
+ if (valueTransition.onComplete) valueTransition.onComplete();
800
+ },
801
+ name,
802
+ motionValue: value,
803
+ element,
804
+ };
805
+ if (!isTransitionDefined(valueTransition)) Object.assign(options, getDefaultTransition(name, options));
806
+ if (options.duration) options.duration = secondsToMilliseconds(options.duration);
807
+ if (options.repeatDelay) options.repeatDelay = secondsToMilliseconds(options.repeatDelay);
808
+ if (options.from !== undefined) options.keyframes[0] = options.from;
809
+ let skip = false;
810
+ if ((options.type as unknown) === false || (options.duration === 0 && !options.repeatDelay)) {
811
+ options.duration = 0;
812
+ options.type = 'keyframes';
813
+ if (options.delay === 0) skip = true;
814
+ }
815
+ if (MotionGlobalConfig.instantAnimations || MotionGlobalConfig.skipAnimations) {
816
+ skip = true;
817
+ options.duration = 0;
818
+ options.type = 'keyframes';
819
+ options.delay = 0;
820
+ }
821
+ options.allowFlatten = !valueTransition.type && !valueTransition.ease;
822
+ if (skip && value.get() !== undefined) {
823
+ const final = getFinalKeyframe(options.keyframes, valueTransition);
824
+ if (final !== undefined) {
825
+ frame.update(() => {
826
+ options.onUpdate!(final);
827
+ options.onComplete!();
828
+ });
829
+ return undefined;
830
+ }
831
+ }
832
+ return startAnimation(options);
833
+ };
834
+
835
+ /** Resolves keyframes and starts a JS or WAAPI animation for one value. */
836
+ export function startAnimation(input: AnimationOptions): AnimationPlaybackControls {
837
+ const { keyframes: resolved, finalKeyframe } = resolveKeyframes(input.keyframes, input.name, input.motionValue, input.element);
838
+ const options: AnimationOptions = { finalKeyframe, ...input, keyframes: resolved };
839
+ if (!canAnimate(resolved, options.name, options.type, options.velocity)) {
840
+ if (MotionGlobalConfig.instantAnimations || !options.delay) options.onUpdate?.(getFinalKeyframe(resolved, options, finalKeyframe));
841
+ resolved[0] = resolved[resolved.length - 1];
842
+ options.duration = 0;
843
+ options.type = 'keyframes';
844
+ options.repeat = 0;
845
+ }
846
+ if (!options.isSync && supportsBrowserAnimation(options)) {
847
+ return new NativeAnimation({ ...options, element: options.motionValue!.owner.current });
848
+ }
849
+ return new JSAnimation(options);
850
+ }
851
+
852
+ export { isCSSVar };