Newer
Older
import React, {SetStateAction, useEffect, useRef, useState} from "react";
Katarína Sieklová
committed
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;
}
Katarína Sieklová
committed
interface AnimateProps {
typewriterRef: React.MutableRefObject<TypewriterClass | undefined>,
Katarína Sieklová
committed
link: string,
Katarína Sieklová
committed
}
export const useAnimate = ({link, text, typewriterRef, audioFiles}: AnimateProps) => {
const language = useRecoilValue(languageAtom);
Katarína Sieklová
committed
const [paused, setPaused] = useState(false);
const [animationObj, setAnimationObject] = useState<unknown>(null);
Katarína Sieklová
committed
const getAnimationObject = (obj: SetStateAction<null>) => setAnimationObject(obj);
const [currentIndex, setCurrentIndex] = useState(0);
const [isAnimationComplete, setIsAnimationComplete] = useState(false);
const [isMuted, setIsMuted] = useState(false);
Katarína Sieklová
committed
const line = text[currentIndex];
const navigate = useNavigate();
const audioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
audioRef.current = new Audio(audioFiles[currentIndex]);
}, []);
Katarína Sieklová
committed
useEffect(() => {
if (typewriterRef.current) {
typewriterRef.current.deleteAll(0.0000000000000000000001);
if (audioRef.current) {
audioRef.current.play();
}
Katarína Sieklová
committed
typewriterRef.current
.typeString(line[language as keyof Texts])
.start()
.callFunction(() => {
setIsAnimationComplete(true);
setPaused(true)
});
}
}, [language, currentIndex]);
const handleClick = () => {
Katarína Sieklová
committed
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();
}
Katarína Sieklová
committed
}
};
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) {
}
})
.typeString(line[language as keyof Texts])
.start()
.callFunction(() => {
setIsAnimationComplete(true);
setPaused(true);
});
Katarína Sieklová
committed
}
return {
paused,
isAnimationComplete,
isLast: currentIndex == text.length - 1,
getAnimationObject,
handleClick,
onInit,
handleMuteToggle,