This commit is contained in:
Marcelo
2026-02-17 00:07:00 +00:00
parent b7a86a2d1c
commit be4ca2ed78
92 changed files with 6850 additions and 1188 deletions

127
components/AssistantDrawer.tsx Normal file → Executable file
View File

@@ -1,6 +1,11 @@
"use client";
import { FormEvent, useEffect, useMemo, useState } from "react";
import { SubmitEvent, useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter } from "@/components/ui/sheet";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
type AssistantMessage = {
id: string;
@@ -25,6 +30,14 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
]);
const [input, setInput] = useState("");
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [messages]);
useEffect(() => {
if (mode === "page") {
return;
@@ -35,17 +48,7 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
return () => window.removeEventListener(ASSISTANT_TOGGLE_EVENT, onToggle);
}, [mode]);
const panelClasses = useMemo(() => {
if (mode === "page") {
return "mx-auto flex h-[70vh] max-w-3xl flex-col rounded-2xl border border-slate-300 bg-white shadow-xl";
}
return `fixed right-0 top-0 z-50 h-screen w-full max-w-md border-l border-slate-300 bg-white shadow-2xl transition-transform ${
isOpen ? "translate-x-0" : "translate-x-full"
}`;
}, [isOpen, mode]);
const send = (event: FormEvent) => {
const send = (event: SubmitEvent) => {
event.preventDefault();
const trimmed = input.trim();
if (!trimmed) return;
@@ -59,57 +62,65 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
setInput("");
};
if (mode === "global" && !isOpen) {
const ChatContent = (
<div className="flex h-full flex-col">
<ScrollArea className="flex-1 p-4">
<div className="space-y-4">
{messages.map((message) => (
<div
key={message.id}
className={`max-w-[90%] rounded-lg px-3 py-2 text-sm ${message.role === "user"
? "ml-auto bg-primary text-primary-foreground"
: "mr-auto border border-border bg-muted text-foreground"
}`}
>
{message.content}
</div>
))}
<div ref={scrollRef} />
</div>
</ScrollArea>
<SheetFooter className="mt-auto border-t bg-background p-4 sm:flex-col">
<form className="w-full" onSubmit={send}>
<div className="flex gap-2">
<Input
className="flex-1"
onChange={(event) => setInput(event.target.value)}
placeholder="Type your message..."
value={input}
/>
<Button type="submit">Send</Button>
</div>
</form>
</SheetFooter>
</div>
);
if (mode === "page") {
return (
<aside className={panelClasses}>
<div />
</aside>
<Card className="mx-auto flex h-[68vh] max-w-4xl flex-col shadow-xl">
<CardHeader className="border-b px-4 py-3">
<CardTitle className="text-2xl text-primary font-serif">AI Assistant</CardTitle>
</CardHeader>
<CardContent className="flex-1 p-0 overflow-hidden">
{ChatContent}
</CardContent>
</Card>
);
}
return (
<aside className={panelClasses}>
<div className="flex items-center justify-between border-b border-slate-200 px-4 py-3">
<h2 className="acve-heading text-2xl">AI Assistant</h2>
{mode === "global" ? (
<button
className="rounded-md border border-slate-300 px-2 py-1 text-sm text-slate-600 hover:bg-slate-50"
onClick={() => setIsOpen(false)}
type="button"
>
Close
</button>
) : null}
</div>
<div className="flex-1 space-y-3 overflow-y-auto p-4">
{messages.map((message) => (
<div
key={message.id}
className={`max-w-[90%] rounded-lg px-3 py-2 text-sm ${
message.role === "user"
? "ml-auto bg-brand text-white"
: "mr-auto border border-slate-200 bg-slate-50 text-slate-800"
}`}
>
{message.content}
</div>
))}
</div>
<form className="border-t border-slate-200 p-3" onSubmit={send}>
<div className="flex gap-2">
<input
className="flex-1 rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
onChange={(event) => setInput(event.target.value)}
placeholder="Type your message..."
value={input}
/>
<button className="rounded-md bg-brand px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Send
</button>
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetContent className="flex w-full flex-col p-0 sm:max-w-md">
<SheetHeader className="px-4 py-3 border-b">
<SheetTitle className="text-primary font-serif">AI Assistant</SheetTitle>
<SheetDescription className="sr-only">Chat with our AI assistant</SheetDescription>
</SheetHeader>
<div className="flex-1 overflow-hidden">
{ChatContent}
</div>
</form>
</aside>
</SheetContent>
</Sheet>
);
}

123
components/CourseCard.tsx Normal file → Executable file
View File

@@ -1,43 +1,104 @@
import Link from "next/link";
import type { Course } from "@/types/course";
import type { Prisma } from "@prisma/client";
import ProgressBar from "@/components/ProgressBar";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
type PublicCourseCardCourse = Prisma.CourseGetPayload<{
include: {
author: {
select: {
fullName: true;
};
};
modules: {
select: {
_count: {
select: {
lessons: true;
};
};
};
};
_count: {
select: {
enrollments: true;
};
};
};
}>;
type CourseCardProps = {
course: Course;
course: PublicCourseCardCourse;
progress?: number;
};
export default function CourseCard({ course, progress = 0 }: CourseCardProps) {
return (
<Link
href={`/courses/${course.slug}`}
className="group flex h-full flex-col justify-between rounded-2xl border border-slate-300 bg-white p-6 shadow-sm transition hover:-translate-y-0.5 hover:border-brand/60"
>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="rounded-full bg-[#ead7a0] px-3 py-1 text-xs font-semibold text-[#8a6b00]">{course.level}</span>
<span className="text-sm font-semibold text-slate-700">Rating {course.rating.toFixed(1)}</span>
</div>
<h3 className="text-2xl leading-tight text-[#212937] md:text-4xl">{course.title}</h3>
<p className="text-base text-slate-600 md:text-lg">{course.summary}</p>
</div>
const levelBadgeClass = (level: PublicCourseCardCourse["level"]) => {
if (level === "BEGINNER") return "bg-emerald-100 text-emerald-900 border border-emerald-200";
if (level === "INTERMEDIATE") return "bg-sky-100 text-sky-900 border border-sky-200";
return "bg-violet-100 text-violet-900 border border-violet-200";
};
<div className="mt-5 border-t border-slate-200 pt-4 text-base text-slate-600 md:text-lg">
{progress > 0 ? (
<div className="mb-4">
<ProgressBar value={progress} label={`Progress ${progress}%`} />
const levelLabel = (level: PublicCourseCardCourse["level"]) => {
if (level === "BEGINNER") return "Beginner";
if (level === "INTERMEDIATE") return "Intermediate";
return "Advanced";
};
const getText = (value: unknown): string => {
if (!value) return "";
if (typeof value === "string") return value;
if (typeof value === "object") {
const record = value as Record<string, unknown>;
if (typeof record.en === "string") return record.en;
if (typeof record.es === "string") return record.es;
}
return "";
};
export default function CourseCard({ course, progress = 0 }: CourseCardProps) {
const lessonsCount = course.modules.reduce((total, module) => total + module._count.lessons, 0);
const title = getText(course.title) || "Untitled course";
const summary = getText(course.description) || "Course details will be published soon.";
const instructor = course.author.fullName || "ACVE Team";
return (
<Link href={`/courses/${course.slug}`} className="group block h-full">
<Card className="h-full border-border hover:-translate-y-0.5 hover:border-primary/60 transition-all duration-200">
<CardHeader className="space-y-3 pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge variant="secondary" className={levelBadgeClass(course.level)}>
{levelLabel(course.level)}
</Badge>
<Badge variant="outline">{course.status.toLowerCase()}</Badge>
</div>
<span className="text-sm font-semibold text-muted-foreground">{lessonsCount} lessons</span>
</div>
) : null}
<div className="mb-1 flex items-center justify-between">
<span>{course.weeks} weeks</span>
<span>{course.lessonsCount} lessons</span>
</div>
<div className="mb-3 flex items-center justify-between">
<span>{course.students.toLocaleString()} students</span>
<span className="text-brand transition-transform group-hover:translate-x-1">{">"}</span>
</div>
<div className="text-sm font-semibold text-slate-700 md:text-base">By {course.instructor}</div>
</div>
<CardTitle className="text-[1.85rem] leading-tight md:text-[2rem]">{title}</CardTitle>
<CardDescription className="text-base leading-relaxed">{summary}</CardDescription>
</CardHeader>
<CardContent className="pt-4 text-base text-muted-foreground">
{progress > 0 ? (
<div className="mb-4">
<ProgressBar value={progress} label={`Progress ${progress}%`} />
</div>
) : null}
<div className="mb-1 flex items-center justify-between">
<span>{course._count.enrollments.toLocaleString()} enrolled</span>
<span>{lessonsCount} lessons</span>
</div>
</CardContent>
<CardFooter className="flex items-center justify-between border-t bg-muted/50 px-6 py-4 text-sm text-muted-foreground">
<span>By {instructor}</span>
<div className="flex items-center gap-2">
<span className="font-semibold text-primary">View Course</span>
<span className="text-primary opacity-0 transition-opacity group-hover:opacity-100">{">"}</span>
</div>
</CardFooter>
</Card>
</Link>
);
}

6
components/Footer.tsx Normal file → Executable file
View File

@@ -1,8 +1,8 @@
export default function Footer() {
return (
<footer className="border-t border-slate-300 bg-[#f7f7f8]">
<div className="mx-auto flex w-full max-w-[1300px] items-center justify-between px-4 py-5 text-sm text-slate-600">
<span>ACVE Centro de Estudios</span>
<footer className="border-t bg-muted/30">
<div className="mx-auto flex w-full max-w-[1300px] items-center justify-between px-4 py-6 text-sm text-muted-foreground">
<span className="font-medium">ACVE Centro de Estudios</span>
<span>Professional legal English learning</span>
</div>
</footer>

52
components/LessonRow.tsx Normal file → Executable file
View File

@@ -1,4 +1,7 @@
import type { Lesson } from "@/types/course";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
type LessonRowProps = {
index: number;
@@ -9,47 +12,54 @@ type LessonRowProps = {
};
const typeColors: Record<Lesson["type"], string> = {
video: "bg-[#ffecee] text-[#ca4d6f]",
reading: "bg-[#ecfbf4] text-[#2f9d73]",
interactive: "bg-[#eef4ff] text-[#6288da]",
video: "bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400",
reading: "bg-green-50 text-green-600 dark:bg-green-900/20 dark:text-green-400",
interactive: "bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400",
};
export default function LessonRow({ index, lesson, isActive, isLocked, onSelect }: LessonRowProps) {
return (
<button
className={`w-full rounded-2xl border p-5 text-left transition ${
isActive ? "border-brand/60 bg-white shadow-sm" : "border-slate-200 bg-white hover:border-slate-300"
} ${isLocked ? "cursor-not-allowed opacity-60" : ""}`}
<Button
variant="ghost"
className={cn(
"group h-auto w-full justify-start whitespace-normal rounded-2xl border p-5 text-left transition-all hover:bg-accent/50",
isActive
? "border-primary/60 bg-background shadow-sm ring-1 ring-primary/20"
: "border-border bg-background hover:border-border/80",
isLocked && "cursor-not-allowed opacity-60 hover:bg-transparent"
)}
onClick={isLocked ? undefined : onSelect}
type="button"
disabled={isLocked && !isActive}
>
<div className="flex items-center gap-4">
<div className="flex w-full items-center gap-4">
<div
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border text-lg font-semibold ${
isActive ? "border-brand text-brand" : "border-slate-300 text-slate-500"
}`}
className={cn(
"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border text-lg font-semibold transition-colors",
isActive ? "border-primary text-primary" : "border-input text-muted-foreground group-hover:border-primary/40 group-hover:text-foreground"
)}
>
{isLocked ? "L" : index + 1}
</div>
<div className="min-w-0 flex-1">
<div className="mb-1 flex flex-wrap items-center gap-2 text-sm text-slate-500">
<span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${typeColors[lesson.type]}`}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<Badge variant="outline" className={cn("rounded-full border-0 px-2.5 py-0.5 font-semibold capitalize", typeColors[lesson.type])}>
{lesson.type}
</span>
</Badge>
<span>{lesson.minutes} min</span>
{isLocked ? <span className="text-slate-400">Locked</span> : null}
{lesson.isPreview ? <span className="text-[#8a6b00]">Preview</span> : null}
{isLocked ? <span className="text-muted-foreground/70">Locked</span> : null}
{lesson.isPreview ? <span className="text-yellow-600 dark:text-yellow-400">Preview</span> : null}
</div>
<p className="truncate text-lg text-[#222a38] md:text-2xl">{lesson.title}</p>
<p className="truncate text-lg font-medium text-foreground md:text-2xl">{lesson.title}</p>
</div>
{isActive ? (
<div className="hidden h-20 w-36 overflow-hidden rounded-xl border border-slate-200 bg-[#202020] md:block">
<div className="flex h-full items-center justify-center text-2xl text-white/80">Play</div>
<div className="hidden h-20 w-36 overflow-hidden rounded-xl border border-border bg-muted md:block">
<div className="flex h-full items-center justify-center text-2xl text-muted-foreground/80">Play</div>
</div>
) : null}
</div>
</button>
</Button>
);
}

142
components/Navbar.tsx Normal file → Executable file
View File

@@ -2,10 +2,15 @@
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { ASSISTANT_TOGGLE_EVENT } from "@/components/AssistantDrawer";
import { DEMO_AUTH_EMAIL_COOKIE, DEMO_AUTH_ROLE_COOKIE } from "@/lib/auth/demoAuth";
import { isTeacherEmailAllowed, readTeacherEmailsBrowser } from "@/lib/auth/teacherAllowlist";
import { supabaseBrowser } from "@/lib/supabase/browser";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type NavLink = {
href: string;
@@ -21,105 +26,162 @@ const navLinks: NavLink[] = [
export default function Navbar() {
const pathname = usePathname();
const router = useRouter();
const [userEmail, setUserEmail] = useState<string | null>(null);
const [isTeacher, setIsTeacher] = useState(false);
const linkClass = (href: string) =>
pathname === href || pathname?.startsWith(`${href}/`)
? "rounded-xl bg-brand px-5 py-3 text-sm font-semibold text-white shadow-sm"
: "rounded-xl px-5 py-3 text-sm font-semibold text-slate-700 transition-colors hover:text-brand";
const teacherEmails = useMemo(() => readTeacherEmailsBrowser(), []);
useEffect(() => {
const client = supabaseBrowser();
if (!client) return;
if (!client) {
const cookieMap = new Map(
document.cookie
.split(";")
.map((entry) => entry.trim())
.filter(Boolean)
.map((entry) => {
const [key, ...rest] = entry.split("=");
return [key, decodeURIComponent(rest.join("="))] as const;
}),
);
const email = cookieMap.get(DEMO_AUTH_EMAIL_COOKIE) ?? null;
const role = cookieMap.get(DEMO_AUTH_ROLE_COOKIE) ?? "";
setUserEmail(email);
setIsTeacher(role === "teacher" || isTeacherEmailAllowed(email, teacherEmails));
return;
}
let mounted = true;
client.auth.getUser().then(({ data }) => {
if (!mounted) return;
setUserEmail(data.user?.email ?? null);
const email = data.user?.email ?? null;
setUserEmail(email);
setIsTeacher(isTeacherEmailAllowed(email, teacherEmails));
});
const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserEmail(session?.user?.email ?? null);
const email = session?.user?.email ?? null;
setUserEmail(email);
setIsTeacher(isTeacherEmailAllowed(email, teacherEmails));
});
return () => {
mounted = false;
data.subscription.unsubscribe();
};
}, []);
}, [teacherEmails]);
const links = useMemo(() => {
if (!isTeacher) return navLinks;
return [...navLinks, { href: "/teacher", label: "Teacher Dashboard" }];
}, [isTeacher]);
const authNode = useMemo(() => {
if (!userEmail) {
return (
<div className="flex items-center gap-2 text-sm">
<Link className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50" href="/auth/login">
Login
</Link>
<Link className="rounded-lg bg-brand px-3 py-1.5 text-white hover:brightness-105" href="/auth/signup">
Sign up
</Link>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" asChild>
<Link href="/auth/login">Login</Link>
</Button>
<Button size="sm" asChild>
<Link href="/auth/signup">Sign up</Link>
</Button>
</div>
);
}
return (
<div className="flex items-center gap-2 text-sm">
<span className="max-w-36 truncate text-slate-700">{userEmail}</span>
<button
className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50"
<span className="hidden max-w-36 truncate text-muted-foreground sm:inline-block">{userEmail}</span>
{!isTeacher ? (
<Link
className="inline-flex items-center rounded-md border border-amber-300 bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-900"
href="/auth/login?role=teacher"
>
Teacher area (Teacher only)
</Link>
) : null}
<Button
variant="outline"
size="sm"
onClick={async () => {
const client = supabaseBrowser();
if (!client) return;
if (!client) {
document.cookie = `${DEMO_AUTH_EMAIL_COOKIE}=; path=/; max-age=0`;
document.cookie = `${DEMO_AUTH_ROLE_COOKIE}=; path=/; max-age=0`;
setUserEmail(null);
setIsTeacher(false);
router.refresh();
return;
}
await client.auth.signOut();
}}
type="button"
>
Logout
</button>
</Button>
</div>
);
}, [userEmail]);
}, [isTeacher, router, userEmail]);
return (
<header className="sticky top-0 z-40 border-b border-slate-300 bg-[#f7f7f8]/95 backdrop-blur">
<header className="sticky top-0 z-40 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="mx-auto flex w-full max-w-[1300px] items-center justify-between gap-4 px-4 py-3">
<div className="flex items-center gap-8">
<Link className="flex items-center gap-3" href="/">
<div className="rounded-xl bg-[#edd7bc] p-1.5 shadow-sm">
<div className="rounded-xl bg-accent p-1.5 shadow-sm">
<Image alt="ACVE logo" className="h-10 w-10 rounded-lg object-cover" height={40} src="/images/logo.png" width={40} />
</div>
<div>
<div className="text-2xl font-bold leading-none tracking-tight text-brand md:text-4xl">ACVE</div>
<div className="-mt-1 text-xs text-slate-500 md:text-sm">Centro de Estudios</div>
<div className="text-2xl font-bold leading-none tracking-tight text-primary md:text-4xl">ACVE</div>
<div className="-mt-1 text-xs text-muted-foreground md:text-sm">Centro de Estudios</div>
</div>
</Link>
<nav className="hidden items-center gap-1 text-sm lg:flex">
{navLinks.map((link) => (
<Link key={link.href} className={linkClass(link.href)} href={link.href}>
{link.label}
</Link>
))}
{links.map((link) => {
const isActive = pathname === link.href || pathname?.startsWith(`${link.href}/`);
return (
<Button
key={link.href}
variant={isActive ? "default" : "ghost"}
asChild
className={cn("rounded-xl text-sm font-semibold", !isActive && "text-muted-foreground hover:text-primary")}
>
<Link href={link.href}>{link.label}</Link>
</Button>
);
})}
</nav>
</div>
<div className="flex items-center gap-2">
<button
className="rounded-xl border border-accent bg-white px-4 py-2.5 text-sm font-semibold text-accent hover:bg-amber-50"
<Button
variant="outline"
className="border-primary/20 text-primary hover:bg-primary/5 hover:text-primary"
onClick={() => window.dispatchEvent(new Event(ASSISTANT_TOGGLE_EVENT))}
type="button"
>
AI Assistant
</button>
</Button>
{authNode}
</div>
</div>
<nav className="mx-auto flex w-full max-w-[1300px] gap-2 overflow-x-auto px-4 pb-3 text-sm lg:hidden">
{navLinks.map((link) => (
<Link key={link.href} className={linkClass(link.href)} href={link.href}>
{link.label}
</Link>
))}
{links.map((link) => {
const isActive = pathname === link.href;
return (
<Button
key={link.href}
variant={isActive ? "default" : "ghost"}
size="sm"
asChild
className="whitespace-nowrap rounded-xl"
>
<Link href={link.href}>{link.label}</Link>
</Button>
);
})}
</nav>
</header>
);

6
components/ProgressBar.tsx Normal file → Executable file
View File

@@ -8,9 +8,9 @@ export default function ProgressBar({ value, label }: ProgressBarProps) {
return (
<div className="w-full">
{label ? <div className="mb-1 text-xs font-semibold text-slate-600">{label}</div> : null}
<div className="h-2.5 w-full rounded-full bg-[#ececef]">
<div className="h-2.5 rounded-full bg-brand transition-all" style={{ width: `${clamped}%` }} />
{label ? <div className="mb-1 text-xs font-semibold text-muted-foreground">{label}</div> : null}
<div className="h-2.5 w-full rounded-full bg-secondary">
<div className="h-2.5 rounded-full bg-primary transition-all" style={{ width: `${clamped}%` }} />
</div>
</div>
);

31
components/Tabs.tsx Normal file → Executable file
View File

@@ -1,3 +1,5 @@
import { Tabs as TabsPrimitive, TabsList, TabsTrigger } from "@/components/ui/tabs";
type TabsProps<T extends string> = {
options: readonly T[];
active: T;
@@ -6,21 +8,18 @@ type TabsProps<T extends string> = {
export default function Tabs<T extends string>({ options, active, onChange }: TabsProps<T>) {
return (
<div className="inline-flex flex-wrap gap-2">
{options.map((option) => (
<button
key={option}
className={`rounded-xl border px-6 py-3 text-base font-semibold transition-colors ${
option === active
? "border-accent bg-accent text-white shadow-sm"
: "border-slate-300 bg-white text-slate-700 hover:border-slate-400"
}`}
onClick={() => onChange(option)}
type="button"
>
{option}
</button>
))}
</div>
<TabsPrimitive value={active} onValueChange={(v) => onChange(v as T)}>
<TabsList className="h-auto gap-2 bg-transparent p-0">
{options.map((option) => (
<TabsTrigger
key={option}
value={option}
className="rounded-xl border border-input bg-background px-4 py-2 text-sm font-semibold text-slate-700 data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm md:px-5 md:py-2.5"
>
{option}
</TabsTrigger>
))}
</TabsList>
</TabsPrimitive>
);
}

123
components/auth/LoginForm.tsx Normal file → Executable file
View File

@@ -1,95 +1,152 @@
"use client";
import { createBrowserClient } from "@supabase/ssr";
import { FormEvent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { supabaseBrowser } from "@/lib/supabase/browser";
type LoginFormProps = {
redirectTo: string;
role?: string;
showForgot?: boolean;
};
// Helper to prevent open redirect vulnerabilities
const normalizeRedirect = (redirectTo: string) => {
if (!redirectTo.startsWith("/")) return "/courses";
return redirectTo;
if (redirectTo.startsWith("/") && !redirectTo.startsWith("//")) {
return redirectTo;
}
return "/home"; // Default fallback
};
export default function LoginForm({ redirectTo }: LoginFormProps) {
export default function LoginForm({ redirectTo, role, showForgot }: LoginFormProps) {
const router = useRouter();
const safeRedirect = normalizeRedirect(redirectTo);
const isTeacher = role === "teacher";
const showForgotNotice = Boolean(showForgot);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
// Construct the "Forgot Password" link to preserve context
const forgotHref = `/auth/login?redirectTo=${encodeURIComponent(safeRedirect)}${isTeacher ? "&role=teacher" : ""
}&forgot=1`;
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
setError(null);
setLoading(true);
const client = supabaseBrowser();
if (!client) {
setLoading(false);
setError("Supabase is not configured. Add NEXT_PUBLIC_SUPABASE_* to .env.local.");
return;
}
// 1. Initialize the Supabase Client (Browser side)
const supabase = createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
const { error: signInError } = await client.auth.signInWithPassword({ email, password });
setLoading(false);
// 2. Attempt Real Login
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
});
if (signInError) {
setError(signInError.message);
setLoading(false);
setError(signInError.message); // e.g. "Invalid login credentials"
return;
}
// 3. CRITICAL: Refresh the Server Context
// This forces Next.js to re-run the Middleware and Server Components
// so they see the new cookie immediately.
router.refresh();
// 4. Navigate to the protected page
router.push(safeRedirect);
};
return (
<div className="acve-panel mx-auto w-full max-w-md p-6">
<h1 className="acve-heading text-4xl">Login</h1>
<p className="mt-1 text-base text-slate-600">Sign in to access protected learning routes.</p>
<div className="acve-panel mx-auto w-full max-w-md p-6 bg-white rounded-xl shadow-sm border border-slate-200">
<h1 className="text-3xl font-bold text-slate-900 mb-2">
{isTeacher ? "Acceso Profesores" : "Iniciar Sesión"}
</h1>
<p className="text-slate-600 mb-6">
{isTeacher
? "Gestiona tus cursos y estudiantes."
: "Ingresa para continuar aprendiendo."}
</p>
<form className="mt-5 space-y-4" onSubmit={onSubmit}>
{showForgotNotice && (
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
El restablecimiento de contraseña no está disponible en este momento. Contacta a soporte.
</div>
)}
<form className="space-y-4" onSubmit={onSubmit}>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Email</span>
<span className="mb-1 block text-sm font-medium text-slate-700">Email</span>
<input
className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setEmail(event.target.value)}
className="w-full rounded-lg border border-slate-300 px-3 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all"
onChange={(e) => setEmail(e.target.value)}
required
type="email"
value={email}
placeholder="tu@email.com"
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Password</span>
<span className="mb-1 block text-sm font-medium text-slate-700">Contraseña</span>
<input
className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setPassword(event.target.value)}
className="w-full rounded-lg border border-slate-300 px-3 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all"
onChange={(e) => setPassword(e.target.value)}
required
type="password"
value={password}
placeholder="••••••••"
/>
</label>
{error ? <p className="text-sm text-red-600">{error}</p> : null}
{error && (
<div className="rounded-md bg-red-50 p-3 text-sm text-red-600 border border-red-100">
{error}
</div>
)}
<button
className="acve-button-primary w-full px-4 py-2 font-semibold hover:brightness-105 disabled:opacity-60"
className="w-full rounded-lg bg-black px-4 py-2.5 font-semibold text-white hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
disabled={loading}
type="submit"
>
{loading ? "Signing in..." : "Login"}
{loading ? "Entrando..." : "Entrar"}
</button>
</form>
<p className="mt-4 text-sm text-slate-600">
New here?{" "}
<Link className="font-semibold text-brand" href="/auth/signup">
Create an account
</Link>
</p>
<div className="mt-6 space-y-2 text-center text-sm text-slate-600">
<div>
<Link className="font-semibold text-black hover:underline" href={forgotHref}>
¿Olvidaste tu contraseña?
</Link>
</div>
<div>
¿Nuevo aquí?{" "}
<Link className="font-semibold text-black hover:underline" href="/auth/signup">
Crear cuenta
</Link>
</div>
{!isTeacher && (
<div className="pt-2 border-t border-slate-100 mt-4">
¿Eres profesor?{" "}
<Link
className="font-semibold text-black hover:underline"
href={`/auth/login?role=teacher&redirectTo=${encodeURIComponent(safeRedirect)}`}
>
Ingresa aquí
</Link>
</div>
)}
</div>
</div>
);
}
}

View File

@@ -0,0 +1,218 @@
"use client";
import { useEffect, useMemo, useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Check, Lock, PlayCircle } from "lucide-react";
import { toggleLessonComplete } from "@/app/(protected)/courses/[slug]/learn/actions";
import ProgressBar from "@/components/ProgressBar";
type ClassroomLesson = {
id: string;
title: string;
description: string;
videoUrl: string | null;
estimatedDuration: number;
};
type ClassroomModule = {
id: string;
title: string;
lessons: ClassroomLesson[];
};
type StudentClassroomClientProps = {
courseSlug: string;
courseTitle: string;
modules: ClassroomModule[];
initialSelectedLessonId: string;
initialCompletedLessonIds: string[];
};
export default function StudentClassroomClient({
courseSlug,
courseTitle,
modules,
initialSelectedLessonId,
initialCompletedLessonIds,
}: StudentClassroomClientProps) {
const router = useRouter();
const [isSaving, startTransition] = useTransition();
const [selectedLessonId, setSelectedLessonId] = useState(initialSelectedLessonId);
const [completedLessonIds, setCompletedLessonIds] = useState(initialCompletedLessonIds);
useEffect(() => {
setSelectedLessonId(initialSelectedLessonId);
}, [initialSelectedLessonId]);
useEffect(() => {
setCompletedLessonIds(initialCompletedLessonIds);
}, [initialCompletedLessonIds]);
const flatLessons = useMemo(() => modules.flatMap((module) => module.lessons), [modules]);
const completedSet = useMemo(() => new Set(completedLessonIds), [completedLessonIds]);
const totalLessons = flatLessons.length;
const completedCount = completedLessonIds.length;
const progressPercent = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;
const selectedLesson =
flatLessons.find((lesson) => lesson.id === selectedLessonId) ?? flatLessons[0] ?? null;
const isRestricted = (lessonId: string) => {
const lessonIndex = flatLessons.findIndex((lesson) => lesson.id === lessonId);
if (lessonIndex <= 0) return false;
if (completedSet.has(lessonId)) return false;
const previousLesson = flatLessons[lessonIndex - 1];
return !completedSet.has(previousLesson.id);
};
const navigateToLesson = (lessonId: string) => {
if (isRestricted(lessonId)) return;
setSelectedLessonId(lessonId);
router.push(`/courses/${courseSlug}/learn?lesson=${lessonId}`, { scroll: false });
};
const handleToggleComplete = async () => {
if (!selectedLesson || isSaving) return;
const lessonId = selectedLesson.id;
const wasCompleted = completedSet.has(lessonId);
setCompletedLessonIds((prev) =>
wasCompleted ? prev.filter((id) => id !== lessonId) : [...prev, lessonId],
);
startTransition(async () => {
const result = await toggleLessonComplete({ courseSlug, lessonId });
if (!result.success) {
setCompletedLessonIds((prev) =>
wasCompleted ? [...prev, lessonId] : prev.filter((id) => id !== lessonId),
);
return;
}
setCompletedLessonIds((prev) => {
if (result.isCompleted) {
return prev.includes(lessonId) ? prev : [...prev, lessonId];
}
return prev.filter((id) => id !== lessonId);
});
router.refresh();
});
};
if (!selectedLesson) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6">
<h1 className="text-2xl font-semibold text-slate-900">No lessons available yet</h1>
<p className="mt-2 text-sm text-slate-600">This course does not have lessons configured.</p>
</div>
);
}
return (
<div className="grid gap-6 lg:grid-cols-[1.7fr_1fr]">
<section className="space-y-4 rounded-xl border border-slate-200 bg-white p-5">
<Link href={`/courses/${courseSlug}`} className="text-sm font-medium text-slate-600 hover:text-slate-900">
{"<-"} Back to Course
</Link>
<div className="aspect-video overflow-hidden rounded-xl border border-slate-200 bg-black">
{selectedLesson.videoUrl ? (
<video
key={`${selectedLesson.id}-${selectedLesson.videoUrl}`}
className="h-full w-full"
controls
onEnded={handleToggleComplete}
src={selectedLesson.videoUrl}
/>
) : (
<div className="flex h-full items-center justify-center text-sm text-slate-300">
Video not available for this lesson
</div>
)}
</div>
<div className="space-y-2 rounded-xl border border-slate-200 bg-white p-4">
<h1 className="text-2xl font-semibold text-slate-900">{selectedLesson.title}</h1>
{selectedLesson.description ? (
<p className="text-sm text-slate-600">{selectedLesson.description}</p>
) : null}
<p className="text-xs text-slate-500">
Duration: {Math.max(1, Math.ceil(selectedLesson.estimatedDuration / 60))} min
</p>
</div>
<button
type="button"
onClick={handleToggleComplete}
disabled={isSaving}
className="rounded-md border border-slate-300 bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-60"
>
{completedSet.has(selectedLesson.id) ? "Mark as Incomplete" : "Mark as Complete"}
</button>
</section>
<aside className="rounded-xl border border-slate-200 bg-white p-4">
<h2 className="mb-3 text-lg font-semibold text-slate-900">Course Content</h2>
<p className="mb-3 text-xs text-slate-500">{courseTitle}</p>
<div className="mb-4">
<ProgressBar
value={progressPercent}
label={`${completedCount}/${totalLessons} lessons (${progressPercent}%)`}
/>
</div>
<div className="max-h-[70vh] space-y-4 overflow-y-auto pr-1">
{modules.map((module, moduleIndex) => (
<div key={module.id} className="rounded-xl border border-slate-200 bg-slate-50/40">
<div className="border-b border-slate-200 px-3 py-2">
<p className="text-sm font-semibold text-slate-800">
Module {moduleIndex + 1}: {module.title}
</p>
</div>
<div className="space-y-1 p-2">
{module.lessons.map((lesson, lessonIndex) => {
const completed = completedSet.has(lesson.id);
const restricted = isRestricted(lesson.id);
const active = lesson.id === selectedLesson.id;
return (
<button
key={lesson.id}
type="button"
disabled={restricted}
onClick={() => navigateToLesson(lesson.id)}
className={`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left text-sm transition-colors ${
active
? "border-slate-300 bg-white text-slate-900"
: "border-transparent bg-white/70 text-slate-700 hover:border-slate-200"
} ${restricted ? "cursor-not-allowed opacity-60 hover:border-transparent" : ""}`}
>
<span className="inline-flex h-5 w-5 items-center justify-center">
{completed ? (
<Check className="h-4 w-4 text-emerald-600" />
) : restricted ? (
<Lock className="h-4 w-4 text-slate-400" />
) : (
<PlayCircle className="h-4 w-4 text-slate-500" />
)}
</span>
<span className="line-clamp-1">
{lessonIndex + 1}. {lesson.title}
</span>
</button>
);
})}
</div>
</div>
))}
</div>
</aside>
</div>
);
}

45
components/teacher/TeacherDashboardClient.tsx Normal file → Executable file
View File

@@ -15,6 +15,13 @@ export default function TeacherDashboardClient() {
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []);
const totalLessons = courses.reduce((sum, course) => sum + course.lessons.length, 0);
const totalStudents = courses.reduce((sum, course) => sum + course.students, 0);
const averageRating =
courses.length === 0 ? 0 : courses.reduce((sum, course) => sum + course.rating, 0) / courses.length;
const publishedCount = courses.filter((course) => course.status === "Published").length;
const draftCount = courses.filter((course) => course.status === "Draft").length;
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-3">
@@ -22,14 +29,39 @@ export default function TeacherDashboardClient() {
<h1 className="text-3xl font-bold text-slate-900">Teacher Dashboard</h1>
<p className="text-slate-600">Manage teacher-created courses stored locally for MVP.</p>
</div>
<Link
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
href="/teacher/courses/new"
>
Create course
</Link>
<div className="flex gap-2">
<Link
className="rounded-md border border-slate-300 px-4 py-2 text-sm font-semibold hover:bg-slate-50"
href="/teacher/uploads"
>
Upload library
</Link>
<Link
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
href="/teacher/courses/new"
>
Create course
</Link>
</div>
</div>
<section className="grid gap-4 sm:grid-cols-3">
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Courses</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{courses.length}</p>
<p className="mt-1 text-xs text-slate-500">Published: {publishedCount} | Draft: {draftCount}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lessons</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{totalLessons}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg. rating</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{averageRating.toFixed(1)}</p>
<p className="mt-1 text-xs text-slate-500">Students tracked: {totalStudents}</p>
</article>
</section>
{courses.length === 0 ? (
<div className="rounded-xl border border-dashed border-slate-300 bg-white p-6 text-sm text-slate-600">
No teacher-created courses yet.
@@ -41,6 +73,7 @@ export default function TeacherDashboardClient() {
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{course.level}</p>
<p className="mt-1 text-xs font-semibold uppercase tracking-wide text-slate-500">{course.status}</p>
<h2 className="text-xl font-semibold text-slate-900">{course.title}</h2>
<p className="mt-1 text-sm text-slate-600">{course.summary}</p>
</div>

493
components/teacher/TeacherEditCourseForm.tsx Normal file → Executable file
View File

@@ -1,176 +1,373 @@
// components/teacher/TeacherEditCourseForm.tsx
"use client";
import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import {
updateCourse,
createModule,
createLesson,
reorderModules,
reorderLessons,
} from "@/app/(protected)/teacher/actions";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { getTeacherCourseBySlug, teacherCoursesUpdatedEventName, updateTeacherCourse } from "@/lib/data/teacherCourses";
import type { Course, CourseLevel } from "@/types/course";
import Link from "next/link";
import { toast } from "sonner";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];
import { Prisma } from "@prisma/client";
type TeacherEditCourseFormProps = {
type CourseData = {
id: string;
slug: string;
title: Prisma.JsonValue;
description: Prisma.JsonValue;
level: string;
status: string;
price: number;
modules: {
id: string;
title: Prisma.JsonValue;
lessons: { id: string; title: Prisma.JsonValue }[];
}[];
};
export default function TeacherEditCourseForm({ slug }: TeacherEditCourseFormProps) {
export default function TeacherEditCourseForm({ course }: { course: CourseData }) {
const router = useRouter();
const [course, setCourse] = useState<Course | null>(null);
const [title, setTitle] = useState("");
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [rating, setRating] = useState(5);
const [saved, setSaved] = useState(false);
const [loading, setLoading] = useState(false);
const [optimisticModules, setOptimisticModules] = useState(course.modules);
useEffect(() => {
const load = () => {
const found = getTeacherCourseBySlug(slug) ?? null;
setCourse(found);
if (!found) return;
setTitle(found.title);
setLevel(found.level);
setSummary(found.summary);
setInstructor(found.instructor);
setWeeks(found.weeks);
setRating(found.rating);
};
setOptimisticModules(course.modules);
}, [course.modules]);
load();
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, [slug]);
const submit = (event: FormEvent) => {
event.preventDefault();
if (!course) return;
updateTeacherCourse(course.slug, {
title: title.trim(),
level,
summary: summary.trim(),
instructor: instructor.trim(),
weeks: Math.max(1, weeks),
rating: Math.min(5, Math.max(0, rating)),
});
setSaved(true);
window.setTimeout(() => setSaved(false), 1200);
// Helper for JSON/String fields
const getStr = (val: Prisma.JsonValue) => {
if (typeof val === "string") return val;
if (val && typeof val === "object" && !Array.isArray(val)) {
const v = val as Record<string, unknown>;
if (typeof v.en === "string") return v.en;
if (typeof v.es === "string") return v.es;
return "";
}
return "";
};
if (!course) {
return (
<div className="mx-auto max-w-2xl space-y-3 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900">Teacher course not found</h1>
<p className="text-slate-600">This editor only works for courses created in the teacher area.</p>
<Link className="inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/teacher">
Back to dashboard
</Link>
</div>
);
// 1. SAVE COURSE SETTINGS
async function handleSubmit(formData: FormData) {
setLoading(true);
const res = await updateCourse(course.id, course.slug, formData);
if (res.success) {
toast.success("Curso actualizado");
router.refresh();
} else {
toast.error("Error al guardar");
}
setLoading(false);
}
// 2. CREATE NEW MODULE
const handleAddModule = async () => {
setLoading(true); // Block UI while working
const res = await createModule(course.id);
if (res.success) {
toast.success("Módulo agregado");
router.refresh();
} else {
toast.error("Error al crear módulo");
}
setLoading(false);
};
// 3. CREATE NEW LESSON
const handleAddLesson = async (moduleId: string) => {
setLoading(true);
const res = await createLesson(moduleId);
if (res.success && res.lessonId) {
toast.success("Lección creada");
// Redirect immediately to the video upload page
router.push(`/teacher/courses/${course.slug}/lessons/${res.lessonId}`);
} else {
toast.error("Error al crear lección");
setLoading(false); // Only stop loading if we failed (otherwise we are redirecting)
}
};
// 4. REORDER MODULES (optimistic)
const handleReorderModule = async (moduleIndex: number, direction: "up" | "down") => {
const swapWith = direction === "up" ? moduleIndex - 1 : moduleIndex + 1;
if (swapWith < 0 || swapWith >= optimisticModules.length) return;
const next = [...optimisticModules];
[next[moduleIndex], next[swapWith]] = [next[swapWith], next[moduleIndex]];
setOptimisticModules(next);
const res = await reorderModules(optimisticModules[moduleIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
// 5. REORDER LESSONS (optimistic)
const handleReorderLesson = async (
moduleIndex: number,
lessonIndex: number,
direction: "up" | "down"
) => {
const lessons = optimisticModules[moduleIndex].lessons;
const swapWith = direction === "up" ? lessonIndex - 1 : lessonIndex + 1;
if (swapWith < 0 || swapWith >= lessons.length) return;
const nextModules = [...optimisticModules];
const nextLessons = [...lessons];
[nextLessons[lessonIndex], nextLessons[swapWith]] = [
nextLessons[swapWith],
nextLessons[lessonIndex],
];
nextModules[moduleIndex] = { ...nextModules[moduleIndex], lessons: nextLessons };
setOptimisticModules(nextModules);
const res = await reorderLessons(lessons[lessonIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
return (
<div className="mx-auto max-w-3xl space-y-5">
<form className="space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
<h1 className="text-2xl font-bold text-slate-900">Edit Course</h1>
<div className="mx-auto max-w-4xl space-y-6">
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Title</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-slate-900">Editar Curso</h1>
<div className="flex gap-2">
<Link
href={`/courses/${course.slug}`}
target="_blank"
className="px-3 py-2 text-sm border border-slate-300 rounded-md hover:bg-slate-50 flex items-center gap-2"
>
{levels.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Summary</span>
<textarea
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setSummary(event.target.value)}
rows={3}
value={summary}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Instructor</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setInstructor(event.target.value)}
value={instructor}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Weeks</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
min={1}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Rating (0-5)</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
max={5}
min={0}
onChange={(event) => setRating(Number(event.target.value))}
step={0.1}
type="number"
value={rating}
/>
</label>
</div>
<div className="flex items-center gap-3">
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Save changes
</button>
{saved ? <span className="text-sm font-medium text-emerald-700">Saved</span> : null}
<span>👁</span> Ver Vista Previa
</Link>
<button
className="rounded-md border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50"
onClick={() => router.push(`/teacher/courses/${course.slug}/lessons/new`)}
type="button"
form="edit-form"
type="submit"
disabled={loading}
className="bg-black text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-slate-800 disabled:opacity-50"
>
Add lesson
{loading ? "Guardando..." : "Guardar Cambios"}
</button>
</div>
</form>
</div>
<section className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h2 className="text-lg font-semibold text-slate-900">Lessons</h2>
<div className="mt-3 space-y-2">
{course.lessons.map((lesson) => (
<div key={lesson.id} className="rounded-md border border-slate-200 p-3 text-sm">
<p className="font-medium text-slate-900">{lesson.title}</p>
<p className="text-slate-600">
{lesson.type} | {lesson.minutes} min {lesson.isPreview ? "| Preview" : ""}
</p>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* LEFT COLUMN: Main Info */}
<div className="lg:col-span-2 space-y-6">
<form id="edit-form" action={handleSubmit} className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm space-y-4">
{/* Title */}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Título</label>
<input
name="title"
defaultValue={getStr(course.title)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div>
))}
{/* Description */}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Resumen</label>
<textarea
name="summary"
rows={4}
defaultValue={getStr(course.description)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Nivel</label>
<select
name="level"
defaultValue={course.level}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="BEGINNER">Principiante</option>
<option value="INTERMEDIATE">Intermedio</option>
<option value="ADVANCED">Avanzado</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Estado</label>
<select
name="status"
defaultValue={course.status}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="DRAFT">Borrador</option>
<option value="PUBLISHED">Publicado</option>
</select>
</div>
</div>
</form>
{/* MODULES & LESSONS SECTION */}
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Plan de Estudios</h2>
<button
type="button"
onClick={handleAddModule}
disabled={loading}
className="text-sm text-blue-600 font-medium hover:underline disabled:opacity-50"
>
+ Nuevo Módulo
</button>
</div>
<div className="space-y-4">
{optimisticModules.length === 0 && (
<div className="text-center py-8 border border-dashed border-slate-200 rounded-lg bg-slate-50">
<p className="text-slate-500 text-sm mb-2">Tu curso está vacío.</p>
<button onClick={handleAddModule} className="text-black underline text-sm font-medium">
Agrega el primer módulo
</button>
</div>
)}
{optimisticModules.map((module, moduleIndex) => (
<div key={module.id} className="border border-slate-200 rounded-xl overflow-hidden bg-white shadow-sm">
{/* Module Header */}
<div className="bg-slate-50 px-4 py-2 border-b border-slate-200 flex justify-between items-center">
<div className="flex items-center gap-2">
<span className="font-medium text-sm text-slate-800">{getStr(module.title)}</span>
<div className="flex items-center">
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "up")}
disabled={moduleIndex === 0}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo arriba"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "down")}
disabled={moduleIndex === optimisticModules.length - 1}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo abajo"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
</div>
<button className="text-xs text-slate-500 hover:text-black">Editar Título</button>
</div>
{/* Lessons List */}
<div className="divide-y divide-slate-100">
{module.lessons.map((lesson, lessonIndex) => (
<div
key={lesson.id}
className="px-4 py-3 flex items-center gap-2 hover:bg-slate-50 transition-colors group"
>
<div className="flex flex-col">
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "up")}
disabled={lessonIndex === 0}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección arriba"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "down")}
disabled={lessonIndex === module.lessons.length - 1}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección abajo"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
<Link
href={`/teacher/courses/${course.slug}/lessons/${lesson.id}`}
className="flex items-center gap-3 flex-1 min-w-0"
>
<span className="text-slate-400 text-lg group-hover:text-blue-500 flex-shrink-0"></span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-700 group-hover:text-slate-900">
{getStr(lesson.title)}
</p>
</div>
<span className="text-xs text-slate-400 opacity-0 group-hover:opacity-100 border border-slate-200 rounded px-2 py-1 flex-shrink-0">
Editar Contenido
</span>
</Link>
</div>
))}
{/* Add Lesson Button */}
<button
type="button"
onClick={() => handleAddLesson(module.id)}
disabled={loading}
className="w-full text-left px-4 py-3 text-xs text-slate-500 hover:text-blue-600 hover:bg-slate-50 font-medium flex items-center gap-2 transition-colors"
>
<span className="text-lg leading-none">+</span> Agregar Lección
</button>
</div>
</div>
))}
</div>
</div>
</div>
</section>
{/* RIGHT COLUMN: Price / Help */}
<div className="space-y-6">
<div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
<label className="block text-sm font-medium text-slate-700 mb-1">Precio (MXN)</label>
<input
form="edit-form"
name="price"
type="number"
step="0.01"
defaultValue={course.price}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
/>
<p className="mt-2 text-xs text-slate-500">
Si es 0, el curso será gratuito.
</p>
</div>
<div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
<h3 className="font-semibold text-slate-900 mb-2">💡 Tips</h3>
<ul className="text-sm text-slate-600 space-y-2 list-disc pl-4">
<li>Crea módulos para organizar tus temas.</li>
<li>Dentro de cada módulo, agrega lecciones.</li>
<li>Haz clic en una lección para <strong>subir el video</strong>.</li>
</ul>
</div>
</div>
</div>
</div>
);
}
}

178
components/teacher/TeacherNewCourseForm.tsx Normal file → Executable file
View File

@@ -1,112 +1,108 @@
"use client";
import { FormEvent, useState } from "react";
import { createCourse } from "@/app/(protected)/teacher/actions"; // Server Action
import { useRouter } from "next/navigation";
import { getAllCourseSlugs } from "@/lib/data/courseCatalog";
import { createTeacherCourse } from "@/lib/data/teacherCourses";
import type { CourseLevel } from "@/types/course";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];
import { useState, FormEvent } from "react";
import Link from "next/link";
export default function TeacherNewCourseForm() {
const router = useRouter();
const [title, setTitle] = useState("");
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = (event: FormEvent) => {
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setIsLoading(true);
setError(null);
const cleanTitle = title.trim();
const cleanSummary = summary.trim();
const cleanInstructor = instructor.trim();
const formData = new FormData(event.currentTarget);
if (!cleanTitle || !cleanSummary || !cleanInstructor) {
setError("Title, summary, and instructor are required.");
return;
try {
// 1. Call the Server Action
const result = await createCourse(formData);
if (result.success && result.data) {
// 2. Redirect to the Course Editor
// We will build the [slug]/edit page next
router.push(`/teacher/courses/${result.data.slug}/edit`);
} else {
setError(result.error || "Algo salió mal al crear el curso.");
setIsLoading(false);
}
} catch {
setError("Error de conexión. Inténtalo de nuevo.");
setIsLoading(false);
}
const created = createTeacherCourse(
{
title: cleanTitle,
level,
summary: cleanSummary,
instructor: cleanInstructor,
weeks: Math.max(1, weeks),
},
getAllCourseSlugs(),
);
router.push(`/teacher/courses/${created.slug}/edit`);
};
}
return (
<form className="mx-auto max-w-2xl space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
<h1 className="text-2xl font-bold text-slate-900">Create Course</h1>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Title</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
<div className="mx-auto max-w-2xl">
{/* Breadcrumb / Back Link */}
<div className="mb-6">
<Link
href="/teacher"
className="text-sm text-slate-500 hover:text-slate-900 transition-colors"
>
{levels.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
</label>
Volver al Panel
</Link>
</div>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Summary</span>
<textarea
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setSummary(event.target.value)}
rows={3}
value={summary}
/>
</label>
<div className="rounded-xl border border-slate-200 bg-white p-8 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900 mb-2">Crear Nuevo Curso</h1>
<p className="text-slate-600 mb-8">
Empieza con un título. Podrás agregar lecciones, cuestionarios y más detalles en la siguiente pantalla.
</p>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Instructor</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setInstructor(event.target.value)}
value={instructor}
/>
</label>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label
htmlFor="title"
className="block text-sm font-medium text-slate-700 mb-1"
>
Título del Curso
</label>
<input
id="title"
name="title"
type="text"
required
disabled={isLoading}
placeholder="Ej. Inglés Jurídico: Contratos Internacionales"
className="w-full rounded-lg border border-slate-300 px-4 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all disabled:opacity-50 disabled:bg-slate-50"
autoFocus
/>
<p className="mt-2 text-xs text-slate-500">
Esto generará la URL pública de tu curso.
</p>
</div>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Weeks</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
min={1}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
{error && (
<div className="bg-red-50 text-red-600 text-sm p-3 rounded-md border border-red-100">
{error}
</div>
)}
{error ? <p className="text-sm text-red-600">{error}</p> : null}
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Create course
</button>
</form>
<div className="flex items-center gap-4 pt-4">
<Link
href="/teacher"
className="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900 transition-colors"
>
Cancelar
</Link>
<button
type="submit"
disabled={isLoading}
className="rounded-lg bg-black px-6 py-2 text-sm font-medium text-white hover:bg-slate-800 transition-colors disabled:opacity-50 flex items-center gap-2"
>
{isLoading ? (
<>Creating...</>
) : (
"Crear Curso & Continuar"
)}
</button>
</div>
</form>
</div>
</div>
);
}
}

0
components/teacher/TeacherNewLessonForm.tsx Normal file → Executable file
View File

View File

@@ -0,0 +1,140 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { getTeacherCourses, teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import type { Course } from "@/types/course";
type UploadAsset = {
id: string;
fileName: string;
type: "video" | "pdf" | "audio";
duration?: string;
size: string;
uploadedAt: string;
};
const mockAssets: UploadAsset[] = [
{ id: "asset-1", fileName: "contracts-intro-v1.mp4", type: "video", duration: "08:34", size: "48 MB", uploadedAt: "2026-02-01" },
{ id: "asset-2", fileName: "clause-red-flags.mp4", type: "video", duration: "12:12", size: "66 MB", uploadedAt: "2026-02-03" },
{ id: "asset-3", fileName: "brief-writing-reference.pdf", type: "pdf", size: "2.3 MB", uploadedAt: "2026-02-05" },
];
export default function TeacherUploadsLibraryClient() {
const [courses, setCourses] = useState<Course[]>([]);
const [selectedCourseByAsset, setSelectedCourseByAsset] = useState<Record<string, string>>({});
const [selectedLessonByAsset, setSelectedLessonByAsset] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const load = () => setCourses(getTeacherCourses());
load();
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []);
const lessonOptionsByCourse = useMemo(() => {
const map: Record<string, Array<{ id: string; title: string }>> = {};
for (const course of courses) {
map[course.slug] = course.lessons.map((lesson) => ({ id: lesson.id, title: lesson.title }));
}
return map;
}, [courses]);
const attachAsset = (assetId: string) => {
const courseSlug = selectedCourseByAsset[assetId];
const lessonId = selectedLessonByAsset[assetId];
if (!courseSlug || !lessonId) {
setMessage("Select a course and lesson before attaching.");
return;
}
setMessage(`Placeholder only: asset attached to ${courseSlug} / ${lessonId}.`);
};
return (
<div className="space-y-6">
<header className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<h1 className="text-3xl font-bold text-slate-900">Upload Library</h1>
<p className="mt-1 text-sm text-slate-600">Central cloud-style asset library for reusing videos and files across courses.</p>
<p className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
Upload disabled in MVP. This is a placeholder for backend integration.
</p>
<div className="mt-4 flex gap-2">
<Link className="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50" href="/teacher">
Back to dashboard
</Link>
<button className="rounded-md bg-slate-200 px-3 py-1.5 text-sm font-semibold text-slate-700" type="button">
Upload file (disabled)
</button>
</div>
</header>
{message ? (
<p className="rounded-md border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700">{message}</p>
) : null}
<section className="grid gap-4">
{mockAssets.map((asset) => {
const selectedCourse = selectedCourseByAsset[asset.id] ?? "";
const lessonOptions = selectedCourse ? lessonOptionsByCourse[selectedCourse] ?? [] : [];
return (
<article key={asset.id} className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{asset.type}</p>
<h2 className="text-lg font-semibold text-slate-900">{asset.fileName}</h2>
<p className="mt-1 text-sm text-slate-600">
{asset.size} {asset.duration ? `| ${asset.duration}` : ""} | Uploaded {asset.uploadedAt}
</p>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
onChange={(event) => {
const slug = event.target.value;
setSelectedCourseByAsset((current) => ({ ...current, [asset.id]: slug }));
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: "" }));
}}
value={selectedCourse}
>
<option value="">Select course</option>
{courses.map((course) => (
<option key={course.slug} value={course.slug}>
{course.title}
</option>
))}
</select>
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
disabled={!selectedCourse}
onChange={(event) =>
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: event.target.value }))
}
value={selectedLessonByAsset[asset.id] ?? ""}
>
<option value="">Select lesson</option>
{lessonOptions.map((lesson) => (
<option key={lesson.id} value={lesson.id}>
{lesson.title}
</option>
))}
</select>
<button
className="rounded-md border border-slate-300 px-3 py-2 text-sm font-semibold hover:bg-slate-50"
onClick={() => attachAsset(asset.id)}
type="button"
>
Attach to lesson
</button>
</div>
</article>
);
})}
</section>
</div>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { toast } from "sonner"; // or use alert()
interface VideoUploadProps {
lessonId: string;
currentVideoUrl?: string | null;
onUploadComplete: (url: string) => void; // Callback to save to DB
}
export default function VideoUpload({ lessonId, currentVideoUrl, onUploadComplete }: VideoUploadProps) {
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
setProgress(0);
const supabase = createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
// Create a unique file path: lesson_id/timestamp_filename
const filePath = `${lessonId}/${Date.now()}_${file.name}`;
const { error } = await supabase.storage
.from("courses") // Make sure this bucket exists!
.upload(filePath, file, {
upsert: true,
});
if (error) {
toast.error("Upload failed: " + error.message);
setUploading(false);
return;
}
// Get Public URL
const { data: { publicUrl } } = supabase.storage
.from("courses")
.getPublicUrl(filePath);
onUploadComplete(publicUrl);
setUploading(false);
};
return (
<div className="border border-slate-200 rounded-lg p-6 bg-slate-50">
<h3 className="font-medium text-slate-900 mb-2">Video de la Lección</h3>
{currentVideoUrl ? (
<div className="mb-4 aspect-video bg-black rounded-md overflow-hidden relative group">
<video src={currentVideoUrl} controls className="w-full h-full" />
<div className="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center">
<p className="text-white text-sm">Subir otro para reemplazar</p>
</div>
</div>
) : (
<div className="mb-4 aspect-video bg-slate-200 rounded-md flex items-center justify-center text-slate-400">
Sin video
</div>
)}
<div className="flex flex-col gap-2">
<label className="block w-full">
<span className="sr-only">Choose video</span>
<input
type="file"
accept="video/*"
onChange={handleUpload}
disabled={uploading}
className="block w-full text-sm text-slate-500
file:mr-4 file:py-2 file:px-4
file:rounded-full file:border-0
file:text-sm file:font-semibold
file:bg-black file:text-white
hover:file:bg-slate-800
"
/>
</label>
{uploading && (
<div className="w-full bg-slate-200 rounded-full h-2 mt-2">
<div className="bg-black h-2 rounded-full transition-all" style={{ width: `${progress}%` }}></div>
</div>
)}
</div>
</div>
);
}

36
components/ui/badge.tsx Executable file
View File

@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

57
components/ui/button.tsx Executable file
View File

@@ -0,0 +1,57 @@
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 buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

76
components/ui/card.tsx Executable file
View File

@@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

22
components/ui/input.tsx Executable file
View File

@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

48
components/ui/scroll-area.tsx Executable file
View File

@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

140
components/ui/sheet.tsx Executable file
View File

@@ -0,0 +1,140 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
{children}
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

31
components/ui/sonner.tsx Normal file
View File

@@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

55
components/ui/tabs.tsx Executable file
View File

@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }