17 Commits
dev ... master

Author SHA1 Message Date
e091a78bdb fix(ts): fix interfaces for type safety 2025-07-27 13:41:02 +06:00
3ef526ec1a chore: refactor code for type safety 2025-07-27 03:19:25 +06:00
0ea199c0fe fix(ui): fix question item answer indexing in results page 2025-07-25 19:09:06 +06:00
d57aa9b073 fix(exam): fix startexam function (not finding examdata) 2025-07-22 22:08:42 +06:00
341a46e788 fix(ui): fix results screen 2025-07-22 17:59:15 +06:00
5245ab878d fix(func): fix issues in results page 2025-07-16 22:28:26 +06:00
32c9065f6f fix(ui): fix profile screen 2025-07-16 16:25:26 +06:00
aa7bc67dc9 feat(screens): implement bookmark and profile screens 2025-07-15 21:20:26 +06:00
71eeafdaee feat(ui): add modal functionality, leaderboard view 2025-07-10 19:28:50 +06:00
64fc4d9a9a feat(ui): add avatar and badge components 2025-07-10 14:51:45 +06:00
d42a42a8d1 fix(exam): fix pretest screen start exam button 2025-07-07 21:01:11 +06:00
22eb8285ec fix(ui): fix exam and result screen ui 2025-07-07 17:52:01 +06:00
48519c42c3 fix(ui): fix exam screen layout, bottom navigation tabs 2025-07-07 13:57:04 +06:00
06418a82ab added exam routes 2025-07-05 19:05:47 +06:00
576398883d fixed sliding gallery, fixed styling 2025-07-04 02:49:17 +06:00
17ebe63dfd Merge branch 'main' of https://git.omukk.dev/shafin808s/examjam-frontend 2025-07-03 01:54:56 +06:00
b0737ea703 Initial commit 2025-07-02 19:41:20 +00:00
45 changed files with 3080 additions and 332 deletions

View File

@ -76,7 +76,7 @@ const page = () => {
{error && <DestructibleAlert text={error} extraStyles="" />}
<button
onClick={() => router.push("/home")}
onClick={loginUser}
disabled={isLoading}
className="w-full h-14 flex justify-center items-center border border-[#113768] rounded-full bg-transparent hover:bg-[#113768] hover:text-white transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
>

View File

@ -58,7 +58,7 @@ export default function RegisterPage() {
}
try {
await register(form, setToken);
router.push("/tabs/home");
router.push("/home");
} catch (error: any) {
console.error("Error:", error.response || error.message);
if (error.response?.detail) {
@ -89,57 +89,52 @@ export default function RegisterPage() {
<FormField
title="Full name"
value={form.name}
handleChangeText={(e) =>
setForm({ ...form, name: e.target.value })
}
handleChangeText={(value) => setForm({ ...form, name: value })}
/>
<FormField
title="Institution"
placeholder="Enter a institution"
value={form.institution}
handleChangeText={(e) =>
setForm({ ...form, institution: e.target.value })
handleChangeText={(value) =>
setForm({ ...form, institution: value })
}
/>
<FormField
title="SSC Roll No."
placeholder="Enter your SSC Roll No."
value={form.sscRoll}
handleChangeText={(e) =>
setForm({ ...form, sscRoll: e.target.value })
handleChangeText={(value) =>
setForm({ ...form, sscRoll: value })
}
/>
<FormField
title="HSC Roll No."
placeholder="Enter your HSC Roll No."
value={form.hscRoll}
handleChangeText={(e) =>
setForm({ ...form, hscRoll: e.target.value })
handleChangeText={(value) =>
setForm({ ...form, hscRoll: value })
}
/>
<FormField
title="Email Address"
placeholder="Enter your email address..."
value={form.email}
handleChangeText={(e) =>
setForm({ ...form, email: e.target.value })
}
handleChangeText={(value) => setForm({ ...form, email: value })}
/>
<FormField
title="Phone Number"
placeholder="Enter your phone number.."
value={form.phone}
handleChangeText={(e) =>
setForm({ ...form, phone: e.target.value })
}
handleChangeText={(value) => setForm({ ...form, phone: value })}
/>
<FormField
title="Password"
placeholder="Enter a password"
value={form.password}
handleChangeText={(e) =>
setForm({ ...form, password: e.target.value })
handleChangeText={(value) =>
setForm({ ...form, password: value })
}
placeholder={undefined}
/>
</div>

View File

@ -1,7 +1,87 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
import React, { useState, useEffect } from "react";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { Bookmark, BookmarkCheck, ListFilter, MoveLeft } from "lucide-react";
import { useRouter } from "next/navigation";
interface Question {
id: number;
question: string;
options: Record<string, string>;
}
interface QuestionItemProps {
question: Question;
}
const QuestionItem = ({ question }: QuestionItemProps) => {
const [bookmark, setBookmark] = useState(true);
return (
<div className="border border-[#8abdff]/50 rounded-2xl p-4 flex flex-col gap-7">
<h3 className="text-xl font-medium">
{question.id + 1}. {question.question}
</h3>
<div className="flex justify-between items-center">
<div></div>
<button onClick={() => setBookmark(!bookmark)}>
{bookmark ? (
<BookmarkCheck size={25} color="#113768" />
) : (
<Bookmark size={25} color="#113768" />
)}
</button>
</div>
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => {
return (
<div key={key} className="flex items-center gap-3">
<span className="px-2 py-1 flex items-center rounded-full border font-medium text-sm">
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
</div>
);
})}
</div>
</div>
);
};
export default page;
const BookmarkPage = () => {
const router = useRouter();
const [questions, setQuestions] = useState();
useEffect(() => {
fetch("/data/bookmark.json")
.then((res) => res.json())
.then((data) => setQuestions(data))
.catch((err) => console.error("Error loading questions: ", err));
}, []);
return (
<BackgroundWrapper>
<section className="min-h-screen flex flex-col justify-between">
<div className="flex-1 mb-20">
<div className="mx-8 mt-10 pb-6 space-y-6">
<button onClick={() => router.push("/home")}>
<MoveLeft size={30} color="#113768" />
</button>
<h1 className="text-4xl font-semibold text-[#113768]">Bookmark</h1>
<div className="flex justify-between">
<h3 className="text-xl font-semibold text-[#113768]">Recent</h3>
<button>
<ListFilter size={24} color="#113768" />
</button>
</div>
{questions?.map((question) => (
<QuestionItem key={question.id} question={question} />
))}
</div>
</div>
</section>
</BackgroundWrapper>
);
};
export default BookmarkPage;

View File

@ -1,23 +1,29 @@
"use client";
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, ReactNode } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import Header from "@/components/Header";
import SlidingGallery from "@/components/SlidingGallery";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import DestructibleAlert from "@/components/DestructibleAlert";
import { ChevronRight } from "lucide-react"; // Using Lucide React for icons
import { ChevronRight } from "lucide-react";
import styles from "@/css/Home.module.css";
import { API_URL } from "@/lib/auth";
import { Avatar } from "@/components/ui/avatar";
import { getLinkedViews } from "@/lib/gallery-views";
import { getTopThree } from "@/lib/leaderboard";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api";
interface LinkedView {
id: string;
content: ReactNode;
}
const page = () => {
const profileImg = "/images/static/avatar.jpg";
const router = useRouter();
const [boardData, setBoardData] = useState([]);
const [boardError, setBoardError] = useState(null);
const [linkedViews, setLinkedViews] = useState<LinkedView[]>();
const performanceData = [
{ label: "Mock Test", progress: 20 },
@ -30,7 +36,6 @@ const page = () => {
{ label: "Chemistry", progress: 57 },
];
// Fetch function for leaderboard data
useEffect(() => {
let isMounted = true;
async function fetchBoardData() {
@ -45,32 +50,22 @@ const page = () => {
if (isMounted) setBoardError(error.message || "An error occurred");
}
}
const fetchedLinkedViews = getLinkedViews();
setLinkedViews(fetchedLinkedViews);
fetchBoardData();
return () => {
isMounted = false;
};
}, []);
const getTopThree = (boardData) => {
if (!boardData || boardData.length === 0) return [];
return boardData
.slice()
.sort((a, b) => b.points - a.points)
.slice(0, 3)
.map((player, index) => ({
...player,
rank: index + 1,
height: index === 0 ? 250 : index === 1 ? 200 : 170,
}));
};
return (
<BackgroundWrapper>
<div className={styles.container}>
<Header displayTabTitle={null} displayUser image={profileImg} />
<Header displayUser />
<div className={styles.scrollContainer}>
<div className={styles.contentWrapper}>
<SlidingGallery />
<SlidingGallery views={linkedViews} height="23vh" />
<div className={styles.mainContent}>
{/* Categories Section */}
<div>
@ -92,8 +87,8 @@ const page = () => {
<Image
src="/images/icons/topic-test.png"
alt="Topic Test"
width={70}
height={70}
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
Topic Test
@ -106,8 +101,8 @@ const page = () => {
<Image
src="/images/icons/mock-test.png"
alt="Mock Test"
width={70}
height={70}
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
Mock Test
@ -122,8 +117,8 @@ const page = () => {
<Image
src="/images/icons/past-paper.png"
alt="Past Papers"
width={62}
height={62}
width={68}
height={68}
/>
<span className={styles.categoryButtonText}>
Past Papers
@ -136,8 +131,8 @@ const page = () => {
<Image
src="/images/icons/subject-test.png"
alt="Subject Test"
width={70}
height={70}
width={80}
height={80}
/>
<span className={styles.categoryButtonText}>
Subject Test
@ -166,13 +161,7 @@ const page = () => {
<div key={idx} className={styles.topThreeItem}>
<div className={styles.studentInfo}>
<span className={styles.rank}>{student.rank}</span>
<Image
src="/images/static/avatar.jpg"
alt="Avatar"
width={20}
height={20}
className={styles.avatar}
/>
<Avatar className="bg-slate-300 w-4 h-4 rounded-full"></Avatar>
<span className={styles.studentName}>
{student.name}
</span>

View File

@ -5,11 +5,13 @@ import Link from "next/link";
import { ReactNode } from "react";
import { usePathname } from "next/navigation";
import clsx from "clsx";
import { House, LayoutGrid, Bookmark, Settings } from "lucide-react";
const tabs = [
{ name: "Home", href: "/tabs/home" },
{ name: "Profile", href: "/tabs/profile" },
{ name: "Leaderboard", href: "/tabs/leaderboard" },
{ name: "Home", href: "/home", component: <House size={30} /> },
{ name: "Unit", href: "/unit", component: <LayoutGrid size={30} /> },
{ name: "Bookmark", href: "/bookmark", component: <Bookmark size={30} /> },
{ name: "Settings", href: "/settings", component: <Settings size={30} /> },
];
export default function TabsLayout({ children }: { children: ReactNode }) {
@ -19,7 +21,7 @@ export default function TabsLayout({ children }: { children: ReactNode }) {
<div className="min-h-screen flex flex-col">
<main className="flex-1">{children}</main>
<nav className="flex justify-around border-t p-4 bg-white">
<nav className="h-[70px] w-full flex justify-around items-center border-t border-t-neutral-400 p-4 rounded-t-4xl bg-white fixed bottom-0">
{tabs.map((tab) => (
<Link
key={tab.name}
@ -29,7 +31,7 @@ export default function TabsLayout({ children }: { children: ReactNode }) {
pathname === tab.href ? "text-blue-600" : "text-gray-500"
)}
>
{tab.name}
{tab.component}
</Link>
))}
</nav>

View File

@ -0,0 +1,187 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { API_URL, getToken } from "@/lib/auth";
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
import { UserData } from "@/types/auth";
import React, { useEffect, useState } from "react";
const LeaderboardPage = () => {
const [boardError, setBoardError] = useState<string | null>(null);
const [boardData, setBoardData] = useState<BoardData[]>([]);
const [userData, setUserData] = useState<UserData>({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
email: "",
phone: "",
});
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) throw new Error("User is not authenticated");
const response = await fetch(`${API_URL}/me`, {
method: "get",
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error("Failed to fetch user data");
const fetchedUserData = await response.json();
setLoading(false);
setUserData(fetchedUserData);
} catch (error) {
console.error(error);
setUserData(undefined);
}
}
async function fetchBoardData() {
try {
const boardResponse = await fetch(`${API_URL}/leaderboard`, {
method: "GET",
});
if (!boardResponse.ok) {
throw new Error("Failed to fetch leaderboard data");
}
const fetchedBoardData = await boardResponse.json();
if (Array.isArray(fetchedBoardData) && fetchedBoardData.length > 0) {
setBoardData(fetchedBoardData);
} else {
setBoardError("No leaderboard data available.");
setBoardData([]);
}
} catch (error) {
console.error(error);
setBoardError("Something went wrong. Please try again.");
setBoardData([]);
}
}
fetchUser();
fetchBoardData();
}, []);
const getTopThree = (boardData: BoardData[]) => {
if (!boardData || !Array.isArray(boardData)) return [];
const sortedData = boardData
.filter((player) => player?.points !== undefined) // Ensure `points` exists
.sort((a, b) => b.points - a.points);
const topThree = sortedData.slice(0, 3).map((player, index) => ({
...player,
rank: index + 1,
height: index === 0 ? 280 : index === 1 ? 250 : 220,
}));
return [topThree[1], topThree[0], topThree[2]].filter(Boolean); // Handle missing players
};
const getUserData = (boardData: BoardData[], name: string) => {
if (!boardData || !Array.isArray(boardData)) return [];
const sortedData = boardData
.filter((player) => player?.name && player?.points !== undefined)
.sort((a, b) => b.points - a.points);
const result = sortedData.find((player) => player.name === name);
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
};
return (
<BackgroundWrapper>
<section>
<Header displayTabTitle={"Leaderboard"} />
<section className="flex flex-col mx-10 pt-10 space-y-4">
<section className="flex justify-evenly items-end">
{getTopThree(boardData).map((student, idx) =>
student ? (
<div
key={idx}
className="w-[100px] flex flex-col bg-[#113768] rounded-t-xl items-center justify-start pt-4 space-y-3"
style={{ height: student.height }}
>
<h3 className="font-bold text-xl text-white">
{student.rank}
</h3>
<Avatar className="bg-slate-300 w-12 h-12">
<AvatarFallback className="text-xl font-semibold">
{student.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<p className="font-bold text-md text-center text-white">
{student.name}
</p>
<p className="text-sm text-white">({student.points}pt)</p>
</div>
) : null
)}
</section>
<div className="w-full border-[0.5px] border-[#c5dbf8] bg-[#c5dbf8]"></div>
<section className="border-[1px] border-[#c0dafc] w-full rounded-3xl p-6 space-y-4 mb-20">
<section>
{getUserData(boardData, userData.name).map((user, idx) => (
<div
key={idx}
className="flex bg-[#113768] rounded-[8] py-2 px-4 justify-between items-center"
>
<div className=" flex gap-3 items-center">
<h2 className="font-medium text-sm text-white">
{user.rank}
</h2>
<Avatar className="bg-slate-300 w-6 h-6">
<AvatarFallback className="text-sm font-semibold">
{user.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<h3 className="font-medium text-sm text-white">You</h3>
</div>
<p className="font-medium text-white/70 text-sm">
{user.points}pt
</p>
</div>
))}
</section>
<div className="w-full border-[0.5px] border-[#c5dbf8] bg-[#c5dbf8]"></div>
<section className="space-y-4">
{getLeaderboard(boardData)
.slice(0, 10)
.map((user, idx) => (
<div
key={idx}
className="flex border-2 border-[#c5dbf8] rounded-[8] py-2 px-4 justify-between items-center"
>
<div className="flex gap-3 items-center">
<h2 className="font-medium text-sm">{idx + 1}</h2>
<Avatar className="bg-slate-300 w-6 h-6">
<AvatarFallback className="text-sm font-semibold">
{user.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<h3 className="font-medium text-sm">
{user.name.split(" ").slice(0, 2).join(" ")}
</h3>
</div>
<p className="font-medium text-[#000]/40 text-sm">
{user.points}pt
</p>
</div>
))}
</section>
</section>
</section>
</section>
</BackgroundWrapper>
);
};
export default LeaderboardPage;

126
app/(tabs)/paper/page.tsx Normal file
View File

@ -0,0 +1,126 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
interface Mock {
id: string;
title: string;
rating: number;
}
export default function PaperScreen() {
const router = useRouter();
const searchParams = useSearchParams();
const name = searchParams.get("name") || "";
const [questions, setQuestions] = useState<Mock[] | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [componentKey, setComponentKey] = useState<number>(0);
async function fetchMocks() {
try {
const questionResponse = await fetch(`${API_URL}/mocks`, {
method: "GET",
});
const fetchedQuestionData: Mock[] = await questionResponse.json();
setQuestions(fetchedQuestionData);
} catch (error) {
setErrorMsg(error instanceof Error ? error.message : "An error occurred");
}
}
useEffect(() => {
if (name) {
fetchMocks();
}
}, [name]);
const onRefresh = async () => {
setRefreshing(true);
await fetchMocks();
setComponentKey((prevKey) => prevKey + 1);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
if (errorMsg) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<Header displayTabTitle={name} />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<DestructibleAlert text={errorMsg} extraStyles="" />
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" /> */}
</div>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle={name} />
<div className="mx-10 pt-10 overflow-y-auto">
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
{questions ? (
questions.map((mock) => (
<div key={mock.id}>
<button
onClick={() =>
router.push(
`/exam/pretest?unitname=${name}&id=${mock.id}&title=${mock.title}&rating=${mock.rating}`
)
}
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 gap-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{mock.title}</h3>
<p className="text-md font-normal">
Rating: {mock.rating} / 10
</p>
</button>
</div>
))
) : (
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="p-2 bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50 rounded-full"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
}

View File

@ -1,7 +1,122 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
import ProfileManager from "@/components/ProfileManager";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { getToken, API_URL } from "@/lib/auth";
import { ChevronLeft, Edit2, Lock, Save } from "lucide-react";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { UserData } from "@/types/auth";
const ProfilePage = () => {
const router = useRouter();
const [userData, setUserData] = useState<UserData | undefined>();
const [editStatus, setEditStatus] = useState(false);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) return;
const response = await fetch(`${API_URL}/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const fetchedUserData = await response.json();
setUserData(fetchedUserData);
}
} catch (error) {
console.error("Error fetching user data: ", error);
}
}
fetchUser();
}, []);
const handleSave = async () => {
// try {
// const token = await getToken();
// if (!token || !userData) return;
// const response = await fetch(`${API_URL}/profile/edit`, {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// Authorization: `Bearer ${token}`,
// },
// body: JSON.stringify(userData),
// });
// if (response.ok) {
// setEditStatus(false);
// } else {
// console.error("Failed to save profile");
// }
// } catch (error) {
// console.error("Error saving profile:", error);
// }
console.log("Updated user data:", userData);
setEditStatus(false);
};
return (
<section className="min-h-screen mb-32">
<div className="h-48 bg-gradient-to-b from-[#113768] to-white w-full">
<button
onClick={() => router.push("/settings")}
className="absolute top-10 left-6 p-2 bg-black/30 rounded-full"
>
<ChevronLeft size={30} color="white" />
</button>
</div>
<div className="relative mx-10">
<Avatar className="bg-[#113768] w-32 h-32 absolute -top-20 left-1/2 transform -translate-x-1/2">
<AvatarFallback className="text-3xl text-white">
{userData?.name ? userData.name.charAt(0).toUpperCase() : ""}
</AvatarFallback>
</Avatar>
<div className="pt-14 space-y-8">
<ProfileManager
userData={userData}
edit={editStatus}
setUserData={setUserData}
/>
<button
onClick={() => {
if (editStatus) handleSave();
else setEditStatus(true);
}}
className={`p-3 ${
editStatus ? "bg-green-500" : "bg-[#113768]"
} w-full flex gap-3 justify-center items-center rounded-full`}
>
{editStatus ? (
<Save size={20} color="white" />
) : (
<Edit2 size={20} color="white" />
)}
<p className="text-white">
{editStatus ? "Save Changes" : "Edit Profile"}
</p>
</button>
<button className="p-3 bg-[#113768] w-full flex gap-3 justify-center items-center rounded-full">
<Lock size={20} color="white" />
<p className="text-white">Change Password</p>
</button>
</div>
</div>
</section>
);
};
export default page;
export default ProfilePage;

View File

@ -0,0 +1,189 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { API_URL, getToken } from "@/lib/auth";
import {
Bookmark,
ChartColumn,
ChevronRight,
Clock4,
CreditCard,
Crown,
Globe,
LogOut,
MapPin,
MoveLeft,
Trash2,
UserCircle2,
} from "lucide-react";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
const SettingsPage = () => {
const router = useRouter();
const [userData, setUserData] = useState(null);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) return;
const response = await fetch(`${API_URL}/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const fetchedUserData = await response.json();
setUserData(fetchedUserData);
}
} catch (error) {
console.error("Error fetching user data: ", error);
}
}
fetchUser();
}, []);
return (
<BackgroundWrapper>
<section className="min-h-screen flex flex-col justify-between">
<div className="flex-1 mb-20">
<div className="mx-8 mt-10 pb-6 space-y-6">
<section className="flex justify-between">
<button onClick={() => router.push("/home")}>
<MoveLeft size={30} color="#113768" />
</button>
<h3 className="text-lg font-semibold text-[#113768]">Settings</h3>
<button onClick={() => router.push("/profile")}>
<UserCircle2 size={30} color="#113768" />
</button>
</section>
<section className="flex flex-col gap-4">
<div className="flex gap-4 items-center">
<Avatar className="bg-[#113768] w-20 h-20">
<AvatarFallback className="text-3xl text-white">
{userData?.name
? userData.name.charAt(0).toUpperCase()
: ""}
</AvatarFallback>
</Avatar>
<div className="flex flex-col items-start">
<h1 className="font-semibold text-2xl">{userData?.name}</h1>
<h3 className=" text-md">{userData?.email}</h3>
</div>
</div>
</section>
<section className="flex flex-col gap-8">
<button
onClick={() => router.push("/profile")}
className="flex justify-between"
>
<div className="flex items-center gap-4">
<UserCircle2 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Your profile
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</button>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Bookmark size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Bookmarks
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<CreditCard size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Payments
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Globe size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Languages
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<MapPin size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Location
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Crown size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Subscription
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<ChartColumn size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Performance
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Trash2 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Clear Cache
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Clock4 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Clear History
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<LogOut size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Log out
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<p className="text-center text-[#113768]/50 font-medium">
ExamJam | Version 1.0
</p>
</section>
</div>
</div>
</section>
</BackgroundWrapper>
);
};
export default SettingsPage;

View File

@ -33,7 +33,7 @@ const Unit = () => {
/>
<div className="flex-1">
<div className="overflow-y-auto">
<div className="border border-blue-200 gap-4 rounded-3xl p-6 mx-10 mt-10">
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
{units ? (
units.map((unit) => (
<button

View File

@ -1,7 +1,366 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
};
import React, { useEffect, useState, useCallback, useMemo } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useTimer } from "@/context/TimerContext";
import { useExam } from "@/context/ExamContext";
import { API_URL, getToken } from "@/lib/auth";
import Header from "@/components/Header";
import { Bookmark, BookmarkCheck } from "lucide-react";
import { useModal } from "@/context/ModalContext";
import Modal from "@/components/ExamModal";
import { Question } from "@/types/exam";
import QuestionItem from "@/components/QuestionItem";
export default page;
// Types
// interface Question {
// id: number;
// question: string;
// options: Record<string, string>;
// }
// interface QuestionItemProps {
// question: Question;
// selectedAnswer?: string;
// handleSelect: (questionId: number, option: string) => void;
// }
// const QuestionItem = React.memo<QuestionItemProps>(
// ({ question, selectedAnswer, handleSelect }) => {
// const [bookmark, setBookmark] = useState(false);
// return (
// <div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
// <h3 className="text-xl font-medium mb-[20px]">
// {question.id}. {question.question}
// </h3>
// <div className="flex justify-between items-center">
// <div></div>
// <button onClick={() => setBookmark(!bookmark)}>
// {bookmark ? (
// <BookmarkCheck size={25} color="#113768" />
// ) : (
// <Bookmark size={25} color="#113768" />
// )}
// </button>
// </div>
// <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"
// onClick={() => handleSelect(question.id, key)}
// >
// <span
// className={`flex items-center rounded-full border px-1.5 ${
// selectedAnswer === key
// ? "text-white bg-[#113768] border-[#113768]"
// : ""
// }`}
// >
// {key.toUpperCase()}
// </span>
// <span className="option-description">{value}</span>
// </button>
// ))}
// </div>
// </div>
// );
// }
// );
// QuestionItem.displayName = "QuestionItem";
export default function ExamPage() {
// All hooks at the top - no conditional calls
const router = useRouter();
const { id } = useParams();
const time = useSearchParams().get("time");
const { isOpen, close } = useModal();
const { setInitialTime, stopTimer } = useTimer();
const {
currentAttempt,
setAnswer,
getAnswer,
submitExam: submitExamContext,
setApiResponse,
isExamStarted,
isExamCompleted,
isHydrated,
isInitialized,
currentExam,
} = useExam();
// State management
const [questions, setQuestions] = useState<Question[] | null>(null);
const [loading, setLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [submissionLoading, setSubmissionLoading] = useState(false);
const [componentState, setComponentState] = useState<
"loading" | "redirecting" | "ready"
>("loading");
// Combined initialization effect
useEffect(() => {
let mounted = true;
const initializeComponent = async () => {
// Wait for hydration and initialization
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);
}
};
const showExitDialog = useCallback(() => {
if (window.confirm("Are you sure you want to quit the exam?")) {
stopTimer();
router.push("/unit");
}
}, [stopTimer, router]);
useEffect(() => {
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 (
<div className="min-h-screen bg-gray-50 flex 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>
<p className="text-lg font-medium text-gray-900">Submitting...</p>
</div>
</div>
);
}
// Render the main exam interface
return (
<div className="min-h-screen bg-gray-50">
<Header
examDuration={time}
displayTabTitle={null}
image={undefined}
displayUser={undefined}
displaySubject={undefined}
/>
<Modal open={isOpen} onClose={close} title={currentExam?.title}>
{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 -
currentAttempt?.answers.length}
</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 (
<div
key={q.id ?? idx}
className={`h-16 w-16 rounded-full flex items-center justify-center
text-2xl
${
answered
? "bg-[#0E2C53] text-white font-semibold"
: "bg-[#E9EDF1] text-black font-normal"
}`}
>
{idx + 1}
</div>
);
})}
</section>
</div>
) : (
<p>No attempt data.</p>
)}
</Modal>
<div className="container mx-auto px-6 py-8">
{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>
</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>
);
}

View File

@ -1,7 +1,194 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
};
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
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";
import { Exam } from "@/types/exam";
export default page;
interface Metadata {
metadata: {
quantity: number;
type: string;
duration: number;
marking: string;
};
}
export default function PretestPage() {
const router = useRouter();
const searchParams = useSearchParams();
const [examData, setExamData] = useState<Exam>();
const { startExam, setCurrentExam } = useExam();
// Get params from URL search params
const name = searchParams.get("name") || "";
const id = searchParams.get("id") || "";
const title = searchParams.get("title") || "";
const rating = searchParams.get("rating") || "";
const [metadata, setMetadata] = useState<Metadata | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
async function fetchQuestions() {
if (!id) return;
try {
setLoading(true);
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
method: "GET",
});
if (!questionResponse.ok) {
throw new Error("Failed to fetch questions");
}
const data = await questionResponse.json();
const fetchedMetadata: Metadata = data;
setExamData(data);
setMetadata(fetchedMetadata);
} catch (error) {
console.error(error);
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setLoading(false);
}
}
useEffect(() => {
if (id) {
fetchQuestions();
}
}, [id]);
if (error) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<div className="mx-10 mt-10">
<button onClick={() => router.push("/unit")} className="mb-4">
<ArrowLeft size={30} color="black" />
</button>
<DestructibleAlert text={error} extraStyles="" />
</div>
{/* <CustomBackHandler fallbackRoute="paper" /> */}
</div>
</BackgroundWrapper>
);
}
function handleStartExam() {
setCurrentExam(examData);
startExam(examData); // Pass examData directly
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
}
return (
<BackgroundWrapper>
<div className="min-h-screen flex flex-col justify-between">
<div className="flex-1 overflow-y-auto mb-20">
{metadata ? (
<div className="mx-10 mt-10 gap-6 pb-6 space-y-6">
<button onClick={() => router.back()}>
<ArrowLeft size={30} color="black" />
</button>
<h1 className="text-4xl font-semibold text-[#113768]">{title}</h1>
<p className="text-xl font-medium text-[#113768]">
Rating: {rating} / 10
</p>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-8 py-7 px-5 space-y-8">
<div className="flex gap-5 items-center">
<HelpCircle size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.quantity}
</p>
<p className="font-normal text-lg">
{metadata.metadata.type}
</p>
</div>
</div>
<div className="flex gap-5 items-center">
<Clock size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.duration} mins
</p>
<p className="font-normal text-lg">Time Taken</p>
</div>
</div>
<div className="flex gap-5 items-center">
<XCircle size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.marking}
</p>
<p className="font-normal text-lg">
From each wrong answer
</p>
</div>
</div>
</div>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-4 py-7 px-5 space-y-4">
<h2 className="text-xl font-bold">Ready yourself!</h2>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
You must complete this test in one session - make sure your
internet connection is reliable.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
There is negative marking for the wrong answer.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
The more you answer correctly, the better chance you have of
winning a badge.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
You can retake this test however many times you want. But,
you will earn points only once.
</p>
</div>
</div>
</div>
) : (
<div className="mt-60 flex flex-col items-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<button
onClick={async () => handleStartExam()}
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
>
Start Test
</button>
{/* <CustomBackHandler fallbackRoute="paper" /> */}
</div>
</BackgroundWrapper>
);
}

View File

@ -1,7 +1,122 @@
"use client";
import { useRouter } from "next/navigation";
import { useExam, useExamResults } from "@/context/ExamContext";
import { useEffect, useState } from "react";
import React from "react";
import { ArrowLeft } from "lucide-react";
import SlidingGallery from "@/components/SlidingGallery";
import QuestionItem from "@/components/QuestionItem";
import { getResultViews } from "@/lib/gallery-views";
const page = () => {
return <div>page</div>;
};
export default function ResultsPage() {
const router = useRouter();
const {
clearExam,
isExamCompleted,
getApiResponse,
currentAttempt,
isHydrated,
} = useExam();
export default page;
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Wait for hydration first
if (!isHydrated) return;
// Check if exam is completed, redirect if not
if (!isExamCompleted() || !currentAttempt) {
router.push("/unit");
return;
}
// If we have exam results, we're ready to render
if (currentAttempt?.answers) {
setIsLoading(false);
}
}, [isExamCompleted, currentAttempt, isHydrated, router]);
const handleBackToHome = () => {
clearExam();
router.push("/unit");
};
// Show loading screen while initializing or if no exam results
if (isLoading || !currentAttempt) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="mt-60 flex flex-col items-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
</div>
</div>
);
}
const apiResponse = getApiResponse();
const timeTaken =
currentAttempt.endTime && currentAttempt.startTime
? Math.round(
(currentAttempt.endTime.getTime() -
currentAttempt.startTime.getTime()) /
1000 /
60
)
: 0;
const views = getResultViews(currentAttempt);
// Get score-based message
const getScoreMessage = () => {
if (!currentAttempt.score || currentAttempt.score < 30)
return "Try harder!";
if (currentAttempt.score < 70) return "Getting Better";
return "You did great!";
};
return (
<div className="min-h-screen bg-white">
<button className="p-10" onClick={handleBackToHome}>
<ArrowLeft size={30} color="black" />
</button>
<div className="bg-white rounded-lg shadow-lg px-10 pb-20">
<h1 className="text-2xl font-bold text-[#113768] mb-4 text-center">
{getScoreMessage()}
</h1>
{/* Score Display */}
<SlidingGallery className="my-8" views={views} height="170px" />
{apiResponse?.questions && (
<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}
selectedAnswer={currentAttempt.answers[question.id - 1]}
mode="result"
/>
))}
</div>
</div>
)}
</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>
);
}

View File

@ -1,8 +1,8 @@
import type { Metadata } from "next";
import { Montserrat } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/context/AuthContext";
import { TimerProvider } from "@/context/TimerContext";
import { Providers } from "./providers";
const montserrat = Montserrat({
subsets: ["latin"],
@ -13,7 +13,7 @@ const montserrat = Montserrat({
export const metadata: Metadata = {
title: "ExamJam",
description: "Your exam preparation platform",
description: "The best place to prepare for your exams!",
};
export default function RootLayout({
@ -24,9 +24,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>
);

View File

@ -3,34 +3,10 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { useState, useEffect } from "react";
import BackgroundWrapper from "@/components/BackgroundWrapper";
export default function Home() {
const router = useRouter();
const [windowDimensions, setWindowDimensions] = useState({
width: 0,
height: 0,
});
useEffect(() => {
function handleResize() {
setWindowDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Set initial dimensions
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const handleLogin = () => {
router.push("/login");
};
return (
<BackgroundWrapper>
@ -62,7 +38,7 @@ export default function Home() {
{/* Action Buttons */}
<div className="flex flex-col gap-4">
<button
onClick={handleLogin}
onClick={() => router.replace("/login")}
className="w-full h-[60px] flex justify-center items-center border border-[#113768] rounded-full bg-transparent hover:bg-[#113768] hover:text-white transition-colors duration-200"
>
<span

18
app/providers.tsx Normal file
View File

@ -0,0 +1,18 @@
"use client";
import { ExamProvider } from "@/context/ExamContext";
import { TimerProvider } from "@/context/TimerContext";
import { AuthProvider } from "@/context/AuthContext";
import { ModalProvider } from "@/context/ModalContext";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<TimerProvider>
<AuthProvider>
<ExamProvider>
<ModalProvider>{children}</ModalProvider>
</ExamProvider>
</AuthProvider>
</TimerProvider>
);
}

BIN
bun.lockb

Binary file not shown.

21
components.json Normal file
View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

91
components/ExamModal.tsx Normal file
View File

@ -0,0 +1,91 @@
"use client";
import { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
interface ModalProps {
/** Control visibility */
open: boolean;
/** Callback for both explicit and implicit close actions */
onClose: () => void;
/** Optional heading */
title?: string;
children: React.ReactNode;
/** Center horizontally and vertically? (default true) */
center?: boolean;
}
export default function Modal({
open,
onClose,
title,
children,
center = true,
}: ModalProps) {
const dialogRef = useRef<HTMLDialogElement | null>(null);
// Open / close imperatively to keep <dialog> in sync with prop
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
// Close on native <dialog> close event
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
const handleClose = () => onClose();
dialog.addEventListener("close", handleClose);
return () => dialog.removeEventListener("close", handleClose);
}, [onClose]);
// ESC -> close (for browsers without builtin <dialog> handling)
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
if (typeof window === "undefined") return null; // SSR guard
return createPortal(
<dialog
ref={dialogRef}
className={`fixed top-0 right-0 h-[110vh] z-50 w-[87vw]
ml-auto transform-none /* 1 & 2 */
backdrop:bg-black/20
transition-[opacity,transform] duration-300
${
open
? "opacity-100 translate-x-0 translate-y-0"
: "opacity-0 translate-x-4"
}
${center ? "rounded-l-xl" : ""}
`}
>
{/* Card */}
<div className="bg-white rounded-xl overflow-hidden pb-10">
{title && (
<header className="flex items-center justify-between px-6 pt-10 pb-4 dark:border-zinc-700">
<h2 className="text-2xl font-semibold">{title}</h2>
<button
aria-label="Close"
onClick={onClose}
className="p-1 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full"
>
<X className="h-5 w-5" />
</button>
</header>
)}
<section className="px-6 ">{children}</section>
</div>
</dialog>,
document.body
);
}

View File

@ -1,34 +1,35 @@
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { ChevronLeft, Layers } from "lucide-react";
import { useTimer } from "@/context/TimerContext";
import styles from "@/css/Header.module.css";
import { useExam } from "@/context/ExamContext";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useModal } from "@/context/ModalContext";
import { API_URL, getToken } from "@/lib/auth";
import { UserData } from "@/types/auth";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api";
// You'll need to implement getToken for Next.js - could use cookies, localStorage, etc.
const getToken = async () => {
// Replace with your token retrieval logic
if (typeof window !== "undefined") {
return localStorage.getItem("token") || sessionStorage.getItem("token");
}
return null;
};
interface HeaderProps {
displayUser?: boolean;
displaySubject?: string;
displayTabTitle?: string;
examDuration?: string;
}
const Header = ({
image,
displayUser,
displaySubject,
displayTabTitle,
examDuration,
}) => {
}: HeaderProps) => {
const router = useRouter();
const { open } = useModal();
const { clearExam } = useExam();
const [totalSeconds, setTotalSeconds] = useState(
examDuration ? parseInt(examDuration) * 60 : 0
);
const { timeRemaining, stopTimer } = useTimer();
const [userData, setUserData] = useState(null);
const [userData, setUserData] = useState<UserData>();
useEffect(() => {
if (!examDuration) return;
@ -84,6 +85,7 @@ const Header = ({
if (stopTimer) {
stopTimer();
}
clearExam();
router.push("/unit");
}
};
@ -96,36 +98,32 @@ const Header = ({
<header className={styles.header}>
{displayUser && (
<div className={styles.profile}>
{image && (
<Image
src={image}
alt="Profile"
width={40}
height={40}
className={styles.profileImg}
/>
)}
<Avatar className="bg-gray-200 w-10 h-10">
<AvatarFallback className=" text-lg">
{userData?.name ? userData.name.charAt(0).toUpperCase() : ""}
</AvatarFallback>
</Avatar>
<span className={styles.text}>
Hello {userData?.name ? userData.name.split(" ")[0] : ""}
Hello, {userData?.name ? userData.name.split(" ")[0] : ""}
</span>
</div>
)}
{displaySubject && (
<div className={styles.profile}>
<button onClick={handleBackClick} className={styles.iconButton}>
<ChevronLeft size={24} color="white" />
</button>
<span className={styles.text}>{displaySubject}</span>
</div>
)}
{displayTabTitle && (
<div className={styles.profile}>
<button onClick={handleBackClick} className={styles.iconButton}>
<ChevronLeft size={24} color="white" />
</button>
<span className={styles.text}>{displayTabTitle}</span>
</div>
)}
{displaySubject && (
<div className={styles.profile}>
<span className={styles.text}>{displaySubject}</span>
</div>
)}
{examDuration && (
<div className={styles.examHeader}>
<button onClick={showExitDialog} className={styles.iconButton}>
@ -145,7 +143,7 @@ const Header = ({
</span>
<span className={styles.timeLabel}>Mins</span>
</div>
<div className={styles.timeUnit}>
<div className={styles.timeUnit} style={{ borderRight: "none" }}>
<span className={styles.timeValue}>
{String(seconds).padStart(2, "0")}
</span>
@ -154,8 +152,7 @@ const Header = ({
</div>
<button
disabled
onClick={() => router.push("/exam/modal")}
onClick={open}
className={`${styles.iconButton} ${styles.disabled}`}
>
<Layers size={30} color="white" />

View File

@ -0,0 +1,136 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface UserData {
name: string;
institution: string;
sscRoll: string;
hscRoll: string;
email: string;
phone: string;
}
interface ProfileManagerProps {
userData: UserData | undefined;
edit: boolean;
setUserData: React.Dispatch<React.SetStateAction<UserData | undefined>>;
}
export default function ProfileManager({
userData,
edit,
setUserData,
}: ProfileManagerProps) {
if (!userData) return null;
const handleChange = (field: keyof UserData, value: string) => {
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
};
return (
<div className="mx-auto">
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name" className="text-sm font-semibold text-gray-700">
Name
</Label>
<Input
id="name"
type="text"
value={userData.name}
onChange={(e) => handleChange("name", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="institution"
className="text-sm font-semibold text-gray-700"
>
Institution
</Label>
<Input
id="institution"
type="text"
value={userData.institution}
onChange={(e) => handleChange("institution", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="flex gap-4">
<div className="space-y-2 w-full">
<Label
htmlFor="sscRoll"
className="text-sm font-semibold text-gray-700"
>
SSC Roll
</Label>
<Input
id="sscRoll"
type="text"
value={userData.sscRoll}
onChange={(e) => handleChange("sscRoll", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2 w-full">
<Label
htmlFor="hscRoll"
className="text-sm font-semibold text-gray-700"
>
HSC Roll
</Label>
<Input
id="hscRoll"
type="text"
value={userData.hscRoll}
onChange={(e) => handleChange("hscRoll", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
<div className="space-y-2">
<Label
htmlFor="email"
className="text-sm font-semibold text-gray-700"
>
Email
</Label>
<Input
id="email"
type="email"
value={userData.email}
onChange={(e) => handleChange("email", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="phone"
className="text-sm font-semibold text-gray-700"
>
Phone
</Label>
<Input
id="phone"
type="tel"
value={userData.phone}
onChange={(e) => handleChange("phone", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
</div>
);
}

132
components/QuestionItem.tsx Normal file
View File

@ -0,0 +1,132 @@
import { Question } from "@/types/exam";
import { BookmarkCheck, Bookmark } from "lucide-react";
import React, { useState } from "react";
import { Badge } from "./ui/badge";
interface ResultItemProps {
mode: "result";
question: Question;
selectedAnswer: string | undefined;
}
interface ExamItemProps {
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, selectedAnswer } = props;
const isExam = props.mode === "exam";
return (
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
<h3 className="text-xl font-semibold ">
{question.id}. {question.question}
</h3>
{isExam && (
<div className="flex justify-between items-center mb-4">
<div></div>
<button onClick={() => setBookmark(!bookmark)}>
{bookmark ? (
<BookmarkCheck size={25} color="#113768" />
) : (
<Bookmark size={25} color="#113768" />
)}
</button>
</div>
)}
{isExam ? (
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => {
const isSelected = selectedAnswer === key;
return (
<button
key={key}
className="flex items-center gap-3"
onClick={
isExam
? () => props.handleSelect(question.id, key)
: undefined
}
disabled={!isExam}
>
<span
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>
);
})}
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex justify-between items-center">
<div></div>
{!selectedAnswer ? (
<Badge className="bg-yellow-500" variant="destructive">
Skipped
</Badge>
) : selectedAnswer.answer === 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?.answer;
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";
}
if (isSelected && !isCorrect) {
optionStyle += " bg-red-600 text-white border-red-600";
}
if (!isCorrect && !isSelected) {
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>
);
};
export default QuestionItem;

View File

@ -3,67 +3,171 @@ import Link from "next/link";
import Image from "next/image";
import styles from "../css/SlidingGallery.module.css";
const views = [
{
id: "1",
content: (
<Link
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
className={styles.link}
>
<div className={styles.facebook}>
<div className={styles.textView}>
<h3 className={styles.facebookOne}>Meet, Share, and Learn!</h3>
<p className={styles.facebookTwo}>Join Facebook Community</p>
</div>
<div className={styles.logoView}>
<Image
src="/images/static/facebook-logo.png"
alt="Facebook Logo"
width={120}
height={120}
/>
</div>
</div>
</Link>
),
},
];
interface SlidingGalleryProps {
views?: {
id: string;
content: React.ReactNode;
}[];
className?: string;
showPagination?: boolean;
autoScroll?: boolean;
autoScrollInterval?: number;
onSlideChange?: (currentIndex: number) => void;
height?: string | number;
}
const SlidingGallery = () => {
const SlidingGallery = ({
views = [],
className = "",
showPagination = true,
autoScroll = false,
autoScrollInterval = 5000,
onSlideChange = () => {},
height = "100vh",
}: SlidingGalleryProps) => {
const [activeIdx, setActiveIdx] = useState(0);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const scrollRef = useRef(null);
const galleryRef = useRef(null);
const autoScrollRef = useRef(null);
const handleScroll = (event) => {
const scrollLeft = event.target.scrollLeft;
const slideWidth = event.target.clientWidth;
const index = Math.round(scrollLeft / slideWidth);
setActiveIdx(index);
// Auto-scroll functionality
useEffect(() => {
if (autoScroll && views.length > 1) {
autoScrollRef.current = setInterval(() => {
setActiveIdx((prevIdx) => {
const nextIdx = (prevIdx + 1) % views.length;
goToSlide(nextIdx);
return nextIdx;
});
}, autoScrollInterval);
return () => {
if (autoScrollRef.current) {
clearInterval(autoScrollRef.current);
}
};
}
}, [autoScroll, autoScrollInterval, views.length]);
// Clear auto-scroll on user interaction
const handleUserInteraction = () => {
if (autoScrollRef.current) {
clearInterval(autoScrollRef.current);
}
};
useEffect(() => {
const updateDimensions = () => {
if (galleryRef.current) {
setDimensions({
width: galleryRef.current.clientWidth,
height: galleryRef.current.clientHeight,
});
}
};
// Initial dimension update
updateDimensions();
// Add resize listener
window.addEventListener("resize", updateDimensions);
// Cleanup
return () => window.removeEventListener("resize", updateDimensions);
}, []);
useEffect(() => {
// Recalculate active index when dimensions change
if (scrollRef.current && dimensions.width > 0) {
const scrollLeft = scrollRef.current.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
setActiveIdx(index);
}
}, [dimensions]);
const handleScroll = (event: { target: { scrollLeft: any } }) => {
handleUserInteraction();
const scrollLeft = event.target.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
if (index !== activeIdx) {
setActiveIdx(index);
onSlideChange(index);
}
};
const goToSlide = (index) => {
if (scrollRef.current) {
scrollRef.current.scrollTo({
left: index * dimensions.width,
behavior: "smooth",
});
}
};
const handleDotClick = (index) => {
handleUserInteraction();
goToSlide(index);
setActiveIdx(index);
onSlideChange(index);
};
// Early return if no views
if (!views || views.length === 0) {
return (
<div className={`${styles.gallery} ${className}`}>
<div className={styles.emptyState}>
<p>No content to display</p>
</div>
</div>
);
}
return (
<div className={styles.gallery}>
<div
className={`${styles.gallery} ${className}`}
ref={galleryRef}
style={{ height }}
>
<div
className={styles.scrollContainer}
ref={scrollRef}
onScroll={handleScroll}
style={{
width: "100%",
height: "100%",
}}
>
{views.map((item) => (
<div key={item.id} className={styles.slide}>
<div
key={item.id}
className={styles.slide}
style={{
width: dimensions.width,
height: "100%",
flexShrink: 0,
}}
>
{item.content}
</div>
))}
</div>
<div className={styles.pagination}>
{views.map((_, index) => (
<div
key={index}
className={`${styles.dot} ${
activeIdx === index ? styles.activeDot : styles.inactiveDot
}`}
/>
))}
</div>
{showPagination && views.length > 1 && (
<div className={styles.pagination}>
{views.map((_, index) => (
<div
key={index}
className={`${styles.dot} ${
activeIdx === index ? styles.activeDot : styles.inactiveDot
}`}
onClick={() => handleDotClick(index)}
style={{ cursor: "pointer" }}
/>
))}
</div>
)}
</div>
);
};

53
components/ui/avatar.tsx Normal file
View File

@ -0,0 +1,53 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

46
components/ui/badge.tsx Normal file
View File

@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

21
components/ui/input.tsx Normal file
View File

@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

24
components/ui/label.tsx Normal file
View File

@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@ -1,7 +1,7 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useRouter, usePathname } from "next/navigation";
interface AuthContextType {
token: string | null;
@ -47,6 +47,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
const [token, setTokenState] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const pathname = usePathname();
// Custom setToken function that also updates cookies
const setToken = (newToken: string | null) => {
@ -58,21 +59,22 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
useEffect(() => {
const initializeAuth = () => {
const storedToken = getCookie("authToken");
console.log("Current pathname:", pathname);
console.log("Stored token:", storedToken);
if (storedToken) {
setTokenState(storedToken);
// Only redirect if we're on login/register pages
if (
router.pathname === "/" ||
router.pathname === "/login" ||
router.pathname === "/register"
pathname === "/" ||
pathname === "/login" ||
pathname === "/register"
) {
console.log("Redirecting to /home");
router.replace("/home");
}
} else {
// Only redirect to login if we're on a protected page
const publicPages = ["/", "/login", "/register"];
if (!publicPages.includes(router.pathname)) {
if (!publicPages.includes(pathname)) {
router.replace("/");
}
}
@ -80,10 +82,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
setIsLoading(false);
};
// Small delay to ensure router is ready
const timer = setTimeout(initializeAuth, 100);
return () => clearTimeout(timer);
}, [router.pathname]);
initializeAuth();
}, [pathname, router]);
// Function to log out
const logout = () => {

276
context/ExamContext.tsx Normal file
View File

@ -0,0 +1,276 @@
"use client";
import React, {
createContext,
useContext,
useState,
useEffect,
ReactNode,
} from "react";
import { useRouter } from "next/navigation";
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 router = useRouter();
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);
setCurrentAttemptState(null);
};
const startExam = (exam?: Exam) => {
const examToUse = exam || currentExam;
if (!examToUse) {
console.warn("No exam selected, redirecting to /unit");
router.push("/unit");
return;
}
const attempt: ExamAttempt = {
examId: examToUse.id,
exam: examToUse,
answers: [],
startTime: new Date(),
totalQuestions: 0,
};
setCurrentAttemptState(attempt);
setIsInitialized(true);
};
const setAnswer = (questionId: string, answer: any) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
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) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
setCurrentAttemptState((prev) => {
if (!prev) return null;
return {
...prev,
apiResponse: response,
};
});
};
const submitExam = (): ExamAttempt | null => {
if (!currentAttempt) {
console.warn("No exam attempt to submit, redirecting to /unit");
router.push("/unit");
return null;
}
// 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,
totalQuestions,
passed: currentAttempt.exam.passingScore
? score >= currentAttempt.exam.passingScore
: undefined,
};
setCurrentAttemptState(completedAttempt);
return completedAttempt;
};
const clearExam = (): void => {
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 = () => !!currentExam && !!currentAttempt;
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) - now returns null instead of throwing
export const useExamResults = (): ExamAttempt | null => {
const { currentAttempt, isExamCompleted, isHydrated } = useExam();
// Wait for hydration before making decisions
if (!isHydrated) {
return null;
}
// If no completed exam is found, return null (let component handle redirect)
if (!isExamCompleted() || !currentAttempt) {
return null;
}
return currentAttempt;
};

24
context/ModalContext.tsx Normal file
View File

@ -0,0 +1,24 @@
"use client";
import { createContext, useContext, useState } from "react";
const ModalContext = createContext(null);
export function ModalProvider({ children }) {
const [isOpen, setIsOpen] = useState(false);
const open = () => setIsOpen(true);
const close = () => setIsOpen(false);
const toggle = () => setIsOpen((prev) => !prev);
return (
<ModalContext.Provider value={{ isOpen, open, close, toggle }}>
{children}
</ModalContext.Provider>
);
}
export function useModal() {
const ctx = useContext(ModalContext);
if (!ctx) throw new Error("useModal must be inside <ModalProvider>");
return ctx;
}

View File

@ -29,7 +29,7 @@
}
.text {
font-size: 24px;
font-size: 20px ;
font-family: 'Montserrat', sans-serif;
font-weight: 700;
color: #fff;
@ -79,6 +79,8 @@
display: flex;
flex-direction: column;
align-items: center;
border-right: 1px solid #000;
width: 100%;
}
.timeValue {
@ -133,14 +135,14 @@
@media (max-width: 480px) {
.header {
height: 80px;
height: 100px;
padding-top: 15px;
padding-left: 15px;
padding-right: 15px;
}
.text {
font-size: 14px;
font-size: 17px;
}
.profile {
@ -148,22 +150,22 @@
}
.profileImg {
width: 30px;
height: 30px;
width: 40px;
height: 40px;
}
.timer {
width: 120px;
height: 40px;
width: 180px;
height: 60px;
padding: 0 5px;
}
.timeValue {
font-size: 14px;
font-size: 18px;
}
.timeLabel {
font-size: 10px;
font-size: 12px;
}
.examHeader {

View File

@ -70,6 +70,7 @@
.categoriesContainer {
display: flex;
flex-direction: column;
justify-content: space-evenly;
gap: 16px;
padding-top: 25px;
}
@ -228,7 +229,7 @@
}
.categoryButtonText {
font-size: 12px;
font-size: 14px;
}
.categoryRow {
@ -246,11 +247,11 @@
}
.sectionTitle {
font-size: 18px;
font-size: 22px;
}
.categoryButton {
height: 100px;
height: 200px;
}
.mainContent {
@ -258,7 +259,7 @@
}
.categoryRow {
flex-direction: column;
flex-direction: row;
}
.categoryButton {

View File

@ -1,119 +1,167 @@
/* SlidingGallery.module.css */
.gallery {
height: 200px;
width: 100%;
border: 1px solid #113768;
border-radius: 25px;
position: relative;
overflow: hidden;
}
position: relative;
width: 100%;
height: 100vh; /* Default height, can be overridden by props */
overflow: hidden;
display: flex;
flex-direction: column;
}
.scrollContainer {
display: flex;
height: 100%;
overflow-x: auto;
scroll-behavior: smooth;
scroll-snap-type: x mandatory;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* Internet Explorer 10+ */
}
.emptyState {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: #666;
font-size: 1.2rem;
}
.scrollContainer::-webkit-scrollbar {
display: none; /* WebKit */
}
.scrollContainer {
flex: 1;
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE and Edge */
}
.slide {
min-width: calc(100% - 72px);
display: flex;
justify-content: center;
align-items: center;
scroll-snap-align: start;
padding: 0 36px;
}
.scrollContainer::-webkit-scrollbar {
display: none; /* Chrome, Safari, Opera */
}
.link {
text-decoration: none;
color: inherit;
width: 100%;
.slide {
min-width: 100%;
scroll-snap-align: start;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
box-sizing: border-box;
}
.link {
width: 100%;
height: 100%;
display: block;
text-decoration: none;
color: inherit;
}
.facebook {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 40px;
box-sizing: border-box;
background: linear-gradient(135deg, #1877f2 0%, #42a5f5 100%);
border-radius: 20px;
color: white;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.facebook:hover {
transform: translateY(-5px);
}
.textView {
flex: 1;
padding-right: 20px;
}
.facebookOne {
font-size: clamp(1.5rem, 4vw, 2.5rem);
font-weight: 700;
margin: 0 0 16px 0;
line-height: 1.2;
}
.facebookTwo {
font-size: clamp(1rem, 2.5vw, 1.25rem);
margin: 0;
opacity: 0.9;
line-height: 1.4;
}
.logoView {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.logoView img {
width: clamp(120px, 15vw, 120px);
height: clamp(120px, 15vw, 120px);
object-fit: contain;
}
.pagination {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 6px;
z-index: 10;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
transition: all 0.3s ease;
cursor: pointer;
}
.activeDot {
background-color: #113768;
}
.inactiveDot {
background-color: #b1d3ff;
}
.inactiveDot:hover {
background-color: rgba(255, 255, 255, 0.8);
}
/* Responsive adjustments */
@media (max-width: 768px) {
.gallery {
height: 70vh; /* Adjust for mobile */
}
.facebook {
flex: 1;
display: flex;
justify-content: space-between;
flex-direction: row;
height: 100%;
background-color: #fff;
border-radius: 25px;
padding: 20px;
box-sizing: border-box;
}
.facebookOne {
font-family: 'Montserrat', sans-serif;
font-weight: 900;
color: #113768;
font-size: 20px;
margin: 0;
}
.facebookTwo {
font-family: 'Montserrat', sans-serif;
font-weight: 600;
color: #113768;
font-size: 13px;
margin: 0;
}
.pagination {
display: flex;
flex-direction: row;
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.dot {
width: 10px;
height: 10px;
border-radius: 5px;
margin: 0 5px;
}
.activeDot {
background-color: #113768;
}
.inactiveDot {
background-color: #ccc;
flex-direction: column;
text-align: center;
padding: 30px 20px;
}
.textView {
width: 60%;
display: flex;
flex-direction: column;
justify-content: space-between;
padding-right: 0;
margin-bottom: 20px;
}
.logoView {
width: 40%;
display: flex;
justify-content: flex-end;
align-items: flex-end;
.slide {
padding: 15px;
}
}
@media (max-width: 480px) {
.gallery {
height: 60vh;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.slide {
min-width: calc(100% - 40px);
padding: 0 20px;
}
.facebookOne {
font-size: 18px;
}
.facebookTwo {
font-size: 12px;
}
.facebook {
padding: 20px 15px;
}
.slide {
padding: 10px;
}
}

View File

@ -88,3 +88,13 @@ export const getTokenFromCookie = () => {
export const clearAuthToken = () => {
setCookie("authToken", null);
};
export const getToken = async () => {
if (typeof window === "undefined") {
return null;
}
// Extract authToken from cookies
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
return match ? decodeURIComponent(match[1]) : null;
};

136
lib/gallery-views.tsx Normal file
View File

@ -0,0 +1,136 @@
// lib/gallery-views.tsx
import Link from "next/link";
import Image from "next/image";
interface ExamResults {
score: number;
totalQuestions: number;
answers: string[];
}
interface LinkedViews {
id: string;
content: React.ReactNode;
}
export const getResultViews = (examResults: ExamResults | null) => [
{
id: 1,
content: (
<div className="w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-4">
<div className="text-xl text-black">
<span className="font-bold">Accuracy</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/accuracy.png"
alt="accuracy"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
(examResults.score / examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
{
id: 2,
content: (
<div className="w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-3">
<div className="text-xl text-black">
<span className="font-bold">Error</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/error.png"
alt="error"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
((examResults.totalQuestions - examResults.score) /
examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
{
id: 3,
content: (
<div className="my-8 w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-4">
<div className="text-xl text-black">
<span className="font-bold">Attempt</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/attempt.png"
alt="attempt"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
(examResults.answers.length / examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
];
export const getLinkedViews = (): LinkedViews[] => [
{
id: "1",
content: (
<Link
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
className="w-full h-full block text-inherit box-border"
>
<div className="w-full h-full p-6 flex text-black bg-blue-50 rounded-4xl border-[0.5px] border-[#113768]/30">
<div className="">
<h3 className="text-2xl text-[#113768] font-black">
Meet, Share, and Learn!
</h3>
<p className="font-bold text-sm text-[#113768] ">
Join Facebook Community
</p>
</div>
<div className="flex justify-center items-center shrink-0">
<Image
src="/images/static/facebook-logo.png"
alt="Facebook Logo"
width={150}
height={150}
/>
</div>
</div>
</Link>
),
},
];

32
lib/leaderboard.ts Normal file
View File

@ -0,0 +1,32 @@
export interface BoardData {
id: string;
name: string;
points: number;
}
export const getTopThree = (boardData: BoardData[]) => {
if (!boardData || boardData.length === 0) return [];
return boardData
.slice()
.sort((a, b) => b.points - a.points)
.slice(0, 3)
.map((player, index) => ({
...player,
rank: index + 1,
height: index === 0 ? 250 : index === 1 ? 200 : 170,
}));
};
export const getLeaderboard = (boardData: BoardData[]) => {
return boardData.slice().sort((a, b) => b.points - a.points);
};
export const getUserData = (boardData: BoardData[], name: string) => {
if (!boardData || !Array.isArray(boardData)) return [];
const sortedData = boardData
.filter((player) => player?.name && player?.points !== undefined)
.sort((a, b) => b.points - a.points);
const result = sortedData.find((player) => player.name === name);
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
};

38
lib/utils.ts Normal file
View File

@ -0,0 +1,38 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
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);
}
};

View File

@ -9,6 +9,9 @@
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-slot": "^1.2.3",
"capacitor-secure-storage-plugin": "^0.11.0",
"clsx": "^2.1.1",
"lucide-react": "^0.523.0",

152
public/data/bookmark.json Normal file
View File

@ -0,0 +1,152 @@
[
{
"id": 0,
"question": "What is the gravitational acceleration on Earth's surface?",
"options": {
"a": "8.9 m/s²",
"b": "9.8 m/s²",
"c": "10.5 m/s²",
"d": "11.2 m/s²"
}
},
{
"id": 1,
"question": "Which planet is known as the Red Planet?",
"options": {
"a": "Venus",
"b": "Jupiter",
"c": "Mars",
"d": "Saturn"
}
},
{
"id": 2,
"question": "What is the chemical symbol for gold?",
"options": {
"a": "Go",
"b": "Gd",
"c": "Au",
"d": "Ag"
}
},
{
"id": 3,
"question": "How many chambers does a human heart have?",
"options": {
"a": "2",
"b": "3",
"c": "4",
"d": "5"
}
},
{
"id": 4,
"question": "What is the speed of light in a vacuum?",
"options": {
"a": "299,792,458 m/s",
"b": "300,000,000 m/s",
"c": "298,000,000 m/s",
"d": "301,000,000 m/s"
}
},
{
"id": 5,
"question": "Which gas makes up approximately 78% of Earth's atmosphere?",
"options": {
"a": "Oxygen",
"b": "Carbon dioxide",
"c": "Nitrogen",
"d": "Argon"
}
},
{
"id": 6,
"question": "What is the hardest natural substance on Earth?",
"options": {
"a": "Quartz",
"b": "Diamond",
"c": "Graphite",
"d": "Titanium"
}
},
{
"id": 7,
"question": "How many bones are in an adult human body?",
"options": {
"a": "196",
"b": "206",
"c": "216",
"d": "226"
}
},
{
"id": 8,
"question": "What is the pH of pure water?",
"options": {
"a": "6",
"b": "7",
"c": "8",
"d": "9"
}
},
{
"id": 9,
"question": "Which organelle is known as the powerhouse of the cell?",
"options": {
"a": "Nucleus",
"b": "Ribosome",
"c": "Mitochondria",
"d": "Golgi apparatus"
}
},
{
"id": 10,
"question": "What is the most abundant element in the universe?",
"options": {
"a": "Helium",
"b": "Hydrogen",
"c": "Oxygen",
"d": "Carbon"
}
},
{
"id": 11,
"question": "At what temperature does water boil at sea level?",
"options": {
"a": "90°C",
"b": "95°C",
"c": "100°C",
"d": "105°C"
}
},
{
"id": 12,
"question": "How many chromosomes do humans have?",
"options": {
"a": "44",
"b": "46",
"c": "48",
"d": "50"
}
},
{
"id": 13,
"question": "What is the smallest unit of matter?",
"options": {
"a": "Molecule",
"b": "Atom",
"c": "Electron",
"d": "Proton"
}
},
{
"id": 14,
"question": "Which type of electromagnetic radiation has the longest wavelength?",
"options": {
"a": "X-rays",
"b": "Visible light",
"c": "Radio waves",
"d": "Gamma rays"
}
}
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

8
types/auth.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
export interface UserData {
name: string;
institution: string;
sscRoll: string;
hscRoll: string;
email: string;
phone: string;
}

57
types/exam.d.ts vendored Normal file
View File

@ -0,0 +1,57 @@
export interface Question {
id: string;
text: string;
options?: Record<string, string>;
type: "multiple-choice" | "text" | "boolean" | undefined;
correctAnswer: string | undefined;
solution?: string | undefined;
}
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;
totalQuestions: number;
}
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;
}