Study/web/src/features/quiz.tsx
Elijah 517278be71
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Varied question openers, readable rationales, plain practice score
- Stems no longer all open the same way: the writing rules, batch prompt and
  planner ask for varied openings (age openings stay part of the mix), and when
  one opener covers more than a quarter of a quiz the excess stems have only
  their opening reworded, keeping every number, before the check.
- Rationales are asked for as Markdown (a bold key point, then short bullets);
  older one-paragraph rationales are laid out the same way on display.
- The practice score in the quiz header is a plain "x/y correct", with no
  percentage or colour.
- Fix a flaky assertion: the mock's answer-key fix is a no-op when the shuffle
  already put the answer in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:05:46 -07:00

727 lines
34 KiB
TypeScript

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, letterGrade, optionLetter, parseNumericAnswer, 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 { formatRationale } from '@shared/rationale';
import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
import { ExplainSideContext } from './Explain';
/* ------------------------------ 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>
);
}
/* ------------------------------ numeric answer ------------------------------ */
/** The accepted answer(s) of a numeric question, for display. */
function acceptedAnswers(question: SnapshotQuestion): string {
return question.options
.filter((o) => o.correct !== false)
.map((o) => o.text)
.join(' or ');
}
/** A calculation: the student types the number. Units are optional; only the number is checked. */
function NumericAnswer({
question,
value,
revealed,
onChange,
onSubmit,
autoFocus,
}: {
question: SnapshotQuestion;
value: string;
revealed: boolean;
onChange?: (text: string) => void;
onSubmit?: () => void;
autoFocus?: boolean;
}) {
const right = revealed && isFullyCorrect(scoreQuestion(question, value ? [value] : []));
const unreadable = value.trim() !== '' && parseNumericAnswer(value) === null;
const why = question.options.find((o) => o.why)?.why;
return (
<div className="space-y-2.5">
<label className="block">
<span className="sr-only">Your answer</span>
<Input
value={value}
autoFocus={autoFocus}
inputMode="decimal"
autoComplete="off"
spellCheck={false}
readOnly={revealed || !onChange}
onChange={(e) => onChange?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
e.preventDefault();
onSubmit?.();
}
}}
placeholder="Type your answer, e.g. 12.5"
aria-invalid={unreadable || undefined}
className={cx(
'num h-14 max-w-sm rounded-[14px] px-4 text-[20px]',
revealed && (right ? 'border-good bg-good-soft ring-1 ring-good' : 'border-bad bg-bad-soft ring-1 ring-bad'),
)}
/>
</label>
{!revealed && unreadable && <p className="text-[13px] text-bad">Enter a number.</p>}
{revealed && (
<div className="rounded-[14px] border border-good/60 border-dashed px-3.5 py-2.5">
<div className="flex flex-wrap items-baseline gap-x-2 text-[15px]">
<span className="text-[13px] font-medium text-good">Correct answer</span>
<span className="num font-semibold">{acceptedAnswers(question)}</span>
</div>
{why && <div className="mt-1 text-[13.5px] leading-snug text-ink-2">{why}</div>}
</div>
)}
</div>
);
}
/** What the student answered, as text (for the AI explanation). */
function answerTexts(question: SnapshotQuestion, selected: string[]): string[] {
if (question.type === 'numeric') return selected.slice(0, 1);
return question.options.filter((o) => selected.includes(o.id)).map((o) => o.text);
}
/** Tone for a percentage on the 7-point scale: A and B good, C passing, D and F failing. */
export function gradeToneFor(percent: number): 'good' | 'warn' | 'bad' {
const letter = letterGrade(percent);
return letter === 'A' || letter === 'B' ? 'good' : letter === 'C' ? 'warn' : 'bad';
}
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
if (question.type !== 'multi') return null;
const correctIds = question.options.filter((o) => o.correct).map((o) => o.id);
const right = selected.filter((id) => correctIds.includes(id)).length;
const wrong = selected.length - right;
if (right === correctIds.length && wrong === 0) return null;
if (sata === 'strict') return 'All-or-nothing scoring is on, so every correct choice (and no others) is needed for credit.';
const earned = Math.max(0, right - wrong);
return `Partial credit: ${right} correct ${right === 1 ? 'choice' : 'choices'}${wrong > 0 ? ` minus ${wrong} incorrect` : ''} = ${earned} of ${correctIds.length} ${correctIds.length === 1 ? 'point' : 'points'} for this question.`;
}
const fmtPoints = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
function Verdict({ score, detail }: { score: number; detail?: string | null }) {
const full = isFullyCorrect(score);
const partial = !full && score > 0;
return (
<div role="status">
<div className={cx('flex items-center gap-2 text-[15px] font-semibold', full ? 'text-good' : partial ? 'text-warn' : 'text-bad')}>
{full ? <CircleCheck className="size-5" /> : <CircleX className="size-5" />}
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
</div>
{detail && <p className="mt-1 text-[13px] text-ink-2">{detail}</p>}
</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;
/**
* Fixed end time on this device's clock. When set, the countdown follows the wall clock
* and keeps running while the page is hidden or closed. Without it the clock pauses.
*/
deadlineAt?: 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);
// Room the Explain panel needs on the right on smaller screens (0 = question stays centred).
const [explainReserve, setExplainReserve] = useState(0);
const explainSide = useMemo(() => ({ reserve: setExplainReserve }), []);
const topRef = useRef<HTMLDivElement>(null);
const tick = useLatest(p.onTick);
const finish = useLatest(p.onFinish);
const autoSubmitted = useRef(false);
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;
// Running score for practice mode (select-all questions can earn part of a point).
const live = useMemo(() => {
if (p.mode !== 'practice') return null;
let n = 0;
let points = 0;
for (const q of p.questions) {
const a = p.answers[q.id];
if (!a?.checked) continue;
n += 1;
points += scoreQuestion(q, a.selected, p.sataScoring);
}
return n > 0 ? { n, points, percent: Math.round((points / n) * 100) } : null;
}, [p.mode, p.questions, p.answers, p.sataScoring]);
const [wallNow, setWallNow] = useState(() => Date.now());
const deadline = p.deadlineAt && p.timeLimitSec !== null ? p.deadlineAt : null;
const remaining = deadline !== null ? Math.max(0, Math.ceil((deadline - wallNow) / 1000)) : p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
// Time used: wall clock for deadline exams, otherwise the active-study clock.
const clock = deadline !== null && p.timeLimitSec !== null ? Math.max(elapsed, p.timeLimitSec - (remaining ?? 0)) : elapsed;
const clockRef = useLatest(clock);
useEffect(() => {
const timer = setInterval(() => {
setWallNow(Date.now());
// The untimed/legacy clock pauses while the tab is hidden.
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
}, 1000);
// Catch up immediately when returning to a deadline exam.
const onVisible = () => document.visibilityState === 'visible' && setWallNow(Date.now());
document.addEventListener('visibilitychange', onVisible);
return () => {
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}, []);
useEffect(() => {
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(clockRef.current);
}, [elapsed, tick, clockRef]);
useEffect(() => {
if (remaining === 0 && !p.finishing && !autoSubmitted.current) {
autoSubmitted.current = true;
finish.current(clockRef.current);
}
}, [remaining, p.finishing, finish, clockRef]);
useEffect(() => {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
const numeric = question.type === 'numeric';
const toggle = (id: string) => {
if (checked || numeric) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false);
};
const typed = numeric ? (selected[0] ?? '') : '';
const setTyped = (text: string) => !checked && p.onAnswer(question.id, text.trim() ? [text] : [], false);
const canCheck = numeric ? parseNumericAnswer(typed) !== null : selected.length > 0;
const check = () => {
if (!canCheck) return;
// Let the typed answer show its correct/incorrect colour instead of the focus ring.
if (numeric) (document.activeElement as HTMLElement | null)?.blur();
p.onAnswer(question.id, numeric ? [typed.trim()] : 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(clock);
};
const primary = () => {
if (p.mode === 'practice' && !checked) return check();
if (isLast) return void requestFinish();
go(index + 1);
};
useHotkeys({
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)]))),
...(numeric ? {} : 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>
{live && (
<div className="num flex items-center rounded-full px-2.5 py-1 text-[13px] font-medium text-ink-2" aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct`}>
{fmtPoints(live.points)}/{live.n}
<span className="hidden sm:inline">&nbsp;correct</span>
</div>
)}
{/* The clock is a timed-exam feature; untimed sessions track time quietly for the results. */}
{remaining !== null && (
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label="Time remaining">
<Clock className="size-3.5" />
{formatDuration(remaining)}
</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 transition-[transform,max-width] duration-300 ease-out motion-reduce:transition-none sm:px-5 sm:pt-9"
// Explain open on a smaller screen: the question moves left and narrows to make room.
style={explainReserve ? { maxWidth: Math.min(768, window.innerWidth - explainReserve - 40), transform: `translateX(-${explainReserve / 2}px)` } : undefined}
>
<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.' : numeric ? 'Enter your answer.' : 'Choose one answer.'}</p>
{numeric ? (
<NumericAnswer key={question.id} question={question} value={typed} revealed={checked} onChange={setTyped} onSubmit={primary} />
) : (
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
)}
{checked && (
<div className="mt-5 animate-in space-y-4">
<Verdict score={score} detail={creditDetail(question, selected, p.sataScoring)} />
{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]">{formatRationale(question.rationale)}</Markdown>
</div>
)}
<ExplainSideContext.Provider value={explainSide}>{p.renderExtra?.(question, answerTexts(question, selected))}</ExplainSideContext.Provider>
</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={!canCheck} onClick={check} className="min-w-32">
Check
</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>
}
>
{/* Padding keeps the current-question ring (and its offset) inside the scroll area. */}
<div className="grid grid-cols-6 gap-2 p-1.5 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>
</Dialog>
</div>
);
}
/* ------------------------------ results ------------------------------ */
type ScoreTier = 'perfect' | 'a' | 'b' | 'c' | 'fail';
/** Bands of the 7-point scale: 93+ green, 85-92 blue, 77-84 yellow, below 77 (failing) red; 100% is a rainbow. */
export function scoreTier(percent: number): ScoreTier {
const p = Math.round(percent);
return p >= 100 ? 'perfect' : p >= 93 ? 'a' : p >= 85 ? 'b' : p >= 77 ? 'c' : 'fail';
}
const TIER_COLOR: Record<Exclude<ScoreTier, 'perfect'>, string> = { a: 'var(--good)', b: 'var(--accent)', c: 'var(--score-yellow)', fail: 'var(--bad)' };
/** The result ring: fills up and counts to the score; a perfect score cycles through a rainbow. */
function ScoreRing({ percent, size = 136, stroke = 12 }: { percent: number; size?: number; stroke?: number }) {
const tier = scoreTier(percent);
const [shown, setShown] = useState(0);
useEffect(() => {
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return setShown(percent);
let frame = 0;
const started = performance.now();
const tick = (now: number) => {
const t = Math.min(1, (now - started) / 1100);
setShown(Math.round(percent * (1 - (1 - t) ** 3)));
if (t < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [percent]);
const r = (size - stroke) / 2;
const c = 2 * Math.PI * r;
const gid = `score-${size}`;
return (
<div className="relative shrink-0" style={{ width: size, height: size }} role="img" aria-label={`Score ${percent} percent`}>
<svg width={size} height={size} className={cx('-rotate-90', tier === 'perfect' && 'ring-rainbow')} aria-hidden>
{tier === 'perfect' && (
<defs>
<linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#ff4d6d" />
<stop offset="20%" stopColor="#ff9f1c" />
<stop offset="40%" stopColor="#ffd60a" />
<stop offset="60%" stopColor="#2ec27e" />
<stop offset="80%" stopColor="#3a86ff" />
<stop offset="100%" stopColor="#9b5de5" />
</linearGradient>
</defs>
)}
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
<circle
cx={size / 2}
cy={size / 2}
r={r}
fill="none"
stroke={tier === 'perfect' ? `url(#${gid})` : TIER_COLOR[tier]}
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={c}
strokeDashoffset={c * (1 - shown / 100)}
/>
</svg>
<div className="absolute inset-0 grid place-items-center">
<span className="num display text-[38px] leading-none font-medium">
{shown}
<span className="text-[20px] text-ink-3">%</span>
</span>
</div>
{tier === 'perfect' && shown === 100 && (
<span className="pointer-events-none absolute inset-0" aria-hidden>
{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
<span key={i} className="score-spark absolute top-1/2 left-1/2 size-2 rounded-full" style={{ ['--a' as string]: `${i * 45}deg`, background: ['#ff4d6d', '#ff9f1c', '#ffd60a', '#2ec27e', '#3a86ff', '#9b5de5', '#ff4d6d', '#2ec27e'][i] }} />
))}
</span>
)}
</div>
);
}
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 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 tier = scoreTier(percent);
const headline = { perfect: 'Perfect score!', a: 'Excellent work', b: 'Strong result', c: 'Passing', fail: 'Worth another pass' }[tier];
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">
<ScoreRing percent={percent} />
<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">{fmtPoints(points)}</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', { good: 'bg-good', warn: 'bg-warn', bad: 'bg-bad' }[gradeToneFor(pc)])} 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>
{r.q.type === 'numeric' ? <NumericAnswer question={r.q} value={r.selected[0] ?? ''} revealed /> : <OptionList question={r.q} selected={r.selected} revealed />}
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>}
{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]">{formatRationale(r.q.rationale)}</Markdown>
</div>
)}
{p.renderExtra && (
<div className="mt-3">
{p.renderExtra(r.q, answerTexts(r.q, r.selected))}
</div>
)}
</li>
))}
</ol>
)}
</section>
</main>
</div>
);
}
export function RetakeIcon() {
return <RotateCcw />;
}