/* eslint-disable react-hooks/exhaustive-deps */ import { Animated } from "react-native"; import React, { useEffect, useImperativeHandle, useRef, useState } from "react"; export interface ScaleAnimationConfig { duration?: number; startScale?: number; endScale?: number; } /** * @interface ScaleProps * @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 {ScaleAnimationConfig} config - to control "duration" of animation, "start" and "end" scale of child component */ interface ScaleProps { children: React.ReactNode; onScaleStart?: Function; onScaleEnd?: Animated.EndCallback; config?: ScaleAnimationConfig; } /** * @interface ScaleAnimationHandle */ export interface ScaleAnimationHandle { /** * @param {number} scaleTo - the scale value to scale onto * @description triggers scale animation from the endScale of initial config * to the param provided * @returns {void} */ triggerAnimation: (scaleTo: number) => void; } /** * @component * Represents a Scale component instance * @param {React.ReactNode} children * @param {Function} onScaleStart - callback to track when the animation starts * @param {Function} onScaleEnd - callback to track when the animation ends * @param {ScaleAnimationConfig} config - to control "duration" of animation, "start" and "end" opacity of child component * @example * * Hello * */ const Scale = React.forwardRef( ( { children, onScaleStart = () => {}, onScaleEnd = () => {}, config = {}, }: ScaleProps, ref ) => { const { duration = 1000, startScale = 1, endScale = 1.5 } = 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(startScale as number)).current; // used to trigger the initial transition on mount useEffect(() => { Animated.timing(animation, { toValue: endScale as number, duration: duration as number, useNativeDriver: true, }).start(onScaleEnd); onScaleStart(); setReUseOffset(endScale as number); }, []); useImperativeHandle(ref, () => ({ // used to re-trigger the transition after initial transition triggerAnimation(scaleTo) { if (reUseOffset) animation.setValue(reUseOffset as number); Animated.timing(animation, { toValue: scaleTo, duration: duration as number, useNativeDriver: true, }).start(onScaleEnd); onScaleStart(); setReUseOffset(scaleTo); }, })); return ( {children} ); } ); export default Scale;