ExamCraftAI / Frontend /src /components /layout /DashboardLayout.jsx
Hkoradiya123
Serve frontend and backend from one Space
38ee1b6
Raw History Blame Contribute Delete
29.8 kB
import React, { useState, useEffect, useRef } from "react";
import { Outlet, NavLink, useNavigate, Link } from "react-router-dom";
import { useTheme } from "../../context/ThemeContext";
import { cn } from "../../utils/cn";
import { motion, AnimatePresence } from "framer-motion";
import { supabase } from "../../utils/supabaseClient";
import { API_BASE_URL } from "../../utils/api";
import {
LayoutDashboard,
UploadCloud,
BrainCircuit,
History as HistoryIcon,
Settings,
LogOut,
ChevronLeft,
ChevronRight,
Sun,
Moon,
Bell,
Search,
Menu,
X,
KeyRound,
AlertCircle
} from "lucide-react";
export default function DashboardLayout() {
const [isSidebarOpen, setSidebarOpen] = useState(true);
const [isMobileOpen, setMobileOpen] = useState(false);
const [isProfileOpen, setProfileOpen] = useState(false);
const [isNotificationsOpen, setNotificationsOpen] = useState(false);
const [userProfile, setUserProfile] = useState(null);
const [notifications, setNotifications] = useState([]);
// Exam Password States
const [showPasswordPopup, setShowPasswordPopup] = useState(false);
const [examPassword, setExamPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordError, setPasswordError] = useState("");
const [isSavingPassword, setIsSavingPassword] = useState(false);
const profileRef = useRef(null);
const notificationsRef = useRef(null);
const { theme, toggleTheme } = useTheme();
const navigate = useNavigate();
useEffect(() => {
const fetchUser = async () => {
const { data: { session } } = await supabase.auth.getSession();
if (session?.user) {
try {
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.access_token}`
}
});
if (response.ok) {
const data = await response.json();
if (data && data.full_name) {
setUserProfile(data);
// Detect if exam_password is not set
if (data.has_exam_password === false) {
setNotifications([{
id: 'exam_password_setup',
title: 'Set Exam Password',
message: 'A 6-digit exam password is required to secure your papers.',
isUnread: true
}]);
// Prevent sending emails repeatedly per session
if (!sessionStorage.getItem('passwordReminderSent')) {
sessionStorage.setItem('passwordReminderSent', 'true');
fetch(`${API_BASE_URL}/api/send-password-reminder`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${session.access_token}` }
}).catch(err => console.error("Email API Err:", err));
}
}
} else {
setUserProfile(session.user.user_metadata);
}
} else {
setUserProfile(session.user.user_metadata);
}
} catch (error) {
console.error("Failed to fetch profile via API", error);
setUserProfile(session.user.user_metadata);
}
}
};
fetchUser();
}, []);
// Close profile and notification dropdowns when clicking outside
useEffect(() => {
const handleClickOutside = (event) => {
if (profileRef.current && !profileRef.current.contains(event.target)) {
setProfileOpen(false);
}
if (notificationsRef.current && !notificationsRef.current.contains(event.target)) {
setNotificationsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleSavePassword = async (e) => {
e.preventDefault();
setPasswordError("");
if (!/^\d{6}$/.test(examPassword)) {
setPasswordError("Password must be exactly 6 digits.");
return;
}
if (examPassword !== confirmPassword) {
setPasswordError("Passwords do not match.");
return;
}
setIsSavingPassword(true);
try {
const { data: { session } } = await supabase.auth.getSession();
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.access_token}`
},
body: JSON.stringify({ exam_password: examPassword })
});
if (!response.ok) throw new Error("Failed to save password");
setUserProfile(prev => ({ ...prev, has_exam_password: true }));
setNotifications(prev => prev.filter(n => n.id !== 'exam_password_setup'));
setShowPasswordPopup(false);
setExamPassword("");
setConfirmPassword("");
} catch (error) {
setPasswordError(error.message);
} finally {
setIsSavingPassword(false);
}
};
const navItems = [
{ name: "Dashboard", path: "/app", icon: LayoutDashboard },
{ name: "Upload", path: "/app/upload", icon: UploadCloud },
{ name: "Generate", path: "/app/generate", icon: BrainCircuit },
{ name: "History", path: "/app/history", icon: HistoryIcon },
{ name: "Settings", path: "/app/settings", icon: Settings },
];
return (
<div className="flex h-screen w-full bg-background overflow-hidden selection:bg-primary/30">
{/* Sidebar Desktop */}
<motion.aside
initial={{ width: 260 }}
animate={{ width: isSidebarOpen ? 260 : 80 }}
transition={{ duration: 0.3, ease: "easeInOut" }}
className={cn(
"hidden md:flex flex-col border-r border-border bg-card shadow-sm z-20 relative",
"glass dark:bg-card/80 transition-colors"
)}
>
<div className="flex items-center h-16 px-4 shrink-0 overflow-hidden border-b border-border/50">
<BrainCircuit className="h-8 w-8 text-primary shrink-0" />
<AnimatePresence>
{isSidebarOpen && (
<motion.span
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -10 }}
className="ml-3 font-bold text-xl tracking-tight text-foreground whitespace-nowrap"
>
ExamCraft.<span className="text-primary">AI</span>
</motion.span>
)}
</AnimatePresence>
</div>
<button
onClick={() => setSidebarOpen(!isSidebarOpen)}
className="absolute -right-4 top-5 bg-card border border-border rounded-full p-1.5 shadow-md text-muted-foreground hover:text-foreground hover:bg-accent/10 transition-colors"
>
{isSidebarOpen ? <ChevronLeft size={16} /> : <ChevronRight size={16} />}
</button>
<nav className="flex-1 overflow-y-auto w-full px-3 py-6 space-y-2">
{navItems.map((item) => (
<NavLink
key={item.name}
to={item.path}
end={item.path === "/app"}
className={({ isActive }) =>
cn(
"flex items-center space-x-3 px-3 py-3 rounded-lg transition-all duration-200 group relative",
isActive
? "bg-primary text-primary-foreground shadow-[0_0_15px_rgba(var(--primary),0.3)]"
: "text-muted-foreground hover:bg-primary/10 hover:text-foreground"
)
}
>
{({ isActive }) => (
<>
<item.icon className={cn("h-5 w-5 shrink-0 transition-transform", isActive ? "scale-110" : "group-hover:scale-110")} />
<AnimatePresence>
{isSidebarOpen && (
<motion.span
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: "auto" }}
exit={{ opacity: 0, width: 0 }}
className="font-medium whitespace-nowrap overflow-hidden"
>
{item.name}
</motion.span>
)}
</AnimatePresence>
</>
)}
</NavLink>
))}
</nav>
<div className="p-4 border-t border-border/50 shrink-0">
<button
onClick={() => navigate('/login')}
className={cn(
"flex w-full items-center justify-center space-x-3 px-3 py-3 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors group",
!isSidebarOpen && "px-0"
)}>
<LogOut className="h-5 w-5 shrink-0 transition-transform group-hover:-translate-x-1" />
{isSidebarOpen && <span className="font-medium">Logout</span>}
</button>
</div>
</motion.aside>
{/* Main Content Area */}
<main className="flex-1 flex flex-col min-w-0">
{/* Top Navbar */}
<header className="h-16 px-4 flex items-center justify-between border-b border-border/50 bg-background/80 backdrop-blur-md z-10 sticky top-0">
<div className="flex items-center gap-4">
<button className="md:hidden p-2 text-muted-foreground" onClick={() => setMobileOpen(true)}>
<Menu size={24} />
</button>
<div className="relative hidden sm:block">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<input
type="text"
placeholder="Search exams, topics..."
className="h-10 w-64 rounded-full border border-border bg-input/20 pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
/>
</div>
</div>
<div className="flex items-center gap-4">
<button onClick={toggleTheme} className="p-2 rounded-full hover:bg-accent/10 transition-colors text-muted-foreground hover:text-foreground">
{theme === "dark" ? <Sun size={20} className="text-accent" /> : <Moon size={20} />}
</button>
<div className="relative" ref={notificationsRef}>
<button onClick={() => setNotificationsOpen(!isNotificationsOpen)} className="p-2 rounded-full hover:bg-accent/10 transition-colors text-muted-foreground hover:text-foreground relative">
<Bell size={20} />
{notifications.length > 0 && notifications.some(n => n.isUnread) && (
<span className="absolute top-1.5 right-2 h-2.5 w-2.5 bg-destructive rounded-full border-2 border-background animate-pulse"></span>
)}
</button>
<AnimatePresence>
{isNotificationsOpen && (
<motion.div
initial={{ opacity: 0, y: 10, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.95 }}
transition={{ duration: 0.15 }}
className="absolute right-0 mt-3 w-80 rounded-xl border border-border bg-card shadow-lg flex flex-col overflow-hidden z-50 py-1"
>
<div className="px-4 py-3 border-b border-border/50 flex justify-between items-center">
<h3 className="font-semibold text-foreground">Notifications</h3>
<span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded-full font-medium">{notifications.length} New</span>
</div>
<div className="max-h-80 overflow-y-auto w-full p-2 space-y-1">
{notifications.length === 0 ? (
<div className="py-6 text-center text-muted-foreground text-sm">
No new notifications
</div>
) : (
notifications.map(notif => (
<div key={notif.id}
onClick={() => {
setNotificationsOpen(false);
if(notif.id === 'exam_password_setup') setShowPasswordPopup(true);
}}
className="flex items-start gap-3 p-3 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors relative"
>
{notif.isUnread && <span className="absolute top-4 left-2 w-2 h-2 rounded-full bg-primary shrink-0" />}
<div className="bg-primary/10 p-2 rounded-full shrink-0 ml-2">
<Bell size={16} className="text-primary" />
</div>
<div className="flex-1 min-w-0">
<h4 className="text-sm font-semibold text-foreground">{notif.title}</h4>
<p className="text-xs text-muted-foreground mt-0.5 leading-snug">{notif.message}</p>
</div>
</div>
))
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
<div className="relative" ref={profileRef}>
<button
onClick={() => setProfileOpen(!isProfileOpen)}
className="h-9 w-9 rounded-full bg-gradient-to-tr from-primary flex items-center justify-center font-bold text-white to-accent shadow-md cursor-pointer ring-2 ring-primary/20 transition-all hover:ring-primary/50 overflow-hidden"
>
{userProfile?.avatar_url ? (
<img src={userProfile.avatar_url} alt="Profile" className="h-full w-full object-cover" />
) : (
userProfile?.full_name ? userProfile.full_name.charAt(0).toUpperCase() : "U"
)}
</button>
<AnimatePresence>
{isProfileOpen && (
<motion.div
initial={{ opacity: 0, y: 10, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.95 }}
transition={{ duration: 0.15 }}
className="absolute right-0 mt-3 w-56 rounded-xl border border-border bg-card shadow-lg flex flex-col overflow-hidden z-50 py-1"
>
<div className="px-4 py-3 border-b border-border/50">
<p className="text-sm font-semibold text-foreground truncate">{userProfile?.full_name || "User"}</p>
<p className="text-xs text-muted-foreground truncate leading-tight mt-0.5">{userProfile?.work_email || "user@examcraft.ai"}</p>
</div>
<div className="p-1">
<Link
to="/app/settings"
onClick={() => setProfileOpen(false)}
className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground rounded-md hover:bg-accent/10 hover:text-foreground transition-colors w-full text-left"
>
<Settings size={16} /> Profile Settings
</Link>
<button
onClick={async () => {
await supabase.auth.signOut();
navigate('/login');
}}
className="flex items-center gap-2 px-3 py-2 text-sm text-destructive rounded-md hover:bg-destructive/10 transition-colors w-full text-left mt-1"
>
<LogOut size={16} /> Logout
</button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
</header>
{/* Dynamic Page Content */}
<div className="flex-1 overflow-auto p-4 md:p-8 bg-background relative selection:bg-primary/30">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.3 }}
className="h-full w-full max-w-7xl mx-auto"
>
<Outlet />
</motion.div>
</div>
</main>
{/* Mobile Bottom Navigation (Visible on mobile) */}
<nav className="md:hidden fixed bottom-0 left-0 right-0 border-t border-border bg-card/95 backdrop-blur z-50 flex justify-around p-2 pb-safe">
{navItems.slice(0, 4).map((item) => (
<NavLink
key={item.name}
to={item.path}
end={item.path === "/app"}
className={({ isActive }) => cn(
"flex flex-col items-center p-2 rounded-lg text-xs font-medium space-y-1 transition-colors",
isActive ? "text-primary" : "text-muted-foreground"
)}
>
<item.icon className="h-5 w-5" />
<span>{item.name}</span>
</NavLink>
))}
</nav>
{/* Exam Password Creation Popup */}
<AnimatePresence>
{showPasswordPopup && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-background/80 backdrop-blur-sm flex items-center justify-center p-4"
>
<motion.div
initial={{ scale: 0.95, opacity: 0, y: 20 }}
animate={{ scale: 1, opacity: 1, y: 0 }}
exit={{ scale: 0.95, opacity: 0, y: 20 }}
className="bg-card w-full max-w-md rounded-2xl border border-border shadow-[0_0_40px_rgba(0,0,0,0.1)] relative overflow-hidden"
>
{/* Decorative Top Gradient */}
<div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-primary via-accent to-primary"></div>
<button
onClick={() => setShowPasswordPopup(false)}
className="absolute top-5 right-5 p-2 text-muted-foreground hover:bg-muted rounded-full transition-colors z-10"
>
<X size={18} />
</button>
<div className="px-6 pt-10 pb-6 border-b border-border/40 flex flex-col items-center text-center relative">
<div className="absolute -top-10 -right-10 w-24 h-24 bg-primary/10 rounded-full blur-2xl"></div>
<div className="absolute -bottom-10 -left-10 w-24 h-24 bg-accent/10 rounded-full blur-2xl"></div>
<div className="h-16 w-16 rounded-2xl bg-gradient-to-tr from-primary/20 to-accent/20 flex flex-col items-center justify-center mb-5 text-primary shadow-inner border border-primary/10 relative">
<KeyRound size={32} />
<div className="absolute -bottom-1 -right-1 w-4 h-4 rounded-full bg-emerald-500 border-2 border-card flex items-center justify-center animate-pulse">
</div>
</div>
<h2 className="text-2xl font-bold text-foreground">Set Exam PIN</h2>
<p className="text-sm text-muted-foreground mt-2 max-w-[90%]">
Create a secure <span className="text-foreground font-semibold">6-digit PIN</span> to protect your generated resources and control exam sessions.
</p>
</div>
<form onSubmit={handleSavePassword} className="p-6 space-y-5 bg-muted/10">
{passwordError && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
className="p-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-start gap-2 shadow-sm"
>
<AlertCircle size={16} className="shrink-0 mt-0.5" />
<span>{passwordError}</span>
</motion.div>
)}
<div className="space-y-4">
<div className="group">
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 group-focus-within:text-primary transition-colors">6-Digit PIN</label>
<input
type="password"
required
maxLength={6}
value={examPassword}
onChange={(e) => setExamPassword(e.target.value.replace(/\D/g, ''))}
className="w-full h-12 rounded-xl border border-input bg-background/50 backdrop-blur-sm px-4 text-center text-2xl font-mono tracking-[0.5em] placeholder:tracking-normal placeholder:text-sm placeholder:text-center shadow-sm focus:bg-background focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all disabled:opacity-50"
placeholder="••••••"
/>
</div>
<div className="group">
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 group-focus-within:text-primary transition-colors">Confirm PIN</label>
<input
type="password"
required
maxLength={6}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value.replace(/\D/g, ''))}
className="w-full h-12 rounded-xl border border-input bg-background/50 backdrop-blur-sm px-4 text-center text-2xl font-mono tracking-[0.5em] placeholder:tracking-normal placeholder:text-sm placeholder:text-center shadow-sm focus:bg-background focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all disabled:opacity-50"
placeholder="••••••"
/>
</div>
</div>
<div className="pt-4">
<button
type="submit"
disabled={isSavingPassword || examPassword.length !== 6 || confirmPassword.length !== 6}
className="w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 text-primary-foreground shadow-md h-12 rounded-xl flex items-center justify-center text-sm font-bold transition-all disabled:opacity-50 disabled:pointer-events-none hover:shadow-lg hover:-translate-y-0.5"
>
{isSavingPassword ? (
<div className="flex items-center gap-2">
<div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
<span>Saving Securely...</span>
</div>
) : "Save Exam PIN"}
</button>
</div>
</form>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}