import { Animated } from "react-native";
import React, {
forwardRef,
PropsWithChildren,
useEffect,
useImperativeHandle,
useRef,
useState,
} from "react";
export interface SlideAnimationConfig {
duration?: number;
translateX?: number;
translateY?: number;
}
/**
* @interface SlideProps
* @param {React.ReactNode} children
* @param {Function} onSlideStart - callback to track when the animation starts
* @param {Function} onSlideEnd - callback to track when the animation ends
* @param {SlideAnimationConfig} config - to control "duration" of animation, "start" and "end" opacity of child component
*/
type SlideProps = PropsWithChildren<{
onSlideStart?: Function;
onSlideEnd?: Animated.EndCallback;
config?: SlideAnimationConfig;
}>;
export type AnimationHandle = {
/**
* @description triggers slide animation
* @returns {void}
*/
triggerAnimation: () => void;
};
/**
* @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 {SlideAnimationConfig} config - to control "duration" of animation, "start" and "end" opacity of child component
* @example
*
* Hello
*
*/
const Slide = forwardRef((props, ref) => {
const {
children,
config = {},
onSlideStart = () => {},
onSlideEnd = () => {},
} = props;
const { duration = 1000, translateY = 30, translateX = 0 } = config;
const animation = useRef(new Animated.Value(0)).current;
// 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();
useImperativeHandle(ref, () => ({
// used to re-trigger the transition after initial transition
triggerAnimation() {
animation.setValue(0);
Animated.timing(animation, {
toValue: 1,
duration,
useNativeDriver: true,
}).start(onSlideEnd);
onSlideStart();
setReUseOffset(translateY);
},
}));
// used to trigger the initial transition on mount
useEffect(() => {
animation.setValue(0);
Animated.timing(animation, {
toValue: 1,
duration,
useNativeDriver: true,
}).start(onSlideEnd);
onSlideStart();
setReUseOffset(translateY);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
{children}
);
});
export default Slide;