Study/web/src/pages/QuizPage.tsx
Elijah 85d5c9186d
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
Fifth revision: share-link AI safety, sturdier generation, cleaner UI
- Malformed model JSON is sent back for repair, then retried; a failed job
  starts over once before it fails. Visitors can dismiss failed sets.
- Generated sets get a short distinct name and description; flashcards are
  atomic and have no hints; standard study shows known/learning counts.
- Share links: "In progress" list, finished sets join the normal lists with a
  "New" tag, plain progress steps, newest exam first.
- Share-link AI expires after a week, can be limited to the US or Arizona
  (DB-IP Lite or Cloudflare headers) and is locked by abuse protection
  (migration 8).
- The assistant never answers from general knowledge; MCP and web search
  tools load without a manual test.
- Plain-text copy, no question count in exam mode, filler text removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:17:50 -07:00

765 lines
35 KiB
TypeScript

import { ArrowDown, ArrowUp, BookOpen, Check, ChevronRight, ClipboardList, Copy, Download, FolderInput, History, Layers, ListPlus, MoreHorizontal, Pencil, Play, Plus, RotateCcw, Search, Share2, Sparkles, Stamp, Timer, Trash2, WandSparkles } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { blankQuestion, letterGrade, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
import { parseImport } from '@shared/importer';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { QuestionEditor } from '@/features/editors';
import { GenerateDialog, type GeneratePreset } from '@/features/GenerateDialog';
import { useStartSession } from '@/features/study';
import { api, errorMessage } from '@/lib/api';
import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useQuiz, useRefresh } from '@/lib/queries';
import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { SortableList } from '@/ui/Sortable';
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
interface StartPrefs {
mode: 'practice' | 'exam';
shuffleQuestions: boolean;
shuffleOptions: boolean;
}
/** Session options (mode, length, shuffling, exam time limit), shared by the start screen and the start dialog. */
function useStartOptions(quizId: string, total: number, active: boolean) {
const { start, starting } = useStartSession();
const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true });
const [count, setCount] = useState(total);
const [timed, setTimed] = useState(false);
const [minutes, setMinutes] = useState(30);
useEffect(() => {
if (active) {
setCount(total);
setMinutes(Math.max(5, Math.round(total * 1.2)));
setTimed(false);
}
}, [active, total]);
const go = () =>
start({
mode: prefs.mode,
source: { type: 'quiz', quizId },
shuffleQuestions: prefs.shuffleQuestions,
shuffleOptions: prefs.shuffleOptions,
// An exam is always the whole quiz.
count: prefs.mode === 'practice' && count < total ? count : undefined,
// A time limit is an exam option only; practice sessions are never timed.
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
});
return { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, go, starting, total };
}
function StartOptionsFields({ o }: { o: ReturnType<typeof useStartOptions> }) {
const { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, total } = o;
return (
<div className="space-y-5">
<Segmented
label="Mode"
value={prefs.mode}
onChange={(mode) => setPrefs((p) => ({ ...p, mode }))}
options={[
{ value: 'practice', label: 'Practice' },
{ value: 'exam', label: 'Exam' },
]}
className="w-full"
/>
{prefs.mode === 'practice' && (
<Field label={`Questions: ${count === total ? `all ${total}` : `${count} of ${total}`}`}>
<input type="range" min={1} max={total} value={count} onChange={(e) => setCount(Number(e.target.value))} className="mt-1 w-full accent-[var(--accent)]" disabled={total <= 1} />
</Field>
)}
<div className="space-y-4 rounded-xl border border-line p-4">
<Switch checked={prefs.shuffleQuestions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQuestions: v }))} label="Shuffle questions" />
<Switch checked={prefs.shuffleOptions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleOptions: v }))} label="Shuffle answer choices" />
{prefs.mode === 'exam' && (
<>
<Switch checked={timed} onChange={setTimed} label="Time limit" />
{timed && (
<div className="flex items-center gap-2">
<Timer className="size-4 text-ink-3" />
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setMinutes(Math.max(1, Math.min(600, Number(e.target.value) || 1)))} className="w-24" aria-label="Minutes" />
<span className="text-sm text-ink-2">minutes</span>
</div>
)}
</>
)}
</div>
</div>
);
}
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
const o = useStartOptions(quizId, total, open);
return (
<Dialog
open={open}
onOpenChange={(v) => !v && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go}>
Start
</Button>
</>
}
>
<StartOptionsFields o={o} />
</Dialog>
);
}
/** The quiz start screen: how to take it, without showing any questions or answers. */
function StartPanel({ quizId, total, resume, onShowQuestions }: { quizId: string; total: number; resume: { id: string; answeredCount: number; questionCount: number } | null; onShowQuestions: () => void }) {
const o = useStartOptions(quizId, total, true);
if (total === 0) {
return (
<div className="card border-dashed">
<EmptyState icon={<BookOpen />} title="No questions yet" action={<Button variant="primary" icon={<Plus />} onClick={onShowQuestions}>Add questions</Button>}>
Add questions to this quiz before taking it.
</EmptyState>
</div>
);
}
return (
<section className="card p-5 sm:p-6">
{resume && (
<Callout
tone="warn"
icon={<Play />}
className="mb-5"
title="You have a session in progress"
action={
<Button to={`/session/${resume.id}`} variant="marker" size="sm">
Resume ({resume.answeredCount}/{resume.questionCount})
</Button>
}
>
Pick up where you left off, or start a new session below.
</Callout>
)}
<StartOptionsFields o={o} />
<div className="mt-6 flex flex-wrap items-center gap-2 border-t border-line pt-5">
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go} className="min-w-40">
{resume ? 'Start new session' : 'Start'}
</Button>
</div>
</section>
);
}
/** Paste several questions (or cards) as text or JSON and add them to an existing item. */
export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) {
const [text, setText] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (open) setText('');
}, [open]);
const parsed = useMemo(() => (text.trim() ? parseImport(text, { prefer: kind }) : null), [text, kind]);
const all: (DraftQuestion | DraftCard)[] = (parsed?.items ?? []).flatMap((it): (DraftQuestion | DraftCard)[] => (kind === 'quiz' && it.kind === 'quiz' ? it.questions : kind === 'deck' && it.kind === 'deck' ? it.cards : []));
const valid = all.filter((x) => ('stem' in x ? validateDraftQuestion(x, 0).every((i) => i.level !== 'error') : Boolean(x.front.trim() && x.back.trim())));
const noun = kind === 'quiz' ? 'question' : 'card';
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title={`Add several ${noun}s`}
size="lg"
footer={
<>
<span className="mr-auto text-[13px] text-ink-3" aria-live="polite">
{parsed ? (all.length === 0 ? `No ${noun}s recognised yet` : `${valid.length} ready${all.length > valid.length ? `, ${all.length - valid.length} with problems will be skipped` : ''}`) : ''}
</span>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button
variant="primary"
disabled={valid.length === 0}
loading={busy}
onClick={async () => {
setBusy(true);
try {
await onAdd(valid);
onClose();
} finally {
setBusy(false);
}
}}
>
Add {valid.length > 0 ? plural(valid.length, noun) : ''}
</Button>
</>
}
>
<Textarea
autoFocus
rows={14}
value={text}
onChange={(e) => setText(e.target.value)}
spellCheck={false}
className="num text-[13px]"
aria-label={`Paste ${noun}s`}
placeholder={
kind === 'quiz'
? '1. Which electrolyte imbalance causes peaked T waves?\nA. Hypokalemia\n*B. Hyperkalemia\nC. Hyponatremia\nRationale: High potassium speeds repolarisation.\nTopic: Electrolytes\n\n2. Next question…\n\nMark correct choices with * (or add a line "Answer: B, D"). JSON works too.'
: 'Furosemide\tLoop diuretic; monitor potassium\nMetoprolol\tBeta-1 blocker; hold for HR under 60\n\nOne card per line: front, a tab (or " - " or "::"), then back. JSON works too.'
}
/>
</Dialog>
);
}
function QuestionView({ q, index, stat }: { q: Question; index: number; stat?: { seen: number; correct: number; lastCorrect: boolean } }) {
const [open, setOpen] = useState(false);
const hasMore = Boolean(q.rationale) || q.options.some((o) => o.why);
return (
<div>
<div className="mb-2 flex flex-wrap items-center gap-1.5">
<span className="num text-xs font-semibold text-ink-3">{String(index + 1).padStart(2, '0')}</span>
<Badge>{QUESTION_TYPE_LABEL[q.type]}</Badge>
{q.topic && <Badge tone="accent">{q.topic}</Badge>}
{q.difficulty !== 'medium' && <Badge>{q.difficulty}</Badge>}
{stat && stat.seen > 0 && (
<Badge tone={stat.lastCorrect ? 'good' : 'bad'}>
{stat.correct}/{stat.seen} correct
</Badge>
)}
</div>
<Markdown serif className="text-[17px]">
{q.stem}
</Markdown>
<ul className="mt-3 space-y-1.5">
{q.options.map((o, i) => (
<li key={o.id} className="flex items-start gap-2.5 text-[15px]">
<span className={cx('num mt-0.5 grid size-6 shrink-0 place-items-center text-xs font-semibold', q.type === 'single' ? 'rounded-full' : 'rounded-md', o.correct ? 'bg-good text-white dark:text-[#10241a]' : 'bg-sunken text-ink-3')}>
{o.correct ? <Check className="size-3.5" strokeWidth={3} /> : optionLetter(i)}
</span>
<div className="min-w-0 flex-1">
<Markdown className={o.correct ? 'font-medium' : 'text-ink-2'}>{o.text}</Markdown>
{open && o.why && <div className="mt-0.5 text-[13px] text-ink-3">{o.why}</div>}
</div>
</li>
))}
</ul>
{hasMore && (
<>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="mt-3 flex items-center gap-1 text-[13px] font-medium text-accent hover:underline">
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
{open ? 'Hide rationale' : 'Show rationale'}
</button>
{open && q.rationale && (
<div className="mt-2 rounded-xl bg-sunken px-4 py-3">
<Markdown className="text-[14.5px]">{q.rationale}</Markdown>
</div>
)}
</>
)}
</div>
);
}
export default function QuizPage() {
const { quizId = '' } = useParams();
const [params, setParams] = useSearchParams();
const navigate = useNavigate();
const refresh = useRefresh();
const confirm = useConfirm();
const ai = useAiStatus();
const q = useQuiz(quizId);
const data = q.data;
useDocumentTitle(data?.quiz.title);
useAssistantContext(data?.quiz.classId, data?.quiz.title);
const { start, starting } = useStartSession();
// The start screen comes first, so opening a quiz never reveals its answers.
const [tab, setTab] = useState<'start' | 'questions' | 'history'>(() => (params.get('q') || params.get('edit') ? 'questions' : 'start'));
const [editing, setEditing] = useState<string | 'new' | null>(null);
const [draft, setDraft] = useState<DraftQuestion>(blankQuestion());
const [saving, setSaving] = useState(false);
const [filter, setFilter] = useState('');
const [onlyMissed, setOnlyMissed] = useState(false);
const [startOpen, setStartOpen] = useState(false);
const [bulkOpen, setBulkOpen] = useState(false);
const [rename, setRename] = useState(false);
const [move, setMove] = useState(false);
const [share, setShare] = useState(false);
const [generate, setGenerate] = useState<GeneratePreset | null>(null);
const newRef = useRef<HTMLDivElement>(null);
// Deep links: ?start=1 opens the start dialog, ?edit=1 a blank question, ?q=<id> scrolls to a question.
useEffect(() => {
if (!data) return;
const next = new URLSearchParams(params);
if (params.get('start') && data.questions.length > 0) setStartOpen(true);
if (params.get('edit')) {
setDraft(blankQuestion());
setEditing('new');
setTab('questions');
}
const target = params.get('q');
if (target) setTab('questions');
if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
if (params.get('start') || params.get('edit')) {
next.delete('start');
next.delete('edit');
setParams(next, { replace: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data?.quiz.id]);
const topics = useMemo(() => [...new Set((data?.questions ?? []).map((x) => x.topic).filter(Boolean))].sort(), [data]);
const stats = data?.questionStats ?? {};
const shown = useMemo(() => {
const needle = filter.trim().toLowerCase();
return (data?.questions ?? [])
.map((question, index) => ({ question, index }))
.filter(({ question }) => (!needle || question.stem.toLowerCase().includes(needle) || question.topic.toLowerCase().includes(needle)) && (!onlyMissed || stats[question.id]?.lastCorrect === false));
}, [data, filter, onlyMissed, stats]);
if (q.isError) return <ErrorState title="Quiz not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
return (
<div className="space-y-4">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-10 w-96 max-w-full" />
<Skeleton className="h-24" />
{[0, 1].map((i) => (
<Skeleton key={i} className="h-48" />
))}
</div>
);
}
const { quiz, questions, history } = data;
const full = history.filter((h) => h.kind === 'full' && h.maxScore);
const best = full.length ? Math.max(...full.map((h) => pct(h.score, h.maxScore) ?? 0)) : null;
const last = full.length ? pct(full[0].score, full[0].maxScore) : null;
const missedCount = Object.values(stats).filter((s) => !s.lastCorrect).length;
const editingIssues = editing ? validateDraftQuestion(draft, 0) : [];
const canSave = editingIssues.every((i) => i.level !== 'error');
const beginEdit = (question: Question) => {
setDraft(questionToDraft(question));
setEditing(question.id);
};
const beginNew = () => {
setTab('questions');
setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' });
setEditing('new');
setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60);
};
const save = async (another = false) => {
if (!canSave || !editing) return;
setSaving(true);
try {
if (editing === 'new') await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [draft] });
else await api.patch(`/api/questions/${editing}`, draft);
await refresh();
if (another && editing === 'new') {
setDraft({ ...blankQuestion(draft.type), topic: draft.topic });
setTimeout(() => newRef.current?.querySelector('textarea')?.focus(), 60);
} else setEditing(null);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setSaving(false);
}
};
const removeQuestion = async (question: Question) => {
if (!(await confirm({ title: 'Delete this question?', message: 'It will be removed from the quiz. Past attempts keep their own copy.', confirmLabel: 'Delete', danger: true }))) return;
await api.del(`/api/questions/${question.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const moveQuestion = async (index: number, delta: number) => {
const ids = questions.map((x) => x.id);
const to = index + delta;
if (to < 0 || to >= ids.length) return;
[ids[index], ids[to]] = [ids[to], ids[index]];
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const duplicateQuestion = async (question: Question, index: number) => {
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: [questionToDraft(question)], index: index + 1 }).catch((e) => toast.error(errorMessage(e)));
await refresh();
};
const deleteQuiz = async () => {
if (!(await confirm({ title: 'Delete this quiz?', message: `"${quiz.title}" and its ${plural(questions.length, 'question')} will be permanently deleted.`, confirmLabel: 'Delete quiz', danger: true }))) return;
try {
await api.del(`/api/quizzes/${quiz.id}`);
await refresh();
navigate(`/classes/${quiz.classId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const improve = async (ids?: string[]) => {
try {
const res = await api.post<{ draftId: string }>('/api/ai/improve', { quizId: quiz.id, questionIds: ids });
navigate(`/drafts/${res.draftId}`);
} catch (e) {
toast.error(errorMessage(e));
}
};
const editorFooter = (isNew: boolean) => (
<div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<span className="mr-auto" />
<Button variant="ghost" onClick={() => setEditing(null)}>
Cancel
</Button>
{isNew && (
<Button disabled={!canSave} loading={saving} onClick={() => save(true)}>
Save and add another
</Button>
)}
<Button variant="primary" disabled={!canSave} loading={saving} onClick={() => save(false)}>
Save
</Button>
</div>
);
return (
<div className={cx('animate-in', `tab-${data.class.color}`)}>
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-[13px] text-ink-3">
<Link to={`/classes/${data.class.id}`} className="flex items-center gap-1.5 hover:text-ink">
<ClassDot color={data.class.color} />
{data.class.name}
</Link>
<ChevronRight className="size-3.5" />
<span>Quiz</span>
</nav>
<header className="mb-6 flex flex-wrap items-start justify-between gap-x-6 gap-y-4">
<div className="min-w-0">
<h1 className="display text-[30px] sm:text-[36px]">{quiz.title}</h1>
{quiz.description && <p className="mt-1.5 max-w-2xl text-[15px] text-ink-2">{quiz.description}</p>}
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-ink-2">
<span>{plural(questions.length, 'question')}</span>
{full.length > 0 && (
<>
<span>
Last{' '}
<strong className="num text-ink">
{last !== null ? `${letterGrade(last)} · ${last}%` : '—'}
</strong>
</span>
<span>
Best{' '}
<strong className="num text-ink">
{best !== null ? `${letterGrade(best)} · ${best}%` : '—'}
</strong>
</span>
<span>{plural(history.length, 'attempt')}</span>
</>
)}
{data.share?.enabled && (
<Badge tone="accent">
<Share2 /> Shared
</Badge>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{data.activeAttempt ? (
<Button to={`/session/${data.activeAttempt.id}`} variant="marker" size="lg" icon={<Play className="fill-current" />}>
Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount})
</Button>
) : null}
{tab !== 'start' && (
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
{data.activeAttempt ? 'Start new' : 'Start'}
</Button>
)}
<Menu
trigger={
<IconButton label="Quiz options" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
{missedCount > 0 && (
<MenuItem icon={<RotateCcw />} onSelect={() => start({ source: { type: 'missed', quizId: quiz.id } })}>
Practice {missedCount} missed
</MenuItem>
)}
{ai.data?.ready && questions.length > 0 && (
<>
<MenuItem icon={<WandSparkles />} onSelect={() => improve()}>
Improve questions with AI
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setGenerate({ kind: 'deck', quizId: quiz.id, sourceLabel: quiz.title })}>
Make flashcards from this
</MenuItem>
</>
)}
<MenuSeparator />
<MenuItem icon={<Pencil />} onSelect={() => setRename(true)}>
Rename
</MenuItem>
<MenuItem icon={<FolderInput />} onSelect={() => setMove(true)}>
Move
</MenuItem>
<MenuItem
icon={<Copy />}
onSelect={async () => {
const res = await api.post<{ quiz: { id: string } }>(`/api/quizzes/${quiz.id}/duplicate`, {}).catch((e) => (toast.error(errorMessage(e)), null));
if (res) {
await refresh();
navigate(`/quizzes/${res.quiz.id}`);
toast.success('Duplicated');
}
}}
>
Duplicate
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => setShare(true)}>
Share
</MenuItem>
<MenuItem icon={<Download />} onSelect={() => downloadFile(`/api/quizzes/${quiz.id}/export`)}>
Export JSON
</MenuItem>
<MenuItem
icon={<Stamp />}
onSelect={async () => {
await api.post('/api/templates/from', { kind: 'quiz', id: quiz.id }).then(() => toast.success('Saved as a template')).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
Save as template
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={deleteQuiz}>
Delete quiz
</MenuItem>
</Menu>
</div>
</header>
<div className="mb-4 flex flex-wrap items-center gap-2">
<Segmented
value={tab}
onChange={setTab}
label="View"
options={[
{ value: 'start', label: 'Start', icon: <Play /> },
{ value: 'questions', label: `Questions`, icon: <ClipboardList /> },
{ value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> },
]}
/>
{tab === 'questions' && questions.length > 0 && (
<div className="ml-auto flex flex-wrap items-center gap-2">
{missedCount > 0 && (
<button type="button" aria-pressed={onlyMissed} onClick={() => setOnlyMissed(!onlyMissed)} className={cx('h-9 rounded-full border px-3 text-[13px] font-medium', onlyMissed ? 'border-bad bg-bad-soft text-bad' : 'border-line-strong text-ink-2 hover:border-ink-3')}>
Missed ({missedCount})
</button>
)}
{questions.length > 5 && (
<div className="relative">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Find a question" aria-label="Find a question" className="h-9 w-44 pl-8 sm:w-56" />
</div>
)}
</div>
)}
</div>
{tab === 'start' ? (
<StartPanel
quizId={quiz.id}
total={questions.length}
resume={data.activeAttempt ? { id: data.activeAttempt.id, answeredCount: data.activeAttempt.answeredCount, questionCount: data.activeAttempt.questionCount } : null}
onShowQuestions={() => (questions.length === 0 ? beginNew() : setTab('questions'))}
/>
) : tab === 'questions' ? (
<>
{questions.length === 0 && editing !== 'new' ? (
<div className="card border-dashed">
<EmptyState
icon={<BookOpen />}
title="No questions yet"
action={
<>
<Button variant="primary" icon={<Plus />} onClick={beginNew}>
Write a question
</Button>
<Button icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
Paste several
</Button>
<Button icon={<Sparkles />} onClick={() => navigate(`/classes/${quiz.classId}`)}>
Generate from class materials
</Button>
</>
}
>
Write questions one at a time, paste a batch as text, or generate them from your class materials.
</EmptyState>
</div>
) : (
<ol className="space-y-3">
<SortableList
items={shown}
getKey={(x) => x.question.id}
getLabel={(x) => `question ${x.index + 1}`}
noun="question"
disabled={shown.length < 2 || shown.length !== questions.length || editing !== null}
onReorder={async (ids) => {
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
render={({ question, index }, sortable) => (
<li key={question.id} id={`q-${question.id}`} ref={sortable.ref} style={sortable.style} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker', sortable.dragging && 'shadow-3')}>
{editing === question.id ? (
<>
<QuestionEditor value={draft} onChange={setDraft} issues={editingIssues.filter((i) => draft.stem || i.field !== 'stem')} topics={topics} autoFocus onSubmit={() => save(false)} />
{editorFooter(false)}
</>
) : (
<div className="flex items-start gap-2">
{sortable.handle && <div className="-mt-1 -ml-2 sm:-ml-3">{sortable.handle}</div>}
<div className="min-w-0 flex-1">
<QuestionView q={question} index={index} stat={stats[question.id]} />
</div>
<div className="flex shrink-0 flex-col sm:flex-row">
<IconButton label="Edit question" size="sm" onClick={() => beginEdit(question)}>
<Pencil />
</IconButton>
<Menu
trigger={
<IconButton label="Question options" size="sm" tooltip={false}>
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Copy />} onSelect={() => duplicateQuestion(question, index)}>
Duplicate
</MenuItem>
<MenuItem icon={<ArrowUp />} disabled={index === 0} onSelect={() => moveQuestion(index, -1)}>
Move up
</MenuItem>
<MenuItem icon={<ArrowDown />} disabled={index === questions.length - 1} onSelect={() => moveQuestion(index, 1)}>
Move down
</MenuItem>
{ai.data?.ready && (
<MenuItem icon={<WandSparkles />} onSelect={() => improve([question.id])}>
Improve with AI
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => removeQuestion(question)}>
Delete
</MenuItem>
</Menu>
</div>
</div>
)}
</li>
)}
/>
{shown.length === 0 && questions.length > 0 && (
<li className="card">
<EmptyState icon={<Search />} title="No questions match" />
</li>
)}
</ol>
)}
<div ref={newRef} className="mt-3 scroll-mt-24">
{editing === 'new' ? (
<div className="card border-accent/40 p-4 ring-2 ring-accent/15 sm:p-5">
<div className="eyebrow mb-4">New question</div>
<QuestionEditor value={draft} onChange={setDraft} issues={[]} topics={topics} autoFocus onSubmit={() => save(true)} />
{!canSave && draft.stem.trim() && <div className="mt-3 text-[13px] text-ink-3">{editingIssues.find((i) => i.level === 'error')?.message}</div>}
{editorFooter(true)}
</div>
) : (
questions.length > 0 && (
<div className="flex flex-wrap gap-2">
<Button icon={<Plus />} onClick={beginNew}>
Add question
</Button>
<Button variant="ghost" icon={<ListPlus />} onClick={() => setBulkOpen(true)}>
Paste several
</Button>
</div>
)
)}
</div>
</>
) : history.length === 0 ? (
<div className="card">
<EmptyState icon={<History />} title="No attempts yet">
Finished sessions are listed here with your score and time.
</EmptyState>
</div>
) : (
<>
{full.length >= 2 && (
<Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}>
{last !== null && best !== null && last >= best ? `Your latest attempt (${letterGrade(last)}, ${last}%) is your best so far.` : `Latest ${last !== null ? `${letterGrade(last)} (${last}%)` : '—'}, best ${best !== null ? `${letterGrade(best)} (${best}%)` : '—'} across ${plural(full.length, 'full attempt')}.`}
</Callout>
)}
<ul className="card divide-y divide-line">
{history.map((h) => {
const p = pct(h.score, h.maxScore);
const tone = gradeTone(p);
return (
<li key={h.id}>
<Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-11 w-14 shrink-0 place-items-center rounded-[10px] leading-none font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>
{p === null ? (
'—'
) : (
<span className="flex flex-col items-center gap-0.5">
<span className="text-[16px]">{letterGrade(p)}</span>
<span className="text-[11px] font-medium opacity-80">{p}%</span>
</span>
)}
</span>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">
{h.completedAt ? formatDateTime(h.completedAt) : ''}
<span className="ml-2 font-normal text-ink-3">{timeAgo(h.completedAt)}</span>
</span>
<span className="text-xs text-ink-3">
{h.mode === 'exam' ? 'Exam' : 'Practice'}
{h.kind !== 'full' ? ' · missed only' : ''} · {h.maxScore ?? h.questionCount} scored{h.elapsedSec > 0 ? ` · ${formatMinutes(h.elapsedSec)}` : ''}
</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
</li>
);
})}
</ul>
</>
)}
<StartSessionDialog open={startOpen} onClose={() => setStartOpen(false)} quizId={quiz.id} total={questions.length} title={quiz.title} />
<BulkAddDialog
open={bulkOpen}
onClose={() => setBulkOpen(false)}
kind="quiz"
onAdd={async (items) => {
try {
await api.post(`/api/quizzes/${quiz.id}/questions`, { questions: items });
await refresh();
toast.success(`Added ${plural(items.length, 'question')}`);
} catch (e) {
toast.error(errorMessage(e));
throw e;
}
}}
/>
<RenameDialog target={rename ? { kind: 'quiz', id: quiz.id, title: quiz.title, description: quiz.description } : null} onClose={() => setRename(false)} />
<MoveDialog target={move ? { kind: 'quiz', id: quiz.id, title: quiz.title, classId: quiz.classId, folderId: quiz.folderId } : null} onClose={() => setMove(false)} />
<ShareDialog target={share ? { kind: 'quiz', id: quiz.id, title: quiz.title } : null} onClose={() => setShare(false)} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={quiz.classId} folderId={quiz.folderId} preset={generate ?? undefined} />
{starting && <span className="sr-only" role="status">Starting session</span>}
</div>
);
}