|
| 1 | +import * as React from 'react'; |
| 2 | +import { useLayoutEffect } from 'soybean-react-ui/use-layout-effect'; |
| 3 | + |
| 4 | +import { useStateMachine } from './use-state-machine'; |
| 5 | + |
| 6 | +export function usePresence(present: boolean) { |
| 7 | + const [node, setNode] = React.useState<HTMLElement>(); |
| 8 | + const stylesRef = React.useRef<CSSStyleDeclaration | null>(null); |
| 9 | + const prevPresentRef = React.useRef(present); |
| 10 | + const prevAnimationNameRef = React.useRef<string>('none'); |
| 11 | + const initialState = present ? 'mounted' : 'unmounted'; |
| 12 | + const [state, send] = useStateMachine(initialState, { |
| 13 | + mounted: { |
| 14 | + ANIMATION_OUT: 'unmountSuspended', |
| 15 | + UNMOUNT: 'unmounted' |
| 16 | + }, |
| 17 | + unmounted: { |
| 18 | + MOUNT: 'mounted' |
| 19 | + }, |
| 20 | + unmountSuspended: { |
| 21 | + ANIMATION_END: 'unmounted', |
| 22 | + MOUNT: 'mounted' |
| 23 | + } |
| 24 | + }); |
| 25 | + |
| 26 | + React.useEffect(() => { |
| 27 | + const currentAnimationName = getAnimationName(stylesRef.current); |
| 28 | + prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none'; |
| 29 | + }, [state]); |
| 30 | + |
| 31 | + useLayoutEffect(() => { |
| 32 | + const styles = stylesRef.current; |
| 33 | + const wasPresent = prevPresentRef.current; |
| 34 | + const hasPresentChanged = wasPresent !== present; |
| 35 | + |
| 36 | + if (hasPresentChanged) { |
| 37 | + const prevAnimationName = prevAnimationNameRef.current; |
| 38 | + const currentAnimationName = getAnimationName(styles); |
| 39 | + |
| 40 | + if (present) { |
| 41 | + send('MOUNT'); |
| 42 | + } else if (currentAnimationName === 'none' || styles?.display === 'none') { |
| 43 | + // If there is no exit animation or the element is hidden, animations won't run |
| 44 | + // so we unmount instantly |
| 45 | + send('UNMOUNT'); |
| 46 | + } else { |
| 47 | + /** |
| 48 | + * When `present` changes to `false`, we check changes to animation-name to |
| 49 | + * determine whether an animation has started. We chose this approach (reading |
| 50 | + * computed styles) because there is no `animationrun` event and `animationstart` |
| 51 | + * fires after `animation-delay` has expired which would be too late. |
| 52 | + */ |
| 53 | + const isAnimating = prevAnimationName !== currentAnimationName; |
| 54 | + |
| 55 | + if (wasPresent && isAnimating) { |
| 56 | + send('ANIMATION_OUT'); |
| 57 | + } else { |
| 58 | + send('UNMOUNT'); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + prevPresentRef.current = present; |
| 63 | + } |
| 64 | + }, [present, send]); |
| 65 | + |
| 66 | + useLayoutEffect(() => { |
| 67 | + if (node) { |
| 68 | + let timeoutId: number; |
| 69 | + const ownerWindow = node.ownerDocument.defaultView ?? window; |
| 70 | + /** |
| 71 | + * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` |
| 72 | + * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we |
| 73 | + * make sure we only trigger ANIMATION_END for the currently active animation. |
| 74 | + */ |
| 75 | + const handleAnimationEnd = (event: AnimationEvent) => { |
| 76 | + const currentAnimationName = getAnimationName(stylesRef.current); |
| 77 | + const isCurrentAnimation = currentAnimationName.includes(event.animationName); |
| 78 | + if (event.target === node && isCurrentAnimation) { |
| 79 | + // With React 18 concurrency this update is applied a frame after the |
| 80 | + // animation ends, creating a flash of visible content. By setting the |
| 81 | + // animation fill mode to "forwards", we force the node to keep the |
| 82 | + // styles of the last keyframe, removing the flash. |
| 83 | + // |
| 84 | + // Previously we flushed the update via ReactDom.flushSync, but with |
| 85 | + // exit animations this resulted in the node being removed from the |
| 86 | + // DOM before the synthetic animationEnd event was dispatched, meaning |
| 87 | + // user-provided event handlers would not be called. |
| 88 | + // https://github.com/radix-ui/primitives/pull/1849 |
| 89 | + send('ANIMATION_END'); |
| 90 | + if (!prevPresentRef.current) { |
| 91 | + const currentFillMode = node.style.animationFillMode; |
| 92 | + node.style.animationFillMode = 'forwards'; |
| 93 | + // Reset the style after the node had time to unmount (for cases |
| 94 | + // where the component chooses not to unmount). Doing this any |
| 95 | + // sooner than `setTimeout` (e.g. with `requestAnimationFrame`) |
| 96 | + // still causes a flash. |
| 97 | + timeoutId = ownerWindow.setTimeout(() => { |
| 98 | + if (node.style.animationFillMode === 'forwards') { |
| 99 | + node.style.animationFillMode = currentFillMode; |
| 100 | + } |
| 101 | + }); |
| 102 | + } |
| 103 | + } |
| 104 | + }; |
| 105 | + const handleAnimationStart = (event: AnimationEvent) => { |
| 106 | + if (event.target === node) { |
| 107 | + // if animation occurred, store its name as the previous animation. |
| 108 | + prevAnimationNameRef.current = getAnimationName(stylesRef.current); |
| 109 | + } |
| 110 | + }; |
| 111 | + node.addEventListener('animationstart', handleAnimationStart); |
| 112 | + node.addEventListener('animationcancel', handleAnimationEnd); |
| 113 | + node.addEventListener('animationend', handleAnimationEnd); |
| 114 | + return () => { |
| 115 | + ownerWindow.clearTimeout(timeoutId); |
| 116 | + node.removeEventListener('animationstart', handleAnimationStart); |
| 117 | + node.removeEventListener('animationcancel', handleAnimationEnd); |
| 118 | + node.removeEventListener('animationend', handleAnimationEnd); |
| 119 | + }; |
| 120 | + } |
| 121 | + // Transition to the unmounted state if the node is removed prematurely. |
| 122 | + // We avoid doing so during cleanup as the node may change but still exist. |
| 123 | + send('ANIMATION_END'); |
| 124 | + return () => {}; |
| 125 | + }, [node, send]); |
| 126 | + |
| 127 | + return { |
| 128 | + isPresent: ['mounted', 'unmountSuspended'].includes(state), |
| 129 | + ref: React.useCallback((newNode: HTMLElement) => { |
| 130 | + stylesRef.current = newNode ? getComputedStyle(newNode) : null; |
| 131 | + setNode(newNode); |
| 132 | + }, []) |
| 133 | + }; |
| 134 | +} |
| 135 | + |
| 136 | +/* ----------------------------------------------------------------------------------------------- */ |
| 137 | + |
| 138 | +function getAnimationName(styles: CSSStyleDeclaration | null) { |
| 139 | + return styles?.animationName || 'none'; |
| 140 | +} |
0 commit comments