@krate/motion 0.0.0-bootstrap.0 → 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,340 @@
1
+ // animate(): motion values, plain values, elements, selectors, objects and
2
+ // timelines (sequences with `at`), with playback controls; stagger();
3
+ // animation controls for the `animate` prop. Ported from framer-motion and
4
+ // motion-dom (MIT, Copyright (c) 2018 Framer B.V.), see NOTICE.
5
+
6
+ import { animateMotionValue, GroupAnimation, getValueTransition as rootValueTransition, type Transition } from './animation.js';
7
+ import { easingDefinitionToFunction, getEasingForSegment } from './easing.js';
8
+ import { createGeneratorEasing, defaultOffset, fillOffset, isGenerator, spring } from './generators.js';
9
+ import { resolveElements, type ElementOrSelector } from './gestures.js';
10
+ import { isMotionValue, motionValue, type AnimationPlaybackControls, type MotionValue } from './motion-value.js';
11
+ import { animateTarget, animateVisualElement, MotionNode, nodeStore, setTarget, type AnimationControlsLike } from './node.js';
12
+ import { mixNumber, progress, removeItem, secondsToMilliseconds } from './utils.js';
13
+
14
+ export interface AnimationScope<T = any> {
15
+ readonly current: T;
16
+ animations: AnimationPlaybackControls[];
17
+ }
18
+
19
+ export type DOMKeyframesDefinition = Record<string, any>;
20
+ export type AnimationSequence = Array<any>;
21
+
22
+ const isDOMKeyframes = (k: unknown): k is DOMKeyframesDefinition => typeof k === 'object' && k !== null && !Array.isArray(k);
23
+
24
+ function createNodeFor(subject: any): MotionNode {
25
+ if (typeof Element !== 'undefined' && subject instanceof Element) {
26
+ const node = new MotionNode({ props: {}, svg: subject instanceof SVGElement && subject.tagName.toLowerCase() !== 'svg' });
27
+ node.mount(subject as HTMLElement);
28
+ return node;
29
+ }
30
+ // A plain object (a three.js object, a store): values are written as properties.
31
+ const node = new MotionNode({ props: {} });
32
+ node.readValue = (key: string) => subject[key];
33
+ node.render = () => {
34
+ for (const key in node.latestValues) subject[key] = node.latestValues[key];
35
+ };
36
+ (node as any).current = subject;
37
+ nodeStore.set(subject, node);
38
+ return node;
39
+ }
40
+
41
+ function animateSingleValue(value: any, keyframes: any, options?: Transition): AnimationPlaybackControls | undefined {
42
+ const mv = isMotionValue(value) ? value : motionValue(value);
43
+ void mv.start(animateMotionValue('', mv, keyframes, options));
44
+ return mv.animation;
45
+ }
46
+
47
+ function resolveSubjects(subject: any, keyframes: any, scope?: AnimationScope, cache?: Record<string, NodeListOf<Element>>): any[] {
48
+ if (typeof subject === 'string' && isDOMKeyframes(keyframes)) return resolveElements(subject, scope, cache);
49
+ if (typeof NodeList !== 'undefined' && subject instanceof NodeList) return Array.from(subject);
50
+ if (Array.isArray(subject)) return subject;
51
+ return [subject];
52
+ }
53
+
54
+ function animateSubject(subject: any, keyframes: any, options?: any, scope?: AnimationScope): AnimationPlaybackControls[] {
55
+ const animations: AnimationPlaybackControls[] = [];
56
+ const single = isMotionValue(subject) || typeof subject === 'number' || (typeof subject === 'string' && !isDOMKeyframes(keyframes));
57
+ if (single) {
58
+ const a = animateSingleValue(subject, isDOMKeyframes(keyframes) ? keyframes.default || keyframes : keyframes, options ? options.default || options : options);
59
+ if (a) animations.push(a);
60
+ return animations;
61
+ }
62
+ const subjects = resolveSubjects(subject, keyframes, scope);
63
+ if (!subjects.length) throw new Error('@krate/motion: animate() found no valid elements.');
64
+ for (let i = 0; i < subjects.length; i++) {
65
+ const s = subjects[i];
66
+ if (s == null) throw new Error("@krate/motion: you're trying to animate null. Ensure selectors find elements and refs are attached.");
67
+ const node = nodeStore.get(s) || createNodeFor(s);
68
+ const transition = { ...options };
69
+ if ('delay' in transition && typeof transition.delay === 'function') transition.delay = transition.delay(i, subjects.length);
70
+ animations.push(...animateTarget(node, { ...keyframes, transition }, {}));
71
+ }
72
+ return animations;
73
+ }
74
+
75
+ // Timelines
76
+
77
+ interface ValueKeyframe {
78
+ value: any;
79
+ at: number;
80
+ easing?: any;
81
+ }
82
+
83
+ function calcNextTime(current: number, next: number | string, prev: number, labels: Map<string, number>): number {
84
+ if (typeof next === 'number') return next;
85
+ if (next.startsWith('-') || next.startsWith('+')) return Math.max(0, current + parseFloat(next));
86
+ if (next === '<') return prev;
87
+ if (next.startsWith('<')) return Math.max(0, prev + parseFloat(next.slice(1)));
88
+ return labels.get(next) ?? current;
89
+ }
90
+
91
+ function addKeyframes(seq: ValueKeyframe[], keyframes: any[], easing: any, offset: number[], start: number, end: number): void {
92
+ for (let i = 0; i < seq.length; i++) {
93
+ if (seq[i].at > start && seq[i].at < end) {
94
+ removeItem(seq, seq[i]);
95
+ i--;
96
+ }
97
+ }
98
+ for (let i = 0; i < keyframes.length; i++) seq.push({ value: keyframes[i], at: mixNumber(start, end, offset[i]), easing: getEasingForSegment(easing, i) });
99
+ }
100
+
101
+ const compareByTime = (a: ValueKeyframe, b: ValueKeyframe): number => {
102
+ if (a.at === b.at) {
103
+ if (a.value === null) return 1;
104
+ if (b.value === null) return -1;
105
+ return 0;
106
+ }
107
+ return a.at - b.at;
108
+ };
109
+
110
+ /** Converts a timeline into one keyframes animation per subject and value. */
111
+ export function createAnimationsFromSequence(
112
+ sequence: AnimationSequence,
113
+ { defaultTransition = {}, ...sequenceTransition }: any = {},
114
+ scope?: AnimationScope,
115
+ ): Map<any, { keyframes: Record<string, any[]>; transition: Record<string, any> }> {
116
+ const defaultDuration = defaultTransition.duration || 0.3;
117
+ const definitions = new Map<any, { keyframes: Record<string, any[]>; transition: Record<string, any> }>();
118
+ const sequences = new Map<any, Record<string, ValueKeyframe[]>>();
119
+ const cache: Record<string, NodeListOf<Element>> = {};
120
+ const labels = new Map<string, number>();
121
+ let prevTime = 0;
122
+ let currentTime = 0;
123
+ let totalDuration = 0;
124
+ for (const segment of sequence) {
125
+ if (typeof segment === 'string') {
126
+ labels.set(segment, currentTime);
127
+ continue;
128
+ }
129
+ if (!Array.isArray(segment)) {
130
+ labels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, labels));
131
+ continue;
132
+ }
133
+ const [subject, keyframes, transition = {}] = segment as [any, any, any];
134
+ if (transition.at !== undefined) currentTime = calcNextTime(currentTime, transition.at, prevTime, labels);
135
+ let maxDuration = 0;
136
+ const resolveValue = (valueKeyframes: any, valueTransition: any, valueSeq: ValueKeyframe[], index = 0, count = 0): void => {
137
+ const list = Array.isArray(valueKeyframes) ? [...valueKeyframes] : [valueKeyframes];
138
+ const { delay = 0, times = defaultOffset(list), type = 'keyframes', repeat, repeatType: _rt, repeatDelay: _rd = 0, ...rest } = valueTransition;
139
+ let { ease = defaultTransition.ease || 'easeOut', duration } = valueTransition;
140
+ const calcDelay = typeof delay === 'function' ? delay(index, count) : delay;
141
+ const generator = isGenerator(type) ? type : type === 'spring' ? spring : undefined;
142
+ if (list.length <= 2 && generator) {
143
+ let delta = 100;
144
+ if (list.length === 2 && list.every((k) => typeof k === 'number')) delta = Math.abs(list[1] - list[0]);
145
+ const springTransition = { ...rest };
146
+ if (duration !== undefined) springTransition.duration = secondsToMilliseconds(duration);
147
+ const e = createGeneratorEasing(springTransition, delta, generator);
148
+ ease = e.ease;
149
+ duration = e.duration;
150
+ }
151
+ duration ??= defaultDuration;
152
+ const startTime = currentTime + calcDelay;
153
+ const t = [...times];
154
+ if (t.length === 1 && t[0] === 0) t[1] = 1;
155
+ const remainder = t.length - list.length;
156
+ if (remainder > 0) fillOffset(t, remainder);
157
+ if (list.length === 1) list.unshift(null);
158
+ if (repeat) {
159
+ if (repeat >= 20) throw new Error('@krate/motion: repeat count too high, must be less than 20');
160
+ duration *= (repeat + 1);
161
+ const origFrames = [...list];
162
+ const origTimes = [...t];
163
+ ease = Array.isArray(ease) ? [...ease] : [ease];
164
+ const origEase = [...ease];
165
+ for (let r = 0; r < repeat; r++) {
166
+ list.push(...origFrames);
167
+ for (let k = 0; k < origFrames.length; k++) {
168
+ t.push(origTimes[k] + (r + 1));
169
+ ease.push(k === 0 ? 'linear' : getEasingForSegment(origEase, k - 1));
170
+ }
171
+ }
172
+ for (let k = 0; k < t.length; k++) t[k] /= repeat + 1;
173
+ }
174
+ const target = startTime + duration;
175
+ addKeyframes(valueSeq, list, ease, t, startTime, target);
176
+ maxDuration = Math.max(calcDelay + duration, maxDuration);
177
+ totalDuration = Math.max(target, totalDuration);
178
+ };
179
+ const subjectSeq = (s: any): Record<string, ValueKeyframe[]> => {
180
+ if (!sequences.has(s)) sequences.set(s, {});
181
+ return sequences.get(s)!;
182
+ };
183
+ const valueSeq = (name: string, seqs: Record<string, ValueKeyframe[]>): ValueKeyframe[] => (seqs[name] ||= []);
184
+ if (isMotionValue(subject)) {
185
+ resolveValue(keyframes, transition, valueSeq('default', subjectSeq(subject)));
186
+ } else {
187
+ const subjects = resolveSubjects(subject, keyframes, scope, cache);
188
+ for (let i = 0; i < subjects.length; i++) {
189
+ const seqs = subjectSeq(subjects[i]);
190
+ for (const key in keyframes) {
191
+ const vt = transition && transition[key] ? { ...transition, ...transition[key] } : { ...transition };
192
+ resolveValue(keyframes[key], vt, valueSeq(key, seqs), i, subjects.length);
193
+ }
194
+ }
195
+ }
196
+ prevTime = currentTime;
197
+ currentTime += maxDuration;
198
+ }
199
+ sequences.forEach((valueSeqs, subject) => {
200
+ for (const key in valueSeqs) {
201
+ const seq = valueSeqs[key].sort(compareByTime);
202
+ const keyframes: any[] = [];
203
+ const offset: number[] = [];
204
+ const easing: any[] = [];
205
+ for (const { at, value, easing: e } of seq) {
206
+ keyframes.push(value);
207
+ offset.push(progress(0, totalDuration, at));
208
+ easing.push(e || 'easeOut');
209
+ }
210
+ if (offset[0] !== 0) {
211
+ offset.unshift(0);
212
+ keyframes.unshift(keyframes[0]);
213
+ easing.unshift('easeInOut');
214
+ }
215
+ if (offset[offset.length - 1] !== 1) {
216
+ offset.push(1);
217
+ keyframes.push(null);
218
+ }
219
+ if (!definitions.has(subject)) definitions.set(subject, { keyframes: {}, transition: {} });
220
+ const def = definitions.get(subject)!;
221
+ def.keyframes[key] = keyframes;
222
+ def.transition[key] = { ...defaultTransition, duration: totalDuration, ease: easing, times: offset, ...sequenceTransition };
223
+ }
224
+ });
225
+ return definitions;
226
+ }
227
+
228
+ function animateSequence(sequence: AnimationSequence, options?: any, scope?: AnimationScope): AnimationPlaybackControls[] {
229
+ const out: AnimationPlaybackControls[] = [];
230
+ createAnimationsFromSequence(sequence, options, scope).forEach(({ keyframes, transition }, subject) => {
231
+ out.push(...animateSubject(subject, isMotionValue(subject) ? keyframes.default : keyframes, isMotionValue(subject) ? transition.default : transition));
232
+ });
233
+ return out;
234
+ }
235
+
236
+ class GroupAnimationWithThen extends GroupAnimation {}
237
+
238
+ const isSequence = (v: unknown): v is AnimationSequence => Array.isArray(v) && v.some(Array.isArray);
239
+
240
+ /** animate() options: a transition, per-value transitions, and a stagger() delay for several elements. */
241
+ export type DOMAnimationOptions = Omit<Transition, 'delay'> & { delay?: number | ((i: number, total: number) => number); [key: string]: any };
242
+
243
+ export type AnimateFunction = {
244
+ (sequence: AnimationSequence, options?: any): GroupAnimation;
245
+ (value: MotionValue<any> | number | string, keyframes: any, options?: DOMAnimationOptions): GroupAnimation;
246
+ (subject: ElementOrSelector | object, keyframes: DOMKeyframesDefinition, options?: DOMAnimationOptions): GroupAnimation;
247
+ };
248
+
249
+ /** Creates `animate`, optionally scoped to an element (useAnimate). */
250
+ export function createScopedAnimate(scope?: AnimationScope): AnimateFunction {
251
+ return ((subjectOrSequence: any, optionsOrKeyframes?: any, options?: any) => {
252
+ let animations: AnimationPlaybackControls[];
253
+ let onComplete: (() => void) | undefined;
254
+ if (isSequence(subjectOrSequence)) {
255
+ animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope);
256
+ } else {
257
+ const { onComplete: done, ...rest } = options || {};
258
+ if (typeof done === 'function') onComplete = done;
259
+ animations = animateSubject(subjectOrSequence, optionsOrKeyframes, rest, scope);
260
+ }
261
+ const animation = new GroupAnimationWithThen(animations);
262
+ if (onComplete) void animation.finished.then(onComplete);
263
+ if (scope) {
264
+ scope.animations.push(animation);
265
+ void animation.finished.then(() => removeItem(scope.animations, animation));
266
+ }
267
+ return animation;
268
+ }) as AnimateFunction;
269
+ }
270
+
271
+ /** Animates motion values, plain values, elements, selectors, objects and timelines. */
272
+ export const animate: AnimateFunction = /*@__PURE__*/ createScopedAnimate();
273
+
274
+ export type StaggerOrigin = 'first' | 'last' | 'center' | number;
275
+
276
+ /** Delays for `delay` in animate() or `delayChildren`: `stagger(0.1, { from: "center" })`. */
277
+ export function stagger(duration = 0.1, { startDelay = 0, from = 0, ease }: { startDelay?: number; from?: StaggerOrigin; ease?: any } = {}): (i: number, total: number) => number {
278
+ return (i, total) => {
279
+ const fromIndex = typeof from === 'number' ? from : from === 'first' ? 0 : from === 'last' ? total - 1 : (total - 1) / 2;
280
+ let delay = duration * Math.abs(fromIndex - i);
281
+ if (ease) {
282
+ const max = total * duration;
283
+ delay = easingDefinitionToFunction(ease)(delay / max) * max;
284
+ }
285
+ return startDelay + delay;
286
+ };
287
+ }
288
+
289
+ export interface LegacyAnimationControls extends AnimationControlsLike {
290
+ set(definition: any): void;
291
+ stop(): void;
292
+ mount(): () => void;
293
+ }
294
+
295
+ function setVariants(node: MotionNode, labels: string[]): void {
296
+ for (const key of [...labels].reverse()) {
297
+ const variant = node.getVariant(key);
298
+ if (variant) setTarget(node, variant);
299
+ node.variantChildren?.forEach((child) => setVariants(child, labels));
300
+ }
301
+ }
302
+
303
+ /** Controls passed to the `animate` prop of one or more elements (useAnimation). */
304
+ export function animationControls(): LegacyAnimationControls {
305
+ let hasMounted = false;
306
+ const subscribers = new Set<MotionNode>();
307
+ const controls: LegacyAnimationControls = {
308
+ subscribe(node) {
309
+ subscribers.add(node);
310
+ return () => void subscribers.delete(node);
311
+ },
312
+ start(definition, transitionOverride) {
313
+ if (!hasMounted) throw new Error('@krate/motion: controls.start() should only be called after a component has mounted (in an effect or onMount).');
314
+ const out: Array<Promise<any>> = [];
315
+ subscribers.forEach((node) => out.push(animateVisualElement(node, definition, { transitionOverride })));
316
+ return Promise.all(out);
317
+ },
318
+ set(definition) {
319
+ if (!hasMounted) throw new Error('@krate/motion: controls.set() should only be called after a component has mounted.');
320
+ subscribers.forEach((node) => {
321
+ if (Array.isArray(definition)) setVariants(node, definition);
322
+ else if (typeof definition === 'string') setVariants(node, [definition]);
323
+ else setTarget(node, definition);
324
+ });
325
+ },
326
+ stop() {
327
+ subscribers.forEach((node) => node.values.forEach((v) => v.stop()));
328
+ },
329
+ mount() {
330
+ hasMounted = true;
331
+ return () => {
332
+ hasMounted = false;
333
+ controls.stop();
334
+ };
335
+ },
336
+ };
337
+ return controls;
338
+ }
339
+
340
+ export { rootValueTransition as getValueTransition };