App · project 06 of 19
Surveying exam flashcards.
Flashcards and timed mock exams for a licensing exam. The app grades you.
How to use it
- Set your exam date in Settings. The schedule paces itself to it.
- Press Start today's session and answer each card. The app marks it and decides when it comes back.
- Take a timed mock exam when you want a score by content area.
- This demonstration runs on 40 sample cards and keeps your progress in this browser only.
Where it helps most
- Any multiple-choice licensing or certification exam: swap in your own cards.
- People who are too generous when they grade themselves.
- Studying in short sessions on a phone.
The idea
A licensing exam with five content areas and a few hundred worked problems to get through. Flashcard apps make you grade yourself after every card, which is slow and too generous. I wanted the computer to know whether I got it right, decide when each card comes back, and pace the whole deck to the exam date.
The build
Claude built a static app: Leitner boxes with automatic grading, new cards most-likely first, conceptual and calculation tabs, and timed mock exams drawn in proportion to the exam blueprint. The full version syncs progress between phone and laptop through a small Cloudflare function that checks the sign-in token before it reads or writes anything.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
You are a front-end engineer who has prepared for a professional licensing exam. Build a study app for a multiple-choice exam as static files: one index.html plus a cards.js data file.
Data (cards.js): AREAS (id, name, weight % of the exam), and CARDS. Each card has id, area, topic family, mode (conceptual or calculation), question, optional setup text shared with follow-on questions, choices, answer index, a worked solution and a likelihood tier (High / Medium / Low). Concept cards may have no choices.
Study (Leitner boxes 1 to 6, reviews every 1, 2, 4, 7, 14 and 21 days):
- No grade buttons. Picking the right choice moves the card up a box; a wrong pick, or revealing a problem without picking, sends it to box 1 and repeats it later in the same session. Revealing a concept card counts as remembered. One Next button (or Space) moves on.
- New cards come most-likely first, a set number per day, paced to an exam date the learner picks. Nothing is scheduled past two days before the exam.
- Tabs to study only conceptual or only calculation cards.
Mock exams: timed, one answer each, drawn in proportion to the area weights, setup questions kept with their follow-ons, recent misses drawn more often. Results by area, and missed questions can be sent back to box 1.
Also: a home page with days to the exam, cards due, learned counts per area and per topic; a searchable card browser; settings for exam date, daily pace and theme; export and import of progress as JSON. Progress saves to localStorage. Use in-page dialogs, not alert or confirm.
Optional sync across devices: put the site behind Cloudflare Access and add a Pages Function at /api/progress (GET and PUT) that verifies the Access JWT (Cf-Access-Jwt-Assertion) against the team's public keys and stores each user's progress in Workers KV under their verified email. The app pushes after each change and pulls the newer copy on load.
Plain HTML, CSS and JavaScript, no libraries, works on a phone, keyboard shortcuts (A to D, Space). After building, list how you checked the scheduling, the mock-exam blueprint and that every answer in cards.js is correct.
Get the code5 files, exactly as they run on this site
The demonstration runs on 40 sample cards written for it. The sync function comes from the full version, with the sign-in address replaced by a placeholder.
index.html55 lines
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Surveying exam flashcards · demonstration</title>
<meta name="robots" content="noindex,nofollow">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./app.css">
</head>
<body>
<p class="demo-note"><b>Demonstration.</b> 40 sample cards written for this demo. No account: your progress stays in this browser.</p>
<header>
<div class="bar">
<h1>Surveying Exam Flashcards</h1>
<nav>
<button data-view="home" class="on">Home</button>
<button data-view="study">Study</button>
<button data-view="exam">Mock exams</button>
<button data-view="browse">Cards</button>
<button data-view="settings">Settings</button>
</nav>
</div>
</header>
<main>
<section id="view-home"></section>
<section id="view-study" class="hidden">
<div class="modes" data-modes></div>
<div id="study-empty" class="card hidden"></div>
<div id="study-active" class="hidden">
<div class="muted" id="study-progress"></div>
<div class="card" id="flashcard" aria-live="polite"></div>
<div class="row" id="reveal-row"><button class="primary" id="reveal">Show answer</button>
<span class="muted">Pick a choice (A to D) or press Space.</span></div>
<div class="row hidden" id="next-row"><button class="primary" id="next">Next</button>
<span class="muted" id="grade-note"></span></div>
</div>
</section>
<section id="view-exam" class="hidden"></section>
<section id="view-browse" class="hidden"></section>
<section id="view-settings" class="hidden"></section>
</main>
<div class="modal hidden" id="modal" role="dialog" aria-modal="true">
<div class="card"><p id="modal-msg" class="u6"></p>
<div class="row u16"><button class="ghost" id="modal-no">Cancel</button><button class="primary" id="modal-yes">OK</button></div></div>
</div>
<script src="./cards.js"></script>
<script src="./app.js"></script>
</body>
</html>
app.js (the study logic)723 lines
const KEY = "surveying-flashcards-demo-v1";
const OLD_KEY = "surveying-flashcards-demo-old";
const BOX_DAYS = [1, 2, 4, 7, 14, 21]; // Leitner boxes 1..6
const DAY = 864e5;
const LETTERS = "ABCDE";
// Demo targets: below 60% needs work, 70% or better is on track.
const PASS_LOW = 60, PASS_HIGH = 70;
const AREA_NAMES = Object.fromEntries(AREAS.map(a => [a.id, a.name]));
const BY_ID = Object.fromEntries(CARDS.map(c => [c.id, c]));
const isProblem = c => !!c.c;
/* ---------- small helpers ---------- */
const esc = s => String(s).replace(/[&<>"']/g, ch => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[ch]));
const iso = d => new Date(d.getTime() - d.getTimezoneOffset() * 6e4).toISOString().slice(0, 10);
const today = () => iso(new Date());
const addDays = (s, n) => { const d = new Date(s + "T12:00:00"); d.setDate(d.getDate() + n); return iso(d); };
const daysBetween = (a, b) => Math.round((new Date(b + "T12:00:00") - new Date(a + "T12:00:00")) / DAY);
const fmt = s => new Date(s + "T12:00:00").toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
const pct = (a, b) => b ? Math.round(100 * a / b) : 0;
const mmss = s => { s = Math.max(0, Math.round(s)); const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60), x = s % 60;
return (h ? h + ":" + String(m).padStart(2, "0") : m) + ":" + String(x).padStart(2, "0"); };
// In-page confirmation (the artifact viewer suppresses window.confirm and alert).
function ask(msg, onYes, yesLabel = "OK", noLabel = "Cancel") {
const m = document.getElementById("modal");
document.getElementById("modal-msg").textContent = msg;
const yes = document.getElementById("modal-yes"), no = document.getElementById("modal-no");
yes.textContent = yesLabel; no.textContent = noLabel; no.classList.toggle("hidden", !noLabel);
const close = () => m.classList.add("hidden");
yes.onclick = () => { close(); onYes && onYes(); };
no.onclick = close;
m.classList.remove("hidden"); yes.focus();
}
const tell = msg => ask(msg, null, "OK", "");
/* ---------- persistent state (auto-saved to this browser) ---------- */
function freshState() {
return { v: 2, examDate: "", startDate: today(), newPerDay: 10, includeLow: true, mode: "all", cards: {}, log: {}, mocks: [], active: null };
}
function load() {
try {
const s = JSON.parse(localStorage.getItem(KEY));
if (s) return s;
// Carry the exam date and pace over from the first version; its card ids no longer exist.
const old = JSON.parse(localStorage.getItem(OLD_KEY));
if (old) return Object.assign(freshState(), { examDate: old.examDate || "", newPerDay: old.newPerDay || 0 });
} catch (e) { /* storage blocked or corrupt */ }
return null;
}
function save() {
S.savedAt = Date.now();
try { localStorage.setItem(KEY, JSON.stringify(S)); } catch (e) { /* storage blocked: app still works this session */ }
}
let S = Object.assign(freshState(), load() || {});
/* ---------- plan & exam timing ---------- */
const examDate = () => S.examDate || addDays(S.startDate, 28);
const daysLeft = () => daysBetween(today(), examDate());
const newDaysAvailable = () => Math.max(1, daysLeft() - 7); // last 7 days are review-only
const planCards = () => CARDS.filter(c => S.includeLow || c.tier !== "Low"); // CARDS is sorted most likely first
const autoNewPerDay = () => Math.max(1, Math.ceil(planCards().length / newDaysAvailable()));
const newPerDay = () => S.newPerDay || autoNewPerDay();
/* ---------- Leitner scheduling ---------- */
function setDue(st, t) {
let due = addDays(t, st.gap);
if (S.examDate) { // exam-aware cap: nothing is pushed past two days before the exam
const cap = addDays(S.examDate, -2);
if (due > cap) due = cap > t ? cap : t;
}
st.due = due;
}
function applyGrade(id, g) {
const t = today();
const st = S.cards[id] || { box: 1, due: t, reps: 0, lapses: 0 };
if (g === 1) { st.box = 1; st.lapses++; }
else if (g === 3) st.box = Math.min(6, st.box + 1);
else if (g === 4) st.box = Math.min(6, st.box + 2);
// Hard keeps the box and shortens the wait.
st.gap = g === 1 ? 1 : g === 2 ? Math.max(1, Math.round(BOX_DAYS[st.box - 1] / 2)) : BOX_DAYS[st.box - 1];
setDue(st, t);
st.reps++; st.last = t;
S.cards[id] = st;
const L = S.log[t] || { reviewed: 0, correct: 0, newSeen: 0 };
L.reviewed++; if (g >= 3) L.correct++;
S.log[t] = L;
save();
}
function newSeenToday() { return (S.log[today()] || {}).newSeen || 0; }
function dueCards() {
const t = today();
return CARDS.filter(c => modeOk(c) && S.cards[c.id] && S.cards[c.id].due <= t)
.sort((a, b) => S.cards[a.id].box - S.cards[b.id].box || b.score - a.score);
}
function newCardsToday() {
const remaining = Math.max(0, newPerDay() - newSeenToday());
return planCards().filter(c => modeOk(c) && !S.cards[c.id]).slice(0, remaining);
}
/* ---------- stats ---------- */
const learned = c => S.cards[c.id] && S.cards[c.id].box >= 5;
const seen = c => !!S.cards[c.id];
function streak() {
let n = 0, d = today();
if (!(S.log[d] || {}).reviewed) d = addDays(d, -1); // today not started yet doesn't break the streak
while ((S.log[d] || {}).reviewed) { n++; d = addDays(d, -1); }
return n;
}
function accuracy() {
let r = 0, c = 0;
Object.values(S.log).forEach(l => { r += l.reviewed; c += l.correct; });
return r ? pct(c, r) + "%" : "-";
}
/* ---------- question rendering ---------- */
function srcLine(c) { return esc(c.src); }
function tags(c) {
const figure = c.kind === "figure" ? `<span class="tag">Figure</span>` : "";
return `<span class="tag ${c.mode === "calculation" ? "calc" : ""}">${modeLabel(c)}</span>` +
`<span class="tag ${c.tier}">${c.tier} likelihood</span><span class="tag">${esc(AREA_NAMES[c.area])}</span>` +
`<span class="tag">${esc(c.family)}</span>${figure}`;
}
function figHtml(c) {
return c.fig ? `<img class="fig" src="${esc(c.fig)}" alt="Figure from the book for this problem" loading="lazy">` : "";
}
// state: { picked: index|null, reveal: bool, locked: bool }
function questionHtml(c, state) {
let h = c.ctx ? `<p class="ctx"><b>Setup:</b> ${esc(c.ctx)}</p>` : "";
h += `<p class="qtext">${esc(c.q)}</p>${figHtml(c)}`;
if (isProblem(c)) {
h += `<div class="choices">` + c.c.map((txt, i) => {
let cls = "choice";
if (state.picked === i) cls += " picked";
if (state.reveal && i === c.a) cls += " right";
else if (state.reveal && state.picked === i) cls += " wrong";
return `<button class="${cls}" data-choice="${i}" ${state.locked ? "disabled" : ""}><span class="l">${LETTERS[i]}</span><span>${esc(txt)}</span></button>`;
}).join("") + `</div>`;
}
return h;
}
function answerHtml(c, picked) {
let h = `<div class="answer">`;
if (isProblem(c)) {
const verdict = picked == null ? "" : picked === c.a ? `<span class="pass">Correct.</span> ` : `<span class="fail">Not quite.</span> `;
h += `<p class="u1">${verdict}<b>Answer: ${LETTERS[c.a]}) ${esc(c.c[c.a])}</b></p>`;
}
h += `<p class="u2">${esc(c.sol)}</p>`;
if (c.note) h += `<div class="note"><b>Note:</b> ${esc(c.note)}</div>`;
return h + `<div class="src">${srcLine(c)}</div></div>`;
}
document.addEventListener("click", e => { // tap a figure to enlarge it
if (e.target.classList.contains("fig")) e.target.classList.toggle("big");
});
/* ---------- rendering: home ---------- */
function renderHome() {
const due = dueCards().length;
const news = newCardsToday().length;
const plan = planCards();
const boxCounts = [1, 2, 3, 4, 5, 6].map(b => CARDS.filter(c => S.cards[c.id] && S.cards[c.id].box === b).length);
const examBanner = S.examDate ? "" :
`<div class="banner"><b>Pick your exam date in Settings</b> (currently assumed: ${fmt(examDate())}). The schedule below adjusts to it.</div>`;
const activeBanner = S.active ?
`<div class="banner"><b>Mock exam in progress:</b> ${esc(S.active.name)}. <button class="ghost" data-go="exam">Resume</button></div>` : "";
const mockByArea = {};
S.mocks.forEach(m => Object.entries(m.byArea).forEach(([a, [ok, n]]) => {
const t = mockByArea[a] || [0, 0]; t[0] += ok; t[1] += n; mockByArea[a] = t;
}));
const areaRows = AREAS.map(a => {
const cs = CARDS.filter(c => c.area === a.id);
const ok = cs.filter(learned).length, started = cs.filter(seen).length;
const mk = mockByArea[a.id];
return `<tr>
<td><b>${a.name}</b><br><span class="tag">${a.weight}% of exam</span></td>
<td class="u3"><div class="bar-track"><div class="bar-fill" data-w="${pct(ok, cs.length)}"></div></div>
<span class="muted">${ok} of ${cs.length} learned · ${started} started${mk ? ` · mock exams ${pct(mk[0], mk[1])}%` : ""}</span></td></tr>`;
}).join("");
const famRows = FAMILIES.slice(0, 10).map(f => {
const cs = CARDS.filter(c => c.family === f.name);
return `<tr><td>${esc(f.name)}</td><td>${cs.length}</td><td>${cs.filter(learned).length} / ${cs.length}</td></tr>`;
}).join("");
// Plan: new cards in likelihood order, with each tier's target dates.
let cum = 0; const perDay = newPerDay();
const planRows = ["High", "Medium", "Low"].map(t => {
const n = plan.filter(c => c.tier === t).length;
if (!n) return `<tr><td>${t}</td><td>0</td><td class="muted">Excluded in Settings</td></tr>`;
const startIdx = cum; cum += n;
const startDay = addDays(S.startDate, Math.floor(startIdx / perDay));
const endDay = addDays(S.startDate, Math.max(0, Math.ceil(cum / perDay) - 1));
return `<tr><td><span class="tag ${t}">${t}</span></td><td>${n}</td><td>${fmt(startDay)} to ${fmt(endDay)}</td></tr>`;
}).join("");
const last = S.mocks[S.mocks.length - 1];
const reviewDay = addDays(examDate(), -7);
document.getElementById("view-home").innerHTML = `
${activeBanner}${examBanner}
<div class="card">
<div class="grid">
<div class="stat"><b>${daysLeft()}</b><span>days to exam (${fmt(examDate())})</span></div>
<div class="stat"><b>${due + news}</b><span>cards for today (${due} review, ${news} new)</span></div>
<div class="stat"><b>${CARDS.filter(learned).length} / ${CARDS.length}</b><span>learned</span></div>
<div class="stat"><b>${last ? pct(last.correct, last.n) + "%" : "-"}</b><span>last mock exam${last ? " (" + fmt(last.date) + ")" : ""}</span></div>
</div>
<p class="row u4">
<button class="primary" data-go="study">${due + news ? "Start today's session" : "Nothing due: browse cards"}</button>
<button class="ghost" data-go="exam">Take a mock exam</button>
</p>
<p class="muted u5">${streak()} day streak · flashcard accuracy ${accuracy()}</p>
</div>
<h2>Exam areas</h2>
<div class="card scroll-x">
<table>${areaRows}</table>
<p class="muted u5">Mock exams draw questions in proportion to each area's share of the exam.</p>
</div>
<h2>Topics</h2>
<div class="card scroll-x">
<table><tr><th>Topic</th><th>Cards</th><th>Learned</th></tr>${famRows}</table>
<p class="muted u5">In the full version each card's likelihood is ranked from how often its topic is tested and the exam weight of its area. Here the sample cards carry a fixed likelihood.</p>
</div>
<h2>Schedule</h2>
<div class="card scroll-x">
<p class="u6">Introduce about <b>${perDay} new cards per day</b> from ${fmt(S.startDate)}, most likely first. Review everything during the final week, starting ${fmt(reviewDay)}. Take a full mock exam each week.</p>
<table><tr><th>Likelihood</th><th>Cards</th><th>Target dates</th></tr>${planRows}</table>
<p class="muted">${plan.filter(c => !seen(c)).length} planned cards not started.</p>
</div>
<h2>Box system</h2>
<div class="card">
<div class="boxes">${boxCounts.map((n, i) => `<div class="box"><span class="muted">Box ${i + 1}</span><b>${n}</b><span class="muted">every ${BOX_DAYS[i]}d</span></div>`).join("")}</div>
<p class="muted u5">There are no grade buttons. Answer right and the card moves up a box; miss it and it goes back to box 1 and comes round again this session. Cards in box 5 and above count as learned. Missed mock-exam questions can be sent back to box 1.</p>
</div>`;
}
/* ---------- study ---------- */
// Conceptual cards recall a definition, rule or formula; calculation cards need working out a value.
const MODES = [["all", "All"], ["conceptual", "Conceptual"], ["calculation", "Calculation"]];
const modeOk = c => S.mode === "all" || c.mode === S.mode;
const modeLabel = c => c.mode === "calculation" ? "Calculation" : "Conceptual";
function modeTabs() {
return MODES.map(([id, name]) => {
const n = id === "all" ? CARDS.length : CARDS.filter(c => c.mode === id).length;
return `<button data-mode="${id}" class="${S.mode === id ? "on" : ""}" aria-pressed="${S.mode === id}">${name} <span class="muted">${n}</span></button>`;
}).join("");
}
function refreshModes() {
document.querySelectorAll("[data-modes]").forEach(el => el.innerHTML = modeTabs());
}
let browseDraw = () => {};
let queue = [], index = 0, flipped = false, picked = null;
function startSession() {
queue = [...dueCards(), ...newCardsToday()].map(c => c.id);
index = 0; flipped = false; picked = null; lastGrade = 0; gradeNote = "";
renderStudy();
}
function currentCard() { return BY_ID[queue[index]]; }
function renderStudy() {
const empty = document.getElementById("study-empty");
const active = document.getElementById("study-active");
refreshModes();
if (!queue.length || index >= queue.length) {
empty.classList.remove("hidden"); active.classList.add("hidden");
const scope = S.mode === "all" ? "" : ` in ${S.mode}`;
empty.innerHTML = queue.length
? `<p class="u2"><b>Session complete.</b> ${(S.log[today()] || {}).reviewed || 0} cards reviewed today.</p>`
: `<p class="u2"><b>All done for today${scope}.</b> Come back tomorrow, switch the tab above, take a mock exam, or browse the cards.</p>`;
queue = []; return;
}
empty.classList.add("hidden"); active.classList.remove("hidden");
const c = currentCard();
const st = S.cards[c.id];
document.getElementById("study-progress").textContent =
`${index + 1} of ${queue.length} · ${st ? "box " + st.box : "new"}`;
document.getElementById("flashcard").innerHTML = `<div>${tags(c)}</div>` +
questionHtml(c, { picked, reveal: flipped, locked: flipped }) + (flipped ? answerHtml(c, picked) : "");
document.getElementById("next-row").classList.toggle("hidden", !flipped);
document.getElementById("reveal-row").classList.toggle("hidden", flipped);
document.getElementById("grade-note").textContent = flipped ? gradeNote : "";
}
// Grades are automatic: a picked choice is right (Good) or wrong (Again);
// revealing a concept card is Good; revealing a problem without picking is Again.
let gradeNote = "", lastGrade = 0;
function autoGrade(g) {
const c = currentCard();
if (!c || lastGrade) return;
const isNew = !S.cards[c.id];
applyGrade(c.id, g);
if (isNew) { const L = S.log[today()]; L.newSeen = (L.newSeen || 0) + 1; save(); }
lastGrade = g;
gradeNote = g === 3 ? "Scheduled for later." : "Wrong or missed: it comes back later this session.";
}
function flip() {
if (!queue.length) return;
if (flipped) return next();
flipped = true;
const c = currentCard();
if (!isProblem(c)) autoGrade(3);
else autoGrade(1);
renderStudy();
}
function pick(i) {
const c = currentCard();
if (!c || flipped || !isProblem(c) || i >= c.c.length) return;
picked = i; flipped = true;
autoGrade(picked === c.a ? 3 : 1);
renderStudy();
}
function next() {
if (!flipped || index >= queue.length) return;
const c = currentCard();
if (lastGrade === 1) queue.push(c.id); // missed: repeat later in this session
index++; flipped = false; picked = null; lastGrade = 0; gradeNote = "";
renderStudy();
}
/* ---------- mock exams ---------- */
const MOCKS = [
{ id: "full", name: "Mock exam", n: 20, minutes: 55, areas: null,
blurb: "20 questions in 55 minutes, drawn in proportion to the exam areas." },
{ id: "half", name: "Short mock exam", n: 10, minutes: 28, areas: null,
blurb: "10 questions in 28 minutes, same blueprint." },
{ id: "weak", name: "Heaviest-areas drill", n: 10, minutes: 28, areas: ["data", "planning"],
blurb: "10 questions from Data Analysis and Survey Planning, the two largest areas." },
];
// Largest-remainder split of n questions over the area weights.
function quotas(n, areaIds) {
const as = AREAS.filter(a => !areaIds || areaIds.includes(a.id));
const tot = as.reduce((s, a) => s + a.weight, 0);
const raw = as.map(a => ({ id: a.id, x: n * a.weight / tot }));
raw.forEach(r => { r.q = Math.floor(r.x); });
let left = n - raw.reduce((s, r) => s + r.q, 0);
[...raw].sort((a, b) => (b.x - b.q) - (a.x - a.q)).forEach(r => { if (left > 0) { r.q++; left--; } });
return Object.fromEntries(raw.map(r => [r.id, r.q]));
}
// Draw a random exam: follow-on parts stay with their setup question, a problem and its
// twin from the other book never appear together, and likely topics and recent misses
// are drawn more often.
function buildMock(def) {
const recent = new Set(S.mocks.slice(-3).flatMap(m => m.ids || []));
const missed = new Set(S.mocks.slice(-5).flatMap(m => m.missed || []));
const groups = {};
CARDS.filter(c => isProblem(c) && !c.noMock).forEach(c => (groups[c.grp] = groups[c.grp] || []).push(c));
const pool = Object.values(groups).map(g => {
g.sort((a, b) => a.ord - b.ord);
let w = 0.25 + g[0].score;
if (g.some(c => missed.has(c.id))) w *= 1.6;
if (g.some(c => recent.has(c.id))) w *= 0.3;
return { items: g, area: g[0].area, w };
});
const left = quotas(def.n, def.areas); // questions still needed per area
const chosen = [], used = new Set();
const twinTaken = c => (c.dup && used.has(c.dup)) || CARDS.some(o => o.dup === c.id && used.has(o.id));
// A group can span areas (e.g. a leveling setup with a construction follow-on), so
// every part must fit its own area's remaining quota.
const fits = p => {
const need = {};
p.items.forEach(c => { need[c.area] = (need[c.area] || 0) + 1; });
return Object.entries(need).every(([a, n]) => (left[a] || 0) >= n);
};
let cand = pool.filter(p => p.items.every(c => c.area in left));
while (Object.values(left).some(n => n > 0) && cand.length) {
cand = cand.filter(fits);
if (!cand.length) break;
const total = cand.reduce((s, p) => s + p.w, 0);
let r = Math.random() * total, k = 0;
while (k < cand.length - 1 && (r -= cand[k].w) > 0) k++;
const p = cand.splice(k, 1)[0];
if (p.items.some(twinTaken)) continue;
p.items.forEach(c => { used.add(c.id); chosen.push(c); left[c.area]--; });
}
// Keep each group together; mix groups so areas are interleaved like the real exam.
const byGrp = {};
chosen.forEach(c => (byGrp[c.grp] = byGrp[c.grp] || []).push(c.id));
const order = Object.values(byGrp);
for (let i = order.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [order[i], order[j]] = [order[j], order[i]]; }
return order.flat();
}
function bookExamIds(examId) {
return CARDS.filter(c => c.exam === examId).sort((a, b) => a.ord - b.ord).map(c => c.id);
}
function startExam(kind) {
const def = MOCKS.find(m => m.id === kind);
const book = BOOK_EXAMS.find(b => b.id === kind);
const ids = def ? buildMock(def) : bookExamIds(kind);
S.active = { kind, name: def ? def.name : book.name, minutes: def ? def.minutes : book.minutes,
ids, answers: {}, flags: {}, start: Date.now(), idx: 0 };
save(); renderExam();
}
const remaining = () => S.active.minutes * 60 - (Date.now() - S.active.start) / 1000;
let tick = null;
function renderExam() {
clearInterval(tick); tick = null;
const root = document.getElementById("view-exam");
if (S.active) return renderRunner(root);
if (examResult) return renderResult(root, examResult);
const count = id => bookExamIds(id).length;
const hist = S.mocks.slice().reverse().map((m, i) => `<tr>
<td>${fmt(m.date)}</td><td>${esc(m.name)}</td>
<td><b class="${scoreClass(pct(m.correct, m.n))}">${pct(m.correct, m.n)}%</b> <span class="muted">(${m.correct}/${m.n})</span></td>
<td class="muted">${AREAS.filter(a => m.byArea[a.id]).map(a => `${a.name.split(" ")[0]} ${pct(...m.byArea[a.id])}%`).join(" · ")}</td>
<td><button class="ghost" data-review="${S.mocks.length - 1 - i}">Review</button></td></tr>`).join("");
root.innerHTML = `
<div class="card"><p class="u2">Timed, multiple choice, one answer each, like the real CBT exam. The clock keeps running if you leave this tab, and the exam submits itself when time is up. In this demo, ${PASS_HIGH}% or better is on track.</p></div>
<h2>Generated mock exams</h2>
<div class="exam-pick">${MOCKS.map(m => `<div class="card"><h3>${m.name}</h3><p class="muted">${m.blurb}</p>
<button class="primary" data-start="${m.id}">Start (${m.minutes} min)</button></div>`).join("")}</div>
<h2>History</h2>
<div class="card scroll-x">${S.mocks.length ? `<table><tr><th>Date</th><th>Exam</th><th>Score</th><th>By area</th><th></th></tr>${hist}</table>`
: `<p class="muted u2">No mock exams yet.</p>`}</div>`;
}
const scoreClass = p => p >= PASS_HIGH ? "pass" : p >= PASS_LOW ? "edge" : "fail";
function renderRunner(root) {
const A = S.active, c = BY_ID[A.ids[A.idx]];
const answered = Object.keys(A.answers).length;
root.innerHTML = `
<div class="examhead">
<span class="timer" id="timer">${mmss(remaining())}</span>
<span class="muted st">${esc(A.name)} · question ${A.idx + 1} of ${A.ids.length} · ${answered} answered</span>
<span class="u7"></span>
<button class="danger" id="submit">Submit</button>
</div>
<div class="card">
<div class="muted u8">${esc(AREA_NAMES[c.area])}</div>
${questionHtml(c, { picked: A.answers[c.id] ?? null, reveal: false, locked: false })}
<div class="row u9">
<button class="ghost" id="prev" ${A.idx ? "" : "disabled"}>Previous</button>
<button class="ghost" id="flag">${A.flags[c.id] ? "Unflag" : "Flag for review"}</button>
<span class="u7"></span>
<button class="primary" id="next">${A.idx < A.ids.length - 1 ? "Next" : "Review answers"}</button>
</div>
</div>
<details class="card" ${A.showGrid ? "open" : ""} id="gridbox"><summary>All questions (filled = answered, orange ring = flagged)</summary>
<div class="qgrid u10">${A.ids.map((id, i) =>
`<button data-jump="${i}" class="${A.answers[id] != null ? "done" : ""} ${A.flags[id] ? "flag" : ""} ${i === A.idx ? "cur" : ""}">${i + 1}</button>`).join("")}</div>
</details>`;
const go = i => { A.idx = Math.max(0, Math.min(A.ids.length - 1, i)); save(); renderRunner(root); window.scrollTo(0, 0); };
root.querySelectorAll("[data-choice]").forEach(b => b.onclick = () => { A.answers[c.id] = +b.dataset.choice; save(); renderRunner(root); });
root.querySelector("#prev").onclick = () => go(A.idx - 1);
root.querySelector("#next").onclick = () => { if (A.idx < A.ids.length - 1) go(A.idx + 1); else { A.showGrid = true; save(); renderRunner(root); document.getElementById("gridbox").scrollIntoView(); } };
root.querySelector("#flag").onclick = () => { A.flags[c.id] = !A.flags[c.id]; save(); renderRunner(root); };
root.querySelector("#gridbox").ontoggle = e => { A.showGrid = e.target.open; save(); };
root.querySelectorAll("[data-jump]").forEach(b => b.onclick = () => go(+b.dataset.jump));
root.querySelector("#submit").onclick = () => {
const blank = A.ids.length - Object.keys(A.answers).length;
ask(blank ? `${blank} question(s) unanswered. Submit anyway? On the real exam, never leave one blank.` : "Submit the exam?", () => finishExam(), "Submit");
};
clearInterval(tick);
tick = setInterval(() => {
if (!S.active) { clearInterval(tick); return; }
const r = remaining(), el = document.getElementById("timer");
if (el) { el.textContent = mmss(r); el.classList.toggle("low", r < 600); }
if (r <= 0) { clearInterval(tick); finishExam(true); }
}, 1000);
}
let examResult = null;
function finishExam(timedOut) {
const A = S.active; if (!A) return;
const byArea = {}, missed = [];
let correct = 0;
A.ids.forEach(id => {
const c = BY_ID[id], ok = A.answers[id] === c.a;
const t = byArea[c.area] || [0, 0]; t[1]++; if (ok) { t[0]++; correct++; } else missed.push(id);
byArea[c.area] = t;
});
const used = Math.min(A.minutes * 60, (Date.now() - A.start) / 1000);
const rec = { kind: A.kind, name: A.name, date: today(), n: A.ids.length, correct, byArea, missed,
ids: A.ids, answers: A.answers, usedMin: Math.round(used / 60), minutes: A.minutes, timedOut: !!timedOut };
S.mocks.push(rec); S.active = null; save();
examResult = rec;
show("exam");
}
function renderResult(root, m) {
const p = pct(m.correct, m.n);
const verdict = p >= PASS_HIGH ? "Above the highest historical cut score." :
p >= PASS_LOW ? "Close: keep going." : "Below the demo target.";
const areaRows = AREAS.filter(a => m.byArea[a.id]).map(a => {
const [ok, n] = m.byArea[a.id];
return `<tr><td>${a.name}<br><span class="tag">${a.weight}% of exam</span></td><td>${ok}/${n}</td>
<td class="u3"><div class="bar-track"><div class="bar-fill" data-w="${pct(ok, n)}"></div></div><span class="${scoreClass(pct(ok, n))}">${pct(ok, n)}%</span></td></tr>`;
}).join("");
const famMiss = {};
m.missed.forEach(id => { const f = BY_ID[id].family; famMiss[f] = (famMiss[f] || 0) + 1; });
const weak = Object.entries(famMiss).sort((a, b) => b[1] - a[1]).slice(0, 5)
.map(([f, n]) => `${esc(f)} (${n})`).join(", ");
const items = m.ids.map((id, i) => {
const c = BY_ID[id], a = m.answers[id], ok = a === c.a;
return `<details class="card" data-ok="${ok}"><summary><b class="${ok ? "pass" : "fail"}">${i + 1}. ${ok ? "Correct" : a == null ? "Blank" : "Wrong"}</b>
<span class="muted">· ${esc(AREA_NAMES[c.area])} · ${esc(c.q.slice(0, 90))}${c.q.length > 90 ? "..." : ""}</span></summary>
<div class="u10">${questionHtml(c, { picked: a ?? null, reveal: true, locked: true })}${answerHtml(c, a ?? null)}</div></details>`;
}).join("");
root.innerHTML = `
<div class="card">
<div class="row u11">
<div><div class="muted">${esc(m.name)} · ${fmt(m.date)} · ${m.usedMin} of ${m.minutes} min${m.timedOut ? " (time ran out)" : ""}</div>
<div class="score-big ${scoreClass(p)}">${p}%</div><div>${m.correct} of ${m.n} correct. ${verdict}</div></div>
<div class="row"><button class="primary" id="tocards" ${m.missed.length ? "" : "disabled"}>Send ${m.missed.length} missed to flashcards</button>
<button class="ghost" id="back">Back to exams</button></div>
</div>
<p class="muted u5">Demo target ${PASS_HIGH}%.${weak ? " Most missed topics: " + weak + "." : ""}</p>
</div>
<div class="card scroll-x"><table><tr><th>Area</th><th>Score</th><th></th></tr>${areaRows}</table></div>
<div class="row u12"><b>Review</b><select id="filter"><option value="miss">Missed only</option><option value="all">All questions</option></select></div>
<div id="review">${items}</div>`;
const filt = () => { const all = root.querySelector("#filter").value === "all";
root.querySelectorAll("#review > details").forEach(d => d.classList.toggle("hidden", !all && d.dataset.ok === "true")); };
root.querySelector("#filter").onchange = filt; filt();
root.querySelector("#back").onclick = () => { examResult = null; renderExam(); };
root.querySelector("#tocards").onclick = e => {
const t = today();
m.missed.forEach(id => {
const st = S.cards[id] || { box: 1, reps: 0, lapses: 0 };
st.box = 1; st.due = t; st.gap = 1; S.cards[id] = st;
});
save(); e.target.textContent = "Added: due today"; e.target.disabled = true;
};
}
/* ---------- browse & settings ---------- */
function renderBrowse() {
const opts = AREAS.map(a => `<option value="${a.id}">${a.name}</option>`).join("");
const fams = FAMILIES.map(f => `<option>${esc(f.name)}</option>`).join("");
document.getElementById("view-browse").innerHTML = `
<div class="modes" data-modes></div>
<div class="card">
<div class="row">
<input class="u13" id="q" placeholder="Search questions or answers">
<select id="area"><option value="">All areas</option>${opts}</select>
<select id="fam"><option value="">All topics</option>${fams}</select>
<select id="tier"><option value="">All likelihoods</option><option>High</option><option>Medium</option><option>Low</option></select>
<select id="kind"><option value="">All cards</option><option value="problem">Worked problems</option><option value="concept">Concepts</option></select>
</div>
<p class="muted u5" id="count"></p>
</div>
<div id="list"></div>`;
const val = id => document.getElementById(id).value;
const draw = () => {
const q = val("q").toLowerCase(), a = val("area"), f = val("fam"), t = val("tier"), k = val("kind");
const rows = CARDS.filter(c => modeOk(c) && (!a || c.area === a) && (!f || c.family === f) && (!t || c.tier === t) &&
(!k || (k === "problem" ? isProblem(c) : k === "concept" ? !isProblem(c) : k === "figure" ? !!c.fig : !!c.note)) &&
(!q || [c.q, c.ctx, c.sol, c.src, c.pages, (c.c || []).join(" ")].join(" ").toLowerCase().includes(q)));
document.getElementById("count").textContent = `${rows.length} cards, most likely first.`;
document.getElementById("list").innerHTML = rows.slice(0, 120).map(c => {
const st = S.cards[c.id];
const label = !st ? "not started" : st.box >= 5 ? "learned" : "box " + st.box;
return `<details class="card"><summary>${tags(c)}<span class="tag">${label}</span><br><b>${esc(c.q)}</b></summary>
<div class="u10">${questionHtml(c, { picked: null, reveal: true, locked: true })}${answerHtml(c, null)}</div></details>`;
}).join("") + (rows.length > 120 ? `<p class="muted">Showing the first 120. Narrow the filters to see more.</p>` : "") ||
`<p class="muted">No cards match.</p>`;
};
["q", "area", "fam", "tier", "kind"].forEach(id => document.getElementById(id).addEventListener(id === "q" ? "input" : "change", draw));
browseDraw = draw;
refreshModes();
draw();
}
function renderSettings() {
document.getElementById("view-settings").innerHTML = `
<div class="card">
<h2 class="u6">Exam date</h2>
<p class="muted u6">The schedule and review timing adjust to this date.</p>
<div class="row"><input type="date" id="exam" value="${S.examDate || ""}" min="${today()}">
<button class="ghost" id="exam-clear">Use default (28 days)</button></div>
</div>
<div class="card">
<h2 class="u6">Daily new cards</h2>
<p class="muted u6">Automatic: ${autoNewPerDay()} per day. Enter a number to override.</p>
<div class="row"><input type="number" id="perday" min="1" max="200" value="${S.newPerDay || ""}" placeholder="${autoNewPerDay()}">
<button class="ghost" id="perday-save">Save</button></div>
<p class="u14"><label><input type="checkbox" id="lowtier" ${S.includeLow ? "checked" : ""}> Include low-likelihood cards in the plan (${CARDS.filter(c => c.tier === "Low").length} cards)</label></p>
</div>
<div class="card">
<h2 class="u6">Theme</h2>
<select id="theme"><option value="">Match device</option><option value="light">Light</option><option value="dark">Dark</option></select>
</div>
<div class="card">
<h2 class="u6">Backup</h2>
<p class="muted u6">Progress and mock exam history stay in this browser only. Copy them to keep a backup, or import a saved file on another device.</p>
<div class="row"><button class="ghost" id="export">Copy progress</button>
<label class="ghost u15">Import file<input type="file" id="import" accept="application/json" class="hidden"></label></div>
</div>
<div class="card">
<h2 class="u6">About the cards</h2>
<p class="muted u2">${CARDS.filter(isProblem).length} worked problems and ${CARDS.filter(c => !isProblem(c)).length} concept cards, all written for this demonstration and checked by recomputing every answer. The full version runs the same app on a much larger private deck.</p>
</div>
<div class="card">
<h2 class="u6">Reset</h2>
<p class="muted u6">Erases all card progress and mock exam history in this browser.</p>
<button class="danger" id="reset">Reset progress</button>
</div>`;
document.getElementById("exam").addEventListener("change", e => { S.examDate = e.target.value; save(); render(); });
document.getElementById("exam-clear").onclick = () => { S.examDate = ""; save(); render(); };
document.getElementById("perday-save").onclick = () => {
const v = parseInt(document.getElementById("perday").value, 10);
S.newPerDay = v > 0 ? v : 0; save(); render();
};
document.getElementById("lowtier").onchange = e => { S.includeLow = e.target.checked; save(); render(); };
const savedTheme = (() => { try { return localStorage.getItem("surveying-theme") || ""; } catch (e) { return ""; } })();
const themeSel = document.getElementById("theme");
themeSel.value = savedTheme;
themeSel.onchange = () => {
try { localStorage.setItem("surveying-theme", themeSel.value); } catch (e) {}
applyTheme(themeSel.value);
};
document.getElementById("export").onclick = async e => {
const btn = e.currentTarget;
try { await navigator.clipboard.writeText(JSON.stringify(S)); btn.textContent = "Copied"; }
catch (err) { btn.textContent = "Copy failed"; }
setTimeout(() => { btn.textContent = "Copy progress"; }, 1600);
};
document.getElementById("import").onchange = async e => {
const f = e.target.files[0]; if (!f) return;
try {
const data = JSON.parse(await f.text());
if (!data || typeof data.cards !== "object") throw new Error("not a progress file");
S = Object.assign(freshState(), data, { v: 2 });
save(); render();
} catch (err) { tell("That file is not a valid progress file. Choose a file saved with Copy progress."); }
};
document.getElementById("reset").onclick = () => {
ask("Erase all progress and mock exam history in this browser? This can't be undone.", () => {
S = Object.assign(freshState(), { examDate: S.examDate });
examResult = null; save(); render();
}, "Erase");
};
}
function applyTheme(t) {
if (t) document.documentElement.setAttribute("data-theme", t);
else document.documentElement.removeAttribute("data-theme");
}
/* ---------- navigation ---------- */
const VIEWS = ["home", "study", "exam", "browse", "settings"];
let view = "home";
function show(v) {
view = v;
document.querySelectorAll("nav button").forEach(b => b.classList.toggle("on", b.dataset.view === v));
VIEWS.forEach(name => document.getElementById("view-" + name).classList.toggle("hidden", name !== v));
render();
window.scrollTo(0, 0);
}
function render() {
if (view !== "exam") { clearInterval(tick); tick = null; }
if (view === "home") renderHome();
if (view === "study") { if (!queue.length && index === 0) startSession(); else renderStudy(); }
if (view === "exam") renderExam();
if (view === "browse") renderBrowse();
if (view === "settings") renderSettings();
}
document.querySelectorAll("nav button").forEach(b => b.addEventListener("click", () => show(b.dataset.view)));
// Mode tabs appear in Study and Cards; the choice is shared, so both views follow it.
document.querySelector("main").addEventListener("click", e => {
const b = e.target.closest("[data-mode]"); if (!b) return;
S.mode = b.dataset.mode; save();
startSession();
browseDraw();
});
document.getElementById("view-home").addEventListener("click", e => {
const b = e.target.closest("[data-go]"); if (b) show(b.dataset.go);
});
document.getElementById("view-exam").addEventListener("click", e => {
const s = e.target.closest("[data-start]");
if (s) {
const go = () => { S.active = null; startExam(s.dataset.start); };
if (S.active) ask("Abandon the exam in progress?", go, "Abandon"); else go();
return;
}
const r = e.target.closest("[data-review]");
if (r) { examResult = S.mocks[+r.dataset.review]; renderExam(); window.scrollTo(0, 0); }
});
document.getElementById("flashcard").addEventListener("click", e => {
const b = e.target.closest("[data-choice]"); if (b) pick(+b.dataset.choice);
});
document.getElementById("reveal").addEventListener("click", flip);
document.getElementById("next").addEventListener("click", next);
document.addEventListener("keydown", e => {
if (["INPUT", "SELECT", "TEXTAREA"].includes(e.target.tagName) || e.ctrlKey || e.metaKey || e.altKey) return;
if (!document.getElementById("modal").classList.contains("hidden")) { if (e.key === "Escape") document.getElementById("modal-no").click(); return; }
const k = e.key.toUpperCase();
if (view === "study") {
if (e.code === "Space") { e.preventDefault(); flip(); }
else if (!flipped && "ABCDE".includes(k) && k.length === 1) pick(LETTERS.indexOf(k));
} else if (view === "exam" && S.active) {
const c = BY_ID[S.active.ids[S.active.idx]];
if ("ABCDE".includes(k) && k.length === 1 && LETTERS.indexOf(k) < c.c.length) { S.active.answers[c.id] = LETTERS.indexOf(k); save(); renderExam(); }
else if (e.key === "ArrowRight" && S.active.idx < S.active.ids.length - 1) { S.active.idx++; save(); renderExam(); }
else if (e.key === "ArrowLeft" && S.active.idx > 0) { S.active.idx--; save(); renderExam(); }
}
});
try { applyTheme(localStorage.getItem("surveying-theme") || ""); } catch (e) {}
// The header wraps on narrow screens; keep the exam timer bar just below it.
const setHdr = () => {
const h = document.querySelector("header");
document.documentElement.style.setProperty("--hdr", (getComputedStyle(h).position === "sticky" ? h.offsetHeight : 0) + "px");
};
window.addEventListener("resize", setHdr); setHdr();
show(S.active ? "exam" : "home");
// Bar widths are set here rather than in a style="" attribute, so the page works under the site's strict
// Content-Security-Policy (style-src 'self').
(function () {
const size = root => root.querySelectorAll('[data-w]').forEach(el => { el.style.width = el.dataset.w + '%'; });
size(document);
new MutationObserver(() => size(document)).observe(document.body, { childList: true, subtree: true });
})();
app.css118 lines
:root {
--bg: #f6f7f9; --card: #ffffff; --ink: #1b2430; --muted: #617084;
--line: #dde2ea; --accent: #1f5fae; --good: #2e7d4f; --bad: #b3362b;
--hard: #b26a00; --easy: #2b7aa8; --good-bg: #e7f4ec; --bad-bg: #fbeceb; --note-bg: #fff6e5;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #13171d; --card: #1d232c; --ink: #e8edf3; --muted: #9aa7b8;
--line: #2e3744; --accent: #6aa6ef; --good: #5bbf85; --bad: #ef7b70;
--hard: #e0a24a; --easy: #6cb6df; --good-bg: #1c3326; --bad-bg: #3a2220; --note-bg: #3a2f17;
}
}
:root[data-theme="dark"] {
--bg: #13171d; --card: #1d232c; --ink: #e8edf3; --muted: #9aa7b8;
--line: #2e3744; --accent: #6aa6ef; --good: #5bbf85; --bad: #ef7b70;
--hard: #e0a24a; --easy: #6cb6df; --good-bg: #1c3326; --bad-bg: #3a2220; --note-bg: #3a2f17;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 16px/1.5 system-ui, -apple-system, Segoe UI, Roboto, sans-serif; }
header { position: sticky; top: env(safe-area-inset-top, 0px); z-index: 3; background: var(--card); border-bottom: 1px solid var(--line); }
header .bar { max-width: 900px; margin: auto; padding: 10px 16px; display: flex; align-items: center; gap: 8px 12px; flex-wrap: wrap; }
header h1 { font-size: 17px; margin: 0; flex: 1; min-width: 180px; }
nav { display: flex; flex-wrap: wrap; gap: 2px; }
nav button { background: none; border: 1px solid transparent; color: var(--muted); padding: 6px 10px; border-radius: 8px; cursor: pointer; font: inherit; }
nav button.on { color: var(--accent); border-color: var(--line); background: var(--bg); }
.modes { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 12px; }
.modes button { background: none; border: 1px solid var(--line); color: var(--muted); padding: 6px 12px; border-radius: 99px; cursor: pointer; font: inherit; font-size: 14px; }
.modes button.on { color: var(--ink); border-color: var(--accent); background: var(--bg); box-shadow: 0 0 0 1px var(--accent) inset; }
.modes button span { font-size: 12px; }
main { max-width: 900px; margin: auto; padding: 16px; }
h2 { font-size: 18px; margin: 20px 0 10px; }
h3 { font-size: 16px; margin: 0 0 6px; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 16px; margin-bottom: 14px; }
.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.stat b { display: block; font-size: 24px; }
.stat span, .muted { color: var(--muted); font-size: 14px; }
.bar-track { height: 10px; background: var(--line); border-radius: 99px; overflow: hidden; margin: 6px 0 2px; }
.bar-fill { height: 100%; background: var(--accent); border-radius: 99px; }
.tag { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 99px; border: 1px solid var(--line); color: var(--muted); margin: 0 6px 4px 0; }
.tag.def, .tag.High { color: var(--bad); border-color: var(--bad); }
.tag.mar, .tag.Medium { color: var(--hard); border-color: var(--hard); }
.tag.Low { color: var(--easy); border-color: var(--easy); }
.tag.calc { color: var(--accent); border-color: var(--accent); }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
td, th { text-align: left; padding: 8px 6px; border-bottom: 1px solid var(--line); vertical-align: top; }
.scroll-x { overflow-x: auto; }
input, select { font: inherit; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); max-width: 100%; }
button.primary, button.ghost, button.danger { font: inherit; padding: 10px 16px; border-radius: 10px; cursor: pointer; border: 1px solid var(--accent); }
button.primary { background: var(--accent); color: #fff; }
button.ghost { background: none; color: var(--accent); }
button.danger { border-color: var(--bad); background: none; color: var(--bad); }
button:disabled { opacity: .45; cursor: default; }
.row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.hidden { display: none !important; }
.banner { background: var(--card); border-left: 4px solid var(--hard); padding: 12px 14px; border-radius: 10px; margin-bottom: 14px; }
.boxes { display: flex; gap: 6px; flex-wrap: wrap; }
.box { flex: 1; min-width: 60px; text-align: center; padding: 8px 4px; border: 1px solid var(--line); border-radius: 10px; font-size: 13px; }
.box b { display: block; font-size: 18px; }
/* question layout, shared by flashcards, mock exams and the card list */
.ctx { font-size: 14px; color: var(--muted); border-left: 3px solid var(--line); padding: 2px 0 2px 10px; margin: 0 0 10px; }
.qtext { font-size: 18px; margin: 4px 0 12px; }
.fig { display: block; max-width: 100%; max-height: 420px; margin: 4px auto 12px; background: #fff; border: 1px solid var(--line); border-radius: 8px; padding: 6px; cursor: zoom-in; }
.fig.big { max-height: none; cursor: zoom-out; }
.choices { display: grid; gap: 8px; margin: 6px 0 4px; }
.choice { text-align: left; font: inherit; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--card); color: var(--ink); cursor: pointer; display: flex; gap: 10px; }
.choice .l { font-weight: 600; color: var(--muted); min-width: 1.2em; }
.choice.picked { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.choice.right { border-color: var(--good); background: var(--good-bg); }
.choice.wrong { border-color: var(--bad); background: var(--bad-bg); }
.choice:disabled { cursor: default; opacity: 1; color: var(--ink); }
.answer { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 12px; }
.note { background: var(--note-bg); border-radius: 8px; padding: 8px 10px; font-size: 14px; margin-top: 10px; }
.src { margin-top: 12px; font-size: 13px; color: var(--muted); }
/* mock exams */
.exam-pick { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
.exam-pick .card { margin: 0; display: flex; flex-direction: column; gap: 8px; }
.exam-pick .card p { margin: 0; flex: 1; }
.examhead { position: sticky; top: calc(var(--hdr, 54px) + 6px); z-index: 2; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; margin-bottom: 12px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.timer { font-variant-numeric: tabular-nums; font-weight: 700; font-size: 20px; }
.timer.low { color: var(--bad); }
.qgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(38px, 1fr)); gap: 6px; }
.qgrid button { font: inherit; font-size: 13px; padding: 6px 0; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--ink); cursor: pointer; }
.qgrid button.done { background: var(--accent); border-color: var(--accent); color: #fff; }
.qgrid button.flag { box-shadow: 0 0 0 2px var(--hard) inset; }
.qgrid button.cur { outline: 2px solid var(--ink); outline-offset: 1px; }
.demo-note { margin: 0; padding: 8px 16px; font-size: 13px; text-align: center; background: var(--note-bg); color: var(--ink); border-bottom: 1px solid var(--line); }
.score-big { font-size: 40px; font-weight: 700; line-height: 1.1; }
.pass { color: var(--good); } .fail { color: var(--bad); } .edge { color: var(--hard); }
details > summary { cursor: pointer; }
.modal { position: fixed; inset: 0; z-index: 20; background: rgba(0,0,0,.45); display: flex; align-items: center; justify-content: center; padding: 16px; }
.modal .card { max-width: 420px; width: 100%; margin: 0; }
.examhead .st { font-size: 14px; }
@media (max-width: 560px) {
.qtext { font-size: 17px; }
header { position: static; }
.examhead .st { order: 3; width: 100%; font-size: 13px; }
}
/* former inline styles (CSP) */
.u1{margin:0 0 6px !important}
.u2{margin:0 !important}
.u3{width:40% !important}
.u4{margin:14px 0 0 !important}
.u5{margin:10px 0 0 !important}
.u6{margin-top:0 !important}
.u7{flex:1 !important}
.u8{font-size:13px !important;margin-bottom:4px !important}
.u9{margin-top:12px !important}
.u10{margin-top:10px !important}
.u11{justify-content:space-between !important}
.u12{margin-bottom:10px !important}
.u13{flex:1 !important;min-width:180px !important}
.u14{margin:12px 0 0 !important}
.u15{padding:10px 16px !important;display:inline-block !important;cursor:pointer !important;color:var(--accent) !important}
.u16{justify-content:flex-end !important}
cards.js (40 sample cards)47 lines
// Sample cards written for this demonstration. Every question is original.
const AREAS = [{"id": "planning", "name": "Survey Planning", "weight": 25}, {"id": "field", "name": "Field Data Collection", "weight": 15}, {"id": "data", "name": "Data Analysis and Evaluation", "weight": 30}, {"id": "mapping", "name": "Mapping", "weight": 10}, {"id": "construction", "name": "Construction Surveying", "weight": 20}];
const FAMILIES = [{"name": "Horizontal curves", "problems": 6}, {"name": "Traverse and coordinates", "problems": 6}, {"name": "Leveling", "problems": 4}, {"name": "Maps and contours", "problems": 4}, {"name": "Grades and slope staking", "problems": 4}, {"name": "Control and planning", "problems": 3}, {"name": "Errors and accuracy", "problems": 3}, {"name": "Distance measurement", "problems": 2}, {"name": "Vertical curves", "problems": 2}, {"name": "Earthwork and volumes", "problems": 2}, {"name": "Coordinate systems", "problems": 2}, {"name": "Areas", "problems": 1}, {"name": "GNSS", "problems": 1}];
const BOOK_EXAMS = [];
const CARDS = [
{"id": "hc-1", "area": "data", "family": "Horizontal curves", "topic": "curve length", "mode": "calculation", "q": "A circular curve has radius 800 ft and central angle 40°00'00\". Length of the curve is most nearly:", "sol": "L = R × Δ (radians) = 800 × 40×π/180 = 558.51 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["558.51 ft", "291.18 ft", "547.23 ft", "586.39 ft"], "a": 0, "grp": "hc", "score": 1.0, "ord": 0},
{"id": "hc-2", "area": "data", "family": "Horizontal curves", "topic": "tangent length", "mode": "calculation", "q": "Same curve. Tangent length T is most nearly:", "sol": "T = R tan(Δ/2) = 800 × tan 20° = 291.18 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["273.62 ft", "291.18 ft", "671.28 ft", "279.25 ft"], "a": 1, "ctx": "A circular curve has radius 800 ft and central angle 40°00'00\".", "grp": "hc", "score": 0.998, "ord": 1},
{"id": "hc-3", "area": "data", "family": "Horizontal curves", "topic": "long chord", "mode": "calculation", "q": "Same curve. Long chord LC is most nearly:", "sol": "LC = 2R sin(Δ/2) = 2 × 800 × sin 20° = 547.23 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["558.51 ft", "582.35 ft", "547.23 ft", "514.23 ft"], "a": 2, "ctx": "A circular curve has radius 800 ft and central angle 40°00'00\".", "grp": "hc", "score": 0.996, "ord": 2},
{"id": "hc-4", "area": "data", "family": "Horizontal curves", "topic": "curve stationing", "mode": "calculation", "q": "Same curve, with the PI at station 12+40.00. Station of the PT is most nearly:", "sol": "PC = PI − T = 9+48.82; PT = PC + L = 15+07.33. The PT is found along the curve, not by adding T to the PI.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["15+31.18", "15+07.33", "14+96.06", "15+19.25"], "a": 1, "ctx": "A circular curve has radius 800 ft and central angle 40°00'00\".", "grp": "hc", "score": 0.994, "ord": 3},
{"id": "tr-1", "area": "data", "family": "Traverse and coordinates", "topic": "traverse closure", "mode": "calculation", "q": "A closed traverse has a latitude error of -0.24 ft and a departure error of +0.32 ft. Perimeter 3,200.00 ft. Linear error of closure is most nearly:", "sol": "e = √(0.24² + 0.32²) = 0.40 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["0.56 ft", "0.40 ft", "0.08 ft", "0.32 ft"], "a": 1, "grp": "tr", "score": 0.988, "ord": 6},
{"id": "tr-2", "area": "data", "family": "Traverse and coordinates", "topic": "traverse precision", "mode": "calculation", "q": "Same traverse. Relative precision is most nearly:", "sol": "Precision = e / perimeter = 0.40 / 3,200 = 1/8,000.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["1/5,700", "1/8,000", "1/10,000", "1/13,300"], "a": 1, "ctx": "A closed traverse has a latitude error of -0.24 ft and a departure error of +0.32 ft. Perimeter 3,200.00 ft.", "grp": "tr", "score": 0.986, "ord": 7},
{"id": "tr-3", "area": "data", "family": "Traverse and coordinates", "topic": "azimuth and bearing", "mode": "calculation", "q": "A line has an azimuth (from north) of 237°15'00\". Its bearing is:", "sol": "237°15' is in the SW quadrant: bearing = S (237°15' − 180°) W = S 57°15'00\" W.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["N 57°15'00\" W", "S 57°15'00\" W", "S 32°45'00\" W", "N 57°15'00\" E"], "a": 1, "grp": "tr-3", "score": 0.984, "ord": 8},
{"id": "tr-4", "area": "data", "family": "Traverse and coordinates", "topic": "latitude and departure", "mode": "calculation", "q": "A course is 450.00 ft long on a bearing of N 35°00'00\" E. Its latitude and departure are most nearly:", "sol": "Lat = L cos β = 368.62 ft (north, +); Dep = L sin β = 258.11 ft (east, +).", "tier": "High", "src": "Sample card written for this demonstration", "c": ["Lat 258.11, Dep 368.62", "Lat 368.62, Dep 258.11", "Lat −368.62, Dep 258.11", "Lat 368.62, Dep −258.11"], "a": 1, "grp": "tr-4", "score": 0.982, "ord": 9},
{"id": "tr-5", "area": "data", "family": "Traverse and coordinates", "topic": "inverse", "mode": "calculation", "q": "Point A is at N 1,000.00, E 1,000.00 and point B at N 1,300.00, E 1,400.00. Distance and bearing from A to B:", "sol": "ΔN = 300, ΔE = 400. Distance = √(300²+400²) = 500.00 ft; bearing = N tan⁻¹(400/300) E = N 53°07'48\" E.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["500.00 ft, N 53°07'48\" E", "500.00 ft, N 36°52'12\" E", "700.00 ft, N 45°00'00\" E", "500.00 ft, S 53°07'48\" W"], "a": 0, "grp": "tr-5", "score": 0.98, "ord": 10},
{"id": "fd-1", "area": "field", "family": "Distance measurement", "topic": "temperature correction", "mode": "calculation", "q": "A steel tape standardized at 68°F is used at 98°F to measure 600.00 ft. The corrected distance is most nearly (α = 6.45×10⁻⁶ /°F):", "sol": "C = α × ΔT × L = 6.45×10⁻⁶ × 30 × 600 = +0.116 ft. A warm tape is too long, so it reads short: add the correction. 600.12 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["599.88 ft", "600.00 ft", "600.12 ft", "600.23 ft"], "a": 2, "grp": "fd-1", "score": 0.968, "ord": 16},
{"id": "fd-2", "area": "field", "family": "Distance measurement", "topic": "slope reduction", "mode": "calculation", "q": "A slope distance of 350.00 ft is measured on a 6°30'00\" vertical angle. The horizontal distance is most nearly:", "sol": "H = S cos θ = 350.00 × cos 6.5° = 347.75 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["347.75 ft", "39.62 ft", "352.26 ft", "350.00 ft"], "a": 0, "grp": "fd-2", "score": 0.966, "ord": 17},
{"id": "lv-1", "area": "field", "family": "Leveling", "topic": "differential leveling", "mode": "calculation", "q": "A backsight of 4.52 ft is taken on a benchmark at elevation 1,200.00 ft. A foresight of 7.18 ft is read on point X. Elevation of X:", "sol": "HI = 1,200.00 + 4.52 = 1,204.52. Elev X = HI − FS = 1,204.52 − 7.18 = 1,197.34 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["1,202.66 ft", "1,197.34 ft", "1,211.70 ft", "1,195.48 ft"], "a": 1, "grp": "lv-1", "score": 0.964, "ord": 18},
{"id": "lv-2", "area": "field", "family": "Leveling", "topic": "height of instrument", "mode": "conceptual", "q": "In differential leveling, what is the height of instrument (HI)?", "sol": "The elevation of the line of sight: the known elevation plus the backsight. Every foresight is subtracted from it.", "tier": "High", "src": "Sample card written for this demonstration", "grp": "lv-2", "score": 0.962, "ord": 19},
{"id": "pl-1", "area": "planning", "family": "Control and planning", "topic": "closure standard", "mode": "calculation", "q": "A traverse with a 5,000-ft perimeter must meet a precision of 1/10,000. The largest allowable linear error of closure is:", "sol": "Allowable error = perimeter × precision = 5,000 / 10,000 = 0.50 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["0.05 ft", "0.50 ft", "2.00 ft", "5.00 ft"], "a": 1, "grp": "pl-1", "score": 0.956, "ord": 22},
{"id": "pl-2", "area": "planning", "family": "Control and planning", "topic": "control first", "mode": "conceptual", "q": "Why is control established before detail (topography, stakeout) on a project?", "sol": "Control is the accurate framework everything else ties to. Working from the whole to the part keeps small errors in detail from adding up across the site.", "tier": "High", "src": "Sample card written for this demonstration", "grp": "pl-2", "score": 0.954, "ord": 23},
{"id": "mp-1", "area": "mapping", "family": "Maps and contours", "topic": "map scale", "mode": "calculation", "q": "On a map at 1\" = 200', two points are 2.35 in apart. The ground distance is:", "sol": "2.35 in × 200 ft/in = 470 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["235 ft", "470 ft", "85 ft", "4,700 ft"], "a": 1, "grp": "mp-1", "score": 0.944, "ord": 28},
{"id": "cn-1", "area": "construction", "family": "Grades and slope staking", "topic": "grade elevation", "mode": "calculation", "q": "Station 10+00 has a design elevation of 520.00 ft on a −1.50% grade. The design elevation at station 13+50:", "sol": "Δ = −0.015 × 350 ft = −5.25 ft. 520.00 − 5.25 = 514.75 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["514.75 ft", "525.25 ft", "519.48 ft", "505.00 ft"], "a": 0, "grp": "cn-1", "score": 0.936, "ord": 32},
{"id": "cn-2", "area": "construction", "family": "Grades and slope staking", "topic": "cut or fill", "mode": "calculation", "q": "Ground elevation at a stake is 534.20 ft and design grade is 530.75 ft. The stake is marked:", "sol": "Ground is above grade by 534.20 − 530.75 = 3.45 ft, so it is a cut: C 3.45.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["F 3.45", "C 3.45", "C 0.00", "F 0.00"], "a": 1, "grp": "cn-2", "score": 0.934, "ord": 33},
{"id": "cn-3", "area": "construction", "family": "Grades and slope staking", "topic": "slope stake offset", "mode": "calculation", "q": "A cut section has a 20-ft half-width to the toe of the cut slope, side slopes of 2:1 (horizontal:vertical) and a cut of 6.0 ft at the catch point. Offset from centerline to the slope stake:", "sol": "Offset = half-width + slope ratio × cut = 20 + 2 × 6.0 = 32.0 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["26.0 ft", "32.0 ft", "23.0 ft", "40.0 ft"], "a": 1, "grp": "cn-3", "score": 0.932, "ord": 34},
{"id": "vc-1", "area": "construction", "family": "Vertical curves", "topic": "high point", "mode": "calculation", "q": "A crest vertical curve joins a +2.00% grade to a −1.50% grade, length 600 ft. Distance from the BVC to the high point is most nearly:", "sol": "x = g₁ L / (g₁ − g₂) = 2.00 × 600 / 3.50 = 342.86 ft.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["300.00 ft", "342.86 ft", "257.14 ft", "400.00 ft"], "a": 1, "grp": "vc", "score": 0.93, "ord": 35},
{"id": "cn-4", "area": "construction", "family": "Earthwork and volumes", "topic": "average end area", "mode": "calculation", "q": "End areas of 210 sq ft and 330 sq ft are 100 ft apart. The volume by average end areas is:", "sol": "V = (A₁ + A₂)/2 × L / 27 = 270 × 100 / 27 = 1,000 cu yd.", "tier": "High", "src": "Sample card written for this demonstration", "c": ["1,000 cu yd", "2,000 cu yd", "27,000 cu yd", "500 cu yd"], "a": 0, "grp": "cn-4", "score": 0.926, "ord": 37},
{"id": "hc-5", "area": "data", "family": "Horizontal curves", "topic": "degree of curve", "mode": "calculation", "q": "Degree of curve (arc definition) for a 800-ft radius is most nearly:", "sol": "D = 5,729.58 / R = 7.1620° = 7°09'43\".", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["7°09'43\"", "5°43'46\"", "7°18'36\"", "3°34'52\""], "a": 0, "grp": "hc-5", "score": 0.592, "ord": 4},
{"id": "hc-6", "area": "data", "family": "Horizontal curves", "topic": "curve terms", "mode": "conceptual", "q": "On a circular curve, what is the PI?", "sol": "The point of intersection: where the two tangents, extended, meet. The curve starts at the PC and ends at the PT.", "tier": "Medium", "src": "Sample card written for this demonstration", "grp": "hc-6", "score": 0.59, "ord": 5},
{"id": "tr-6", "area": "planning", "family": "Traverse and coordinates", "topic": "angle closure", "mode": "calculation", "q": "The interior angles of a closed seven-sided traverse should add up to:", "sol": "Sum of interior angles = (n − 2) × 180° = 5 × 180° = 900°.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["720°", "900°", "1,080°", "1,260°"], "a": 1, "grp": "tr-6", "score": 0.578, "ord": 11},
{"id": "ar-1", "area": "data", "family": "Areas", "topic": "area by coordinates", "mode": "calculation", "q": "A triangular lot has corners at (E 0, N 0), (E 400, N 0) and (E 150, N 300), in feet. Its area is most nearly:", "sol": "Area = ½ |x₁(y₂−y₃) + x₂(y₃−y₁) + x₃(y₁−y₂)| = ½ × 400 × 300 = 60,000 sq ft = 60,000 / 43,560 = 1.38 acres.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["1.38 acres", "2.75 acres", "0.69 acres", "1.84 acres"], "a": 0, "grp": "ar-1", "score": 0.576, "ord": 12},
{"id": "er-1", "area": "data", "family": "Errors and accuracy", "topic": "error propagation", "mode": "calculation", "q": "A distance is taped in four segments, each with a standard error of ±0.02 ft. The standard error of the total is:", "sol": "Random errors add in quadrature: √(4 × 0.02²) = 0.02 × √4 = ±0.04 ft.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["±0.08 ft", "±0.04 ft", "±0.02 ft", "±0.01 ft"], "a": 1, "grp": "er-1", "score": 0.574, "ord": 13},
{"id": "er-3", "area": "data", "family": "Errors and accuracy", "topic": "error types", "mode": "conceptual", "q": "Which kind of error cannot be removed by a correction and is reduced only by repeating measurements?", "sol": "Random errors have no fixed sign or size, so no single correction removes them; averaging repeats reduces them. Systematic errors are corrected; blunders are found and thrown out.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["Systematic error", "Random error", "Blunder", "Instrument calibration error"], "a": 1, "grp": "er-3", "score": 0.57, "ord": 15},
{"id": "lv-3", "area": "field", "family": "Leveling", "topic": "curvature and refraction", "mode": "calculation", "q": "Combined curvature and refraction for a 5,000-ft sight is most nearly (h = 0.0206 F², F in thousands of feet):", "sol": "h = 0.0206 × 5² = 0.515 ft, about 0.52 ft. Balancing backsight and foresight lengths cancels it.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["0.10 ft", "0.52 ft", "0.67 ft", "2.06 ft"], "a": 1, "grp": "lv-3", "score": 0.56, "ord": 20},
{"id": "pl-3", "area": "planning", "family": "GNSS", "topic": "PDOP", "mode": "conceptual", "q": "For a GNSS observation session, which PDOP value is the best?", "sol": "PDOP measures satellite geometry; lower is better. Under about 3 is good; many specifications reject sessions above 6.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["1.8", "4.5", "7.0", "12.0"], "a": 0, "grp": "pl-3", "score": 0.552, "ord": 24},
{"id": "pl-4", "area": "planning", "family": "Coordinate systems", "topic": "grid to ground", "mode": "calculation", "q": "A grid distance is 1,000.00 ft and the combined factor is 0.99985. The ground distance is most nearly:", "sol": "Ground = grid / combined factor = 1000.00 / 0.99985 = 1,000.15 ft.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["999.85 ft", "1,000.15 ft", "1,000.00 ft", "1,001.50 ft"], "a": 1, "grp": "pl-4", "score": 0.55, "ord": 25},
{"id": "pl-6", "area": "planning", "family": "Control and planning", "topic": "benchmarks", "mode": "conceptual", "q": "What is a benchmark?", "sol": "A benchmark is a stable, permanent point whose elevation is known. A temporary benchmark (TBM) is set for the duration of a job.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["A point with a known horizontal position only", "A permanent point of known elevation", "A temporary stake for grading", "A property corner monument"], "a": 1, "grp": "pl-6", "score": 0.546, "ord": 27},
{"id": "mp-2", "area": "mapping", "family": "Maps and contours", "topic": "representative fraction", "mode": "calculation", "q": "A map scale of 1:2,400 is the same as:", "sol": "2,400 in on the ground per inch on the map = 2,400 / 12 = 200 ft per inch.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["1\" = 24'", "1\" = 200'", "1\" = 2,400'", "1\" = 100'"], "a": 1, "grp": "mp-2", "score": 0.542, "ord": 29},
{"id": "mp-3", "area": "mapping", "family": "Maps and contours", "topic": "contour interpolation", "mode": "calculation", "q": "Two spot elevations, 101.3 ft and 108.7 ft, are 74 ft apart. How far from the lower point does the 105-ft contour cross?", "sol": "Linear interpolation: (105 − 101.3) / (108.7 − 101.3) × 74 = 3.7 / 7.4 × 74 = 37.0 ft.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["37.0 ft", "33.0 ft", "50.0 ft", "5.0 ft"], "a": 0, "grp": "mp-3", "score": 0.54, "ord": 30},
{"id": "vc-2", "area": "construction", "family": "Vertical curves", "topic": "middle ordinate", "mode": "calculation", "q": "Same curve. The middle ordinate (curve below the PVI) is most nearly:", "sol": "e = A L / 8 with A in % and L in stations = 3.50 × 6 / 8 = 2.625 ft, about 2.63 ft.", "tier": "Medium", "src": "Sample card written for this demonstration", "c": ["1.31 ft", "2.63 ft", "5.25 ft", "0.88 ft"], "a": 1, "ctx": "A crest vertical curve joins a +2.00% grade to a −1.50% grade, length 600 ft.", "grp": "vc", "score": 0.528, "ord": 36},
{"id": "cn-5", "area": "construction", "family": "Earthwork and volumes", "topic": "swell and shrinkage", "mode": "conceptual", "q": "Why do earthwork estimates use swell and shrinkage factors?", "sol": "Soil takes more volume once excavated (swell) and less once compacted (shrinkage). Bank, loose and compacted yards differ, so haul and fill quantities are adjusted.", "tier": "Medium", "src": "Sample card written for this demonstration", "grp": "cn-5", "score": 0.524, "ord": 38},
{"id": "er-2", "area": "data", "family": "Errors and accuracy", "topic": "standard error of the mean", "mode": "calculation", "q": "Five repeated measurements of a distance have a standard deviation of 0.030 ft. The standard error of the mean is most nearly:", "sol": "σ_mean = σ / √n = 0.030 / √5 = 0.013 ft.", "tier": "Low", "src": "Sample card written for this demonstration", "c": ["0.006 ft", "0.013 ft", "0.030 ft", "0.067 ft"], "a": 1, "grp": "er-2", "score": 0.272, "ord": 14},
{"id": "lv-4", "area": "field", "family": "Leveling", "topic": "reciprocal leveling", "mode": "conceptual", "q": "Why do surveyors use reciprocal leveling across a river?", "sol": "A wide river stops you from setting up halfway. Reading across from both banks and averaging cancels the errors that balanced sights normally cancel.", "tier": "Low", "src": "Sample card written for this demonstration", "c": ["To save time on long lines", "Because sights cannot be balanced there, so reading from both sides averages out curvature, refraction and collimation error", "To avoid needing a benchmark", "To measure the river's depth"], "a": 1, "grp": "lv-4", "score": 0.258, "ord": 21},
{"id": "pl-5", "area": "planning", "family": "Coordinate systems", "topic": "combined factor", "mode": "conceptual", "q": "What makes up the combined factor used to convert between ground and grid distances?", "sol": "Combined factor = grid scale factor × elevation (sea-level) factor. Grid distance = ground distance × combined factor.", "tier": "Low", "src": "Sample card written for this demonstration", "grp": "pl-5", "score": 0.248, "ord": 26},
{"id": "mp-4", "area": "mapping", "family": "Maps and contours", "topic": "reading contours", "mode": "conceptual", "q": "Contour lines that are close together show:", "sol": "Close spacing means elevation changes quickly over a short distance: steep ground. Wide spacing is gentle.", "tier": "Low", "src": "Sample card written for this demonstration", "c": ["Flat ground", "Steep ground", "A depression", "A ridge line"], "a": 1, "grp": "mp-4", "score": 0.238, "ord": 31},
{"id": "cn-6", "area": "construction", "family": "Grades and slope staking", "topic": "offset stakes", "mode": "conceptual", "q": "Why are construction stakes often set on an offset line instead of on the exact point?", "sol": "Grading and excavation wipe out stakes on the line itself. An offset (say 10 ft) keeps the reference alive through construction.", "tier": "Low", "src": "Sample card written for this demonstration", "c": ["They are cheaper", "Stakes on the work line would be destroyed by the equipment; offsets survive and the crew measures back", "Offsets are more accurate", "Codes forbid stakes on the line"], "a": 1, "grp": "cn-6", "score": 0.222, "ord": 39}
];
progress.js (optional sync, Cloudflare Pages Function)70 lines
// Per-user progress sync. Cloudflare Access signs the user in and sends a signed
// JWT (Cf-Access-Jwt-Assertion). We verify its signature against the team's keys
// and use the verified email as the only key, so one user cannot read another's data.
// Storage: KV namespace bound as PROGRESS (set in the Pages project settings).
const TEAM = "https://YOUR-TEAM.cloudflareaccess.com";
const MAX_BYTES = 5 * 1024 * 1024;
let keyCache = { at: 0, keys: null };
const json = (obj, status = 200) =>
new Response(JSON.stringify(obj), {
status,
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
});
const bytes = s => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=")), c => c.charCodeAt(0));
const text = b => new TextDecoder().decode(b);
async function verifiedEmail(request) {
const token = request.headers.get("Cf-Access-Jwt-Assertion");
if (!token) return null;
const parts = token.split(".");
if (parts.length !== 3) return null;
const header = JSON.parse(text(bytes(parts[0])));
const payload = JSON.parse(text(bytes(parts[1])));
if (header.alg !== "RS256" || payload.iss !== TEAM) return null;
if (!payload.exp || payload.exp * 1000 < Date.now() || !payload.email) return null;
if (!keyCache.keys || Date.now() - keyCache.at > 3600e3) {
const r = await fetch(TEAM + "/cdn-cgi/access/certs");
keyCache = { at: Date.now(), keys: (await r.json()).keys || [] };
}
const jwk = keyCache.keys.find(k => k.kid === header.kid);
if (!jwk) return null;
const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
const ok = await crypto.subtle.verify(
"RSASSA-PKCS1-v1_5", key, bytes(parts[2]), new TextEncoder().encode(parts[0] + "." + parts[1])
);
return ok ? payload.email : null;
}
export async function onRequest({ request, env }) {
let email;
try { email = await verifiedEmail(request); } catch (e) { email = null; }
if (!email) return json({ error: "Sign in required" }, 401);
if (!env.PROGRESS) return json({ error: "Storage not configured" }, 500);
const key = "progress:" + email.trim().toLowerCase();
if (request.method === "GET") {
const raw = await env.PROGRESS.get(key);
return raw ? json(JSON.parse(raw)) : json({ data: null, savedAt: 0 });
}
if (request.method === "PUT") {
const body_text = await request.text();
if (body_text.length > MAX_BYTES) return json({ error: "Too large" }, 413);
let body;
try { body = JSON.parse(body_text); } catch (e) { return json({ error: "Bad JSON" }, 400); }
if (!body || typeof body !== "object" || typeof body.cards !== "object") {
return json({ error: "Not a progress file" }, 400);
}
const savedAt = Number(body.savedAt) || Date.now();
await env.PROGRESS.put(key, JSON.stringify({ data: body, savedAt }));
return json({ ok: true, savedAt });
}
return json({ error: "Method not allowed" }, 405);
}
Have an idea of your own?
Look around your day, find the thing that wastes your time, and build the fix. Everything here is free to help you start. If you would rather I built it, or you just want to talk an idea through, write to me.