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

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,696 @@
1
+ // @krate/motion inside a Preact island.
2
+ //
3
+ // A "use client" component of a server-rendered page runs as a Preact island
4
+ // (React semantics on preact/compat), and the build points its @krate/motion
5
+ // imports here. The API is motion/react's, rendered by Preact over the same
6
+ // engine the Krate build uses: a motion component creates a MotionNode, its
7
+ // server render is the node's initial state, and contexts carry variants,
8
+ // presence, MotionConfig, LayoutGroup and LazyMotion as in framer-motion
9
+ // (MIT, Copyright (c) 2018 Framer B.V.), see NOTICE.
10
+
11
+ import { cloneElement, createContext, createElement, Fragment, options, toChildArray, type ComponentChildren, type VNode } from 'preact';
12
+ import { forwardRef } from 'preact/compat';
13
+ import { useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
14
+ import {
15
+ animationControls,
16
+ animationFrame,
17
+ buildHTMLStyles,
18
+ buildSVGAttrs,
19
+ createRenderState,
20
+ createReorderGroup,
21
+ createScopedAnimate,
22
+ createScrollMotionValues,
23
+ hasReducedMotionListener,
24
+ initPrefersReducedMotion,
25
+ inView,
26
+ isForcedMotionValue,
27
+ isMotionValue,
28
+ isSVGComponent,
29
+ isValidMotionProp,
30
+ makeLatestValues,
31
+ motionTemplate,
32
+ motionValue,
33
+ MotionNode,
34
+ prefersReducedMotion,
35
+ springMotionValue,
36
+ styleObject,
37
+ timeMotionValue,
38
+ trackScroll,
39
+ transformMotionValue,
40
+ velocityMotionValue,
41
+ WillChangeMotionValue,
42
+ wrap,
43
+ childVariantContext,
44
+ type AnimateFunction,
45
+ type AnimationScope,
46
+ type FeatureDefinition,
47
+ type LegacyAnimationControls,
48
+ type MotionValue,
49
+ type MotionValueEventCallbacks,
50
+ type ReorderContext,
51
+ type ScrollMotionValues,
52
+ type ScrollOffset,
53
+ type SpringOptions,
54
+ type InterpolateOptions,
55
+ } from '@krate/motion/engine';
56
+ import { gestureFeatures } from '@krate/motion/engine/gestures';
57
+ import { createDragControls, dragFeatures, type DragControls } from '@krate/motion/engine/drag';
58
+ import { layoutFeatures } from '@krate/motion/engine/layout';
59
+ import type { AnimatePresenceProps, LayoutGroupProps, MotionConfigProps, MotionProps } from '../types.js';
60
+
61
+ export type * from '../types.js';
62
+
63
+ type AnyProps = Record<string, any>;
64
+ type Features = Record<string, FeatureDefinition | undefined>;
65
+
66
+ // Contexts
67
+
68
+ export interface MotionContextValue {
69
+ node?: MotionNode | null;
70
+ }
71
+
72
+ export interface PresenceContextValue {
73
+ id: string;
74
+ isPresent: boolean;
75
+ initial?: false;
76
+ custom?: any;
77
+ onExitComplete?: (id: string) => void;
78
+ register: (id: string) => () => void;
79
+ }
80
+
81
+ export interface MotionConfigContextValue {
82
+ transition?: any;
83
+ reducedMotion?: 'user' | 'always' | 'never';
84
+ transformPagePoint?: (p: { x: number; y: number }) => { x: number; y: number };
85
+ isStatic?: boolean;
86
+ nonce?: string;
87
+ }
88
+
89
+ export interface LazyContextValue {
90
+ features?: Features;
91
+ strict: boolean;
92
+ }
93
+
94
+ export const MotionContext = createContext<MotionContextValue>({});
95
+ export const PresenceContext = createContext<PresenceContextValue | null>(null);
96
+ export const MotionConfigContext = createContext<MotionConfigContextValue>({ reducedMotion: 'never' });
97
+ export const LayoutGroupContext = createContext<{ id?: string; forceRender?: () => void }>({});
98
+ export const LazyContext = createContext<LazyContextValue>({ strict: false });
99
+
100
+ // Layout updates: Preact changes the DOM while it renders a queued update,
101
+ // so the layout feature measures every layout element before the queue runs
102
+ // and after it. It wraps Preact's render queue when a layout element first
103
+ // mounts (engine/layout.ts), so islands without layout props keep none of it.
104
+ (globalThis as { __krateMotionPreactOptions?: unknown }).__krateMotionPreactOptions = options;
105
+
106
+ const unitless = new Set(['animationIterationCount', 'aspectRatio', 'columnCount', 'flex', 'flexGrow', 'flexShrink', 'fontWeight', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'tabSize', 'widows', 'zIndex', 'zoom', 'fillOpacity', 'floodOpacity', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'scale']);
107
+
108
+ function filterProps(props: AnyProps, isDom: boolean, forwardMotionProps: boolean): AnyProps {
109
+ const out: AnyProps = {};
110
+ for (const key in props) {
111
+ if (key === 'values' && typeof props.values === 'object') continue;
112
+ if (key === 'children' || key === 'style') continue;
113
+ if (!isValidMotionProp(key) || (forwardMotionProps && isValidMotionProp(key)) || (!isDom && !isValidMotionProp(key)) || (props.draggable && key.startsWith('onDrag'))) {
114
+ out[key] = props[key];
115
+ }
116
+ }
117
+ return out;
118
+ }
119
+
120
+ const allFeatures: Features = /*@__PURE__*/ (() => {
121
+ return { ...gestureFeatures, ...dragFeatures, ...layoutFeatures };
122
+ })();
123
+
124
+ function useLayoutId(props: AnyProps): string | undefined {
125
+ const groupId = useContext(LayoutGroupContext).id;
126
+ return groupId && props.layoutId !== undefined ? groupId + '-' + props.layoutId : props.layoutId;
127
+ }
128
+
129
+ let presenceIds = 0;
130
+
131
+ function createMotionComponent(Component: any, { forwardMotionProps = false }: { forwardMotionProps?: boolean } = {}, preloaded?: Features): any {
132
+ const isSVG = isSVGComponent(Component);
133
+ const isDom = typeof Component === 'string';
134
+ function MotionComponent(props: AnyProps, externalRef: any) {
135
+ const config = useContext(MotionConfigContext);
136
+ const configAndProps: AnyProps = { ...props, layoutId: useLayoutId(props) };
137
+ if (configAndProps.transition === undefined && config.transition !== undefined) configAndProps.transition = config.transition;
138
+ if (configAndProps.transformPagePoint === undefined && config.transformPagePoint) configAndProps.transformPagePoint = config.transformPagePoint;
139
+ const parent = useContext(MotionContext).node ?? null;
140
+ const presence = useContext(PresenceContext);
141
+ const lazy = useContext(LazyContext);
142
+ if (preloaded && lazy.strict && !props.ignoreStrict) {
143
+ throw new Error('@krate/motion: you have rendered a `motion` component within a `LazyMotion` component with strict mode. Use `m` instead.');
144
+ }
145
+ const features = preloaded || lazy.features || {};
146
+ const nodeRef = useRef<MotionNode | null>(null);
147
+ if (!nodeRef.current) {
148
+ nodeRef.current = new MotionNode({
149
+ parent,
150
+ props: configAndProps,
151
+ presence,
152
+ config,
153
+ blockInitialAnimation: presence ? presence.initial === false : false,
154
+ tag: typeof Component === 'string' ? Component : 'div',
155
+ svg: isSVG,
156
+ features,
157
+ });
158
+ }
159
+ const node = nodeRef.current;
160
+ const exitId = useRef('');
161
+ if (!exitId.current) exitId.current = 'm' + ++presenceIds;
162
+ const mounted = useRef(false);
163
+ const prevPresent = useRef(presence ? presence.isPresent : true);
164
+
165
+ // The first render is the node's initial state (also on the server).
166
+ const visual = useMemo(() => {
167
+ const state = createRenderState();
168
+ if (isSVG) {
169
+ buildSVGAttrs(state, node.latestValues, typeof Component === 'string' && Component.toLowerCase() === 'svg', configAndProps.transformTemplate, styleObject(props.style));
170
+ return { attrs: state.attrs, style: { ...state.vars, ...state.style } };
171
+ }
172
+ buildHTMLStyles(state, node.latestValues, configAndProps.transformTemplate);
173
+ return { attrs: {}, style: { ...state.vars, ...state.style } };
174
+ }, []);
175
+ const raw: AnyProps = {};
176
+ const styleProp = styleObject(props.style) || {};
177
+ for (const key in styleProp) {
178
+ const v = styleProp[key];
179
+ if (!isMotionValue(v) && !isForcedMotionValue(key, configAndProps)) raw[key] = v;
180
+ }
181
+ const style: AnyProps = { ...raw, ...visual.style };
182
+ const domProps: AnyProps = { ...filterProps(props, isDom, forwardMotionProps), ...visual.attrs };
183
+ if (props.drag && props.dragListener !== false) {
184
+ domProps.draggable = false;
185
+ style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = 'none';
186
+ style.touchAction = props.drag === true ? 'none' : `pan-${props.drag === 'x' ? 'y' : 'x'}`;
187
+ }
188
+ if (props.tabIndex === undefined && (props.onTap || props.onTapStart || props.whileTap)) domProps.tabIndex = 0;
189
+ for (const key in style) {
190
+ const v = style[key];
191
+ if (typeof v === 'number' && v !== 0 && !unitless.has(key) && !key.startsWith('--')) style[key] = v + 'px';
192
+ }
193
+ domProps.style = style;
194
+
195
+ const ref = useCallback(
196
+ (el: any) => {
197
+ if (el) {
198
+ node.mount(el);
199
+ } else {
200
+ node.unmount();
201
+ }
202
+ if (typeof externalRef === 'function') externalRef(el);
203
+ else if (externalRef && typeof externalRef === 'object') externalRef.current = el;
204
+ },
205
+ [node],
206
+ );
207
+ domProps.ref = ref;
208
+ if (isMotionValue(props.children)) domProps.children = props.children.get();
209
+ else domProps.children = props.children;
210
+
211
+ useLayoutEffect(() => {
212
+ if (mounted.current) node.update(configAndProps, presence);
213
+ mounted.current = true;
214
+ node.updateFeatures();
215
+ node.scheduleRenderMicrotask();
216
+ const isPresent = presence ? presence.isPresent : true;
217
+ if (prevPresent.current && !isPresent && presence) {
218
+ const done = presence.onExitComplete;
219
+ void node.animationState.setActive('exit', true).then(() => done?.(exitId.current));
220
+ } else if (!prevPresent.current && isPresent) {
221
+ void node.animationState.setActive('exit', false);
222
+ }
223
+ prevPresent.current = isPresent;
224
+ });
225
+ useEffect(() => {
226
+ void node.animationState.animateChanges();
227
+ node.enteringChildren = undefined;
228
+ });
229
+ useEffect(() => {
230
+ if (!presence) return undefined;
231
+ return presence.register(exitId.current);
232
+ }, []);
233
+
234
+ const context = useMemo(() => ({ node }), [node]);
235
+ return createElement(MotionContext.Provider, { value: context }, createElement(Component, domProps));
236
+ }
237
+ return /*@__PURE__*/ forwardRef(MotionComponent as any);
238
+ }
239
+
240
+ type MotionNamespace = { [tag: string]: any } & {
241
+ create: (component: any, options?: { forwardMotionProps?: boolean }) => any;
242
+ };
243
+
244
+ function makeNamespace(preloaded?: Features): MotionNamespace {
245
+ const cache = new Map<unknown, any>();
246
+ const create = (component: any, opts?: { forwardMotionProps?: boolean }) => {
247
+ if (!opts && cache.has(component)) return cache.get(component);
248
+ const c = createMotionComponent(component, opts, preloaded);
249
+ if (!opts) cache.set(component, c);
250
+ return c;
251
+ };
252
+ const fn = Object.assign((component: any, opts?: { forwardMotionProps?: boolean }) => create(component, opts), { create });
253
+ return new Proxy(fn, {
254
+ get(target, key: string | symbol) {
255
+ if (typeof key !== 'string' || key in target) return (target as any)[key];
256
+ return create(key);
257
+ },
258
+ }) as MotionNamespace;
259
+ }
260
+
261
+ /** `motion.div` and every element, with all features; `motion.create(Component)`. */
262
+ export const motion: MotionNamespace = /*@__PURE__*/ makeNamespace(allFeatures);
263
+ /** The same elements with only the features a LazyMotion loads. */
264
+ export const m: MotionNamespace = /*@__PURE__*/ makeNamespace();
265
+
266
+ export interface FeatureBundle {
267
+ readonly __features: Features;
268
+ }
269
+
270
+ /** Animations and gestures. */
271
+ export const domAnimation: FeatureBundle = { __features: gestureFeatures };
272
+ /** Animations only. */
273
+ export const domMin: FeatureBundle = { __features: {} };
274
+ /** Animations, gestures, drag and layout. */
275
+ export const domMax: FeatureBundle = /*@__PURE__*/ (() => {
276
+ return { __features: allFeatures };
277
+ })();
278
+
279
+ export function LazyMotion({ children, features, strict = false }: { children?: ComponentChildren; features: FeatureBundle | (() => Promise<FeatureBundle | { default: FeatureBundle }>); strict?: boolean }) {
280
+ const [loaded, setLoaded] = useState<Features | undefined>(typeof features === 'function' ? undefined : features.__features);
281
+ useEffect(() => {
282
+ if (typeof features !== 'function') return;
283
+ void features().then((f: any) => setLoaded((f.default || f).__features));
284
+ }, []);
285
+ return createElement(LazyContext.Provider, { value: { features: loaded, strict } }, children);
286
+ }
287
+
288
+ export function MotionConfig({ children, ...props }: MotionConfigProps) {
289
+ const parent = useContext(MotionConfigContext);
290
+ const value = { ...parent, ...props };
291
+ if (props.transition && parent.transition && props.transition.inherit) value.transition = { ...parent.transition, ...props.transition };
292
+ return createElement(MotionConfigContext.Provider, { value: value as MotionConfigContextValue }, children);
293
+ }
294
+
295
+ export function LayoutGroup({ children, id, inherit = true }: LayoutGroupProps) {
296
+ const parent = useContext(LayoutGroupContext);
297
+ const [, force] = useState(0);
298
+ const groupId = inherit === true && parent.id && id ? parent.id + '-' + id : id ?? (inherit !== false ? parent.id : undefined);
299
+ const value = useMemo(() => ({ id: groupId, forceRender: () => force((n) => n + 1) }), [groupId]);
300
+ return createElement(LayoutGroupContext.Provider, { value }, children);
301
+ }
302
+
303
+ // AnimatePresence
304
+
305
+ const keyOf = (child: VNode): string => String(child.key ?? '');
306
+ const onlyElements = (children: ComponentChildren): VNode[] => toChildArray(children).filter((c): c is VNode => typeof c === 'object' && c !== null);
307
+
308
+ function PresenceChild({ children, initial, isPresent, onExitComplete, custom, mode }: { children?: any; initial?: false; isPresent: boolean; onExitComplete?: () => void; custom?: any; mode: string }) {
309
+ const registered = useRef(new Map<string, boolean>()).current;
310
+ const id = useId();
311
+ const context = useMemo<PresenceContextValue>(
312
+ () => ({
313
+ id,
314
+ initial,
315
+ isPresent,
316
+ custom,
317
+ onExitComplete: (childId: string) => {
318
+ registered.set(childId, true);
319
+ for (const done of registered.values()) if (!done) return;
320
+ onExitComplete?.();
321
+ },
322
+ register: (childId: string) => {
323
+ registered.set(childId, false);
324
+ return () => registered.delete(childId);
325
+ },
326
+ }),
327
+ [isPresent, onExitComplete, custom],
328
+ );
329
+ useMemo(() => {
330
+ registered.forEach((_v, key) => registered.set(key, false));
331
+ }, [isPresent]);
332
+ useEffect(() => {
333
+ if (!isPresent && !registered.size) onExitComplete?.();
334
+ }, [isPresent]);
335
+ let child: VNode = children as VNode;
336
+ if (mode === 'popLayout') child = createElement(PopChild, { isPresent }, children) as VNode;
337
+ return createElement(PresenceContext.Provider, { value: context }, child);
338
+ }
339
+
340
+ function PopChild({ children, isPresent }: { children?: any; isPresent: boolean }) {
341
+ const ref = useRef<HTMLElement | null>(null);
342
+ const childRef = ((children as VNode).props as AnyProps).ref ?? (children as any).ref;
343
+ const setRef = useCallback(
344
+ (el: HTMLElement | null) => {
345
+ ref.current = el;
346
+ if (typeof childRef === 'function') childRef(el);
347
+ else if (childRef && typeof childRef === 'object') childRef.current = el;
348
+ },
349
+ [childRef],
350
+ );
351
+ useLayoutEffect(() => {
352
+ const el = ref.current;
353
+ if (isPresent || !el) return;
354
+ const { offsetWidth: width, offsetHeight: height, offsetTop: top, offsetLeft: left } = el;
355
+ if (!width || !height) return;
356
+ el.style.setProperty('position', 'absolute', 'important');
357
+ el.style.setProperty('width', width + 'px', 'important');
358
+ el.style.setProperty('height', height + 'px', 'important');
359
+ el.style.setProperty('top', top + 'px', 'important');
360
+ el.style.setProperty('left', left + 'px', 'important');
361
+ }, [isPresent]);
362
+ return cloneElement(children as VNode, { ref: setRef });
363
+ }
364
+
365
+ /** Keeps removed children rendered until their exit animations finish. */
366
+ export function AnimatePresence({ children, custom, initial = true, onExitComplete, mode = 'sync', propagate = false }: AnimatePresenceProps) {
367
+ const parentPresence = useContext(PresenceContext);
368
+ const isParentPresent = parentPresence ? parentPresence.isPresent : true;
369
+ const present = useMemo(() => onlyElements(children), [children]);
370
+ const presentKeys = propagate && !isParentPresent ? [] : present.map(keyOf);
371
+ const isInitialRender = useRef(true);
372
+ const pending = useRef(present);
373
+ const exitComplete = useRef(new Map<string, boolean>()).current;
374
+ // Preact commits a render that returns null (React discards it when the
375
+ // render also sets state), so the children are diffed into refs here.
376
+ const diffed = useRef(present);
377
+ const renderedRef = useRef(present);
378
+ const [, force] = useState(0);
379
+ const { forceRender } = useContext(LayoutGroupContext);
380
+ if (present !== diffed.current) {
381
+ let next = [...present];
382
+ const exiting: VNode[] = [];
383
+ const prev = renderedRef.current;
384
+ for (let i = 0; i < prev.length; i++) {
385
+ const child = prev[i];
386
+ if (!presentKeys.includes(keyOf(child))) {
387
+ next.splice(i, 0, child);
388
+ exiting.push(child);
389
+ }
390
+ }
391
+ if (mode === 'wait' && exiting.length) next = exiting;
392
+ renderedRef.current = onlyElements(next);
393
+ diffed.current = present;
394
+ }
395
+ const rendered = renderedRef.current;
396
+ useLayoutEffect(() => {
397
+ isInitialRender.current = false;
398
+ pending.current = present;
399
+ for (const child of rendered) {
400
+ const key = keyOf(child);
401
+ if (!presentKeys.includes(key)) {
402
+ if (exitComplete.get(key) !== true) exitComplete.set(key, false);
403
+ } else {
404
+ exitComplete.delete(key);
405
+ }
406
+ }
407
+ }, [rendered, presentKeys.length, presentKeys.join('-')]);
408
+ return createElement(
409
+ Fragment,
410
+ null,
411
+ rendered.map((child) => {
412
+ const key = keyOf(child);
413
+ const isPresent = propagate && !isParentPresent ? false : present === rendered || presentKeys.includes(key);
414
+ const onExit = (): void => {
415
+ if (!exitComplete.has(key)) return;
416
+ exitComplete.set(key, true);
417
+ for (const done of exitComplete.values()) if (!done) return;
418
+ forceRender?.();
419
+ renderedRef.current = pending.current;
420
+ diffed.current = pending.current;
421
+ force((n) => n + 1);
422
+ if (propagate && parentPresence) parentPresence.onExitComplete?.(parentPresence.id);
423
+ onExitComplete?.();
424
+ };
425
+ return createElement(
426
+ PresenceChild,
427
+ { key, isPresent, initial: !isInitialRender.current || initial ? undefined : false, custom, mode, onExitComplete: isPresent ? undefined : onExit },
428
+ child,
429
+ );
430
+ }),
431
+ );
432
+ }
433
+
434
+ // Reorder
435
+
436
+ const ReorderContext = createContext<ReorderContext<any> | null>(null);
437
+
438
+ function ReorderGroup({ as = 'ul', axis = 'y', onReorder, values, children, ...props }: AnyProps, ref: any) {
439
+ const latest = useRef({ axis, values, onReorder });
440
+ latest.current = { axis, values, onReorder };
441
+ const ctx = useMemo(() => createReorderGroup(() => latest.current), []);
442
+ return createElement(motion.create(as), { ...props, ref }, createElement(ReorderContext.Provider, { value: ctx }, children));
443
+ }
444
+
445
+ function useDefaultMotionValue(value: any, initial = 0): MotionValue {
446
+ const fallback = useMotionValue(initial);
447
+ return isMotionValue(value) ? value : fallback;
448
+ }
449
+
450
+ function ReorderItem({ children, style = {}, value, as = 'li', onDrag, layout = true, ...props }: AnyProps, ref: any) {
451
+ const group = useContext(ReorderContext);
452
+ const x = useDefaultMotionValue(style.x);
453
+ const y = useDefaultMotionValue(style.y);
454
+ const zIndex = useTransform([x, y], ([lx, ly]: number[]) => (lx || ly ? 1 : 'unset'));
455
+ const axis = group ? group.axis : 'y';
456
+ return createElement(
457
+ motion.create(as),
458
+ {
459
+ drag: axis,
460
+ ...props,
461
+ dragSnapToOrigin: true,
462
+ style: { ...style, x, y, zIndex },
463
+ layout,
464
+ onDrag: (event: PointerEvent, info: any) => {
465
+ const { velocity } = info;
466
+ if (velocity[axis] && group) group.updateOrder(value, axis === 'x' ? x.get() : y.get(), velocity[axis]);
467
+ onDrag?.(event, info);
468
+ },
469
+ onLayoutMeasure: (box: any) => group?.registerItem(value, box),
470
+ ref,
471
+ },
472
+ children,
473
+ );
474
+ }
475
+
476
+ export const Reorder = /*@__PURE__*/ (() => {
477
+ return { Group: forwardRef(ReorderGroup as any) as any, Item: forwardRef(ReorderItem as any) as any };
478
+ })();
479
+
480
+ // Hooks
481
+
482
+ function useConstant<T>(make: () => T): T {
483
+ const ref = useRef<{ v: T } | null>(null);
484
+ if (!ref.current) ref.current = { v: make() };
485
+ return ref.current.v;
486
+ }
487
+
488
+ export function useMotionValue<T>(initial: T): MotionValue<T> {
489
+ return useConstant(() => motionValue(initial));
490
+ }
491
+
492
+ export function useTransform(input: any, rangeOrFn?: any, outputRange?: any[], options?: InterpolateOptions<any>): MotionValue<any> {
493
+ const value = useConstant(() => transformMotionValue(input, rangeOrFn, outputRange, options));
494
+ useEffect(() => () => value.destroy(), []);
495
+ return value;
496
+ }
497
+
498
+ export function useSpring(source: MotionValue<any> | number | string, options?: SpringOptions): MotionValue<any> {
499
+ const value = useConstant(() => springMotionValue(source, options));
500
+ const isStatic = useContext(MotionConfigContext).isStatic;
501
+ useEffect(() => () => value.destroy(), []);
502
+ useEffect(() => {
503
+ if (!isStatic && !isMotionValue(source)) value.set(source);
504
+ }, [source]);
505
+ return value;
506
+ }
507
+
508
+ export function useVelocity(value: MotionValue<number>): MotionValue<number> {
509
+ const v = useConstant(() => velocityMotionValue(value));
510
+ useEffect(() => () => v.destroy(), []);
511
+ return v;
512
+ }
513
+
514
+ export function useMotionTemplate(fragments: TemplateStringsArray, ...values: Array<MotionValue<any> | string | number>): MotionValue<string> {
515
+ const v = useConstant(() => motionTemplate(fragments, ...values));
516
+ useEffect(() => () => v.destroy(), []);
517
+ return v;
518
+ }
519
+
520
+ export function useMotionValueEvent<V, E extends keyof MotionValueEventCallbacks<V>>(value: MotionValue<V>, event: E, callback: MotionValueEventCallbacks<V>[E]): void {
521
+ useLayoutEffect(() => value.on(event, callback), [value, event, callback]);
522
+ }
523
+
524
+ export function useTime(): MotionValue<number> {
525
+ const [t, stop] = useConstant(() => timeMotionValue());
526
+ useEffect(() => stop, []);
527
+ return t;
528
+ }
529
+
530
+ export function useAnimationFrame(callback: (time: number, delta: number) => void): void {
531
+ const latest = useRef(callback);
532
+ latest.current = callback;
533
+ useEffect(() => animationFrame((t, d) => latest.current(t, d)), []);
534
+ }
535
+
536
+ type RefObject<T> = { current: T | null };
537
+
538
+ export function useScroll({ container, target, ...options }: { container?: RefObject<Element>; target?: RefObject<Element>; offset?: ScrollOffset; axis?: 'x' | 'y' } = {}): ScrollMotionValues {
539
+ const values = useConstant(createScrollMotionValues);
540
+ useLayoutEffect(
541
+ () => trackScroll(values, { ...options, container: container?.current || undefined, target: target?.current || undefined }),
542
+ [container, target, JSON.stringify(options.offset)],
543
+ );
544
+ return values;
545
+ }
546
+
547
+ export function useInView(ref: RefObject<Element>, { root, margin, amount, once = false, initial = false }: { root?: RefObject<Element>; margin?: string; amount?: 'some' | 'all' | number; once?: boolean; initial?: boolean } = {}): boolean {
548
+ const [isInView, setInView] = useState(initial);
549
+ useEffect(() => {
550
+ if (!ref.current || (once && isInView)) return undefined;
551
+ return inView(
552
+ ref.current,
553
+ () => {
554
+ setInView(true);
555
+ return once ? undefined : () => setInView(false);
556
+ },
557
+ { root: (root && root.current) || undefined, margin, amount },
558
+ );
559
+ }, [root, ref, margin, once, amount]);
560
+ return isInView;
561
+ }
562
+
563
+ export function useAnimate<T extends Element = any>(): [AnimationScope<T>, AnimateFunction] {
564
+ const scope = useConstant(() => ({ current: null as unknown as T, animations: [] as any[] }));
565
+ const animate = useConstant(() => createScopedAnimate(scope));
566
+ useEffect(
567
+ () => () => {
568
+ for (const a of scope.animations) a.stop();
569
+ scope.animations.length = 0;
570
+ },
571
+ [],
572
+ );
573
+ return [scope, animate];
574
+ }
575
+
576
+ export function useAnimationControls(): LegacyAnimationControls {
577
+ const controls = useConstant(animationControls);
578
+ useLayoutEffect(controls.mount, []);
579
+ return controls;
580
+ }
581
+
582
+ export const useAnimation: () => LegacyAnimationControls = useAnimationControls;
583
+
584
+ export function useDragControls(): DragControls {
585
+ return useConstant(createDragControls);
586
+ }
587
+
588
+ export function useCycle<T>(...items: T[]): [T, (next?: number) => void] {
589
+ const index = useRef(0);
590
+ const [item, setItem] = useState(items[index.current]);
591
+ const cycle = useCallback((next?: number) => {
592
+ index.current = typeof next !== 'number' ? wrap(0, items.length, index.current + 1) : next;
593
+ setItem(() => items[index.current]);
594
+ }, [items.length, ...items]);
595
+ return [item, cycle];
596
+ }
597
+
598
+ export function useReducedMotion(): boolean | null {
599
+ if (!hasReducedMotionListener.current) initPrefersReducedMotion();
600
+ const [reduced] = useState(prefersReducedMotion.current);
601
+ return reduced;
602
+ }
603
+
604
+ export function useReducedMotionConfig(): boolean | null {
605
+ const reduced = useReducedMotion();
606
+ const { reducedMotion } = useContext(MotionConfigContext);
607
+ return reducedMotion === 'never' ? false : reducedMotion === 'always' ? true : reduced;
608
+ }
609
+
610
+ export function useWillChange(): WillChangeMotionValue {
611
+ return useConstant(() => new WillChangeMotionValue('auto'));
612
+ }
613
+
614
+ export function usePresence(subscribe = true): [true] | [false, () => void] | [true, null] {
615
+ const context = useContext(PresenceContext);
616
+ const id = useId();
617
+ useEffect(() => {
618
+ if (context && subscribe) return context.register(id);
619
+ return undefined;
620
+ }, [subscribe]);
621
+ const safeToRemove = useCallback(() => {
622
+ if (subscribe && context && context.onExitComplete) context.onExitComplete(id);
623
+ }, [id, context && context.onExitComplete, subscribe]);
624
+ if (context === null) return [true, null];
625
+ return !context.isPresent && context.onExitComplete ? [false, safeToRemove] : [true];
626
+ }
627
+
628
+ export function useIsPresent(): boolean {
629
+ const context = useContext(PresenceContext);
630
+ return context === null ? true : context.isPresent;
631
+ }
632
+
633
+ export function usePresenceData(): any {
634
+ const context = useContext(PresenceContext);
635
+ return context ? context.custom : undefined;
636
+ }
637
+
638
+ export { isMotionValue, makeLatestValues, childVariantContext };
639
+ export type { MotionProps };
640
+
641
+ export {
642
+ animate,
643
+ stagger,
644
+ scroll,
645
+ scrollInfo,
646
+ inView,
647
+ hover,
648
+ press,
649
+ motionValue,
650
+ MotionValue,
651
+ transform,
652
+ interpolate,
653
+ mix,
654
+ wrap,
655
+ clamp,
656
+ progress,
657
+ frame,
658
+ cancelFrame,
659
+ frameData,
660
+ frameSteps,
661
+ time,
662
+ spring,
663
+ inertia,
664
+ keyframes,
665
+ animationControls,
666
+ easeIn,
667
+ easeOut,
668
+ easeInOut,
669
+ circIn,
670
+ circOut,
671
+ circInOut,
672
+ backIn,
673
+ backOut,
674
+ backInOut,
675
+ anticipate,
676
+ cubicBezier,
677
+ steps,
678
+ linear,
679
+ mirrorEasing,
680
+ reverseEasing,
681
+ animateValue,
682
+ MotionGlobalConfig,
683
+ createScopedAnimate,
684
+ transformValue,
685
+ delay,
686
+ distance,
687
+ distance2D,
688
+ pipe,
689
+ noop,
690
+ isValidMotionProp,
691
+ isDragActive,
692
+ } from '@krate/motion/engine';
693
+ export { DragControls } from '@krate/motion/engine/drag';
694
+ export type { AnimationPlaybackControls, AnimationScope, Easing, EasingDefinition, ScrollInfo, ScrollOffset, SpringOptions, LegacyAnimationControls, Transition } from '@krate/motion/engine';
695
+ export type { PanInfo, Point } from '@krate/motion/engine/drag';
696
+ export type { EventInfo } from '@krate/motion/engine';