@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,342 @@
1
+ // Animation generators: tween keyframes, springs and inertia. A generator
2
+ // returns its value at a time t (ms). Ported from motion-dom (MIT, Copyright
3
+ // (c) 2018 Framer B.V.), see NOTICE.
4
+
5
+ import { easeInOut, easingDefinitionToFunction, isEasingArray, type Easing, type EasingDefinition } from './easing.js';
6
+ import { interpolate } from './values.js';
7
+ import { clamp, millisecondsToSeconds, mixNumber, progress, secondsToMilliseconds, velocityPerSecond, warnOnce } from './utils.js';
8
+
9
+ export interface GeneratorState<V> {
10
+ done: boolean;
11
+ value: V;
12
+ }
13
+
14
+ export interface KeyframeGenerator<V> {
15
+ calculatedDuration: number | null;
16
+ next(t: number): GeneratorState<V>;
17
+ toString?(): string;
18
+ }
19
+
20
+ export interface GeneratorOptions {
21
+ keyframes: any[];
22
+ duration?: number;
23
+ times?: number[];
24
+ ease?: Easing | EasingDefinition | Array<Easing | EasingDefinition>;
25
+ velocity?: number;
26
+ stiffness?: number;
27
+ damping?: number;
28
+ mass?: number;
29
+ bounce?: number;
30
+ visualDuration?: number;
31
+ restDelta?: number;
32
+ restSpeed?: number;
33
+ power?: number;
34
+ timeConstant?: number;
35
+ bounceDamping?: number;
36
+ bounceStiffness?: number;
37
+ modifyTarget?: (v: number) => number;
38
+ min?: number;
39
+ max?: number;
40
+ [key: string]: any;
41
+ }
42
+
43
+ export type GeneratorFactory = ((options: GeneratorOptions) => KeyframeGenerator<any>) & {
44
+ applyToOptions?: (options: any) => any;
45
+ };
46
+
47
+ /** Even 0-1 offsets for n keyframes. */
48
+ export function defaultOffset(arr: unknown[]): number[] {
49
+ const offset = [0];
50
+ fillOffset(offset, arr.length - 1);
51
+ return offset;
52
+ }
53
+
54
+ export function fillOffset(offset: number[], remaining: number): void {
55
+ const min = offset[offset.length - 1];
56
+ for (let i = 1; i <= remaining; i++) offset.push(mixNumber(min, 1, progress(0, remaining, i)));
57
+ }
58
+
59
+ export const convertOffsetToTimes = (offset: number[], duration: number): number[] => offset.map((o) => o * duration);
60
+
61
+ /** A tween through keyframes (`times` and per-segment `ease` supported). */
62
+ export const keyframes: GeneratorFactory = ({ duration = 300, keyframes: values, times, ease = 'easeInOut' }) => {
63
+ const fns = isEasingArray(ease) ? (ease as any[]).map(easingDefinitionToFunction) : easingDefinitionToFunction(ease as any);
64
+ const state: GeneratorState<any> = { done: false, value: values[0] };
65
+ const absolute = convertOffsetToTimes(times && times.length === values.length ? times : defaultOffset(values), duration);
66
+ const map = interpolate(absolute, values, {
67
+ ease: Array.isArray(fns) ? fns : values.map(() => fns || easeInOut).splice(0, values.length - 1),
68
+ });
69
+ return {
70
+ calculatedDuration: duration,
71
+ next(t) {
72
+ state.value = map(t);
73
+ state.done = t >= duration;
74
+ return state;
75
+ },
76
+ };
77
+ };
78
+
79
+ export const maxGeneratorDuration = 20000;
80
+
81
+ /** The time (ms) a generator takes to settle, sampled every 50ms. */
82
+ export function calcGeneratorDuration(generator: KeyframeGenerator<any>): number {
83
+ let duration = 0;
84
+ const step = 50;
85
+ let state = generator.next(duration);
86
+ while (!state.done && duration < maxGeneratorDuration) {
87
+ duration += step;
88
+ state = generator.next(duration);
89
+ }
90
+ return duration >= maxGeneratorDuration ? Infinity : duration;
91
+ }
92
+
93
+ export function calcGeneratorVelocity(resolve: (t: number) => number, t: number, current: number): number {
94
+ const prevT = Math.max(t - 5, 0);
95
+ return velocityPerSecond(current - resolve(prevT), t - prevT);
96
+ }
97
+
98
+ /** A CSS `linear()` easing that samples `easing` every `resolution` ms. */
99
+ export function generateLinearEasing(easing: Easing, duration: number, resolution = 10): string {
100
+ let points = '';
101
+ const n = Math.max(Math.round(duration / resolution), 2);
102
+ for (let i = 0; i < n; i++) points += Math.round(easing(i / (n - 1)) * 10000) / 10000 + ', ';
103
+ return `linear(${points.substring(0, points.length - 2)})`;
104
+ }
105
+
106
+ /** Turns a generator into a 0-1 easing and its duration (s), for WAAPI. */
107
+ export function createGeneratorEasing(options: any, scale = 100, create: GeneratorFactory) {
108
+ const generator = create({ ...options, keyframes: [0, scale] });
109
+ const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
110
+ return {
111
+ type: 'keyframes',
112
+ ease: (p: number) => generator.next(duration * p).value / scale,
113
+ duration: millisecondsToSeconds(duration),
114
+ };
115
+ }
116
+
117
+ export const springDefaults = {
118
+ stiffness: 100,
119
+ damping: 10,
120
+ mass: 1,
121
+ velocity: 0,
122
+ duration: 800,
123
+ bounce: 0.3,
124
+ visualDuration: 0.3,
125
+ restSpeed: { granular: 0.01, default: 2 },
126
+ restDelta: { granular: 0.005, default: 0.5 },
127
+ minDuration: 0.01,
128
+ maxDuration: 10,
129
+ minDamping: 0.05,
130
+ maxDamping: 1,
131
+ };
132
+
133
+ const safeMin = 0.001;
134
+
135
+ function calcAngularFreq(undamped: number, ratio: number): number {
136
+ return undamped * Math.sqrt(1 - ratio * ratio);
137
+ }
138
+
139
+ /** Finds stiffness and damping for a spring of `duration` (ms) and `bounce`. */
140
+ export function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass }: any) {
141
+ let envelope: (f: number) => number;
142
+ let derivative: (f: number) => number;
143
+ warnOnce(duration <= secondsToMilliseconds(springDefaults.maxDuration), 'Spring duration must be 10 seconds or less');
144
+ const ratio = clamp(springDefaults.minDamping, springDefaults.maxDamping, 1 - bounce);
145
+ const dur = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));
146
+ if (ratio < 1) {
147
+ envelope = (f) => {
148
+ const decay = f * ratio;
149
+ const delta = decay * dur;
150
+ const a = decay - velocity;
151
+ const b = calcAngularFreq(f, ratio);
152
+ return safeMin - (a / b) * Math.exp(-delta);
153
+ };
154
+ derivative = (f) => {
155
+ const decay = f * ratio;
156
+ const delta = decay * dur;
157
+ const d = delta * velocity + velocity;
158
+ const e = ratio ** 2 * f ** 2 * dur;
159
+ const g = calcAngularFreq(f ** 2, ratio);
160
+ const factor = -envelope(f) + safeMin > 0 ? -1 : 1;
161
+ return (factor * ((d - e) * Math.exp(-delta))) / g;
162
+ };
163
+ } else {
164
+ envelope = (f) => -safeMin + Math.exp(-f * dur) * ((f - velocity) * dur + 1);
165
+ derivative = (f) => Math.exp(-f * dur) * ((velocity - f) * (dur * dur));
166
+ }
167
+ let f = 5 / dur;
168
+ for (let i = 1; i < 12; i++) f -= envelope(f) / derivative(f);
169
+ const ms = secondsToMilliseconds(dur);
170
+ if (isNaN(f)) return { stiffness: springDefaults.stiffness, damping: springDefaults.damping, duration: ms };
171
+ const stiffness = f ** 2 * mass;
172
+ return { stiffness, damping: ratio * 2 * Math.sqrt(mass * stiffness), duration: ms };
173
+ }
174
+
175
+ function getSpringOptions(options: any) {
176
+ let out: any = {
177
+ velocity: springDefaults.velocity,
178
+ stiffness: springDefaults.stiffness,
179
+ damping: springDefaults.damping,
180
+ mass: springDefaults.mass,
181
+ isResolvedFromDuration: false,
182
+ ...options,
183
+ };
184
+ const has = (keys: string[]) => keys.some((k) => options[k] !== undefined);
185
+ if (!has(['stiffness', 'damping', 'mass']) && has(['duration', 'bounce'])) {
186
+ if (options.visualDuration) {
187
+ const root = (2 * Math.PI) / (options.visualDuration * 1.2);
188
+ const stiffness = root * root;
189
+ const damping = 2 * clamp(0.05, 1, 1 - (options.bounce || 0)) * Math.sqrt(stiffness);
190
+ out = { ...out, mass: springDefaults.mass, stiffness, damping };
191
+ } else {
192
+ out = { ...out, ...findSpring(options), mass: springDefaults.mass };
193
+ out.isResolvedFromDuration = true;
194
+ }
195
+ }
196
+ return out;
197
+ }
198
+
199
+ /**
200
+ * A spring generator. `spring(visualDuration, bounce)` returns a generator
201
+ * from 0 to 1 that can be used as a `type` or easing.
202
+ */
203
+ export const spring: GeneratorFactory & ((visualDuration?: number, bounce?: number) => KeyframeGenerator<number>) = ((
204
+ optionsOrVisualDuration: GeneratorOptions | number = springDefaults.visualDuration,
205
+ bounce: number = springDefaults.bounce,
206
+ ) => {
207
+ const options: GeneratorOptions =
208
+ typeof optionsOrVisualDuration !== 'object' ? { visualDuration: optionsOrVisualDuration, keyframes: [0, 1], bounce } : optionsOrVisualDuration;
209
+ let { restSpeed, restDelta } = options;
210
+ const origin = options.keyframes[0];
211
+ const target = options.keyframes[options.keyframes.length - 1];
212
+ const state: GeneratorState<number> = { done: false, value: origin };
213
+ const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration } = getSpringOptions({
214
+ ...options,
215
+ velocity: -millisecondsToSeconds(options.velocity || 0),
216
+ });
217
+ const initialVelocity = velocity || 0;
218
+ const ratio = damping / (2 * Math.sqrt(stiffness * mass));
219
+ const delta0 = target - origin;
220
+ const undamped = millisecondsToSeconds(Math.sqrt(stiffness / mass));
221
+ const granular = Math.abs(delta0) < 5;
222
+ restSpeed ||= granular ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default;
223
+ restDelta ||= granular ? springDefaults.restDelta.granular : springDefaults.restDelta.default;
224
+ let resolve: (t: number) => number;
225
+ if (ratio < 1) {
226
+ const angular = calcAngularFreq(undamped, ratio);
227
+ resolve = (t) => {
228
+ const env = Math.exp(-ratio * undamped * t);
229
+ return target - env * (((initialVelocity + ratio * undamped * delta0) / angular) * Math.sin(angular * t) + delta0 * Math.cos(angular * t));
230
+ };
231
+ } else if (ratio === 1) {
232
+ resolve = (t) => target - Math.exp(-undamped * t) * (delta0 + (initialVelocity + undamped * delta0) * t);
233
+ } else {
234
+ const damped = undamped * Math.sqrt(ratio * ratio - 1);
235
+ resolve = (t) => {
236
+ const env = Math.exp(-ratio * undamped * t);
237
+ const ft = Math.min(damped * t, 300);
238
+ return target - (env * ((initialVelocity + ratio * undamped * delta0) * Math.sinh(ft) + damped * delta0 * Math.cosh(ft))) / damped;
239
+ };
240
+ }
241
+ const generator: KeyframeGenerator<number> = {
242
+ calculatedDuration: isResolvedFromDuration ? duration || null : null,
243
+ next(t) {
244
+ const current = resolve(t);
245
+ if (!isResolvedFromDuration) {
246
+ let v = t === 0 ? initialVelocity : 0;
247
+ if (ratio < 1) v = t === 0 ? secondsToMilliseconds(initialVelocity) : calcGeneratorVelocity(resolve, t, current);
248
+ state.done = Math.abs(v) <= restSpeed! && Math.abs(target - current) <= restDelta!;
249
+ } else {
250
+ state.done = t >= duration;
251
+ }
252
+ state.value = state.done ? target : current;
253
+ return state;
254
+ },
255
+ toString() {
256
+ const d = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
257
+ return d + 'ms ' + generateLinearEasing((p) => generator.next(d * p).value, d, 30);
258
+ },
259
+ };
260
+ return generator;
261
+ }) as any;
262
+
263
+ spring.applyToOptions = (options: any) => {
264
+ const g = createGeneratorEasing(options, 100, spring);
265
+ options.ease = g.ease;
266
+ options.duration = secondsToMilliseconds(g.duration);
267
+ options.type = 'keyframes';
268
+ return options;
269
+ };
270
+
271
+ /** A decay animation (momentum), springing back into `min`/`max` when it crosses them. */
272
+ export const inertia: GeneratorFactory = ({
273
+ keyframes: frames,
274
+ velocity = 0,
275
+ power = 0.8,
276
+ timeConstant = 325,
277
+ bounceDamping = 10,
278
+ bounceStiffness = 500,
279
+ modifyTarget,
280
+ min,
281
+ max,
282
+ restDelta = 0.5,
283
+ restSpeed,
284
+ }) => {
285
+ const origin = frames[0];
286
+ const state: GeneratorState<number> = { done: false, value: origin };
287
+ const outOfBounds = (v: number): boolean => (min !== undefined && v < min) || (max !== undefined && v > max);
288
+ const nearestBoundary = (v: number): number | undefined => {
289
+ if (min === undefined) return max;
290
+ if (max === undefined) return min;
291
+ return Math.abs(min - v) < Math.abs(max - v) ? min : max;
292
+ };
293
+ let amplitude = power * velocity;
294
+ const ideal = origin + amplitude;
295
+ const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
296
+ if (target !== ideal) amplitude = target - origin;
297
+ const calcDelta = (t: number): number => -amplitude * Math.exp(-t / timeConstant);
298
+ const calcLatest = (t: number): number => target + calcDelta(t);
299
+ const applyFriction = (t: number): void => {
300
+ const d = calcDelta(t);
301
+ const latest = calcLatest(t);
302
+ state.done = Math.abs(d) <= restDelta;
303
+ state.value = state.done ? target : latest;
304
+ };
305
+ let timeReachedBoundary: number | undefined;
306
+ let bounceSpring: KeyframeGenerator<number> | undefined;
307
+ const checkCatchBoundary = (t: number): void => {
308
+ if (!outOfBounds(state.value)) return;
309
+ timeReachedBoundary = t;
310
+ bounceSpring = spring({
311
+ keyframes: [state.value, nearestBoundary(state.value)],
312
+ velocity: calcGeneratorVelocity(calcLatest, t, state.value),
313
+ damping: bounceDamping,
314
+ stiffness: bounceStiffness,
315
+ restDelta,
316
+ restSpeed,
317
+ });
318
+ };
319
+ checkCatchBoundary(0);
320
+ return {
321
+ calculatedDuration: null,
322
+ next(t) {
323
+ let updated = false;
324
+ if (!bounceSpring && timeReachedBoundary === undefined) {
325
+ updated = true;
326
+ applyFriction(t);
327
+ checkCatchBoundary(t);
328
+ }
329
+ if (timeReachedBoundary !== undefined && t >= timeReachedBoundary) return bounceSpring!.next(t - timeReachedBoundary);
330
+ if (!updated) applyFriction(t);
331
+ return state;
332
+ },
333
+ };
334
+ };
335
+
336
+ export const isGenerator = (type: unknown): type is GeneratorFactory => typeof type === 'function' && 'applyToOptions' in type;
337
+
338
+ const transitionTypeMap: Record<string, GeneratorFactory> = { decay: inertia, inertia, tween: keyframes, keyframes, spring };
339
+
340
+ export function replaceTransitionType(t: any): void {
341
+ if (typeof t.type === 'string') t.type = transitionTypeMap[t.type];
342
+ }
@@ -0,0 +1,136 @@
1
+ // The gesture features: whileHover/onHover*, whileTap/onTap*, whileFocus and
2
+ // whileInView/onViewport*. Loaded only by elements that use these props.
3
+ // Ported from framer-motion (MIT, Copyright (c) 2018 Framer B.V.), see
4
+ // NOTICE.
5
+
6
+ import { frame } from './frameloop.js';
7
+ import { addDomEvent, extractEventInfo, hover, observeIntersection, press } from './gestures.js';
8
+ import { Feature, type FeatureDefinition, type MotionNode } from './node.js';
9
+
10
+ function handleHover(node: MotionNode, event: PointerEvent, lifecycle: 'Start' | 'End'): void {
11
+ const { props } = node;
12
+ if (node.animationState && props.whileHover) void node.animationState.setActive('whileHover', lifecycle === 'Start');
13
+ const cb = props['onHover' + lifecycle];
14
+ if (cb) frame.postRender(() => cb(event, extractEventInfo(event)));
15
+ }
16
+
17
+ class HoverGesture extends Feature {
18
+ private cancel?: () => void;
19
+ mount(): void {
20
+ const el = this.node.current;
21
+ if (!el) return;
22
+ this.cancel = hover(el, (_el, start) => {
23
+ handleHover(this.node, start, 'Start');
24
+ return (end) => handleHover(this.node, end, 'End');
25
+ });
26
+ }
27
+ unmount(): void {
28
+ this.cancel?.();
29
+ }
30
+ }
31
+
32
+ function handlePress(node: MotionNode, event: PointerEvent, lifecycle: 'Start' | 'End' | 'Cancel'): void {
33
+ const { props } = node;
34
+ if (typeof HTMLButtonElement !== 'undefined' && node.current instanceof HTMLButtonElement && node.current.disabled) return;
35
+ if (node.animationState && props.whileTap) void node.animationState.setActive('whileTap', lifecycle === 'Start');
36
+ const cb = props['onTap' + (lifecycle === 'End' ? '' : lifecycle)];
37
+ if (cb) frame.postRender(() => cb(event, extractEventInfo(event)));
38
+ }
39
+
40
+ class PressGesture extends Feature {
41
+ private cancel?: () => void;
42
+ mount(): void {
43
+ const el = this.node.current;
44
+ if (!el) return;
45
+ this.cancel = press(
46
+ el,
47
+ (_el, start) => {
48
+ handlePress(this.node, start, 'Start');
49
+ return (end, { success }) => handlePress(this.node, end, success ? 'End' : 'Cancel');
50
+ },
51
+ { useGlobalTarget: this.node.props.globalTapTarget },
52
+ );
53
+ }
54
+ unmount(): void {
55
+ this.cancel?.();
56
+ }
57
+ }
58
+
59
+ class FocusGesture extends Feature {
60
+ private isActive = false;
61
+ private cancel?: () => void;
62
+ mount(): void {
63
+ const el = this.node.current;
64
+ if (!el) return;
65
+ const offFocus = addDomEvent(el, 'focus', () => {
66
+ let visible = false;
67
+ try {
68
+ visible = el.matches(':focus-visible');
69
+ } catch {
70
+ visible = true;
71
+ }
72
+ if (!visible || !this.node.animationState) return;
73
+ void this.node.animationState.setActive('whileFocus', true);
74
+ this.isActive = true;
75
+ });
76
+ const offBlur = addDomEvent(el, 'blur', () => {
77
+ if (!this.isActive || !this.node.animationState) return;
78
+ void this.node.animationState.setActive('whileFocus', false);
79
+ this.isActive = false;
80
+ });
81
+ this.cancel = () => {
82
+ offFocus();
83
+ offBlur();
84
+ };
85
+ }
86
+ unmount(): void {
87
+ this.cancel?.();
88
+ }
89
+ }
90
+
91
+ class InViewFeature extends Feature {
92
+ private hasEnteredView = false;
93
+ private isInView = false;
94
+ private stop?: () => void;
95
+ private start(): void {
96
+ this.stop?.();
97
+ const { viewport = {} } = this.node.getProps();
98
+ const { root, margin: rootMargin, amount = 'some', once } = viewport;
99
+ if (typeof IntersectionObserver === 'undefined' || !this.node.current) return;
100
+ this.stop = observeIntersection(
101
+ this.node.current,
102
+ { root: root ? root.current ?? root : undefined, rootMargin, threshold: typeof amount === 'number' ? amount : amount === 'all' ? 1 : 0 },
103
+ (entry) => {
104
+ const { isIntersecting } = entry;
105
+ if (this.isInView === isIntersecting) return;
106
+ this.isInView = isIntersecting;
107
+ if (once && !isIntersecting && this.hasEnteredView) return;
108
+ if (isIntersecting) this.hasEnteredView = true;
109
+ if (this.node.animationState) void this.node.animationState.setActive('whileInView', isIntersecting);
110
+ const { onViewportEnter, onViewportLeave } = this.node.getProps();
111
+ const cb = isIntersecting ? onViewportEnter : onViewportLeave;
112
+ if (cb) cb(entry);
113
+ },
114
+ );
115
+ }
116
+ mount(): void {
117
+ this.start();
118
+ }
119
+ update(): void {
120
+ const { props, prevProps } = this.node;
121
+ const v = props.viewport || {};
122
+ const p = (prevProps && prevProps.viewport) || {};
123
+ if (['amount', 'margin', 'root'].some((k) => v[k] !== p[k])) this.start();
124
+ }
125
+ unmount(): void {
126
+ this.stop?.();
127
+ }
128
+ }
129
+
130
+ /** The gesture features. */
131
+ export const gestureFeatures: Record<string, FeatureDefinition> = {
132
+ hover: { isEnabled: (p) => !!(p.whileHover || p.onHoverStart || p.onHoverEnd), Feature: HoverGesture },
133
+ tap: { isEnabled: (p) => !!(p.whileTap || p.onTap || p.onTapStart || p.onTapCancel), Feature: PressGesture },
134
+ focus: { isEnabled: (p) => !!p.whileFocus, Feature: FocusGesture },
135
+ inView: { isEnabled: (p) => !!(p.whileInView || p.onViewportEnter || p.onViewportLeave), Feature: InViewFeature },
136
+ };