import { Archive, ArrowDownAZ, ArrowLeft, ArrowRight, BookOpen, ChevronDown, Clock, Copy, Download, FileImage, FileText, FileUp, Folder as FolderIcon, FolderInput, FolderPlus, GripVertical, Layers, MoreHorizontal, NotebookPen, Pencil, Play, Plus, Presentation, Search, Share2, Sparkles, Trash2, TriangleAlert, Upload, X, } from 'lucide-react'; import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; import { toast } from 'sonner'; import { ClassDialog } from '@/app/Shell'; import { MoveDialog, NewItemDialog, RenameDialog, ShareDialog, type EditableKind, type ShareKind } from '@/features/dialogs'; import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog'; import { ImportDialog } from '@/features/ImportDialog'; import { useStartSession } from '@/features/study'; import { api, errorMessage, uploadWithProgress } from '@/lib/api'; import { assistant, ITEM_DRAG_TYPE, useAssistantContext } from '@/lib/assistantStore'; import { useClass, useRefresh } from '@/lib/queries'; import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types'; import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util'; import { SortableList, type SortableRenderProps } from '@/ui/Sortable'; import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui'; import { letterGrade } from '@shared/content'; type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note'; const ITEM_URL = { quiz: 'quizzes', deck: 'decks', document: 'documents', note: 'notes' } as const; function DocIcon({ kind }: { kind: string }) { if (kind === 'pptx') return ; if (kind === 'image') return ; return ; } function KindIcon({ item }: { item: Item }) { const tone = { quiz: 'bg-accent-soft text-accent', deck: 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker', document: 'bg-sunken text-ink-2', note: 'bg-good-soft text-good' }[item.kind]; return ( svg]:size-[18px]', tone)}> {item.kind === 'quiz' ? : item.kind === 'deck' ? : item.kind === 'note' ? : } ); } function itemMeta(item: Item): ReactNode { if (item.kind === 'quiz') { const q = item as QuizItem; return ( <> {plural(q.questionCount, 'question')} {q.lastPercent !== null && ( Last {letterGrade(q.lastPercent ?? 0)} · {q.lastPercent}% )} {q.lastStudiedAt && {timeAgo(q.lastStudiedAt)}} ); } if (item.kind === 'deck') { const d = item as DeckItem; return ( <> {plural(d.cardCount, 'card')} {d.cardCount > 0 && {d.learnedCount} learned} ); } if (item.kind === 'document') { const d = item as DocumentItem; return ( <> {d.docKind === 'markdown' ? 'MD' : d.docKind} {d.pageCount ? {plural(d.pageCount, d.docKind === 'pptx' ? 'slide' : 'page')} : null} {formatBytes(d.size)} ); } return {item.description || 'Empty note'}; } interface Uploading { id: number; name: string; progress: number; error?: string; } export default function ClassPage() { const { classId = '' } = useParams(); const navigate = useNavigate(); const refresh = useRefresh(); const confirm = useConfirm(); const { start } = useStartSession(); const [polling, setPolling] = useState(false); const q = useClass(classId, polling ? 1500 : false); const data = q.data; useDocumentTitle(data?.class.name); /** * The exam (folder) in view: a class is divided into exams, each with its own material. * 'all' shows everything, 'none' what is in no exam. Remembered per class; new visitors start * on the latest exam. */ const [examChoice, setExamChoice] = useLocalStorage(`sd.exam.${classId}`, ''); const exams = data?.folders ?? []; const examView = examChoice === 'all' || examChoice === 'none' || exams.some((f) => f.id === examChoice) ? examChoice : exams.length ? exams[exams.length - 1].id : 'all'; const currentExam = exams.find((f) => f.id === examView) ?? null; const groupLabel = data?.class.groupLabel ?? 'Exam'; useAssistantContext(classId, currentExam ? `${data?.class.name} · ${currentExam.name}` : data?.class.name, [], currentExam?.id ?? null); const [filter, setFilter] = useState('all'); const [query, setQuery] = useState(''); const [sort, setSort] = useLocalStorage<'manual' | 'recent' | 'title'>('sd.classSort', 'manual'); const [collapsed, setCollapsed] = useLocalStorage>(`sd.folders.${classId}`, {}); const [newKind, setNewKind] = useState<{ kind: 'quiz' | 'deck' | 'note' | 'folder'; folderId?: string | null } | null>(null); const [rename, setRename] = useState[0]['target']>(null); const [move, setMove] = useState[0]['target']>(null); const [share, setShare] = useState<{ kind: ShareKind; id: string; title: string } | null>(null); const [importOpen, setImportOpen] = useState(false); const [generate, setGenerate] = useState(null); const [editClass, setEditClass] = useState(false); const [pasteOpen, setPasteOpen] = useState(false); const [uploads, setUploads] = useState([]); const [dragging, setDragging] = useState(false); const fileRef = useRef(null); const dragDepth = useRef(0); useEffect(() => { setPolling(Boolean(data?.items.some((i) => i.kind === 'document' && (i.status === 'pending' || i.status === 'processing')))); }, [data]); useEffect(() => { setFilter('all'); setQuery(''); }, [classId]); const upload = async (files: File[]) => { for (const file of files) { const id = Date.now() + Math.random(); setUploads((u) => [...u, { id, name: file.name, progress: 0 }]); const form = new FormData(); form.append('classId', classId); if (currentExam) form.append('folderId', currentExam.id); form.append('file', file); try { await uploadWithProgress('/api/documents', form, (p) => setUploads((u) => u.map((x) => (x.id === id ? { ...x, progress: p } : x)))); setUploads((u) => u.filter((x) => x.id !== id)); await refresh(); } catch (e) { setUploads((u) => u.map((x) => (x.id === id ? { ...x, error: errorMessage(e) } : x))); } } }; /** Items of the exam in view. */ const scoped = useMemo(() => { const items = data?.items ?? []; const known = new Set((data?.folders ?? []).map((f) => f.id)); if (examView === 'all') return items; if (examView === 'none') return items.filter((i) => !i.folderId || !known.has(i.folderId)); return items.filter((i) => i.folderId === examView); }, [data, examView]); const looseCount = useMemo(() => { const known = new Set((data?.folders ?? []).map((f) => f.id)); return (data?.items ?? []).filter((i) => !i.folderId || !known.has(i.folderId)).length; }, [data]); const counts = useMemo(() => { const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 }; for (const i of scoped) { c.all += 1; c[i.kind] += 1; } return c; }, [scoped]); const visible = useMemo(() => { const needle = query.trim().toLowerCase(); const list = scoped.filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle))); return list.sort((a, b) => sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt, ); }, [scoped, filter, query, sort]); if (q.isError) return q.refetch()} />; if (!data) { return (
{[0, 1, 2, 3].map((i) => ( ))}
); } const cls = data.class; const remove = async (item: Item) => { const noun = item.kind === 'deck' ? 'deck' : item.kind; const extra = item.kind === 'quiz' ? ' Its attempt history stays in your statistics.' : item.kind === 'deck' ? ' Review progress for its cards will be lost.' : item.kind === 'document' ? ' The uploaded file is removed from the server.' : ''; if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${item.title}" will be permanently deleted.${extra}`, confirmLabel: 'Delete', danger: true }))) return; try { await api.del(`/api/${ITEM_URL[item.kind]}/${item.id}`); await refresh(); toast.success('Deleted'); } catch (e) { toast.error(errorMessage(e)); } }; const duplicate = async (item: Item) => { try { await api.post(`/api/${ITEM_URL[item.kind]}/${item.id}/duplicate`, {}); await refresh(); toast.success('Duplicated'); } catch (e) { toast.error(errorMessage(e)); } }; const removeFolder = async (f: Folder) => { const noun = groupLabel.toLowerCase(); if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${f.name}" will be removed. Everything in it stays in the class, outside any ${noun}.`, confirmLabel: `Delete ${noun}`, danger: true }))) return; await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e))); if (examChoice === f.id) setExamChoice(''); await refresh(); }; const deleteClass = async () => { if (!(await confirm({ title: `Delete ${cls.name}?`, message: `This permanently deletes the class and everything in it: ${plural(counts.quiz, 'quiz', 'quizzes')}, ${plural(counts.deck, 'deck')}, ${plural(counts.document, 'document')} and ${plural(counts.note, 'note')}. Export it first if you might want it back.`, confirmLabel: 'Delete class', danger: true }))) return; try { await api.del(`/api/classes/${cls.id}`); await refresh(); navigate('/'); toast.success('Class deleted'); } catch (e) { toast.error(errorMessage(e)); } }; const primaryAction = (item: Item): ReactNode => { if (item.kind === 'quiz') { const z = item as QuizItem; if (z.activeAttemptId) return ( ); if (z.questionCount > 0) return ( ); return null; } if (item.kind === 'deck') { const d = item as DeckItem; if (d.dueCount + Math.min(d.newCount, 20) > 0 && d.cardCount > 0) return ( ); if (d.cardCount > 0) return ( ); } return null; }; const row = (item: Item, sortable?: SortableRenderProps) => { const doc = item.kind === 'document' ? (item as DocumentItem) : null; const busy = doc && (doc.status === 'pending' || doc.status === 'processing'); return (
  • {sortable?.handle}
    { // Dropping this onto the assistant adds it to the chat. e.dataTransfer.setData(ITEM_DRAG_TYPE, JSON.stringify({ kind: item.kind, id: item.id, title: item.title })); e.dataTransfer.effectAllowed = 'copyLink'; }} > {item.title}
    {busy ? ( <> {doc.status === 'pending' ? 'Waiting to be read' : 'Reading…'} ) : doc?.status === 'failed' ? ( {doc.error || 'Could not be read'} ) : ( itemMeta(item) )} {doc?.needsOcr && doc.status === 'ready' && Needs AI reading} {item.shared && ( Shared )}
    {primaryAction(item)} } > {item.kind === 'quiz' && (item as QuizItem).questionCount > 0 && ( <> } onSelect={() => start({ source: { type: 'quiz', quizId: item.id } })}> Quick practice } onSelect={() => setGenerate({ kind: 'deck', quizId: item.id, sourceLabel: item.title })}> Make flashcards from this )} {item.kind === 'deck' && (item as DeckItem).cardCount > 0 && ( <> } onSelect={() => navigate(`/decks/${item.id}/cram`)}> Browse all cards } onSelect={() => setGenerate({ kind: 'quiz', deckId: item.id, sourceLabel: item.title })}> Make a quiz from this )} {item.kind === 'document' && doc?.status === 'ready' && ( <> } onSelect={() => setGenerate({ documentIds: [item.id] })}> Generate from this } onSelect={() => assistant.open({ documentIds: [item.id], classId, newChat: true })}> Ask about this )} {item.kind === 'note' && ( } onSelect={() => setGenerate({ noteId: item.id, sourceLabel: item.title })}> Generate from this )} } onSelect={() => setRename({ kind: item.kind as EditableKind, id: item.id, title: item.title, description: item.kind === 'quiz' || item.kind === 'deck' ? item.description : undefined })}> Rename } onSelect={() => setMove({ kind: item.kind as EditableKind, id: item.id, title: item.title, classId, folderId: item.folderId })}> Move {(item.kind === 'quiz' || item.kind === 'deck') && ( } onSelect={() => duplicate(item)}> Duplicate )} } onSelect={() => setShare({ kind: item.kind, id: item.id, title: item.title })}> Share {(item.kind === 'quiz' || item.kind === 'deck') && ( } onSelect={() => downloadFile(`/api/${ITEM_URL[item.kind]}/${item.id}/export`)}> Export JSON )} {item.kind === 'document' && ( } onSelect={() => downloadFile(`/api/documents/${item.id}/file?download=1`)}> Download original )} } danger onSelect={() => remove(item)}> Delete
  • ); }; // Inside each section, items are grouped under a subheading per type. const KIND_ORDER = ['quiz', 'deck', 'note', 'document'] as const; const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', document: 'Class Materials', note: 'Notes' } as const; const KIND_HEADING_ICON = { quiz: , deck: , document: , note: } as const; const canSort = sort === 'manual' && !query.trim(); const persistOrder = (kind: Item['kind']) => async (ids: string[]) => { // Keys within one folder group; keep the rest of this kind in their current relative order. const all = (data?.items ?? []).filter((i) => i.kind === kind).sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt - b.createdAt).map((i) => i.id); const moved = new Set(ids); let k = 0; const merged = all.map((id) => (moved.has(id) ? ids[k++] : id)); try { await api.post(`/api/classes/${classId}/items/reorder`, { kind, ids: merged }); await refresh(); } catch (e) { toast.error(errorMessage(e)); await refresh(); } }; const list = (items: Item[]) => canSort && items.length > 1 ? ( i.id} getLabel={(i) => i.title} noun={items[0].kind === 'deck' ? 'deck' : items[0].kind} onReorder={(ids) => void persistOrder(items[0].kind)(ids)} render={(item, props) => row(item, props)} /> ) : ( items.map((i) => row(i)) ); const section = (items: Item[]) => { if (filter !== 'all') { // One kind only; group by kind anyway so ordering stays within a kind. return
      {list(items)}
    ; } return (
    {KIND_ORDER.filter((k) => items.some((i) => i.kind === k)).map((k, n) => { const group = items.filter((i) => i.kind === k); return (

    svg]:size-3.5', n > 0 && 'border-t')}> {KIND_HEADING_ICON[k]} {KIND_HEADING[k]} {group.length}

      {list(group)}
    ); })}
    ); }; const loose = visible.filter((i) => !i.folderId || !data.folders.some((f) => f.id === i.folderId)); const searching = query.trim().length > 0 || filter !== 'all'; const isEmpty = data.items.length === 0 && uploads.length === 0; const addMenu = ( }> Add } > {currentExam && Adding to {currentExam.name}} } onSelect={() => setNewKind({ kind: 'quiz', folderId: currentExam?.id ?? null })}> New quiz } onSelect={() => setNewKind({ kind: 'deck', folderId: currentExam?.id ?? null })}> New flashcard deck } onSelect={() => setNewKind({ kind: 'note', folderId: currentExam?.id ?? null })}> New note } onSelect={() => setNewKind({ kind: 'folder' })}> New {groupLabel.toLowerCase()} } onSelect={() => fileRef.current?.click()}> Upload class materials } onSelect={() => setPasteOpen(true)}> Paste text as a document } onSelect={() => setImportOpen(true)}> Import quizzes or cards ); return (
    { if (!e.dataTransfer.types.includes('Files')) return; dragDepth.current += 1; setDragging(true); }} onDragLeave={() => { dragDepth.current = Math.max(0, dragDepth.current - 1); if (dragDepth.current === 0) setDragging(false); }} onDragOver={(e) => e.dataTransfer.types.includes('Files') && e.preventDefault()} onDrop={(e) => { if (!e.dataTransfer.files.length) return; e.preventDefault(); dragDepth.current = 0; setDragging(false); void upload([...e.dataTransfer.files]); }} > (e.target.files && upload([...e.target.files]), (e.target.value = ''))} />
    {cls.code || 'Class'} {cls.archived && Archived} {data.share?.enabled && ( Shared )}

    {cls.name}

    {cls.description &&

    {cls.description}

    }
    {data.due.total > 0 && ( )} {addMenu} } > } onSelect={() => setEditClass(true)}> Edit class } onSelect={() => setShare({ kind: 'class', id: cls.id, title: cls.name })}> Share whole class } onSelect={() => downloadFile(`/api/export/class/${cls.id}`)}> Export class (JSON) } onSelect={async () => { await api.patch(`/api/classes/${cls.id}`, { archived: !cls.archived }).catch((e) => toast.error(errorMessage(e))); await refresh(); }} > {cls.archived ? 'Unarchive' : 'Archive'} } danger onSelect={deleteClass}> Delete class
    {isEmpty ? (
    } title="Fill this class with material" action={ <> } > Drop lecture slides, PDFs or notes anywhere on this page, import existing quizzes and flashcards, or write your own.
    ) : ( <> setNewKind({ kind: 'folder' })} onRename={(f) => setRename({ kind: 'folder', id: f.id, title: f.name })} onShare={(f) => setShare({ kind: 'folder', id: f.id, title: f.name })} onDelete={removeFolder} onReorder={async (ids) => { await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e))); await refresh(); }} />
    {( [ ['all', 'All'], ['quiz', 'Quizzes'], ['deck', 'Flashcards'], ['note', 'Notes'], ['document', 'Class Materials'], ] as const ).map(([v, label]) => ( ))}
    setQuery(e.target.value)} placeholder="Filter" aria-label="Filter this class" className="h-9 w-36 pl-8 sm:w-48" />
    Your order (drag to rearrange), icon: }, { value: 'recent', label: Recent, icon: }, { value: 'title', label: A to Z, icon: }, ]} />
    {uploads.length > 0 && (
      {uploads.map((u) => (
    • {u.name}
      {u.error ?
      {u.error}
      : }
      {u.error && ( setUploads((x) => x.filter((y) => y.id !== u.id))}> )}
    • ))}
    )} {visible.length === 0 ? (
    {currentExam && !searching ? ( } action={ <> } > Add this {groupLabel.toLowerCase()}'s slides and notes, then generate quizzes and flashcards from them. Use Move on anything already in the class to bring it here. ) : ( }> {query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'} )}
    ) : examView !== 'all' ? ( section(visible) ) : (
    {loose.length > 0 && section(loose)} f.id} getLabel={(f) => f.name} noun="folder" liveAs="div" disabled={!canSort || searching || data.folders.length < 2} onReorder={async (ids) => { await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e))); await refresh(); }} render={(f, sortable) => { const items = visible.filter((i) => i.folderId === f.id); if (items.length === 0 && searching) return null; const isCollapsed = collapsed[f.id] && !searching; return (
    {sortable.handle} } > } onSelect={() => setNewKind({ kind: 'quiz', folderId: f.id })}> New quiz here } onSelect={() => setNewKind({ kind: 'deck', folderId: f.id })}> New deck here } onSelect={() => setRename({ kind: 'folder', id: f.id, title: f.name })}> Rename } onSelect={() => setShare({ kind: 'folder', id: f.id, title: f.name })}> Share folder } danger onSelect={() => removeFolder(f)}> Delete folder
    {!isCollapsed && (items.length > 0 ? ( section(items) ) : (
    Empty. Use "Move" on any item to put it here.
    ))}
    ); }} />
    )} )} {dragging && (
    Drop to add to {cls.name}
    PDF, Word, PowerPoint, text, Markdown and images
    )} setNewKind(null)} /> setRename(null)} /> setMove(null)} /> setShare(null)} /> setImportOpen(false)} classId={classId} folderId={currentExam?.id ?? null} /> setGenerate(null)} classId={classId} folderId={currentExam?.id ?? null} preset={generate ?? undefined} /> setPasteOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
    ); } function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) { const refresh = useRefresh(); const [title, setTitle] = useState(''); const [text, setText] = useState(''); const [busy, setBusy] = useState(false); useEffect(() => { if (open) { setTitle(''); setText(''); } }, [open]); const save = async () => { setBusy(true); try { await api.post('/api/documents/text', { classId, folderId: folderId ?? null, title, text }); await refresh(); toast.success('Added as a document'); onClose(); } catch (e) { toast.error(errorMessage(e)); } finally { setBusy(false); } }; return ( !o && onClose()} title="Paste text as a document" size="lg" footer={ <> } >
    setTitle(e.target.value)} placeholder="Week 4 lecture notes" maxLength={200} />