import { ButtonWidgetComponentProps } from "@/model/widget/button"; import lightTheme from "@/utils/themes/light"; import { Button, ThemeProvider, useMediaQuery } from "@mui/material"; import { useEffect, useRef, useState } from "react"; import QuizDialog from "../shared/QuizDialog"; import RunningStripe from "../shared/RunningStripe"; import { useQuizCompletionStatus } from "../shared/useQuizCompletionStatus"; export default function OpenQuizButton({ quizId, fixedSide, autoShowQuizTime = null, dialogDimensions, hideOnMobile, openOnLeaveAttempt, buttonFlash = false, withShadow = false, rounded = false, buttonText = "Пройти квиз", buttonTextColor, buttonBackgroundColor, fullScreen = false, }: ButtonWidgetComponentProps) { const isMobile = useMediaQuery("(max-width: 600px)"); const [isQuizShown, setIsQuizShown] = useState(false); const isQuizCompleted = useQuizCompletionStatus(quizId); const [isFlashEnabled, setIsFlashEnabled] = useState(buttonFlash); const preventQuizAutoShowRef = useRef(false); const preventOpenOnLeaveAttemptRef = useRef(false); useEffect( function setAutoShowQuizTimer() { if (autoShowQuizTime === null || openOnLeaveAttempt) return; const timeout = setTimeout(() => { setIsQuizShown(true); }, autoShowQuizTime * 1000); return () => { clearTimeout(timeout); }; }, [autoShowQuizTime, openOnLeaveAttempt] ); useEffect( function attachLeaveListener() { if (!openOnLeaveAttempt) return; const handleMouseLeave = () => { if (!preventOpenOnLeaveAttemptRef.current) { preventOpenOnLeaveAttemptRef.current = true; setIsQuizShown(true); } }; document.addEventListener("mouseleave", handleMouseLeave); return () => { document.removeEventListener("mouseleave", handleMouseLeave); }; }, [openOnLeaveAttempt] ); function openQuiz() { preventQuizAutoShowRef.current = true; setIsQuizShown(true); setIsFlashEnabled(false); } if (hideOnMobile && isMobile) return null; return ( setIsQuizShown(false)} paperSx={[ isMobile || fullScreen ? { width: "100%", height: "100%", maxHeight: "100%", borderRadius: 0, m: 0, } : { width: dialogDimensions?.width, height: dialogDimensions?.height, }, ]} /> ); }