- Did a bit of refactor related to the exam/exercises page;

- Improved the responsiveness of the page for mobile;
This commit is contained in:
Tiago Ribeiro
2023-10-17 08:52:41 +01:00
parent 550cdba5a7
commit 9b852bd6be
15 changed files with 491 additions and 819 deletions

View File

@@ -37,7 +37,7 @@ export default function Layout({user, children, className, navDisabled = false,
/>
<div
className={clsx(
"w-full min-h-full h-fit lg:mr-8 bg-white shadow-md rounded-2xl p-4 md:p-12 pb-8 flex flex-col gap-8 md:gap-12 relative overflow-hidden mt-2",
"w-full min-h-full h-fit md:mr-8 bg-white shadow-md rounded-2xl p-4 md:p-12 pb-8 flex flex-col gap-8 md:gap-12 relative overflow-hidden mt-2",
className,
)}>
{children}

View File

@@ -75,10 +75,10 @@ export default function MobileMenu({isOpen, onClose, path, user}: Props) {
Exams
</Link>
<Link
href="/exercise"
href="/exercises"
className={clsx(
"transition ease-in-out duration-300 w-fit",
path === "/exercise" && "text-mti-purple-light font-semibold border-b-2 border-b-mti-purple-light ",
path === "/exercises" && "text-mti-purple-light font-semibold border-b-2 border-b-mti-purple-light ",
)}>
Exercises
</Link>

View File

@@ -3,9 +3,7 @@ import Link from "next/link";
import FocusLayer from "@/components/FocusLayer";
import {preventNavigation} from "@/utils/navigation.disabled";
import {useRouter} from "next/router";
import axios from "axios";
import {RiLogoutBoxFill} from "react-icons/ri";
import {BsList, BsPower} from "react-icons/bs";
import {BsList} from "react-icons/bs";
import clsx from "clsx";
import moment from "moment";
import MobileMenu from "./MobileMenu";
@@ -47,12 +45,12 @@ export default function Navbar({user, path, navDisabled = false, focusMode = fal
return (
<>
{user && <MobileMenu path={path} isOpen={isMenuOpen} onClose={() => setIsMenuOpen(false)} user={user} />}
<header className="w-full bg-transparent py-4 -lg:justify-between lg:gap-12 flex items-center relative -lg:px-4">
<Link href={disableNavigation ? "" : "/"} className=" lg:px-8 flex gap-8 items-center">
<img src="/logo.png" alt="EnCoach's Logo" className="w-12" />
<h1 className="font-bold text-2xl w-1/6 -lg:hidden">EnCoach</h1>
<header className="w-full bg-transparent py-2 md:py-4 -md:justify-between md:gap-12 flex items-center relative -md:px-4">
<Link href={disableNavigation ? "" : "/"} className=" md:px-8 flex gap-8 items-center">
<img src="/logo.png" alt="EnCoach's Logo" className="w-8 md:w-12" />
<h1 className="font-bold text-2xl w-1/6 -md:hidden">EnCoach</h1>
</Link>
<div className="flex justify-end -md:items-center gap-4 lg:w-5/6 lg:mr-8">
<div className="flex justify-end -md:items-center gap-4 md:w-5/6 md:mr-8">
{showExpirationDate() && (
<Link
href="https://encoach.com/join"
@@ -71,10 +69,10 @@ export default function Navbar({user, path, navDisabled = false, focusMode = fal
)}
<Link href={disableNavigation ? "" : "/profile"} className="flex gap-6 items-center justify-end -md:hidden">
<img src={user.profilePicture} alt={user.name} className="w-10 h-10 rounded-full object-cover" />
<span className="text-right -lg:hidden">{user.name}</span>
<span className="text-right -md:hidden">{user.name}</span>
</Link>
<div className="cursor-pointer md:hidden" onClick={() => setIsMenuOpen(true)}>
<BsList className="text-mti-purple-light" size={32} />
<BsList className="text-mti-purple-light w-8 h-8" />
</div>
</div>
{focusMode && <FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />}

View File

@@ -0,0 +1,85 @@
/* eslint-disable @next/next/no-img-element */
import {User} from "@/interfaces/user";
import {calculateAverageLevel} from "@/utils/score";
import {capitalize} from "lodash";
import {ReactElement} from "react";
import ProgressBar from "./Low/ProgressBar";
interface Props {
user: User;
items: {
icon: ReactElement;
value: string | number;
label: string;
}[];
children?: ReactElement;
}
export default function ProfileSummary({user, items}: Props) {
return (
<section className="w-full flex -md:flex-col gap-4 md:gap-8">
<img
src={user.profilePicture}
alt={user.name}
className="aspect-square h-20 md:h-64 rounded-3xl drop-shadow-xl object-cover -md:hidden"
/>
<div className="flex md:flex-col gap-4 md:py-4 w-full -md:items-center">
<img src={user.profilePicture} alt={user.name} className="aspect-square h-24 md:hidden rounded-3xl drop-shadow-xl object-cover" />
<div className="flex -md:flex-col justify-between w-full gap-8">
<div className="flex flex-col gap-2 py-2">
<h1 className="font-bold text-2xl md:text-4xl">{user.name}</h1>
<h6 className="font-normal text-base text-mti-gray-taupe">{capitalize(user.type)}</h6>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={100}
color="purple"
className="max-w-xs w-32 md:self-end h-10 -md:hidden"
/>
</div>
<ProgressBar
label=""
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="red"
className="w-full h-3 drop-shadow-lg -md:hidden"
/>
<div className="flex justify-between w-full mt-8 -md:hidden">
{items.map((item) => (
<div className="flex gap-4 items-center" key={item.label}>
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
{item.icon}
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{item.value}</span>
<span className="font-normal text-base text-mti-gray-dim">{item.label}</span>
</div>
</div>
))}
</div>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="purple"
className="w-full md:hidden h-8"
textClassName="!text-mti-black"
/>
<div className="grid grid-cols-2 gap-4 w-full mt-4 md:hidden">
{items.map((item) => (
<div className="flex gap-4 items-center" key={item.label}>
<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
{item.icon}
</div>
<div className="flex flex-col">
<span className="font-bold text-lg md:text-xl">{item.value}</span>
<span className="font-normal text-sm md:text-base text-mti-gray-dim">{item.label}</span>
</div>
</div>
))}
</div>
</section>
);
}

View File

@@ -11,6 +11,7 @@ import Button from "@/components/Low/Button";
import {calculateAverageLevel} from "@/utils/score";
import {sortByModuleName} from "@/utils/moduleUtils";
import {capitalize} from "lodash";
import ProfileSummary from "@/components/ProfileSummary";
interface Props {
user: User;
@@ -31,68 +32,35 @@ export default function Selection({user, page, onStart, disableSelection = false
return (
<>
<div className="w-full h-full relative flex flex-col gap-16">
<section className="w-full flex gap-8">
<img src={user.profilePicture} alt={user.name} className="aspect-square h-64 rounded-3xl drop-shadow-xl object-cover" />
<div className="flex flex-col gap-4 py-4 w-full">
<div className="flex justify-between w-full gap-8">
<div className="flex flex-col gap-2 py-2">
<h1 className="font-bold text-4xl">{user.name}</h1>
<h6 className="font-normal text-base text-mti-gray-taupe capitalize">{user.type}</h6>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={100}
color="purple"
className="max-w-xs w-32 self-end h-10"
<div className="w-full h-full relative flex flex-col gap-8 md:gap-16">
{user && (
<ProfileSummary
user={user}
items={[
{
icon: <BsBook className="text-ielts-reading w-6 h-6 md:w-8 md:h-8" />,
label: "Reading",
value: totalExamsByModule(stats, "reading"),
},
{
icon: <BsHeadphones className="text-ielts-listening w-6 h-6 md:w-8 md:h-8" />,
label: "Listening",
value: totalExamsByModule(stats, "listening"),
},
{
icon: <BsPen className="text-ielts-writing w-6 h-6 md:w-8 md:h-8" />,
label: "Writing",
value: totalExamsByModule(stats, "writing"),
},
{
icon: <BsMegaphone className="text-ielts-speaking w-6 h-6 md:w-8 md:h-8" />,
label: "Speaking",
value: totalExamsByModule(stats, "speaking"),
},
]}
/>
</div>
<ProgressBar
label=""
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="red"
className="w-full h-3 drop-shadow-lg"
/>
<div className="flex justify-between w-full mt-8">
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsBook className="text-ielts-reading w-8 h-8" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{totalExamsByModule(stats, "reading")}</span>
<span className="font-normal text-base text-mti-gray-dim">Reading</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsHeadphones className="text-ielts-listening w-8 h-8" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{totalExamsByModule(stats, "listening")}</span>
<span className="font-normal text-base text-mti-gray-dim">Listening</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsPen className="text-ielts-writing w-8 h-8" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{totalExamsByModule(stats, "writing")}</span>
<span className="font-normal text-base text-mti-gray-dim">Writing</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsMegaphone className="text-ielts-speaking w-8 h-8" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{totalExamsByModule(stats, "speaking")}</span>
<span className="font-normal text-base text-mti-gray-dim">Speaking</span>
</div>
</div>
</div>
</div>
</section>
)}
<section className="flex flex-col gap-3">
<span className="font-bold text-lg">About {capitalize(page)}</span>
<span className="text-mti-gray-taupe">
@@ -119,7 +87,7 @@ export default function Selection({user, page, onStart, disableSelection = false
)}
</span>
</section>
<section className="w-full flex justify-between gap-8 mt-8">
<section className="w-full flex -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8">
<div
onClick={!disableSelection ? () => toggleModule("reading") : undefined}
className={clsx(
@@ -201,9 +169,9 @@ export default function Selection({user, page, onStart, disableSelection = false
)}
</div>
</section>
<div className="flex w-full justify-between items-center">
<div className="flex w-full -md:flex-col -md:gap-4 -md:justify-center md:justify-between items-center">
<div
className="flex gap-3 items-center text-mti-gray-dim text-sm cursor-pointer tooltip"
className="flex gap-3 items-center text-mti-gray-dim text-sm cursor-pointer tooltip w-full -md:justify-center"
data-tip="If possible, the platform will choose exams not yet done"
onClick={() => setAvoidRepeatedExams((prev) => !prev)}>
<input type="checkbox" className="hidden" />
@@ -217,6 +185,11 @@ export default function Selection({user, page, onStart, disableSelection = false
</div>
<span>Avoid Repeated Questions</span>
</div>
<div className="tooltip w-full" data-tip={`Your screen size is too small to do ${page}`}>
<Button color="purple" className="px-12 w-full max-w-xs md:hidden" disabled>
Start Exam
</Button>
</div>
<Button
onClick={() =>
onStart(
@@ -225,7 +198,7 @@ export default function Selection({user, page, onStart, disableSelection = false
)
}
color="purple"
className="px-12 w-full max-w-xs self-end"
className="px-12 w-full max-w-xs md:self-end -md:hidden"
disabled={selectedModules.length === 0 && !disableSelection}>
Start Exam
</Button>

View File

@@ -110,28 +110,28 @@ export default function BatchCodeGenerator({user}: {user: User}) {
{user && (
<div className="grid grid-cols-2 gap-4">
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("student")}
disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.student.includes(user.type)}>
Student
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("teacher")}
disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.teacher.includes(user.type)}>
Teacher
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("admin")}
disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.admin.includes(user.type)}>
Admin
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("owner")}
disabled={emails.length === 0 || isLoading || !PERMISSIONS.generateCode.owner.includes(user.type)}>

View File

@@ -59,28 +59,28 @@ export default function CodeGenerator({user}: {user: User}) {
{user && (
<div className="grid grid-cols-2 gap-4">
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("student")}
disabled={!PERMISSIONS.generateCode.student.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
Student
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("teacher")}
disabled={!PERMISSIONS.generateCode.teacher.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
Teacher
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("admin")}
disabled={!PERMISSIONS.generateCode.admin.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>
Admin
</Button>
<Button
className="w-48"
className="w-44 md:w-48"
variant="outline"
onClick={() => generateCode("owner")}
disabled={!PERMISSIONS.generateCode.owner.includes(user.type) || (isExpiryDateEnabled && expiryDate === null)}>

View File

@@ -55,7 +55,7 @@ export default function ExamLoader() {
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"px-6 py-4 w-44 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"hover:bg-mti-purple-light hover:border-mti-purple-dark hover:text-white",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",

View File

@@ -0,0 +1,287 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {useEffect, useState} from "react";
import {Module} from "@/interfaces";
import Selection from "@/exams/Selection";
import Reading from "@/exams/Reading";
import {Exam, UserSolution} from "@/interfaces/exam";
import Listening from "@/exams/Listening";
import Writing from "@/exams/Writing";
import {ToastContainer, toast} from "react-toastify";
import Finish from "@/exams/Finish";
import axios from "axios";
import {Stat} from "@/interfaces/user";
import Speaking from "@/exams/Speaking";
import {v4 as uuidv4} from "uuid";
import useUser from "@/hooks/useUser";
import useExamStore from "@/stores/examStore";
import Layout from "@/components/High/Layout";
import AbandonPopup from "@/components/AbandonPopup";
import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
import {useRouter} from "next/router";
import {getExam} from "@/utils/exams";
import {capitalize} from "lodash";
interface Props {
page: "exams" | "exercises";
}
export default function ExamPage({page}: Props) {
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [moduleIndex, setModuleIndex] = useState(0);
const [sessionId, setSessionId] = useState("");
const [exam, setExam] = useState<Exam>();
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
const [showAbandonPopup, setShowAbandonPopup] = useState(false);
const [avoidRepeated, setAvoidRepeated] = useState(false);
const [timeSpent, setTimeSpent] = useState(0);
const [exams, setExams] = useExamStore((state) => [state.exams, state.setExams]);
const [userSolutions, setUserSolutions] = useExamStore((state) => [state.userSolutions, state.setUserSolutions]);
const [showSolutions, setShowSolutions] = useExamStore((state) => [state.showSolutions, state.setShowSolutions]);
const [selectedModules, setSelectedModules] = useExamStore((state) => [state.selectedModules, state.setSelectedModules]);
const {user} = useUser({redirectTo: "/login"});
const router = useRouter();
useEffect(() => setSessionId(uuidv4()), []);
useEffect(() => {
selectedModules.length > 0 && timeSpent === 0 && !showSolutions;
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
const timerInterval = setInterval(() => {
setTimeSpent((prev) => prev + 1);
}, 1000);
return () => {
clearInterval(timerInterval);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules.length]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
const nextExam = exams[moduleIndex];
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, exams]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map((module) => getExam(module, avoidRepeated));
Promise.all(examPromises).then((values) => {
if (values.every((x) => !!x)) {
setExams(values.map((x) => x!));
} else {
toast.error("Something went wrong, please try again");
setTimeout(router.reload, 500);
}
});
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, setExams, exams]);
useEffect(() => {
if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
const newStats: Stat[] = userSolutions.map((solution) => ({
...solution,
timeSpent,
session: sessionId,
exam: solution.exam!,
module: solution.module!,
user: user?.id || "",
date: new Date().getTime(),
}));
axios
.post<{ok: boolean}>("/api/stats", newStats)
.then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]);
const updateExamWithUserSolutions = (exam: Exam): Exam => {
if (exam.module === "reading" || exam.module === "listening") {
const parts = exam.parts.map((p) =>
Object.assign(p, {
exercises: p.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions})),
}),
);
return Object.assign(exam, {parts});
}
const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions}));
return Object.assign(exam, {exercises});
};
const onFinish = (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.exercise);
const solutionExams = solutions.map((x) => x.exam);
if (exam && !solutionExams.includes(exam.id)) return;
if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
setHasBeenUploaded(true);
setIsEvaluationLoading(true);
Promise.all(
exam.exercises.map(async (exercise) => {
return (exam.module === "writing" ? evaluateWritingAnswer : evaluateSpeakingAnswer)(
exams,
exam.id,
exercise.id,
solutions.find((x) => x.exercise === exercise.id)!,
).then((response) => {
if (response) {
setUserSolutions([...userSolutions.filter((x) => x.exercise !== exercise.id), response]);
}
});
}),
).finally(() => {
setIsEvaluationLoading(false);
setHasBeenUploaded(false);
});
}
axios.get("/api/stats/update");
setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
setModuleIndex((prev) => prev + 1);
};
const aggregateScoresByModule = (answers: UserSolution[]): {module: Module; total: number; missing: number; correct: number}[] => {
const scores: {[key in Module]: {total: number; missing: number; correct: number}} = {
reading: {
total: 0,
correct: 0,
missing: 0,
},
listening: {
total: 0,
correct: 0,
missing: 0,
},
writing: {
total: 0,
correct: 0,
missing: 0,
},
speaking: {
total: 0,
correct: 0,
missing: 0,
},
};
answers.forEach((x) => {
scores[x.module!] = {
total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing,
};
});
return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0)
.map((x) => ({module: x as Module, ...scores[x as Module]}));
};
const renderScreen = () => {
if (selectedModules.length === 0) {
return (
<Selection
page={page}
user={user!}
disableSelection={page === "exams"}
onStart={(modules, avoid) => {
setSelectedModules(modules);
setAvoidRepeated(avoid);
}}
/>
);
}
if (moduleIndex >= selectedModules.length) {
return (
<Finish
isLoading={isEvaluationLoading}
user={user!}
modules={selectedModules}
onViewResults={() => {
setShowSolutions(true);
setModuleIndex(0);
setExam(exams[0]);
}}
scores={aggregateScoresByModule(userSolutions)}
/>
);
}
if (exam && exam.module === "reading") {
return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "listening") {
return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "writing") {
return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "speaking") {
return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
return <>Loading...</>;
};
return (
<>
<Head>
<title>
{capitalize(page)
.slice(0, page.length - 1)
.toString()}{" "}
| EnCoach
</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<Layout
user={user}
className="justify-between"
focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
<>
{renderScreen()}
{!showSolutions && moduleIndex < selectedModules.length && (
<AbandonPopup
isOpen={showAbandonPopup}
abandonPopupTitle="Leave Exercise"
abandonPopupDescription="Are you sure you want to leave the exercise? You will lose all your progress."
abandonConfirmButtonText="Confirm"
onAbandon={() => router.reload()}
onCancel={() => setShowAbandonPopup(false)}
/>
)}
</>
</Layout>
)}
</>
);
}

View File

@@ -60,7 +60,7 @@ export default function Admin() {
<ToastContainer />
{user && (
<Layout user={user} className="gap-6">
<section className="w-full flex gap-8 justify-between">
<section className="w-full flex -md:flex-col gap-8 justify-between">
<ExamLoader />
<CodeGenerator user={user} />
<BatchCodeGenerator user={user} />

View File

@@ -1,40 +1,9 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {useEffect, useState} from "react";
import {Module} from "@/interfaces";
import Selection from "@/exams/Selection";
import Reading from "@/exams/Reading";
import {
Exam,
ListeningExam,
ReadingExam,
SpeakingExam,
UserSolution,
Evaluation,
WritingExam,
WritingExercise,
SpeakingExercise,
} from "@/interfaces/exam";
import Listening from "@/exams/Listening";
import Writing from "@/exams/Writing";
import {ToastContainer, toast} from "react-toastify";
import Finish from "@/exams/Finish";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat} from "@/interfaces/user";
import Speaking from "@/exams/Speaking";
import {v4 as uuidv4} from "uuid";
import useUser from "@/hooks/useUser";
import useExamStore from "@/stores/examStore";
import Layout from "@/components/High/Layout";
import {speakingReverseMarking, writingReverseMarking} from "@/utils/score";
import AbandonPopup from "@/components/AbandonPopup";
import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
import {useRouter} from "next/router";
import {getExam} from "@/utils/exams";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import ExamPage from "./(exam)/ExamPage";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -67,255 +36,5 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
}, sessionOptions);
export default function Page() {
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [moduleIndex, setModuleIndex] = useState(0);
const [sessionId, setSessionId] = useState("");
const [exam, setExam] = useState<Exam>();
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
const [showAbandonPopup, setShowAbandonPopup] = useState(false);
const [avoidRepeated, setAvoidRepeated] = useState(false);
const [timeSpent, setTimeSpent] = useState(0);
const [exams, setExams] = useExamStore((state) => [state.exams, state.setExams]);
const [userSolutions, setUserSolutions] = useExamStore((state) => [state.userSolutions, state.setUserSolutions]);
const [showSolutions, setShowSolutions] = useExamStore((state) => [state.showSolutions, state.setShowSolutions]);
const [selectedModules, setSelectedModules] = useExamStore((state) => [state.selectedModules, state.setSelectedModules]);
const {user} = useUser({redirectTo: "/login"});
const router = useRouter();
useEffect(() => setSessionId(uuidv4()), []);
useEffect(() => {
selectedModules.length > 0 && timeSpent === 0 && !showSolutions;
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
const timerInterval = setInterval(() => {
setTimeSpent((prev) => prev + 1);
}, 1000);
return () => {
clearInterval(timerInterval);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules.length]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
const nextExam = exams[moduleIndex];
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, exams]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map((module) => getExam(module, avoidRepeated));
Promise.all(examPromises).then((values) => {
if (values.every((x) => !!x)) {
setExams(values.map((x) => x!));
} else {
toast.error("Something went wrong, please try again");
setTimeout(router.reload, 500);
}
});
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, setExams, exams]);
useEffect(() => {
if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
const newStats: Stat[] = userSolutions.map((solution) => ({
...solution,
timeSpent,
session: sessionId,
exam: solution.exam!,
module: solution.module!,
user: user?.id || "",
date: new Date().getTime(),
}));
axios
.post<{ok: boolean}>("/api/stats", newStats)
.then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]);
const updateExamWithUserSolutions = (exam: Exam): Exam => {
if (exam.module === "reading" || exam.module === "listening") {
const parts = exam.parts.map((p) =>
Object.assign(p, {
exercises: p.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions})),
}),
);
return Object.assign(exam, {parts});
}
const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions}));
return Object.assign(exam, {exercises});
};
const onFinish = (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.exercise);
const solutionExams = solutions.map((x) => x.exam);
if (exam && !solutionExams.includes(exam.id)) return;
if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
setHasBeenUploaded(true);
setIsEvaluationLoading(true);
Promise.all(
exam.exercises.map(async (exercise) => {
return (exam.module === "writing" ? evaluateWritingAnswer : evaluateSpeakingAnswer)(
exams,
exam.id,
exercise.id,
solutions.find((x) => x.exercise === exercise.id)!,
).then((response) => {
if (response) {
setUserSolutions([...userSolutions.filter((x) => x.exercise !== exercise.id), response]);
}
});
}),
).finally(() => {
setIsEvaluationLoading(false);
setHasBeenUploaded(false);
});
}
axios.get("/api/stats/update");
setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
setModuleIndex((prev) => prev + 1);
};
const aggregateScoresByModule = (answers: UserSolution[]): {module: Module; total: number; missing: number; correct: number}[] => {
const scores: {[key in Module]: {total: number; missing: number; correct: number}} = {
reading: {
total: 0,
correct: 0,
missing: 0,
},
listening: {
total: 0,
correct: 0,
missing: 0,
},
writing: {
total: 0,
correct: 0,
missing: 0,
},
speaking: {
total: 0,
correct: 0,
missing: 0,
},
};
answers.forEach((x) => {
scores[x.module!] = {
total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing,
};
});
return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0)
.map((x) => ({module: x as Module, ...scores[x as Module]}));
};
const renderScreen = () => {
if (selectedModules.length === 0) {
return (
<Selection
page="exams"
user={user!}
disableSelection
onStart={(modules, avoid) => {
setSelectedModules(modules);
setAvoidRepeated(avoid);
}}
/>
);
}
if (moduleIndex >= selectedModules.length) {
return (
<Finish
isLoading={isEvaluationLoading}
user={user!}
modules={selectedModules}
onViewResults={() => {
setShowSolutions(true);
setModuleIndex(0);
setExam(exams[0]);
}}
scores={aggregateScoresByModule(userSolutions)}
/>
);
}
if (exam && exam.module === "reading") {
return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "listening") {
return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "writing") {
return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "speaking") {
return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
return <>Loading...</>;
};
return (
<>
<Head>
<title>Exam | EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<Layout
user={user}
className="justify-between"
focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
<>
{renderScreen()}
{!showSolutions && moduleIndex < selectedModules.length && (
<AbandonPopup
isOpen={showAbandonPopup}
abandonPopupTitle="Leave Exercise"
abandonPopupDescription="Are you sure you want to leave the exercise? You will lose all your progress."
abandonConfirmButtonText="Confirm"
onAbandon={() => router.reload()}
onCancel={() => setShowAbandonPopup(false)}
/>
)}
</>
</Layout>
)}
</>
);
return <ExamPage page="exams" />;
}

View File

@@ -1,43 +1,9 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {useEffect, useState} from "react";
import {Module} from "@/interfaces";
import Selection from "@/exams/Selection";
import Reading from "@/exams/Reading";
import {
Exam,
ListeningExam,
ReadingExam,
SpeakingExam,
UserSolution,
Evaluation,
WritingExam,
WritingExercise,
SpeakingExercise,
} from "@/interfaces/exam";
import Listening from "@/exams/Listening";
import Writing from "@/exams/Writing";
import {ToastContainer, toast} from "react-toastify";
import Finish from "@/exams/Finish";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat} from "@/interfaces/user";
import Speaking from "@/exams/Speaking";
import {v4 as uuidv4} from "uuid";
import useUser from "@/hooks/useUser";
import useExamStore from "@/stores/examStore";
import Sidebar from "@/components/Sidebar";
import Layout from "@/components/High/Layout";
import {sortByModule} from "@/utils/moduleUtils";
import {speakingReverseMarking, writingReverseMarking} from "@/utils/score";
import AbandonPopup from "@/components/AbandonPopup";
import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
import {useRouter} from "next/router";
import {getExam} from "@/utils/exams";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import ExamPage from "./(exam)/ExamPage";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -70,253 +36,5 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
}, sessionOptions);
export default function Page() {
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [moduleIndex, setModuleIndex] = useState(0);
const [sessionId, setSessionId] = useState("");
const [exam, setExam] = useState<Exam>();
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
const [showAbandonPopup, setShowAbandonPopup] = useState(false);
const [avoidRepeated, setAvoidRepeated] = useState(false);
const [timeSpent, setTimeSpent] = useState(0);
const [exams, setExams] = useExamStore((state) => [state.exams, state.setExams]);
const [userSolutions, setUserSolutions] = useExamStore((state) => [state.userSolutions, state.setUserSolutions]);
const [showSolutions, setShowSolutions] = useExamStore((state) => [state.showSolutions, state.setShowSolutions]);
const [selectedModules, setSelectedModules] = useExamStore((state) => [state.selectedModules, state.setSelectedModules]);
const {user} = useUser({redirectTo: "/login"});
const router = useRouter();
useEffect(() => console.log({examId: exam?.id, exam}), [exam]);
useEffect(() => setSessionId(uuidv4()), []);
useEffect(() => {
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
const timerInterval = setInterval(() => {
setTimeSpent((prev) => prev + 1);
}, 1000);
return () => {
clearInterval(timerInterval);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules.length]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
const nextExam = exams[moduleIndex];
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, exams]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map((module) => getExam(module, avoidRepeated));
Promise.all(examPromises).then((values) => {
if (values.every((x) => !!x)) {
setExams(values.map((x) => x!));
} else {
toast.error("Something went wrong, please try again");
setTimeout(router.reload, 500);
}
});
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, setExams, exams]);
useEffect(() => {
if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
const newStats: Stat[] = userSolutions.map((solution) => ({
...solution,
timeSpent,
session: sessionId,
exam: solution.exam!,
module: solution.module!,
user: user?.id || "",
date: new Date().getTime(),
}));
axios
.post<{ok: boolean}>("/api/stats", newStats)
.then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]);
const updateExamWithUserSolutions = (exam: Exam): Exam => {
if (exam.module === "reading" || exam.module === "listening") {
const parts = exam.parts.map((p) =>
Object.assign(p, {
exercises: p.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions})),
}),
);
return Object.assign(exam, {parts});
}
const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions}));
return Object.assign(exam, {exercises});
};
const onFinish = (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.exercise);
const solutionExams = solutions.map((x) => x.exam);
if (exam && !solutionExams.includes(exam.id)) return;
if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
setHasBeenUploaded(true);
setIsEvaluationLoading(true);
Promise.all(
exam.exercises.map(async (exercise) => {
return (exam.module === "writing" ? evaluateWritingAnswer : evaluateSpeakingAnswer)(
exams,
exam.id,
exercise.id,
solutions.find((x) => x.exercise === exercise.id)!,
).then((response) => {
if (response) {
setUserSolutions([...userSolutions.filter((x) => x.exercise !== exercise.id), response]);
}
});
}),
).finally(() => {
setIsEvaluationLoading(false);
setHasBeenUploaded(false);
});
}
axios.get("/api/stats/update");
setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
setModuleIndex((prev) => prev + 1);
};
const aggregateScoresByModule = (answers: UserSolution[]): {module: Module; total: number; missing: number; correct: number}[] => {
const scores: {[key in Module]: {total: number; missing: number; correct: number}} = {
reading: {
total: 0,
correct: 0,
missing: 0,
},
listening: {
total: 0,
correct: 0,
missing: 0,
},
writing: {
total: 0,
correct: 0,
missing: 0,
},
speaking: {
total: 0,
correct: 0,
missing: 0,
},
};
answers.forEach((x) => {
scores[x.module!] = {
total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing,
};
});
return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0)
.map((x) => ({module: x as Module, ...scores[x as Module]}));
};
const renderScreen = () => {
if (selectedModules.length === 0) {
return (
<Selection
page="exercises"
user={user!}
onStart={(modules, avoid) => {
setSelectedModules(modules);
setAvoidRepeated(avoid);
}}
/>
);
}
if (moduleIndex >= selectedModules.length) {
return (
<Finish
isLoading={isEvaluationLoading}
user={user!}
modules={selectedModules}
onViewResults={() => {
setShowSolutions(true);
setModuleIndex(0);
}}
scores={aggregateScoresByModule(userSolutions)}
/>
);
}
if (exam && exam.module === "reading") {
return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "listening") {
return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "writing") {
return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
if (exam && exam.module === "speaking") {
return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
}
return <>Loading...</>;
};
return (
<>
<Head>
<title>Exercises | EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<Layout
user={user}
className="justify-between"
focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
<>
{renderScreen()}
{!showSolutions && moduleIndex < selectedModules.length && (
<AbandonPopup
isOpen={showAbandonPopup}
abandonPopupTitle="Leave Exercise"
abandonPopupDescription="Are you sure you want to leave the exercise? You will lose all your progress."
abandonConfirmButtonText="Confirm"
onAbandon={() => router.reload()}
onCancel={() => setShowAbandonPopup(false)}
/>
)}
</>
</Layout>
)}
</>
);
return <ExamPage page="exercises" />;
}

View File

@@ -6,7 +6,7 @@ import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {useEffect, useState} from "react";
import useStats from "@/hooks/useStats";
import {averageScore, totalExams} from "@/utils/stats";
import {averageScore, groupBySession, totalExams} from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import Diagnostic from "@/components/Diagnostic";
@@ -21,6 +21,7 @@ import DemographicInformationInput from "@/components/DemographicInformationInpu
import moment from "moment";
import Link from "next/link";
import {MODULE_ARRAY} from "@/utils/moduleUtils";
import ProfileSummary from "@/components/ProfileSummary";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -159,105 +160,26 @@ export default function Home() {
<ToastContainer />
{user && (
<Layout user={user}>
<section className="w-full flex -md:flex-col gap-4 md:gap-8">
<img
src={user.profilePicture}
alt={user.name}
className="aspect-square h-20 md:h-64 rounded-3xl drop-shadow-xl object-cover -md:hidden"
<ProfileSummary
user={user}
items={[
{
icon: <BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: Object.keys(groupBySession(stats)).length,
label: "Exams",
},
{
icon: <BsPencil className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: stats.length,
label: "Exercises",
},
{
icon: <BsStar className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: `${stats.length > 0 ? averageScore(stats) : 0}%`,
label: "Average Score",
},
]}
/>
<div className="flex md:flex-col gap-4 md:py-4 w-full -md:items-center">
<img
src={user.profilePicture}
alt={user.name}
className="aspect-square h-24 md:hidden rounded-3xl drop-shadow-xl object-cover"
/>
<div className="flex -md:flex-col justify-between w-full gap-8">
<div className="flex flex-col gap-2 py-2">
<h1 className="font-bold text-2xl md:text-4xl">{user.name}</h1>
<h6 className="font-normal text-base text-mti-gray-taupe">{capitalize(user.type)}</h6>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={100}
color="purple"
className="max-w-xs w-32 md:self-end h-10 -md:hidden"
/>
</div>
<ProgressBar
label=""
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="red"
className="w-full h-3 drop-shadow-lg -md:hidden"
/>
<div className="flex justify-between w-full mt-8 -md:hidden">
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsFileEarmarkText className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{totalExams(stats)}</span>
<span className="font-normal text-base text-mti-gray-dim">Exams</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsPencil className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{stats.length}</span>
<span className="font-normal text-base text-mti-gray-dim">Exercises</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsStar className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{stats.length > 0 ? averageScore(stats) : 0}%</span>
<span className="font-normal text-base text-mti-gray-dim">Average Score</span>
</div>
</div>
</div>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="purple"
className="w-full md:hidden h-8"
textClassName="!text-mti-black"
/>
<div className="grid grid-cols-2 gap-4 w-full mt-4 md:hidden">
<div className="flex gap-4 items-center">
<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
<BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-lg md:text-xl">{totalExams(stats)}</span>
<span className="font-normal text-sm md:text-base text-mti-gray-dim">Exams</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
<BsPencil className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-lg md:text-xl">{stats.length}</span>
<span className="font-normal text-sm md:text-base text-mti-gray-dim">Exercises</span>
</div>
</div>
<div className="flex gap-4 items-center col-span-2">
<div className="w-12 h-12 md:w-16 md:h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
<BsStar className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-lg md:text-xl">{stats.length > 0 ? averageScore(stats) : 0}%</span>
<span className="font-normal text-sm md:text-base text-mti-gray-dim">Average Score</span>
</div>
</div>
</div>
</section>
<section className="flex flex-col gap-1 md:gap-3">
<span className="font-bold text-lg">Bio</span>
@@ -275,7 +197,7 @@ export default function Home() {
<div className="w-8 h-8 md:w-12 md:h-12 bg-mti-gray-smoke flex items-center justify-center rounded-lg md:rounded-xl">
{module === "reading" && <BsBook className="text-ielts-reading w-4 h-4 md:w-5 md:h-5" />}
{module === "listening" && <BsHeadphones className="text-ielts-listening w-4 h-4 md:w-5 md:h-5" />}
{module === "writing" && <BsPencil className="text-ielts-writing w-4 h-4 md:w-5 md:h-5" />}
{module === "writing" && <BsPen className="text-ielts-writing w-4 h-4 md:w-5 md:h-5" />}
{module === "speaking" && <BsMegaphone className="text-ielts-speaking w-4 h-4 md:w-5 md:h-5" />}
</div>
<div className="flex justify-between w-full">

View File

@@ -241,8 +241,8 @@ export default function History({user}: {user: User}) {
<ToastContainer />
{user && (
<Layout user={user}>
<div className="w-full flex justify-between items-center">
<div className="w-3/4">
<div className="w-full flex -md:flex-col -md:gap-4 justify-between items-center">
<div className="md:w-3/4">
{(user.type === "developer" || user.type === "owner") && (
<Select
options={users.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
@@ -274,7 +274,7 @@ export default function History({user}: {user: User}) {
/>
)}
</div>
<div className="flex gap-4 w-full justify-end">
<div className="flex gap-4 w-full -md:justify-center md:justify-end">
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
@@ -305,7 +305,7 @@ export default function History({user}: {user: User}) {
</div>
</div>
{groupedStats && Object.keys(groupedStats).length > 0 && !isStatsLoading && (
<div className="grid grid-cols-3 w-full gap-6">
<div className="grid grid-cols-1 md:grid-cols-3 w-full gap-4 md:gap-6">
{Object.keys(filterStatsByDate(groupedStats))
.sort((a, b) => parseInt(b) - parseInt(a))
.map(customContent)}

View File

@@ -21,6 +21,7 @@ import Select from "react-select";
import useGroups from "@/hooks/useGroups";
import DatePicker from "react-datepicker";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import ProfileSummary from "@/components/ProfileSummary";
ChartJS.register(LinearScale, CategoryScale, PointElement, LineElement, LineController, Legend, Tooltip);
@@ -144,58 +145,27 @@ export default function Stats() {
<ToastContainer />
{user && (
<Layout user={user} className="gap-8">
<section className="w-full flex gap-8">
<img src={user.profilePicture} alt={user.name} className="aspect-square h-64 rounded-3xl drop-shadow-xl object-cover" />
<div className="flex flex-col gap-4 py-4 w-full">
<div className="flex justify-between w-full gap-8">
<div className="flex flex-col gap-2 py-2">
<h1 className="font-bold text-4xl">{user.name}</h1>
<h6 className="font-normal text-base text-mti-gray-taupe">{capitalize(user.type)}</h6>
</div>
<ProgressBar
label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
percentage={100}
color="purple"
className="max-w-xs w-32 self-end h-10"
<ProfileSummary
user={user}
items={[
{
icon: <BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: Object.keys(groupBySession(userStats)).length,
label: "Exams",
},
{
icon: <BsPencil className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: userStats.length,
label: "Exercises",
},
{
icon: <BsStar className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
value: `${stats.length > 0 ? averageScore(userStats) : 0}%`,
label: "Average Score",
},
]}
/>
</div>
<ProgressBar
label=""
percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
color="red"
className="w-full h-3 drop-shadow-lg"
/>
<div className="flex justify-between w-full mt-8">
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsFileEarmarkText className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{Object.keys(groupBySession(userStats)).length}</span>
<span className="font-normal text-base text-mti-gray-dim">Exams</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsPencil className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{userStats.length}</span>
<span className="font-normal text-base text-mti-gray-dim">Exercises</span>
</div>
</div>
<div className="flex gap-4 items-center">
<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
<BsStar className="w-8 h-8 text-mti-red-light" />
</div>
<div className="flex flex-col">
<span className="font-bold text-xl">{averageScore(userStats)}%</span>
<span className="font-normal text-base text-mti-gray-dim">Average Score</span>
</div>
</div>
</div>
</div>
</section>
<section className="flex flex-col gap-3">
<div className="w-full flex justify-between gap-8 items-center">
<>
@@ -246,9 +216,9 @@ export default function Stats() {
</div>
{stats.length > 0 && (
<div className="flex gap-4 flex-wrap">
<div className="flex -md:flex-col -md:items-center gap-4 flex-wrap">
{/* Exams per module */}
<div className="flex flex-col gap-10 border w-full h-96 max-w-xs border-mti-gray-platinum p-4 pb-12 rounded-xl">
<div className="flex flex-col gap-10 border w-full h-fit md:h-96 md:max-w-xs border-mti-gray-platinum p-4 pb-12 rounded-xl">
<span className="text-sm font-bold">Exams per Module</span>
<div className="flex flex-col gap-4">
{MODULE_ARRAY.map((module) => (
@@ -272,7 +242,7 @@ export default function Stats() {
</div>
{/* Module Score */}
<div className="flex flex-col gap-10 border w-full h-96 max-w-xs border-mti-gray-platinum p-4 pb-12 rounded-xl">
<div className="flex flex-col gap-10 border w-full h-fit md:h-96 md:max-w-xs border-mti-gray-platinum p-4 pb-12 rounded-xl">
<span className="text-sm font-bold">Module Score Bands</span>
<div className="flex flex-col gap-4">
{MODULE_ARRAY.map((module) => (
@@ -296,7 +266,7 @@ export default function Stats() {
</div>
{/* Total Score Band per Session */}
<div className="w-full max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-96">
<div className="w-full md:max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-fit md:h-96">
<span className="text-sm font-bold">Total Score Band per Session</span>
<Chart
type="line"
@@ -319,7 +289,7 @@ export default function Stats() {
</div>
{/* Module Score Band per Session */}
<div className="w-full max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-96">
<div className="w-full md:max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-fit md:h-96">
<span className="text-sm font-bold">Module Score Band per Session</span>
<Chart
type="line"
@@ -340,7 +310,7 @@ export default function Stats() {
</div>
{/* Average Time per Module */}
<div className="w-full max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-96">
<div className="w-full md:max-w-2xl border border-mti-gray-platinum p-4 pb-12 rounded-xl h-fit md:h-96">
<span className="text-sm font-bold">Average Time per Module (in Minutes)</span>
<Chart
type="line"