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" ? `Figure` : ""; return `${modeLabel(c)}` + `${c.tier} likelihood${esc(AREA_NAMES[c.area])}` + `${esc(c.family)}${figure}`; } function figHtml(c) { return c.fig ? `Figure from the book for this problem` : ""; } // state: { picked: index|null, reveal: bool, locked: bool } function questionHtml(c, state) { let h = c.ctx ? `

Setup: ${esc(c.ctx)}

` : ""; h += `

${esc(c.q)}

${figHtml(c)}`; if (isProblem(c)) { h += `
` + 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 ``; }).join("") + `
`; } return h; } function answerHtml(c, picked) { let h = `
`; if (isProblem(c)) { const verdict = picked == null ? "" : picked === c.a ? `Correct. ` : `Not quite. `; h += `

${verdict}Answer: ${LETTERS[c.a]}) ${esc(c.c[c.a])}

`; } h += `

${esc(c.sol)}

`; if (c.note) h += `
Note: ${esc(c.note)}
`; return h + `
${srcLine(c)}
`; } 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 ? "" : ``; const activeBanner = S.active ? `` : ""; 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 ` ${a.name}
${a.weight}% of exam
${ok} of ${cs.length} learned · ${started} started${mk ? ` · mock exams ${pct(mk[0], mk[1])}%` : ""}`; }).join(""); const famRows = FAMILIES.slice(0, 10).map(f => { const cs = CARDS.filter(c => c.family === f.name); return `${esc(f.name)}${cs.length}${cs.filter(learned).length} / ${cs.length}`; }).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 `${t}0Excluded in Settings`; 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 `${t}${n}${fmt(startDay)} to ${fmt(endDay)}`; }).join(""); const last = S.mocks[S.mocks.length - 1]; const reviewDay = addDays(examDate(), -7); document.getElementById("view-home").innerHTML = ` ${activeBanner}${examBanner}
${daysLeft()}days to exam (${fmt(examDate())})
${due + news}cards for today (${due} review, ${news} new)
${CARDS.filter(learned).length} / ${CARDS.length}learned
${last ? pct(last.correct, last.n) + "%" : "-"}last mock exam${last ? " (" + fmt(last.date) + ")" : ""}

${streak()} day streak · flashcard accuracy ${accuracy()}

Exam areas

${areaRows}

Mock exams draw questions in proportion to each area's share of the exam.

Topics

${famRows}
TopicCardsLearned

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.

Schedule

Introduce about ${perDay} new cards per day from ${fmt(S.startDate)}, most likely first. Review everything during the final week, starting ${fmt(reviewDay)}. Take a full mock exam each week.

${planRows}
LikelihoodCardsTarget dates

${plan.filter(c => !seen(c)).length} planned cards not started.

Box system

${boxCounts.map((n, i) => `
Box ${i + 1}${n}every ${BOX_DAYS[i]}d
`).join("")}

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.

`; } /* ---------- 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 ``; }).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 ? `

Session complete. ${(S.log[today()] || {}).reviewed || 0} cards reviewed today.

` : `

All done for today${scope}. Come back tomorrow, switch the tab above, take a mock exam, or browse the cards.

`; 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 = `
${tags(c)}
` + 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) => ` ${fmt(m.date)}${esc(m.name)} ${pct(m.correct, m.n)}% (${m.correct}/${m.n}) ${AREAS.filter(a => m.byArea[a.id]).map(a => `${a.name.split(" ")[0]} ${pct(...m.byArea[a.id])}%`).join(" · ")} `).join(""); root.innerHTML = `

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.

Generated mock exams

${MOCKS.map(m => `

${m.name}

${m.blurb}

`).join("")}

History

${S.mocks.length ? `${hist}
DateExamScoreBy area
` : `

No mock exams yet.

`}
`; } 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 = `
${mmss(remaining())} ${esc(A.name)} · question ${A.idx + 1} of ${A.ids.length} · ${answered} answered
${esc(AREA_NAMES[c.area])}
${questionHtml(c, { picked: A.answers[c.id] ?? null, reveal: false, locked: false })}
All questions (filled = answered, orange ring = flagged)
${A.ids.map((id, i) => ``).join("")}
`; 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 `${a.name}
${a.weight}% of exam${ok}/${n}
${pct(ok, n)}%`; }).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 `
${i + 1}. ${ok ? "Correct" : a == null ? "Blank" : "Wrong"} · ${esc(AREA_NAMES[c.area])} · ${esc(c.q.slice(0, 90))}${c.q.length > 90 ? "..." : ""}
${questionHtml(c, { picked: a ?? null, reveal: true, locked: true })}${answerHtml(c, a ?? null)}
`; }).join(""); root.innerHTML = `
${esc(m.name)} · ${fmt(m.date)} · ${m.usedMin} of ${m.minutes} min${m.timedOut ? " (time ran out)" : ""}
${p}%
${m.correct} of ${m.n} correct. ${verdict}

Demo target ${PASS_HIGH}%.${weak ? " Most missed topics: " + weak + "." : ""}

${areaRows}
AreaScore
Review
${items}
`; 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 => ``).join(""); const fams = FAMILIES.map(f => ``).join(""); document.getElementById("view-browse").innerHTML = `

`; 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 `
${tags(c)}${label}
${esc(c.q)}
${questionHtml(c, { picked: null, reveal: true, locked: true })}${answerHtml(c, null)}
`; }).join("") + (rows.length > 120 ? `

Showing the first 120. Narrow the filters to see more.

` : "") || `

No cards match.

`; }; ["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 = `

Exam date

The schedule and review timing adjust to this date.

Daily new cards

Automatic: ${autoNewPerDay()} per day. Enter a number to override.

Theme

Backup

Progress and mock exam history stay in this browser only. Copy them to keep a backup, or import a saved file on another device.

About the cards

${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.

Reset

Erases all card progress and mock exam history in this browser.

`; 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 }); })();