Added a Scroll To Top function

This commit is contained in:
Tiago Ribeiro
2024-02-05 17:59:46 +00:00
parent f6166ca9e1
commit 8baa25c445
8 changed files with 354 additions and 393 deletions

View File

@@ -63,6 +63,8 @@ export default function MultipleChoice({
const hasExamEnded = useExamStore((state) => state.hasExamEnded); const hasExamEnded = useExamStore((state) => state.hasExamEnded);
const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));
useEffect(() => { useEffect(() => {
if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type}); if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type});
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -93,6 +95,8 @@ export default function MultipleChoice({
} else { } else {
setQuestionIndex((prev) => prev + 1); setQuestionIndex((prev) => prev + 1);
} }
scrollToTop();
}; };
const back = () => { const back = () => {
@@ -101,6 +105,8 @@ export default function MultipleChoice({
} else { } else {
setQuestionIndex((prev) => prev - 1); setQuestionIndex((prev) => prev - 1);
} }
scrollToTop();
}; };
return ( return (

View File

@@ -32,6 +32,8 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]); const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]);
const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));
useEffect(() => { useEffect(() => {
if (hasExamEnded && exerciseIndex === -1) { if (hasExamEnded && exerciseIndex === -1) {
setExerciseIndex((prev) => prev + 1); setExerciseIndex((prev) => prev + 1);
@@ -52,6 +54,7 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
}; };
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
@@ -92,6 +95,7 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
}; };
const previousExercise = (solution?: UserSolution) => { const previousExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }

View File

@@ -93,6 +93,8 @@ export default function Reading({exam, showSolutions = false, onFinish}: Props)
const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]); const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]);
const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));
useEffect(() => { useEffect(() => {
const listener = (e: KeyboardEvent) => { const listener = (e: KeyboardEvent) => {
if (e.key === "F3" || ((e.ctrlKey || e.metaKey) && e.key === "f")) { if (e.key === "F3" || ((e.ctrlKey || e.metaKey) && e.key === "f")) {
@@ -127,6 +129,7 @@ export default function Reading({exam, showSolutions = false, onFinish}: Props)
}; };
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
@@ -167,6 +170,7 @@ export default function Reading({exam, showSolutions = false, onFinish}: Props)
}; };
const previousExercise = (solution?: UserSolution) => { const previousExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }

View File

@@ -26,11 +26,14 @@ export default function Speaking({exam, showSolutions = false, onFinish}: Props)
const [userSolutions, setUserSolutions] = useState<UserSolution[]>(exam.exercises.map((x) => defaultUserSolutions(x, exam))); const [userSolutions, setUserSolutions] = useState<UserSolution[]>(exam.exercises.map((x) => defaultUserSolutions(x, exam)));
const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]); const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]);
const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));
useEffect(() => { useEffect(() => {
setCurrentQuestionIndex(0); setCurrentQuestionIndex(0);
}, [questionIndex]); }, [questionIndex]);
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
@@ -55,6 +58,7 @@ export default function Speaking({exam, showSolutions = false, onFinish}: Props)
}; };
const previousExercise = (solution?: UserSolution) => { const previousExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }

View File

@@ -24,7 +24,10 @@ export default function Writing({exam, showSolutions = false, onFinish}: Props)
const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]); const [hasExamEnded, setHasExamEnded] = useExamStore((state) => [state.hasExamEnded, state.setHasExamEnded]);
const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
@@ -48,6 +51,7 @@ export default function Writing({exam, showSolutions = false, onFinish}: Props)
}; };
const previousExercise = (solution?: UserSolution) => { const previousExercise = (solution?: UserSolution) => {
scrollToTop();
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }

View File

@@ -1,6 +1,6 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { Module } from "@/interfaces"; import {Module} from "@/interfaces";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import AbandonPopup from "@/components/AbandonPopup"; import AbandonPopup from "@/components/AbandonPopup";
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
@@ -12,430 +12,333 @@ import Selection from "@/exams/Selection";
import Speaking from "@/exams/Speaking"; import Speaking from "@/exams/Speaking";
import Writing from "@/exams/Writing"; import Writing from "@/exams/Writing";
import useUser from "@/hooks/useUser"; import useUser from "@/hooks/useUser";
import { Exam, UserSolution, Variant } from "@/interfaces/exam"; import {Exam, UserSolution, Variant} from "@/interfaces/exam";
import { Stat } from "@/interfaces/user"; import {Stat} from "@/interfaces/user";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import { import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
evaluateSpeakingAnswer, import {getExam} from "@/utils/exams";
evaluateWritingAnswer,
} from "@/utils/evaluation";
import { getExam } from "@/utils/exams";
import axios from "axios"; import axios from "axios";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import { toast, ToastContainer } from "react-toastify"; import {toast, ToastContainer} from "react-toastify";
import { v4 as uuidv4 } from "uuid"; import {v4 as uuidv4} from "uuid";
interface Props { interface Props {
page: "exams" | "exercises"; page: "exams" | "exercises";
} }
export default function ExamPage({ page }: Props) { export default function ExamPage({page}: Props) {
const [hasBeenUploaded, setHasBeenUploaded] = useState(false); const [variant, setVariant] = useState<Variant>("full");
const [moduleIndex, setModuleIndex] = useState(0); const [avoidRepeated, setAvoidRepeated] = useState(false);
const [sessionId, setSessionId] = useState(""); const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [exam, setExam] = useState<Exam>(); const [showAbandonPopup, setShowAbandonPopup] = useState(false);
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false); const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
const [showAbandonPopup, setShowAbandonPopup] = useState(false); const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState<string[]>([]);
const [avoidRepeated, setAvoidRepeated] = useState(false);
const [timeSpent, setTimeSpent] = useState(0);
const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState<
string[]
>([]);
const [variant, setVariant] = useState<Variant>("full");
const [exams, setExams] = useExamStore((state) => [ const {assignment} = useExamStore((state) => state);
state.exams, const {exam, setExam} = useExamStore((state) => state);
state.setExams, const {exams, setExams} = useExamStore((state) => state);
]); const {timeSpent, setTimeSpent} = useExamStore((state) => state);
const [userSolutions, setUserSolutions] = useExamStore((state) => [ const {sessionId, setSessionId} = useExamStore((state) => state);
state.userSolutions, const {moduleIndex, setModuleIndex} = useExamStore((state) => state);
state.setUserSolutions, const {userSolutions, setUserSolutions} = useExamStore((state) => state);
]); const {showSolutions, setShowSolutions} = useExamStore((state) => state);
const [showSolutions, setShowSolutions] = useExamStore((state) => [ const {selectedModules, setSelectedModules} = useExamStore((state) => state);
state.showSolutions,
state.setShowSolutions,
]);
const [selectedModules, setSelectedModules] = useExamStore((state) => [
state.selectedModules,
state.setSelectedModules,
]);
const assignment = useExamStore((state) => state.assignment);
const { user } = useUser({ redirectTo: "/login" }); const {user} = useUser({redirectTo: "/login"});
const router = useRouter(); const router = useRouter();
useEffect(() => setSessionId(uuidv4()), []); useEffect(() => setSessionId(uuidv4()), [setSessionId]);
useEffect(() => { useEffect(() => {
if (user?.type === "developer") console.log(exam); if (user?.type === "developer") console.log(exam);
}, [exam, user]); }, [exam, user]);
useEffect(() => { useEffect(() => {
selectedModules.length > 0 && timeSpent === 0 && !showSolutions; selectedModules.length > 0 && timeSpent === 0 && !showSolutions;
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) { if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
const timerInterval = setInterval(() => { const timerInterval = setInterval(() => {
setTimeSpent((prev) => prev + 1); setTimeSpent(timeSpent + 1);
}, 1000); }, 1000);
return () => { return () => {
clearInterval(timerInterval); clearInterval(timerInterval);
}; };
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules.length]); }, [selectedModules.length]);
useEffect(() => { useEffect(() => {
if (showSolutions) setModuleIndex(-1); if (showSolutions) setModuleIndex(-1);
}, [showSolutions]); }, [setModuleIndex, showSolutions]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if ( if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
selectedModules.length > 0 && const nextExam = exams[moduleIndex];
exams.length > 0 && setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
moduleIndex < selectedModules.length }
) { })();
const nextExam = exams[moduleIndex]; // eslint-disable-next-line react-hooks/exhaustive-deps
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined); }, [selectedModules, moduleIndex, exams]);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, exams]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if (selectedModules.length > 0 && exams.length === 0) { if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map((module) => const examPromises = selectedModules.map((module) => getExam(module, avoidRepeated, variant));
getExam(module, avoidRepeated, variant), Promise.all(examPromises).then((values) => {
); if (values.every((x) => !!x)) {
Promise.all(examPromises).then((values) => { setExams(values.map((x) => x!));
if (values.every((x) => !!x)) { } else {
setExams(values.map((x) => x!)); toast.error("Something went wrong, please try again");
} else { setTimeout(router.reload, 500);
toast.error("Something went wrong, please try again"); }
setTimeout(router.reload, 500); });
} }
}); })();
} // eslint-disable-next-line react-hooks/exhaustive-deps
})(); }, [selectedModules, setExams, exams]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, setExams, exams]);
useEffect(() => { useEffect(() => {
if ( if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
selectedModules.length > 0 && const newStats: Stat[] = userSolutions.map((solution) => ({
exams.length !== 0 && ...solution,
moduleIndex >= selectedModules.length && id: solution.id || uuidv4(),
!hasBeenUploaded && timeSpent,
!showSolutions session: sessionId,
) { exam: solution.exam!,
const newStats: Stat[] = userSolutions.map((solution) => ({ module: solution.module!,
...solution, user: user?.id || "",
id: solution.id || uuidv4(), date: new Date().getTime(),
timeSpent, ...(assignment ? {assignment: assignment.id} : {}),
session: sessionId, }));
exam: solution.exam!,
module: solution.module!,
user: user?.id || "",
date: new Date().getTime(),
...(assignment ? { assignment: assignment.id } : {}),
}));
axios axios
.post<{ ok: boolean }>("/api/stats", newStats) .post<{ok: boolean}>("/api/stats", newStats)
.then((response) => setHasBeenUploaded(response.data.ok)) .then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false)); .catch(() => setHasBeenUploaded(false));
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]); }, [selectedModules, moduleIndex, hasBeenUploaded]);
useEffect(() => { useEffect(() => {
setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0); setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0);
}, [statsAwaitingEvaluation]); }, [statsAwaitingEvaluation]);
useEffect(() => { useEffect(() => {
if (statsAwaitingEvaluation.length > 0) { if (statsAwaitingEvaluation.length > 0) {
checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation); checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [statsAwaitingEvaluation]); }, [statsAwaitingEvaluation]);
const checkIfStatsHaveBeenEvaluated = (ids: string[]) => { const checkIfStatsHaveBeenEvaluated = (ids: string[]) => {
setTimeout(async () => { setTimeout(async () => {
const awaitedStats = await Promise.all( const awaitedStats = await Promise.all(ids.map(async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data));
ids.map(async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data), const solutionsEvaluated = awaitedStats.every((stat) => stat.solutions.every((x) => x.evaluation !== null));
); if (solutionsEvaluated) {
const solutionsEvaluated = awaitedStats.every((stat) => const statsUserSolutions: UserSolution[] = awaitedStats.map((stat) => ({
stat.solutions.every((x) => x.evaluation !== null), id: stat.id,
); exercise: stat.exercise,
if (solutionsEvaluated) { score: stat.score,
const statsUserSolutions: UserSolution[] = awaitedStats.map((stat) => ({ solutions: stat.solutions,
id: stat.id, type: stat.type,
exercise: stat.exercise, exam: stat.exam,
score: stat.score, module: stat.module,
solutions: stat.solutions, }));
type: stat.type,
exam: stat.exam,
module: stat.module,
}));
const updatedUserSolutions = userSolutions.map((x) => { const updatedUserSolutions = userSolutions.map((x) => {
const respectiveSolution = statsUserSolutions.find( const respectiveSolution = statsUserSolutions.find((y) => y.exercise === x.exercise);
(y) => y.exercise === x.exercise, return respectiveSolution ? respectiveSolution : x;
); });
return respectiveSolution ? respectiveSolution : x;
});
setUserSolutions(updatedUserSolutions); setUserSolutions(updatedUserSolutions);
return setStatsAwaitingEvaluation((prev) => return setStatsAwaitingEvaluation((prev) => prev.filter((x) => !ids.includes(x)));
prev.filter((x) => !ids.includes(x)), }
);
}
return checkIfStatsHaveBeenEvaluated(ids); return checkIfStatsHaveBeenEvaluated(ids);
}, 5 * 1000); }, 5 * 1000);
}; };
const updateExamWithUserSolutions = (exam: Exam): Exam => { const updateExamWithUserSolutions = (exam: Exam): Exam => {
if (exam.module === "reading" || exam.module === "listening") { if (exam.module === "reading" || exam.module === "listening") {
const parts = exam.parts.map((p) => const parts = exam.parts.map((p) =>
Object.assign(p, { Object.assign(p, {
exercises: p.exercises.map((x) => exercises: p.exercises.map((x) =>
Object.assign(x, { Object.assign(x, {
userSolutions: userSolutions.find((y) => x.id === y.exercise) userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
?.solutions, }),
}), ),
), }),
}), );
); return Object.assign(exam, {parts});
return Object.assign(exam, { parts }); }
}
const exercises = exam.exercises.map((x) => const exercises = exam.exercises.map((x) =>
Object.assign(x, { Object.assign(x, {
userSolutions: userSolutions.find((y) => x.id === y.exercise) userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
?.solutions, }),
}), );
); return Object.assign(exam, {exercises});
return Object.assign(exam, { exercises }); };
};
const onFinish = (solutions: UserSolution[]) => { const onFinish = (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.exercise); const solutionIds = solutions.map((x) => x.exercise);
const solutionExams = solutions.map((x) => x.exam); const solutionExams = solutions.map((x) => x.exam);
if (exam && !solutionExams.includes(exam.id)) return; if (exam && !solutionExams.includes(exam.id)) return;
if ( if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
exam && setHasBeenUploaded(true);
(exam.module === "writing" || exam.module === "speaking") && setIsEvaluationLoading(true);
solutions.length > 0 &&
!showSolutions
) {
setHasBeenUploaded(true);
setIsEvaluationLoading(true);
Promise.all( Promise.all(
exam.exercises.map(async (exercise) => { exam.exercises.map(async (exercise) => {
const evaluationID = uuidv4(); const evaluationID = uuidv4();
if (exercise.type === "writing") if (exercise.type === "writing")
return await evaluateWritingAnswer( return await evaluateWritingAnswer(exercise, solutions.find((x) => x.exercise === exercise.id)!, evaluationID);
exercise,
solutions.find((x) => x.exercise === exercise.id)!,
evaluationID,
);
if ( if (exercise.type === "interactiveSpeaking" || exercise.type === "speaking")
exercise.type === "interactiveSpeaking" || return await evaluateSpeakingAnswer(exercise, solutions.find((x) => x.exercise === exercise.id)!, evaluationID);
exercise.type === "speaking" }),
) )
return await evaluateSpeakingAnswer( .then((responses) => {
exercise, setStatsAwaitingEvaluation((prev) => [...prev, ...responses.filter((x) => !!x).map((r) => (r as any).id)]);
solutions.find((x) => x.exercise === exercise.id)!, setUserSolutions([...userSolutions, ...responses.filter((x) => !!x)] as any);
evaluationID, })
); .finally(() => {
}), setHasBeenUploaded(false);
) });
.then((responses) => { }
setStatsAwaitingEvaluation((prev) => [
...prev,
...responses.filter((x) => !!x).map((r) => (r as any).id),
]);
setUserSolutions([
...userSolutions,
...responses.filter((x) => !!x),
] as any);
})
.finally(() => {
setHasBeenUploaded(false);
});
}
axios.get("/api/stats/update"); axios.get("/api/stats/update");
setUserSolutions([ setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), setModuleIndex(moduleIndex + 1);
...solutions, };
]);
setModuleIndex((prev) => prev + 1);
};
const aggregateScoresByModule = ( const aggregateScoresByModule = (answers: UserSolution[]): {module: Module; total: number; missing: number; correct: number}[] => {
answers: UserSolution[], const scores: {
): { module: Module; total: number; missing: number; correct: number }[] => { [key in Module]: {total: number; missing: number; correct: number};
const scores: { } = {
[key in Module]: { total: number; missing: number; correct: number }; reading: {
} = { total: 0,
reading: { correct: 0,
total: 0, missing: 0,
correct: 0, },
missing: 0, listening: {
}, total: 0,
listening: { correct: 0,
total: 0, missing: 0,
correct: 0, },
missing: 0, writing: {
}, total: 0,
writing: { correct: 0,
total: 0, missing: 0,
correct: 0, },
missing: 0, speaking: {
}, total: 0,
speaking: { correct: 0,
total: 0, missing: 0,
correct: 0, },
missing: 0, level: {
}, total: 0,
level: { correct: 0,
total: 0, missing: 0,
correct: 0, },
missing: 0, };
},
};
answers.forEach((x) => { answers.forEach((x) => {
scores[x.module!] = { scores[x.module!] = {
total: scores[x.module!].total + x.score.total, total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct, correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing, missing: scores[x.module!].missing + x.score.missing,
}; };
}); });
return Object.keys(scores) return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0) .filter((x) => scores[x as Module].total > 0)
.map((x) => ({ module: x as Module, ...scores[x as Module] })); .map((x) => ({module: x as Module, ...scores[x as Module]}));
}; };
const renderScreen = () => { const renderScreen = () => {
if (selectedModules.length === 0) { if (selectedModules.length === 0) {
return ( return (
<Selection <Selection
page={page} page={page}
user={user!} user={user!}
disableSelection={page === "exams"} disableSelection={page === "exams"}
onStart={(modules: Module[], avoid: boolean, variant: Variant) => { onStart={(modules: Module[], avoid: boolean, variant: Variant) => {
setModuleIndex(0); setModuleIndex(0);
setAvoidRepeated(avoid); setAvoidRepeated(avoid);
setSelectedModules(modules); setSelectedModules(modules);
setVariant(variant); setVariant(variant);
}} }}
/> />
); );
} }
if (moduleIndex >= selectedModules.length || moduleIndex === -1) { if (moduleIndex >= selectedModules.length || moduleIndex === -1) {
return ( return (
<Finish <Finish
isLoading={isEvaluationLoading} isLoading={isEvaluationLoading}
user={user!} user={user!}
modules={selectedModules} modules={selectedModules}
onViewResults={() => { onViewResults={() => {
setShowSolutions(true); setShowSolutions(true);
setModuleIndex(0); setModuleIndex(0);
setExam(exams[0]); setExam(exams[0]);
}} }}
scores={aggregateScoresByModule(userSolutions)} scores={aggregateScoresByModule(userSolutions)}
/> />
); );
} }
if (exam && exam.module === "reading") { if (exam && exam.module === "reading") {
return ( return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Reading }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "listening") { if (exam && exam.module === "listening") {
return ( return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Listening }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "writing") { if (exam && exam.module === "writing") {
return ( return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Writing }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "speaking") { if (exam && exam.module === "speaking") {
return ( return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Speaking }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "level") { if (exam && exam.module === "level") {
return ( return <Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} /> }
);
}
return <>Loading...</>; return <>Loading...</>;
}; };
return ( return (
<> <>
<ToastContainer /> <ToastContainer />
{user && ( {user && (
<Layout <Layout
user={user} user={user}
className="justify-between" className="justify-between"
focusMode={ focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
selectedModules.length !== 0 && onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
!showSolutions && <>
moduleIndex < selectedModules.length {renderScreen()}
} {!showSolutions && moduleIndex < selectedModules.length && (
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)} <AbandonPopup
> isOpen={showAbandonPopup}
<> abandonPopupTitle="Leave Exercise"
{renderScreen()} abandonPopupDescription="Are you sure you want to leave the exercise? You will lose all your progress."
{!showSolutions && moduleIndex < selectedModules.length && ( abandonConfirmButtonText="Confirm"
<AbandonPopup onAbandon={() => router.reload()}
isOpen={showAbandonPopup} onCancel={() => setShowAbandonPopup(false)}
abandonPopupTitle="Leave Exercise" />
abandonPopupDescription="Are you sure you want to leave the exercise? You will lose all your progress." )}
abandonConfirmButtonText="Confirm" </>
onAbandon={() => router.reload()} </Layout>
onCancel={() => setShowAbandonPopup(false)} )}
/> </>
)} );
</>
</Layout>
)}
</>
);
} }

View File

@@ -5,17 +5,35 @@ import {create} from "zustand";
export interface ExamState { export interface ExamState {
exams: Exam[]; exams: Exam[];
userSolutions: UserSolution[];
showSolutions: boolean;
hasExamEnded: boolean;
selectedModules: Module[];
assignment?: Assignment;
setHasExamEnded: (hasExamEnded: boolean) => void;
setUserSolutions: (userSolutions: UserSolution[]) => void;
setExams: (exams: Exam[]) => void; setExams: (exams: Exam[]) => void;
userSolutions: UserSolution[];
setUserSolutions: (userSolutions: UserSolution[]) => void;
showSolutions: boolean;
setShowSolutions: (showSolutions: boolean) => void; setShowSolutions: (showSolutions: boolean) => void;
hasExamEnded: boolean;
setHasExamEnded: (hasExamEnded: boolean) => void;
selectedModules: Module[];
setSelectedModules: (modules: Module[]) => void; setSelectedModules: (modules: Module[]) => void;
assignment?: Assignment;
setAssignment: (assignment: Assignment) => void; setAssignment: (assignment: Assignment) => void;
timeSpent: number;
setTimeSpent: (timeSpent: number) => void;
sessionId: string;
setSessionId: (sessionId: string) => void;
moduleIndex: number;
setModuleIndex: (moduleIndex: number) => void;
exam?: Exam;
setExam: (exam?: Exam) => void;
reset: () => void; reset: () => void;
} }
@@ -26,16 +44,26 @@ export const initialState = {
selectedModules: [], selectedModules: [],
hasExamEnded: false, hasExamEnded: false,
assignment: undefined, assignment: undefined,
timeSpent: 0,
sessionId: "",
exam: undefined,
moduleIndex: 0,
}; };
const useExamStore = create<ExamState>((set) => ({ const useExamStore = create<ExamState>((set) => ({
...initialState, ...initialState,
setUserSolutions: (userSolutions: UserSolution[]) => set(() => ({userSolutions})), setUserSolutions: (userSolutions: UserSolution[]) => set(() => ({userSolutions})),
setExams: (exams: Exam[]) => set(() => ({exams})), setExams: (exams: Exam[]) => set(() => ({exams})),
setShowSolutions: (showSolutions: boolean) => set(() => ({showSolutions})), setShowSolutions: (showSolutions: boolean) => set(() => ({showSolutions})),
setSelectedModules: (modules: Module[]) => set(() => ({selectedModules: modules})), setSelectedModules: (modules: Module[]) => set(() => ({selectedModules: modules})),
setHasExamEnded: (hasExamEnded: boolean) => set(() => ({hasExamEnded})), setHasExamEnded: (hasExamEnded: boolean) => set(() => ({hasExamEnded})),
setAssignment: (assignment: Assignment) => set(() => ({assignment})), setAssignment: (assignment: Assignment) => set(() => ({assignment})),
setTimeSpent: (timeSpent) => set(() => ({timeSpent})),
setSessionId: (sessionId: string) => set(() => ({sessionId})),
setExam: (exam?: Exam) => set(() => ({exam})),
setModuleIndex: (moduleIndex: number) => set(() => ({moduleIndex})),
reset: () => set(() => initialState), reset: () => set(() => initialState),
})); }));

View File

@@ -31,7 +31,15 @@
margin: 0; margin: 0;
} }
html, html {
min-height: 100vh !important;
height: 100%;
max-width: 100vw;
overflow-x: hidden;
overflow-y: auto;
font-family: "Open Sans", system-ui, -apple-system, "Helvetica Neue", sans-serif;
}
body { body {
min-height: 100vh !important; min-height: 100vh !important;
height: 100%; height: 100%;