Files
quiz/static/admin.js
ameer b40f05220c style: refinement pass for admin + student SPAs
Targeted fixes on top of the editorial-lecture-hall pass:

- Leaderboard rank columns now align across all rows; medal stripes
  reserve their 3px width on every row (no more 6px shift between
  podium and chasers). Silver bumps to higher-contrast values in both
  light and dark modes.
- Student leaderboard gains a visible "you" highlight (blue stripe,
  blue name + score, small "you" eyebrow under the name). Matches by
  display name since the server's student-facing top5 doesn't include
  student_id.
- Lobby and Finished states share an editorial state-cta treatment:
  display-serif "Ready to start." / "That's a wrap." with a numeric
  cta-stats strip that anchors the right column on a projector.
- "02 PRE-FLIGHT" eyebrow continues the "01 JOIN" sequence on the
  side panel, giving the page a magazine-spread rhythm.
- Live distribution suppresses empty bars when zero submissions and
  shows a calm italic "Bars appear once the first answer comes in."
  line instead.
- Roster orders newest-first; the top three rows light their dot
  green and the freshest row gets a soft pulsing halo, so the
  operator sees the room filling up at a glance.
- Student reveal "Your pick" tag moves to a top-edge ribbon above the
  option text so it stops colliding with the count column on phones.
2026-05-02 22:11:55 +08:00

583 lines
20 KiB
JavaScript

/* Quiz admin SPA.
*
* Single page, no router. boot() decides between login form and dashboard
* based on whether GET /admin/api/state returns 200 (authed) or 401.
*
* The dashboard is state-driven: a single primary action button per
* session state (Start / Stop early / Next / Finish / Reset). The QR
* code, join URL, and participant list are always visible on the left
* so the operator can leave the page on a projector.
*/
const app = document.querySelector("#admin-app");
const store = {
session: null, // /admin/api/state response
ws: null,
roster: [],
currentQuestion: null,
histogram: null,
totalCount: 0,
submittedCount: 0,
closedPayload: null, // last question_closed message
leaderboard: [],
endedPayload: null,
notice: null,
questionDeadlineMs: null,
};
let countdownTimer = null;
function escapeText(value) {
return String(value ?? "").replace(/[&<>"']/g, (c) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#039;",
})[c]);
}
async function api(path, options = {}) {
const headers = options.body ? { "Content-Type": "application/json", ...(options.headers || {}) } : options.headers;
const response = await fetch(path, {
credentials: "same-origin",
...options,
headers,
});
if (response.status === 401) {
const error = new Error("unauthorized");
error.status = 401;
throw error;
}
if (!response.ok) {
const error = new Error(await response.text());
error.status = response.status;
throw error;
}
const contentType = response.headers.get("content-type") || "";
return contentType.includes("json") ? response.json() : response.text();
}
async function boot() {
try {
store.session = await api("/admin/api/state");
store.notice = null;
renderDashboard();
connectWS();
} catch (err) {
if (err.status === 401) {
renderLogin();
} else if (err.status === 503) {
renderUnavailable(err.message || "Session not initialised on the server.");
} else {
renderUnavailable(err.message || "Could not load admin state.");
}
}
}
function renderUnavailable(detail) {
app.innerHTML = `
<section class="centered-shell">
<div class="card narrow">
<h1>Quiz unavailable</h1>
<p>${escapeText(detail)}</p>
<p class="muted">Verify <code>QUIZ_POOL_PATH</code> on the server points at a valid pool JSON, then restart <code>quiz.service</code>.</p>
</div>
</section>
`;
}
function renderLogin(error = null) {
app.innerHTML = `
<section class="centered-shell">
<form id="login-form" class="card narrow stack">
<header class="card-header">
<h1>Quiz admin</h1>
<p class="muted">Sign in to control the live session.</p>
</header>
<label class="field">
<span>Password</span>
<input name="password" type="password" autocomplete="current-password" required autofocus>
</label>
${error ? `<p class="alert error">${escapeText(error)}</p>` : ""}
<button class="btn primary block" type="submit">Sign in</button>
</form>
</section>
`;
document.querySelector("#login-form").addEventListener("submit", async (event) => {
event.preventDefault();
const submit = event.submitter || event.currentTarget.querySelector("button");
submit.disabled = true;
const password = new FormData(event.currentTarget).get("password");
try {
await api("/admin/login", { method: "POST", body: JSON.stringify({ password }) });
await boot();
} catch (err) {
submit.disabled = false;
renderLogin(err.status === 401 ? "Wrong password." : "Could not sign in.");
}
});
}
function renderDashboard() {
const session = store.session;
if (!session) return;
const state = store.endedPayload ? "finished" : (store.closedPayload?.state || session.state);
app.innerHTML = `
<header class="topbar">
<div class="topbar-title">
<h1>${escapeText(session.title)}</h1>
<p class="muted">${escapeText(session.pool_meta.question_count)} questions · ${escapeText(session.pool_meta.score_fn.replace(/_/g, " "))} · ${escapeText(session.pool_meta.time_limit_default)} s default</p>
</div>
<div class="topbar-actions">
<span class="state-badge state-${escapeText(state)}">${escapeText(stateLabel(state))}</span>
<button id="logout-btn" class="btn ghost">Sign out</button>
</div>
</header>
${store.notice ? `<div class="alert info">${escapeText(store.notice)}</div>` : ""}
<section class="dashboard">
<aside class="dashboard-side">
${renderJoinPanel()}
${renderRosterPanel()}
</aside>
<main class="dashboard-main">
${renderStatePanel(state)}
</main>
</section>
`;
document.querySelector("#logout-btn").addEventListener("click", logout);
bindStateActions();
if (state === "question_open") startCountdown();
}
function stateLabel(state) {
return ({
lobby: "Lobby",
question_open: "Question live",
question_closed: "Reveal",
between_questions: "Between",
finished: "Finished",
})[state] || state || "—";
}
function renderJoinPanel() {
const session = store.session;
return `
<div class="card panel join-panel">
<h2>Join</h2>
<div class="qr-wrap">${session.qr_url ? `<img class="qr" src="${session.qr_url}" alt="Join QR">` : "<div class='qr-fallback'>QR unavailable</div>"}</div>
<div class="join-url-row">
<code class="join-url">${escapeText(session.join_url)}</code>
<button id="copy-url" class="btn ghost small" type="button">Copy</button>
</div>
<p class="muted small">Session id: <code>${escapeText(session.sid)}</code></p>
</div>
`;
}
function renderRosterPanel() {
const r = store.roster || [];
// Newest-first so late joiners are visible at the top of the list. The
// first three are tagged so the CSS can warm their dot — gives the
// operator a quick "yes the room is live" cue without an explicit log.
const ordered = r.slice().reverse();
return `
<div class="card panel">
<h2>Joined <span class="count">${r.length}</span></h2>
${ordered.length
? `<ul class="roster">${ordered.map((p, i) =>
`<li class="${i < 3 ? "is-fresh" : ""}"><span class="dot"></span><span class="who"><b>${escapeText(p.name)}</b><small>${escapeText(p.student_id)}</small></span></li>`
).join("")}</ul>`
: `<p class="muted">No students have joined yet. Share the QR or URL.</p>`}
</div>
`;
}
function renderStatePanel(state) {
if (state === "lobby") return renderLobby();
if (state === "question_open") return renderQuestionOpen();
if (state === "question_closed" || state === "between_questions") return renderQuestionClosed();
if (state === "finished") return renderFinished();
return `<div class="card panel"><p class="muted">Unknown state: ${escapeText(state)}</p></div>`;
}
function renderLobby() {
const total = store.session.pool_meta.question_count;
const joined = (store.roster || []).length;
return `
<div class="card panel state-cta-card">
<div class="state-cta">
<p class="cta-eyebrow"><span class="cta-num">02</span> Pre-flight</p>
<h2>Ready to start.</h2>
<p>When you start, question&nbsp;1 of&nbsp;${total} opens for everyone in the room. Late joiners can still hop in mid-question; they get whatever time remains on the clock.</p>
<div class="cta-stats">
<div class="cta-stat"><span class="muted">Joined</span><b>${joined}</b></div>
<div class="cta-stat"><span class="muted">Questions</span><b>${total}</b></div>
<div class="cta-stat"><span class="muted">Per question</span><b>${store.session.pool_meta.time_limit_default}<small>s</small></b></div>
</div>
<button class="btn primary big" data-action="next">Start quiz →</button>
</div>
</div>
`;
}
function renderQuestionOpen() {
const q = store.currentQuestion;
if (!q) {
return `<div class="card panel"><p class="muted">Waiting for question to broadcast…</p></div>`;
}
const total = store.session.pool_meta.question_count;
const idx = q.question_idx;
return `
<div class="card panel question-card">
<div class="question-head">
<span class="qnum">Q${idx + 1} / ${total}</span>
<span id="countdown" class="countdown" data-deadline="${store.questionDeadlineMs ?? 0}">—</span>
</div>
<div class="qbar"><span id="qbar-fill"></span></div>
<h2 class="question-text">${escapeText(q.text)}</h2>
<ol class="options">
${["A","B","C","D"].map((k) =>
`<li><span class="key">${k}</span><span class="opt-text">${escapeText(q.options[k] || "")}</span></li>`
).join("")}
</ol>
${renderLiveHistogram()}
<div class="action-row">
<button class="btn warn" data-action="close">Stop early</button>
</div>
</div>
`;
}
function renderLiveHistogram() {
if (!store.histogram) return `<p class="muted small">Awaiting the first submission…</p>`;
const h = store.histogram;
const submitted = store.submittedCount || 0;
const total = Math.max(1, store.totalCount || 0);
// While nobody has submitted yet, suppress the bar rows — empty bars
// read as broken rather than "no data". Show a calm awaiting line.
if (submitted === 0) {
return `
<div class="hist live">
<div class="hist-summary">
<span><b>0</b> submitted</span>
${store.totalCount ? `<span class="muted">of ${store.totalCount} joined</span>` : ""}
</div>
<p class="muted small hist-awaiting">Bars appear once the first answer comes in.</p>
</div>
`;
}
return `
<div class="hist live">
<div class="hist-summary">
<span><b>${submitted}</b> submitted</span>
${store.totalCount ? `<span class="muted">of ${store.totalCount} joined</span>` : ""}
${h.pending != null && h.pending > 0 ? `<span class="muted">${h.pending} pending</span>` : ""}
</div>
<div class="hist-rows">
${["A","B","C","D"].map((k) => {
const v = h[k] || 0;
const pct = Math.round(100 * v / total);
return `
<div class="hist-row">
<span class="key">${k}</span>
<div class="bar"><span class="fill" style="width:${pct}%"></span></div>
<span class="num">${v}</span>
</div>
`;
}).join("")}
</div>
</div>
`;
}
function renderQuestionClosed() {
const c = store.closedPayload;
const q = store.currentQuestion;
if (!c || !q) {
return `<div class="card panel"><p class="muted">Reveal pending…</p></div>`;
}
const total = store.session.pool_meta.question_count;
const idx = q.question_idx;
const isLast = idx >= total - 1;
const totalSubmitters = ["A","B","C","D"].reduce((a, k) => a + (c.histogram[k] || 0), 0) + (c.histogram.missed || 0);
const denom = Math.max(1, totalSubmitters);
return `
<div class="card panel reveal-card">
<div class="question-head">
<span class="qnum">Q${idx + 1} / ${total}</span>
<span class="state-badge state-question_closed">Closed</span>
</div>
<h2 class="question-text">${escapeText(q.text)}</h2>
<ol class="options reveal">
${["A","B","C","D"].map((k) => {
const correct = k === c.correct;
return `
<li class="${correct ? "correct" : ""}">
<span class="key">${k}${correct ? " ✓" : ""}</span>
<span class="opt-text">${escapeText(q.options[k] || "")}</span>
<span class="opt-count muted">${c.histogram[k] || 0}</span>
</li>
`;
}).join("")}
</ol>
${c.explanation ? `<p class="explanation">${escapeText(c.explanation)}</p>` : ""}
<div class="hist final">
<div class="hist-rows">
${["A","B","C","D"].map((k) => {
const v = c.histogram[k] || 0;
const pct = Math.round(100 * v / denom);
const correct = k === c.correct;
return `
<div class="hist-row ${correct ? "is-correct" : ""}">
<span class="key">${k}</span>
<div class="bar"><span class="fill" style="width:${pct}%"></span></div>
<span class="num">${v} (${pct}%)</span>
</div>
`;
}).join("")}
${c.histogram.missed ? `<div class="hist-row missed"><span class="key">—</span><div class="bar"></div><span class="num">${c.histogram.missed} missed</span></div>` : ""}
</div>
</div>
<h3>Top so far</h3>
${renderLeaderboardList(store.leaderboard.slice(0, 10))}
<div class="action-row">
<button class="btn primary big" data-action="next">${isLast ? "Finish quiz →" : "Next question →"}</button>
<button class="btn ghost" data-action="end">Finish now</button>
</div>
</div>
`;
}
function renderFinished() {
const total = store.session.pool_meta.question_count;
return `
<div class="card panel">
<div class="state-cta">
<h2>That's a wrap.</h2>
<p>${total} question${total === 1 ? "" : "s"} complete. Final standings below; download the CSV when you're ready to grade.</p>
</div>
<h3>Final leaderboard</h3>
${renderLeaderboardList(store.leaderboard)}
<div class="action-row">
<a class="btn ghost" href="/admin/api/csv" target="_blank" rel="noopener">Download CSV</a>
<button class="btn warn" data-action="reset">Reset session</button>
</div>
<p class="muted small">Reset clears all submissions and the participant list, then returns to the lobby. The QR / join URL stays the same.</p>
</div>
`;
}
function renderLeaderboardList(rows) {
if (!rows || !rows.length) return `<p class="muted">No scores yet.</p>`;
return `
<ol class="leaderboard">
${rows.map((r) => `
<li>
<span class="rank">${r.rank}</span>
<span class="who"><b>${escapeText(r.name)}</b>${r.student_id ? `<small>${escapeText(r.student_id)}</small>` : ""}</span>
<span class="score">${r.score}</span>
</li>
`).join("")}
</ol>
`;
}
function bindStateActions() {
document.querySelectorAll("[data-action]").forEach((btn) => {
btn.addEventListener("click", () => onAction(btn.dataset.action, btn));
});
const copy = document.querySelector("#copy-url");
if (copy) copy.addEventListener("click", copyJoinUrl);
}
async function onAction(action, btn) {
if (action === "reset") {
if (!confirm("Reset clears all participants and submissions. Continue?")) return;
btn.disabled = true;
try {
await api("/admin/api/reset", { method: "POST" });
// Server pushes a state=lobby broadcast over WS; rerender once the
// message lands, plus optimistically clear local accumulators.
store.roster = [];
store.histogram = null;
store.currentQuestion = null;
store.closedPayload = null;
store.endedPayload = null;
store.leaderboard = [];
store.session.state = "lobby";
store.session.current_question_idx = null;
renderDashboard();
} catch (err) {
alert(err.message || "Reset failed.");
btn.disabled = false;
}
return;
}
if (!store.ws || store.ws.readyState !== WebSocket.OPEN) {
store.notice = "Reconnecting to live channel…";
renderDashboard();
connectWS();
return;
}
const msg = ({
next: { type: "next" },
close: { type: "close_question" },
end: { type: "end_session" },
})[action];
if (msg) {
btn.disabled = true;
store.ws.send(JSON.stringify(msg));
}
}
async function logout() {
try {
await api("/admin/logout", { method: "POST" });
} catch {}
if (store.ws) store.ws.close();
store.ws = null;
store.session = null;
renderLogin();
}
function copyJoinUrl() {
const url = store.session?.join_url;
if (!url) return;
navigator.clipboard.writeText(url).then(() => {
const btn = document.querySelector("#copy-url");
if (!btn) return;
const original = btn.textContent;
btn.textContent = "Copied!";
setTimeout(() => { btn.textContent = original; }, 1500);
});
}
function connectWS() {
if (store.ws) {
try { store.ws.close(); } catch {}
}
const sid = store.session.sid;
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const ws = new WebSocket(`${protocol}://${window.location.host}/ws/instructor/${sid}`);
store.ws = ws;
ws.addEventListener("message", (event) => {
try { handleWSMessage(JSON.parse(event.data)); } catch (e) { console.warn("bad ws msg", e); }
});
ws.addEventListener("close", () => {
store.notice = "Live connection dropped. Trying to reconnect…";
renderDashboard();
setTimeout(() => { if (store.session) connectWS(); }, 2000);
});
ws.addEventListener("open", () => {
if (store.notice && store.notice.startsWith("Live connection")) {
store.notice = null;
renderDashboard();
}
});
}
function handleWSMessage(message) {
switch (message.type) {
case "state":
store.session.state = message.state;
store.session.current_question_idx = message.current_question_idx;
if (message.state === "lobby") {
store.currentQuestion = null;
store.closedPayload = null;
store.endedPayload = null;
store.histogram = null;
}
renderDashboard();
break;
case "lobby_update":
store.roster = message.participants || [];
renderDashboard();
break;
case "question_open":
store.session.state = "question_open";
store.session.current_question_idx = message.question_idx;
store.currentQuestion = message;
store.closedPayload = null;
store.histogram = null;
store.submittedCount = 0;
store.totalCount = 0;
store.questionDeadlineMs = Date.now() + (message.remaining_ms ?? message.time_limit * 1000);
renderDashboard();
break;
case "live_histogram":
store.histogram = message.histogram;
store.submittedCount = message.submitted_count;
store.totalCount = message.total_count;
patchHistogramOnly();
break;
case "question_closed":
store.session.state = "question_closed";
store.closedPayload = message;
store.histogram = message.histogram;
stopCountdown();
renderDashboard();
break;
case "between_questions":
// Not currently emitted by the new advance_to_next; safe to ignore.
break;
case "full_leaderboard":
store.leaderboard = message.leaderboard || [];
renderDashboard();
break;
case "session_ended":
store.session.state = "finished";
store.endedPayload = message;
stopCountdown();
renderDashboard();
break;
case "error":
store.notice = `Server error: ${message.message || message.code || "unknown"}`;
renderDashboard();
break;
}
}
function patchHistogramOnly() {
// Update histogram without re-rendering the entire dashboard, so the
// countdown bar doesn't flicker.
const target = document.querySelector(".question-card");
if (!target) { renderDashboard(); return; }
const live = target.querySelector(".hist.live");
const replacement = renderLiveHistogram();
if (live) {
const wrap = document.createElement("div");
wrap.innerHTML = replacement;
live.replaceWith(wrap.firstElementChild);
} else {
// No histogram yet; do a full render.
renderDashboard();
}
}
function startCountdown() {
stopCountdown();
countdownTimer = setInterval(tickCountdown, 250);
tickCountdown();
}
function stopCountdown() {
if (countdownTimer) clearInterval(countdownTimer);
countdownTimer = null;
}
function tickCountdown() {
const el = document.querySelector("#countdown");
const fill = document.querySelector("#qbar-fill");
if (!el || !fill || !store.questionDeadlineMs) return;
const remaining = Math.max(0, store.questionDeadlineMs - Date.now());
const limit = (store.currentQuestion?.time_limit ?? 60) * 1000;
el.textContent = `${Math.ceil(remaining / 1000)}s`;
el.classList.toggle("urgent", remaining > 0 && remaining <= 10000);
fill.style.width = `${Math.max(0, Math.min(100, remaining / limit * 100))}%`;
if (remaining <= 0) stopCountdown();
}
boot();