( ref: RefObject<HTMLElement | null>, isActive: boolean, onStart: ((element: HTMLElement) => void | Promise<void>) | undefined, onEnd: () => void )
| 105 | } |
| 106 | |
| 107 | function useAnimation( |
| 108 | ref: RefObject<HTMLElement | null>, |
| 109 | isActive: boolean, |
| 110 | onStart: ((element: HTMLElement) => void | Promise<void>) | undefined, |
| 111 | onEnd: () => void |
| 112 | ): void { |
| 113 | let isActiveRef = useRef<boolean | null>(null); |
| 114 | let start = useEffectEvent(onStart); |
| 115 | useLayoutEffect(() => { |
| 116 | if (isActive && ref.current && isActiveRef.current !== isActive) { |
| 117 | isActiveRef.current = isActive; |
| 118 | if (!('getAnimations' in ref.current)) { |
| 119 | // JSDOM |
| 120 | onEnd(); |
| 121 | return; |
| 122 | } |
| 123 | |
| 124 | let startPromise = start?.(ref.current); |
| 125 | |
| 126 | let animations = ref.current |
| 127 | .getAnimations() |
| 128 | .filter( |
| 129 | a => |
| 130 | (typeof DocumentTimeline === 'undefined' || a.timeline instanceof DocumentTimeline) && |
| 131 | a.playState === 'running' |
| 132 | ); |
| 133 | if (animations.length === 0 && !startPromise) { |
| 134 | onEnd(); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | Promise.all([startPromise, ...animations.map(a => a.finished)]) |
| 139 | .then(() => { |
| 140 | flushSync(() => { |
| 141 | onEnd(); |
| 142 | }); |
| 143 | }) |
| 144 | .catch(() => {}); |
| 145 | } |
| 146 | |
| 147 | isActiveRef.current = isActive; |
| 148 | }, [ref, isActive, onEnd]); |
| 149 | } |
no test coverage detected