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"; const WIDGET_DEFAULT_WIDTH = "600px"; const WIDGET_DEFAULT_HEIGHT = "80%"; interface Props { quizId: string; fixedSide?: "left" | "right"; dialogDimensions?: { width: string; height: string; }; /** * Открыть квиз через X секунд, 0 - сразу */ autoShowQuizTime?: number | null; hideOnMobile?: boolean; openOnLeaveAttempt?: boolean; buttonFlash?: boolean; withShadow?: boolean; rounded?: boolean; buttonText?: string; buttonTextColor?: string; buttonBackgroundColor?: string; } export default function OpenQuizButton({ quizId, fixedSide, autoShowQuizTime = null, dialogDimensions, hideOnMobile, openOnLeaveAttempt, buttonFlash = false, withShadow = false, rounded = false, buttonText = "Пройти квиз", buttonTextColor, buttonBackgroundColor, }: Props) { 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={{ width: dialogDimensions?.width ?? WIDGET_DEFAULT_WIDTH, height: dialogDimensions?.height ?? WIDGET_DEFAULT_HEIGHT, }} /> ); }