UNPKG

@atlaskit/motion

Version:

A set of utilities to apply motion in your application.

201 lines (194 loc) 8.6 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; // Exposes start and finish callbacks while useMotion coordinates the animation lifecycle. import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import mergeRefs from '@atlaskit/ds-lib/merge-refs'; import { getComputedAnimationDurationMs } from '../utils/get-computed-animation-duration-ms'; import { getDurationMs } from '../utils/get-duration-ms'; import { isReducedMotion } from '../utils/is-reduced-motion'; import { useLayoutEffect } from '../utils/use-layout-effect'; import { resolveMotionToken } from '../utils/resolve-motion-token'; import { Reanimate } from './reanimate'; import { useExitingPersistence } from './use-exiting-persistence'; import { useStaggeredEntrance } from './use-staggered-entrance'; /** * __useMotion__ * * A hook form of the `Motion` primitive. It manages the entering/exiting animation * lifecycle and returns `{ ref, reanimate, state }` so that motion can be applied to * an existing element __without__ introducing an extra wrapper element. The consumer * drives the animation styling from `state` (e.g. via a `cssMap`) and applies the * animation to their own element. * * The returned `ref` __must__ be attached to the animated element, otherwise exit * timing, `onFinish`, and `ExitingPersistence` removal will not work. */ export function useMotion() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, onFinishMotion = _ref.onFinish, onStartMotion = _ref.onStart, initialState = _ref.initialState; var reducedMotion = isReducedMotion(); var staggered = useStaggeredEntrance(); var _useExitingPersistenc = useExitingPersistence(), isExiting = _useExitingPersistenc.isExiting, onExitFinished = _useExitingPersistenc.onFinish, appear = _useExitingPersistenc.appear; var staggeredDelay = isExiting ? 0 : staggered.delay; var staggeredIsReady = staggered.isReady; var _useState = useState(initialState !== null && initialState !== void 0 ? initialState : appear ? staggeredIsReady && !staggeredDelay ? 'entering' : 'init' : 'visible'), _useState2 = _slicedToArray(_useState, 2), state = _useState2[0], setState = _useState2[1]; // ExitingPersistence must win during render so consumers apply exit styles before layout effects. // The lifecycle effect below uses the same value to measure and finish that exit. var motionState = isExiting ? 'exiting' : state; var elementRef = useRef(null); var onStartMotionRef = useRef(onStartMotion); onStartMotionRef.current = onStartMotion; var reanimateRef = useRef(); var animationRef = useRef(); var staggeredEntryRef = useRef(); useLayoutEffect(function () { if (motionState === 'exiting') { var _onStartMotionRef$cur; (_onStartMotionRef$cur = onStartMotionRef.current) === null || _onStartMotionRef$cur === void 0 || _onStartMotionRef$cur.call(onStartMotionRef, 'exiting'); } if (motionState === 'entering') { var _onStartMotionRef$cur2; (_onStartMotionRef$cur2 = onStartMotionRef.current) === null || _onStartMotionRef$cur2 === void 0 || _onStartMotionRef$cur2.call(onStartMotionRef, 'entering'); } }, [motionState]); /** * Updates relevant state. * Called when the animation is finished, or immediately with reduced motion. */ var onAnimationEnd = useCallback(function (currentState, cancelled) { // We are done animating, so we set the state to visible var newState = 'visible'; if (currentState === 'exiting') { if (!reanimateRef.current) { // Updates the `ExitingPersistence` to remove this child onExitFinished === null || onExitFinished === void 0 || onExitFinished(); } onFinishMotion === null || onFinishMotion === void 0 || onFinishMotion('exiting'); } if (currentState === 'entering') { onFinishMotion === null || onFinishMotion === void 0 || onFinishMotion('entering'); } if (reanimateRef.current === Reanimate.exit_then_enter) { // We are done exiting, so we set the state to entering reanimateRef.current = Reanimate.enter; newState = 'entering'; } else if (reanimateRef.current === Reanimate.enter) { // We are done reanimating, so we clear the reanimate state reanimateRef.current = undefined; } else if (reanimateRef.current === Reanimate.exit) { // We are done reanimating, so we clear the reanimate state reanimateRef.current = undefined; newState = 'hidden'; } if (!cancelled) { setState(newState); } // We ignore this for onFinishMotion as consumers could potentially inline the function // which would then trigger this effect every re-render. // We want to make it easier for consumers so we go down this path unfortunately. }, // eslint-disable-next-line react-hooks/exhaustive-deps [onExitFinished]); // Handles staggered entry useEffect(function () { if (state !== 'init') { return; } if (reducedMotion) { onAnimationEnd('entering', false); return; } // We delay the entry animation by the stagger delay staggeredEntryRef.current = setTimeout(function () { setState('entering'); }, staggeredDelay); return function () { if (staggeredEntryRef.current) { clearTimeout(staggeredEntryRef.current); } }; }, [onAnimationEnd, state, staggeredIsReady, staggeredDelay, reducedMotion]); useEffect(function () { // Tracking this to prevent changing state on an unmounted component var isCancelled = false; if (!staggeredIsReady) { return; } // On initial mount if elements aren't set to animate on appear, we return early and callback // This only occurs on initial mount, as appear will be true once the component is mounted if (!appear) { onFinishMotion && onFinishMotion('entering'); return; } // If the state is visible, hidden or init, we don't need to do anything if (motionState === 'visible' || motionState === 'init' || motionState === 'hidden') { return; } // If there is reduced motion or no exit animation, we call the onAnimationEnd function immediately if (reducedMotion) { onAnimationEnd(motionState, isCancelled); return; } var animationDuration = 0; if (motionState === 'entering' || motionState === 'exiting') { if (elementRef.current) { if (elementRef.current.style.animation) { // Motion token var animationTimings = getDurationMs(resolveMotionToken(elementRef.current.style.animation)); animationDuration = animationTimings.duration; animationDuration += animationTimings.delay; } else { // Custom motion var computedStyles = window.getComputedStyle(elementRef.current); animationDuration = getComputedAnimationDurationMs(computedStyles.animationName, computedStyles.animationDuration, computedStyles.animationDelay); } } } // Queue `onAnimationEnd` for after the animation has finished if (motionState === 'exiting') { animationRef.current = setTimeout(function () { return onAnimationEnd(motionState, isCancelled); }, animationDuration); } else if (motionState === 'entering') { animationRef.current = setTimeout(function () { return onAnimationEnd(motionState, isCancelled); }, animationDuration); } return function () { isCancelled = true; if (animationRef.current) { clearTimeout(animationRef.current); } }; // We ignore this for onFinishMotion as consumers could potentially inline the function // which would then trigger this effect every re-render. // We want to make it easier for consumers so we go down this path unfortunately. // eslint-disable-next-line react-hooks/exhaustive-deps }, [onAnimationEnd, motionState, appear, staggeredDelay, staggeredIsReady, reducedMotion]); var reanimate = useCallback(function (value) { animationRef.current && clearTimeout(animationRef.current); reanimateRef.current = value; if (value === Reanimate.exit_then_enter) { setState('exiting'); } else if (value === Reanimate.enter) { setState('entering'); } else if (value === Reanimate.exit) { setState('exiting'); } }, []); var ref = useMemo(function () { return mergeRefs([staggered.ref, elementRef]); }, [staggered.ref]); return { ref: ref, reanimate: reanimate, state: motionState }; }