@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,365 @@
1
+ // Layout animations. Every element with `layout` or `layoutId` is measured
2
+ // before and after each update (Krate: around each signal flush; Preact:
3
+ // around each render); when its box changed it is drawn with a transform
4
+ // from the old box to the new one and the transform eases to none (FLIP).
5
+ // Nested layout elements counter their parents' transform, border-radius and
6
+ // box-shadow are corrected for the scale, and an element whose layoutId
7
+ // matches one that just left starts from that one's box (shared element
8
+ // transitions). Loaded only by elements that use layout props. Follows the
9
+ // projection model of framer-motion (MIT, Copyright (c) 2018 Framer B.V.),
10
+ // see NOTICE.
11
+
12
+ import { animateMotionValue, type Transition } from './animation.js';
13
+ import { cancelFrame } from './frameloop.js';
14
+ import { motionValue, type MotionValue } from './motion-value.js';
15
+ import { buildTransform } from './render.js';
16
+ import { complex } from './values.js';
17
+ import { Feature, scaleCorrectors, type FeatureDefinition, type MotionNode } from './node.js';
18
+ import type { Box } from './drag.js';
19
+ import { layoutGroupId } from './scope.js';
20
+ import { mixNumber } from './utils.js';
21
+
22
+ export const defaultLayoutTransition: Transition = { duration: 0.45, ease: [0.4, 0, 0.1, 1] };
23
+
24
+ const mixBox = (a: Box, b: Box, p: number): Box => ({
25
+ x: { min: mixNumber(a.x.min, b.x.min, p), max: mixNumber(a.x.max, b.x.max, p) },
26
+ y: { min: mixNumber(a.y.min, b.y.min, p), max: mixNumber(a.y.max, b.y.max, p) },
27
+ });
28
+ const copyBox = (b: Box): Box => ({ x: { ...b.x }, y: { ...b.y } });
29
+ const len = (a: { min: number; max: number }): number => a.max - a.min;
30
+ const center = (a: { min: number; max: number }): number => (a.min + a.max) / 2;
31
+ const boxEquals = (a: Box, b: Box): boolean =>
32
+ Math.abs(a.x.min - b.x.min) < 0.5 && Math.abs(a.x.max - b.x.max) < 0.5 && Math.abs(a.y.min - b.y.min) < 0.5 && Math.abs(a.y.max - b.y.max) < 0.5;
33
+
34
+ /** Maps `box` from an ancestor's visual space back to its layout (local) space. */
35
+ function inverseMap(box: Box, from: Box, to: Box): Box {
36
+ const out = copyBox(box);
37
+ for (const axis of ['x', 'y'] as const) {
38
+ const s = len(from[axis]) ? len(to[axis]) / len(from[axis]) : 1;
39
+ out[axis].min = to[axis].min + (box[axis].min - from[axis].min) * s;
40
+ out[axis].max = to[axis].min + (box[axis].max - from[axis].min) * s;
41
+ }
42
+ return out;
43
+ }
44
+
45
+ const projections = new Set<Projection>();
46
+ const sharedLeads = new Map<string, Set<Projection>>();
47
+ const departed = new Map<string, { box: Box; at: number }>();
48
+ let hooksInstalled = false;
49
+ let snapshotTaken = false;
50
+
51
+ function sortedProjections(): Projection[] {
52
+ return Array.from(projections).sort((a, b) => a.node.depth - b.node.depth);
53
+ }
54
+
55
+ /** Measures every layout element's layout box with all layout transforms removed. */
56
+ function measureAll(list: Projection[]): Map<Projection, Box> {
57
+ const out = new Map<Projection, Box>();
58
+ const saved: Array<[HTMLElement | SVGElement, string]> = [];
59
+ for (const p of list) {
60
+ const el = p.node.current;
61
+ if (!el || !el.isConnected) continue;
62
+ saved.push([el, el.style.transform]);
63
+ el.style.transform = 'none';
64
+ }
65
+ const sx = typeof window !== 'undefined' ? window.scrollX : 0;
66
+ const sy = typeof window !== 'undefined' ? window.scrollY : 0;
67
+ for (const p of list) {
68
+ const el = p.node.current;
69
+ if (!el || !el.isConnected) continue;
70
+ p.node.notify('BeforeLayoutMeasure');
71
+ const r = el.getBoundingClientRect();
72
+ out.set(p, { x: { min: r.left + sx, max: r.right + sx }, y: { min: r.top + sy, max: r.bottom + sy } });
73
+ }
74
+ for (const [el, t] of saved) el.style.transform = t;
75
+ return out;
76
+ }
77
+
78
+ /** Records where every layout element is drawn, before an update changes the DOM. */
79
+ export function layoutWillUpdate(): void {
80
+ if (snapshotTaken || !projections.size) return;
81
+ snapshotTaken = true;
82
+ const list = sortedProjections();
83
+ const idle = list.filter((p) => !p.isAnimating());
84
+ const measured = measureAll(idle);
85
+ for (const p of list) {
86
+ p.snapshot = p.isAnimating() ? p.visualBox() : measured.get(p) || p.layout;
87
+ p.snapshotDependency = p.node.props.layoutDependency;
88
+ }
89
+ }
90
+
91
+ /** Measures every layout element after an update and animates the ones that moved. */
92
+ export function layoutDidUpdate(): void {
93
+ if (!snapshotTaken) return;
94
+ snapshotTaken = false;
95
+ const list = sortedProjections();
96
+ const measured = measureAll(list);
97
+ for (const p of list) {
98
+ const box = measured.get(p);
99
+ if (!box) continue;
100
+ p.didUpdate(box);
101
+ }
102
+ }
103
+
104
+ function installHooks(): void {
105
+ if (hooksInstalled) return;
106
+ hooksInstalled = true;
107
+ // In a Preact island the DOM changes while Preact renders its queue.
108
+ const preact = (globalThis as { __krateMotionPreactOptions?: { debounceRendering?: (cb: () => void) => void } }).__krateMotionPreactOptions;
109
+ if (preact) {
110
+ const prev = preact.debounceRendering;
111
+ const defer = (cb: () => void): void => {
112
+ if (prev) prev(cb);
113
+ else void Promise.resolve().then(cb);
114
+ };
115
+ preact.debounceRendering = (cb: () => void) =>
116
+ defer(() => {
117
+ layoutWillUpdate();
118
+ cb();
119
+ layoutDidUpdate();
120
+ });
121
+ }
122
+ if (typeof (globalThis as any).krateOnBeforeFlush === 'function' && typeof (globalThis as any).krateOnAfterFlush === 'function') {
123
+ (globalThis as any).krateOnBeforeFlush(layoutWillUpdate);
124
+ (globalThis as any).krateOnAfterFlush(layoutDidUpdate);
125
+ }
126
+ }
127
+
128
+ /** The layout projection of one node. */
129
+ export class Projection {
130
+ layout?: Box;
131
+ snapshot?: Box;
132
+ snapshotDependency: unknown;
133
+ private from?: Box;
134
+ private progress: MotionValue<number> = motionValue(1);
135
+ private target?: Box;
136
+ private localTarget?: Box;
137
+ isAnimationBlocked = false;
138
+ private listeners = new Map<string, Set<(e: any) => void>>();
139
+ private borderRadius?: number;
140
+ private boxShadow?: string;
141
+ private offProgress?: () => void;
142
+
143
+ constructor(public node: MotionNode) {}
144
+
145
+ get parent(): Projection | null {
146
+ for (let n = this.node.parent; n; n = n.parent) if (n.projection) return n.projection as Projection;
147
+ return null;
148
+ }
149
+
150
+ get layoutId(): string | undefined {
151
+ const id = this.node.props.layoutId;
152
+ if (id === undefined || id === null) return undefined;
153
+ const group = layoutGroupId(this.node.layoutScope ?? null);
154
+ return group ? `${group}-${id}` : String(id);
155
+ }
156
+
157
+ isAnimating(): boolean {
158
+ return !!this.from && this.progress.get() < 1;
159
+ }
160
+
161
+ /** The box the element is drawn in now (page coordinates). */
162
+ visualBox(): Box | undefined {
163
+ if (!this.layout) return undefined;
164
+ if (!this.from || !this.target) return this.layout;
165
+ return mixBox(this.from, this.target, this.progress.get());
166
+ }
167
+
168
+ addEventListener(name: string, cb: (e: any) => void): () => void {
169
+ let set = this.listeners.get(name);
170
+ if (!set) this.listeners.set(name, (set = new Set()));
171
+ set.add(cb);
172
+ return () => set!.delete(cb);
173
+ }
174
+
175
+ private emit(name: string, e: any): void {
176
+ this.listeners.get(name)?.forEach((cb) => cb(e));
177
+ }
178
+
179
+ mount(): void {
180
+ installHooks();
181
+ projections.add(this);
182
+ this.offProgress = this.progress.on('change', () => this.scheduleRenderTree());
183
+ const el = this.node.current;
184
+ if (!el) return;
185
+ const [box] = measureAll([this]).values();
186
+ if (!box) return;
187
+ this.layout = box;
188
+ this.readCorrectedStyles();
189
+ const id = this.layoutId;
190
+ if (id !== undefined) {
191
+ let set = sharedLeads.get(id);
192
+ if (!set) sharedLeads.set(id, (set = new Set()));
193
+ // The element this one takes over from: one still shown (crossfade
194
+ // partner) or one that left in the same update.
195
+ let fromBox: Box | undefined;
196
+ for (const other of set) if (other !== this && other.node.current?.isConnected) fromBox = other.visualBox();
197
+ const gone = departed.get(id);
198
+ if (!fromBox && gone && performance.now() - gone.at < 1000) fromBox = gone.box;
199
+ departed.delete(id);
200
+ set.add(this);
201
+ if (fromBox && !boxEquals(fromBox, box)) this.animateFrom(fromBox, box, true);
202
+ }
203
+ this.node.notify('LayoutMeasure', box, undefined);
204
+ }
205
+
206
+ private readCorrectedStyles(): void {
207
+ const el = this.node.current;
208
+ if (!el || typeof getComputedStyle === 'undefined') return;
209
+ const cs = getComputedStyle(el);
210
+ const r = parseFloat(cs.borderTopLeftRadius);
211
+ this.borderRadius = isNaN(r) ? undefined : r;
212
+ this.boxShadow = cs.boxShadow && cs.boxShadow !== 'none' ? cs.boxShadow : undefined;
213
+ }
214
+
215
+ unmount(): void {
216
+ projections.delete(this);
217
+ this.offProgress?.();
218
+ this.progress.stop();
219
+ const id = this.layoutId;
220
+ if (id !== undefined) {
221
+ const set = sharedLeads.get(id);
222
+ set?.delete(this);
223
+ const box = this.snapshot && snapshotTaken ? this.snapshot : this.visualBox();
224
+ if (box) departed.set(id, { box, at: performance.now() });
225
+ if (set && !set.size) sharedLeads.delete(id);
226
+ }
227
+ }
228
+
229
+ didUpdate(box: Box): void {
230
+ const prev = this.snapshot || this.layout;
231
+ this.snapshot = undefined;
232
+ const { layoutDependency } = this.node.props;
233
+ const dependencyChanged = layoutDependency === undefined || layoutDependency !== this.snapshotDependency;
234
+ const changed = !!prev && !boxEquals(prev, box);
235
+ const delta = prev ? { x: prev.x.min - box.x.min, y: prev.y.min - box.y.min } : { x: 0, y: 0 };
236
+ this.layout = box;
237
+ this.readCorrectedStyles();
238
+ this.node.notify('LayoutMeasure', box, prev);
239
+ this.emit('didUpdate', { delta, hasLayoutChanged: changed, layout: box, snapshot: prev });
240
+ if (!changed || !prev) {
241
+ if (this.from) this.scheduleRenderTree();
242
+ return;
243
+ }
244
+ if (this.isAnimationBlocked || !dependencyChanged) {
245
+ this.from = undefined;
246
+ this.target = box;
247
+ this.scheduleRenderTree();
248
+ return;
249
+ }
250
+ this.animateFrom(prev, box, false);
251
+ }
252
+
253
+ private animateFrom(from: Box, to: Box, shared: boolean): void {
254
+ const mode = this.node.props.layout;
255
+ let start = copyBox(from);
256
+ if (!shared && mode === 'position') {
257
+ // Animate the position only: the size changes at once.
258
+ start = { x: { min: from.x.min, max: from.x.min + len(to.x) }, y: { min: from.y.min, max: from.y.min + len(to.y) } };
259
+ } else if (!shared && mode === 'size') {
260
+ start = { x: { min: to.x.min, max: to.x.min + len(from.x) }, y: { min: to.y.min, max: to.y.min + len(from.y) } };
261
+ }
262
+ this.from = start;
263
+ this.target = to;
264
+ const props = this.node.getProps();
265
+ const base: any = props.transition ?? this.node.getDefaultTransition() ?? {};
266
+ const transition: Transition = { ...defaultLayoutTransition, ...(base.layout ?? base) };
267
+ this.progress.jump(0);
268
+ this.node.notify('LayoutAnimationStart');
269
+ if (this.node.shouldReduceMotion) {
270
+ this.progress.set(1);
271
+ this.node.notify('LayoutAnimationComplete');
272
+ return;
273
+ }
274
+ void this.progress.start(animateMotionValue('layout', this.progress, [0, 1], { ...transition, isSync: true } as Transition)).then(() => {
275
+ if (this.progress.get() >= 1) this.node.notify('LayoutAnimationComplete');
276
+ });
277
+ this.scheduleRenderTree();
278
+ }
279
+
280
+ private scheduleRenderTree(): void {
281
+ this.node.scheduleRender();
282
+ for (const p of projections) if (p !== this && this.node.current && p.node.current && this.node.current.contains(p.node.current)) p.node.scheduleRender();
283
+ }
284
+
285
+ /** The box the element must take in its parent's layout space (counters animating ancestors). */
286
+ private computeLocalTarget(): Box | undefined {
287
+ const v = this.visualBox();
288
+ if (!v) return undefined;
289
+ const chain: Projection[] = [];
290
+ for (let p = this.parent; p; p = p.parent) chain.unshift(p);
291
+ let box = v;
292
+ for (const p of chain) {
293
+ const pv = p.localTarget;
294
+ if (!pv || !p.layout || (!p.from && boxEquals(pv, p.layout))) continue;
295
+ box = inverseMap(box, pv, p.layout);
296
+ }
297
+ return box;
298
+ }
299
+
300
+ /** Writes the projection transform and the scale-corrected styles onto the element style. */
301
+ applyProjectionStyles(style: CSSStyleDeclaration, _styleProp?: unknown): void {
302
+ const L = this.layout;
303
+ const V = (this.localTarget = this.computeLocalTarget());
304
+ if (!L || !V) return;
305
+ const sx = len(L.x) ? len(V.x) / len(L.x) : 1;
306
+ const sy = len(L.y) ? len(V.y) / len(L.y) : 1;
307
+ const tx = center(V.x) - center(L.x);
308
+ const ty = center(V.y) - center(L.y);
309
+ const identity = Math.abs(tx) < 0.01 && Math.abs(ty) < 0.01 && Math.abs(sx - 1) < 0.0001 && Math.abs(sy - 1) < 0.0001;
310
+ const user = buildTransform(this.node.latestValues, {}, this.node.props.transformTemplate);
311
+ if (identity) {
312
+ style.transform = user;
313
+ if (this.borderRadius !== undefined && !this.node.latestValues.borderRadius) style.borderRadius = '';
314
+ return;
315
+ }
316
+ const projection = `translate3d(${tx}px, ${ty}px, 0) scale(${sx}, ${sy})`;
317
+ style.transform = user === 'none' ? projection : `${projection} ${user}`;
318
+ style.transformOrigin = '50% 50% 0';
319
+ const radius = this.node.latestValues.borderRadius !== undefined ? parseFloat(this.node.latestValues.borderRadius) : this.borderRadius;
320
+ if (radius !== undefined && !isNaN(radius) && radius > 0) {
321
+ const xr = len(V.x) ? (radius / len(V.x)) * 100 : 0;
322
+ const yr = len(V.y) ? (radius / len(V.y)) * 100 : 0;
323
+ style.borderRadius = `${xr}% / ${yr}%`;
324
+ }
325
+ const shadow = this.node.latestValues.boxShadow ?? this.boxShadow;
326
+ if (shadow && typeof shadow === 'string') {
327
+ const parsed = complex.parse(shadow) as any[];
328
+ if (parsed.length <= 5) {
329
+ const template = complex.createTransformer!(shadow);
330
+ const o = typeof parsed[0] !== 'number' ? 1 : 0;
331
+ parsed[o] /= sx;
332
+ parsed[o + 1] /= sy;
333
+ const avg = mixNumber(sx, sy, 0.5);
334
+ if (typeof parsed[o + 2] === 'number') parsed[o + 2] /= avg;
335
+ if (typeof parsed[o + 3] === 'number') parsed[o + 3] /= avg;
336
+ style.boxShadow = template(parsed);
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ class LayoutFeature extends Feature {
343
+ mount(): void {
344
+ const node = this.node;
345
+ if (!node.projection) node.projection = new Projection(node);
346
+ const p = node.projection as Projection;
347
+ p.mount();
348
+ const { layoutDependency } = node.props;
349
+ p.snapshotDependency = layoutDependency;
350
+ }
351
+ update(): void {}
352
+ unmount(): void {
353
+ const p = this.node.projection as Projection | undefined;
354
+ p?.unmount();
355
+ cancelFrame(this.node.render);
356
+ }
357
+ }
358
+
359
+ scaleCorrectors.borderRadius = { correct: (v: any) => v };
360
+ scaleCorrectors.boxShadow = { correct: (v: any) => v };
361
+
362
+ /** The layout feature (`layout`, `layoutId`). */
363
+ export const layoutFeatures: Record<string, FeatureDefinition> = {
364
+ layout: { isEnabled: (p) => !!(p.layout || p.layoutId !== undefined), Feature: LayoutFeature },
365
+ };
@@ -0,0 +1,234 @@
1
+ // MotionValue: a value with velocity tracking and change/animation events.
2
+ // It writes to nothing by itself; nodes subscribe to it and render on the
3
+ // shared frame loop. Ported from motion-dom (MIT, Copyright (c) 2018 Framer
4
+ // B.V.), see NOTICE.
5
+
6
+ import { cancelFrame, frame, time } from './frameloop.js';
7
+ import { SubscriptionManager, velocityPerSecond, warnOnce } from './utils.js';
8
+
9
+ const MAX_VELOCITY_DELTA = 30;
10
+ const isFloat = (v: unknown): boolean => !isNaN(parseFloat(v as string));
11
+
12
+ export interface AnimationPlaybackControls {
13
+ time: number;
14
+ speed: number;
15
+ startTime: number | null;
16
+ state: string;
17
+ duration: number;
18
+ iterationDuration?: number;
19
+ stop(): void;
20
+ play(): void;
21
+ pause(): void;
22
+ complete(): void;
23
+ cancel(): void;
24
+ then(onResolve: () => void, onReject?: () => void): Promise<void>;
25
+ finished: Promise<any>;
26
+ attachTimeline?(timeline: any): () => void;
27
+ }
28
+
29
+ export type StartAnimation = (complete: () => void) => AnimationPlaybackControls | undefined;
30
+
31
+ export interface MotionValueEventCallbacks<V> {
32
+ change: (latest: V) => void;
33
+ animationStart: () => void;
34
+ animationComplete: () => void;
35
+ animationCancel: () => void;
36
+ destroy: () => void;
37
+ renderRequest: () => void;
38
+ }
39
+
40
+ /** Values collected while a transformValue computes its first value. */
41
+ export const collectMotionValues: { current: MotionValue<any>[] | undefined } = { current: undefined };
42
+
43
+ /** A value Motion can animate, with velocity and change subscribers. */
44
+ export class MotionValue<V = any> {
45
+ current!: V;
46
+ prev: V | undefined;
47
+ prevFrameValue: V | undefined;
48
+ updatedAt!: number;
49
+ prevUpdatedAt: number | undefined;
50
+ canTrackVelocity: boolean | null = null;
51
+ events: { [K in keyof MotionValueEventCallbacks<V>]?: SubscriptionManager<MotionValueEventCallbacks<V>[K]> } = {};
52
+ animation?: AnimationPlaybackControls;
53
+ hasAnimated = false;
54
+ owner?: any;
55
+ dependents?: Set<MotionValue<any>>;
56
+ private passiveEffect?: (v: V, set: (v: V) => void) => void;
57
+ private stopPassiveEffect?: () => void;
58
+
59
+ constructor(init: V, options: { owner?: any } = {}) {
60
+ this.setCurrent(init);
61
+ this.owner = options.owner;
62
+ }
63
+
64
+ updateAndNotify = (v: V): void => {
65
+ const now = time.now();
66
+ if (this.updatedAt !== now) this.setPrevFrameValue();
67
+ this.prev = this.current;
68
+ this.setCurrent(v);
69
+ if (this.current !== this.prev) {
70
+ this.events.change?.notify(this.current);
71
+ if (this.dependents) for (const d of this.dependents) d.dirty();
72
+ }
73
+ };
74
+
75
+ setCurrent(current: V): void {
76
+ this.current = current;
77
+ this.updatedAt = time.now();
78
+ if (this.canTrackVelocity === null && current !== undefined) this.canTrackVelocity = isFloat(this.current);
79
+ }
80
+
81
+ setPrevFrameValue(prev: V = this.current): void {
82
+ this.prevFrameValue = prev;
83
+ this.prevUpdatedAt = this.updatedAt;
84
+ }
85
+
86
+ /** @deprecated use `on("change", cb)` */
87
+ onChange(cb: (v: V) => void): () => void {
88
+ warnOnce(false, 'value.onChange(callback) is deprecated. Switch to value.on("change", callback).');
89
+ return this.on('change', cb);
90
+ }
91
+
92
+ on<E extends keyof MotionValueEventCallbacks<V>>(event: E, cb: MotionValueEventCallbacks<V>[E]): () => void {
93
+ if (!this.events[event]) (this.events as any)[event] = new SubscriptionManager();
94
+ const unsubscribe = (this.events[event] as SubscriptionManager<any>).add(cb);
95
+ if (event === 'change') {
96
+ return () => {
97
+ unsubscribe();
98
+ // No change listener left at the next frame: nothing shows the
99
+ // value, so its animation stops.
100
+ frame.read(() => {
101
+ if (!this.events.change!.getSize()) this.stop();
102
+ });
103
+ };
104
+ }
105
+ return unsubscribe;
106
+ }
107
+
108
+ clearListeners(): void {
109
+ for (const key in this.events) (this.events as any)[key].clear();
110
+ }
111
+
112
+ /** Puts a function between `set` and the value (useSpring uses it to animate). */
113
+ attach(passiveEffect: (v: V, set: (v: V) => void) => void, stopPassiveEffect: () => void): void {
114
+ this.passiveEffect = passiveEffect;
115
+ this.stopPassiveEffect = stopPassiveEffect;
116
+ }
117
+
118
+ set(v: V): void {
119
+ if (!this.passiveEffect) this.updateAndNotify(v);
120
+ else this.passiveEffect(v, this.updateAndNotify);
121
+ }
122
+
123
+ setWithVelocity(prev: V, current: V, delta: number): void {
124
+ this.set(current);
125
+ this.prev = undefined;
126
+ this.prevFrameValue = prev;
127
+ this.prevUpdatedAt = this.updatedAt - delta;
128
+ }
129
+
130
+ /** Sets the value, stops its animation and resets its velocity to 0. */
131
+ jump(v: V, endAnimation = true): void {
132
+ this.updateAndNotify(v);
133
+ this.prev = v;
134
+ this.prevUpdatedAt = this.prevFrameValue = undefined;
135
+ if (endAnimation) this.stop();
136
+ if (this.stopPassiveEffect) this.stopPassiveEffect();
137
+ }
138
+
139
+ dirty(): void {
140
+ this.events.change?.notify(this.current);
141
+ }
142
+
143
+ addDependent(d: MotionValue<any>): void {
144
+ (this.dependents ||= new Set()).add(d);
145
+ }
146
+
147
+ removeDependent(d: MotionValue<any>): void {
148
+ this.dependents?.delete(d);
149
+ }
150
+
151
+ get(): V {
152
+ if (collectMotionValues.current) collectMotionValues.current.push(this);
153
+ return this.current;
154
+ }
155
+
156
+ getPrevious(): V | undefined {
157
+ return this.prev;
158
+ }
159
+
160
+ /** Velocity in units per second (0 for non-numeric values). */
161
+ getVelocity(): number {
162
+ const now = time.now();
163
+ if (!this.canTrackVelocity || this.prevFrameValue === undefined || now - this.updatedAt > MAX_VELOCITY_DELTA) return 0;
164
+ const delta = Math.min(this.updatedAt - (this.prevUpdatedAt as number), MAX_VELOCITY_DELTA);
165
+ return velocityPerSecond(parseFloat(this.current as any) - parseFloat(this.prevFrameValue as any), delta);
166
+ }
167
+
168
+ start(startAnimation: StartAnimation): Promise<void> {
169
+ this.stop();
170
+ return new Promise<void>((resolve) => {
171
+ this.hasAnimated = true;
172
+ this.animation = startAnimation(resolve);
173
+ this.events.animationStart?.notify();
174
+ }).then(() => {
175
+ this.events.animationComplete?.notify();
176
+ this.clearAnimation();
177
+ });
178
+ }
179
+
180
+ stop(): void {
181
+ if (this.animation) {
182
+ this.animation.stop();
183
+ this.events.animationCancel?.notify();
184
+ }
185
+ this.clearAnimation();
186
+ }
187
+
188
+ isAnimating(): boolean {
189
+ return !!this.animation;
190
+ }
191
+
192
+ clearAnimation(): void {
193
+ delete this.animation;
194
+ }
195
+
196
+ destroy(): void {
197
+ this.dependents?.clear();
198
+ this.events.destroy?.notify();
199
+ this.clearListeners();
200
+ this.stop();
201
+ if (this.stopPassiveEffect) this.stopPassiveEffect();
202
+ }
203
+ }
204
+
205
+ /** Creates a MotionValue. */
206
+ export function motionValue<V>(init: V, options?: { owner?: any }): MotionValue<V> {
207
+ return new MotionValue(init, options);
208
+ }
209
+
210
+ export const isMotionValue = (v: unknown): v is MotionValue => Boolean(v && (v as MotionValue).getVelocity);
211
+
212
+ /** Sets `output` from `getLatest` (before render) whenever one of `inputs` changes. */
213
+ export function subscribeValue(inputs: MotionValue<any>[], output: MotionValue<any>, getLatest: () => any): void {
214
+ const update = (): void => output.set(getLatest());
215
+ const schedule = (): void => {
216
+ frame.preRender(update, false, true);
217
+ };
218
+ const subs = inputs.map((v) => v.on('change', schedule));
219
+ output.on('destroy', () => {
220
+ subs.forEach((u) => u());
221
+ cancelFrame(update);
222
+ });
223
+ }
224
+
225
+ /** A MotionValue computed from the motion values `fn` reads, recomputed when they change. */
226
+ export function transformValue<O>(fn: () => O): MotionValue<O> {
227
+ const collected: MotionValue<any>[] = [];
228
+ collectMotionValues.current = collected;
229
+ const initial = fn();
230
+ collectMotionValues.current = undefined;
231
+ const value = motionValue(initial);
232
+ subscribeValue(collected, value, fn);
233
+ return value;
234
+ }