/* eslint-disable react-hooks/exhaustive-deps */ import { Animated } from "react-native"; import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState, } from "react"; /** * @interface FadeAnimationHandle */ export interface FadeAnimationHandle { /** * @param {number} fadeTo - the fade value to fade onto * @description triggers fade animation from the endOpacity of initial config * to the param provided * @returns {void} */ triggerAnimation: (fadeTo: number) => void; } export interface FadeAnimationConfig { duration?: number; startOpacity?: number; endOpacity?: number; } /** * @interface FadeProps * @param {React.ReactNode} children * @param {Function} onFadeStart - callback to track when the animation starts * @param {Function} onFadeEnd - callback to track when the animation ends * @param {FadeAnimationConfig} config - to control "duration" of animation, "start" and "end" opacity of child component */ interface FadeProps { children: React.ReactNode; onFadeStart?: Function; onFadeEnd?: Animated.EndCallback; config?: FadeAnimationConfig; } /** * @component * Represents a Fade component instance * @param {React.ReactNode} children * @param {Function} onFadeStart - callback to track when the animation starts * @param {Function} onFadeEnd - callback to track when the animation ends * @param {FadeAnimationConfig} config - to control "duration" of animation, "start" and "end" opacity of child component * @example * * Hello * */ const Fade = forwardRef( ( { children, onFadeStart = () => {}, onFadeEnd = () => {}, config = {}, }: FadeProps, ref ) => { const { duration = 1000, startOpacity = 0, endOpacity = 1 } = config; // once the component runs it initial transition // it stores the value to be used as initial point for the next transition const [reUseOffset, setReUseOffset] = useState(); const animation = useRef( new Animated.Value(startOpacity as number) ).current; // used to trigger the initial transition on mount useEffect(() => { Animated.timing(animation, { toValue: endOpacity as number, duration: duration as number, useNativeDriver: true, }).start(onFadeEnd); onFadeStart(); setReUseOffset(endOpacity); }, []); useImperativeHandle(ref, () => ({ // used to re-trigger the transition after initial transition triggerAnimation(fadeTo) { if (reUseOffset) animation.setValue(reUseOffset as number); Animated.timing(animation, { toValue: fadeTo, duration: duration as number, useNativeDriver: true, }).start(onFadeEnd); onFadeStart(); setReUseOffset(fadeTo); }, })); return ( {children} ); } ); export default Fade;