Study/src/app/(protected)/[classSlug]/flashcards/[deckId]/page.tsx

185 lines
6.4 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
import { useParams, useRouter } from "next/navigation";
import { FlashcardViewer } from "@/components/flashcards/FlashcardViewer";
import { CardManager } from "@/components/flashcards/CardManager";
import { ShareMenu } from "@/components/ui/ShareMenu";
interface Card {
id: string;
front: string;
back: string;
sortOrder: number;
}
interface DeckData {
id: string;
name: string;
description: string | null;
cards: Card[];
class: { slug: string; name: string };
progress: Array<{
mode: "SEQUENTIAL" | "SHUFFLED";
currentIndex: number;
orderJson: string;
cardResultsJson: string | null;
sessionId: string;
revision: number;
updatedAt: string;
}>;
}
export default function DeckStudyPage() {
const params = useParams();
const router = useRouter();
const classSlug = params.classSlug as string;
const deckId = params.deckId as string;
const [deck, setDeck] = useState<DeckData | null>(null);
const [loading, setLoading] = useState(true);
const [view, setView] = useState<"study" | "manage">("study");
const [restartKey, setRestartKey] = useState(0);
async function handleRestart() {
if (!deck) return;
const responses = await Promise.all(
deck.progress.map((progress) =>
fetch("/api/progress", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contentType: "DECK",
contentId: deck.id,
mode: progress.mode,
sessionId: progress.sessionId,
}),
})
)
).catch(() => null);
if (!responses || responses.some((response) => !response.ok)) {
window.alert("The session could not be restarted. Your saved progress was kept.");
return;
}
// Clear locally and force remount
setDeck({ ...deck, progress: [] });
setRestartKey(k => k + 1);
}
const fetchDeck = useCallback(async () => {
try {
const res = await fetch(`/api/decks/${deckId}`);
if (!res.ok) throw new Error("Not found");
const data = await res.json();
setDeck(data);
} catch {
router.push(`/${classSlug}/flashcards`);
} finally {
setLoading(false);
}
}, [deckId, classSlug, router]);
useEffect(() => {
const timer = window.setTimeout(() => void fetchDeck(), 0);
return () => window.clearTimeout(timer);
}, [fetchDeck]);
if (loading || !deck) {
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="animate-subtle-pulse">
<div className="h-8 bg-bg-surface-alt rounded w-1/3 mb-4" />
<div className="h-64 bg-bg-surface rounded-xl border border-border-light" />
</div>
</div>
);
}
return (
<div className="mx-auto w-full max-w-5xl py-1 md:py-3">
{/* Header */}
<div className="mb-7 flex flex-col items-start justify-between gap-4 rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5 md:flex-row md:items-center">
<div>
<button
onClick={() => router.push(`/${classSlug}/flashcards`)}
className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-text-heading mb-2 transition-colors cursor-pointer"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Back to decks
</button>
<p className="text-xs font-bold uppercase tracking-[0.16em] text-primary">Flashcard session</p>
<h1 className="editorial-title mt-1 text-3xl text-text-heading">{deck.name}</h1>
{deck.description && (
<p className="text-sm text-text-secondary mt-1">{deck.description}</p>
)}
</div>
{/* View toggle & Share */}
<div className="flex items-center justify-between w-full md:w-auto gap-2 md:gap-4 self-end md:self-auto">
{view === "study" && (
<button
onClick={handleRestart}
className="p-1.5 rounded-lg text-text-muted hover:text-text-heading hover:bg-bg-surface-alt transition-all duration-200 cursor-pointer"
title="Restart Session"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
)}
<div className="flex items-center gap-2 md:gap-4 ml-auto">
<ShareMenu targetType="DECK" contentId={deck.id} classSlug={classSlug} />
<div className="flex rounded-xl border border-border-light bg-bg-surface-alt p-1">
<button
onClick={() => setView("study")}
className={`px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 cursor-pointer ${
view === "study"
? "bg-bg-surface text-text-heading shadow-sm"
: "text-text-muted hover:text-text-heading"
}`}
>
Study
</button>
<button
onClick={() => setView("manage")}
className={`px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 cursor-pointer ${
view === "manage"
? "bg-bg-surface text-text-heading shadow-sm"
: "text-text-muted hover:text-text-heading"
}`}
>
Manage
</button>
</div>
</div>
</div>
</div>
{/* Content */}
{view === "study" ? (
<FlashcardViewer
key={restartKey}
cards={deck.cards}
deckId={deck.id}
initialProgress={
deck.progress?.length
? deck.progress.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0]
: null
}
/>
) : (
<CardManager
cards={deck.cards}
deckId={deck.id}
onCardsChanged={fetchDeck}
/>
)}
</div>
);
}