import React, {SetStateAction, useEffect, useRef, 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[], audioFiles: string[] } export const useAnimate = ({link, text, typewriterRef, audioFiles}: AnimateProps) => { const language = useRecoilValue(languageAtom); const [paused, setPaused] = useState(false); const [animationObj, setAnimationObject] = useState<unknown>(null); const getAnimationObject = (obj: SetStateAction<null>) => setAnimationObject(obj); const [currentIndex, setCurrentIndex] = useState(0); const [isAnimationComplete, setIsAnimationComplete] = useState(false); const [isMuted, setIsMuted] = useState(false); const line = text[currentIndex]; const navigate = useNavigate(); const audioRef = useRef<HTMLAudioElement | null>(null); useEffect(() => { audioRef.current = new Audio(audioFiles[currentIndex]); }, []); useEffect(() => { if (typewriterRef.current) { typewriterRef.current.deleteAll(0.0000000000000000000001); if (audioRef.current) { audioRef.current.play(); } 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); if (audioRef.current) { audioRef.current.src = audioFiles[currentIndex + 1]; audioRef.current.load(); } } }; const handleMuteToggle = () => { if (audioRef.current) { audioRef.current.muted = !isMuted; setIsMuted(!isMuted); } }; const onInit = ({typewriter, pauseFor}: { typewriter: TypewriterClass; pauseFor: number }) => { typewriterRef.current = typewriter; typewriter .pauseFor(pauseFor) .callFunction(() => { if (audioRef.current) { // audioRef.current.play(); } }) .typeString(line[language as keyof Texts]) .start() .callFunction(() => { setIsAnimationComplete(true); setPaused(true); }); } return { paused, isAnimationComplete, isLast: currentIndex == text.length - 1, getAnimationObject, handleClick, onInit, handleMuteToggle, isMuted, animationObj } }