( ref: RefObject<HTMLElement | null>, isReady: boolean = true, onEnter?: (element: HTMLElement) => void | Promise<void> )
| 18 | import {useLayoutEffect} from './useLayoutEffect'; |
| 19 | |
| 20 | export function useEnterAnimation( |
| 21 | ref: RefObject<HTMLElement | null>, |
| 22 | isReady: boolean = true, |
| 23 | onEnter?: (element: HTMLElement) => void | Promise<void> |
| 24 | ): boolean { |
| 25 | let [isEntering, setEntering] = useState(true); |
| 26 | let isAnimationReady = isEntering && isReady; |
| 27 | |
| 28 | // Hide the element while it prepares for entry, using only non-layout-thrashing attributes. |
| 29 | // This prevents accidental flashes of content in scenarios where no hidden styling is applied |
| 30 | // while the enter animation is not yet ready (e.g. popovers prior to placement calculation). |
| 31 | useLayoutEffect(() => { |
| 32 | if (!isReady && ref.current) { |
| 33 | return chain( |
| 34 | setStyle(ref.current, 'opacity', '0'), |
| 35 | setStyle(ref.current, 'clip', 'rect(0 0 0 0)'), |
| 36 | setStyle(ref.current, 'clip-path', 'inset(50%)'), |
| 37 | setStyle(ref.current, 'mask-image', 'linear-gradient(#0000, #0000)') |
| 38 | ); |
| 39 | } |
| 40 | }, [ref, isReady]); |
| 41 | |
| 42 | // There are two cases for entry animations: |
| 43 | // 1. CSS @keyframes. The `animation` property is set during the isEntering state, and it is removed after the animation finishes. |
| 44 | // 2. CSS transitions. The initial styles are applied during the isEntering state, and removed immediately, causing the transition to occur. |
| 45 | // |
| 46 | // In the second case, cancel any transitions that were triggered prior to the isEntering = false state (when the transition is supposed to start). |
| 47 | // This can happen when isReady starts as false (e.g. popovers prior to placement calculation). |
| 48 | useLayoutEffect(() => { |
| 49 | if (isAnimationReady && ref.current && 'getAnimations' in ref.current) { |
| 50 | for (let animation of ref.current.getAnimations()) { |
| 51 | if (animation instanceof CSSTransition) { |
| 52 | animation.cancel(); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | }, [ref, isAnimationReady]); |
| 57 | |
| 58 | useAnimation( |
| 59 | ref, |
| 60 | isAnimationReady, |
| 61 | onEnter, |
| 62 | useCallback(() => setEntering(false), []) |
| 63 | ); |
| 64 | return isAnimationReady; |
| 65 | } |
| 66 | |
| 67 | export function useExitAnimation( |
| 68 | ref: RefObject<HTMLElement | null>, |
no test coverage detected