fix(api): fix api logic for exam screen

needs more work for the timercontext
This commit is contained in:
shafin-r
2025-08-31 02:20:55 +06:00
parent 08a560abe5
commit b112a8fdac
7 changed files with 301 additions and 684 deletions

View File

@ -1,300 +1,156 @@
"use client"; "use client";
import React, { useEffect, useState, useCallback, useMemo } from "react"; import React, { useEffect, useCallback, useMemo } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { useTimer } from "@/context/TimerContext"; import { useTimer } from "@/context/TimerContext";
import { useExam } from "@/context/ExamContext"; import { useExam } from "@/context/ExamContext";
import { API_URL, getToken } from "@/lib/auth";
import Header from "@/components/Header"; import Header from "@/components/Header";
import { useModal } from "@/context/ModalContext"; import { useModal } from "@/context/ModalContext";
import Modal from "@/components/ExamModal"; import Modal from "@/components/ExamModal";
import { Question } from "@/types/exam";
import QuestionItem from "@/components/QuestionItem"; import QuestionItem from "@/components/QuestionItem";
import BackgroundWrapper from "@/components/BackgroundWrapper";
export default function ExamPage() { export default function ExamPage() {
// All hooks at the top - no conditional calls
const router = useRouter(); const router = useRouter();
const { id } = useParams(); const searchParams = useSearchParams();
const time = useSearchParams().get("time"); const test_id = searchParams.get("test_id") || "";
const { isOpen, close } = useModal(); const type = searchParams.get("type") || "";
const { setInitialTime, stopTimer } = useTimer();
const {
currentAttempt,
setAnswer,
getAnswer,
submitExam: submitExamContext,
setApiResponse,
isExamStarted,
isExamCompleted,
isHydrated,
isInitialized,
currentExam,
} = useExam();
// State management const { isOpen, close, open } = useModal();
const [questions, setQuestions] = useState<Question[] | null>(null); const { timeRemaining, setInitialTime, stopTimer } = useTimer();
const [loading, setLoading] = useState(true); const { test, answers, startExam, setAnswer, submitExam, cancelExam } =
const [isSubmitting, setIsSubmitting] = useState(false); useExam();
const [submissionLoading, setSubmissionLoading] = useState(false);
const [componentState, setComponentState] = useState<
"loading" | "redirecting" | "ready"
>("loading");
// Combined initialization effect // Start exam + timer
useEffect(() => { useEffect(() => {
let mounted = true; if (type && test_id) {
startExam(type, test_id).then(() => {
const initializeComponent = async () => { if (test?.metadata.time_limit_minutes) {
// Wait for hydration and initialization setInitialTime(test.metadata.time_limit_minutes * 60); // convert to seconds
if (!isHydrated || !isInitialized || isSubmitting) {
return;
}
// Check exam state and handle redirects
if (!isExamStarted()) {
if (mounted) {
setComponentState("redirecting");
setTimeout(() => {
if (mounted) router.push("/unit");
}, 100);
} }
return;
}
if (isExamCompleted()) {
if (mounted) {
setComponentState("redirecting");
setTimeout(() => {
if (mounted) router.push("/exam/results");
}, 100);
}
return;
}
// Component is ready to render
if (mounted) {
setComponentState("ready");
}
};
initializeComponent();
return () => {
mounted = false;
};
}, [
isHydrated,
isInitialized,
isExamStarted,
isExamCompleted,
isSubmitting,
router,
]);
// Fetch questions effect
useEffect(() => {
if (componentState !== "ready") return;
const fetchQuestions = async () => {
try {
const response = await fetch(`${API_URL}/mock/${id}`);
const data = await response.json();
setQuestions(data.questions);
} catch (error) {
console.error("Error fetching questions:", error);
} finally {
setLoading(false);
}
};
fetchQuestions();
if (time) setInitialTime(Number(time));
}, [id, time, setInitialTime, componentState]);
const handleSelect = useCallback(
(questionId: number, option: string) => {
setAnswer(questionId.toString(), option);
},
[setAnswer]
);
const handleSubmit = async () => {
if (!currentAttempt) return console.error("No exam attempt found");
stopTimer();
setSubmissionLoading(true);
setIsSubmitting(true);
const answersForAPI = currentAttempt.answers.reduce(
(acc, { questionId, answer }) => {
acc[+questionId] = answer;
return acc;
},
{} as Record<number, string>
);
try {
const response = await fetch(`${API_URL}/submit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${await getToken()}`,
},
body: JSON.stringify({ mock_id: id, data: answersForAPI }),
}); });
if (!response.ok)
throw new Error((await response.json()).message || "Submission failed");
const responseData = await response.json();
submitExamContext();
setApiResponse(responseData);
router.push("/exam/results");
} catch (error) {
console.error("Error submitting answers:", error);
setIsSubmitting(false);
} finally {
setSubmissionLoading(false);
} }
}; }, [type, test_id, startExam, setInitialTime]);
const showExitDialog = useCallback(() => { const showExitDialog = useCallback(() => {
if (window.confirm("Are you sure you want to quit the exam?")) { if (window.confirm("Are you sure you want to quit the exam?")) {
stopTimer(); stopTimer();
cancelExam();
router.push("/unit"); router.push("/unit");
} }
}, [stopTimer, router]); }, [stopTimer, cancelExam, router]);
useEffect(() => { if (!test) {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = "";
};
const handlePopState = (e: PopStateEvent) => {
e.preventDefault();
showExitDialog();
};
window.addEventListener("beforeunload", handleBeforeUnload);
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("popstate", handlePopState);
};
}, [showExitDialog]);
const answeredSet = useMemo(() => {
if (!currentAttempt) return new Set<string>();
return new Set(currentAttempt.answers.map((a) => String(a.questionId)));
}, [currentAttempt]);
// Show loading/redirecting state
if (componentState === "loading" || componentState === "redirecting") {
const loadingText =
componentState === "redirecting" ? "Redirecting..." : "Loading...";
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
<p className="text-lg font-medium text-gray-900">{loadingText}</p>
</div>
</div>
);
}
// Show submission loading
if (submissionLoading) {
return ( return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center"> <div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="flex flex-col items-center justify-center"> <div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div> <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
<p className="text-lg font-medium text-gray-900">Submitting...</p> <p className="text-lg font-medium text-gray-900">Loading exam...</p>
</div> </div>
</div> </div>
); );
} }
// Render the main exam interface // answered set for modal overview
// const answeredSet = useMemo(
// () =>
// new Set(
// answers
// .map((a, idx) =>
// a !== null && a !== undefined ? idx.toString() : null
// )
// .filter(Boolean) as string[]
// ),
// [answers]
// );
return ( return (
<div className="min-h-screen bg-gray-50"> <div className="min-h-screen bg-gray-50">
<Header examDuration={time} /> {/* Header with live timer */}
<Modal open={isOpen} onClose={close} title={currentExam?.title}> <Header />
{currentAttempt ? (
<div>
<div className="flex gap-4">
<p className="">Questions: {currentExam?.questions.length}</p>
<p className="">
Answers:{" "}
<span className="text-[#113768] font-bold">
{currentAttempt?.answers.length}
</span>
</p>
<p className="">
Skipped:{" "}
<span className="text-yellow-600 font-bold">
{(currentExam?.questions?.length ?? 0) -
(currentAttempt?.answers?.length ?? 0)}
</span>
</p>
</div>
<div className="h-[0.5px] border-[0.5px] border-black/10 w-full my-3"></div>
<section className="flex flex-wrap gap-4">
{currentExam?.questions.map((q, idx) => {
const answered = answeredSet.has(String(q.id));
return ( {/* Modal: Question overview */}
<div {/* <Modal open={isOpen} onClose={close} title="Exam Overview">
key={q.id ?? idx} <div>
className={`h-16 w-16 rounded-full flex items-center justify-center <div className="flex gap-6 mb-4">
text-2xl <p className="font-medium">Questions: {test.questions.length}</p>
<p className="font-medium">
Answered:{" "}
<span className="text-blue-900 font-bold">
{answeredSet.size}
</span>
</p>
<p className="font-medium">
Skipped:{" "}
<span className="text-yellow-600 font-bold">
{test.questions.length - answeredSet.size}
</span>
</p>
</div>
<div className="h-[0.5px] border-[0.5px] border-black/10 w-full my-3"></div>
<section className="flex flex-wrap gap-4">
{test.questions.map((q, idx) => {
const answered = answeredSet.has(String(idx));
return (
<div
key={q.question_id}
className={`h-12 w-12 rounded-full flex items-center justify-center cursor-pointer
${ ${
answered answered
? "bg-[#0E2C53] text-white font-semibold" ? "bg-blue-900 text-white"
: "bg-[#E9EDF1] text-black font-normal" : "bg-gray-200 text-gray-900"
}`} }
> hover:opacity-80 transition`}
{idx + 1} onClick={() => {
</div> // optional: scroll to question
); const el = document.getElementById(`question-${idx}`);
})} if (el) {
</section> el.scrollIntoView({ behavior: "smooth" });
</div> close();
) : ( }
<p>No attempt data.</p> }}
)} >
</Modal> {idx + 1}
<div className="container mx-auto px-6 py-8"> </div>
{loading ? ( );
<div className="flex items-center justify-center min-h-64"> })}
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900"></div> </section>
</div>
) : (
<div className="space-y-6 mb-20">
{questions?.map((q) => (
<QuestionItem
key={q.id}
question={q}
selectedAnswer={getAnswer(q.id.toString())}
handleSelect={handleSelect}
mode="exam"
/>
))}
</div>
)}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
<button
onClick={handleSubmit}
disabled={submissionLoading}
className="w-full bg-blue-900 text-white py-4 px-6 rounded-lg font-bold text-lg hover:bg-blue-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Submit
</button>
</div> </div>
</div> </Modal> */}
{/* Questions */}
<BackgroundWrapper>
<div className="container mx-auto px-6 py-8 mb-20">
{test.questions.map((q, idx) => (
<div id={`question-${idx}`} key={q.question_id}>
<QuestionItem
question={q}
index={idx}
selectedAnswer={answers[idx]}
onSelect={(answer) => setAnswer(idx, answer)}
/>
</div>
))}
{/* Bottom submit bar */}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex">
<button
onClick={submitExam}
className="flex-1 bg-blue-900 text-white p-6 font-bold text-lg hover:bg-blue-800 transition-colors"
>
Submit
</button>
<button
onClick={showExitDialog}
className="flex-1 bg-gray-200 text-gray-900 p-6 font-bold text-lg hover:bg-gray-300 transition-colors"
>
Cancel
</button>
</div>
</div>
</BackgroundWrapper>
</div> </div>
); );
} }

View File

@ -14,14 +14,14 @@ import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper"; import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth"; import { API_URL, getToken } from "@/lib/auth";
import { useExam } from "@/context/ExamContext"; import { useExam } from "@/context/ExamContext";
import { Question } from "@/types/exam"; import { Test } from "@/types/exam";
import { Metadata } from "@/types/exam"; import { Metadata } from "@/types/exam";
function PretestPageContent() { function PretestPageContent() {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { startExam, setCurrentExam } = useExam(); const { startExam } = useExam();
const [examData, setExamData] = useState<Question[]>(); const [examData, setExamData] = useState<Test>();
// Get params from URL search params // Get params from URL search params
const id = searchParams.get("test_id") || ""; const id = searchParams.get("test_id") || "";
@ -55,7 +55,7 @@ function PretestPageContent() {
const data = await questionResponse.json(); const data = await questionResponse.json();
const fetchedMetadata: Metadata = data.metadata; const fetchedMetadata: Metadata = data.metadata;
const fetchedQuestions: Question[] = data.questions; const fetchedQuestions: Test = data.questions;
setMetadata(fetchedMetadata); setMetadata(fetchedMetadata);
setExamData(fetchedQuestions); setExamData(fetchedQuestions);
@ -123,9 +123,9 @@ function PretestPageContent() {
function handleStartExam() { function handleStartExam() {
if (!examData) return; if (!examData) return;
setCurrentExam(examData); router.push(
startExam(examData); `/exam/${id}?type=${type}&test_id=${metadata?.test_id}&attempt_id=${metadata?.attempt_id}`
router.push(`/exam/${id}?test_id=${metadata?.test_id}`); );
} }
return ( return (
<BackgroundWrapper> <BackgroundWrapper>

View File

@ -1,4 +1,6 @@
import React, { useState, useEffect } from "react"; "use client";
import React from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { ChevronLeft, Layers } from "lucide-react"; import { ChevronLeft, Layers } from "lucide-react";
import { useTimer } from "@/context/TimerContext"; import { useTimer } from "@/context/TimerContext";
@ -12,53 +14,25 @@ interface HeaderProps {
displayUser?: boolean; displayUser?: boolean;
displaySubject?: string; displaySubject?: string;
displayTabTitle?: string; displayTabTitle?: string;
examDuration?: string | null;
} }
const Header = ({ const Header = ({
displayUser, displayUser,
displaySubject, displaySubject,
displayTabTitle, displayTabTitle,
examDuration,
}: HeaderProps) => { }: HeaderProps) => {
const router = useRouter(); const router = useRouter();
const { open } = useModal(); const { open } = useModal();
const { clearExam } = useExam(); const { cancelExam } = useExam();
const [totalSeconds, setTotalSeconds] = useState( const { stopTimer, timeRemaining } = useTimer();
examDuration ? parseInt(examDuration) * 60 : 0 const { user } = useAuth();
);
const { stopTimer } = useTimer();
const { user, isLoading } = useAuth();
useEffect(() => {
if (!examDuration) return;
const timer = setInterval(() => {
setTotalSeconds((prev) => {
if (prev <= 0) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [examDuration]);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const showExitDialog = () => { const showExitDialog = () => {
const confirmed = window.confirm("Are you sure you want to quit the exam?"); const confirmed = window.confirm("Are you sure you want to quit the exam?");
if (confirmed) { if (confirmed) {
if (stopTimer) { stopTimer();
stopTimer(); cancelExam();
} router.push("/categories");
clearExam();
router.push("/unit");
} }
}; };
@ -66,6 +40,11 @@ const Header = ({
router.back(); router.back();
}; };
// format time from context
const hours = Math.floor(timeRemaining / 3600);
const minutes = Math.floor((timeRemaining % 3600) / 60);
const seconds = timeRemaining % 60;
return ( return (
<header className={styles.header}> <header className={styles.header}>
{displayUser && ( {displayUser && (
@ -96,7 +75,8 @@ const Header = ({
</div> </div>
)} )}
{examDuration && ( {/* Exam timer header */}
{timeRemaining > 0 && (
<div className={styles.examHeader}> <div className={styles.examHeader}>
<button onClick={showExitDialog} className={styles.iconButton}> <button onClick={showExitDialog} className={styles.iconButton}>
<ChevronLeft size={30} color="white" /> <ChevronLeft size={30} color="white" />
@ -123,10 +103,7 @@ const Header = ({
</div> </div>
</div> </div>
<button <button onClick={open} className={`${styles.iconButton}`}>
onClick={open}
className={`${styles.iconButton} ${styles.disabled}`}
>
<Layers size={30} color="white" /> <Layers size={30} color="white" />
</button> </button>
</div> </div>

View File

@ -1,136 +1,77 @@
import { Question } from "@/types/exam"; "use client";
import { BookmarkCheck, Bookmark } from "lucide-react";
import React, { useState } from "react";
import { Badge } from "./ui/badge";
interface ResultItemProps { import React from "react";
mode: "result"; import { Question, Answer } from "@/types/exam";
import { Bookmark } from "lucide-react";
interface QuestionItemProps {
question: Question; question: Question;
selectedAnswer: { answer: string } | undefined; index: number;
selectedAnswer: Answer;
onSelect: (answer: Answer) => void;
} }
interface ExamItemProps { const letters = ["A", "B", "C", "D"]; // extend if needed
mode: "exam";
question: Question;
selectedAnswer?: string;
handleSelect: (questionId: number, option: string) => void;
}
type QuestionItemProps = ResultItemProps | ExamItemProps;
const QuestionItem = (props: QuestionItemProps) => {
const [bookmark, setBookmark] = useState(false);
const { question } = props;
const isExam = props.mode === "exam";
// Extract correct type-safe selectedAnswer
const selectedAnswer = isExam
? props.selectedAnswer
: props.selectedAnswer?.answer;
const handleOptionSelect = (key: string) => {
if (isExam && props.handleSelect) {
props.handleSelect(parseInt(question.id), key);
}
};
const QuestionItem: React.FC<QuestionItemProps> = ({
question,
index,
selectedAnswer,
onSelect,
}) => {
return ( return (
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col"> <div className="border border-blue-100 p-6 bg-slate-100 rounded-3xl mb-6">
<h3 className="text-xl font-semibold "> <p className="text-lg font-semibold mb-3">
{question.id}. {question.question} {index + 1}. {question.question}
</h3> </p>
{isExam && ( <div className="w-full flex justify-between">
<div className="flex justify-between items-center mb-4"> <div></div>
<div></div> <Bookmark size={24} />
<button onClick={() => setBookmark(!bookmark)}> </div>
{bookmark ? (
<BookmarkCheck size={25} color="#113768" />
) : (
<Bookmark size={25} color="#113768" />
)}
</button>
</div>
)}
{isExam ? ( <div className="flex flex-col gap-3">
<div className="flex flex-col gap-4 items-start"> {question.options.map((opt, optIdx) => {
{Object.entries(question.options ?? {}).map(([key, value]) => { const isSelected =
const isSelected = selectedAnswer === key; question.type === "Single"
? selectedAnswer === optIdx
: Array.isArray(selectedAnswer) &&
selectedAnswer.includes(optIdx);
return ( return (
<div key={optIdx} className="flex items-center gap-3">
<button <button
key={key} onClick={() => {
className="flex items-center gap-3" if (question.type === "Single") {
onClick={() => handleOptionSelect(key)} onSelect(optIdx);
} else {
let newAnswers = Array.isArray(selectedAnswer)
? [...selectedAnswer]
: [];
if (newAnswers.includes(optIdx)) {
newAnswers = newAnswers.filter((a) => a !== optIdx);
} else {
newAnswers.push(optIdx);
}
onSelect(newAnswers);
}
}}
className={`w-7 h-7 rounded-full border font-bold
flex items-center justify-center
${
isSelected
? "bg-blue-600 text-white border-blue-600"
: "bg-gray-100 text-gray-900 border-gray-400"
}
hover:bg-blue-500 hover:text-white transition-colors`}
> >
<span {letters[optIdx]}
className={`flex items-center rounded-full border px-1.5 ${
isSelected ? "text-white bg-[#113768] border-[#113768]" : ""
}`}
>
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
</button> </button>
); <span className="text-gray-900">{opt}</span>
})} </div>
</div> );
) : ( })}
<div className="flex flex-col gap-3"> </div>
<div className="flex justify-between items-center">
<div></div>
{!selectedAnswer ? (
<Badge className="bg-yellow-500" variant="destructive">
Skipped
</Badge>
) : selectedAnswer === question.correctAnswer ? (
<Badge className="bg-green-500 text-white" variant="default">
Correct
</Badge>
) : (
<Badge className="bg-red-500 text-white" variant="default">
Incorrect
</Badge>
)}
</div>
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options ?? {}).map(([key, value]) => {
const isCorrect = key === question.correctAnswer;
const isSelected = key === selectedAnswer;
let optionStyle =
"px-2 py-1 flex items-center rounded-full border font-medium text-sm";
if (isCorrect) {
optionStyle += " bg-green-600 text-white border-green-600";
} else if (isSelected && !isCorrect) {
optionStyle += " bg-red-600 text-white border-red-600";
} else {
optionStyle += " border-gray-300 text-gray-700";
}
return (
<div key={key} className="flex items-center gap-3">
<span className={optionStyle}>{key.toUpperCase()}</span>
<span className="option-description">{value}</span>
</div>
);
})}
</div>
<div className="h-[0.5px] border-[0.5px] border-dashed border-black/20"></div>
<div className="flex flex-col gap-2">
<h3 className="text-lg font-bold text-black/40">Solution:</h3>
<p className="text-lg">{question.solution}</p>
</div>
</div>
)}
</div> </div>
); );
}; };

View File

@ -1,231 +1,100 @@
"use client"; "use client";
import React, { import React, { createContext, useContext, useState } from "react";
createContext, import { Test, Answer } from "@/types/exam";
useContext, import { API_URL } from "@/lib/auth";
useState, import { getToken } from "@/lib/auth";
useEffect,
ReactNode,
} from "react";
import { useRouter } from "next/navigation";
import { Test, TestAttempt, TestContextType, Answer } from "@/types/exam"; interface ExamContextType {
import { getFromStorage, removeFromStorage, setToStorage } from "@/lib/utils"; test: Test | null;
import { useAuth } from "./AuthContext"; answers: Answer[];
startExam: (testType: string, testId: string) => Promise<void>;
setAnswer: (questionIndex: number, answer: Answer) => void;
submitExam: () => Promise<void>;
cancelExam: () => void;
}
const ExamContext = createContext<TestContextType | undefined>(undefined); const ExamContext = createContext<ExamContextType | undefined>(undefined);
const STORAGE_KEYS = { export const ExamProvider: React.FC<{ children: React.ReactNode }> = ({
CURRENT_EXAM: "current-exam",
CURRENT_ATTEMPT: "current-attempt",
} as const;
export const ExamProvider: React.FC<{ children: ReactNode }> = ({
children, children,
}) => { }) => {
const router = useRouter(); const [test, setTest] = useState<Test | null>(null);
const [currentExam, setCurrentExamState] = useState<Test | null>(null); const [answers, setAnswers] = useState<Answer[]>([]);
const [currentAttempt, setCurrentAttemptState] = useState<TestAttempt | null>(
null
);
const [isHydrated, setIsHydrated] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const { user } = useAuth();
// Hydrate from storage // start exam
useEffect(() => { const startExam = async (testType: string, testId: string) => {
const savedExam = getFromStorage<Test>(STORAGE_KEYS.CURRENT_EXAM); try {
const savedAttempt = getFromStorage<TestAttempt>( const token = await getToken(); // if needed
STORAGE_KEYS.CURRENT_ATTEMPT const res = await fetch(`${API_URL}/tests/${testType}/${testId}`, {
); method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (savedExam) setCurrentExamState(savedExam); if (!res.ok) throw new Error(`Failed to fetch test: ${res.status}`);
if (savedAttempt) setCurrentAttemptState(savedAttempt); const data: Test = await res.json();
setTest(data);
setIsHydrated(true); setAnswers(Array(data.questions.length).fill(null));
}, []); } catch (err) {
console.error("startExam error:", err);
// Persist exam
useEffect(() => {
if (!isHydrated) return;
if (currentExam) {
setToStorage(STORAGE_KEYS.CURRENT_EXAM, currentExam);
} else {
removeFromStorage(STORAGE_KEYS.CURRENT_EXAM);
} }
}, [currentExam, isHydrated]);
// Persist attempt
useEffect(() => {
if (!isHydrated) return;
if (currentAttempt) {
setToStorage(STORAGE_KEYS.CURRENT_ATTEMPT, currentAttempt);
} else {
removeFromStorage(STORAGE_KEYS.CURRENT_ATTEMPT);
}
}, [currentAttempt, isHydrated]);
const setCurrentExam = (exam: Test) => {
setCurrentExamState(exam);
setCurrentAttemptState(null);
}; };
const startExam = (exam?: Test): void => { // update answer
const examToUse = exam || currentExam; const setAnswer = (questionIndex: number, answer: Answer) => {
const user_id = user?.user_id; setAnswers((prev) => {
const updated = [...prev];
if (!examToUse) { updated[questionIndex] = answer;
console.warn("No exam selected, redirecting to /unit"); return updated;
router.push("/unit");
return;
}
const attempt: TestAttempt = {
user_id: user_id, // TODO: inject from auth
test_id: examToUse.metadata.test_id,
subject_id: "temp-subject", // TODO: might delete
topic_id: "temp-topic", // TODO: might delete
test_type: "Mock", // or "Subject"/"Topic" depending on flow
attempt_id: crypto.randomUUID(),
start_time: new Date().toISOString(),
end_time: "",
user_questions: examToUse.questions,
user_answers: Array(examToUse.questions.length).fill(null),
correct_answers: [],
correct_answers_count: 0,
wrong_answers_count: 0,
skipped_questions_count: 0,
};
setCurrentAttemptState(attempt);
setIsInitialized(true);
};
const setAnswer = (questionId: string, answer: Answer) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
const questionIndex = currentAttempt.user_questions.findIndex(
(q) => q.question_id === questionId
);
if (questionIndex === -1) return;
setCurrentAttemptState((prev) => {
if (!prev) return null;
const updatedAnswers = [...prev.user_answers];
updatedAnswers[questionIndex] = answer;
return { ...prev, user_answers: updatedAnswers };
}); });
}; };
const setApiResponse = (response: any) => { // submit exam
// If you want to store API response in attempt const submitExam = async () => {
setCurrentAttemptState((prev) => if (!test) return;
prev ? { ...prev, apiResponse: response } : null const token = await getToken();
); try {
}; const { type, test_id, attempt_id } = test.metadata;
const res = await fetch(
`${API_URL}/tests/${type}/${test_id}/${attempt_id}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${token}`,
},
body: JSON.stringify({ answers }),
}
);
if (!res.ok) throw new Error("Failed to submit exam");
const submitExam = (): TestAttempt | null => { // clear
if (!currentAttempt) { setTest(null);
console.warn("No exam attempt to submit, redirecting to /unit"); setAnswers([]);
router.push("/unit"); } catch (err) {
return null; console.error("Failed to submit exam. Reason:", err);
} }
const totalQuestions = currentAttempt.user_questions.length;
// Example evaluation (assumes correct answers in `correct_answers`)
const wrong = currentAttempt.user_answers.filter(
(ans, idx) => ans !== null && ans !== currentAttempt.correct_answers[idx]
).length;
const skipped = currentAttempt.user_answers.filter(
(ans) => ans === null
).length;
const correct = totalQuestions - wrong - skipped;
const completedAttempt: TestAttempt = {
...currentAttempt,
end_time: new Date().toISOString(),
correct_answers_count: correct,
wrong_answers_count: wrong,
skipped_questions_count: skipped,
};
setCurrentAttemptState(completedAttempt);
return completedAttempt;
}; };
const clearExam = (): void => { // cancel exam
setCurrentExamState(null); const cancelExam = () => {
setCurrentAttemptState(null); setTest(null);
}; setAnswers([]);
const getAnswer = (questionId: string): Answer => {
if (!currentAttempt) return null;
const index = currentAttempt.user_questions.findIndex(
(q) => q.question_id === questionId
);
return index >= 0 ? currentAttempt.user_answers[index] : null;
};
const getApiResponse = (): any => {
return (currentAttempt as any)?.apiResponse;
};
const getProgress = (): number => {
if (!currentAttempt) return 0;
const totalQuestions = currentAttempt.user_questions.length;
const answered = currentAttempt.user_answers.filter(
(a) => a !== null
).length;
return totalQuestions > 0 ? (answered / totalQuestions) * 100 : 0;
};
const isExamStarted = () => !!currentExam && !!currentAttempt;
const isExamCompleted = (): boolean => {
if (!isHydrated) return false;
return !!currentAttempt?.end_time;
};
const contextValue: TestContextType = {
currentExam,
currentAttempt,
setCurrentExam,
startExam,
setAnswer,
submitExam,
clearExam,
setApiResponse,
getAnswer,
getProgress,
isExamStarted,
isExamCompleted,
getApiResponse,
isHydrated,
isInitialized,
}; };
return ( return (
<ExamContext.Provider value={contextValue}>{children}</ExamContext.Provider> <ExamContext.Provider
value={{ test, answers, startExam, setAnswer, submitExam, cancelExam }}
>
{children}
</ExamContext.Provider>
); );
}; };
export const useExam = (): TestContextType => { export const useExam = (): ExamContextType => {
const context = useContext(ExamContext); const ctx = useContext(ExamContext);
if (!context) { if (!ctx) throw new Error("useExam must be used inside ExamProvider");
throw new Error("useExam must be used within an ExamProvider"); return ctx;
}
return context;
};
export const useExamResults = (): TestAttempt | null => {
const { currentAttempt, isExamCompleted, isHydrated } = useExam();
if (!isHydrated) return null;
if (!isExamCompleted() || !currentAttempt) return null;
return currentAttempt;
}; };

View File

@ -1,31 +1,36 @@
"use client"; "use client";
import React, { createContext, useContext, useState, useEffect } from "react"; import React, {
createContext,
useContext,
useState,
useEffect,
useRef,
} from "react";
// Define the context type
interface TimerContextType { interface TimerContextType {
timeRemaining: number; timeRemaining: number;
resetTimer: (duration: number) => void; resetTimer: (duration: number) => void;
stopTimer: () => void; stopTimer: () => void;
setInitialTime: (duration: number) => void; // New function to set the initial time setInitialTime: (duration: number) => void;
} }
// Create the context with a default value of `undefined`
const TimerContext = createContext<TimerContextType | undefined>(undefined); const TimerContext = createContext<TimerContextType | undefined>(undefined);
// Provider Component
export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({ export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
children, children,
}) => { }) => {
const [timeRemaining, setTimeRemaining] = useState<number>(0); // Default is 0 const [timeRemaining, setTimeRemaining] = useState<number>(0);
let timer: NodeJS.Timeout; const timerRef = useRef<NodeJS.Timeout | null>(null);
// countdown effect
useEffect(() => { useEffect(() => {
if (timeRemaining > 0) { if (timeRemaining > 0 && !timerRef.current) {
timer = setInterval(() => { timerRef.current = setInterval(() => {
setTimeRemaining((prev) => { setTimeRemaining((prev) => {
if (prev <= 1) { if (prev <= 1) {
clearInterval(timer); clearInterval(timerRef.current!);
timerRef.current = null;
return 0; return 0;
} }
return prev - 1; return prev - 1;
@ -34,20 +39,29 @@ export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
} }
return () => { return () => {
clearInterval(timer); // Cleanup timer on unmount if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}; };
}, [timeRemaining]); }, [timeRemaining]);
const resetTimer = (duration: number) => { const resetTimer = (duration: number) => {
clearInterval(timer); if (timerRef.current) clearInterval(timerRef.current);
timerRef.current = null;
setTimeRemaining(duration); setTimeRemaining(duration);
}; };
const stopTimer = () => { const stopTimer = () => {
clearInterval(timer); if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}; };
const setInitialTime = (duration: number) => { const setInitialTime = (duration: number) => {
if (timerRef.current) clearInterval(timerRef.current);
timerRef.current = null;
setTimeRemaining(duration); setTimeRemaining(duration);
}; };
@ -60,7 +74,6 @@ export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
); );
}; };
// Hook to use the TimerContext
export const useTimer = (): TimerContextType => { export const useTimer = (): TimerContextType => {
const context = useContext(TimerContext); const context = useContext(TimerContext);
if (!context) { if (!context) {

39
types/exam.d.ts vendored
View File

@ -24,42 +24,3 @@ export interface Test {
export type Answer = number | null; export type Answer = number | null;
export type AnswersMap = Record<string, Answer>; export type AnswersMap = Record<string, Answer>;
export interface TestAttempt {
user_id: string | undefined;
test_id: string;
subject_id: string;
topic_id: string;
test_type: "Subject" | "Topic" | "Mock" | "Past";
attempt_id: string;
start_time: string;
end_time: string;
user_questions: Question[];
user_answers: (number | null)[];
correct_answers: number[];
correct_answers_count: number;
wrong_answers_count: number;
skipped_questions_count: number;
}
export interface TestContextType {
currentExam: Test | null;
currentAttempt: TestAttempt | null;
isHydrated: boolean;
isInitialized: boolean;
// Actions
setCurrentExam: (exam: Test) => void;
startExam: (exam?: Test) => void;
setAnswer: (questionId: string, answer: Answer) => void;
submitExam: () => TestAttempt | null; // or Promise<TestAttempt | null> if API
clearExam: () => void;
setApiResponse: (response: any) => void;
// Getters
getAnswer: (questionId: string) => Answer;
getProgress: () => number;
isExamStarted: () => boolean;
isExamCompleted: () => boolean;
getApiResponse: () => any;
}