Skip to content
Snippets Groups Projects
useAnimate.tsx 2.23 KiB
Newer Older
import {SetStateAction, useEffect, useState} from "react";
import {TypewriterClass} from "typewriter-effect";
import {useNavigate} from "react-router-dom";
import {useRecoilValue} from "recoil";
import {languageAtom} from "../atoms/languageAtom";

export interface Texts {
    EN: string;
    SK: string;
}
interface AnimateProps {
    typewriterRef:  React.MutableRefObject<TypewriterClass | undefined>,
    link: string,
    text: Texts[]
}
export const useAnimate = ({link, text, typewriterRef}: AnimateProps) => {
    const language = useRecoilValue(languageAtom);

    const [paused, setPaused] = useState(false);
    const [, setAnimationObject] = useState(null);
    const getAnimationObject = (obj: SetStateAction<null>) => setAnimationObject(obj);

    const [currentIndex, setCurrentIndex] = useState(0);
    const [isAnimationComplete, setIsAnimationComplete] = useState(false);
    const line = text[currentIndex];
    const navigate = useNavigate();

    useEffect(() => {
        if (typewriterRef.current) {
            typewriterRef.current.deleteAll(0.0000000000000000000001);
            typewriterRef.current
                .typeString(line[language as keyof Texts])
                .start()
                .callFunction(() => {
                    setIsAnimationComplete(true);
                    setPaused(true)
                });
        }
    }, [language, currentIndex]);

    const handleClick = () => {
        if(currentIndex == text.length -1) {
            navigate(link);
        }
        if (isAnimationComplete) {
            setCurrentIndex((prevIndex) => (prevIndex + 1) % text.length);
            setIsAnimationComplete(false);
            setPaused(false);
        }
    };

    const onInit = ({ typewriter, pauseFor }: { typewriter: TypewriterClass; pauseFor: number }) => {
            typewriterRef.current = typewriter;
            typewriter
                .pauseFor(pauseFor)
                .typeString(line[language as keyof Texts])
                .start()
                .callFunction(() => {
                    setIsAnimationComplete(true);
                    setPaused(true);
                });
    }

    return {paused, isAnimationComplete, isLast: currentIndex == text.length - 1, getAnimationObject, handleClick, onInit}
}