generated from muhtadeetaron/nextjs-template
fix(ts): refactor codebase for capacitor setup
This commit is contained in:
@ -9,28 +9,39 @@ import FormField from "@/components/FormField";
|
|||||||
import { login } from "@/lib/auth";
|
import { login } from "@/lib/auth";
|
||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
import { useAuth } from "@/context/AuthContext";
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { LoginForm } from "@/types/auth";
|
||||||
|
|
||||||
const page = () => {
|
const LoginPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { setToken } = useAuth();
|
const { setToken } = useAuth();
|
||||||
const [form, setForm] = useState({
|
|
||||||
|
const [form, setForm] = useState<LoginForm>({
|
||||||
email: "",
|
email: "",
|
||||||
password: "",
|
password: "",
|
||||||
});
|
});
|
||||||
const [error, setError] = useState(null);
|
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
// For Rafeed
|
|
||||||
// Function to login a user. I've kept it in a barebones form right now, but you can just call the login function from /lib/auth.ts and pass on the form.
|
|
||||||
const loginUser = async () => {
|
const loginUser = async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
await login(form, setToken); // Call the login function
|
await login(form, setToken);
|
||||||
router.push("/home"); // Redirect on successful login
|
router.push("/home");
|
||||||
} catch (error) {
|
} catch (err: unknown) {
|
||||||
console.log(error);
|
console.error(err);
|
||||||
setError(error.message); // Handle error messages
|
|
||||||
|
if (
|
||||||
|
typeof err === "object" &&
|
||||||
|
err !== null &&
|
||||||
|
"message" in err &&
|
||||||
|
typeof err.message === "string"
|
||||||
|
) {
|
||||||
|
setError(err.message);
|
||||||
|
} else {
|
||||||
|
setError("An unexpected error occurred.");
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@ -63,13 +74,17 @@ const page = () => {
|
|||||||
title="Email Address"
|
title="Email Address"
|
||||||
value={form.email}
|
value={form.email}
|
||||||
placeholder="Enter your email address..."
|
placeholder="Enter your email address..."
|
||||||
handleChangeText={(e) => setForm({ ...form, email: e })}
|
handleChangeText={(value) =>
|
||||||
|
setForm({ ...form, email: value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<FormField
|
<FormField
|
||||||
title="Password"
|
title="Password"
|
||||||
value={form.password}
|
value={form.password}
|
||||||
placeholder="Enter a password"
|
placeholder="Enter a password"
|
||||||
handleChangeText={(e) => setForm({ ...form, password: e })}
|
handleChangeText={(value) =>
|
||||||
|
setForm({ ...form, password: value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -94,7 +109,7 @@ const page = () => {
|
|||||||
className="text-center mb-[70px]"
|
className="text-center mb-[70px]"
|
||||||
style={{ fontFamily: "Montserrat, sans-serif" }}
|
style={{ fontFamily: "Montserrat, sans-serif" }}
|
||||||
>
|
>
|
||||||
Don't have an account?{" "}
|
Don't have an account?{" "}
|
||||||
<Link href="/register" className="text-[#276ac0] hover:underline">
|
<Link href="/register" className="text-[#276ac0] hover:underline">
|
||||||
Register here.
|
Register here.
|
||||||
</Link>
|
</Link>
|
||||||
@ -106,4 +121,4 @@ const page = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default page;
|
export default LoginPage;
|
||||||
|
|||||||
@ -10,11 +10,18 @@ import { useAuth } from "@/context/AuthContext";
|
|||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
import FormField from "@/components/FormField";
|
import FormField from "@/components/FormField";
|
||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
|
import { RegisterForm } from "@/types/auth";
|
||||||
|
|
||||||
|
interface CustomError extends Error {
|
||||||
|
response?: {
|
||||||
|
detail?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default function RegisterPage() {
|
export default function RegisterPage() {
|
||||||
const { setToken } = useAuth();
|
const { setToken } = useAuth();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [form, setForm] = useState({
|
const [form, setForm] = useState<RegisterForm>({
|
||||||
name: "",
|
name: "",
|
||||||
institution: "",
|
institution: "",
|
||||||
sscRoll: "",
|
sscRoll: "",
|
||||||
@ -25,13 +32,12 @@ export default function RegisterPage() {
|
|||||||
});
|
});
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const handleError = (error: any) => {
|
const handleError = (error: { detail: string }) => {
|
||||||
if (error?.detail) {
|
if (error?.detail) {
|
||||||
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
||||||
if (match) {
|
if (match) {
|
||||||
const field = match[1];
|
const field = match[1];
|
||||||
const value = match[2];
|
return `The ${field} already exists. Please try again.`;
|
||||||
return `The ${field} already exists. Please use a different value.`;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "An unexpected error occurred. Please try again.";
|
return "An unexpected error occurred. Please try again.";
|
||||||
@ -56,16 +62,30 @@ export default function RegisterPage() {
|
|||||||
setError(validationError);
|
setError(validationError);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await register(form, setToken);
|
await register(form, setToken);
|
||||||
router.push("/home");
|
router.push("/home");
|
||||||
} catch (error: any) {
|
} catch (error) {
|
||||||
console.error("Error:", error.response || error.message);
|
// Type guard for built-in Error type
|
||||||
if (error.response?.detail) {
|
if (error instanceof Error) {
|
||||||
const decodedError = handleError({ detail: error.response.detail });
|
console.error(
|
||||||
setError(decodedError);
|
"Error:",
|
||||||
|
(error as CustomError).response || error.message
|
||||||
|
);
|
||||||
|
|
||||||
|
const response = (error as CustomError).response;
|
||||||
|
|
||||||
|
if (response?.detail) {
|
||||||
|
const decodedError = handleError({ detail: response.detail });
|
||||||
|
setError(decodedError);
|
||||||
|
} else {
|
||||||
|
setError(error.message || "An unexpected error occurred.");
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
setError(error.message || "An unexpected error occurred.");
|
// Fallback for non-standard errors
|
||||||
|
console.error("Unexpected error:", error);
|
||||||
|
setError("An unexpected error occurred.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -148,7 +168,7 @@ export default function RegisterPage() {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<p className="text-center text-sm">
|
<p className="text-center text-sm">
|
||||||
Already have an account?{" "}
|
Already have an account?
|
||||||
<Link href="/login" className="text-blue-600">
|
<Link href="/login" className="text-blue-600">
|
||||||
Login here
|
Login here
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@ -50,7 +50,7 @@ const QuestionItem = ({ question }: QuestionItemProps) => {
|
|||||||
|
|
||||||
const BookmarkPage = () => {
|
const BookmarkPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [questions, setQuestions] = useState();
|
const [questions, setQuestions] = useState<Question[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch("/data/bookmark.json")
|
fetch("/data/bookmark.json")
|
||||||
@ -74,7 +74,7 @@ const BookmarkPage = () => {
|
|||||||
<ListFilter size={24} color="#113768" />
|
<ListFilter size={24} color="#113768" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{questions?.map((question) => (
|
{questions.map((question: Question) => (
|
||||||
<QuestionItem key={question.id} question={question} />
|
<QuestionItem key={question.id} question={question} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,7 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
|
|
||||||
const page = () => {
|
|
||||||
return <div>page</div>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default page;
|
|
||||||
@ -1,57 +1,56 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useState, useEffect, ReactNode } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Header from "@/components/Header";
|
import Header from "@/components/Header";
|
||||||
import SlidingGallery from "@/components/SlidingGallery";
|
import SlidingGallery from "@/components/SlidingGallery";
|
||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
|
||||||
import { ChevronRight } from "lucide-react";
|
import { ChevronRight } from "lucide-react";
|
||||||
import styles from "@/css/Home.module.css";
|
import styles from "@/css/Home.module.css";
|
||||||
import { API_URL } from "@/lib/auth";
|
import { API_URL } from "@/lib/auth";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { getLinkedViews } from "@/lib/gallery-views";
|
import { getLinkedViews } from "@/lib/gallery-views";
|
||||||
import { getTopThree } from "@/lib/leaderboard";
|
import { getTopThree } from "@/lib/leaderboard";
|
||||||
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
|
import { GalleryViews } from "@/types/gallery";
|
||||||
|
|
||||||
interface LinkedView {
|
interface LeaderboardEntry {
|
||||||
id: string;
|
id: string;
|
||||||
content: ReactNode;
|
name: string;
|
||||||
|
points: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = () => {
|
const HomePage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [boardData, setBoardData] = useState([]);
|
const [boardData, setBoardData] = useState<LeaderboardEntry[]>([]);
|
||||||
const [boardError, setBoardError] = useState(null);
|
const [boardError, setBoardError] = useState<string | null>(null);
|
||||||
const [linkedViews, setLinkedViews] = useState<LinkedView[]>();
|
const [linkedViews, setLinkedViews] = useState<GalleryViews[]>();
|
||||||
|
|
||||||
const performanceData = [
|
|
||||||
{ label: "Mock Test", progress: 20 },
|
|
||||||
{ label: "Topic Test", progress: 70 },
|
|
||||||
{ label: "Subject Test", progress: 50 },
|
|
||||||
];
|
|
||||||
|
|
||||||
const progressData = [
|
|
||||||
{ label: "Physics", progress: 25 },
|
|
||||||
{ label: "Chemistry", progress: 57 },
|
|
||||||
];
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let isMounted = true;
|
let isMounted = true;
|
||||||
async function fetchBoardData() {
|
|
||||||
|
const fetchBoardData = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_URL}/leaderboard`);
|
const response = await fetch(`${API_URL}/leaderboard`);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to fetch leaderboard data");
|
throw new Error("Failed to fetch leaderboard data");
|
||||||
}
|
}
|
||||||
const data = await response.json();
|
|
||||||
|
const data: LeaderboardEntry[] = await response.json();
|
||||||
if (isMounted) setBoardData(data);
|
if (isMounted) setBoardData(data);
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
if (isMounted) setBoardError(error.message || "An error occurred");
|
if (isMounted) {
|
||||||
|
const message =
|
||||||
|
err instanceof Error ? err.message : "An unexpected error occurred";
|
||||||
|
setBoardError(message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
const fetchedLinkedViews = getLinkedViews();
|
|
||||||
|
const fetchedLinkedViews: GalleryViews[] = getLinkedViews();
|
||||||
setLinkedViews(fetchedLinkedViews);
|
setLinkedViews(fetchedLinkedViews);
|
||||||
|
|
||||||
fetchBoardData();
|
fetchBoardData();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@ -157,20 +156,24 @@ const page = () => {
|
|||||||
</div>
|
</div>
|
||||||
<div className={styles.divider}></div>
|
<div className={styles.divider}></div>
|
||||||
<div className={styles.topThreeList}>
|
<div className={styles.topThreeList}>
|
||||||
{getTopThree(boardData).map((student, idx) => (
|
{boardError ? (
|
||||||
<div key={idx} className={styles.topThreeItem}>
|
<DestructibleAlert text={boardError} />
|
||||||
<div className={styles.studentInfo}>
|
) : (
|
||||||
<span className={styles.rank}>{student.rank}</span>
|
getTopThree(boardData).map((student, idx) => (
|
||||||
<Avatar className="bg-slate-300 w-4 h-4 rounded-full"></Avatar>
|
<div key={idx} className={styles.topThreeItem}>
|
||||||
<span className={styles.studentName}>
|
<div className={styles.studentInfo}>
|
||||||
{student.name}
|
<span className={styles.rank}>{student.rank}</span>
|
||||||
|
<Avatar className="bg-slate-300 w-4 h-4 rounded-full" />
|
||||||
|
<span className={styles.studentName}>
|
||||||
|
{student.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className={styles.points}>
|
||||||
|
{student.points}pt
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<span className={styles.points}>
|
))
|
||||||
{student.points}pt
|
)}
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -232,4 +235,4 @@ const page = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default page;
|
export default HomePage;
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
import Header from "@/components/Header";
|
import Header from "@/components/Header";
|
||||||
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { API_URL, getToken } from "@/lib/auth";
|
import { API_URL, getToken } from "@/lib/auth";
|
||||||
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
|
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
|
||||||
@ -40,7 +41,14 @@ const LeaderboardPage = () => {
|
|||||||
setUserData(fetchedUserData);
|
setUserData(fetchedUserData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
setUserData(undefined);
|
setUserData({
|
||||||
|
name: "",
|
||||||
|
institution: "",
|
||||||
|
sscRoll: "",
|
||||||
|
hscRoll: "",
|
||||||
|
email: "",
|
||||||
|
phone: "",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,6 +105,33 @@ const LeaderboardPage = () => {
|
|||||||
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
|
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<BackgroundWrapper>
|
||||||
|
<section>
|
||||||
|
<Header displayTabTitle="Leaderboard" />
|
||||||
|
<section className="flex flex-col mx-10 pt-10 space-y-4">
|
||||||
|
<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">Loading...</p>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
</BackgroundWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (boardError) {
|
||||||
|
return (
|
||||||
|
<BackgroundWrapper>
|
||||||
|
<section>
|
||||||
|
<Header displayTabTitle="Leaderboard" />
|
||||||
|
<section className="flex flex-col mx-10 pt-10 space-y-4">
|
||||||
|
<DestructibleAlert text={boardError} />
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
</BackgroundWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BackgroundWrapper>
|
<BackgroundWrapper>
|
||||||
<section>
|
<section>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useState } from "react";
|
import { Suspense, useEffect, useState } from "react";
|
||||||
import Header from "@/components/Header";
|
import Header from "@/components/Header";
|
||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
@ -15,7 +15,7 @@ interface Mock {
|
|||||||
rating: number;
|
rating: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PaperScreen() {
|
function PaperPageContent() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const name = searchParams.get("name") || "";
|
const name = searchParams.get("name") || "";
|
||||||
@ -23,7 +23,6 @@ export default function PaperScreen() {
|
|||||||
const [questions, setQuestions] = useState<Mock[] | null>(null);
|
const [questions, setQuestions] = useState<Mock[] | null>(null);
|
||||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||||
const [refreshing, setRefreshing] = useState<boolean>(false);
|
const [refreshing, setRefreshing] = useState<boolean>(false);
|
||||||
const [componentKey, setComponentKey] = useState<number>(0);
|
|
||||||
|
|
||||||
async function fetchMocks() {
|
async function fetchMocks() {
|
||||||
try {
|
try {
|
||||||
@ -45,12 +44,7 @@ export default function PaperScreen() {
|
|||||||
|
|
||||||
const onRefresh = async () => {
|
const onRefresh = async () => {
|
||||||
setRefreshing(true);
|
setRefreshing(true);
|
||||||
|
|
||||||
await fetchMocks();
|
await fetchMocks();
|
||||||
setComponentKey((prevKey) => prevKey + 1);
|
|
||||||
setTimeout(() => {
|
|
||||||
setRefreshing(false);
|
|
||||||
}, 1000);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (errorMsg) {
|
if (errorMsg) {
|
||||||
@ -124,3 +118,20 @@ export default function PaperScreen() {
|
|||||||
</BackgroundWrapper>
|
</BackgroundWrapper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default function PaperScreen() {
|
||||||
|
<Suspense
|
||||||
|
fallback={
|
||||||
|
<BackgroundWrapper>
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<div className="mx-10 mt-10 flex flex-col justify-center items-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">Loading...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BackgroundWrapper>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<PaperPageContent />
|
||||||
|
</Suspense>;
|
||||||
|
}
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { API_URL, getToken } from "@/lib/auth";
|
import { API_URL, getToken } from "@/lib/auth";
|
||||||
|
import { UserData } from "@/types/auth";
|
||||||
import {
|
import {
|
||||||
Bookmark,
|
Bookmark,
|
||||||
ChartColumn,
|
ChartColumn,
|
||||||
@ -22,7 +23,14 @@ import React, { useEffect, useState } from "react";
|
|||||||
|
|
||||||
const SettingsPage = () => {
|
const SettingsPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [userData, setUserData] = useState(null);
|
const [userData, setUserData] = useState<UserData>({
|
||||||
|
name: "",
|
||||||
|
institution: "",
|
||||||
|
sscRoll: "",
|
||||||
|
hscRoll: "",
|
||||||
|
email: "",
|
||||||
|
phone: "",
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchUser() {
|
async function fetchUser() {
|
||||||
|
|||||||
@ -16,21 +16,18 @@ const units = [
|
|||||||
const Unit = () => {
|
const Unit = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const handleUnitPress = (unit) => {
|
const handleUnitPress = (unit: {
|
||||||
|
id?: number;
|
||||||
|
name: string;
|
||||||
|
rating?: number;
|
||||||
|
}) => {
|
||||||
router.push(`/paper?name=${encodeURIComponent(unit.name)}`);
|
router.push(`/paper?name=${encodeURIComponent(unit.name)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BackgroundWrapper>
|
<BackgroundWrapper>
|
||||||
<div className="flex flex-col min-h-screen">
|
<div className="flex flex-col min-h-screen">
|
||||||
<Header
|
<Header displayTabTitle="Units" />
|
||||||
displayExamInfo={null}
|
|
||||||
displayTabTitle={"Units"}
|
|
||||||
displaySubject={null}
|
|
||||||
displayUser={false}
|
|
||||||
title=""
|
|
||||||
image={""}
|
|
||||||
/>
|
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<div className="overflow-y-auto">
|
<div className="overflow-y-auto">
|
||||||
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
|
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
|
||||||
|
|||||||
@ -6,71 +6,11 @@ import { useTimer } from "@/context/TimerContext";
|
|||||||
import { useExam } from "@/context/ExamContext";
|
import { useExam } from "@/context/ExamContext";
|
||||||
import { API_URL, getToken } from "@/lib/auth";
|
import { API_URL, getToken } from "@/lib/auth";
|
||||||
import Header from "@/components/Header";
|
import Header from "@/components/Header";
|
||||||
import { Bookmark, BookmarkCheck } from "lucide-react";
|
|
||||||
import { useModal } from "@/context/ModalContext";
|
import { useModal } from "@/context/ModalContext";
|
||||||
import Modal from "@/components/ExamModal";
|
import Modal from "@/components/ExamModal";
|
||||||
import { Question } from "@/types/exam";
|
import { Question } from "@/types/exam";
|
||||||
import QuestionItem from "@/components/QuestionItem";
|
import QuestionItem from "@/components/QuestionItem";
|
||||||
|
|
||||||
// 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() {
|
export default function ExamPage() {
|
||||||
// All hooks at the top - no conditional calls
|
// All hooks at the top - no conditional calls
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -280,13 +220,7 @@ export default function ExamPage() {
|
|||||||
// Render the main exam interface
|
// Render the main exam interface
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
<Header
|
<Header examDuration={time} />
|
||||||
examDuration={time}
|
|
||||||
displayTabTitle={null}
|
|
||||||
image={undefined}
|
|
||||||
displayUser={undefined}
|
|
||||||
displaySubject={undefined}
|
|
||||||
/>
|
|
||||||
<Modal open={isOpen} onClose={close} title={currentExam?.title}>
|
<Modal open={isOpen} onClose={close} title={currentExam?.title}>
|
||||||
{currentAttempt ? (
|
{currentAttempt ? (
|
||||||
<div>
|
<div>
|
||||||
@ -301,8 +235,8 @@ export default function ExamPage() {
|
|||||||
<p className="">
|
<p className="">
|
||||||
Skipped:{" "}
|
Skipped:{" "}
|
||||||
<span className="text-yellow-600 font-bold">
|
<span className="text-yellow-600 font-bold">
|
||||||
{currentExam?.questions.length -
|
{(currentExam?.questions?.length ?? 0) -
|
||||||
currentAttempt?.answers.length}
|
(currentAttempt?.answers?.length ?? 0)}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { useEffect, useState } from "react";
|
import { Suspense, useEffect, useState } from "react";
|
||||||
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
|
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
|
||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
@ -18,47 +18,46 @@ interface Metadata {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PretestPage() {
|
function PretestPageContent() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const [examData, setExamData] = useState<Exam>();
|
const [examData, setExamData] = useState<Exam>();
|
||||||
const { startExam, setCurrentExam } = useExam();
|
const { startExam, setCurrentExam } = useExam();
|
||||||
|
|
||||||
// Get params from URL search params
|
// Get params from URL search params
|
||||||
const name = searchParams.get("name") || "";
|
|
||||||
const id = searchParams.get("id") || "";
|
const id = searchParams.get("id") || "";
|
||||||
const title = searchParams.get("title") || "";
|
const title = searchParams.get("title") || "";
|
||||||
const rating = searchParams.get("rating") || "";
|
const rating = searchParams.get("rating") || "";
|
||||||
|
|
||||||
const [metadata, setMetadata] = useState<Metadata | null>(null);
|
const [metadata, setMetadata] = useState<Metadata | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string>();
|
||||||
|
console.log(loading);
|
||||||
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(() => {
|
useEffect(() => {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (id) {
|
if (id) {
|
||||||
fetchQuestions();
|
fetchQuestions();
|
||||||
}
|
}
|
||||||
@ -74,15 +73,16 @@ export default function PretestPage() {
|
|||||||
</button>
|
</button>
|
||||||
<DestructibleAlert text={error} extraStyles="" />
|
<DestructibleAlert text={error} extraStyles="" />
|
||||||
</div>
|
</div>
|
||||||
{/* <CustomBackHandler fallbackRoute="paper" /> */}
|
|
||||||
</div>
|
</div>
|
||||||
</BackgroundWrapper>
|
</BackgroundWrapper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleStartExam() {
|
function handleStartExam() {
|
||||||
|
if (!examData) return;
|
||||||
|
|
||||||
setCurrentExam(examData);
|
setCurrentExam(examData);
|
||||||
startExam(examData); // Pass examData directly
|
startExam(examData);
|
||||||
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
|
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
@ -192,3 +192,22 @@ export default function PretestPage() {
|
|||||||
</BackgroundWrapper>
|
</BackgroundWrapper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default function PretestPage() {
|
||||||
|
return (
|
||||||
|
<Suspense
|
||||||
|
fallback={
|
||||||
|
<BackgroundWrapper>
|
||||||
|
<div className="min-h-screen">
|
||||||
|
<div className="mx-10 mt-10 flex flex-col justify-center items-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">Loading...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BackgroundWrapper>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<PretestPageContent />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -1,13 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useExam, useExamResults } from "@/context/ExamContext";
|
import { useExam } from "@/context/ExamContext";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { ArrowLeft } from "lucide-react";
|
import { ArrowLeft } from "lucide-react";
|
||||||
import SlidingGallery from "@/components/SlidingGallery";
|
import SlidingGallery from "@/components/SlidingGallery";
|
||||||
import QuestionItem from "@/components/QuestionItem";
|
import QuestionItem from "@/components/QuestionItem";
|
||||||
import { getResultViews } from "@/lib/gallery-views";
|
import { getResultViews } from "@/lib/gallery-views";
|
||||||
|
import { Question } from "@/types/exam";
|
||||||
|
|
||||||
export default function ResultsPage() {
|
export default function ResultsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -58,15 +59,15 @@ export default function ResultsPage() {
|
|||||||
|
|
||||||
const apiResponse = getApiResponse();
|
const apiResponse = getApiResponse();
|
||||||
|
|
||||||
const timeTaken =
|
// const timeTaken =
|
||||||
currentAttempt.endTime && currentAttempt.startTime
|
// currentAttempt.endTime && currentAttempt.startTime
|
||||||
? Math.round(
|
// ? Math.round(
|
||||||
(currentAttempt.endTime.getTime() -
|
// (currentAttempt.endTime.getTime() -
|
||||||
currentAttempt.startTime.getTime()) /
|
// currentAttempt.startTime.getTime()) /
|
||||||
1000 /
|
// 1000 /
|
||||||
60
|
// 60
|
||||||
)
|
// )
|
||||||
: 0;
|
// : 0;
|
||||||
|
|
||||||
const views = getResultViews(currentAttempt);
|
const views = getResultViews(currentAttempt);
|
||||||
|
|
||||||
@ -98,11 +99,13 @@ export default function ResultsPage() {
|
|||||||
Solutions
|
Solutions
|
||||||
</h3>
|
</h3>
|
||||||
<div className="flex flex-col gap-7">
|
<div className="flex flex-col gap-7">
|
||||||
{apiResponse.questions.map((question) => (
|
{apiResponse.questions.map((question: Question) => (
|
||||||
<QuestionItem
|
<QuestionItem
|
||||||
key={question.id}
|
key={question.id}
|
||||||
question={question}
|
question={question}
|
||||||
selectedAnswer={currentAttempt.answers[question.id - 1]}
|
selectedAnswer={
|
||||||
|
currentAttempt.answers[parseInt(question.id) - 1]
|
||||||
|
}
|
||||||
mode="result"
|
mode="result"
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -53,7 +53,7 @@ export default function Home() {
|
|||||||
className="text-center font-medium"
|
className="text-center font-medium"
|
||||||
style={{ fontFamily: "Montserrat, sans-serif" }}
|
style={{ fontFamily: "Montserrat, sans-serif" }}
|
||||||
>
|
>
|
||||||
Don't have an account?{" "}
|
Don't have an account?
|
||||||
<Link href="/register" className="text-[#276ac0] hover:underline">
|
<Link href="/register" className="text-[#276ac0] hover:underline">
|
||||||
Register here
|
Register here
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@ -1,6 +1,10 @@
|
|||||||
import React from "react";
|
import React, { ReactNode } from "react";
|
||||||
|
|
||||||
const BackgroundWrapper = ({ children }) => {
|
interface BackgroundWrapperProps {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BackgroundWrapper = ({ children }: BackgroundWrapperProps) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="min-h-screen bg-cover bg-center bg-no-repeat relative"
|
className="min-h-screen bg-cover bg-center bg-no-repeat relative"
|
||||||
@ -10,9 +14,7 @@ const BackgroundWrapper = ({ children }) => {
|
|||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="min-h-screen"
|
className="min-h-screen"
|
||||||
style={{
|
style={{ backgroundColor: "rgba(0, 0, 0, 0)" }}
|
||||||
backgroundColor: "rgba(0, 0, 0, 0)", // Optional overlay - adjust opacity as needed
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,12 +1,14 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
|
interface DestructibleAlertProps {
|
||||||
|
text: string;
|
||||||
|
extraStyles?: string;
|
||||||
|
}
|
||||||
|
|
||||||
const DestructibleAlert = ({
|
const DestructibleAlert = ({
|
||||||
text,
|
text,
|
||||||
extraStyles = "",
|
extraStyles = "",
|
||||||
}: {
|
}: DestructibleAlertProps) => {
|
||||||
text: string;
|
|
||||||
extraStyles?: string;
|
|
||||||
}) => {
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`border bg-red-200 border-blue-200 rounded-3xl py-6 ${extraStyles}`}
|
className={`border bg-red-200 border-blue-200 rounded-3xl py-6 ${extraStyles}`}
|
||||||
|
|||||||
@ -1,4 +1,11 @@
|
|||||||
import React, { useState } from "react";
|
import React, { useState, InputHTMLAttributes } from "react";
|
||||||
|
|
||||||
|
interface FormFieldProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||||
|
title: string;
|
||||||
|
placeholder?: string;
|
||||||
|
value: string;
|
||||||
|
handleChangeText: (value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
const FormField = ({
|
const FormField = ({
|
||||||
title,
|
title,
|
||||||
@ -6,68 +13,38 @@ const FormField = ({
|
|||||||
value,
|
value,
|
||||||
handleChangeText,
|
handleChangeText,
|
||||||
...props
|
...props
|
||||||
}) => {
|
}: FormFieldProps) => {
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
const isPasswordField = title.toLowerCase().includes("password");
|
||||||
|
|
||||||
const isPasswordField = title === "Password" || title === "Confirm Password";
|
const inputId = `input-${title.replace(/\s+/g, "-").toLowerCase()}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<label
|
<label
|
||||||
className="block mb-2"
|
htmlFor={inputId}
|
||||||
style={{
|
className="block mb-2 text-[#666666] text-[18px] font-medium font-montserrat tracking-[-0.5px]"
|
||||||
color: "#666666",
|
|
||||||
fontFamily: "Montserrat, sans-serif",
|
|
||||||
fontWeight: "500",
|
|
||||||
fontSize: 18,
|
|
||||||
marginBottom: 8,
|
|
||||||
letterSpacing: "-0.5px",
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{title}
|
{title}
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<div
|
<div className="h-16 px-4 bg-[#D2DFF0] rounded-3xl flex items-center justify-between">
|
||||||
className="h-16 px-4 bg-blue-200 rounded-3xl flex items-center justify-between"
|
|
||||||
style={{
|
|
||||||
height: 64,
|
|
||||||
paddingLeft: 16,
|
|
||||||
paddingRight: 16,
|
|
||||||
backgroundColor: "#D2DFF0",
|
|
||||||
borderRadius: 20,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<input
|
<input
|
||||||
|
id={inputId}
|
||||||
type={isPasswordField && !showPassword ? "password" : "text"}
|
type={isPasswordField && !showPassword ? "password" : "text"}
|
||||||
value={value}
|
value={value}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
onChange={(e) => handleChangeText(e.target.value)}
|
onChange={(e) => handleChangeText(e.target.value)}
|
||||||
className="flex-1 bg-transparent outline-none border-none text-blue-950"
|
className="flex-1 bg-transparent outline-none border-none text-blue-950 text-[16px] font-inherit"
|
||||||
style={{
|
|
||||||
color: "#0D47A1",
|
|
||||||
fontSize: 16,
|
|
||||||
fontFamily: "inherit",
|
|
||||||
backgroundColor: "transparent",
|
|
||||||
border: "none",
|
|
||||||
outline: "none",
|
|
||||||
}}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{isPasswordField && (
|
{isPasswordField && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
onClick={() => setShowPassword((prev) => !prev)}
|
||||||
className="ml-2 text-gray-600 hover:text-gray-800 focus:outline-none"
|
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||||
style={{
|
className="ml-2 text-gray-600 hover:text-gray-800 focus:outline-none font-montserrat font-medium text-[16px] bg-none border-none"
|
||||||
fontFamily: "Montserrat, sans-serif",
|
|
||||||
fontWeight: "500",
|
|
||||||
fontSize: 16,
|
|
||||||
background: "none",
|
|
||||||
border: "none",
|
|
||||||
cursor: "pointer",
|
|
||||||
padding: 0,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{showPassword ? "Hide" : "Show"}
|
{showPassword ? "Hide" : "Show"}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@ -13,7 +13,7 @@ interface HeaderProps {
|
|||||||
displayUser?: boolean;
|
displayUser?: boolean;
|
||||||
displaySubject?: string;
|
displaySubject?: string;
|
||||||
displayTabTitle?: string;
|
displayTabTitle?: string;
|
||||||
examDuration?: string;
|
examDuration?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Header = ({
|
const Header = ({
|
||||||
@ -28,7 +28,7 @@ const Header = ({
|
|||||||
const [totalSeconds, setTotalSeconds] = useState(
|
const [totalSeconds, setTotalSeconds] = useState(
|
||||||
examDuration ? parseInt(examDuration) * 60 : 0
|
examDuration ? parseInt(examDuration) * 60 : 0
|
||||||
);
|
);
|
||||||
const { timeRemaining, stopTimer } = useTimer();
|
const { stopTimer } = useTimer();
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const [userData, setUserData] = useState<UserData>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import { Badge } from "./ui/badge";
|
|||||||
interface ResultItemProps {
|
interface ResultItemProps {
|
||||||
mode: "result";
|
mode: "result";
|
||||||
question: Question;
|
question: Question;
|
||||||
selectedAnswer: string | undefined;
|
selectedAnswer: { answer: string } | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ExamItemProps {
|
interface ExamItemProps {
|
||||||
@ -20,10 +20,22 @@ type QuestionItemProps = ResultItemProps | ExamItemProps;
|
|||||||
|
|
||||||
const QuestionItem = (props: QuestionItemProps) => {
|
const QuestionItem = (props: QuestionItemProps) => {
|
||||||
const [bookmark, setBookmark] = useState(false);
|
const [bookmark, setBookmark] = useState(false);
|
||||||
const { question, selectedAnswer } = props;
|
|
||||||
|
const { question } = props;
|
||||||
|
|
||||||
const isExam = props.mode === "exam";
|
const isExam = props.mode === "exam";
|
||||||
|
|
||||||
|
// Extract correct type-safe selectedAnswer
|
||||||
|
const selectedAnswer = isExam
|
||||||
|
? props.selectedAnswer
|
||||||
|
: props.selectedAnswer?.answer;
|
||||||
|
|
||||||
|
const handleOptionSelect = (key: string) => {
|
||||||
|
if (isExam && props.handleSelect) {
|
||||||
|
props.handleSelect(parseInt(question.id), key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
|
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
|
||||||
<h3 className="text-xl font-semibold ">
|
<h3 className="text-xl font-semibold ">
|
||||||
@ -45,19 +57,14 @@ const QuestionItem = (props: QuestionItemProps) => {
|
|||||||
|
|
||||||
{isExam ? (
|
{isExam ? (
|
||||||
<div className="flex flex-col gap-4 items-start">
|
<div className="flex flex-col gap-4 items-start">
|
||||||
{Object.entries(question.options).map(([key, value]) => {
|
{Object.entries(question.options ?? {}).map(([key, value]) => {
|
||||||
const isSelected = selectedAnswer === key;
|
const isSelected = selectedAnswer === key;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={key}
|
key={key}
|
||||||
className="flex items-center gap-3"
|
className="flex items-center gap-3"
|
||||||
onClick={
|
onClick={() => handleOptionSelect(key)}
|
||||||
isExam
|
|
||||||
? () => props.handleSelect(question.id, key)
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
disabled={!isExam}
|
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
className={`flex items-center rounded-full border px-1.5 ${
|
className={`flex items-center rounded-full border px-1.5 ${
|
||||||
@ -80,7 +87,7 @@ const QuestionItem = (props: QuestionItemProps) => {
|
|||||||
<Badge className="bg-yellow-500" variant="destructive">
|
<Badge className="bg-yellow-500" variant="destructive">
|
||||||
Skipped
|
Skipped
|
||||||
</Badge>
|
</Badge>
|
||||||
) : selectedAnswer.answer === question.correctAnswer ? (
|
) : selectedAnswer === question.correctAnswer ? (
|
||||||
<Badge className="bg-green-500 text-white" variant="default">
|
<Badge className="bg-green-500 text-white" variant="default">
|
||||||
Correct
|
Correct
|
||||||
</Badge>
|
</Badge>
|
||||||
@ -90,23 +97,20 @@ const QuestionItem = (props: QuestionItemProps) => {
|
|||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col gap-4 items-start">
|
<div className="flex flex-col gap-4 items-start">
|
||||||
{Object.entries(question.options).map(([key, value]) => {
|
{Object.entries(question.options ?? {}).map(([key, value]) => {
|
||||||
const isCorrect = key === question.correctAnswer;
|
const isCorrect = key === question.correctAnswer;
|
||||||
const isSelected = key === selectedAnswer?.answer;
|
const isSelected = key === selectedAnswer;
|
||||||
|
|
||||||
let optionStyle =
|
let optionStyle =
|
||||||
"px-2 py-1 flex items-center rounded-full border font-medium text-sm";
|
"px-2 py-1 flex items-center rounded-full border font-medium text-sm";
|
||||||
|
|
||||||
if (isCorrect) {
|
if (isCorrect) {
|
||||||
optionStyle += " bg-green-600 text-white border-green-600";
|
optionStyle += " bg-green-600 text-white border-green-600";
|
||||||
}
|
} else if (isSelected && !isCorrect) {
|
||||||
|
|
||||||
if (isSelected && !isCorrect) {
|
|
||||||
optionStyle += " bg-red-600 text-white border-red-600";
|
optionStyle += " bg-red-600 text-white border-red-600";
|
||||||
}
|
} else {
|
||||||
|
|
||||||
if (!isCorrect && !isSelected) {
|
|
||||||
optionStyle += " border-gray-300 text-gray-700";
|
optionStyle += " border-gray-300 text-gray-700";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,7 +122,9 @@ const QuestionItem = (props: QuestionItemProps) => {
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="h-[0.5px] border-[0.5px] border-dashed border-black/20"></div>
|
<div className="h-[0.5px] border-[0.5px] border-dashed border-black/20"></div>
|
||||||
|
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<h3 className="text-lg font-bold text-black/40">Solution:</h3>
|
<h3 className="text-lg font-bold text-black/40">Solution:</h3>
|
||||||
<p className="text-lg">{question.solution}</p>
|
<p className="text-lg">{question.solution}</p>
|
||||||
|
|||||||
@ -1,13 +1,15 @@
|
|||||||
import React, { useState, useRef, useEffect } from "react";
|
import React, {
|
||||||
import Link from "next/link";
|
useState,
|
||||||
import Image from "next/image";
|
useRef,
|
||||||
|
useEffect,
|
||||||
|
useCallback,
|
||||||
|
UIEvent,
|
||||||
|
} from "react";
|
||||||
import styles from "../css/SlidingGallery.module.css";
|
import styles from "../css/SlidingGallery.module.css";
|
||||||
|
import { GalleryViews } from "@/types/gallery";
|
||||||
|
|
||||||
interface SlidingGalleryProps {
|
interface SlidingGalleryProps {
|
||||||
views?: {
|
views: GalleryViews[] | undefined;
|
||||||
id: string;
|
|
||||||
content: React.ReactNode;
|
|
||||||
}[];
|
|
||||||
className?: string;
|
className?: string;
|
||||||
showPagination?: boolean;
|
showPagination?: boolean;
|
||||||
autoScroll?: boolean;
|
autoScroll?: boolean;
|
||||||
@ -17,7 +19,7 @@ interface SlidingGalleryProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SlidingGallery = ({
|
const SlidingGallery = ({
|
||||||
views = [],
|
views,
|
||||||
className = "",
|
className = "",
|
||||||
showPagination = true,
|
showPagination = true,
|
||||||
autoScroll = false,
|
autoScroll = false,
|
||||||
@ -25,15 +27,47 @@ const SlidingGallery = ({
|
|||||||
onSlideChange = () => {},
|
onSlideChange = () => {},
|
||||||
height = "100vh",
|
height = "100vh",
|
||||||
}: SlidingGalleryProps) => {
|
}: SlidingGalleryProps) => {
|
||||||
const [activeIdx, setActiveIdx] = useState(0);
|
const [activeIdx, setActiveIdx] = useState<number>(0);
|
||||||
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
|
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
|
||||||
const scrollRef = useRef(null);
|
|
||||||
const galleryRef = useRef(null);
|
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||||
const autoScrollRef = useRef(null);
|
const galleryRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const autoScrollRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
|
const handleScroll = (event: UIEvent<HTMLDivElement>) => {
|
||||||
|
handleUserInteraction();
|
||||||
|
const scrollLeft = event.currentTarget.scrollLeft;
|
||||||
|
const slideWidth = dimensions.width;
|
||||||
|
const index = Math.round(scrollLeft / slideWidth);
|
||||||
|
|
||||||
|
if (index !== activeIdx) {
|
||||||
|
setActiveIdx(index);
|
||||||
|
onSlideChange(index);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const goToSlide = useCallback(
|
||||||
|
(index: number) => {
|
||||||
|
if (scrollRef.current) {
|
||||||
|
scrollRef.current.scrollTo({
|
||||||
|
left: index * dimensions.width,
|
||||||
|
behavior: "smooth",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[dimensions.width]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDotClick = (index: number) => {
|
||||||
|
handleUserInteraction();
|
||||||
|
goToSlide(index);
|
||||||
|
setActiveIdx(index);
|
||||||
|
onSlideChange(index);
|
||||||
|
};
|
||||||
|
|
||||||
// Auto-scroll functionality
|
// Auto-scroll functionality
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (autoScroll && views.length > 1) {
|
if (autoScroll && views && views.length > 1) {
|
||||||
autoScrollRef.current = setInterval(() => {
|
autoScrollRef.current = setInterval(() => {
|
||||||
setActiveIdx((prevIdx) => {
|
setActiveIdx((prevIdx) => {
|
||||||
const nextIdx = (prevIdx + 1) % views.length;
|
const nextIdx = (prevIdx + 1) % views.length;
|
||||||
@ -48,15 +82,17 @@ const SlidingGallery = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}, [autoScroll, autoScrollInterval, views.length]);
|
}, [autoScroll, autoScrollInterval, views?.length, goToSlide, views]);
|
||||||
|
|
||||||
// Clear auto-scroll on user interaction
|
// Clear auto-scroll on user interaction
|
||||||
const handleUserInteraction = () => {
|
const handleUserInteraction = () => {
|
||||||
if (autoScrollRef.current) {
|
if (autoScrollRef.current) {
|
||||||
clearInterval(autoScrollRef.current);
|
clearInterval(autoScrollRef.current);
|
||||||
|
autoScrollRef.current = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Update dimensions
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const updateDimensions = () => {
|
const updateDimensions = () => {
|
||||||
if (galleryRef.current) {
|
if (galleryRef.current) {
|
||||||
@ -67,18 +103,13 @@ const SlidingGallery = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initial dimension update
|
|
||||||
updateDimensions();
|
updateDimensions();
|
||||||
|
|
||||||
// Add resize listener
|
|
||||||
window.addEventListener("resize", updateDimensions);
|
window.addEventListener("resize", updateDimensions);
|
||||||
|
|
||||||
// Cleanup
|
|
||||||
return () => window.removeEventListener("resize", updateDimensions);
|
return () => window.removeEventListener("resize", updateDimensions);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Recalculate index when dimension changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Recalculate active index when dimensions change
|
|
||||||
if (scrollRef.current && dimensions.width > 0) {
|
if (scrollRef.current && dimensions.width > 0) {
|
||||||
const scrollLeft = scrollRef.current.scrollLeft;
|
const scrollLeft = scrollRef.current.scrollLeft;
|
||||||
const slideWidth = dimensions.width;
|
const slideWidth = dimensions.width;
|
||||||
@ -87,34 +118,6 @@ const SlidingGallery = ({
|
|||||||
}
|
}
|
||||||
}, [dimensions]);
|
}, [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) {
|
if (!views || views.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className={`${styles.gallery} ${className}`}>
|
<div className={`${styles.gallery} ${className}`}>
|
||||||
@ -138,6 +141,8 @@ const SlidingGallery = ({
|
|||||||
style={{
|
style={{
|
||||||
width: "100%",
|
width: "100%",
|
||||||
height: "100%",
|
height: "100%",
|
||||||
|
overflowX: "scroll",
|
||||||
|
display: "flex",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{views.map((item) => (
|
{views.map((item) => (
|
||||||
@ -154,6 +159,7 @@ const SlidingGallery = ({
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showPagination && views.length > 1 && (
|
{showPagination && views.length > 1 && (
|
||||||
<div className={styles.pagination}>
|
<div className={styles.pagination}>
|
||||||
{views.map((_, index) => (
|
{views.map((_, index) => (
|
||||||
|
|||||||
@ -86,7 +86,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
|||||||
setCurrentAttemptState(null);
|
setCurrentAttemptState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const startExam = (exam?: Exam) => {
|
const startExam = (exam?: Exam): void => {
|
||||||
const examToUse = exam || currentExam;
|
const examToUse = exam || currentExam;
|
||||||
|
|
||||||
if (!examToUse) {
|
if (!examToUse) {
|
||||||
@ -101,6 +101,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
|||||||
answers: [],
|
answers: [],
|
||||||
startTime: new Date(),
|
startTime: new Date(),
|
||||||
totalQuestions: 0,
|
totalQuestions: 0,
|
||||||
|
score: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
setCurrentAttemptState(attempt);
|
setCurrentAttemptState(attempt);
|
||||||
|
|||||||
@ -1,24 +1,41 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { createContext, useContext, useState } from "react";
|
import { createContext, useContext, useState } from "react";
|
||||||
|
|
||||||
const ModalContext = createContext(null);
|
// Define the context type
|
||||||
|
interface ModalContextType {
|
||||||
|
isOpen: boolean;
|
||||||
|
open: () => void;
|
||||||
|
close: () => void;
|
||||||
|
toggle: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
export function ModalProvider({ children }) {
|
// Create context with default values (no null)
|
||||||
|
const ModalContext = createContext<ModalContextType>({
|
||||||
|
isOpen: false,
|
||||||
|
open: () => {},
|
||||||
|
close: () => {},
|
||||||
|
toggle: () => {},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function ModalProvider({ children }: { children: React.ReactNode }) {
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
const open = () => setIsOpen(true);
|
const open = () => setIsOpen(true);
|
||||||
const close = () => setIsOpen(false);
|
const close = () => setIsOpen(false);
|
||||||
const toggle = () => setIsOpen((prev) => !prev);
|
const toggle = () => setIsOpen((prev) => !prev);
|
||||||
|
|
||||||
|
const value: ModalContextType = {
|
||||||
|
isOpen,
|
||||||
|
open,
|
||||||
|
close,
|
||||||
|
toggle,
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalContext.Provider value={{ isOpen, open, close, toggle }}>
|
<ModalContext.Provider value={value}>{children}</ModalContext.Provider>
|
||||||
{children}
|
|
||||||
</ModalContext.Provider>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useModal() {
|
export function useModal(): ModalContextType {
|
||||||
const ctx = useContext(ModalContext);
|
return useContext(ModalContext);
|
||||||
if (!ctx) throw new Error("useModal must be inside <ModalProvider>");
|
|
||||||
return ctx;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,6 +11,15 @@ const compat = new FlatCompat({
|
|||||||
|
|
||||||
const eslintConfig = [
|
const eslintConfig = [
|
||||||
...compat.extends("next/core-web-vitals", "next/typescript"),
|
...compat.extends("next/core-web-vitals", "next/typescript"),
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
// Disable the no-explicit-any rule
|
||||||
|
"@typescript-eslint/no-explicit-any": "off",
|
||||||
|
|
||||||
|
// Alternative: Make it a warning instead of error
|
||||||
|
// "@typescript-eslint/no-explicit-any": "warn",
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export default eslintConfig;
|
export default eslintConfig;
|
||||||
|
|||||||
69
lib/auth.ts
69
lib/auth.ts
@ -1,20 +1,37 @@
|
|||||||
export const API_URL = "https://examjam-api.pptx704.com";
|
export const API_URL = "https://examjam-api.pptx704.com";
|
||||||
|
|
||||||
// Cookie utility functions
|
// Cookie utility function
|
||||||
const setCookie = (name, value, days = 7) => {
|
const setCookie = (name: string, value: string | null, days: number = 7) => {
|
||||||
if (typeof document === "undefined") return;
|
if (typeof document === "undefined") return;
|
||||||
|
|
||||||
if (value === null) {
|
if (value === null) {
|
||||||
// Delete cookie by setting expiration to past date
|
|
||||||
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
|
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
|
||||||
} else {
|
} else {
|
||||||
const expires = new Date();
|
const expires = new Date();
|
||||||
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
|
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
|
||||||
document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Strict; Secure`;
|
document.cookie = `${name}=${encodeURIComponent(
|
||||||
|
value
|
||||||
|
)}; expires=${expires.toUTCString()}; path=/; SameSite=Strict; Secure`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const login = async (form, setToken) => {
|
interface AuthForm {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
[key: string]: any; // for flexibility
|
||||||
|
}
|
||||||
|
|
||||||
|
type SetTokenFn = (token: string) => void;
|
||||||
|
|
||||||
|
// Optional: Create a custom error type to carry extra data
|
||||||
|
interface APIError extends Error {
|
||||||
|
response?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const login = async (
|
||||||
|
form: AuthForm,
|
||||||
|
setToken: SetTokenFn
|
||||||
|
): Promise<void> => {
|
||||||
const response = await fetch(`${API_URL}/auth/login`, {
|
const response = await fetch(`${API_URL}/auth/login`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -29,27 +46,14 @@ export const login = async (form, setToken) => {
|
|||||||
throw new Error(data.message || "Login failed");
|
throw new Error(data.message || "Login failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save the token to cookies instead of secure storage
|
|
||||||
setCookie("authToken", data.token);
|
setCookie("authToken", data.token);
|
||||||
setToken(data.token); // Update the token in context
|
setToken(data.token);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleError = (error) => {
|
export const register = async (
|
||||||
// Check if error has a "detail" property
|
form: AuthForm,
|
||||||
if (error?.detail) {
|
setToken: SetTokenFn
|
||||||
// Match the field causing the issue
|
): Promise<void> => {
|
||||||
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
|
||||||
|
|
||||||
if (match) {
|
|
||||||
const field = match[1]; // The field name, e.g., "phone"
|
|
||||||
const value = match[2]; // The duplicate value, e.g., "0987654321"
|
|
||||||
return `The ${field} already exists. Please use a different value.`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "An unexpected error occurred. Please try again.";
|
|
||||||
};
|
|
||||||
|
|
||||||
export const register = async (form, setToken) => {
|
|
||||||
const response = await fetch(`${API_URL}/auth/register`, {
|
const response = await fetch(`${API_URL}/auth/register`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -58,22 +62,19 @@ export const register = async (form, setToken) => {
|
|||||||
body: JSON.stringify(form),
|
body: JSON.stringify(form),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json(); // Parse the response JSON
|
const data = await response.json();
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
// Instead of throwing a string, include full error data for debugging
|
const error: APIError = new Error(data?.detail || "Registration failed");
|
||||||
const error = new Error(data?.detail || "Registration failed");
|
error.response = data;
|
||||||
error.response = data; // Attach the full response for later use
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save the token to cookies instead of secure storage
|
|
||||||
setCookie("authToken", data.token);
|
setCookie("authToken", data.token);
|
||||||
setToken(data.token); // Update the token in context
|
setToken(data.token);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Additional utility function to get token from cookies (if needed elsewhere)
|
export const getTokenFromCookie = (): string | null => {
|
||||||
export const getTokenFromCookie = () => {
|
|
||||||
if (typeof document === "undefined") return null;
|
if (typeof document === "undefined") return null;
|
||||||
|
|
||||||
const value = `; ${document.cookie}`;
|
const value = `; ${document.cookie}`;
|
||||||
@ -84,17 +85,15 @@ export const getTokenFromCookie = () => {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Utility function to clear auth token (for logout)
|
export const clearAuthToken = (): void => {
|
||||||
export const clearAuthToken = () => {
|
|
||||||
setCookie("authToken", null);
|
setCookie("authToken", null);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getToken = async () => {
|
export const getToken = async (): Promise<string | null> => {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract authToken from cookies
|
|
||||||
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
|
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
|
||||||
return match ? decodeURIComponent(match[1]) : null;
|
return match ? decodeURIComponent(match[1]) : null;
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,16 +1,14 @@
|
|||||||
// lib/gallery-views.tsx
|
// lib/gallery-views.tsx
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
import { ExamAnswer } from "@/types/exam";
|
||||||
|
import { GalleryViews } from "@/types/gallery";
|
||||||
|
|
||||||
|
// Define the ExamResults type if not already defined
|
||||||
interface ExamResults {
|
interface ExamResults {
|
||||||
score: number;
|
score: number;
|
||||||
totalQuestions: number;
|
totalQuestions: number;
|
||||||
answers: string[];
|
answers: ExamAnswer[]; // or more specific type based on your answer structure
|
||||||
}
|
|
||||||
|
|
||||||
interface LinkedViews {
|
|
||||||
id: string;
|
|
||||||
content: React.ReactNode;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getResultViews = (examResults: ExamResults | null) => [
|
export const getResultViews = (examResults: ExamResults | null) => [
|
||||||
@ -104,9 +102,9 @@ export const getResultViews = (examResults: ExamResults | null) => [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export const getLinkedViews = (): LinkedViews[] => [
|
export const getLinkedViews = (): GalleryViews[] => [
|
||||||
{
|
{
|
||||||
id: "1",
|
id: 1,
|
||||||
content: (
|
content: (
|
||||||
<Link
|
<Link
|
||||||
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
|
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
|
||||||
|
|||||||
@ -1,7 +1,5 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {};
|
||||||
/* config options here */
|
|
||||||
};
|
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
@ -4,11 +4,12 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev --turbopack",
|
"dev": "next dev --turbopack",
|
||||||
"build": "next build",
|
"build": "next build ",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "next lint"
|
"lint": "next lint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@capacitor/core": "^7.4.2",
|
||||||
"@radix-ui/react-avatar": "^1.1.10",
|
"@radix-ui/react-avatar": "^1.1.10",
|
||||||
"@radix-ui/react-label": "^2.1.7",
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
"@radix-ui/react-slot": "^1.2.3",
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
@ -20,6 +21,7 @@
|
|||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@capacitor/cli": "^7.4.2",
|
||||||
"@eslint/eslintrc": "^3",
|
"@eslint/eslintrc": "^3",
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
|
|||||||
15
types/auth.d.ts
vendored
15
types/auth.d.ts
vendored
@ -6,3 +6,18 @@ export interface UserData {
|
|||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RegisterForm {
|
||||||
|
name: string;
|
||||||
|
institution: string;
|
||||||
|
sscRoll: string;
|
||||||
|
hscRoll: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginForm {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|||||||
10
types/exam.d.ts
vendored
10
types/exam.d.ts
vendored
@ -1,6 +1,6 @@
|
|||||||
export interface Question {
|
export interface Question {
|
||||||
id: string;
|
id: string;
|
||||||
text: string;
|
question: string;
|
||||||
options?: Record<string, string>;
|
options?: Record<string, string>;
|
||||||
type: "multiple-choice" | "text" | "boolean" | undefined;
|
type: "multiple-choice" | "text" | "boolean" | undefined;
|
||||||
correctAnswer: string | undefined;
|
correctAnswer: string | undefined;
|
||||||
@ -18,7 +18,7 @@ export interface Exam {
|
|||||||
|
|
||||||
export interface ExamAnswer {
|
export interface ExamAnswer {
|
||||||
questionId: string;
|
questionId: string;
|
||||||
answer: any;
|
answer: string;
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ export interface ExamAttempt {
|
|||||||
answers: ExamAnswer[];
|
answers: ExamAnswer[];
|
||||||
startTime: Date;
|
startTime: Date;
|
||||||
endTime?: Date;
|
endTime?: Date;
|
||||||
score?: number;
|
score: number;
|
||||||
passed?: boolean;
|
passed?: boolean;
|
||||||
apiResponse?: any;
|
apiResponse?: any;
|
||||||
totalQuestions: number;
|
totalQuestions: number;
|
||||||
@ -42,9 +42,9 @@ export interface ExamContextType {
|
|||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
setCurrentExam: (exam: Exam) => void;
|
setCurrentExam: (exam: Exam) => void;
|
||||||
startExam: () => void;
|
startExam: (exam?: Exam) => void;
|
||||||
setAnswer: (questionId: string, answer: any) => void;
|
setAnswer: (questionId: string, answer: any) => void;
|
||||||
submitExam: () => ExamAttempt;
|
submitExam: () => ExamAttempt | null;
|
||||||
clearExam: () => void;
|
clearExam: () => void;
|
||||||
setApiResponse: (response: any) => void;
|
setApiResponse: (response: any) => void;
|
||||||
|
|
||||||
|
|||||||
4
types/gallery.d.ts
vendored
Normal file
4
types/gallery.d.ts
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export interface GalleryViews {
|
||||||
|
id: number;
|
||||||
|
content: React.JSX.Element;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user