main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
import { GroupAnimationWithThen } from 'motion-dom';
import { removeItem } from 'motion-utils';
import { animateSequence } from './sequence.mjs';
import { animateSubject } from './subject.mjs';
function isSequence(value) {
return Array.isArray(value) && value.some(Array.isArray);
}
/**
* Creates an animation function that is optionally scoped
* to a specific element.
*/
function createScopedAnimate(scope) {
/**
* Implementation
*/
function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) {
let animations = [];
let animationOnComplete;
if (isSequence(subjectOrSequence)) {
animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope);
}
else {
// Extract top-level onComplete so it doesn't get applied per-value
const { onComplete, ...rest } = options || {};
if (typeof onComplete === "function") {
animationOnComplete = onComplete;
}
animations = animateSubject(subjectOrSequence, optionsOrKeyframes, rest, scope);
}
const animation = new GroupAnimationWithThen(animations);
if (animationOnComplete) {
animation.finished.then(animationOnComplete);
}
if (scope) {
scope.animations.push(animation);
animation.finished.then(() => {
removeItem(scope.animations, animation);
});
}
return animation;
}
return scopedAnimate;
}
const animate = createScopedAnimate();
export { animate, createScopedAnimate };

View File

@@ -0,0 +1,19 @@
import { resolveElements } from 'motion-dom';
import { isDOMKeyframes } from '../utils/is-dom-keyframes.mjs';
function resolveSubjects(subject, keyframes, scope, selectorCache) {
if (typeof subject === "string" && isDOMKeyframes(keyframes)) {
return resolveElements(subject, scope, selectorCache);
}
else if (subject instanceof NodeList) {
return Array.from(subject);
}
else if (Array.isArray(subject)) {
return subject;
}
else {
return [subject];
}
}
export { resolveSubjects };

View File

@@ -0,0 +1,14 @@
import { spring } from 'motion-dom';
import { createAnimationsFromSequence } from '../sequence/create.mjs';
import { animateSubject } from './subject.mjs';
function animateSequence(sequence, options, scope) {
const animations = [];
const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring });
animationDefinitions.forEach(({ keyframes, transition }, subject) => {
animations.push(...animateSubject(subject, keyframes, transition));
});
return animations;
}
export { animateSequence };

View File

@@ -0,0 +1,10 @@
import { isMotionValue, motionValue } from 'motion-dom';
import { animateMotionValue } from '../interfaces/motion-value.mjs';
function animateSingleValue(value, keyframes, options) {
const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options));
return motionValue$1.animation;
}
export { animateSingleValue };

View File

@@ -0,0 +1,53 @@
import { isMotionValue } from 'motion-dom';
import { invariant } from 'motion-utils';
import { visualElementStore } from '../../render/store.mjs';
import { animateTarget } from '../interfaces/visual-element-target.mjs';
import { createDOMVisualElement, createObjectVisualElement } from '../utils/create-visual-element.mjs';
import { isDOMKeyframes } from '../utils/is-dom-keyframes.mjs';
import { resolveSubjects } from './resolve-subjects.mjs';
import { animateSingleValue } from './single-value.mjs';
function isSingleValue(subject, keyframes) {
return (isMotionValue(subject) ||
typeof subject === "number" ||
(typeof subject === "string" && !isDOMKeyframes(keyframes)));
}
/**
* Implementation
*/
function animateSubject(subject, keyframes, options, scope) {
const animations = [];
if (isSingleValue(subject, keyframes)) {
animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes)
? keyframes.default || keyframes
: keyframes, options ? options.default || options : options));
}
else {
const subjects = resolveSubjects(subject, keyframes, scope);
const numSubjects = subjects.length;
invariant(Boolean(numSubjects), "No valid elements provided.", "no-valid-elements");
for (let i = 0; i < numSubjects; i++) {
const thisSubject = subjects[i];
invariant(thisSubject !== null, "You're trying to perform an animation on null. Ensure that selectors are correctly finding elements and refs are correctly hydrated.", "animate-null");
const createVisualElement = thisSubject instanceof Element
? createDOMVisualElement
: createObjectVisualElement;
if (!visualElementStore.has(thisSubject)) {
createVisualElement(thisSubject);
}
const visualElement = visualElementStore.get(thisSubject);
const transition = { ...options };
/**
* Resolve stagger function if provided.
*/
if ("delay" in transition &&
typeof transition.delay === "function") {
transition.delay = transition.delay(i, numSubjects);
}
animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {}));
}
}
return animations;
}
export { animateSubject };

View File

@@ -0,0 +1,105 @@
import { resolveElements, getValueTransition, getAnimationMap, animationMapKey, getComputedStyle, fillWildcards, applyPxDefaults, NativeAnimation } from 'motion-dom';
import { invariant, secondsToMilliseconds } from 'motion-utils';
function animateElements(elementOrSelector, keyframes, options, scope) {
const elements = resolveElements(elementOrSelector, scope);
const numElements = elements.length;
invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements");
/**
* WAAPI doesn't support interrupting animations.
*
* Therefore, starting animations requires a three-step process:
* 1. Stop existing animations (write styles to DOM)
* 2. Resolve keyframes (read styles from DOM)
* 3. Create new animations (write styles to DOM)
*
* The hybrid `animate()` function uses AsyncAnimation to resolve
* keyframes before creating new animations, which removes style
* thrashing. Here, we have much stricter filesize constraints.
* Therefore we do this in a synchronous way that ensures that
* at least within `animate()` calls there is no style thrashing.
*
* In the motion-native-animate-mini-interrupt benchmark this
* was 80% faster than a single loop.
*/
const animationDefinitions = [];
/**
* Step 1: Build options and stop existing animations (write)
*/
for (let i = 0; i < numElements; i++) {
const element = elements[i];
const elementTransition = { ...options };
/**
* Resolve stagger function if provided.
*/
if (typeof elementTransition.delay === "function") {
elementTransition.delay = elementTransition.delay(i, numElements);
}
for (const valueName in keyframes) {
let valueKeyframes = keyframes[valueName];
if (!Array.isArray(valueKeyframes)) {
valueKeyframes = [valueKeyframes];
}
const valueOptions = {
...getValueTransition(elementTransition, valueName),
};
valueOptions.duration && (valueOptions.duration = secondsToMilliseconds(valueOptions.duration));
valueOptions.delay && (valueOptions.delay = secondsToMilliseconds(valueOptions.delay));
/**
* If there's an existing animation playing on this element then stop it
* before creating a new one.
*/
const map = getAnimationMap(element);
const key = animationMapKey(valueName, valueOptions.pseudoElement || "");
const currentAnimation = map.get(key);
currentAnimation && currentAnimation.stop();
animationDefinitions.push({
map,
key,
unresolvedKeyframes: valueKeyframes,
options: {
...valueOptions,
element,
name: valueName,
allowFlatten: !elementTransition.type && !elementTransition.ease,
},
});
}
}
/**
* Step 2: Resolve keyframes (read)
*/
for (let i = 0; i < animationDefinitions.length; i++) {
const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i];
const { element, name, pseudoElement } = animationOptions;
if (!pseudoElement && unresolvedKeyframes[0] === null) {
unresolvedKeyframes[0] = getComputedStyle(element, name);
}
fillWildcards(unresolvedKeyframes);
applyPxDefaults(unresolvedKeyframes, name);
/**
* If we only have one keyframe, explicitly read the initial keyframe
* from the computed style. This is to ensure consistency with WAAPI behaviour
* for restarting animations, for instance .play() after finish, when it
* has one vs two keyframes.
*/
if (!pseudoElement && unresolvedKeyframes.length < 2) {
unresolvedKeyframes.unshift(getComputedStyle(element, name));
}
animationOptions.keyframes = unresolvedKeyframes;
}
/**
* Step 3: Create new animations (write)
*/
const animations = [];
for (let i = 0; i < animationDefinitions.length; i++) {
const { map, key, options: animationOptions } = animationDefinitions[i];
const animation = new NativeAnimation(animationOptions);
map.set(key, animation);
animation.finished.finally(() => map.delete(key));
animations.push(animation);
}
return animations;
}
export { animateElements };

View File

@@ -0,0 +1,13 @@
import { GroupAnimationWithThen } from 'motion-dom';
import { createAnimationsFromSequence } from '../../sequence/create.mjs';
import { animateElements } from './animate-elements.mjs';
function animateSequence(definition, options) {
const animations = [];
createAnimationsFromSequence(definition, options).forEach(({ keyframes, transition }, element) => {
animations.push(...animateElements(element, keyframes, transition));
});
return new GroupAnimationWithThen(animations);
}
export { animateSequence };

View File

@@ -0,0 +1,12 @@
import { GroupAnimationWithThen } from 'motion-dom';
import { animateElements } from './animate-elements.mjs';
const createScopedWaapiAnimate = (scope) => {
function scopedAnimate(elementOrSelector, keyframes, options) {
return new GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope));
}
return scopedAnimate;
};
const animateMini = /*@__PURE__*/ createScopedWaapiAnimate();
export { animateMini, createScopedWaapiAnimate };

View File

@@ -0,0 +1,12 @@
const isNotNull = (value) => value !== null;
function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) {
const resolvedKeyframes = keyframes.filter(isNotNull);
const index = repeat && repeatType !== "loop" && repeat % 2 === 1
? 0
: resolvedKeyframes.length - 1;
return !index || finalKeyframe === undefined
? resolvedKeyframes[index]
: finalKeyframe;
}
export { getFinalKeyframe };

View File

@@ -0,0 +1,80 @@
import { invariant } from 'motion-utils';
import { setTarget } from '../../render/utils/setters.mjs';
import { animateVisualElement } from '../interfaces/visual-element.mjs';
function stopAnimation(visualElement) {
visualElement.values.forEach((value) => value.stop());
}
function setVariants(visualElement, variantLabels) {
const reversedLabels = [...variantLabels].reverse();
reversedLabels.forEach((key) => {
const variant = visualElement.getVariant(key);
variant && setTarget(visualElement, variant);
if (visualElement.variantChildren) {
visualElement.variantChildren.forEach((child) => {
setVariants(child, variantLabels);
});
}
});
}
function setValues(visualElement, definition) {
if (Array.isArray(definition)) {
return setVariants(visualElement, definition);
}
else if (typeof definition === "string") {
return setVariants(visualElement, [definition]);
}
else {
setTarget(visualElement, definition);
}
}
/**
* @public
*/
function animationControls() {
/**
* Track whether the host component has mounted.
*/
let hasMounted = false;
/**
* A collection of linked component animation controls.
*/
const subscribers = new Set();
const controls = {
subscribe(visualElement) {
subscribers.add(visualElement);
return () => void subscribers.delete(visualElement);
},
start(definition, transitionOverride) {
invariant(hasMounted, "controls.start() should only be called after a component has mounted. Consider calling within a useEffect hook.");
const animations = [];
subscribers.forEach((visualElement) => {
animations.push(animateVisualElement(visualElement, definition, {
transitionOverride,
}));
});
return Promise.all(animations);
},
set(definition) {
invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook.");
return subscribers.forEach((visualElement) => {
setValues(visualElement, definition);
});
},
stop() {
subscribers.forEach((visualElement) => {
stopAnimation(visualElement);
});
},
mount() {
hasMounted = true;
return () => {
hasMounted = false;
controls.stop();
};
},
};
return controls;
}
export { animationControls, setValues };

View File

@@ -0,0 +1,18 @@
"use client";
import { useConstant } from '../../utils/use-constant.mjs';
import { useUnmountEffect } from '../../utils/use-unmount-effect.mjs';
import { createScopedWaapiAnimate } from '../animators/waapi/animate-style.mjs';
function useAnimateMini() {
const scope = useConstant(() => ({
current: null, // Will be hydrated by React
animations: [],
}));
const animate = useConstant(() => createScopedWaapiAnimate(scope));
useUnmountEffect(() => {
scope.animations.forEach((animation) => animation.stop());
});
return [scope, animate];
}
export { useAnimateMini };

View File

@@ -0,0 +1,19 @@
"use client";
import { useConstant } from '../../utils/use-constant.mjs';
import { useUnmountEffect } from '../../utils/use-unmount-effect.mjs';
import { createScopedAnimate } from '../animate/index.mjs';
function useAnimate() {
const scope = useConstant(() => ({
current: null, // Will be hydrated by React
animations: [],
}));
const animate = useConstant(() => createScopedAnimate(scope));
useUnmountEffect(() => {
scope.animations.forEach((animation) => animation.stop());
scope.animations.length = 0;
});
return [scope, animate];
}
export { useAnimate };

View File

@@ -0,0 +1,65 @@
"use client";
import { useState, useLayoutEffect } from 'react';
import { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs';
import { createBox } from '../../projection/geometry/models.mjs';
import { VisualElement } from '../../render/VisualElement.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { animateVisualElement } from '../interfaces/visual-element.mjs';
const createObject = () => ({});
class StateVisualElement extends VisualElement {
constructor() {
super(...arguments);
this.measureInstanceViewportBox = createBox;
}
build() { }
resetTransform() { }
restoreTransform() { }
removeValueFromRenderState() { }
renderInstance() { }
scrapeMotionValuesFromProps() {
return createObject();
}
getBaseTargetFromProps() {
return undefined;
}
readValueFromInstance(_state, key, options) {
return options.initialState[key] || 0;
}
sortInstanceNodePosition() {
return 0;
}
}
const useVisualState = makeUseVisualState({
scrapeMotionValuesFromProps: createObject,
createRenderState: createObject,
});
/**
* This is not an officially supported API and may be removed
* on any version.
*/
function useAnimatedState(initialState) {
const [animationState, setAnimationState] = useState(initialState);
const visualState = useVisualState({}, false);
const element = useConstant(() => {
return new StateVisualElement({
props: {
onUpdate: (v) => {
setAnimationState({ ...v });
},
},
visualState,
presenceContext: null,
}, { initialState });
});
useLayoutEffect(() => {
element.mount({});
return () => element.unmount();
}, [element]);
const startAnimation = useConstant(() => (animationDefinition) => {
return animateVisualElement(element, animationDefinition);
});
return [animationState, startAnimation];
}
export { useAnimatedState };

View File

@@ -0,0 +1,42 @@
"use client";
import { useConstant } from '../../utils/use-constant.mjs';
import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';
import { animationControls } from './animation-controls.mjs';
/**
* Creates `LegacyAnimationControls`, which can be used to manually start, stop
* and sequence animations on one or more components.
*
* The returned `LegacyAnimationControls` should be passed to the `animate` property
* of the components you want to animate.
*
* These components can then be animated with the `start` method.
*
* ```jsx
* import * as React from 'react'
* import { motion, useAnimation } from 'framer-motion'
*
* export function MyComponent(props) {
* const controls = useAnimation()
*
* controls.start({
* x: 100,
* transition: { duration: 0.5 },
* })
*
* return <motion.div animate={controls} />
* }
* ```
*
* @returns Animation controller with `start` and `stop` methods
*
* @public
*/
function useAnimationControls() {
const controls = useConstant(animationControls);
useIsomorphicLayoutEffect(controls.mount, []);
return controls;
}
const useAnimation = useAnimationControls;
export { useAnimation, useAnimationControls };

View File

@@ -0,0 +1,98 @@
import { getValueTransition, makeAnimationInstant, frame, JSAnimation, AsyncMotionValueAnimation } from 'motion-dom';
import { secondsToMilliseconds, MotionGlobalConfig } from 'motion-utils';
import { getFinalKeyframe } from '../animators/waapi/utils/get-final-keyframe.mjs';
import { getDefaultTransition } from '../utils/default-transitions.mjs';
import { isTransitionDefined } from '../utils/is-transition-defined.mjs';
const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
const valueTransition = getValueTransition(transition, name) || {};
/**
* Most transition values are currently completely overwritten by value-specific
* transitions. In the future it'd be nicer to blend these transitions. But for now
* delay actually does inherit from the root transition if not value-specific.
*/
const delay = valueTransition.delay || transition.delay || 0;
/**
* Elapsed isn't a public transition option but can be passed through from
* optimized appear effects in milliseconds.
*/
let { elapsed = 0 } = transition;
elapsed = elapsed - secondsToMilliseconds(delay);
const options = {
keyframes: Array.isArray(target) ? target : [null, target],
ease: "easeOut",
velocity: value.getVelocity(),
...valueTransition,
delay: -elapsed,
onUpdate: (v) => {
value.set(v);
valueTransition.onUpdate && valueTransition.onUpdate(v);
},
onComplete: () => {
onComplete();
valueTransition.onComplete && valueTransition.onComplete();
},
name,
motionValue: value,
element: isHandoff ? undefined : element,
};
/**
* If there's no transition defined for this value, we can generate
* unique transition settings for this value.
*/
if (!isTransitionDefined(valueTransition)) {
Object.assign(options, getDefaultTransition(name, options));
}
/**
* Both WAAPI and our internal animation functions use durations
* as defined by milliseconds, while our external API defines them
* as seconds.
*/
options.duration && (options.duration = secondsToMilliseconds(options.duration));
options.repeatDelay && (options.repeatDelay = secondsToMilliseconds(options.repeatDelay));
/**
* Support deprecated way to set initial value. Prefer keyframe syntax.
*/
if (options.from !== undefined) {
options.keyframes[0] = options.from;
}
let shouldSkip = false;
if (options.type === false ||
(options.duration === 0 && !options.repeatDelay)) {
makeAnimationInstant(options);
if (options.delay === 0) {
shouldSkip = true;
}
}
if (MotionGlobalConfig.instantAnimations ||
MotionGlobalConfig.skipAnimations) {
shouldSkip = true;
makeAnimationInstant(options);
options.delay = 0;
}
/**
* If the transition type or easing has been explicitly set by the user
* then we don't want to allow flattening the animation.
*/
options.allowFlatten = !valueTransition.type && !valueTransition.ease;
/**
* If we can or must skip creating the animation, and apply only
* the final keyframe, do so. We also check once keyframes are resolved but
* this early check prevents the need to create an animation at all.
*/
if (shouldSkip && !isHandoff && value.get() !== undefined) {
const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
if (finalKeyframe !== undefined) {
frame.update(() => {
options.onUpdate(finalKeyframe);
options.onComplete();
});
return;
}
}
return valueTransition.isSync
? new JSAnimation(options)
: new AsyncMotionValueAnimation(options);
};
export { animateMotionValue };

View File

@@ -0,0 +1,83 @@
import { getValueTransition, frame, positionalKeys } from 'motion-dom';
import { setTarget } from '../../render/utils/setters.mjs';
import { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs';
import { getOptimisedAppearId } from '../optimized-appear/get-appear-id.mjs';
import { animateMotionValue } from './motion-value.mjs';
/**
* Decide whether we should block this animation. Previously, we achieved this
* just by checking whether the key was listed in protectedKeys, but this
* posed problems if an animation was triggered by afterChildren and protectedKeys
* had been set to true in the meantime.
*/
function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
needsAnimating[key] = false;
return shouldBlock;
}
function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) {
let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition;
if (transitionOverride)
transition = transitionOverride;
const animations = [];
const animationTypeState = type &&
visualElement.animationState &&
visualElement.animationState.getState()[type];
for (const key in target) {
const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null);
const valueTarget = target[key];
if (valueTarget === undefined ||
(animationTypeState &&
shouldBlockAnimation(animationTypeState, key))) {
continue;
}
const valueTransition = {
delay,
...getValueTransition(transition || {}, key),
};
/**
* If the value is already at the defined target, skip the animation.
*/
const currentValue = value.get();
if (currentValue !== undefined &&
!value.isAnimating &&
!Array.isArray(valueTarget) &&
valueTarget === currentValue &&
!valueTransition.velocity) {
continue;
}
/**
* If this is the first time a value is being animated, check
* to see if we're handling off from an existing animation.
*/
let isHandoff = false;
if (window.MotionHandoffAnimation) {
const appearId = getOptimisedAppearId(visualElement);
if (appearId) {
const startTime = window.MotionHandoffAnimation(appearId, key, frame);
if (startTime !== null) {
valueTransition.startTime = startTime;
isHandoff = true;
}
}
}
addValueToWillChange(visualElement, key);
value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && positionalKeys.has(key)
? { type: false }
: valueTransition, visualElement, isHandoff));
const animation = value.animation;
if (animation) {
animations.push(animation);
}
}
if (transitionEnd) {
Promise.all(animations).then(() => {
frame.update(() => {
transitionEnd && setTarget(visualElement, transitionEnd);
});
});
}
return animations;
}
export { animateTarget };

View File

@@ -0,0 +1,59 @@
import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';
import { calcChildStagger } from '../utils/calc-child-stagger.mjs';
import { animateTarget } from './visual-element-target.mjs';
function animateVariant(visualElement, variant, options = {}) {
const resolved = resolveVariant(visualElement, variant, options.type === "exit"
? visualElement.presenceContext?.custom
: undefined);
let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
if (options.transitionOverride) {
transition = options.transitionOverride;
}
/**
* If we have a variant, create a callback that runs it as an animation.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getAnimation = resolved
? () => Promise.all(animateTarget(visualElement, resolved, options))
: () => Promise.resolve();
/**
* If we have children, create a callback that runs all their animations.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size
? (forwardDelay = 0) => {
const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options);
}
: () => Promise.resolve();
/**
* If the transition explicitly defines a "when" option, we need to resolve either
* this animation or all children animations before playing the other.
*/
const { when } = transition;
if (when) {
const [first, last] = when === "beforeChildren"
? [getAnimation, getChildAnimations]
: [getChildAnimations, getAnimation];
return first().then(() => last());
}
else {
return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
}
}
function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
const animations = [];
for (const child of visualElement.variantChildren) {
child.notify("AnimationStart", variant);
animations.push(animateVariant(child, variant, {
...options,
delay: delay +
(typeof delayChildren === "function" ? 0 : delayChildren) +
calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection),
}).then(() => child.notify("AnimationComplete", variant)));
}
return Promise.all(animations);
}
export { animateVariant };

View File

@@ -0,0 +1,26 @@
import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';
import { animateTarget } from './visual-element-target.mjs';
import { animateVariant } from './visual-element-variant.mjs';
function animateVisualElement(visualElement, definition, options = {}) {
visualElement.notify("AnimationStart", definition);
let animation;
if (Array.isArray(definition)) {
const animations = definition.map((variant) => animateVariant(visualElement, variant, options));
animation = Promise.all(animations);
}
else if (typeof definition === "string") {
animation = animateVariant(visualElement, definition, options);
}
else {
const resolvedDefinition = typeof definition === "function"
? resolveVariant(visualElement, definition, options.custom)
: definition;
animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));
}
return animation.then(() => {
visualElement.notify("AnimationComplete", definition);
});
}
export { animateVisualElement };

View File

@@ -0,0 +1,6 @@
import { camelToDash } from '../../render/dom/utils/camel-to-dash.mjs';
const optimizedAppearDataId = "framerAppearId";
const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
export { optimizedAppearDataAttribute, optimizedAppearDataId };

View File

@@ -0,0 +1,7 @@
import { optimizedAppearDataAttribute } from './data-id.mjs';
function getOptimisedAppearId(visualElement) {
return visualElement.props[optimizedAppearDataAttribute];
}
export { getOptimisedAppearId };

View File

@@ -0,0 +1,38 @@
import { appearAnimationStore } from './store.mjs';
import { appearStoreId } from './store-id.mjs';
function handoffOptimizedAppearAnimation(elementId, valueName, frame) {
const storeId = appearStoreId(elementId, valueName);
const optimisedAnimation = appearAnimationStore.get(storeId);
if (!optimisedAnimation) {
return null;
}
const { animation, startTime } = optimisedAnimation;
function cancelAnimation() {
window.MotionCancelOptimisedAnimation?.(elementId, valueName, frame);
}
/**
* We can cancel the animation once it's finished now that we've synced
* with Motion.
*
* Prefer onfinish over finished as onfinish is backwards compatible with
* older browsers.
*/
animation.onfinish = cancelAnimation;
if (startTime === null || window.MotionHandoffIsComplete?.(elementId)) {
/**
* If the startTime is null, this animation is the Paint Ready detection animation
* and we can cancel it immediately without handoff.
*
* Or if we've already handed off the animation then we're now interrupting it.
* In which case we need to cancel it.
*/
cancelAnimation();
return null;
}
else {
return startTime;
}
}
export { handoffOptimizedAppearAnimation };

View File

@@ -0,0 +1,171 @@
import { startWaapiAnimation } from 'motion-dom';
import { noop } from 'motion-utils';
import { optimizedAppearDataId } from './data-id.mjs';
import { getOptimisedAppearId } from './get-appear-id.mjs';
import { handoffOptimizedAppearAnimation } from './handoff.mjs';
import { appearAnimationStore, appearComplete } from './store.mjs';
import { appearStoreId } from './store-id.mjs';
/**
* A single time to use across all animations to manually set startTime
* and ensure they're all in sync.
*/
let startFrameTime;
/**
* A dummy animation to detect when Chrome is ready to start
* painting the page and hold off from triggering the real animation
* until then. We only need one animation to detect paint ready.
*
* https://bugs.chromium.org/p/chromium/issues/detail?id=1406850
*/
let readyAnimation;
/**
* Keep track of animations that were suspended vs cancelled so we
* can easily resume them when we're done measuring layout.
*/
const suspendedAnimations = new Set();
function resumeSuspendedAnimations() {
suspendedAnimations.forEach((data) => {
data.animation.play();
data.animation.startTime = data.startTime;
});
suspendedAnimations.clear();
}
function startOptimizedAppearAnimation(element, name, keyframes, options, onReady) {
// Prevent optimised appear animations if Motion has already started animating.
if (window.MotionIsMounted) {
return;
}
const id = element.dataset[optimizedAppearDataId];
if (!id)
return;
window.MotionHandoffAnimation = handoffOptimizedAppearAnimation;
const storeId = appearStoreId(id, name);
if (!readyAnimation) {
readyAnimation = startWaapiAnimation(element, name, [keyframes[0], keyframes[0]],
/**
* 10 secs is basically just a super-safe duration to give Chrome
* long enough to get the animation ready.
*/
{ duration: 10000, ease: "linear" });
appearAnimationStore.set(storeId, {
animation: readyAnimation,
startTime: null,
});
/**
* If there's no readyAnimation then there's been no instantiation
* of handoff animations.
*/
window.MotionHandoffAnimation = handoffOptimizedAppearAnimation;
window.MotionHasOptimisedAnimation = (elementId, valueName) => {
if (!elementId)
return false;
/**
* Keep a map of elementIds that have started animating. We check
* via ID instead of Element because of hydration errors and
* pre-hydration checks. We also actively record IDs as they start
* animating rather than simply checking for data-appear-id as
* this attrbute might be present but not lead to an animation, for
* instance if the element's appear animation is on a different
* breakpoint.
*/
if (!valueName) {
return appearComplete.has(elementId);
}
const animationId = appearStoreId(elementId, valueName);
return Boolean(appearAnimationStore.get(animationId));
};
window.MotionHandoffMarkAsComplete = (elementId) => {
if (appearComplete.has(elementId)) {
appearComplete.set(elementId, true);
}
};
window.MotionHandoffIsComplete = (elementId) => {
return appearComplete.get(elementId) === true;
};
/**
* We only need to cancel transform animations as
* they're the ones that will interfere with the
* layout animation measurements.
*/
window.MotionCancelOptimisedAnimation = (elementId, valueName, frame, canResume) => {
const animationId = appearStoreId(elementId, valueName);
const data = appearAnimationStore.get(animationId);
if (!data)
return;
if (frame && canResume === undefined) {
/**
* Wait until the end of the subsequent frame to cancel the animation
* to ensure we don't remove the animation before the main thread has
* had a chance to resolve keyframes and render.
*/
frame.postRender(() => {
frame.postRender(() => {
data.animation.cancel();
});
});
}
else {
data.animation.cancel();
}
if (frame && canResume) {
suspendedAnimations.add(data);
frame.render(resumeSuspendedAnimations);
}
else {
appearAnimationStore.delete(animationId);
/**
* If there are no more animations left, we can remove the cancel function.
* This will let us know when we can stop checking for conflicting layout animations.
*/
if (!appearAnimationStore.size) {
window.MotionCancelOptimisedAnimation = undefined;
}
}
};
window.MotionCheckAppearSync = (visualElement, valueName, value) => {
const appearId = getOptimisedAppearId(visualElement);
if (!appearId)
return;
const valueIsOptimised = window.MotionHasOptimisedAnimation?.(appearId, valueName);
const externalAnimationValue = visualElement.props.values?.[valueName];
if (!valueIsOptimised || !externalAnimationValue)
return;
const removeSyncCheck = value.on("change", (latestValue) => {
if (externalAnimationValue.get() !== latestValue) {
window.MotionCancelOptimisedAnimation?.(appearId, valueName);
removeSyncCheck();
}
});
return removeSyncCheck;
};
}
const startAnimation = () => {
readyAnimation.cancel();
const appearAnimation = startWaapiAnimation(element, name, keyframes, options);
/**
* Record the time of the first started animation. We call performance.now() once
* here and once in handoff to ensure we're getting
* close to a frame-locked time. This keeps all animations in sync.
*/
if (startFrameTime === undefined) {
startFrameTime = performance.now();
}
appearAnimation.startTime = startFrameTime;
appearAnimationStore.set(storeId, {
animation: appearAnimation,
startTime: startFrameTime,
});
if (onReady)
onReady(appearAnimation);
};
appearComplete.set(id, false);
if (readyAnimation.ready) {
readyAnimation.ready.then(startAnimation).catch(noop);
}
else {
startAnimation();
}
}
export { startOptimizedAppearAnimation };

View File

@@ -0,0 +1,8 @@
import { transformProps } from 'motion-dom';
const appearStoreId = (elementId, valueName) => {
const key = transformProps.has(valueName) ? "transform" : valueName;
return `${elementId}: ${key}`;
};
export { appearStoreId };

View File

@@ -0,0 +1,4 @@
const appearAnimationStore = new Map();
const appearComplete = new Map();
export { appearAnimationStore, appearComplete };

View File

@@ -0,0 +1,249 @@
import { isMotionValue, defaultOffset, isGenerator, createGeneratorEasing, fillOffset } from 'motion-dom';
import { progress, secondsToMilliseconds, invariant, getEasingForSegment } from 'motion-utils';
import { resolveSubjects } from '../animate/resolve-subjects.mjs';
import { calculateRepeatDuration } from './utils/calc-repeat-duration.mjs';
import { calcNextTime } from './utils/calc-time.mjs';
import { addKeyframes } from './utils/edit.mjs';
import { normalizeTimes } from './utils/normalize-times.mjs';
import { compareByTime } from './utils/sort.mjs';
const defaultSegmentEasing = "easeInOut";
const MAX_REPEAT = 20;
function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) {
const defaultDuration = defaultTransition.duration || 0.3;
const animationDefinitions = new Map();
const sequences = new Map();
const elementCache = {};
const timeLabels = new Map();
let prevTime = 0;
let currentTime = 0;
let totalDuration = 0;
/**
* Build the timeline by mapping over the sequence array and converting
* the definitions into keyframes and offsets with absolute time values.
* These will later get converted into relative offsets in a second pass.
*/
for (let i = 0; i < sequence.length; i++) {
const segment = sequence[i];
/**
* If this is a timeline label, mark it and skip the rest of this iteration.
*/
if (typeof segment === "string") {
timeLabels.set(segment, currentTime);
continue;
}
else if (!Array.isArray(segment)) {
timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels));
continue;
}
let [subject, keyframes, transition = {}] = segment;
/**
* If a relative or absolute time value has been specified we need to resolve
* it in relation to the currentTime.
*/
if (transition.at !== undefined) {
currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels);
}
/**
* Keep track of the maximum duration in this definition. This will be
* applied to currentTime once the definition has been parsed.
*/
let maxDuration = 0;
const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => {
const valueKeyframesAsList = keyframesAsList(valueKeyframes);
const { delay = 0, times = defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition;
let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition;
/**
* Resolve stagger() if defined.
*/
const calculatedDelay = typeof delay === "function"
? delay(elementIndex, numSubjects)
: delay;
/**
* If this animation should and can use a spring, generate a spring easing function.
*/
const numKeyframes = valueKeyframesAsList.length;
const createGenerator = isGenerator(type)
? type
: generators?.[type || "keyframes"];
if (numKeyframes <= 2 && createGenerator) {
/**
* As we're creating an easing function from a spring,
* ideally we want to generate it using the real distance
* between the two keyframes. However this isn't always
* possible - in these situations we use 0-100.
*/
let absoluteDelta = 100;
if (numKeyframes === 2 &&
isNumberKeyframesArray(valueKeyframesAsList)) {
const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0];
absoluteDelta = Math.abs(delta);
}
const springTransition = { ...remainingTransition };
if (duration !== undefined) {
springTransition.duration = secondsToMilliseconds(duration);
}
const springEasing = createGeneratorEasing(springTransition, absoluteDelta, createGenerator);
ease = springEasing.ease;
duration = springEasing.duration;
}
duration ?? (duration = defaultDuration);
const startTime = currentTime + calculatedDelay;
/**
* If there's only one time offset of 0, fill in a second with length 1
*/
if (times.length === 1 && times[0] === 0) {
times[1] = 1;
}
/**
* Fill out if offset if fewer offsets than keyframes
*/
const remainder = times.length - valueKeyframesAsList.length;
remainder > 0 && fillOffset(times, remainder);
/**
* If only one value has been set, ie [1], push a null to the start of
* the keyframe array. This will let us mark a keyframe at this point
* that will later be hydrated with the previous value.
*/
valueKeyframesAsList.length === 1 &&
valueKeyframesAsList.unshift(null);
/**
* Handle repeat options
*/
if (repeat) {
invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high");
duration = calculateRepeatDuration(duration, repeat);
const originalKeyframes = [...valueKeyframesAsList];
const originalTimes = [...times];
ease = Array.isArray(ease) ? [...ease] : [ease];
const originalEase = [...ease];
for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) {
valueKeyframesAsList.push(...originalKeyframes);
for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) {
times.push(originalTimes[keyframeIndex] + (repeatIndex + 1));
ease.push(keyframeIndex === 0
? "linear"
: getEasingForSegment(originalEase, keyframeIndex - 1));
}
}
normalizeTimes(times, repeat);
}
const targetTime = startTime + duration;
/**
* Add keyframes, mapping offsets to absolute time.
*/
addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime);
maxDuration = Math.max(calculatedDelay + duration, maxDuration);
totalDuration = Math.max(targetTime, totalDuration);
};
if (isMotionValue(subject)) {
const subjectSequence = getSubjectSequence(subject, sequences);
resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence));
}
else {
const subjects = resolveSubjects(subject, keyframes, scope, elementCache);
const numSubjects = subjects.length;
/**
* For every element in this segment, process the defined values.
*/
for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) {
/**
* Cast necessary, but we know these are of this type
*/
keyframes = keyframes;
transition = transition;
const thisSubject = subjects[subjectIndex];
const subjectSequence = getSubjectSequence(thisSubject, sequences);
for (const key in keyframes) {
resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects);
}
}
}
prevTime = currentTime;
currentTime += maxDuration;
}
/**
* For every element and value combination create a new animation.
*/
sequences.forEach((valueSequences, element) => {
for (const key in valueSequences) {
const valueSequence = valueSequences[key];
/**
* Arrange all the keyframes in ascending time order.
*/
valueSequence.sort(compareByTime);
const keyframes = [];
const valueOffset = [];
const valueEasing = [];
/**
* For each keyframe, translate absolute times into
* relative offsets based on the total duration of the timeline.
*/
for (let i = 0; i < valueSequence.length; i++) {
const { at, value, easing } = valueSequence[i];
keyframes.push(value);
valueOffset.push(progress(0, totalDuration, at));
valueEasing.push(easing || "easeOut");
}
/**
* If the first keyframe doesn't land on offset: 0
* provide one by duplicating the initial keyframe. This ensures
* it snaps to the first keyframe when the animation starts.
*/
if (valueOffset[0] !== 0) {
valueOffset.unshift(0);
keyframes.unshift(keyframes[0]);
valueEasing.unshift(defaultSegmentEasing);
}
/**
* If the last keyframe doesn't land on offset: 1
* provide one with a null wildcard value. This will ensure it
* stays static until the end of the animation.
*/
if (valueOffset[valueOffset.length - 1] !== 1) {
valueOffset.push(1);
keyframes.push(null);
}
if (!animationDefinitions.has(element)) {
animationDefinitions.set(element, {
keyframes: {},
transition: {},
});
}
const definition = animationDefinitions.get(element);
definition.keyframes[key] = keyframes;
definition.transition[key] = {
...defaultTransition,
duration: totalDuration,
ease: valueEasing,
times: valueOffset,
...sequenceTransition,
};
}
});
return animationDefinitions;
}
function getSubjectSequence(subject, sequences) {
!sequences.has(subject) && sequences.set(subject, {});
return sequences.get(subject);
}
function getValueSequence(name, sequences) {
if (!sequences[name])
sequences[name] = [];
return sequences[name];
}
function keyframesAsList(keyframes) {
return Array.isArray(keyframes) ? keyframes : [keyframes];
}
function getValueTransition(transition, key) {
return transition && transition[key]
? {
...transition,
...transition[key],
}
: { ...transition };
}
const isNumber = (keyframe) => typeof keyframe === "number";
const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber);
export { createAnimationsFromSequence, getValueTransition };

View File

@@ -0,0 +1,5 @@
function calculateRepeatDuration(duration, repeat, _repeatDelay) {
return duration * (repeat + 1);
}
export { calculateRepeatDuration };

View File

@@ -0,0 +1,23 @@
/**
* Given a absolute or relative time definition and current/prev time state of the sequence,
* calculate an absolute time for the next keyframes.
*/
function calcNextTime(current, next, prev, labels) {
if (typeof next === "number") {
return next;
}
else if (next.startsWith("-") || next.startsWith("+")) {
return Math.max(0, current + parseFloat(next));
}
else if (next === "<") {
return prev;
}
else if (next.startsWith("<")) {
return Math.max(0, prev + parseFloat(next.slice(1)));
}
else {
return labels.get(next) ?? current;
}
}
export { calcNextTime };

View File

@@ -0,0 +1,30 @@
import { mixNumber } from 'motion-dom';
import { getEasingForSegment, removeItem } from 'motion-utils';
function eraseKeyframes(sequence, startTime, endTime) {
for (let i = 0; i < sequence.length; i++) {
const keyframe = sequence[i];
if (keyframe.at > startTime && keyframe.at < endTime) {
removeItem(sequence, keyframe);
// If we remove this item we have to push the pointer back one
i--;
}
}
}
function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) {
/**
* Erase every existing value between currentTime and targetTime,
* this will essentially splice this timeline into any currently
* defined ones.
*/
eraseKeyframes(sequence, startTime, endTime);
for (let i = 0; i < keyframes.length; i++) {
sequence.push({
value: keyframes[i],
at: mixNumber(startTime, endTime, offset[i]),
easing: getEasingForSegment(easing, i),
});
}
}
export { addKeyframes, eraseKeyframes };

View File

@@ -0,0 +1,13 @@
/**
* Take an array of times that represent repeated keyframes. For instance
* if we have original times of [0, 0.5, 1] then our repeated times will
* be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back
* down to a 0-1 scale.
*/
function normalizeTimes(times, repeat) {
for (let i = 0; i < times.length; i++) {
times[i] = times[i] / (repeat + 1);
}
}
export { normalizeTimes };

View File

@@ -0,0 +1,14 @@
function compareByTime(a, b) {
if (a.at === b.at) {
if (a.value === null)
return 1;
if (b.value === null)
return -1;
return 0;
}
else {
return a.at - b.at;
}
}
export { compareByTime };

View File

@@ -0,0 +1,15 @@
function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) {
const index = Array.from(children)
.sort((a, b) => a.sortNodePosition(b))
.indexOf(child);
const numChildren = children.size;
const maxStaggerDuration = (numChildren - 1) * staggerChildren;
const delayIsFunction = typeof delayChildren === "function";
return delayIsFunction
? delayChildren(index, numChildren)
: staggerDirection === 1
? index * staggerChildren
: maxStaggerDuration - index * staggerChildren;
}
export { calcChildStagger };

View File

@@ -0,0 +1,44 @@
import { isSVGElement, isSVGSVGElement } from 'motion-dom';
import { HTMLVisualElement } from '../../render/html/HTMLVisualElement.mjs';
import { ObjectVisualElement } from '../../render/object/ObjectVisualElement.mjs';
import { visualElementStore } from '../../render/store.mjs';
import { SVGVisualElement } from '../../render/svg/SVGVisualElement.mjs';
function createDOMVisualElement(element) {
const options = {
presenceContext: null,
props: {},
visualState: {
renderState: {
transform: {},
transformOrigin: {},
style: {},
vars: {},
attrs: {},
},
latestValues: {},
},
};
const node = isSVGElement(element) && !isSVGSVGElement(element)
? new SVGVisualElement(options)
: new HTMLVisualElement(options);
node.mount(element);
visualElementStore.set(element, node);
}
function createObjectVisualElement(subject) {
const options = {
presenceContext: null,
props: {},
visualState: {
renderState: {
output: {},
},
latestValues: {},
},
};
const node = new ObjectVisualElement(options);
node.mount(subject);
visualElementStore.set(subject, node);
}
export { createDOMVisualElement, createObjectVisualElement };

View File

@@ -0,0 +1,40 @@
import { transformProps } from 'motion-dom';
const underDampedSpring = {
type: "spring",
stiffness: 500,
damping: 25,
restSpeed: 10,
};
const criticallyDampedSpring = (target) => ({
type: "spring",
stiffness: 550,
damping: target === 0 ? 2 * Math.sqrt(550) : 30,
restSpeed: 10,
});
const keyframesTransition = {
type: "keyframes",
duration: 0.8,
};
/**
* Default easing curve is a slightly shallower version of
* the default browser easing curve.
*/
const ease = {
type: "keyframes",
ease: [0.25, 0.1, 0.35, 1],
duration: 0.3,
};
const getDefaultTransition = (valueKey, { keyframes }) => {
if (keyframes.length > 2) {
return keyframesTransition;
}
else if (transformProps.has(valueKey)) {
return valueKey.startsWith("scale")
? criticallyDampedSpring(keyframes[1])
: underDampedSpring;
}
return ease;
};
export { getDefaultTransition };

View File

@@ -0,0 +1,7 @@
function isAnimationControls(v) {
return (v !== null &&
typeof v === "object" &&
typeof v.start === "function");
}
export { isAnimationControls };

View File

@@ -0,0 +1,5 @@
function isDOMKeyframes(keyframes) {
return typeof keyframes === "object" && !Array.isArray(keyframes);
}
export { isDOMKeyframes };

View File

@@ -0,0 +1,5 @@
const isKeyframesTarget = (v) => {
return Array.isArray(v);
};
export { isKeyframesTarget };

View File

@@ -0,0 +1,10 @@
/**
* Decide whether a transition is defined on a given Transition.
* This filters out orchestration options and returns true
* if any options are left.
*/
function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) {
return !!Object.keys(transition).length;
}
export { isTransitionDefined };

1
node_modules/framer-motion/dist/es/client.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview } from './render/components/motion/elements.mjs';

View File

@@ -0,0 +1,90 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { isHTMLElement } from 'motion-dom';
import * as React from 'react';
import { useId, useRef, useContext, useInsertionEffect } from 'react';
import { MotionConfigContext } from '../../context/MotionConfigContext.mjs';
import { useComposedRefs } from '../../utils/use-composed-ref.mjs';
/**
* Measurement functionality has to be within a separate component
* to leverage snapshot lifecycle.
*/
class PopChildMeasure extends React.Component {
getSnapshotBeforeUpdate(prevProps) {
const element = this.props.childRef.current;
if (element && prevProps.isPresent && !this.props.isPresent) {
const parent = element.offsetParent;
const parentWidth = isHTMLElement(parent)
? parent.offsetWidth || 0
: 0;
const size = this.props.sizeRef.current;
size.height = element.offsetHeight || 0;
size.width = element.offsetWidth || 0;
size.top = element.offsetTop;
size.left = element.offsetLeft;
size.right = parentWidth - size.width - size.left;
}
return null;
}
/**
* Required with getSnapshotBeforeUpdate to stop React complaining.
*/
componentDidUpdate() { }
render() {
return this.props.children;
}
}
function PopChild({ children, isPresent, anchorX, root }) {
const id = useId();
const ref = useRef(null);
const size = useRef({
width: 0,
height: 0,
top: 0,
left: 0,
right: 0,
});
const { nonce } = useContext(MotionConfigContext);
const composedRef = useComposedRefs(ref, children?.ref);
/**
* We create and inject a style block so we can apply this explicit
* sizing in a non-destructive manner by just deleting the style block.
*
* We can't apply size via render as the measurement happens
* in getSnapshotBeforeUpdate (post-render), likewise if we apply the
* styles directly on the DOM node, we might be overwriting
* styles set via the style prop.
*/
useInsertionEffect(() => {
const { width, height, top, left, right } = size.current;
if (isPresent || !ref.current || !width || !height)
return;
const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`;
ref.current.dataset.motionPopId = id;
const style = document.createElement("style");
if (nonce)
style.nonce = nonce;
const parent = root ?? document.head;
parent.appendChild(style);
if (style.sheet) {
style.sheet.insertRule(`
[data-motion-pop-id="${id}"] {
position: absolute !important;
width: ${width}px !important;
height: ${height}px !important;
${x}px !important;
top: ${top}px !important;
}
`);
}
return () => {
if (parent.contains(style)) {
parent.removeChild(style);
}
};
}, [isPresent]);
return (jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React.cloneElement(children, { ref: composedRef }) }));
}
export { PopChild };

View File

@@ -0,0 +1,64 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useId, useMemo } from 'react';
import { PresenceContext } from '../../context/PresenceContext.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { PopChild } from './PopChild.mjs';
const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, root }) => {
const presenceChildren = useConstant(newChildrenMap);
const id = useId();
let isReusedContext = true;
let context = useMemo(() => {
isReusedContext = false;
return {
id,
initial,
isPresent,
custom,
onExitComplete: (childId) => {
presenceChildren.set(childId, true);
for (const isComplete of presenceChildren.values()) {
if (!isComplete)
return; // can stop searching when any is incomplete
}
onExitComplete && onExitComplete();
},
register: (childId) => {
presenceChildren.set(childId, false);
return () => presenceChildren.delete(childId);
},
};
}, [isPresent, presenceChildren, onExitComplete]);
/**
* If the presence of a child affects the layout of the components around it,
* we want to make a new context value to ensure they get re-rendered
* so they can detect that layout change.
*/
if (presenceAffectsLayout && isReusedContext) {
context = { ...context };
}
useMemo(() => {
presenceChildren.forEach((_, key) => presenceChildren.set(key, false));
}, [isPresent]);
/**
* If there's no `motion` components to fire exit animations, we want to remove this
* component immediately.
*/
React.useEffect(() => {
!isPresent &&
!presenceChildren.size &&
onExitComplete &&
onExitComplete();
}, [isPresent]);
if (mode === "popLayout") {
children = (jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, root: root, children: children }));
}
return (jsx(PresenceContext.Provider, { value: context, children: children }));
};
function newChildrenMap() {
return new Map();
}
export { PresenceChild };

View File

@@ -0,0 +1,166 @@
"use client";
import { jsx, Fragment } from 'react/jsx-runtime';
import { useMemo, useRef, useState, useContext } from 'react';
import { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';
import { PresenceChild } from './PresenceChild.mjs';
import { usePresence } from './use-presence.mjs';
import { onlyElements, getChildKey } from './utils.mjs';
/**
* `AnimatePresence` enables the animation of components that have been removed from the tree.
*
* When adding/removing more than a single child, every child **must** be given a unique `key` prop.
*
* Any `motion` components that have an `exit` property defined will animate out when removed from
* the tree.
*
* ```jsx
* import { motion, AnimatePresence } from 'framer-motion'
*
* export const Items = ({ items }) => (
* <AnimatePresence>
* {items.map(item => (
* <motion.div
* key={item.id}
* initial={{ opacity: 0 }}
* animate={{ opacity: 1 }}
* exit={{ opacity: 0 }}
* />
* ))}
* </AnimatePresence>
* )
* ```
*
* You can sequence exit animations throughout a tree using variants.
*
* If a child contains multiple `motion` components with `exit` props, it will only unmount the child
* once all `motion` components have finished animating out. Likewise, any components using
* `usePresence` all need to call `safeToRemove`.
*
* @public
*/
const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", root }) => {
const [isParentPresent, safeToRemove] = usePresence(propagate);
/**
* Filter any children that aren't ReactElements. We can only track components
* between renders with a props.key.
*/
const presentChildren = useMemo(() => onlyElements(children), [children]);
/**
* Track the keys of the currently rendered children. This is used to
* determine which children are exiting.
*/
const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey);
/**
* If `initial={false}` we only want to pass this to components in the first render.
*/
const isInitialRender = useRef(true);
/**
* A ref containing the currently present children. When all exit animations
* are complete, we use this to re-render the component with the latest children
* *committed* rather than the latest children *rendered*.
*/
const pendingPresentChildren = useRef(presentChildren);
/**
* Track which exiting children have finished animating out.
*/
const exitComplete = useConstant(() => new Map());
/**
* Save children to render as React state. To ensure this component is concurrent-safe,
* we check for exiting children via an effect.
*/
const [diffedChildren, setDiffedChildren] = useState(presentChildren);
const [renderedChildren, setRenderedChildren] = useState(presentChildren);
useIsomorphicLayoutEffect(() => {
isInitialRender.current = false;
pendingPresentChildren.current = presentChildren;
/**
* Update complete status of exiting children.
*/
for (let i = 0; i < renderedChildren.length; i++) {
const key = getChildKey(renderedChildren[i]);
if (!presentKeys.includes(key)) {
if (exitComplete.get(key) !== true) {
exitComplete.set(key, false);
}
}
else {
exitComplete.delete(key);
}
}
}, [renderedChildren, presentKeys.length, presentKeys.join("-")]);
const exitingChildren = [];
if (presentChildren !== diffedChildren) {
let nextChildren = [...presentChildren];
/**
* Loop through all the currently rendered components and decide which
* are exiting.
*/
for (let i = 0; i < renderedChildren.length; i++) {
const child = renderedChildren[i];
const key = getChildKey(child);
if (!presentKeys.includes(key)) {
nextChildren.splice(i, 0, child);
exitingChildren.push(child);
}
}
/**
* If we're in "wait" mode, and we have exiting children, we want to
* only render these until they've all exited.
*/
if (mode === "wait" && exitingChildren.length) {
nextChildren = exitingChildren;
}
setRenderedChildren(onlyElements(nextChildren));
setDiffedChildren(presentChildren);
/**
* Early return to ensure once we've set state with the latest diffed
* children, we can immediately re-render.
*/
return null;
}
if (process.env.NODE_ENV !== "production" &&
mode === "wait" &&
renderedChildren.length > 1) {
console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);
}
/**
* If we've been provided a forceRender function by the LayoutGroupContext,
* we can use it to force a re-render amongst all surrounding components once
* all components have finished animating out.
*/
const { forceRender } = useContext(LayoutGroupContext);
return (jsx(Fragment, { children: renderedChildren.map((child) => {
const key = getChildKey(child);
const isPresent = propagate && !isParentPresent
? false
: presentChildren === renderedChildren ||
presentKeys.includes(key);
const onExit = () => {
if (exitComplete.has(key)) {
exitComplete.set(key, true);
}
else {
return;
}
let isEveryExitComplete = true;
exitComplete.forEach((isExitComplete) => {
if (!isExitComplete)
isEveryExitComplete = false;
});
if (isEveryExitComplete) {
forceRender?.();
setRenderedChildren(pendingPresentChildren.current);
propagate && safeToRemove?.();
onExitComplete && onExitComplete();
}
};
return (jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial
? undefined
: false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, root: root, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key));
}) }));
};
export { AnimatePresence };

View File

@@ -0,0 +1,10 @@
"use client";
import { useContext } from 'react';
import { PresenceContext } from '../../context/PresenceContext.mjs';
function usePresenceData() {
const context = useContext(PresenceContext);
return context ? context.custom : undefined;
}
export { usePresenceData };

View File

@@ -0,0 +1,71 @@
"use client";
import { useContext, useId, useEffect, useCallback } from 'react';
import { PresenceContext } from '../../context/PresenceContext.mjs';
/**
* When a component is the child of `AnimatePresence`, it can use `usePresence`
* to access information about whether it's still present in the React tree.
*
* ```jsx
* import { usePresence } from "framer-motion"
*
* export const Component = () => {
* const [isPresent, safeToRemove] = usePresence()
*
* useEffect(() => {
* !isPresent && setTimeout(safeToRemove, 1000)
* }, [isPresent])
*
* return <div />
* }
* ```
*
* If `isPresent` is `false`, it means that a component has been removed the tree, but
* `AnimatePresence` won't really remove it until `safeToRemove` has been called.
*
* @public
*/
function usePresence(subscribe = true) {
const context = useContext(PresenceContext);
if (context === null)
return [true, null];
const { isPresent, onExitComplete, register } = context;
// It's safe to call the following hooks conditionally (after an early return) because the context will always
// either be null or non-null for the lifespan of the component.
const id = useId();
useEffect(() => {
if (subscribe) {
return register(id);
}
}, [subscribe]);
const safeToRemove = useCallback(() => subscribe && onExitComplete && onExitComplete(id), [id, onExitComplete, subscribe]);
return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
}
/**
* Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present.
* There is no `safeToRemove` function.
*
* ```jsx
* import { useIsPresent } from "framer-motion"
*
* export const Component = () => {
* const isPresent = useIsPresent()
*
* useEffect(() => {
* !isPresent && console.log("I've been removed!")
* }, [isPresent])
*
* return <div />
* }
* ```
*
* @public
*/
function useIsPresent() {
return isPresent(useContext(PresenceContext));
}
function isPresent(context) {
return context === null ? true : context.isPresent;
}
export { isPresent, useIsPresent, usePresence };

View File

@@ -0,0 +1,14 @@
import { Children, isValidElement } from 'react';
const getChildKey = (child) => child.key || "";
function onlyElements(children) {
const filtered = [];
// We use forEach here instead of map as map mutates the component key by preprending `.$`
Children.forEach(children, (child) => {
if (isValidElement(child))
filtered.push(child);
});
return filtered;
}
export { getChildKey, onlyElements };

View File

@@ -0,0 +1,16 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { invariant } from 'motion-utils';
import * as React from 'react';
import { useConstant } from '../utils/use-constant.mjs';
import { LayoutGroup } from './LayoutGroup/index.mjs';
let id = 0;
const AnimateSharedLayout = ({ children }) => {
React.useEffect(() => {
invariant(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations");
}, []);
return (jsx(LayoutGroup, { id: useConstant(() => `asl-${id++}`), children: children }));
};
export { AnimateSharedLayout };

View File

@@ -0,0 +1,32 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { useContext, useRef, useMemo } from 'react';
import { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs';
import { DeprecatedLayoutGroupContext } from '../../context/DeprecatedLayoutGroupContext.mjs';
import { useForceUpdate } from '../../utils/use-force-update.mjs';
import { nodeGroup } from '../../projection/node/group.mjs';
const shouldInheritGroup = (inherit) => inherit === true;
const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id";
const LayoutGroup = ({ children, id, inherit = true }) => {
const layoutGroupContext = useContext(LayoutGroupContext);
const deprecatedLayoutGroupContext = useContext(DeprecatedLayoutGroupContext);
const [forceRender, key] = useForceUpdate();
const context = useRef(null);
const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext;
if (context.current === null) {
if (shouldInheritId(inherit) && upstreamId) {
id = id ? upstreamId + "-" + id : upstreamId;
}
context.current = {
id,
group: shouldInheritGroup(inherit)
? layoutGroupContext.group || nodeGroup()
: nodeGroup(),
};
}
const memoizedContext = useMemo(() => ({ ...context.current, forceRender }), [key]);
return (jsx(LayoutGroupContext.Provider, { value: memoizedContext, children: children }));
};
export { LayoutGroup };

View File

@@ -0,0 +1,68 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect } from 'react';
import { LazyContext } from '../../context/LazyContext.mjs';
import { loadFeatures } from '../../motion/features/load-features.mjs';
/**
* Used in conjunction with the `m` component to reduce bundle size.
*
* `m` is a version of the `motion` component that only loads functionality
* critical for the initial render.
*
* `LazyMotion` can then be used to either synchronously or asynchronously
* load animation and gesture support.
*
* ```jsx
* // Synchronous loading
* import { LazyMotion, m, domAnimation } from "framer-motion"
*
* function App() {
* return (
* <LazyMotion features={domAnimation}>
* <m.div animate={{ scale: 2 }} />
* </LazyMotion>
* )
* }
*
* // Asynchronous loading
* import { LazyMotion, m } from "framer-motion"
*
* function App() {
* return (
* <LazyMotion features={() => import('./path/to/domAnimation')}>
* <m.div animate={{ scale: 2 }} />
* </LazyMotion>
* )
* }
* ```
*
* @public
*/
function LazyMotion({ children, features, strict = false }) {
const [, setIsLoaded] = useState(!isLazyBundle(features));
const loadedRenderer = useRef(undefined);
/**
* If this is a synchronous load, load features immediately
*/
if (!isLazyBundle(features)) {
const { renderer, ...loadedFeatures } = features;
loadedRenderer.current = renderer;
loadFeatures(loadedFeatures);
}
useEffect(() => {
if (isLazyBundle(features)) {
features().then(({ renderer, ...loadedFeatures }) => {
loadFeatures(loadedFeatures);
loadedRenderer.current = renderer;
setIsLoaded(true);
});
}
}, []);
return (jsx(LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict }, children: children }));
}
function isLazyBundle(features) {
return typeof features === "function";
}
export { LazyMotion };

View File

@@ -0,0 +1,48 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { useContext, useMemo } from 'react';
import { MotionConfigContext } from '../../context/MotionConfigContext.mjs';
import { loadExternalIsValidProp } from '../../render/dom/utils/filter-props.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
/**
* `MotionConfig` is used to set configuration options for all children `motion` components.
*
* ```jsx
* import { motion, MotionConfig } from "framer-motion"
*
* export function App() {
* return (
* <MotionConfig transition={{ type: "spring" }}>
* <motion.div animate={{ x: 100 }} />
* </MotionConfig>
* )
* }
* ```
*
* @public
*/
function MotionConfig({ children, isValidProp, ...config }) {
isValidProp && loadExternalIsValidProp(isValidProp);
/**
* Inherit props from any parent MotionConfig components
*/
config = { ...useContext(MotionConfigContext), ...config };
/**
* Don't allow isStatic to change between renders as it affects how many hooks
* motion components fire.
*/
config.isStatic = useConstant(() => config.isStatic);
/**
* Creating a new config context object will re-render every `motion` component
* every time it renders. So we only want to create a new one sparingly.
*/
const context = useMemo(() => config, [
JSON.stringify(config.transition),
config.transformPagePoint,
config.reducedMotion,
]);
return (jsx(MotionConfigContext.Provider, { value: context, children: children }));
}
export { MotionConfig };

View File

@@ -0,0 +1,53 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { invariant } from 'motion-utils';
import { forwardRef, useRef, useEffect } from 'react';
import { ReorderContext } from '../../context/ReorderContext.mjs';
import { motion } from '../../render/components/motion/proxy.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { checkReorder } from './utils/check-reorder.mjs';
function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) {
const Component = useConstant(() => motion[as]);
const order = [];
const isReordering = useRef(false);
invariant(Boolean(values), "Reorder.Group must be provided a values prop", "reorder-values");
const context = {
axis,
registerItem: (value, layout) => {
// If the entry was already added, update it rather than adding it again
const idx = order.findIndex((entry) => value === entry.value);
if (idx !== -1) {
order[idx].layout = layout[axis];
}
else {
order.push({ value: value, layout: layout[axis] });
}
order.sort(compareMin);
},
updateOrder: (item, offset, velocity) => {
if (isReordering.current)
return;
const newOrder = checkReorder(order, item, offset, velocity);
if (order !== newOrder) {
isReordering.current = true;
onReorder(newOrder
.map(getValue)
.filter((value) => values.indexOf(value) !== -1));
}
},
};
useEffect(() => {
isReordering.current = false;
});
return (jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsx(ReorderContext.Provider, { value: context, children: children }) }));
}
const ReorderGroup = /*@__PURE__*/ forwardRef(ReorderGroupComponent);
function getValue(item) {
return item.value;
}
function compareMin(a, b) {
return a.layout.min - b.layout.min;
}
export { ReorderGroup, ReorderGroupComponent };

View File

@@ -0,0 +1,34 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { isMotionValue } from 'motion-dom';
import { invariant } from 'motion-utils';
import { forwardRef, useContext } from 'react';
import { ReorderContext } from '../../context/ReorderContext.mjs';
import { motion } from '../../render/components/motion/proxy.mjs';
import { useConstant } from '../../utils/use-constant.mjs';
import { useMotionValue } from '../../value/use-motion-value.mjs';
import { useTransform } from '../../value/use-transform.mjs';
function useDefaultMotionValue(value, defaultValue = 0) {
return isMotionValue(value) ? value : useMotionValue(defaultValue);
}
function ReorderItemComponent({ children, style = {}, value, as = "li", onDrag, layout = true, ...props }, externalRef) {
const Component = useConstant(() => motion[as]);
const context = useContext(ReorderContext);
const point = {
x: useDefaultMotionValue(style.x),
y: useDefaultMotionValue(style.y),
};
const zIndex = useTransform([point.x, point.y], ([latestX, latestY]) => latestX || latestY ? 1 : "unset");
invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group", "reorder-item-child");
const { axis, registerItem, updateOrder } = context;
return (jsx(Component, { drag: axis, ...props, dragSnapToOrigin: true, style: { ...style, x: point.x, y: point.y, zIndex }, layout: layout, onDrag: (event, gesturePoint) => {
const { velocity } = gesturePoint;
velocity[axis] &&
updateOrder(value, point[axis].get(), velocity[axis]);
onDrag && onDrag(event, gesturePoint);
}, onLayoutMeasure: (measured) => registerItem(value, measured), ref: externalRef, ignoreStrict: true, children: children }));
}
const ReorderItem = /*@__PURE__*/ forwardRef(ReorderItemComponent);
export { ReorderItem, ReorderItemComponent };

View File

@@ -0,0 +1,2 @@
export { ReorderGroup as Group } from './Group.mjs';
export { ReorderItem as Item } from './Item.mjs';

View File

@@ -0,0 +1,24 @@
import { mixNumber } from 'motion-dom';
import { moveItem } from 'motion-utils';
function checkReorder(order, value, offset, velocity) {
if (!velocity)
return order;
const index = order.findIndex((item) => item.value === value);
if (index === -1)
return order;
const nextOffset = velocity > 0 ? 1 : -1;
const nextItem = order[index + nextOffset];
if (!nextItem)
return order;
const item = order[index];
const nextLayout = nextItem.layout;
const nextItemCenter = mixNumber(nextLayout.min, nextLayout.max, 0.5);
if ((nextOffset === 1 && item.layout.max + offset > nextItemCenter) ||
(nextOffset === -1 && item.layout.min + offset < nextItemCenter)) {
return moveItem(order, index, index + nextOffset);
}
return order;
}
export { checkReorder };

View File

@@ -0,0 +1,11 @@
"use client";
import { createContext } from 'react';
/**
* Note: Still used by components generated by old versions of Framer
*
* @deprecated
*/
const DeprecatedLayoutGroupContext = createContext(null);
export { DeprecatedLayoutGroupContext };

View File

@@ -0,0 +1,6 @@
"use client";
import { createContext } from 'react';
const LayoutGroupContext = createContext({});
export { LayoutGroupContext };

View File

@@ -0,0 +1,6 @@
"use client";
import { createContext } from 'react';
const LazyContext = createContext({ strict: false });
export { LazyContext };

View File

@@ -0,0 +1,13 @@
"use client";
import { createContext } from 'react';
/**
* @public
*/
const MotionConfigContext = createContext({
transformPagePoint: (p) => p,
isStatic: false,
reducedMotion: "never",
});
export { MotionConfigContext };

View File

@@ -0,0 +1,14 @@
"use client";
import { useContext, useMemo } from 'react';
import { MotionContext } from './index.mjs';
import { getCurrentTreeVariants } from './utils.mjs';
function useCreateMotionContext(props) {
const { initial, animate } = getCurrentTreeVariants(props, useContext(MotionContext));
return useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);
}
function variantLabelsAsDependency(prop) {
return Array.isArray(prop) ? prop.join(" ") : prop;
}
export { useCreateMotionContext };

View File

@@ -0,0 +1,6 @@
"use client";
import { createContext } from 'react';
const MotionContext = /* @__PURE__ */ createContext({});
export { MotionContext };

View File

@@ -0,0 +1,17 @@
import { isControllingVariants } from '../../render/utils/is-controlling-variants.mjs';
import { isVariantLabel } from '../../render/utils/is-variant-label.mjs';
function getCurrentTreeVariants(props, context) {
if (isControllingVariants(props)) {
const { initial, animate } = props;
return {
initial: initial === false || isVariantLabel(initial)
? initial
: undefined,
animate: isVariantLabel(animate) ? animate : undefined,
};
}
return props.inherit !== false ? context : {};
}
export { getCurrentTreeVariants };

View File

@@ -0,0 +1,10 @@
"use client";
import { createContext } from 'react';
/**
* @public
*/
const PresenceContext =
/* @__PURE__ */ createContext(null);
export { PresenceContext };

View File

@@ -0,0 +1,6 @@
"use client";
import { createContext } from 'react';
const ReorderContext = createContext(null);
export { ReorderContext };

View File

@@ -0,0 +1,9 @@
"use client";
import { createContext } from 'react';
/**
* Internal, exported only for usage in Framer
*/
const SwitchLayoutGroupContext = createContext({});
export { SwitchLayoutGroupContext };

1
node_modules/framer-motion/dist/es/debug.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export { recordStats } from 'motion-dom';

2
node_modules/framer-motion/dist/es/dom-mini.mjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { animateSequence } from './animation/animators/waapi/animate-sequence.mjs';
export { animateMini as animate } from './animation/animators/waapi/animate-style.mjs';

9
node_modules/framer-motion/dist/es/dom.mjs generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export * from 'motion-dom';
export * from 'motion-utils';
export { animate, createScopedAnimate } from './animation/animate/index.mjs';
export { animateMini } from './animation/animators/waapi/animate-style.mjs';
export { scroll } from './render/dom/scroll/index.mjs';
export { scrollInfo } from './render/dom/scroll/track.mjs';
export { inView } from './render/dom/viewport/index.mjs';
export { delayInSeconds as delay } from './utils/delay.mjs';
export { distance, distance2D } from './utils/distance.mjs';

View File

@@ -0,0 +1,6 @@
function addDomEvent(target, eventName, handler, options = { passive: true }) {
target.addEventListener(eventName, handler, options);
return () => target.removeEventListener(eventName, handler);
}
export { addDomEvent };

View File

@@ -0,0 +1,8 @@
import { addDomEvent } from './add-dom-event.mjs';
import { addPointerInfo } from './event-info.mjs';
function addPointerEvent(target, eventName, handler, options) {
return addDomEvent(target, eventName, addPointerInfo(handler), options);
}
export { addPointerEvent };

View File

@@ -0,0 +1,15 @@
import { isPrimaryPointer } from 'motion-dom';
function extractEventInfo(event) {
return {
point: {
x: event.pageX,
y: event.pageY,
},
};
}
const addPointerInfo = (handler) => {
return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event));
};
export { addPointerInfo, extractEventInfo };

View File

@@ -0,0 +1,35 @@
"use client";
import { useEffect } from 'react';
import { addDomEvent } from './add-dom-event.mjs';
/**
* Attaches an event listener directly to the provided DOM element.
*
* Bypassing React's event system can be desirable, for instance when attaching non-passive
* event handlers.
*
* ```jsx
* const ref = useRef(null)
*
* useDomEvent(ref, 'wheel', onWheel, { passive: false })
*
* return <div ref={ref} />
* ```
*
* @param ref - React.RefObject that's been provided to the element you want to bind the listener to.
* @param eventName - Name of the event you want listen for.
* @param handler - Function to fire when receiving the event.
* @param options - Options to pass to `Event.addEventListener`.
*
* @public
*/
function useDomEvent(ref, eventName, handler, options) {
useEffect(() => {
const element = ref.current;
if (handler && element) {
return addDomEvent(element, eventName, handler, options);
}
}, [ref, eventName, handler, options]);
}
export { useDomEvent };

View File

@@ -0,0 +1,498 @@
import { frame, mixNumber, setDragLock, percent } from 'motion-dom';
import { invariant } from 'motion-utils';
import { animateMotionValue } from '../../animation/interfaces/motion-value.mjs';
import { addDomEvent } from '../../events/add-dom-event.mjs';
import { addPointerEvent } from '../../events/add-pointer-event.mjs';
import { extractEventInfo } from '../../events/event-info.mjs';
import { convertBoxToBoundingBox, convertBoundingBoxToBox } from '../../projection/geometry/conversion.mjs';
import { calcLength } from '../../projection/geometry/delta-calc.mjs';
import { createBox } from '../../projection/geometry/models.mjs';
import { eachAxis } from '../../projection/utils/each-axis.mjs';
import { measurePageBox } from '../../projection/utils/measure.mjs';
import { getContextWindow } from '../../utils/get-context-window.mjs';
import { isRefObject } from '../../utils/is-ref-object.mjs';
import { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs';
import { PanSession } from '../pan/PanSession.mjs';
import { applyConstraints, calcRelativeConstraints, resolveDragElastic, rebaseAxisConstraints, calcViewportConstraints, calcOrigin, defaultElastic } from './utils/constraints.mjs';
const elementDragControls = new WeakMap();
class VisualElementDragControls {
constructor(visualElement) {
this.openDragLock = null;
this.isDragging = false;
this.currentDirection = null;
this.originPoint = { x: 0, y: 0 };
/**
* The permitted boundaries of travel, in pixels.
*/
this.constraints = false;
this.hasMutatedConstraints = false;
/**
* The per-axis resolved elastic values.
*/
this.elastic = createBox();
/**
* The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments.
*/
this.latestPointerEvent = null;
/**
* The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments.
*/
this.latestPanInfo = null;
this.visualElement = visualElement;
}
start(originEvent, { snapToCursor = false, distanceThreshold } = {}) {
/**
* Don't start dragging if this component is exiting
*/
const { presenceContext } = this.visualElement;
if (presenceContext && presenceContext.isPresent === false)
return;
const onSessionStart = (event) => {
const { dragSnapToOrigin } = this.getProps();
// Stop or pause any animations on both axis values immediately. This allows the user to throw and catch
// the component.
dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation();
if (snapToCursor) {
this.snapToCursor(extractEventInfo(event).point);
}
};
const onStart = (event, info) => {
// Attempt to grab the global drag gesture lock - maybe make this part of PanSession
const { drag, dragPropagation, onDragStart } = this.getProps();
if (drag && !dragPropagation) {
if (this.openDragLock)
this.openDragLock();
this.openDragLock = setDragLock(drag);
// If we don 't have the lock, don't start dragging
if (!this.openDragLock)
return;
}
this.latestPointerEvent = event;
this.latestPanInfo = info;
this.isDragging = true;
this.currentDirection = null;
this.resolveConstraints();
if (this.visualElement.projection) {
this.visualElement.projection.isAnimationBlocked = true;
this.visualElement.projection.target = undefined;
}
/**
* Record gesture origin
*/
eachAxis((axis) => {
let current = this.getAxisMotionValue(axis).get() || 0;
/**
* If the MotionValue is a percentage value convert to px
*/
if (percent.test(current)) {
const { projection } = this.visualElement;
if (projection && projection.layout) {
const measuredAxis = projection.layout.layoutBox[axis];
if (measuredAxis) {
const length = calcLength(measuredAxis);
current = length * (parseFloat(current) / 100);
}
}
}
this.originPoint[axis] = current;
});
// Fire onDragStart event
if (onDragStart) {
frame.postRender(() => onDragStart(event, info));
}
addValueToWillChange(this.visualElement, "transform");
const { animationState } = this.visualElement;
animationState && animationState.setActive("whileDrag", true);
};
const onMove = (event, info) => {
this.latestPointerEvent = event;
this.latestPanInfo = info;
const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps();
// If we didn't successfully receive the gesture lock, early return.
if (!dragPropagation && !this.openDragLock)
return;
const { offset } = info;
// Attempt to detect drag direction if directionLock is true
if (dragDirectionLock && this.currentDirection === null) {
this.currentDirection = getCurrentDirection(offset);
// If we've successfully set a direction, notify listener
if (this.currentDirection !== null) {
onDirectionLock && onDirectionLock(this.currentDirection);
}
return;
}
// Update each point with the latest position
this.updateAxis("x", info.point, offset);
this.updateAxis("y", info.point, offset);
/**
* Ideally we would leave the renderer to fire naturally at the end of
* this frame but if the element is about to change layout as the result
* of a re-render we want to ensure the browser can read the latest
* bounding box to ensure the pointer and element don't fall out of sync.
*/
this.visualElement.render();
/**
* This must fire after the render call as it might trigger a state
* change which itself might trigger a layout update.
*/
onDrag && onDrag(event, info);
};
const onSessionEnd = (event, info) => {
this.latestPointerEvent = event;
this.latestPanInfo = info;
this.stop(event, info);
this.latestPointerEvent = null;
this.latestPanInfo = null;
};
const resumeAnimation = () => eachAxis((axis) => this.getAnimationState(axis) === "paused" &&
this.getAxisMotionValue(axis).animation?.play());
const { dragSnapToOrigin } = this.getProps();
this.panSession = new PanSession(originEvent, {
onSessionStart,
onStart,
onMove,
onSessionEnd,
resumeAnimation,
}, {
transformPagePoint: this.visualElement.getTransformPagePoint(),
dragSnapToOrigin,
distanceThreshold,
contextWindow: getContextWindow(this.visualElement),
});
}
/**
* @internal
*/
stop(event, panInfo) {
const finalEvent = event || this.latestPointerEvent;
const finalPanInfo = panInfo || this.latestPanInfo;
const isDragging = this.isDragging;
this.cancel();
if (!isDragging || !finalPanInfo || !finalEvent)
return;
const { velocity } = finalPanInfo;
this.startAnimation(velocity);
const { onDragEnd } = this.getProps();
if (onDragEnd) {
frame.postRender(() => onDragEnd(finalEvent, finalPanInfo));
}
}
/**
* @internal
*/
cancel() {
this.isDragging = false;
const { projection, animationState } = this.visualElement;
if (projection) {
projection.isAnimationBlocked = false;
}
this.panSession && this.panSession.end();
this.panSession = undefined;
const { dragPropagation } = this.getProps();
if (!dragPropagation && this.openDragLock) {
this.openDragLock();
this.openDragLock = null;
}
animationState && animationState.setActive("whileDrag", false);
}
updateAxis(axis, _point, offset) {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!offset || !shouldDrag(axis, drag, this.currentDirection))
return;
const axisValue = this.getAxisMotionValue(axis);
let next = this.originPoint[axis] + offset[axis];
// Apply constraints
if (this.constraints && this.constraints[axis]) {
next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
}
axisValue.set(next);
}
resolveConstraints() {
const { dragConstraints, dragElastic } = this.getProps();
const layout = this.visualElement.projection &&
!this.visualElement.projection.layout
? this.visualElement.projection.measure(false)
: this.visualElement.projection?.layout;
const prevConstraints = this.constraints;
if (dragConstraints && isRefObject(dragConstraints)) {
if (!this.constraints) {
this.constraints = this.resolveRefConstraints();
}
}
else {
if (dragConstraints && layout) {
this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints);
}
else {
this.constraints = false;
}
}
this.elastic = resolveDragElastic(dragElastic);
/**
* If we're outputting to external MotionValues, we want to rebase the measured constraints
* from viewport-relative to component-relative.
*/
if (prevConstraints !== this.constraints &&
layout &&
this.constraints &&
!this.hasMutatedConstraints) {
eachAxis((axis) => {
if (this.constraints !== false &&
this.getAxisMotionValue(axis)) {
this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);
}
});
}
}
resolveRefConstraints() {
const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();
if (!constraints || !isRefObject(constraints))
return false;
const constraintsElement = constraints.current;
invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref");
const { projection } = this.visualElement;
// TODO
if (!projection || !projection.layout)
return false;
const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
/**
* If there's an onMeasureDragConstraints listener we call it and
* if different constraints are returned, set constraints to that
*/
if (onMeasureDragConstraints) {
const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));
this.hasMutatedConstraints = !!userConstraints;
if (userConstraints) {
measuredConstraints = convertBoundingBoxToBox(userConstraints);
}
}
return measuredConstraints;
}
startAnimation(velocity) {
const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();
const constraints = this.constraints || {};
const momentumAnimations = eachAxis((axis) => {
if (!shouldDrag(axis, drag, this.currentDirection)) {
return;
}
let transition = (constraints && constraints[axis]) || {};
if (dragSnapToOrigin)
transition = { min: 0, max: 0 };
/**
* Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame
* of spring animations so we should look into adding a disable spring option to `inertia`.
* We could do something here where we affect the `bounceStiffness` and `bounceDamping`
* using the value of `dragElastic`.
*/
const bounceStiffness = dragElastic ? 200 : 1000000;
const bounceDamping = dragElastic ? 40 : 10000000;
const inertia = {
type: "inertia",
velocity: dragMomentum ? velocity[axis] : 0,
bounceStiffness,
bounceDamping,
timeConstant: 750,
restDelta: 1,
restSpeed: 10,
...dragTransition,
...transition,
};
// If we're not animating on an externally-provided `MotionValue` we can use the
// component's animation controls which will handle interactions with whileHover (etc),
// otherwise we just have to animate the `MotionValue` itself.
return this.startAxisValueAnimation(axis, inertia);
});
// Run all animations and then resolve the new drag constraints.
return Promise.all(momentumAnimations).then(onDragTransitionEnd);
}
startAxisValueAnimation(axis, transition) {
const axisValue = this.getAxisMotionValue(axis);
addValueToWillChange(this.visualElement, axis);
return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false));
}
stopAnimation() {
eachAxis((axis) => this.getAxisMotionValue(axis).stop());
}
pauseAnimation() {
eachAxis((axis) => this.getAxisMotionValue(axis).animation?.pause());
}
getAnimationState(axis) {
return this.getAxisMotionValue(axis).animation?.state;
}
/**
* Drag works differently depending on which props are provided.
*
* - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
* - Otherwise, we apply the delta to the x/y motion values.
*/
getAxisMotionValue(axis) {
const dragKey = `_drag${axis.toUpperCase()}`;
const props = this.visualElement.getProps();
const externalMotionValue = props[dragKey];
return externalMotionValue
? externalMotionValue
: this.visualElement.getValue(axis, (props.initial
? props.initial[axis]
: undefined) || 0);
}
snapToCursor(point) {
eachAxis((axis) => {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!shouldDrag(axis, drag, this.currentDirection))
return;
const { projection } = this.visualElement;
const axisValue = this.getAxisMotionValue(axis);
if (projection && projection.layout) {
const { min, max } = projection.layout.layoutBox[axis];
axisValue.set(point[axis] - mixNumber(min, max, 0.5));
}
});
}
/**
* When the viewport resizes we want to check if the measured constraints
* have changed and, if so, reposition the element within those new constraints
* relative to where it was before the resize.
*/
scalePositionWithinConstraints() {
if (!this.visualElement.current)
return;
const { drag, dragConstraints } = this.getProps();
const { projection } = this.visualElement;
if (!isRefObject(dragConstraints) || !projection || !this.constraints)
return;
/**
* Stop current animations as there can be visual glitching if we try to do
* this mid-animation
*/
this.stopAnimation();
/**
* Record the relative position of the dragged element relative to the
* constraints box and save as a progress value.
*/
const boxProgress = { x: 0, y: 0 };
eachAxis((axis) => {
const axisValue = this.getAxisMotionValue(axis);
if (axisValue && this.constraints !== false) {
const latest = axisValue.get();
boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]);
}
});
/**
* Update the layout of this element and resolve the latest drag constraints
*/
const { transformTemplate } = this.visualElement.getProps();
this.visualElement.current.style.transform = transformTemplate
? transformTemplate({}, "")
: "none";
projection.root && projection.root.updateScroll();
projection.updateLayout();
this.resolveConstraints();
/**
* For each axis, calculate the current progress of the layout axis
* within the new constraints.
*/
eachAxis((axis) => {
if (!shouldDrag(axis, drag, null))
return;
/**
* Calculate a new transform based on the previous box progress
*/
const axisValue = this.getAxisMotionValue(axis);
const { min, max } = this.constraints[axis];
axisValue.set(mixNumber(min, max, boxProgress[axis]));
});
}
addListeners() {
if (!this.visualElement.current)
return;
elementDragControls.set(this.visualElement, this);
const element = this.visualElement.current;
/**
* Attach a pointerdown event listener on this DOM element to initiate drag tracking.
*/
const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => {
const { drag, dragListener = true } = this.getProps();
drag && dragListener && this.start(event);
});
const measureDragConstraints = () => {
const { dragConstraints } = this.getProps();
if (isRefObject(dragConstraints) && dragConstraints.current) {
this.constraints = this.resolveRefConstraints();
}
};
const { projection } = this.visualElement;
const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
if (projection && !projection.layout) {
projection.root && projection.root.updateScroll();
projection.updateLayout();
}
frame.read(measureDragConstraints);
/**
* Attach a window resize listener to scale the draggable target within its defined
* constraints as the window resizes.
*/
const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints());
/**
* If the element's layout changes, calculate the delta and apply that to
* the drag gesture's origin point.
*/
const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => {
if (this.isDragging && hasLayoutChanged) {
eachAxis((axis) => {
const motionValue = this.getAxisMotionValue(axis);
if (!motionValue)
return;
this.originPoint[axis] += delta[axis].translate;
motionValue.set(motionValue.get() + delta[axis].translate);
});
this.visualElement.render();
}
}));
return () => {
stopResizeListener();
stopPointerListener();
stopMeasureLayoutListener();
stopLayoutUpdateListener && stopLayoutUpdateListener();
};
}
getProps() {
const props = this.visualElement.getProps();
const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
return {
...props,
drag,
dragDirectionLock,
dragPropagation,
dragConstraints,
dragElastic,
dragMomentum,
};
}
}
function shouldDrag(direction, drag, currentDirection) {
return ((drag === true || drag === direction) &&
(currentDirection === null || currentDirection === direction));
}
/**
* Based on an x/y offset determine the current drag direction. If both axis' offsets are lower
* than the provided threshold, return `null`.
*
* @param offset - The x/y offset from origin.
* @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.
*/
function getCurrentDirection(offset, lockThreshold = 10) {
let direction = null;
if (Math.abs(offset.y) > lockThreshold) {
direction = "y";
}
else if (Math.abs(offset.x) > lockThreshold) {
direction = "x";
}
return direction;
}
export { VisualElementDragControls, elementDragControls };

View File

@@ -0,0 +1,27 @@
import { Feature } from '../../motion/features/Feature.mjs';
import { noop } from 'motion-utils';
import { VisualElementDragControls } from './VisualElementDragControls.mjs';
class DragGesture extends Feature {
constructor(node) {
super(node);
this.removeGroupControls = noop;
this.removeListeners = noop;
this.controls = new VisualElementDragControls(node);
}
mount() {
// If we've been provided a DragControls for manual control over the drag gesture,
// subscribe this component to it on mount.
const { dragControls } = this.node.getProps();
if (dragControls) {
this.removeGroupControls = dragControls.subscribe(this.controls);
}
this.removeListeners = this.controls.addListeners() || noop;
}
unmount() {
this.removeGroupControls();
this.removeListeners();
}
}
export { DragGesture };

View File

@@ -0,0 +1,116 @@
import { useConstant } from '../../utils/use-constant.mjs';
/**
* Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components.
*
* ```jsx
* const dragControls = useDragControls()
*
* function startDrag(event) {
* dragControls.start(event, { snapToCursor: true })
* }
*
* return (
* <>
* <div onPointerDown={startDrag} />
* <motion.div drag="x" dragControls={dragControls} />
* </>
* )
* ```
*
* @public
*/
class DragControls {
constructor() {
this.componentControls = new Set();
}
/**
* Subscribe a component's internal `VisualElementDragControls` to the user-facing API.
*
* @internal
*/
subscribe(controls) {
this.componentControls.add(controls);
return () => this.componentControls.delete(controls);
}
/**
* Start a drag gesture on every `motion` component that has this set of drag controls
* passed into it via the `dragControls` prop.
*
* ```jsx
* dragControls.start(e, {
* snapToCursor: true
* })
* ```
*
* @param event - PointerEvent
* @param options - Options
*
* @public
*/
start(event, options) {
this.componentControls.forEach((controls) => {
controls.start(event.nativeEvent || event, options);
});
}
/**
* Cancels a drag gesture.
*
* ```jsx
* dragControls.cancel()
* ```
*
* @public
*/
cancel() {
this.componentControls.forEach((controls) => {
controls.cancel();
});
}
/**
* Stops a drag gesture.
*
* ```jsx
* dragControls.stop()
* ```
*
* @public
*/
stop() {
this.componentControls.forEach((controls) => {
controls.stop();
});
}
}
const createDragControls = () => new DragControls();
/**
* Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop
* and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we
* might want to initiate that dragging from a different component than the draggable one.
*
* By creating a `dragControls` using the `useDragControls` hook, we can pass this into
* the draggable component's `dragControls` prop. It exposes a `start` method
* that can start dragging from pointer events on other components.
*
* ```jsx
* const dragControls = useDragControls()
*
* function startDrag(event) {
* dragControls.start(event, { snapToCursor: true })
* }
*
* return (
* <>
* <div onPointerDown={startDrag} />
* <motion.div drag="x" dragControls={dragControls} />
* </>
* )
* ```
*
* @public
*/
function useDragControls() {
return useConstant(createDragControls);
}
export { DragControls, useDragControls };

View File

@@ -0,0 +1,128 @@
import { mixNumber } from 'motion-dom';
import { progress, clamp } from 'motion-utils';
import { calcLength } from '../../../projection/geometry/delta-calc.mjs';
/**
* Apply constraints to a point. These constraints are both physical along an
* axis, and an elastic factor that determines how much to constrain the point
* by if it does lie outside the defined parameters.
*/
function applyConstraints(point, { min, max }, elastic) {
if (min !== undefined && point < min) {
// If we have a min point defined, and this is outside of that, constrain
point = elastic
? mixNumber(min, point, elastic.min)
: Math.max(point, min);
}
else if (max !== undefined && point > max) {
// If we have a max point defined, and this is outside of that, constrain
point = elastic
? mixNumber(max, point, elastic.max)
: Math.min(point, max);
}
return point;
}
/**
* Calculate constraints in terms of the viewport when defined relatively to the
* measured axis. This is measured from the nearest edge, so a max constraint of 200
* on an axis with a max value of 300 would return a constraint of 500 - axis length
*/
function calcRelativeAxisConstraints(axis, min, max) {
return {
min: min !== undefined ? axis.min + min : undefined,
max: max !== undefined
? axis.max + max - (axis.max - axis.min)
: undefined,
};
}
/**
* Calculate constraints in terms of the viewport when
* defined relatively to the measured bounding box.
*/
function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {
return {
x: calcRelativeAxisConstraints(layoutBox.x, left, right),
y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),
};
}
/**
* Calculate viewport constraints when defined as another viewport-relative axis
*/
function calcViewportAxisConstraints(layoutAxis, constraintsAxis) {
let min = constraintsAxis.min - layoutAxis.min;
let max = constraintsAxis.max - layoutAxis.max;
// If the constraints axis is actually smaller than the layout axis then we can
// flip the constraints
if (constraintsAxis.max - constraintsAxis.min <
layoutAxis.max - layoutAxis.min) {
[min, max] = [max, min];
}
return { min, max };
}
/**
* Calculate viewport constraints when defined as another viewport-relative box
*/
function calcViewportConstraints(layoutBox, constraintsBox) {
return {
x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),
y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),
};
}
/**
* Calculate a transform origin relative to the source axis, between 0-1, that results
* in an asthetically pleasing scale/transform needed to project from source to target.
*/
function calcOrigin(source, target) {
let origin = 0.5;
const sourceLength = calcLength(source);
const targetLength = calcLength(target);
if (targetLength > sourceLength) {
origin = progress(target.min, target.max - sourceLength, source.min);
}
else if (sourceLength > targetLength) {
origin = progress(source.min, source.max - targetLength, target.min);
}
return clamp(0, 1, origin);
}
/**
* Rebase the calculated viewport constraints relative to the layout.min point.
*/
function rebaseAxisConstraints(layout, constraints) {
const relativeConstraints = {};
if (constraints.min !== undefined) {
relativeConstraints.min = constraints.min - layout.min;
}
if (constraints.max !== undefined) {
relativeConstraints.max = constraints.max - layout.min;
}
return relativeConstraints;
}
const defaultElastic = 0.35;
/**
* Accepts a dragElastic prop and returns resolved elastic values for each axis.
*/
function resolveDragElastic(dragElastic = defaultElastic) {
if (dragElastic === false) {
dragElastic = 0;
}
else if (dragElastic === true) {
dragElastic = defaultElastic;
}
return {
x: resolveAxisElastic(dragElastic, "left", "right"),
y: resolveAxisElastic(dragElastic, "top", "bottom"),
};
}
function resolveAxisElastic(dragElastic, minLabel, maxLabel) {
return {
min: resolvePointElastic(dragElastic, minLabel),
max: resolvePointElastic(dragElastic, maxLabel),
};
}
function resolvePointElastic(dragElastic, label) {
return typeof dragElastic === "number"
? dragElastic
: dragElastic[label] || 0;
}
export { applyConstraints, calcOrigin, calcRelativeAxisConstraints, calcRelativeConstraints, calcViewportAxisConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveAxisElastic, resolveDragElastic, resolvePointElastic };

41
node_modules/framer-motion/dist/es/gestures/focus.mjs generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { pipe } from 'motion-utils';
import { addDomEvent } from '../events/add-dom-event.mjs';
import { Feature } from '../motion/features/Feature.mjs';
class FocusGesture extends Feature {
constructor() {
super(...arguments);
this.isActive = false;
}
onFocus() {
let isFocusVisible = false;
/**
* If this element doesn't match focus-visible then don't
* apply whileHover. But, if matches throws that focus-visible
* is not a valid selector then in that browser outline styles will be applied
* to the element by default and we want to match that behaviour with whileFocus.
*/
try {
isFocusVisible = this.node.current.matches(":focus-visible");
}
catch (e) {
isFocusVisible = true;
}
if (!isFocusVisible || !this.node.animationState)
return;
this.node.animationState.setActive("whileFocus", true);
this.isActive = true;
}
onBlur() {
if (!this.isActive || !this.node.animationState)
return;
this.node.animationState.setActive("whileFocus", false);
this.isActive = false;
}
mount() {
this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur()));
}
unmount() { }
}
export { FocusGesture };

29
node_modules/framer-motion/dist/es/gestures/hover.mjs generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import { hover, frame } from 'motion-dom';
import { extractEventInfo } from '../events/event-info.mjs';
import { Feature } from '../motion/features/Feature.mjs';
function handleHoverEvent(node, event, lifecycle) {
const { props } = node;
if (node.animationState && props.whileHover) {
node.animationState.setActive("whileHover", lifecycle === "Start");
}
const eventName = ("onHover" + lifecycle);
const callback = props[eventName];
if (callback) {
frame.postRender(() => callback(event, extractEventInfo(event)));
}
}
class HoverGesture extends Feature {
mount() {
const { current } = this.node;
if (!current)
return;
this.unmount = hover(current, (_element, startEvent) => {
handleHoverEvent(this.node, startEvent, "Start");
return (endEvent) => handleHoverEvent(this.node, endEvent, "End");
});
}
unmount() { }
}
export { HoverGesture };

View File

@@ -0,0 +1,155 @@
import { frame, isPrimaryPointer, cancelFrame, frameData } from 'motion-dom';
import { pipe, secondsToMilliseconds, millisecondsToSeconds } from 'motion-utils';
import { addPointerEvent } from '../../events/add-pointer-event.mjs';
import { extractEventInfo } from '../../events/event-info.mjs';
import { distance2D } from '../../utils/distance.mjs';
/**
* @internal
*/
class PanSession {
constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, } = {}) {
/**
* @internal
*/
this.startEvent = null;
/**
* @internal
*/
this.lastMoveEvent = null;
/**
* @internal
*/
this.lastMoveEventInfo = null;
/**
* @internal
*/
this.handlers = {};
/**
* @internal
*/
this.contextWindow = window;
this.updatePoint = () => {
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
const info = getPanInfo(this.lastMoveEventInfo, this.history);
const isPanStarted = this.startEvent !== null;
// Only start panning if the offset is larger than 3 pixels. If we make it
// any larger than this we'll want to reset the pointer history
// on the first update to avoid visual snapping to the cursor.
const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold;
if (!isPanStarted && !isDistancePastThreshold)
return;
const { point } = info;
const { timestamp } = frameData;
this.history.push({ ...point, timestamp });
const { onStart, onMove } = this.handlers;
if (!isPanStarted) {
onStart && onStart(this.lastMoveEvent, info);
this.startEvent = this.lastMoveEvent;
}
onMove && onMove(this.lastMoveEvent, info);
};
this.handlePointerMove = (event, info) => {
this.lastMoveEvent = event;
this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);
// Throttle mouse move event to once per frame
frame.update(this.updatePoint, true);
};
this.handlePointerUp = (event, info) => {
this.end();
const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;
if (this.dragSnapToOrigin)
resumeAnimation && resumeAnimation();
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
const panInfo = getPanInfo(event.type === "pointercancel"
? this.lastMoveEventInfo
: transformPoint(info, this.transformPagePoint), this.history);
if (this.startEvent && onEnd) {
onEnd(event, panInfo);
}
onSessionEnd && onSessionEnd(event, panInfo);
};
// If we have more than one touch, don't start detecting this gesture
if (!isPrimaryPointer(event))
return;
this.dragSnapToOrigin = dragSnapToOrigin;
this.handlers = handlers;
this.transformPagePoint = transformPagePoint;
this.distanceThreshold = distanceThreshold;
this.contextWindow = contextWindow || window;
const info = extractEventInfo(event);
const initialInfo = transformPoint(info, this.transformPagePoint);
const { point } = initialInfo;
const { timestamp } = frameData;
this.history = [{ ...point, timestamp }];
const { onSessionStart } = handlers;
onSessionStart &&
onSessionStart(event, getPanInfo(initialInfo, this.history));
this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp));
}
updateHandlers(handlers) {
this.handlers = handlers;
}
end() {
this.removeListeners && this.removeListeners();
cancelFrame(this.updatePoint);
}
}
function transformPoint(info, transformPagePoint) {
return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
}
function subtractPoint(a, b) {
return { x: a.x - b.x, y: a.y - b.y };
}
function getPanInfo({ point }, history) {
return {
point,
delta: subtractPoint(point, lastDevicePoint(history)),
offset: subtractPoint(point, startDevicePoint(history)),
velocity: getVelocity(history, 0.1),
};
}
function startDevicePoint(history) {
return history[0];
}
function lastDevicePoint(history) {
return history[history.length - 1];
}
function getVelocity(history, timeDelta) {
if (history.length < 2) {
return { x: 0, y: 0 };
}
let i = history.length - 1;
let timestampedPoint = null;
const lastPoint = lastDevicePoint(history);
while (i >= 0) {
timestampedPoint = history[i];
if (lastPoint.timestamp - timestampedPoint.timestamp >
secondsToMilliseconds(timeDelta)) {
break;
}
i--;
}
if (!timestampedPoint) {
return { x: 0, y: 0 };
}
const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);
if (time === 0) {
return { x: 0, y: 0 };
}
const currentVelocity = {
x: (lastPoint.x - timestampedPoint.x) / time,
y: (lastPoint.y - timestampedPoint.y) / time,
};
if (currentVelocity.x === Infinity) {
currentVelocity.x = 0;
}
if (currentVelocity.y === Infinity) {
currentVelocity.y = 0;
}
return currentVelocity;
}
export { PanSession };

View File

@@ -0,0 +1,50 @@
import { frame } from 'motion-dom';
import { noop } from 'motion-utils';
import { addPointerEvent } from '../../events/add-pointer-event.mjs';
import { Feature } from '../../motion/features/Feature.mjs';
import { getContextWindow } from '../../utils/get-context-window.mjs';
import { PanSession } from './PanSession.mjs';
const asyncHandler = (handler) => (event, info) => {
if (handler) {
frame.postRender(() => handler(event, info));
}
};
class PanGesture extends Feature {
constructor() {
super(...arguments);
this.removePointerDownListener = noop;
}
onPointerDown(pointerDownEvent) {
this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), {
transformPagePoint: this.node.getTransformPagePoint(),
contextWindow: getContextWindow(this.node),
});
}
createPanHandlers() {
const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();
return {
onSessionStart: asyncHandler(onPanSessionStart),
onStart: asyncHandler(onPanStart),
onMove: onPan,
onEnd: (event, info) => {
delete this.session;
if (onPanEnd) {
frame.postRender(() => onPanEnd(event, info));
}
},
};
}
mount() {
this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event));
}
update() {
this.session && this.session.updateHandlers(this.createPanHandlers());
}
unmount() {
this.removePointerDownListener();
this.session && this.session.end();
}
}
export { PanGesture };

32
node_modules/framer-motion/dist/es/gestures/press.mjs generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import { press, frame } from 'motion-dom';
import { extractEventInfo } from '../events/event-info.mjs';
import { Feature } from '../motion/features/Feature.mjs';
function handlePressEvent(node, event, lifecycle) {
const { props } = node;
if (node.current instanceof HTMLButtonElement && node.current.disabled) {
return;
}
if (node.animationState && props.whileTap) {
node.animationState.setActive("whileTap", lifecycle === "Start");
}
const eventName = ("onTap" + (lifecycle === "End" ? "" : lifecycle));
const callback = props[eventName];
if (callback) {
frame.postRender(() => callback(event, extractEventInfo(event)));
}
}
class PressGesture extends Feature {
mount() {
const { current } = this.node;
if (!current)
return;
this.unmount = press(current, (_element, startEvent) => {
handlePressEvent(this.node, startEvent, "Start");
return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel");
}, { useGlobalTarget: this.node.props.globalTapTarget });
}
unmount() { }
}
export { PressGesture };

84
node_modules/framer-motion/dist/es/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,84 @@
export { AnimatePresence } from './components/AnimatePresence/index.mjs';
export { PopChild } from './components/AnimatePresence/PopChild.mjs';
export { PresenceChild } from './components/AnimatePresence/PresenceChild.mjs';
export { LayoutGroup } from './components/LayoutGroup/index.mjs';
export { LazyMotion } from './components/LazyMotion/index.mjs';
export { MotionConfig } from './components/MotionConfig/index.mjs';
export { m } from './render/components/m/proxy.mjs';
export { motion } from './render/components/motion/proxy.mjs';
export { addPointerEvent } from './events/add-pointer-event.mjs';
export { addPointerInfo } from './events/event-info.mjs';
export { animations } from './motion/features/animations.mjs';
export { makeUseVisualState } from './motion/utils/use-visual-state.mjs';
export { calcLength } from './projection/geometry/delta-calc.mjs';
export { createBox } from './projection/geometry/models.mjs';
export { filterProps } from './render/dom/utils/filter-props.mjs';
export { isBrowser } from './utils/is-browser.mjs';
export { useComposedRefs } from './utils/use-composed-ref.mjs';
export { useForceUpdate } from './utils/use-force-update.mjs';
export { useIsomorphicLayoutEffect } from './utils/use-isomorphic-effect.mjs';
export { useUnmountEffect } from './utils/use-unmount-effect.mjs';
export { domAnimation } from './render/dom/features-animation.mjs';
export { domMax } from './render/dom/features-max.mjs';
export { domMin } from './render/dom/features-min.mjs';
export { useMotionValueEvent } from './utils/use-motion-value-event.mjs';
export { useElementScroll } from './value/scroll/use-element-scroll.mjs';
export { useViewportScroll } from './value/scroll/use-viewport-scroll.mjs';
export { useMotionTemplate } from './value/use-motion-template.mjs';
export { useMotionValue } from './value/use-motion-value.mjs';
export { useScroll } from './value/use-scroll.mjs';
export { useSpring } from './value/use-spring.mjs';
export { useTime } from './value/use-time.mjs';
export { useTransform } from './value/use-transform.mjs';
export { useVelocity } from './value/use-velocity.mjs';
export { useWillChange } from './value/use-will-change/index.mjs';
export { WillChangeMotionValue } from './value/use-will-change/WillChangeMotionValue.mjs';
export { resolveMotionValue } from './value/utils/resolve-motion-value.mjs';
export { useReducedMotion } from './utils/reduced-motion/use-reduced-motion.mjs';
export { useReducedMotionConfig } from './utils/reduced-motion/use-reduced-motion-config.mjs';
export * from 'motion-utils';
export { MotionGlobalConfig } from 'motion-utils';
export { animationControls } from './animation/hooks/animation-controls.mjs';
export { useAnimate } from './animation/hooks/use-animate.mjs';
export { useAnimateMini } from './animation/hooks/use-animate-style.mjs';
export { useAnimation, useAnimationControls } from './animation/hooks/use-animation.mjs';
export { animateVisualElement } from './animation/interfaces/visual-element.mjs';
export { useIsPresent, usePresence } from './components/AnimatePresence/use-presence.mjs';
export { usePresenceData } from './components/AnimatePresence/use-presence-data.mjs';
export { useDomEvent } from './events/use-dom-event.mjs';
export { DragControls, useDragControls } from './gestures/drag/use-drag-controls.mjs';
export { isMotionComponent } from './motion/utils/is-motion-component.mjs';
export { unwrapMotionComponent } from './motion/utils/unwrap-motion-component.mjs';
export { isValidMotionProp } from './motion/utils/valid-prop.mjs';
export { addScaleCorrector } from './projection/styles/scale-correction.mjs';
export { useInstantLayoutTransition } from './projection/use-instant-layout-transition.mjs';
export { useResetProjection } from './projection/use-reset-projection.mjs';
export { buildTransform } from './render/html/utils/build-transform.mjs';
export { visualElementStore } from './render/store.mjs';
export { VisualElement } from './render/VisualElement.mjs';
export { useAnimationFrame } from './utils/use-animation-frame.mjs';
export { useCycle } from './utils/use-cycle.mjs';
export { useInView } from './utils/use-in-view.mjs';
export { disableInstantTransitions, useInstantTransition } from './utils/use-instant-transition.mjs';
export { usePageInView } from './utils/use-page-in-view.mjs';
export { optimizedAppearDataAttribute } from './animation/optimized-appear/data-id.mjs';
export { startOptimizedAppearAnimation } from './animation/optimized-appear/start.mjs';
export { LayoutGroupContext } from './context/LayoutGroupContext.mjs';
export { MotionConfigContext } from './context/MotionConfigContext.mjs';
export { MotionContext } from './context/MotionContext/index.mjs';
export { PresenceContext } from './context/PresenceContext.mjs';
export { SwitchLayoutGroupContext } from './context/SwitchLayoutGroupContext.mjs';
export { useAnimatedState as useDeprecatedAnimatedState } from './animation/hooks/use-animated-state.mjs';
export { AnimateSharedLayout } from './components/AnimateSharedLayout.mjs';
export { DeprecatedLayoutGroupContext } from './context/DeprecatedLayoutGroupContext.mjs';
export { useInvertedScale as useDeprecatedInvertedScale } from './value/use-inverted-scale.mjs';
export { delay } from './utils/delay.mjs';
import * as namespace from './components/Reorder/namespace.mjs';
export { namespace as Reorder };
export { animate, createScopedAnimate } from './animation/animate/index.mjs';
export { animateMini } from './animation/animators/waapi/animate-style.mjs';
export { scroll } from './render/dom/scroll/index.mjs';
export { scrollInfo } from './render/dom/scroll/track.mjs';
export { inView } from './render/dom/viewport/index.mjs';
export { distance, distance2D } from './utils/distance.mjs';
export * from 'motion-dom';

2
node_modules/framer-motion/dist/es/m.mjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { createMinimalMotionComponent as create } from './render/components/m/create.mjs';
export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview } from './render/components/m/elements.mjs';

1
node_modules/framer-motion/dist/es/mini.mjs generated vendored Normal file
View File

@@ -0,0 +1 @@
export { useAnimateMini as useAnimate } from './animation/hooks/use-animate-style.mjs';

View File

@@ -0,0 +1,9 @@
class Feature {
constructor(node) {
this.isMounted = false;
this.node = node;
}
update() { }
}
export { Feature };

View File

@@ -0,0 +1,36 @@
import { Feature } from '../Feature.mjs';
let id = 0;
class ExitAnimationFeature extends Feature {
constructor() {
super(...arguments);
this.id = id++;
}
update() {
if (!this.node.presenceContext)
return;
const { isPresent, onExitComplete } = this.node.presenceContext;
const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};
if (!this.node.animationState || isPresent === prevIsPresent) {
return;
}
const exitAnimation = this.node.animationState.setActive("exit", !isPresent);
if (onExitComplete && !isPresent) {
exitAnimation.then(() => {
onExitComplete(this.id);
});
}
}
mount() {
const { register, onExitComplete } = this.node.presenceContext || {};
if (onExitComplete) {
onExitComplete(this.id);
}
if (register) {
this.unmount = register(this.id);
}
}
unmount() { }
}
export { ExitAnimationFeature };

View File

@@ -0,0 +1,40 @@
import { isAnimationControls } from '../../../animation/utils/is-animation-controls.mjs';
import { createAnimationState } from '../../../render/utils/animation-state.mjs';
import { Feature } from '../Feature.mjs';
class AnimationFeature extends Feature {
/**
* We dynamically generate the AnimationState manager as it contains a reference
* to the underlying animation library. We only want to load that if we load this,
* so people can optionally code split it out using the `m` component.
*/
constructor(node) {
super(node);
node.animationState || (node.animationState = createAnimationState(node));
}
updateAnimationControlsSubscription() {
const { animate } = this.node.getProps();
if (isAnimationControls(animate)) {
this.unmountControls = animate.subscribe(this.node);
}
}
/**
* Subscribe any provided AnimationControls to the component's VisualElement
*/
mount() {
this.updateAnimationControlsSubscription();
}
update() {
const { animate } = this.node.getProps();
const { animate: prevAnimate } = this.node.prevProps || {};
if (animate !== prevAnimate) {
this.updateAnimationControlsSubscription();
}
}
unmount() {
this.node.animationState.reset();
this.unmountControls?.();
}
}
export { AnimationFeature };

View File

@@ -0,0 +1,13 @@
import { AnimationFeature } from './animation/index.mjs';
import { ExitAnimationFeature } from './animation/exit.mjs';
const animations = {
animation: {
Feature: AnimationFeature,
},
exit: {
Feature: ExitAnimationFeature,
},
};
export { animations };

View File

@@ -0,0 +1,28 @@
const featureProps = {
animation: [
"animate",
"variants",
"whileHover",
"whileTap",
"exit",
"whileInView",
"whileFocus",
"whileDrag",
],
exit: ["exit"],
drag: ["drag", "dragControls"],
focus: ["whileFocus"],
hover: ["whileHover", "onHoverStart", "onHoverEnd"],
tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"],
pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"],
inView: ["whileInView", "onViewportEnter", "onViewportLeave"],
layout: ["layout", "layoutId"],
};
const featureDefinitions = {};
for (const key in featureProps) {
featureDefinitions[key] = {
isEnabled: (props) => featureProps[key].some((name) => !!props[name]),
};
}
export { featureDefinitions };

View File

@@ -0,0 +1,17 @@
import { DragGesture } from '../../gestures/drag/index.mjs';
import { PanGesture } from '../../gestures/pan/index.mjs';
import { MeasureLayout } from './layout/MeasureLayout.mjs';
import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';
const drag = {
pan: {
Feature: PanGesture,
},
drag: {
Feature: DragGesture,
ProjectionNode: HTMLProjectionNode,
MeasureLayout,
},
};
export { drag };

View File

@@ -0,0 +1,21 @@
import { HoverGesture } from '../../gestures/hover.mjs';
import { FocusGesture } from '../../gestures/focus.mjs';
import { PressGesture } from '../../gestures/press.mjs';
import { InViewFeature } from './viewport/index.mjs';
const gestureAnimations = {
inView: {
Feature: InViewFeature,
},
tap: {
Feature: PressGesture,
},
focus: {
Feature: FocusGesture,
},
hover: {
Feature: HoverGesture,
},
};
export { gestureAnimations };

View File

@@ -0,0 +1,11 @@
import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';
import { MeasureLayout } from './layout/MeasureLayout.mjs';
const layout = {
layout: {
ProjectionNode: HTMLProjectionNode,
MeasureLayout,
},
};
export { layout };

View File

@@ -0,0 +1,147 @@
"use client";
import { jsx } from 'react/jsx-runtime';
import { frame, microtask } from 'motion-dom';
import { useContext, Component } from 'react';
import { usePresence } from '../../../components/AnimatePresence/use-presence.mjs';
import { LayoutGroupContext } from '../../../context/LayoutGroupContext.mjs';
import { SwitchLayoutGroupContext } from '../../../context/SwitchLayoutGroupContext.mjs';
import { globalProjectionState } from '../../../projection/node/state.mjs';
import { correctBorderRadius } from '../../../projection/styles/scale-border-radius.mjs';
import { correctBoxShadow } from '../../../projection/styles/scale-box-shadow.mjs';
import { addScaleCorrector } from '../../../projection/styles/scale-correction.mjs';
/**
* Track whether we've taken any snapshots yet. If not,
* we can safely skip notification of didUpdate.
*
* Difficult to capture in a test but to prevent flickering
* we must set this to true either on update or unmount.
* Running `next-env/layout-id` in Safari will show this behaviour if broken.
*/
let hasTakenAnySnapshot = false;
class MeasureLayoutWithContext extends Component {
/**
* This only mounts projection nodes for components that
* need measuring, we might want to do it for all components
* in order to incorporate transforms
*/
componentDidMount() {
const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;
const { projection } = visualElement;
addScaleCorrector(defaultScaleCorrectors);
if (projection) {
if (layoutGroup.group)
layoutGroup.group.add(projection);
if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {
switchLayoutGroup.register(projection);
}
if (hasTakenAnySnapshot) {
projection.root.didUpdate();
}
projection.addEventListener("animationComplete", () => {
this.safeToRemove();
});
projection.setOptions({
...projection.options,
onExitComplete: () => this.safeToRemove(),
});
}
globalProjectionState.hasEverUpdated = true;
}
getSnapshotBeforeUpdate(prevProps) {
const { layoutDependency, visualElement, drag, isPresent } = this.props;
const { projection } = visualElement;
if (!projection)
return null;
/**
* TODO: We use this data in relegate to determine whether to
* promote a previous element. There's no guarantee its presence data
* will have updated by this point - if a bug like this arises it will
* have to be that we markForRelegation and then find a new lead some other way,
* perhaps in didUpdate
*/
projection.isPresent = isPresent;
hasTakenAnySnapshot = true;
if (drag ||
prevProps.layoutDependency !== layoutDependency ||
layoutDependency === undefined ||
prevProps.isPresent !== isPresent) {
projection.willUpdate();
}
else {
this.safeToRemove();
}
if (prevProps.isPresent !== isPresent) {
if (isPresent) {
projection.promote();
}
else if (!projection.relegate()) {
/**
* If there's another stack member taking over from this one,
* it's in charge of the exit animation and therefore should
* be in charge of the safe to remove. Otherwise we call it here.
*/
frame.postRender(() => {
const stack = projection.getStack();
if (!stack || !stack.members.length) {
this.safeToRemove();
}
});
}
}
return null;
}
componentDidUpdate() {
const { projection } = this.props.visualElement;
if (projection) {
projection.root.didUpdate();
microtask.postRender(() => {
if (!projection.currentAnimation && projection.isLead()) {
this.safeToRemove();
}
});
}
}
componentWillUnmount() {
const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props;
const { projection } = visualElement;
hasTakenAnySnapshot = true;
if (projection) {
projection.scheduleCheckAfterUnmount();
if (layoutGroup && layoutGroup.group)
layoutGroup.group.remove(projection);
if (promoteContext && promoteContext.deregister)
promoteContext.deregister(projection);
}
}
safeToRemove() {
const { safeToRemove } = this.props;
safeToRemove && safeToRemove();
}
render() {
return null;
}
}
function MeasureLayout(props) {
const [isPresent, safeToRemove] = usePresence();
const layoutGroup = useContext(LayoutGroupContext);
return (jsx(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove }));
}
const defaultScaleCorrectors = {
borderRadius: {
...correctBorderRadius,
applyTo: [
"borderTopLeftRadius",
"borderTopRightRadius",
"borderBottomLeftRadius",
"borderBottomRightRadius",
],
},
borderTopLeftRadius: correctBorderRadius,
borderTopRightRadius: correctBorderRadius,
borderBottomLeftRadius: correctBorderRadius,
borderBottomRightRadius: correctBorderRadius,
boxShadow: correctBoxShadow,
};
export { MeasureLayout };

View File

@@ -0,0 +1,12 @@
import { featureDefinitions } from './definitions.mjs';
function loadFeatures(features) {
for (const key in features) {
featureDefinitions[key] = {
...featureDefinitions[key],
...features[key],
};
}
}
export { loadFeatures };

View File

@@ -0,0 +1,72 @@
import { Feature } from '../Feature.mjs';
import { observeIntersection } from './observers.mjs';
const thresholdNames = {
some: 0,
all: 1,
};
class InViewFeature extends Feature {
constructor() {
super(...arguments);
this.hasEnteredView = false;
this.isInView = false;
}
startObserver() {
this.unmount();
const { viewport = {} } = this.node.getProps();
const { root, margin: rootMargin, amount = "some", once } = viewport;
const options = {
root: root ? root.current : undefined,
rootMargin,
threshold: typeof amount === "number" ? amount : thresholdNames[amount],
};
const onIntersectionUpdate = (entry) => {
const { isIntersecting } = entry;
/**
* If there's been no change in the viewport state, early return.
*/
if (this.isInView === isIntersecting)
return;
this.isInView = isIntersecting;
/**
* Handle hasEnteredView. If this is only meant to run once, and
* element isn't visible, early return. Otherwise set hasEnteredView to true.
*/
if (once && !isIntersecting && this.hasEnteredView) {
return;
}
else if (isIntersecting) {
this.hasEnteredView = true;
}
if (this.node.animationState) {
this.node.animationState.setActive("whileInView", isIntersecting);
}
/**
* Use the latest committed props rather than the ones in scope
* when this observer is created
*/
const { onViewportEnter, onViewportLeave } = this.node.getProps();
const callback = isIntersecting ? onViewportEnter : onViewportLeave;
callback && callback(entry);
};
return observeIntersection(this.node.current, options, onIntersectionUpdate);
}
mount() {
this.startObserver();
}
update() {
if (typeof IntersectionObserver === "undefined")
return;
const { props, prevProps } = this.node;
const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps));
if (hasOptionsChanged) {
this.startObserver();
}
}
unmount() { }
}
function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) {
return (name) => viewport[name] !== prevViewport[name];
}
export { InViewFeature };

View File

@@ -0,0 +1,49 @@
/**
* Map an IntersectionHandler callback to an element. We only ever make one handler for one
* element, so even though these handlers might all be triggered by different
* observers, we can keep them in the same map.
*/
const observerCallbacks = new WeakMap();
/**
* Multiple observers can be created for multiple element/document roots. Each with
* different settings. So here we store dictionaries of observers to each root,
* using serialised settings (threshold/margin) as lookup keys.
*/
const observers = new WeakMap();
const fireObserverCallback = (entry) => {
const callback = observerCallbacks.get(entry.target);
callback && callback(entry);
};
const fireAllObserverCallbacks = (entries) => {
entries.forEach(fireObserverCallback);
};
function initIntersectionObserver({ root, ...options }) {
const lookupRoot = root || document;
/**
* If we don't have an observer lookup map for this root, create one.
*/
if (!observers.has(lookupRoot)) {
observers.set(lookupRoot, {});
}
const rootObservers = observers.get(lookupRoot);
const key = JSON.stringify(options);
/**
* If we don't have an observer for this combination of root and settings,
* create one.
*/
if (!rootObservers[key]) {
rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options });
}
return rootObservers[key];
}
function observeIntersection(element, options, callback) {
const rootInteresectionObserver = initIntersectionObserver(options);
observerCallbacks.set(element, callback);
rootInteresectionObserver.observe(element);
return () => {
observerCallbacks.delete(element);
rootInteresectionObserver.unobserve(element);
};
}
export { observeIntersection };

108
node_modules/framer-motion/dist/es/motion/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,108 @@
"use client";
import { jsxs, jsx } from 'react/jsx-runtime';
import { warning, invariant } from 'motion-utils';
import { forwardRef, useContext } from 'react';
import { LayoutGroupContext } from '../context/LayoutGroupContext.mjs';
import { LazyContext } from '../context/LazyContext.mjs';
import { MotionConfigContext } from '../context/MotionConfigContext.mjs';
import { MotionContext } from '../context/MotionContext/index.mjs';
import { useCreateMotionContext } from '../context/MotionContext/create.mjs';
import { useRender } from '../render/dom/use-render.mjs';
import { isSVGComponent } from '../render/dom/utils/is-svg-component.mjs';
import { useHTMLVisualState } from '../render/html/use-html-visual-state.mjs';
import { useSVGVisualState } from '../render/svg/use-svg-visual-state.mjs';
import { isBrowser } from '../utils/is-browser.mjs';
import { featureDefinitions } from './features/definitions.mjs';
import { loadFeatures } from './features/load-features.mjs';
import { motionComponentSymbol } from './utils/symbol.mjs';
import { useMotionRef } from './utils/use-motion-ref.mjs';
import { useVisualElement } from './utils/use-visual-element.mjs';
/**
* Create a `motion` component.
*
* This function accepts a Component argument, which can be either a string (ie "div"
* for `motion.div`), or an actual React component.
*
* Alongside this is a config option which provides a way of rendering the provided
* component "offline", or outside the React render cycle.
*/
function createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) {
preloadedFeatures && loadFeatures(preloadedFeatures);
const useVisualState = isSVGComponent(Component)
? useSVGVisualState
: useHTMLVisualState;
function MotionDOMComponent(props, externalRef) {
/**
* If we need to measure the element we load this functionality in a
* separate class component in order to gain access to getSnapshotBeforeUpdate.
*/
let MeasureLayout;
const configAndProps = {
...useContext(MotionConfigContext),
...props,
layoutId: useLayoutId(props),
};
const { isStatic } = configAndProps;
const context = useCreateMotionContext(props);
const visualState = useVisualState(props, isStatic);
if (!isStatic && isBrowser) {
useStrictMode(configAndProps, preloadedFeatures);
const layoutProjection = getProjectionFunctionality(configAndProps);
MeasureLayout = layoutProjection.MeasureLayout;
/**
* Create a VisualElement for this component. A VisualElement provides a common
* interface to renderer-specific APIs (ie DOM/Three.js etc) as well as
* providing a way of rendering to these APIs outside of the React render loop
* for more performant animations and interactions
*/
context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode);
}
/**
* The mount order and hierarchy is specific to ensure our element ref
* is hydrated by the time features fire their effects.
*/
return (jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] }));
}
MotionDOMComponent.displayName = `motion.${typeof Component === "string"
? Component
: `create(${Component.displayName ?? Component.name ?? ""})`}`;
const ForwardRefMotionComponent = forwardRef(MotionDOMComponent);
ForwardRefMotionComponent[motionComponentSymbol] = Component;
return ForwardRefMotionComponent;
}
function useLayoutId({ layoutId }) {
const layoutGroupId = useContext(LayoutGroupContext).id;
return layoutGroupId && layoutId !== undefined
? layoutGroupId + "-" + layoutId
: layoutId;
}
function useStrictMode(configAndProps, preloadedFeatures) {
const isStrict = useContext(LazyContext).strict;
/**
* If we're in development mode, check to make sure we're not rendering a motion component
* as a child of LazyMotion, as this will break the file-size benefits of using it.
*/
if (process.env.NODE_ENV !== "production" &&
preloadedFeatures &&
isStrict) {
const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";
configAndProps.ignoreStrict
? warning(false, strictMessage, "lazy-strict-mode")
: invariant(false, strictMessage, "lazy-strict-mode");
}
}
function getProjectionFunctionality(props) {
const { drag, layout } = featureDefinitions;
if (!drag && !layout)
return {};
const combined = { ...drag, ...layout };
return {
MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props)
? combined.MeasureLayout
: undefined,
ProjectionNode: combined.ProjectionNode,
};
}
export { createMotionComponent };

View File

@@ -0,0 +1,11 @@
import { transformProps } from 'motion-dom';
import { scaleCorrectors } from '../../projection/styles/scale-correction.mjs';
function isForcedMotionValue(key, { layout, layoutId }) {
return (transformProps.has(key) ||
key.startsWith("origin") ||
((layout || layoutId !== undefined) &&
(!!scaleCorrectors[key] || key === "opacity")));
}
export { isForcedMotionValue };

View File

@@ -0,0 +1,12 @@
import { motionComponentSymbol } from './symbol.mjs';
/**
* Checks if a component is a `motion` component.
*/
function isMotionComponent(component) {
return (component !== null &&
typeof component === "object" &&
motionComponentSymbol in component);
}
export { isMotionComponent };

View File

@@ -0,0 +1,3 @@
const motionComponentSymbol = Symbol.for("motionComponentSymbol");
export { motionComponentSymbol };

View File

@@ -0,0 +1,17 @@
import { isMotionComponent } from './is-motion-component.mjs';
import { motionComponentSymbol } from './symbol.mjs';
/**
* Unwraps a `motion` component and returns either a string for `motion.div` or
* the React component for `motion(Component)`.
*
* If the component is not a `motion` component it returns undefined.
*/
function unwrapMotionComponent(component) {
if (isMotionComponent(component)) {
return component[motionComponentSymbol];
}
return undefined;
}
export { unwrapMotionComponent };

View File

@@ -0,0 +1,38 @@
"use client";
import { useCallback } from 'react';
import { isRefObject } from '../../utils/is-ref-object.mjs';
/**
* Creates a ref function that, when called, hydrates the provided
* external ref and VisualElement.
*/
function useMotionRef(visualState, visualElement, externalRef) {
return useCallback((instance) => {
if (instance) {
visualState.onMount && visualState.onMount(instance);
}
if (visualElement) {
if (instance) {
visualElement.mount(instance);
}
else {
visualElement.unmount();
}
}
if (externalRef) {
if (typeof externalRef === "function") {
externalRef(instance);
}
else if (isRefObject(externalRef)) {
externalRef.current = instance;
}
}
},
/**
* Include externalRef in dependencies to ensure the callback updates
* when the ref changes, allowing proper ref forwarding.
*/
[visualElement]);
}
export { useMotionRef };

View File

@@ -0,0 +1,140 @@
"use client";
import { useContext, useRef, useInsertionEffect, useEffect } from 'react';
import { optimizedAppearDataAttribute } from '../../animation/optimized-appear/data-id.mjs';
import { LazyContext } from '../../context/LazyContext.mjs';
import { MotionConfigContext } from '../../context/MotionConfigContext.mjs';
import { MotionContext } from '../../context/MotionContext/index.mjs';
import { PresenceContext } from '../../context/PresenceContext.mjs';
import { SwitchLayoutGroupContext } from '../../context/SwitchLayoutGroupContext.mjs';
import { isRefObject } from '../../utils/is-ref-object.mjs';
import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';
function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) {
const { visualElement: parent } = useContext(MotionContext);
const lazyContext = useContext(LazyContext);
const presenceContext = useContext(PresenceContext);
const reducedMotionConfig = useContext(MotionConfigContext).reducedMotion;
const visualElementRef = useRef(null);
/**
* If we haven't preloaded a renderer, check to see if we have one lazy-loaded
*/
createVisualElement =
createVisualElement ||
lazyContext.renderer;
if (!visualElementRef.current && createVisualElement) {
visualElementRef.current = createVisualElement(Component, {
visualState,
parent,
props,
presenceContext,
blockInitialAnimation: presenceContext
? presenceContext.initial === false
: false,
reducedMotionConfig,
});
}
const visualElement = visualElementRef.current;
/**
* Load Motion gesture and animation features. These are rendered as renderless
* components so each feature can optionally make use of React lifecycle methods.
*/
const initialLayoutGroupConfig = useContext(SwitchLayoutGroupContext);
if (visualElement &&
!visualElement.projection &&
ProjectionNodeConstructor &&
(visualElement.type === "html" || visualElement.type === "svg")) {
createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig);
}
const isMounted = useRef(false);
useInsertionEffect(() => {
/**
* Check the component has already mounted before calling
* `update` unnecessarily. This ensures we skip the initial update.
*/
if (visualElement && isMounted.current) {
visualElement.update(props, presenceContext);
}
});
/**
* Cache this value as we want to know whether HandoffAppearAnimations
* was present on initial render - it will be deleted after this.
*/
const optimisedAppearId = props[optimizedAppearDataAttribute];
const wantsHandoff = useRef(Boolean(optimisedAppearId) &&
!window.MotionHandoffIsComplete?.(optimisedAppearId) &&
window.MotionHasOptimisedAnimation?.(optimisedAppearId));
useIsomorphicLayoutEffect(() => {
if (!visualElement)
return;
isMounted.current = true;
window.MotionIsMounted = true;
visualElement.updateFeatures();
visualElement.scheduleRenderMicrotask();
/**
* Ideally this function would always run in a useEffect.
*
* However, if we have optimised appear animations to handoff from,
* it needs to happen synchronously to ensure there's no flash of
* incorrect styles in the event of a hydration error.
*
* So if we detect a situtation where optimised appear animations
* are running, we use useLayoutEffect to trigger animations.
*/
if (wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
});
useEffect(() => {
if (!visualElement)
return;
if (!wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
if (wantsHandoff.current) {
// This ensures all future calls to animateChanges() in this component will run in useEffect
queueMicrotask(() => {
window.MotionHandoffMarkAsComplete?.(optimisedAppearId);
});
wantsHandoff.current = false;
}
/**
* Now we've finished triggering animations for this element we
* can wipe the enteringChildren set for the next render.
*/
visualElement.enteringChildren = undefined;
});
return visualElement;
}
function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) {
const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props;
visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"]
? undefined
: getClosestProjectingNode(visualElement.parent));
visualElement.projection.setOptions({
layoutId,
layout,
alwaysMeasureLayout: Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)),
visualElement,
/**
* TODO: Update options in an effect. This could be tricky as it'll be too late
* to update by the time layout animations run.
* We also need to fix this safeToRemove by linking it up to the one returned by usePresence,
* ensuring it gets called if there's no potential layout animations.
*
*/
animationType: typeof layout === "string" ? layout : "both",
initialPromotionConfig,
crossfade: layoutCrossfade,
layoutScroll,
layoutRoot,
});
}
function getClosestProjectingNode(visualElement) {
if (!visualElement)
return undefined;
return visualElement.options.allowProjection !== false
? visualElement.projection
: getClosestProjectingNode(visualElement.parent);
}
export { useVisualElement };

Some files were not shown because too many files have changed in this diff Show More