generated from muhtadeetaron/nextjs-template
fix(ui): fix exam and result screen ui
This commit is contained in:
@ -1,8 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import React, { useEffect, useState, useCallback, useReducer } from "react";
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import { useTimer } from "@/context/TimerContext";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import Header from "@/components/Header";
|
||||
|
||||
@ -19,16 +20,6 @@ interface QuestionItemProps {
|
||||
handleSelect: (questionId: number, option: string) => void;
|
||||
}
|
||||
|
||||
interface AnswerState {
|
||||
[questionId: number]: string;
|
||||
}
|
||||
|
||||
interface AnswerAction {
|
||||
type: "SELECT_ANSWER";
|
||||
questionId: number;
|
||||
option: string;
|
||||
}
|
||||
|
||||
// Components
|
||||
const QuestionItem = React.memo<QuestionItemProps>(
|
||||
({ question, selectedAnswer, handleSelect }) => (
|
||||
@ -62,30 +53,58 @@ const QuestionItem = React.memo<QuestionItemProps>(
|
||||
|
||||
QuestionItem.displayName = "QuestionItem";
|
||||
|
||||
const reducer = (state: AnswerState, action: AnswerAction): AnswerState => {
|
||||
switch (action.type) {
|
||||
case "SELECT_ANSWER":
|
||||
return { ...state, [action.questionId]: action.option };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
export default function ExamPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const searchParams = useSearchParams();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const id = params.id as string;
|
||||
const time = searchParams.get("time");
|
||||
|
||||
const { setInitialTime, stopTimer } = useTimer();
|
||||
|
||||
// Use exam context instead of local state
|
||||
const {
|
||||
currentAttempt,
|
||||
setAnswer,
|
||||
getAnswer,
|
||||
submitExam: submitExamContext,
|
||||
setApiResponse,
|
||||
isExamStarted,
|
||||
isExamCompleted,
|
||||
isHydrated,
|
||||
isInitialized,
|
||||
} = useExam();
|
||||
|
||||
const [questions, setQuestions] = useState<Question[] | null>(null);
|
||||
const [answers, dispatch] = useReducer(reducer, {});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submissionLoading, setSubmissionLoading] = useState(false);
|
||||
|
||||
// Check if exam is properly started
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
if (!isInitialized) return;
|
||||
if (isSubmitting) return; // Don't redirect while submitting
|
||||
|
||||
if (!isExamStarted()) {
|
||||
router.push("/unit");
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExamCompleted()) {
|
||||
router.push("/exam/results");
|
||||
return;
|
||||
}
|
||||
}, [
|
||||
isHydrated,
|
||||
isExamStarted,
|
||||
isExamCompleted,
|
||||
router,
|
||||
isInitialized,
|
||||
isSubmitting,
|
||||
]);
|
||||
|
||||
const fetchQuestions = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/mock/${id}`, {
|
||||
@ -107,17 +126,33 @@ export default function ExamPage() {
|
||||
}
|
||||
}, [id, time, setInitialTime]);
|
||||
|
||||
const handleSelect = useCallback((questionId: number, option: string) => {
|
||||
dispatch({ type: "SELECT_ANSWER", questionId, option });
|
||||
}, []);
|
||||
const handleSelect = useCallback(
|
||||
(questionId: number, option: string) => {
|
||||
// Store answer in context instead of local reducer
|
||||
setAnswer(questionId.toString(), option);
|
||||
},
|
||||
[setAnswer]
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentAttempt) {
|
||||
console.error("No exam attempt found");
|
||||
return;
|
||||
}
|
||||
|
||||
stopTimer();
|
||||
setSubmissionLoading(true);
|
||||
setIsSubmitting(true); // Add this line
|
||||
|
||||
// Convert context answers to the format your API expects
|
||||
const answersForAPI = currentAttempt.answers.reduce((acc, answer) => {
|
||||
acc[parseInt(answer.questionId)] = answer.answer;
|
||||
return acc;
|
||||
}, {} as Record<number, string>);
|
||||
|
||||
const payload = {
|
||||
mock_id: id,
|
||||
data: answers,
|
||||
data: answersForAPI,
|
||||
};
|
||||
|
||||
try {
|
||||
@ -136,18 +171,24 @@ export default function ExamPage() {
|
||||
"Submission failed:",
|
||||
errorData.message || "Unknown error"
|
||||
);
|
||||
setIsSubmitting(false); // Reset on error
|
||||
return;
|
||||
}
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
router.push(
|
||||
`/exam/results?id=${id}&answers=${encodeURIComponent(
|
||||
JSON.stringify(responseData)
|
||||
)}`
|
||||
);
|
||||
// Submit exam in context (this will store the completed attempt)
|
||||
const completedAttempt = submitExamContext();
|
||||
|
||||
// Store API response in context for results page
|
||||
setApiResponse(responseData);
|
||||
|
||||
// Navigate to results without URL parameters
|
||||
router.push("/exam/results");
|
||||
console.log("I'm here");
|
||||
} catch (error) {
|
||||
console.error("Error submitting answers:", error);
|
||||
setIsSubmitting(false); // Reset on error
|
||||
} finally {
|
||||
setSubmissionLoading(false);
|
||||
}
|
||||
@ -215,7 +256,7 @@ export default function ExamPage() {
|
||||
<QuestionItem
|
||||
key={question.id}
|
||||
question={question}
|
||||
selectedAnswer={answers[question.id]}
|
||||
selectedAnswer={getAnswer(question.id.toString())}
|
||||
handleSelect={handleSelect}
|
||||
/>
|
||||
))}
|
||||
@ -234,85 +275,6 @@ export default function ExamPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style jsx>{`
|
||||
.question-container {
|
||||
border: 1px solid #8abdff;
|
||||
border-radius: 25px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.question-text {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 10px;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
.options-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.option-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid transparent;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.option-button:hover {
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
|
||||
.selected-option {
|
||||
background-color: #f0f8ff;
|
||||
}
|
||||
|
||||
.option-text {
|
||||
font-size: 14px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 25px;
|
||||
text-align: center;
|
||||
border: 1px solid #ddd;
|
||||
min-width: 32px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.selected-option-text {
|
||||
color: white;
|
||||
background-color: #113768;
|
||||
border-color: #113768;
|
||||
}
|
||||
|
||||
.option-description {
|
||||
font-size: 16px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.question-container {
|
||||
padding: 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.question-text {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.option-description {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import { API_URL } from "@/lib/auth";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
|
||||
interface Metadata {
|
||||
metadata: {
|
||||
@ -19,6 +20,8 @@ interface Metadata {
|
||||
export default function PretestPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [examData, setExamData] = useState();
|
||||
const { startExam, setCurrentExam } = useExam();
|
||||
|
||||
// Get params from URL search params
|
||||
const name = searchParams.get("name") || "";
|
||||
@ -38,12 +41,14 @@ export default function PretestPage() {
|
||||
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const data = await questionResponse.json();
|
||||
console.log(data);
|
||||
|
||||
if (!questionResponse.ok) {
|
||||
throw new Error("Failed to fetch questions");
|
||||
}
|
||||
|
||||
const fetchedMetadata: Metadata = await questionResponse.json();
|
||||
setExamData(data);
|
||||
const fetchedMetadata: Metadata = data;
|
||||
setMetadata(fetchedMetadata);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@ -171,16 +176,14 @@ export default function PretestPage() {
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="fixed bottom-0 w-full bg-[#113768] h-[78px] flex justify-center items-center border border-transparent text-white font-bold text-2xl hover:bg-[#0d2a52] transition-colors"
|
||||
onClick={() => {
|
||||
if (metadata) {
|
||||
setCurrentExam(examData); // Set exam first
|
||||
startExam(); // Then start exam
|
||||
router.push(`/exam/${id}?time=${metadata.metadata.duration}`);
|
||||
} else {
|
||||
router.push("/unit");
|
||||
}
|
||||
}}
|
||||
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
|
||||
>
|
||||
{metadata ? "Start Test" : "Go Back"}
|
||||
Start Test
|
||||
</button>
|
||||
|
||||
{/* <CustomBackHandler fallbackRoute="paper" /> */}
|
||||
|
||||
@ -1,277 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ArrowLeft, LocateIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useExam, useExamResults } from "@/context/ExamContext";
|
||||
import { useEffect } from "react";
|
||||
import React from "react";
|
||||
|
||||
// Types
|
||||
interface Question {
|
||||
solution: string;
|
||||
id: number;
|
||||
question: string;
|
||||
options: Record<string, string>;
|
||||
correctAnswer: string;
|
||||
userAnswer: string | null;
|
||||
isCorrect: boolean;
|
||||
solution: string;
|
||||
}
|
||||
|
||||
interface ResultSheet {
|
||||
score: number;
|
||||
questions: Question[];
|
||||
interface QuestionItemProps {
|
||||
question: Question;
|
||||
selectedAnswer: string | undefined;
|
||||
}
|
||||
|
||||
const ResultsPage = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const answersParam = searchParams.get("answers");
|
||||
|
||||
if (!answersParam) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
No results found
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => router.push("/unit")}
|
||||
className="bg-blue-900 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-800 transition-colors"
|
||||
>
|
||||
Go Back
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const resultSheet: ResultSheet = JSON.parse(decodeURIComponent(answersParam));
|
||||
|
||||
const getScoreMessage = (score: number) => {
|
||||
if (score < 30) return "Try harder!";
|
||||
if (score < 70) return "Getting Better";
|
||||
return "You did great!";
|
||||
};
|
||||
|
||||
const getStatusColor = (question: Question) => {
|
||||
if (question.userAnswer === null) return "bg-yellow-500";
|
||||
return question.isCorrect ? "bg-green-500" : "bg-red-500";
|
||||
};
|
||||
|
||||
const getStatusText = (question: Question) => {
|
||||
if (question.userAnswer === null) return "Skipped";
|
||||
return question.isCorrect ? "Correct" : "Incorrect";
|
||||
};
|
||||
|
||||
const getOptionClassName = (key: string, question: Question): string => {
|
||||
const isCorrectAnswer = key === question.correctAnswer;
|
||||
const isUserAnswer = key === question.userAnswer;
|
||||
const isCorrectAndUserAnswer = isCorrectAnswer && isUserAnswer;
|
||||
const isUserAnswerWrong = isUserAnswer && !isCorrectAnswer;
|
||||
|
||||
if (isCorrectAndUserAnswer) {
|
||||
return "bg-blue-900 text-white border-blue-900";
|
||||
} else if (isCorrectAnswer) {
|
||||
return "bg-green-500 text-white border-green-500";
|
||||
} else if (isUserAnswerWrong) {
|
||||
return "bg-red-500 text-white border-red-500";
|
||||
}
|
||||
return "border-gray-300";
|
||||
};
|
||||
|
||||
// Handle browser back button
|
||||
useEffect(() => {
|
||||
const handlePopState = () => {
|
||||
router.push("/unit");
|
||||
};
|
||||
|
||||
window.addEventListener("popstate", handlePopState);
|
||||
return () => window.removeEventListener("popstate", handlePopState);
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8 max-w-4xl">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<button
|
||||
onClick={() => router.push("/unit")}
|
||||
className="flex items-center text-gray-700 hover:text-gray-900 transition-colors mb-6"
|
||||
>
|
||||
<ArrowLeft size={30} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="space-y-8">
|
||||
{/* Score Message */}
|
||||
<h1 className="text-3xl font-bold text-blue-900 text-center mb-6">
|
||||
{getScoreMessage(resultSheet.score)}
|
||||
</h1>
|
||||
|
||||
{/* Score Card */}
|
||||
<div className="score-card">
|
||||
<p className="text-2xl font-medium mb-4">Score:</p>
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<div className="w-15 h-15 bg-blue-900 rounded-full flex items-center justify-center">
|
||||
<div className="w-6 h-6 bg-white rounded-full"></div>
|
||||
</div>
|
||||
<span className="text-6xl font-bold text-blue-900">
|
||||
{resultSheet.score}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Solutions Section */}
|
||||
<div className="mt-10">
|
||||
<h2 className="text-3xl font-bold text-blue-900 mb-6">Solutions</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{resultSheet.questions.map((question, idx) => (
|
||||
<div key={idx} className="question-card">
|
||||
{/* Question Header */}
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<h3 className="text-xl font-medium flex-1">
|
||||
{idx + 1}. {question.question}
|
||||
const QuestionItem = React.memo<QuestionItemProps>(
|
||||
({ question, selectedAnswer }) => (
|
||||
<div className="border border-[#8abdff]/50 rounded-2xl p-4 flex flex-col gap-7">
|
||||
<h3 className="text-xl font-medium">
|
||||
{question.id}. {question.question}
|
||||
</h3>
|
||||
<div className="flex flex-col gap-4 items-start">
|
||||
{Object.entries(question.options).map(([key, value]) => (
|
||||
<button key={key} className="flex items-center gap-3">
|
||||
<span
|
||||
className={`status-badge ${getStatusColor(question)}`}
|
||||
>
|
||||
{getStatusText(question)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Options */}
|
||||
<div className="space-y-3 mb-6">
|
||||
{Object.entries(question.options).map(([key, option]) => (
|
||||
<div key={key} className="flex items-center gap-4">
|
||||
<span
|
||||
className={`option-letter ${getOptionClassName(
|
||||
key,
|
||||
question
|
||||
)}`}
|
||||
className={`flex items-center rounded-full border px-1.5 ${
|
||||
selectedAnswer === key
|
||||
? "text-white bg-[#113768] border-[#113768]"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
{key.toUpperCase()}
|
||||
</span>
|
||||
<span className="text-lg">{option}</span>
|
||||
</div>
|
||||
<span className="option-description">{value}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<h3 className="text-xl font-bold text-black/40">Solution:</h3>
|
||||
<p className="text-lg font-medium">{question.solution}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
{/* Solution Divider */}
|
||||
<div className="solution-divider"></div>
|
||||
export default function ResultsPage() {
|
||||
const router = useRouter();
|
||||
const { clearExam, isExamCompleted, getApiResponse } = useExam();
|
||||
|
||||
{/* Solution */}
|
||||
<div>
|
||||
<h4 className="text-xl font-semibold text-gray-500 mb-3">
|
||||
Solution:
|
||||
</h4>
|
||||
<p className="text-lg leading-relaxed text-gray-800">
|
||||
{question.solution}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
useEffect(() => {
|
||||
// Redirect if no completed exam
|
||||
if (!isExamCompleted()) {
|
||||
router.push("/exam/select");
|
||||
return;
|
||||
}
|
||||
}, [isExamCompleted, router]);
|
||||
|
||||
{/* Bottom Button */}
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
|
||||
<div className="container mx-auto max-w-4xl">
|
||||
let examResults;
|
||||
try {
|
||||
examResults = useExamResults();
|
||||
} catch (error) {
|
||||
// Handle case where there's no completed exam
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
No exam results found
|
||||
</h1>
|
||||
<button
|
||||
onClick={() => router.push("/unit")}
|
||||
className="w-full bg-blue-900 text-white py-4 px-6 rounded-lg font-bold text-xl hover:bg-blue-800 transition-colors"
|
||||
onClick={() => router.push("/exam/select")}
|
||||
className="bg-blue-900 text-white px-6 py-3 rounded-lg hover:bg-blue-800"
|
||||
>
|
||||
Next
|
||||
Take an Exam
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
{/* Spacer for fixed button */}
|
||||
<div className="h-24"></div>
|
||||
// Get API response data
|
||||
const apiResponse = getApiResponse();
|
||||
|
||||
const handleBackToHome = () => {
|
||||
router.push("/unit");
|
||||
clearExam();
|
||||
};
|
||||
|
||||
const timeTaken =
|
||||
examResults.endTime && examResults.startTime
|
||||
? Math.round(
|
||||
(examResults.endTime.getTime() - examResults.startTime.getTime()) /
|
||||
1000 /
|
||||
60
|
||||
)
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white">
|
||||
<div className="bg-white rounded-lg shadow-lg px-10 py-20">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2 text-center">
|
||||
Keep up the good work!
|
||||
</h1>
|
||||
|
||||
{/* Score Display */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
|
||||
<div className="bg-blue-50 rounded-lg p-6 text-center">
|
||||
<div className="text-3xl font-bold text-blue-900 mb-2">
|
||||
{examResults.score}%
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">Final Score</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style jsx>{`
|
||||
.score-card {
|
||||
height: 170px;
|
||||
width: 100%;
|
||||
border: 2px solid #c1dcff;
|
||||
border-radius: 25px;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
background: white;
|
||||
}
|
||||
{apiResponse && (
|
||||
<div className="mb-8">
|
||||
<h3 className="text-2xl font-bold text-[#113768] mb-4">
|
||||
Solutions
|
||||
</h3>
|
||||
<div className="flex flex-col gap-7">
|
||||
{apiResponse.questions?.map((question) => (
|
||||
<QuestionItem key={question.id} question={question} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
.question-card {
|
||||
border: 2px solid #abd0ff;
|
||||
padding: 24px;
|
||||
border-radius: 20px;
|
||||
background: white;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
padding: 6px 16px;
|
||||
border-radius: 12px;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
font-size: 14px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.option-letter {
|
||||
min-width: 32px;
|
||||
height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
border: 1px solid;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.solution-divider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
border-top: 1px dashed #000;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.score-card {
|
||||
height: 150px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.question-card {
|
||||
padding: 20px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
font-size: 12px;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
|
||||
.option-letter {
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.container {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
{/* Action Buttons */}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleBackToHome}
|
||||
className="fixed bottom-0 w-full bg-blue-900 text-white h-[74px] font-bold text-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Finish
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ResultsPage;
|
||||
}
|
||||
|
||||
@ -3,6 +3,8 @@ import { Montserrat } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { AuthProvider } from "@/context/AuthContext";
|
||||
import { TimerProvider } from "@/context/TimerContext";
|
||||
import { ExamProvider } from "@/context/ExamContext";
|
||||
import { Providers } from "./providers";
|
||||
|
||||
const montserrat = Montserrat({
|
||||
subsets: ["latin"],
|
||||
@ -24,9 +26,7 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en" className={montserrat.variable}>
|
||||
<body className="font-sans">
|
||||
<TimerProvider>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</TimerProvider>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
15
app/providers.tsx
Normal file
15
app/providers.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { ExamProvider } from "@/context/ExamContext";
|
||||
import { TimerProvider } from "@/context/TimerContext";
|
||||
import { AuthProvider } from "@/context/AuthContext";
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<TimerProvider>
|
||||
<AuthProvider>
|
||||
<ExamProvider>{children}</ExamProvider>
|
||||
</AuthProvider>
|
||||
</TimerProvider>
|
||||
);
|
||||
}
|
||||
260
context/ExamContext.tsx
Normal file
260
context/ExamContext.tsx
Normal file
@ -0,0 +1,260 @@
|
||||
"use client";
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
ReactNode,
|
||||
} from "react";
|
||||
|
||||
import { Exam, ExamAnswer, ExamAttempt, ExamContextType } from "@/types/exam";
|
||||
import { getFromStorage, removeFromStorage, setToStorage } from "@/lib/utils";
|
||||
|
||||
const ExamContext = createContext<ExamContextType | undefined>(undefined);
|
||||
|
||||
const STORAGE_KEYS = {
|
||||
CURRENT_EXAM: "current-exam",
|
||||
CURRENT_ATTEMPT: "current-attempt",
|
||||
} as const;
|
||||
|
||||
export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const [currentExam, setCurrentExamState] = useState<Exam | null>(null);
|
||||
const [currentAttempt, setCurrentAttemptState] = useState<ExamAttempt | null>(
|
||||
null
|
||||
);
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Hydrate from session storage on mount
|
||||
useEffect(() => {
|
||||
const savedExam = getFromStorage<Exam>(STORAGE_KEYS.CURRENT_EXAM);
|
||||
const savedAttempt = getFromStorage<ExamAttempt>(
|
||||
STORAGE_KEYS.CURRENT_ATTEMPT
|
||||
);
|
||||
|
||||
if (savedExam) {
|
||||
setCurrentExamState(savedExam);
|
||||
}
|
||||
|
||||
if (savedAttempt) {
|
||||
// Convert date strings back to Date objects
|
||||
const hydratedAttempt = {
|
||||
...savedAttempt,
|
||||
startTime: new Date(savedAttempt.startTime),
|
||||
endTime: savedAttempt.endTime
|
||||
? new Date(savedAttempt.endTime)
|
||||
: undefined,
|
||||
answers: savedAttempt.answers.map((answer) => ({
|
||||
...answer,
|
||||
timestamp: new Date(answer.timestamp),
|
||||
})),
|
||||
};
|
||||
setCurrentAttemptState(hydratedAttempt);
|
||||
}
|
||||
|
||||
setIsHydrated(true);
|
||||
}, []);
|
||||
|
||||
// Persist to session storage whenever state changes
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
|
||||
if (currentExam) {
|
||||
setToStorage(STORAGE_KEYS.CURRENT_EXAM, currentExam);
|
||||
} else {
|
||||
removeFromStorage(STORAGE_KEYS.CURRENT_EXAM);
|
||||
}
|
||||
}, [currentExam, isHydrated]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
|
||||
if (currentAttempt) {
|
||||
setToStorage(STORAGE_KEYS.CURRENT_ATTEMPT, currentAttempt);
|
||||
} else {
|
||||
removeFromStorage(STORAGE_KEYS.CURRENT_ATTEMPT);
|
||||
}
|
||||
}, [currentAttempt, isHydrated]);
|
||||
|
||||
const setCurrentExam = (exam: Exam) => {
|
||||
setCurrentExamState(exam);
|
||||
// Clear any existing attempt when setting a new exam
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
if (!currentExam) {
|
||||
throw new Error("No exam selected");
|
||||
}
|
||||
|
||||
const attempt: ExamAttempt = {
|
||||
examId: currentExam.id,
|
||||
exam: currentExam,
|
||||
answers: [],
|
||||
startTime: new Date(),
|
||||
};
|
||||
|
||||
setCurrentAttemptState(attempt);
|
||||
setIsInitialized(true);
|
||||
};
|
||||
|
||||
const setAnswer = (questionId: string, answer: any) => {
|
||||
if (!currentAttempt) {
|
||||
throw new Error("No exam attempt started");
|
||||
}
|
||||
|
||||
setCurrentAttemptState((prev) => {
|
||||
if (!prev) return null;
|
||||
|
||||
const existingAnswerIndex = prev.answers.findIndex(
|
||||
(a) => a.questionId === questionId
|
||||
);
|
||||
|
||||
const newAnswer: ExamAnswer = {
|
||||
questionId,
|
||||
answer,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
let newAnswers: ExamAnswer[];
|
||||
if (existingAnswerIndex >= 0) {
|
||||
// Update existing answer
|
||||
newAnswers = [...prev.answers];
|
||||
newAnswers[existingAnswerIndex] = newAnswer;
|
||||
} else {
|
||||
// Add new answer
|
||||
newAnswers = [...prev.answers, newAnswer];
|
||||
}
|
||||
|
||||
return {
|
||||
...prev,
|
||||
answers: newAnswers,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const setApiResponse = (response: any) => {
|
||||
if (!currentAttempt) {
|
||||
throw new Error("No exam attempt started");
|
||||
}
|
||||
|
||||
setCurrentAttemptState((prev) => {
|
||||
if (!prev) return null;
|
||||
return {
|
||||
...prev,
|
||||
apiResponse: response,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const submitExam = (): ExamAttempt => {
|
||||
if (!currentAttempt) {
|
||||
throw new Error("No exam attempt to submit");
|
||||
}
|
||||
|
||||
// Calculate score (simple example - you can customize this)
|
||||
const attemptQuestions = currentAttempt.exam.questions;
|
||||
const totalQuestions = attemptQuestions.length;
|
||||
const answeredQuestions = currentAttempt.answers.filter(
|
||||
(a) => a.questionId !== "__api_response__"
|
||||
).length;
|
||||
const score = Math.round((answeredQuestions / totalQuestions) * 100);
|
||||
|
||||
const completedAttempt: ExamAttempt = {
|
||||
...currentAttempt,
|
||||
endTime: new Date(),
|
||||
score,
|
||||
passed: currentAttempt.exam.passingScore
|
||||
? score >= currentAttempt.exam.passingScore
|
||||
: undefined,
|
||||
};
|
||||
|
||||
setCurrentAttemptState(completedAttempt);
|
||||
return completedAttempt;
|
||||
};
|
||||
|
||||
const clearExam = () => {
|
||||
setCurrentExamState(null);
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
|
||||
const getAnswer = (questionId: string): any => {
|
||||
if (!currentAttempt) return undefined;
|
||||
|
||||
const answer = currentAttempt.answers.find(
|
||||
(a) => a.questionId === questionId
|
||||
);
|
||||
return answer?.answer;
|
||||
};
|
||||
|
||||
const getApiResponse = (): any => {
|
||||
return currentAttempt?.apiResponse;
|
||||
};
|
||||
|
||||
const getProgress = (): number => {
|
||||
if (!currentAttempt || !currentAttempt.exam) return 0;
|
||||
|
||||
const totalQuestions = currentAttempt.exam.questions.length;
|
||||
const answeredQuestions = currentAttempt.answers.filter(
|
||||
(a) => a.questionId !== "__api_response__"
|
||||
).length;
|
||||
|
||||
return totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0;
|
||||
};
|
||||
|
||||
const isExamStarted = (): boolean => {
|
||||
if (!isHydrated) return false; // ⛔ wait for hydration
|
||||
return currentAttempt !== null && !currentAttempt.endTime;
|
||||
};
|
||||
|
||||
const isExamCompleted = (): boolean => {
|
||||
if (!isHydrated) return false; // ⛔ wait for hydration
|
||||
return currentAttempt !== null && currentAttempt.endTime !== undefined;
|
||||
};
|
||||
|
||||
const contextValue: ExamContextType = {
|
||||
currentExam,
|
||||
currentAttempt,
|
||||
setCurrentExam,
|
||||
startExam,
|
||||
setAnswer,
|
||||
submitExam,
|
||||
clearExam,
|
||||
setApiResponse,
|
||||
getAnswer,
|
||||
getProgress,
|
||||
isExamStarted,
|
||||
isExamCompleted,
|
||||
getApiResponse,
|
||||
isHydrated,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
return (
|
||||
<ExamContext.Provider value={contextValue}>{children}</ExamContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useExam = (): ExamContextType => {
|
||||
const context = useContext(ExamContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error("useExam must be used within an ExamProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
// Hook for exam results (only when exam is completed)
|
||||
export const useExamResults = (): ExamAttempt => {
|
||||
const { currentAttempt, isExamCompleted } = useExam();
|
||||
|
||||
if (!isExamCompleted() || !currentAttempt) {
|
||||
throw new Error("No completed exam attempt found");
|
||||
}
|
||||
|
||||
return currentAttempt;
|
||||
};
|
||||
38
lib/utils.ts
38
lib/utils.ts
@ -1,6 +1,38 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export const getFromStorage = <T>(key: string): T | null => {
|
||||
if (typeof window === "undefined") return null;
|
||||
|
||||
try {
|
||||
const item = sessionStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : null;
|
||||
} catch (error) {
|
||||
console.error(`Error reading from sessionStorage (${key}):`, error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const setToStorage = <T>(key: string, value: T): void => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
sessionStorage.setItem(key, JSON.stringify(value));
|
||||
} catch (error) {
|
||||
console.error(`Error writing to sessionStorage (${key}):`, error);
|
||||
}
|
||||
};
|
||||
|
||||
export const removeFromStorage = (key: string): void => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
sessionStorage.removeItem(key);
|
||||
} catch (error) {
|
||||
console.error(`Error removing from sessionStorage (${key}):`, error);
|
||||
}
|
||||
};
|
||||
|
||||
54
types/exam.d.ts
vendored
Normal file
54
types/exam.d.ts
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
export interface Question {
|
||||
id: string;
|
||||
text: string;
|
||||
options?: string[];
|
||||
type: "multiple-choice" | "text" | "boolean";
|
||||
}
|
||||
|
||||
export interface Exam {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
questions: Question[];
|
||||
timeLimit?: number;
|
||||
passingScore?: number;
|
||||
}
|
||||
|
||||
export interface ExamAnswer {
|
||||
questionId: string;
|
||||
answer: any;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface ExamAttempt {
|
||||
examId: string;
|
||||
exam: Exam;
|
||||
answers: ExamAnswer[];
|
||||
startTime: Date;
|
||||
endTime?: Date;
|
||||
score?: number;
|
||||
passed?: boolean;
|
||||
apiResponse?: any;
|
||||
}
|
||||
|
||||
export interface ExamContextType {
|
||||
currentExam: Exam | null;
|
||||
currentAttempt: ExamAttempt | null;
|
||||
isHydrated: boolean;
|
||||
isInitialized: boolean;
|
||||
|
||||
// Actions
|
||||
setCurrentExam: (exam: Exam) => void;
|
||||
startExam: () => void;
|
||||
setAnswer: (questionId: string, answer: any) => void;
|
||||
submitExam: () => ExamAttempt;
|
||||
clearExam: () => void;
|
||||
setApiResponse: (response: any) => void;
|
||||
|
||||
// Getters
|
||||
getAnswer: (questionId: string) => any;
|
||||
getProgress: () => number;
|
||||
isExamStarted: () => boolean;
|
||||
isExamCompleted: () => boolean;
|
||||
getApiResponse: () => any;
|
||||
}
|
||||
Reference in New Issue
Block a user