feat: replace screen state machine with React Router v7 URL routing
Release Pipeline / build-and-release (push) Successful in 5m24s

- Install react-router-dom
- Add slugify utility with full TDD test suite (7 tests)
- Wrap app in BrowserRouter in main.tsx
- Add optional onNavigate prop to ExamRunner.goTo
- Create ExamRoute component (deep-link restore + back/forward sync)
- Migrate App.tsx: replace screen useState with <Routes>, all setScreen()
  calls replaced with navigate(), add activateExam for deep-link activation,
  use useLocation for verify/reset-password special layouts
- Remove unused AppScreen type from types.ts
This commit is contained in:
LaurensBartelds committed 2026-04-24 23:55:52 +02:00
1 parent e97d90e316
commit 4eeacc38c5
10 files changed
+796 -367

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import type { Dispatch, SetStateAction } from 'react'
import ExamRunner from './ExamRunner'
import { loadState } from '../utils/storage'
import { slugify } from '../utils/slug'
import type { Exam, ExamState } from '../types'
interface Props {
exam: Exam | null
examState: ExamState | null
onActivate: (exam: Exam, state: ExamState) => void
setExamState: Dispatch<SetStateAction<ExamState>>
onSubmit: () => void
onExit: () => void
}
export default function ExamRoute({ exam, examState, onActivate, setExamState, onSubmit, onExit }: Readonly<Props>) {
const { slug, n } = useParams<{ slug: string; n: string }>()
const navigate = useNavigate()
const questionIdx = Math.max(0, (Number(n) || 1) - 1)
// Deep link: restore from localStorage if no exam is active on mount
useEffect(() => {
if (!exam) {
const saved = loadState()
if (saved?.exam && slugify(saved.exam.title) === slug) {
onActivate(saved.exam, { ...saved.state, currentIdx: questionIdx })
} else {
navigate('/', { replace: true })
}
}
// Intentionally runs only on mount — dep changes after mount are handled by the sync effect below
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// Sync :n URL param to currentIdx (handles browser back/forward navigation)
useEffect(() => {
setExamState((s) => s ? { ...s, currentIdx: questionIdx } : s)
}, [questionIdx, setExamState])
if (!exam || !examState) return null
return (
<ExamRunner
exam={exam}
state={examState}
setState={setExamState}
onNavigate={(i) => navigate(`/exam/${slug}/q${i + 1}`)}
onSubmit={onSubmit}
onExit={onExit}
/>
)
}
+226 -107
View File
@@ -1,107 +1,143 @@
import { useState, useEffect, useCallback } from 'react'
import type { Exam, ExamState, Question } from '../types'
import { gradeQuestion } from '../utils/grading'
import { formatTime } from '../utils/formatting'
import Tex from './Tex'
import QuestionMedia from './QuestionMedia'
import QuestionRenderer from './questions/QuestionRenderer'
import { useState, useEffect, useCallback } from "react";
import type { Exam, ExamState, Question } from "../types";
import { gradeQuestion } from "../utils/grading";
import { formatTime } from "../utils/formatting";
import Tex from "./Tex";
import QuestionMedia from "./QuestionMedia";
import QuestionRenderer from "./questions/QuestionRenderer";
interface Props {
exam: Exam
state: ExamState
setState: React.Dispatch<React.SetStateAction<ExamState>>
onSubmit: () => void
onExit: () => void
exam: Exam;
state: ExamState;
setState: React.Dispatch<React.SetStateAction<ExamState>>;
onSubmit: () => void;
onExit: () => void;
onNavigate?: (i: number) => void;
}
export default function ExamRunner({ exam, state, setState, onSubmit, onExit }: Readonly<Props>) {
const { currentIdx, answers, flags, startedAt, feedbackMode } = state
const q = exam.questions[currentIdx]
const total = exam.questions.length
const notes = state.notes ?? ''
export default function ExamRunner({
exam,
state,
setState,
onSubmit,
onExit,
onNavigate,
}: Readonly<Props>) {
const { currentIdx, answers, flags, startedAt, feedbackMode } = state;
const q = exam.questions[currentIdx];
const total = exam.questions.length;
const notes = state.notes ?? "";
const [revealed, setRevealed] = useState(() => !!state.revealed?.[q.id])
useEffect(() => { setRevealed(!!state.revealed?.[q.id]) }, [currentIdx, q.id, state.revealed])
const [revealed, setRevealed] = useState(() => !!state.revealed?.[q.id]);
useEffect(() => {
setRevealed(!!state.revealed?.[q.id]);
}, [currentIdx, q.id, state.revealed]);
const setAnswer = (val: unknown) =>
setState((s) => ({ ...s, answers: { ...s.answers, [q.id]: val } }))
setState((s) => ({ ...s, answers: { ...s.answers, [q.id]: val } }));
const goTo = useCallback((i: number) =>
setState((s) => ({ ...s, currentIdx: Math.max(0, Math.min(total - 1, i)) })), [total])
const goTo = useCallback(
(i: number) => {
const next = Math.max(0, Math.min(total - 1, i));
setState((s) => ({ ...s, currentIdx: next }));
onNavigate?.(next);
},
[total, onNavigate],
);
const toggleFlag = useCallback(() =>
setState((s) => ({ ...s, flags: { ...s.flags, [q.id]: !s.flags[q.id] } })), [q.id])
const toggleFlag = useCallback(
() =>
setState((s) => ({
...s,
flags: { ...s.flags, [q.id]: !s.flags[q.id] },
})),
[q.id],
);
const updateNotes = (value: string) =>
setState((s) => ({ ...s, notes: value.slice(0, 1000) }))
setState((s) => ({ ...s, notes: value.slice(0, 1000) }));
const checkAnswer = () => {
setState((s) => ({
...s,
revealed: s.revealed ? { ...s.revealed, [q.id]: true } : { [q.id]: true },
}))
setRevealed(true)
}
}));
setRevealed(true);
};
const [now, setNow] = useState(Date.now())
const [now, setNow] = useState(Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), 1000)
return () => clearInterval(t)
}, [])
const t = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(t);
}, []);
const elapsedMs = now - startedAt
const remainingMs = exam.timeLimitMinutes ? exam.timeLimitMinutes * 60_000 - elapsedMs : null
const timeUrgent = remainingMs != null && remainingMs < 60_000
const elapsedMs = now - startedAt;
const remainingMs = exam.timeLimitMinutes
? exam.timeLimitMinutes * 60_000 - elapsedMs
: null;
const timeUrgent = remainingMs != null && remainingMs < 60_000;
useEffect(() => {
if (remainingMs != null && remainingMs <= 0) onSubmit()
}, [remainingMs, onSubmit])
if (remainingMs != null && remainingMs <= 0) onSubmit();
}, [remainingMs, onSubmit]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement).tagName
if (tag === 'INPUT' || tag === 'TEXTAREA') return
if (e.key === 'ArrowRight' || e.key === 'j') goTo(currentIdx + 1)
if (e.key === 'ArrowLeft' || e.key === 'k') goTo(currentIdx - 1)
if (e.key === 'f') toggleFlag()
if (/^[1-9]$/.test(e.key) && q.type === 'multiple-choice' && q.choices) {
const ci = Number.parseInt(e.key, 10) - 1
const choices = q.choices
if (choices[ci]) setState((s) => ({ ...s, answers: { ...s.answers, [q.id]: choices[ci].id } }))
const tag = (e.target as HTMLElement).tagName;
if (tag === "INPUT" || tag === "TEXTAREA") return;
if (e.key === "ArrowRight" || e.key === "j") goTo(currentIdx + 1);
if (e.key === "ArrowLeft" || e.key === "k") goTo(currentIdx - 1);
if (e.key === "f") toggleFlag();
if (/^[1-9]$/.test(e.key) && q.type === "multiple-choice" && q.choices) {
const ci = Number.parseInt(e.key, 10) - 1;
const choices = q.choices;
if (choices[ci])
setState((s) => ({
...s,
answers: { ...s.answers, [q.id]: choices[ci].id },
}));
}
}
globalThis.addEventListener('keydown', handler)
return () => globalThis.removeEventListener('keydown', handler)
}, [currentIdx, q, goTo, toggleFlag, setState])
};
globalThis.addEventListener("keydown", handler);
return () => globalThis.removeEventListener("keydown", handler);
}, [currentIdx, q, goTo, toggleFlag, setState]);
const graded = feedbackMode === 'immediate' && revealed
const answered = answers[q.id] != null && (!Array.isArray(answers[q.id]) || (answers[q.id] as unknown[]).length > 0)
const result = graded ? gradeQuestion(q, answers[q.id]) : null
const graded = feedbackMode === "immediate" && revealed;
const answered =
answers[q.id] != null &&
(!Array.isArray(answers[q.id]) || (answers[q.id] as unknown[]).length > 0);
const result = graded ? gradeQuestion(q, answers[q.id]) : null;
const navStatus = (qq: Question): string => {
if (feedbackMode === 'immediate' && state.revealed?.[qq.id]) {
const r = gradeQuestion(qq, answers[qq.id])
if (r.status === 'correct') return 'correct'
if (r.status === 'wrong') return 'wrong'
if (feedbackMode === "immediate" && state.revealed?.[qq.id]) {
const r = gradeQuestion(qq, answers[qq.id]);
if (r.status === "correct") return "correct";
if (r.status === "wrong") return "wrong";
// fall through to answered/flagged for ungraded/unanswered revealed states (e.g. essay)
}
if (flags[qq.id]) return 'flagged'
const a = answers[qq.id]
if (a != null && (!Array.isArray(a) || (a as unknown[]).length > 0)) return 'answered'
return ''
}
if (flags[qq.id]) return "flagged";
const a = answers[qq.id];
if (a != null && (!Array.isArray(a) || (a as unknown[]).length > 0))
return "answered";
return "";
};
const answeredCount = exam.questions.filter((qq) => {
const st = navStatus(qq)
return st === 'answered' || st === 'correct' || st === 'wrong'
}).length
const st = navStatus(qq);
return st === "answered" || st === "correct" || st === "wrong";
}).length;
const totalPossible = exam.questions.reduce((acc, qq) => acc + (qq.points ?? 1), 0)
let answerText = ''
if (!Array.isArray(q.answer) && typeof q.answer === 'string') {
answerText = q.choices?.find((c) => c.id === q.answer)?.text ?? q.answer
const totalPossible = exam.questions.reduce(
(acc, qq) => acc + (qq.points ?? 1),
0,
);
let answerText = "";
if (!Array.isArray(q.answer) && typeof q.answer === "string") {
answerText = q.choices?.find((c) => c.id === q.answer)?.text ?? q.answer;
} else if (Array.isArray(q.answer)) {
answerText = q.answer.map((id) => q.choices?.find((c) => c.id === id)?.text ?? id).join(', ')
answerText = q.answer
.map((id) => q.choices?.find((c) => c.id === id)?.text ?? id)
.join(", ");
}
return (
@@ -113,78 +149,155 @@ export default function ExamRunner({ exam, state, setState, onSubmit, onExit }:
<div className="sidebar-section-label">Questions</div>
<div className="nav-list">
{exam.questions.map((qq, i) => {
const st = navStatus(qq)
const st = navStatus(qq);
return (
<button key={qq.id} className={`nav-item${i === currentIdx ? ' active' : ''}`} onClick={() => goTo(i)}>
<span className="nav-item-num">{String(i + 1).padStart(2, '0')}</span>
<span className="nav-item-title">
{qq.category ? `${qq.category} · ` : ''}{qq.type.replace('-', ' ')}
<button
key={qq.id}
className={`nav-item${i === currentIdx ? " active" : ""}`}
onClick={() => goTo(i)}
>
<span className="nav-item-num">
{String(i + 1).padStart(2, "0")}
</span>
<span className={`nav-dot${st ? ' ' + st : ''}`} />
<span className="nav-item-title">
{qq.category ? `${qq.category} · ` : ""}
{qq.type.replace("-", " ")}
</span>
<span className={`nav-dot${st ? " " + st : ""}`} />
</button>
)
);
})}
</div>
<div className="sidebar-section-label">Progress</div>
<div className="mono" style={{ fontSize: 13, color: 'var(--ink-2)' }}>
<div className="mono" style={{ fontSize: 13, color: "var(--ink-2)" }}>
{answeredCount} of {total} answered
</div>
<div className="progress-bar">
<div style={{ width: `${(answeredCount / total) * 100}%` }} />
</div>
<div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 8 }}>
<button className="btn btn-primary" onClick={onSubmit}>Submit exam</button>
<button className="btn btn-ghost btn-sm" onClick={onExit}>Exit to home</button>
<div
style={{
marginTop: 32,
display: "flex",
flexDirection: "column",
gap: 8,
}}
>
<button className="btn btn-primary" onClick={onSubmit}>
Submit exam
</button>
<button className="btn btn-ghost btn-sm" onClick={onExit}>
Exit to home
</button>
</div>
</aside>
<main className="main">
<header className="question-header">
<span className="q-index">Question {String(currentIdx + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</span>
<span className="q-index">
Question {String(currentIdx + 1).padStart(2, "0")} /{" "}
{String(total).padStart(2, "0")}
</span>
{q.category && <span className="q-category">{q.category}</span>}
<span className="q-points">{q.points ?? 1} {(q.points ?? 1) === 1 ? 'pt' : 'pts'}</span>
<span className="q-points">
{q.points ?? 1} {(q.points ?? 1) === 1 ? "pt" : "pts"}
</span>
</header>
<Tex tag="div" className="q-prompt">{q.prompt}</Tex>
<Tex tag="div" className="q-prompt">
{q.prompt}
</Tex>
<QuestionMedia q={q} />
<QuestionRenderer key={q.id} q={q} value={answers[q.id]} onChange={setAnswer} locked={graded && q.type !== 'essay'} graded={graded} />
<QuestionRenderer
key={q.id}
q={q}
value={answers[q.id]}
onChange={setAnswer}
locked={graded && q.type !== "essay"}
graded={graded}
/>
{graded && result && q.type !== 'essay' && (
<div className={`feedback ${result.correct ? 'correct' : 'wrong'}`}>
<div className="feedback-label">{result.correct ? 'Correct' : 'Not quite'}</div>
{graded && result && q.type !== "essay" && (
<div className={`feedback ${result.correct ? "correct" : "wrong"}`}>
<div className="feedback-label">
{result.correct ? "Correct" : "Not quite"}
</div>
<div className="feedback-body">
{!result.correct && q.answer && q.type !== 'match' && q.type !== 'order' && (
{!result.correct &&
q.answer &&
q.type !== "match" &&
q.type !== "order" && (
<p>
<strong>Answer:</strong> <Tex>{answerText}</Tex>
</p>
)}
{q.explanation && (
<p>
<strong>Answer:</strong>{' '}
<Tex>{answerText}</Tex>
<Tex>{q.explanation}</Tex>
</p>
)}
{q.explanation && <p><Tex>{q.explanation}</Tex></p>}
</div>
</div>
)}
<footer className="exam-footer">
<button className="btn" onClick={() => goTo(currentIdx - 1)} disabled={currentIdx === 0}>← Previous</button>
<button
className="btn"
onClick={() => goTo(currentIdx - 1)}
disabled={currentIdx === 0}
>
← Previous
</button>
<button className="btn btn-ghost" onClick={toggleFlag}>
{flags[q.id] ? '⚑ Flagged' : '⚐ Flag for review'}
{flags[q.id] ? "⚑ Flagged" : "⚐ Flag for review"}
</button>
<span className="spacer" />
{feedbackMode === 'immediate' && !revealed && q.type !== 'essay' && answered && (
<button className="btn btn-primary" onClick={checkAnswer}>Check answer</button>
{feedbackMode === "immediate" &&
!revealed &&
q.type !== "essay" &&
answered && (
<button className="btn btn-primary" onClick={checkAnswer}>
Check answer
</button>
)}
{currentIdx < total - 1 ? (
<button
className="btn btn-primary"
onClick={() => goTo(currentIdx + 1)}
>
Next →
</button>
) : (
<button className="btn btn-primary" onClick={onSubmit}>
Submit exam
</button>
)}
{currentIdx < total - 1
? <button className="btn btn-primary" onClick={() => goTo(currentIdx + 1)}>Next →</button>
: <button className="btn btn-primary" onClick={onSubmit}>Submit exam</button>}
</footer>
<div style={{ marginTop: 48, fontSize: 11.5, color: 'var(--ink-4)', display: 'flex', gap: 16, flexWrap: 'wrap' }}>
<span><span className="kbd">←</span> <span className="kbd">→</span> navigate</span>
<span><span className="kbd">F</span> flag</span>
{q.type === 'multiple-choice' && q.choices && (
<span><span className="kbd">1</span>–<span className="kbd">{q.choices.length}</span> select</span>
<div
style={{
marginTop: 48,
fontSize: 11.5,
color: "var(--ink-4)",
display: "flex",
gap: 16,
flexWrap: "wrap",
}}
>
<span>
<span className="kbd">←</span> <span className="kbd">→</span>{" "}
navigate
</span>
<span>
<span className="kbd">F</span> flag
</span>
{q.type === "multiple-choice" && q.choices && (
<span>
<span className="kbd">1</span>–
<span className="kbd">{q.choices.length}</span> select
</span>
)}
</div>
</main>
@@ -197,7 +310,11 @@ export default function ExamRunner({ exam, state, setState, onSubmit, onExit }:
{remainingMs != null && (
<div className="meta-block">
<div className="meta-label">Remaining</div>
<div className={`meta-value mono${timeUrgent ? ' timer-urgent' : ''}`}>{formatTime(Math.max(0, remainingMs))}</div>
<div
className={`meta-value mono${timeUrgent ? " timer-urgent" : ""}`}
>
{formatTime(Math.max(0, remainingMs))}
</div>
</div>
)}
<div className="meta-block">
@@ -207,7 +324,9 @@ export default function ExamRunner({ exam, state, setState, onSubmit, onExit }:
<div className="meta-block">
<div className="meta-label">Mode</div>
<div className="meta-value mono" style={{ fontSize: 13 }}>
{feedbackMode === 'immediate' ? 'Immediate feedback' : 'Grade at end'}
{feedbackMode === "immediate"
? "Immediate feedback"
: "Grade at end"}
</div>
</div>
<div className="meta-block notes-block">
@@ -230,5 +349,5 @@ export default function ExamRunner({ exam, state, setState, onSubmit, onExit }:
)}
</aside>
</div>
)
);
}