Study/src/app/(protected)/[classSlug]/flashcards/page.tsx
Elijah d6f3502cb1
All checks were successful
Automated Container Build / build-and-push (push) Successful in 1m2s
Tighten typing and input validation across study pages
2026-07-13 06:55:17 -07:00

537 lines
25 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ImportModal } from "@/components/import/ImportModal";
import { ShareMenu } from "@/components/ui/ShareMenu";
import {
DndContext,
pointerWithin,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
DragOverEvent,
DragStartEvent,
DragOverlay,
useDroppable,
useDndContext,
} from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { ReorderItem } from "@/types/study";
interface DeckItem {
id: string;
name: string;
description: string | null;
groupId: string | null;
sortOrder: number;
_count: { cards: number };
progress: Array<{
mode: string;
currentIndex: number;
orderJson: string;
cardResultsJson: string | null;
}>;
}
interface MaterialGroup {
id: string;
name: string;
sortOrder: number;
}
const cache: Record<string, { decks: DeckItem[]; groups: MaterialGroup[] }> = {};
function getProgressLabel(deck: DeckItem) {
if (!deck.progress?.length) return null;
const prog = deck.progress[0];
const order = JSON.parse(prog.orderJson) as string[];
const results = prog.cardResultsJson
? (JSON.parse(prog.cardResultsJson) as Record<string, string>)
: {};
const correctCount = Object.values(results).filter((r) => r === "correct").length;
const total = order.length;
const current = Math.min(prog.currentIndex + 1, total);
const modeLabel = prog.mode === "SHUFFLED" ? "shuffled" : "sequential";
return `${current}/${total}, ${modeLabel} · ${correctCount}`;
}
interface SortableDeckCardProps {
deck: DeckItem;
onEdit: (deck: DeckItem) => void;
onDelete: (deck: DeckItem) => void;
classSlug: string;
}
function SortableDeckCard({ deck, onEdit, onDelete, classSlug }: SortableDeckCardProps) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: deck.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.4 : 1,
};
const progressLabel = getProgressLabel(deck);
return (
<div ref={setNodeRef} style={style} className="group flex h-full flex-col rounded-2xl border border-border-light bg-bg-surface shadow-[var(--shadow-card)] transition-all duration-300 hover:-translate-y-0.5 hover:border-primary/25 hover:shadow-[var(--shadow-card-hover)]">
<div className="flex h-full flex-1 flex-col p-5">
<div className="flex items-start gap-2">
<div {...attributes} {...listeners} className="mt-1 cursor-grab active:cursor-grabbing text-text-muted hover:text-text-heading">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8h16M4 16h16" />
</svg>
</div>
<div className="flex-1">
<h3 className="mb-1 text-lg font-extrabold text-text-heading">{deck.name}</h3>
{deck.description && <p className="text-sm text-text-secondary mb-3 line-clamp-2">{deck.description}</p>}
</div>
</div>
<div className="flex items-center gap-3 mt-auto mb-4 pl-7">
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-badge-bg text-badge-text text-xs font-medium">
{deck._count.cards} {deck._count.cards === 1 ? "card" : "cards"}
</span>
{progressLabel && (
<span className="text-xs text-text-muted">{progressLabel}</span>
)}
</div>
<div className="flex flex-col gap-2 border-t border-border-light pt-4 pl-7 sm:flex-row sm:items-center">
<div className="flex w-full min-w-0 gap-2 sm:flex-1">
{deck.progress?.length ? (
<>
<Link href={`/${classSlug}/flashcards/${deck.id}`} className="flex-1 text-center py-2 px-4 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-hover transition-all duration-200">
Continue
</Link>
<button
onClick={async () => {
if (!confirm("Start over from the beginning? This will clear your current progress for this deck.")) return;
await Promise.all([
fetch("/api/progress", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ contentType: "DECK", contentId: deck.id, mode: "SEQUENTIAL" }) }).catch(() => {}),
fetch("/api/progress", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ contentType: "DECK", contentId: deck.id, mode: "SHUFFLED" }) }).catch(() => {})
]);
window.location.href = `/${classSlug}/flashcards/${deck.id}`;
}}
className="flex-1 text-center py-2 px-4 rounded-lg bg-bg-surface-alt border border-border text-text-heading text-sm font-medium hover:bg-border transition-all duration-200 cursor-pointer shadow-sm"
title="Restart"
>
Restart
</button>
</>
) : (
<Link href={`/${classSlug}/flashcards/${deck.id}`} className="flex-1 text-center py-2 px-4 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-hover transition-all duration-200">
Study
</Link>
)}
</div>
<div className="flex items-center justify-end gap-2">
<button onClick={() => onEdit(deck)} className="p-2 rounded-lg text-text-muted hover:text-text-heading hover:bg-bg-surface-alt transition-all duration-200 cursor-pointer" title="Edit">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button onClick={() => onDelete(deck)} className="p-2 rounded-lg text-text-muted hover:text-error hover:bg-error-bg transition-all duration-200 cursor-pointer" title="Delete">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
<ShareMenu targetType="DECK" contentId={deck.id} classSlug={classSlug} compact />
</div>
</div>
</div>
</div>
);
}
function DroppableContainer({ id, children }: { id: string; children: React.ReactNode }) {
const { setNodeRef } = useDroppable({ id });
const { over } = useDndContext();
const isOverContainer = over?.id === id;
const isOverChild = over?.data?.current?.sortable?.containerId === id;
const isOver = isOverContainer || isOverChild;
return (
<div ref={setNodeRef} className={`grid grid-cols-1 md:grid-cols-2 gap-4 min-h-[60px] p-2 -mx-2 rounded-lg border-2 transition-colors duration-200 ${isOver ? "border-primary/40 bg-primary/5 shadow-inner" : "border-transparent"}`}>
{children}
</div>
);
}
export default function FlashcardsPage() {
const params = useParams();
const classSlug = params.classSlug as string;
const [decks, setDecks] = useState<DeckItem[]>(cache[classSlug]?.decks || []);
const [groups, setGroups] = useState<MaterialGroup[]>(cache[classSlug]?.groups || []);
const [loading, setLoading] = useState(!cache[classSlug]);
const [animate] = useState(!cache[classSlug]);
const [showImport, setShowImport] = useState(false);
const [classId, setClassId] = useState<string>("");
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState("");
const [editDescription, setEditDescription] = useState("");
const [isCreatingGroup, setIsCreatingGroup] = useState(false);
const [newGroupName, setNewGroupName] = useState("");
const [editingGroupId, setEditingGroupId] = useState<string | null>(null);
const [editGroupName, setEditGroupName] = useState("");
const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>({});
useEffect(() => {
const saved = localStorage.getItem('flashcards_collapsed_groups');
if (saved) {
try { setCollapsedGroups(JSON.parse(saved)); } catch(e) {}
}
}, []);
function toggleGroup(id: string) {
setCollapsedGroups(prev => {
const next = { ...prev, [id]: !prev[id] };
localStorage.setItem('flashcards_collapsed_groups', JSON.stringify(next));
return next;
});
}
const fetchAll = useCallback(async (cId: string) => {
try {
const [deckRes, groupRes] = await Promise.all([
fetch(`/api/decks/list?classId=${cId}`),
fetch(`/api/material-groups?classId=${cId}&type=DECK`),
]);
const ds = deckRes.ok ? await deckRes.json() : [];
const gs = groupRes.ok ? await groupRes.json() : [];
setDecks(ds);
setGroups(gs);
cache[classSlug] = { decks: ds, groups: gs };
} catch {
setDecks([]);
setGroups([]);
} finally {
setLoading(false);
}
}, [classSlug]);
useEffect(() => {
async function init() {
try {
const classRes = await fetch("/api/classes");
const classes = await classRes.json();
const cls = classes.find((c: { slug: string }) => c.slug === classSlug);
if (!cls) {
setLoading(false);
return;
}
setClassId(cls.id);
fetchAll(cls.id);
} catch {
setLoading(false);
}
}
init();
}, [classSlug, fetchAll]);
// Group Management
async function handleCreateGroup() {
if (!newGroupName.trim()) return;
const res = await fetch("/api/material-groups", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ classId, name: newGroupName.trim(), type: "DECK" }),
});
if (res.ok) {
const g = await res.json();
setGroups((prev) => [...prev, g]);
setIsCreatingGroup(false);
setNewGroupName("");
}
}
async function handleRenameGroup(id: string) {
if (!editGroupName.trim()) return;
await fetch(`/api/material-groups/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: editGroupName.trim() }),
});
setGroups((prev) => prev.map((g) => (g.id === id ? { ...g, name: editGroupName.trim() } : g)));
setEditingGroupId(null);
}
async function handleDeleteGroup(id: string, name: string) {
if (!confirm(`Delete group "${name}"? Decks inside will be moved to Uncategorized.`)) return;
await fetch(`/api/material-groups/${id}`, { method: "DELETE" });
setGroups((prev) => prev.filter((g) => g.id !== id));
setDecks((prev) => prev.map((d) => (d.groupId === id ? { ...d, groupId: null } : d)));
}
// Deck Management
async function handleDeleteDeck(deck: DeckItem) {
if (!confirm(`Delete "${deck.name}" and all its cards?`)) return;
await fetch(`/api/decks/${deck.id}`, { method: "DELETE" });
setDecks((prev) => prev.filter((d) => d.id !== deck.id));
}
async function handleRenameDeck(id: string) {
if (!editName.trim()) return;
await fetch(`/api/decks/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: editName.trim(), description: editDescription.trim() || null }),
});
setDecks((prev) =>
prev.map((d) => (d.id === id ? { ...d, name: editName.trim(), description: editDescription.trim() || null } : d))
);
setEditingId(null);
}
// Drag and drop setup
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
);
const [activeId, setActiveId] = useState<string | null>(null);
function handleDragStart(event: DragStartEvent) {
setActiveId(event.active.id as string);
}
function handleDragOver(event: DragOverEvent) {
// optional layout updates here
}
async function handleDragEnd(event: DragEndEvent) {
setActiveId(null);
const { active, over } = event;
if (!over) return;
const activeId = active.id as string;
const overId = over.id as string;
const activeDeck = decks.find((d) => d.id === activeId);
if (!activeDeck) return;
let targetGroupId: string | null = null;
const overContainerId = over.data.current?.sortable?.containerId;
if (overContainerId) {
targetGroupId = overContainerId === "uncategorized" ? null : overContainerId;
} else if (groups.find(g => g.id === overId) || overId === "uncategorized") {
targetGroupId = overId === "uncategorized" ? null : overId;
} else {
const overDeck = decks.find((d) => d.id === overId);
if (overDeck) {
targetGroupId = overDeck.groupId;
}
}
if (targetGroupId !== undefined) {
setDecks((items) => {
const oldIndex = items.findIndex((d) => d.id === activeId);
const overIndex = items.findIndex((d) => d.id === overId);
let newItems = [...items];
newItems[oldIndex].groupId = targetGroupId;
if (overIndex >= 0 && overIndex !== oldIndex) {
newItems = arrayMove(newItems, oldIndex, overIndex);
} else {
const oldItem = newItems.splice(oldIndex, 1)[0];
newItems.push(oldItem);
}
const affectedGroups = new Set([activeDeck.groupId, targetGroupId]);
const updates: ReorderItem[] = [];
affectedGroups.forEach(gId => {
const gItems = newItems.filter(d => d.groupId === gId);
gItems.forEach((item, index) => {
item.sortOrder = index;
updates.push({ id: item.id, sortOrder: index, groupId: item.groupId });
});
});
fetch("/api/decks/reorder", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: updates }),
});
return newItems;
});
}
}
const groupedDecks = groups.map(g => ({
...g,
decks: decks.filter(d => d.groupId === g.id).sort((a,b) => a.sortOrder - b.sortOrder)
}));
const uncategorizedDecks = decks.filter(d => d.groupId === null).sort((a,b) => a.sortOrder - b.sortOrder);
const activeDeck = decks.find(d => d.id === activeId);
return (
<div className="pb-20">
{/* Header */}
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div><p className="text-xs font-bold uppercase tracking-[0.16em] text-primary">Collection</p><h2 className="editorial-title mt-1 text-3xl text-text-heading">Flashcard decks</h2></div>
<div className="grid grid-cols-2 gap-3 sm:flex">
<button onClick={() => setIsCreatingGroup(true)} className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl border border-border-light bg-bg-surface px-4 font-bold text-text-heading shadow-sm transition-colors hover:bg-bg-surface-alt">
Add Group
</button>
<button onClick={() => setShowImport(true)} className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-primary px-4 font-bold text-white shadow-sm transition-colors hover:bg-primary-hover">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
Import Deck
</button>
</div>
</div>
{isCreatingGroup && (
<div className="animate-slide-up mb-6 flex flex-col gap-3 rounded-2xl border border-primary/20 bg-bg-surface p-5 shadow-sm sm:flex-row sm:items-center">
<input
autoFocus
type="text"
value={newGroupName}
onChange={(e) => setNewGroupName(e.target.value)}
placeholder="e.g. Exam 1 Flashcards"
className="flex-1 px-3 py-2 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30"
/>
<button onClick={handleCreateGroup} className="px-4 py-2 bg-primary text-white font-medium rounded-md hover:bg-primary-hover cursor-pointer">
Save
</button>
<button onClick={() => { setIsCreatingGroup(false); setNewGroupName(""); }} className="px-4 py-2 bg-bg-surface-alt text-text-heading font-medium rounded-md hover:bg-border cursor-pointer">
Cancel
</button>
</div>
)}
{editingId && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
<div className="w-full max-w-md rounded-3xl border border-border bg-bg-surface p-6 shadow-[var(--shadow-modal)]">
<h3 className="editorial-title mb-4 text-2xl text-text-heading">Edit deck</h3>
<input
type="text"
value={editName}
onChange={(e) => setEditName(e.target.value)}
placeholder="Deck Name"
autoFocus
className="w-full px-3 py-2 mb-3 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30"
/>
<textarea
value={editDescription}
onChange={(e) => setEditDescription(e.target.value)}
placeholder="Description (optional)"
rows={3}
className="w-full px-3 py-2 mb-4 rounded-lg border border-border bg-bg-surface-alt/50 text-text-heading focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none"
/>
<div className="flex gap-2 justify-end">
<button onClick={() => setEditingId(null)} className="px-4 py-2 bg-bg-surface-alt text-text-heading font-medium rounded-md hover:bg-border cursor-pointer">Cancel</button>
<button onClick={() => handleRenameDeck(editingId)} className="px-4 py-2 bg-primary text-white font-medium rounded-md hover:bg-primary-hover cursor-pointer">Save Changes</button>
</div>
</div>
</div>
)}
{!loading && decks.length === 0 && groups.length === 0 && (
<div className="text-center py-16">
<h3 className="text-lg font-semibold text-text-heading mb-1">No decks yet</h3>
<p className="text-text-secondary mb-4">Import your first deck or create a group</p>
</div>
)}
{!loading && (
<DndContext sensors={sensors} collisionDetection={pointerWithin} onDragStart={handleDragStart} onDragOver={handleDragOver} onDragEnd={handleDragEnd}>
<div className="space-y-8">
{groupedDecks.map(group => (
<div key={group.id} className="rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5">
<div className={`flex items-center justify-between ${collapsedGroups[group.id] ? "" : "mb-4"}`}>
{editingGroupId === group.id ? (
<div className="flex items-center gap-2">
<input autoFocus value={editGroupName} onChange={e => setEditGroupName(e.target.value)} className="px-2 py-1 rounded border border-border bg-bg-surface text-text-heading focus:ring-1 focus:ring-primary" />
<button onClick={() => handleRenameGroup(group.id)} className="text-xs px-2 py-1 bg-primary text-white rounded">Save</button>
<button onClick={() => setEditingGroupId(null)} className="text-xs px-2 py-1 bg-bg-surface text-text-heading rounded border border-border-light">Cancel</button>
</div>
) : (
<div className="flex items-center gap-2">
<button onClick={() => toggleGroup(group.id)} className="p-1 rounded text-text-muted hover:text-text-heading hover:bg-bg-surface transition-colors cursor-pointer" title={collapsedGroups[group.id] ? "Expand" : "Collapse"}>
<svg className={`w-5 h-5 transition-transform duration-200 ${collapsedGroups[group.id] ? '-rotate-90' : ''}`} 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>
<h3 className="text-lg font-extrabold text-text-heading">{group.name}</h3>
</div>
)}
<div className="flex items-center gap-2">
<ShareMenu targetType="GROUP" contentId={group.id} classSlug={params.classSlug as string} />
<button onClick={() => { setEditingGroupId(group.id); setEditGroupName(group.name); }} className="text-text-muted hover:text-text-heading"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg></button>
<button onClick={() => handleDeleteGroup(group.id, group.name)} className="text-text-muted hover:text-error"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg></button>
</div>
</div>
<div className={collapsedGroups[group.id] ? "hidden" : "block"}>
<SortableContext id={group.id} items={group.decks.map(d => d.id)} strategy={verticalListSortingStrategy}>
<DroppableContainer id={group.id}>
{group.decks.length === 0 ? (
<div className="col-span-1 md:col-span-2 text-center py-4 text-text-muted text-sm border-2 border-dashed border-border-light rounded-lg">Drop decks here</div>
) : (
group.decks.map(deck => (
<SortableDeckCard key={deck.id} deck={deck} onEdit={(d: DeckItem) => { setEditingId(d.id); setEditName(d.name); setEditDescription(d.description || ""); }} onDelete={handleDeleteDeck} classSlug={classSlug} />
))
)}
</DroppableContainer>
</SortableContext>
</div>
</div>
))}
{/* Uncategorized */}
<div className="rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5">
<div className={`flex items-center gap-2 ${collapsedGroups["uncategorized"] ? "" : "mb-4"}`}>
<button onClick={() => toggleGroup("uncategorized")} className="p-1 rounded text-text-muted hover:text-text-heading hover:bg-bg-surface transition-colors cursor-pointer" title={collapsedGroups["uncategorized"] ? "Expand" : "Collapse"}>
<svg className={`w-5 h-5 transition-transform duration-200 ${collapsedGroups["uncategorized"] ? '-rotate-90' : ''}`} 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>
<h3 className="text-lg font-semibold text-text-heading">Uncategorized</h3>
</div>
<div className={collapsedGroups["uncategorized"] ? "hidden" : "block"}>
<SortableContext id="uncategorized" items={uncategorizedDecks.map(d => d.id)} strategy={verticalListSortingStrategy}>
<DroppableContainer id="uncategorized">
{uncategorizedDecks.length === 0 ? (
<div className="col-span-1 md:col-span-2 text-center py-4 text-text-muted text-sm border-2 border-dashed border-border-light rounded-lg">No uncategorized decks</div>
) : (
uncategorizedDecks.map(deck => (
<SortableDeckCard key={deck.id} deck={deck} onEdit={(d: DeckItem) => { setEditingId(d.id); setEditName(d.name); setEditDescription(d.description || ""); }} onDelete={handleDeleteDeck} classSlug={classSlug} />
))
)}
</DroppableContainer>
</SortableContext>
</div>
</div>
</div>
<DragOverlay>
{activeDeck ? (
<div className="opacity-80 scale-105 shadow-xl rotate-2">
<SortableDeckCard deck={activeDeck} onEdit={()=>{}} onDelete={()=>{}} classSlug={classSlug} />
</div>
) : null}
</DragOverlay>
</DndContext>
)}
{showImport && (
<ImportModal classId={classId} importType="flashcards" onClose={() => setShowImport(false)} onImported={() => { setShowImport(false); setLoading(true); window.location.reload(); }} />
)}
</div>
);
}