Add the V2 web app: design system, shell, study flows, AI, settings, sharing

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:53:01 -07:00
parent eae109c166
commit 74a98ac1f1
52 changed files with 11976 additions and 1 deletions

519
web/src/features/quiz.tsx Normal file
View file

@ -0,0 +1,519 @@
import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { isFullyCorrect, optionLetter, scoreQuestion, type SataScoring } from '@shared/content';
import type { AnswerState, SnapshotQuestion } from '@/lib/types';
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Dialog, IconButton, Kbd, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ option list ------------------------------ */
function OptionList({
question,
selected,
revealed,
onToggle,
}: {
question: SnapshotQuestion;
selected: string[];
/** Show which choices are correct (after checking in practice, or in review). */
revealed: boolean;
onToggle?: (id: string) => void;
}) {
const multi = question.type === 'multi';
return (
<ul className="space-y-2.5" role={multi ? 'group' : 'radiogroup'} aria-label="Answer choices">
{question.options.map((o, i) => {
const picked = selected.includes(o.id);
const state = !revealed ? (picked ? 'picked' : 'idle') : o.correct ? (picked ? 'right' : 'missed') : picked ? 'wrong' : 'idle';
const styles = {
idle: 'border-line-strong bg-surface',
picked: 'border-accent bg-accent-soft ring-1 ring-accent',
right: 'border-good bg-good-soft ring-1 ring-good',
missed: 'border-good/60 bg-surface border-dashed',
wrong: 'border-bad bg-bad-soft ring-1 ring-bad',
}[state];
const key = {
idle: 'border-line-strong text-ink-3 bg-surface',
picked: 'border-accent bg-accent text-accent-ink',
right: 'border-good bg-good text-white dark:text-[#10241a]',
missed: 'border-good text-good bg-surface',
wrong: 'border-bad bg-bad text-white dark:text-[#2a1210]',
}[state];
return (
<li key={o.id}>
<button
type="button"
role={multi ? 'checkbox' : 'radio'}
aria-checked={picked}
disabled={revealed || !onToggle}
onClick={() => onToggle?.(o.id)}
className={cx('flex w-full items-start gap-3 rounded-[14px] border px-3.5 py-3 text-left transition-[background,border-color,box-shadow] disabled:cursor-default', styles, !revealed && onToggle && 'hover:border-ink-3 active:scale-[0.995]')}
>
<span className={cx('num mt-px grid size-7 shrink-0 place-items-center border text-[13px] font-semibold', multi ? 'rounded-[8px]' : 'rounded-full', key)}>
{state === 'right' || state === 'missed' ? <Check className="size-4" strokeWidth={3} /> : state === 'wrong' ? <X className="size-4" strokeWidth={3} /> : optionLetter(i)}
</span>
<span className="min-w-0 flex-1">
<Markdown className="text-[16px] leading-snug">{o.text}</Markdown>
{revealed && (state === 'missed' || state === 'wrong' || state === 'right') && (
<span className={cx('mt-1 block text-[13px] font-medium', state === 'wrong' ? 'text-bad' : 'text-good')}>
{state === 'right' ? 'Correct' : state === 'missed' ? (multi ? 'Correct, not selected' : 'Correct answer') : 'Your answer'}
</span>
)}
{revealed && o.why && <span className="mt-1 block text-[13.5px] leading-snug text-ink-2">{o.why}</span>}
</span>
</button>
</li>
);
})}
</ul>
);
}
function Verdict({ score }: { score: number }) {
const full = isFullyCorrect(score);
const partial = !full && score > 0;
return (
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')} role="status">
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
</div>
);
}
/* ------------------------------ runner ------------------------------ */
export interface RunnerProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
index: number;
elapsedSec: number;
timeLimitSec: number | null;
sataScoring: SataScoring;
onAnswer: (questionId: string, selected: string[], checked: boolean) => void;
onFlags: (flags: string[]) => void;
onIndex: (index: number) => void;
/** Called every few seconds with the running clock so progress can be saved. */
onTick?: (elapsedSec: number) => void;
onFinish: (elapsedSec: number) => void;
onExit: () => void;
finishing?: boolean;
/** Extra content under the rationale (AI explanation). */
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
exitLabel?: string;
}
export function QuizRunner(p: RunnerProps) {
const confirm = useConfirm();
const [elapsed, setElapsed] = useState(p.elapsedSec);
const [navOpen, setNavOpen] = useState(false);
const topRef = useRef<HTMLDivElement>(null);
const tick = useLatest(p.onTick);
const finish = useLatest(p.onFinish);
const elapsedRef = useLatest(elapsed);
const total = p.questions.length;
const index = Math.min(p.index, total - 1);
const question = p.questions[index];
const answer = p.answers[question.id];
const selected = answer?.selected ?? [];
const checked = p.mode === 'practice' && Boolean(answer?.checked);
const answeredCount = p.questions.filter((q) => (p.mode === 'practice' ? p.answers[q.id]?.checked : (p.answers[q.id]?.selected.length ?? 0) > 0)).length;
const flagged = p.flags.includes(question.id);
const isLast = index === total - 1;
const remaining = p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
// Session clock: pauses while the tab is hidden.
useEffect(() => {
const timer = setInterval(() => {
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
useEffect(() => {
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(elapsed);
}, [elapsed, tick]);
useEffect(() => {
if (remaining === 0 && !p.finishing) finish.current(elapsedRef.current);
}, [remaining, p.finishing, finish, elapsedRef]);
useEffect(() => {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
const toggle = (id: string) => {
if (checked) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false);
};
const check = () => selected.length > 0 && p.onAnswer(question.id, selected, true);
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
const requestFinish = async () => {
const unanswered = total - answeredCount;
if (unanswered > 0) {
const ok = await confirm(
p.mode === 'exam'
? { title: 'Submit the exam?', message: `${plural(unanswered, 'question')} ${unanswered === 1 ? 'is' : 'are'} unanswered and will be marked wrong.`, confirmLabel: 'Submit' }
: { title: 'Finish now?', message: `You have answered ${answeredCount} of ${total}. Only answered questions are scored.`, confirmLabel: 'Finish' },
);
if (!ok) return;
}
p.onFinish(elapsed);
};
const primary = () => {
if (p.mode === 'practice' && !checked) return check();
if (isLast) return void requestFinish();
go(index + 1);
};
useHotkeys({
...Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)])),
...Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)])),
Enter: primary,
ArrowRight: () => go(index + 1),
ArrowLeft: () => go(index - 1),
// "f" doubles as choice F on six-option questions; the flag keeps a dedicated key too.
...(question.options.length < 6 ? { f: toggleFlag } : {}),
m: toggleFlag,
});
const score = checked ? scoreQuestion(question, selected, p.sataScoring) : 0;
const statusOf = (q: SnapshotQuestion) => {
const a = p.answers[q.id];
if (p.mode === 'practice' && a?.checked) return isFullyCorrect(scoreQuestion(q, a.selected, p.sataScoring)) ? 'right' : 'wrong';
return (a?.selected.length ?? 0) > 0 ? 'answered' : 'blank';
};
return (
<div className="flex min-h-dvh flex-col bg-paper">
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
<IconButton label={p.exitLabel ?? 'Save and exit'} onClick={p.onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{p.title}</div>
<div className="text-xs text-ink-3">{p.mode === 'exam' ? 'Exam' : 'Practice'}</div>
</div>
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
<Clock className="size-3.5" />
{formatDuration(remaining ?? elapsed)}
</div>
<button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator">
<LayoutGrid className="size-3.5 text-ink-3" />
{index + 1}/{total}
</button>
</div>
<ProgressBar value={answeredCount / total} tone="ink" className="h-[3px] rounded-none" label="Progress" />
</header>
<main className="mx-auto w-full max-w-3xl flex-1 px-4 pt-6 pb-32 sm:px-5 sm:pt-9">
<div ref={topRef} className="scroll-mt-20" />
<div key={question.id} className="animate-in">
<div className="mb-3 flex flex-wrap items-center gap-2">
<span className="eyebrow">Question {index + 1}</span>
{question.topic && <Badge tone="accent">{question.topic}</Badge>}
{flagged && (
<Badge tone="marker">
<Flag /> Flagged
</Badge>
)}
</div>
<Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]">
{question.stem}
</Markdown>
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : 'Choose one answer.'}</p>
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
{checked && (
<div className="mt-5 animate-in space-y-4">
<Verdict score={score} />
{question.rationale && (
<div className="rounded-[14px] border border-line bg-surface p-4">
<div className="eyebrow mb-1.5">Rationale</div>
<Markdown className="text-[15px]">{question.rationale}</Markdown>
</div>
)}
{p.renderExtra?.(
question,
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
)}
</div>
)}
</div>
</main>
<footer className="safe-bottom fixed inset-x-0 bottom-0 z-20 border-t border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-[68px] max-w-3xl items-center gap-2 px-3 sm:px-5">
<Button size="lg" variant="ghost" icon={<ArrowLeft />} onClick={() => go(index - 1)} disabled={index === 0} aria-label="Previous question">
<span className="hidden sm:inline">Back</span>
</Button>
<Button size="lg" variant={flagged ? 'marker' : 'ghost'} icon={<Flag className={flagged ? 'fill-current' : undefined} />} onClick={toggleFlag} aria-pressed={flagged}>
<span className="hidden sm:inline">{flagged ? 'Flagged' : 'Flag'}</span>
</Button>
<div className="flex-1" />
{p.mode === 'practice' && !checked ? (
<>
<Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}>
{isLast ? 'Finish' : 'Skip'}
</Button>
<Button size="lg" variant="primary" disabled={selected.length === 0} onClick={check} className="min-w-32">
Check
<span className="hidden sm:inline">
<Kbd>↵</Kbd>
</span>
</Button>
</>
) : isLast ? (
<Button size="lg" variant="primary" loading={p.finishing} onClick={requestFinish} className="min-w-32">
{p.mode === 'exam' ? 'Submit exam' : 'See results'}
</Button>
) : (
<>
{p.mode === 'exam' && answeredCount === total && (
<Button size="lg" variant="ghost" loading={p.finishing} onClick={requestFinish}>
Submit
</Button>
)}
<Button size="lg" variant="primary" onClick={() => go(index + 1)} className="min-w-32">
Next <ArrowRight className="size-4" />
</Button>
</>
)}
</div>
</footer>
<Dialog
open={navOpen}
onOpenChange={setNavOpen}
title="Questions"
description={`${answeredCount} of ${total} answered${p.flags.length ? `, ${p.flags.length} flagged` : ''}`}
footer={
<Button variant="primary" loading={p.finishing} onClick={() => (setNavOpen(false), void requestFinish())}>
{p.mode === 'exam' ? 'Submit exam' : 'Finish'}
</Button>
}
>
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8">
{p.questions.map((q, i) => {
const s = statusOf(q);
return (
<button
key={q.id}
type="button"
aria-label={`Question ${i + 1}, ${s === 'blank' ? 'not answered' : s === 'answered' ? 'answered' : s === 'right' ? 'correct' : 'incorrect'}${p.flags.includes(q.id) ? ', flagged' : ''}`}
aria-current={i === index}
onClick={() => (go(i), setNavOpen(false))}
className={cx(
'num relative grid aspect-square place-items-center rounded-[10px] border text-sm font-semibold',
s === 'right' ? 'border-good bg-good-soft text-good' : s === 'wrong' ? 'border-bad bg-bad-soft text-bad' : s === 'answered' ? 'border-ink bg-ink text-paper' : 'border-line-strong text-ink-2 hover:border-ink-3',
i === index && 'ring-2 ring-accent ring-offset-2 ring-offset-surface',
)}
>
{i + 1}
{p.flags.includes(q.id) && <span className="absolute -top-1 -right-1 size-3 rounded-full bg-marker ring-2 ring-surface" />}
</button>
);
})}
</div>
<div className="mt-5 hidden flex-wrap gap-x-4 gap-y-2 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>1</Kbd>–<Kbd>9</Kbd> or <Kbd>A</Kbd>–<Kbd>E</Kbd> choose
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> check / next
</span>
<span className="flex items-center gap-1.5">
<Kbd>←</Kbd>
<Kbd>→</Kbd> move
</span>
<span className="flex items-center gap-1.5">
<Kbd>M</Kbd> flag
</span>
</div>
</Dialog>
</div>
);
}
/* ------------------------------ results ------------------------------ */
export interface ResultsProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record<string, AnswerState>;
flags: string[];
elapsedSec: number;
sataScoring: SataScoring;
completedAt?: number | null;
actions: ReactNode;
onExit: () => void;
exitLabel?: string;
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
footnote?: ReactNode;
}
export function QuizResults(p: ResultsProps) {
const [filter, setFilter] = useState<'all' | 'wrong' | 'flagged'>('all');
const rows = useMemo(
() =>
p.questions.map((q, i) => {
const selected = p.answers[q.id]?.selected ?? [];
const answered = selected.length > 0;
const score = scoreQuestion(q, selected, p.sataScoring);
return { q, i, selected, answered, score, correct: isFullyCorrect(score), scored: p.mode === 'exam' || answered };
}),
[p.questions, p.answers, p.sataScoring, p.mode],
);
const scored = rows.filter((r) => r.scored);
const points = scored.reduce((n, r) => n + r.score, 0);
const percent = scored.length ? Math.round((points / scored.length) * 100) : 0;
const right = scored.filter((r) => r.correct).length;
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
const wrong = scored.length - right - partial;
const skipped = rows.length - scored.length;
const tone = percent >= 80 ? 'good' : percent >= 60 ? 'warn' : 'bad';
const topics = useMemo(() => {
const map = new Map<string, { n: number; s: number }>();
for (const r of scored) {
const key = r.q.topic || 'General';
const cur = map.get(key) ?? { n: 0, s: 0 };
cur.n += 1;
cur.s += r.score;
map.set(key, cur);
}
return [...map.entries()].map(([topic, v]) => ({ topic, n: v.n, accuracy: v.s / v.n })).sort((a, b) => a.accuracy - b.accuracy);
}, [scored]);
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
const headline = percent >= 90 ? 'Excellent work' : percent >= 80 ? 'Strong result' : percent >= 60 ? 'Getting there' : 'Worth another pass';
return (
<div className="min-h-dvh bg-paper">
<header className="sticky top-0 z-20 border-b border-line bg-paper/95 backdrop-blur">
<div className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-3 sm:px-5">
<IconButton label={p.exitLabel ?? 'Close'} onClick={p.onExit}>
<X />
</IconButton>
<div className="min-w-0 flex-1 truncate text-sm font-semibold">{p.title}</div>
</div>
</header>
<main className="mx-auto max-w-3xl animate-in px-4 pt-8 pb-24 sm:px-5">
<section className="card p-6 sm:p-8">
<div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left">
<Ring value={percent / 100} size={128} stroke={11} tone={tone}>
<div className="leading-none">
<span className="display num text-[38px] font-medium">{percent}</span>
<span className="text-lg text-ink-3">%</span>
</div>
</Ring>
<div className="min-w-0 flex-1">
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
<h1 className="display text-[30px]">{headline}</h1>
<p className="mt-1.5 text-[15px] text-ink-2">
<span className="num font-semibold text-ink">{Number.isInteger(points) ? points : points.toFixed(1)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
</p>
<div className="mt-3 flex flex-wrap justify-center gap-1.5 sm:justify-start">
<Badge tone="good">{right} correct</Badge>
{partial > 0 && <Badge tone="warn">{partial} partly</Badge>}
{wrong > 0 && <Badge tone="bad">{wrong} incorrect</Badge>}
</div>
</div>
</div>
<div className="mt-6 flex flex-wrap justify-center gap-2 border-t border-line pt-5 sm:justify-start">{p.actions}</div>
{p.footnote && <div className="mt-4 text-[13px] text-ink-3">{p.footnote}</div>}
</section>
{topics.length > 1 && (
<section className="mt-6">
<h2 className="eyebrow mb-2.5">By topic</h2>
<div className="card divide-y divide-line">
{topics.map((t) => {
const pc = Math.round(t.accuracy * 100);
return (
<div key={t.topic} className="flex items-center gap-3 px-4 py-2.5">
<span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span>
<span className="text-xs text-ink-3">{plural(t.n, 'question')}</span>
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36">
<div className={cx('h-full rounded-full', pc >= 80 ? 'bg-good' : pc >= 60 ? 'bg-warn' : 'bg-bad')} style={{ width: `${Math.max(4, pc)}%` }} />
</div>
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
</div>
);
})}
</div>
</section>
)}
<section className="mt-8">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<h2 className="eyebrow">Review</h2>
<Segmented
size="sm"
label="Filter questions"
value={filter}
onChange={setFilter}
options={[
{ value: 'all', label: `All ${rows.length}` },
{ value: 'wrong', label: `Missed ${scored.length - right}` },
...(p.flags.length > 0 ? [{ value: 'flagged' as const, label: `Flagged ${p.flags.length}` }] : []),
]}
/>
</div>
{visible.length === 0 ? (
<div className="card px-5 py-8 text-center text-sm text-ink-2">{filter === 'wrong' ? 'Nothing missed. Every scored question was correct.' : 'No questions here.'}</div>
) : (
<ol className="space-y-3">
{visible.map((r) => (
<li key={r.q.id} className="card p-4 sm:p-5">
<div className="mb-2.5 flex flex-wrap items-center gap-2">
<span className="num text-xs font-semibold text-ink-3">{String(r.i + 1).padStart(2, '0')}</span>
{!r.scored ? <Badge>Skipped</Badge> : r.correct ? <Badge tone="good">Correct</Badge> : r.score > 0 ? <Badge tone="warn">Partly correct</Badge> : <Badge tone="bad">{r.answered ? 'Incorrect' : 'Not answered'}</Badge>}
{r.q.topic && <Badge tone="accent">{r.q.topic}</Badge>}
{p.flags.includes(r.q.id) && (
<Badge tone="marker">
<Flag /> Flagged
</Badge>
)}
</div>
<Markdown serif className="mb-3.5 text-[17px]">
{r.q.stem}
</Markdown>
<OptionList question={r.q} selected={r.selected} revealed />
{r.q.rationale && (
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
<div className="eyebrow mb-1">Rationale</div>
<Markdown className="text-[14.5px]">{r.q.rationale}</Markdown>
</div>
)}
{p.renderExtra && (
<div className="mt-3">
{p.renderExtra(
r.q,
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
)}
</div>
)}
</li>
))}
</ol>
)}
</section>
</main>
</div>
);
}
export function RetakeIcon() {
return <RotateCcw />;
}