frontAnswerer/src/widgets/popup/QuizPopup.tsx

79 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-05-08 17:50:18 +00:00
import { useEffect, useRef, useState } from "react";
import QuizDialog from "../shared/QuizDialog";
import { useQuizCompletionStatus } from "../shared/useQuizCompletionStatus";
import { useMediaQuery } from "@mui/material";
const WIDGET_DEFAULT_WIDTH = "600px";
const WIDGET_DEFAULT_HEIGHT = "80%";
interface Props {
quizId: string;
dimensions?: { width: string; height: string; };
/**
* Открыть квиз через X секунд
*/
autoShowQuizTime?: number;
hideOnMobile?: boolean;
openOnLeaveAttempt?: boolean;
}
export default function QuizPopup({
quizId,
dimensions,
autoShowQuizTime = 0,
hideOnMobile = false,
openOnLeaveAttempt = false,
}: Props) {
const initialIsQuizShown = (autoShowQuizTime || openOnLeaveAttempt) ? false : true;
const [isQuizShown, setIsQuizShown] = useState<boolean>(initialIsQuizShown);
const isQuizCompleted = useQuizCompletionStatus(quizId);
const isMobile = useMediaQuery("(max-width: 600px)");
const preventOpenOnLeaveAttemptRef = useRef<boolean>(false);
useEffect(function setAutoShowQuizTimer() {
if (!autoShowQuizTime || 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]);
if (isQuizCompleted) return null;
if (hideOnMobile && isMobile) return null;
return (
<QuizDialog
open={isQuizShown}
quizId={quizId}
onClose={() => setIsQuizShown(false)}
paperSx={{
width: dimensions?.width ?? WIDGET_DEFAULT_WIDTH,
height: dimensions?.height ?? WIDGET_DEFAULT_HEIGHT,
}}
/>
);
}