mathly / mathly2 /static /quiz.js
wzender's picture
Written simulation: no choices, the way on the board, checked by the AI (#14)
423224a unverified
Raw History Blame Contribute Delete
24.5 kB
// A lesson quiz, an exercise test or the simulation: multiple-choice questions (only the simulation is on a server timer), as a dialog over the path (the same sheet as the exercise screen).
// A tap saves the choice on the server; nothing says whether it is right. After the submit (or when time ends) the result shows the
// grade, the skills that lost points and the mistakes' names and tips, never the right answers.
import { api, ApiError } from "./api.js";
import { loadBoard } from "./exercise.js";
import { figures } from "./figures.js";
import { esc, fmt } from "./math.js";
import { pathHref, shuffled } from "./ui.js";
import { hasWork, sendWork } from "./boardwork.js";
import { stepsHtml } from "./reviewsteps.js";
const LIVE_AT = new Set([300, 60, 10, 0]); // seconds left at which the timer is announced to a screen reader
let layer = null, attempt = null, at = 0, timer = null, deadline = 0, orders = {}, warned = false;
const q = selector => layer?.querySelector(selector);
export const isOpen = () => !!layer;
const clock = secs => `${String(Math.floor(secs / 60)).padStart(2, "0")}:${String(secs % 60).padStart(2, "0")}`;
function stopTimer() { clearInterval(timer); timer = null; }
/** Open the sheet for an attempt that the server already has (`#/quiz/<lesson>/<attempt>`). */
export async function open(attemptId) {
const [data] = await Promise.all([api(`/api/attempts/${encodeURIComponent(attemptId)}`), loadBoard()]);
show(data);
}
/** The student opened a lesson's quiz: the server resumes the open attempt or draws a new one; the address then names the attempt. */
export async function start(lessonId) {
const data = await api(`/api/lessons/${encodeURIComponent(lessonId)}/quiz/start`, { method: "POST" });
location.replace(`#/quiz/${encodeURIComponent(lessonId)}/${encodeURIComponent(data.id)}`);
}
/** An exercise test (1 or 2) of a real test, or its simulation: the same, with the attempt's id put in the address.
* `allSkills` (address `#/exam/<test>/<n>/all`) also draws the skills not started yet. */
export async function startExam(testId, number, allSkills = false) {
const data = await api(`/api/tests/${encodeURIComponent(testId)}/exercise/${encodeURIComponent(number)}/start${allSkills ? "?all_skills=true" : ""}`, { method: "POST" });
location.replace(`#/exam/${encodeURIComponent(testId)}/${encodeURIComponent(number)}/${encodeURIComponent(data.id)}`);
}
/** A simulation on request (an open one resumes). `allSkills` is kept for old addresses (`#/sim/<test>/all`). */
export async function startSimulation(testId, allSkills = false) {
const data = await api(`/api/tests/${encodeURIComponent(testId)}/simulation/start${allSkills ? "?all_skills=true" : ""}`, { method: "POST" });
location.replace(`#/sim/${encodeURIComponent(testId)}/${encodeURIComponent(data.id)}`);
}
/** What the sheet is called, who it is about and where closing it leads, by kind. */
const FOCUS = 3; // the practice test on the hard skills
const names = a => a.kind === "exercise_test" ? { title: a.test.title || "ืžื‘ื—ืŸ ืชืจื’ื•ืœ", again: "" } // a test: the readiness block offers the next one
: a.kind === "simulation" ? { title: "ืžื‘ื—ืŸ ืกื™ืžื•ืœืฆื™ื”", again: "" } : { title: "ื‘ื•ื—ืŸ", again: "ื‘ื•ื—ืŸ ื—ื•ื–ืจ" };
/** What the test did to the readiness number: the gain big, the bar growing from before to after, a new level, the next one, and the
* two ways to go on raising it. */
function readinessHtml(r) {
const x = r.readiness;
if (!x) return "";
const test = r.test.id;
return `<section class="qz-ready${x.gain ? " up" : ""}" id="qz-ready" data-gain="${x.gain}">
${x.gain ? `<p class="qz-gain" aria-hidden="true">+${x.gain}</p><p><b>ื”ืžื•ื›ื ื•ืช ืœืžื‘ื—ืŸ ืขืœืชื” ืœึพ${x.after}!</b></p>`
: `<p><b>ื”ืžื•ื›ื ื•ืช ื ืฉืืจื” ${x.after}.</b> <span class="muted">ืฆื™ื•ืŸ ืžืขืœ ${x.after} ื™ืขืœื” ืื•ืชื”.</span></p>`}
${x.level_up ? `<p class="qz-level">๐ŸŽ‰ ืจืžื” ื—ื“ืฉื”: ${esc(x.label)}!</p>` : ""}
<div class="bar rd-bar" role="progressbar" aria-label="ืžื•ื›ื ื•ืช ${x.after} ืžืชื•ืš 100" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${x.after}"><i style="width:${x.before}%" data-to="${x.after}"></i></div>
<p class="muted">${x.next ? `ืขื•ื“ ${x.next.left} ืœืจืžื” "${esc(x.next.name)}"` : "ื”ืจืžื” ื”ื’ื‘ื•ื”ื” ื‘ื™ื•ืชืจ! ๐Ÿ†"}</p>
<p class="qz-more"><a class="button primary" id="qz-more-sim" href="#/sim/${test}">โฑ ืขื•ื“ ืกื™ืžื•ืœืฆื™ื”</a> <a class="button" id="qz-more-practice" href="#/test/${test}/practice">๐Ÿ“ ืžื‘ื—ืŸ ืชืจื’ื•ืœ</a></p></section>`;
}
const chip = a => a.kind === "quiz" ? fmt(a.lesson.name) : a.test.lessons.map(fmt).join(", ");
const leaveTo = () => !attempt || attempt.kind === "quiz" ? pathHref() : `#/test/${attempt.test.id}`;
function ensureLayer() {
if (!layer) {
layer = document.createElement("div");
layer.className = "mx-layer";
document.body.append(layer);
layer.addEventListener("click", onClick);
}
layer.innerHTML = `<div class="mx-scrim" data-close></div><div class="mx-sheet" role="dialog" aria-modal="true" aria-labelledby="qz-title"></div>`;
}
function show(data) {
stopTimer();
if (!attempt || attempt.id !== data.id) at = 0; // a different attempt starts at its first question
attempt = data;
warned = false;
ensureLayer();
if (data.state === "open") {
if (!(data.id in orders)) orders = { [data.id]: {} };
at = Math.min(at, data.questions.length - 1);
deadline = data.due_at ? performance.now() + Math.max(0, new Date(data.due_at) - new Date(data.now)) : 0; // the server's clock, not the device's
renderQuestion();
if (data.due_at) { timer = setInterval(tick, 1000); tick(); }
} else {
renderResult();
}
q(".mx-x")?.focus({ preventScroll: true });
}
export function close() {
if (!layer) return;
stopTimer();
window.MathlyBoard?.closeFull?.();
layer.remove();
layer = attempt = null;
at = 0;
}
const left = () => Math.max(0, Math.ceil((deadline - performance.now()) / 1000));
async function tick() {
if (!layer || attempt?.state !== "open" || !attempt.due_at) return;
const secs = left();
const label = q("#qz-timer");
if (label) label.textContent = clock(secs);
if (LIVE_AT.has(secs) && q("#qz-live")) q("#qz-live").textContent = secs === 0 ? "ื”ื–ืžืŸ ื ื’ืžืจ" : `ื ืฉืืจื• ${secs >= 60 ? `${secs / 60} ื“ืงื•ืช` : `${secs} ืฉื ื™ื•ืช`}`;
if (secs === 0) {
stopTimer();
await finish(false);
}
}
/** Ask the server for the attempt: past the deadline it has been settled already, before it a submit settles it. */
async function finish(submit) {
const id = attempt.id;
try {
if (submit) { await saving; await sendAllWork(); } // the boards go with the hand-in
else if (attempt.written && attempt.state === "open") await sendAllWork(); // time ran out: the boards still go, before the check starts
const data = submit ? await api(`/api/attempts/${id}/submit`, { method: "POST" }) : await api(`/api/attempts/${id}`);
if (data.state === "open") { setTimeout(() => layer && finish(false), 1000); return; } // a hair early on the device: ask again
show(data);
} catch (error) {
if (q("#qz-fb")) q("#qz-fb").innerHTML = `<p class="error" role="alert">${esc(error.message || "ืžืฉื”ื• ื”ืฉืชื‘ืฉ")}</p>`;
}
}
const heading = (title) => `<div class="mx-shtop"><div><span class="ex-chip">${chip(attempt)}</span><h3 id="qz-title">${title}</h3></div>
<div class="mx-shacts">${attempt.state === "open" ? (window.MathlyBoard?.button() || "") : ""}
<button type="button" class="mx-x" data-close aria-label="ืกื’ื™ืจื”">โœ•</button></div></div>`;
function choicesOf(question) {
const order = (orders[attempt.id] ||= {});
order[question.key] ||= shuffled(question.choices).map(c => c.index);
return order[question.key].map(i => question.choices.find(c => c.index === i));
}
/** Is a question answered: a choice, or in the written simulation a board with work or a typed final answer. */
const isAnswered = x => attempt.answers[x.key] !== undefined || (attempt.written && hasWork(boardKey(x.key)));
/** The written simulation's answer area: the way goes on the board; a plain-number answer also has a box. */
function writtenHtml(question) {
const typed = typeof attempt.answers[question.key] === "string" ? attempt.answers[question.key] : "";
const box = question.final ? `<p class="qz-final"><label for="qz-final">ื”ืชืฉื•ื‘ื” ื”ืกื•ืคื™ืช:</label>
<span class="qz-final-row" dir="ltr">${question.final.label ? `<span>${esc(question.final.label)}</span>` : ""}<input id="qz-final" inputmode="decimal" autocomplete="off"
maxlength="40" value="${esc(typed)}" aria-describedby="qz-written-note">${question.final.unit ? `<span>${esc(question.final.unit)}</span>` : ""}</span></p>` : "";
return `<div class="qz-written" id="qz-written"><p class="muted" id="qz-written-note">โœ๏ธ ื›ืžื• ื‘ืžื‘ื—ืŸ ืืžื™ืชื™: ื›ื•ืชื‘ื™ื ืืช ื”ืคืชืจื•ืŸ ื”ืžืœื ื‘ืœื•ื—. ื”ื‘ื•ื“ืง ืจื•ืื” ืืช ื”ื“ืจืš, ืœื ืจืง ืืช ื”ืชืฉื•ื‘ื”.</p>
<p><button type="button" id="qz-open-board" class="primary">ืคืชื™ื—ืช ื”ืœื•ื—</button></p>${box}</div>`;
}
function renderQuestion() {
const total = attempt.questions.length, question = attempt.questions[at], saved = attempt.answers[question.key];
const answered = attempt.questions.filter(isAnswered).length;
q(".mx-sheet").innerHTML = `${heading(names(attempt).title)}
<div class="qz-bar">${attempt.due_at ? `<span class="qz-timer" id="qz-timer" aria-label="ื”ื–ืžืŸ ืฉื ืฉืืจ">${clock(left())}</span>` : ""}
<span id="qz-count">ืฉืืœื” ${at + 1} ืžืชื•ืš ${total}</span></div>
<span class="mx-sr" id="qz-live" role="status" aria-live="polite"></span>
<div class="qz-dots" role="group" aria-label="ื ืขื ื• ${answered} ืžืชื•ืš ${total}">${attempt.questions.map((x, i) =>
`<button type="button" class="qz-dot${isAnswered(x) ? " done" : ""}${i === at ? " cur" : ""}" data-go="${i}" aria-label="ืฉืืœื” ${i + 1}${isAnswered(x) ? ", ื ืขื ืชื”" : ", ืœื ื ืขื ืชื”"}"${i === at ? ' aria-current="step"' : ""}></button>`).join("")}</div>
<div class="mx-q" id="qz-q" data-key="${esc(question.key)}"><p class="ex-text" dir="auto">${fmt(question.question)}</p>${figures(question)}
${attempt.written ? writtenHtml(question) : `<div class="ex-choices" id="qz-choices">${choicesOf(question).map(c =>
`<button type="button" class="ex-choice qz-choice${saved === c.index ? " picked" : ""}" data-i="${c.index}" aria-pressed="${saved === c.index}" dir="auto">${fmt(c.text)}</button>`).join("")}</div>`}
<div id="qz-fb" role="status" aria-live="polite"></div></div>
<div class="qz-nav"><button type="button" data-go="${at - 1}"${at === 0 ? " disabled" : ""}>ื”ืงื•ื“ืžืช</button>
<button type="button" data-go="${at + 1}"${at === total - 1 ? " disabled" : ""}>ื”ื‘ืื”</button>
<button type="button" class="primary" id="qz-submit">ื”ื’ืฉื”</button></div>
<div id="qz-warn"></div>`;
window.MathlyBoard?.mount(layer, `quiz:${attempt.id}:${question.key}`, { question: () => q("#qz-q") });
}
let saving = Promise.resolve(); // the answer saves still on their way to the server
const boardKey = key => `quiz:${attempt.id}:${key}`;
/** In a quiz or a test the way counts: a choice needs something written on the board for this question (or a board already saved). */
function needsWork(question) {
if (!attempt.work_required || hasWork(boardKey(question.key)) || (attempt.work || []).includes(question.key)) return false;
q("#qz-fb").innerHTML = `<div class="ex-note qz-need-work" id="qz-need-work" role="alert"><p><b>โœ๏ธ ืงื•ื“ื ื›ื•ืชื‘ื™ื ืืช ื”ื“ืจืš ื‘ืœื•ื—</b></p>
<p>ื”ืžื•ืจื” ื‘ื•ื“ืง ื’ื ืืช ื”ื“ืจืš, ืœื ืจืง ืืช ื”ืชืฉื•ื‘ื”. ืคืชืจื• ื‘ืœื•ื— ื•ืื– ื‘ื—ืจื• ืชืฉื•ื‘ื”.</p>
<p><button type="button" class="primary" id="qz-open-board">ืคืชื™ื—ืช ื”ืœื•ื—</button></p></div>`;
return true;
}
/** Send the board of every answered question that changed since it was last sent (before handing in). */
function sendAllWork() {
const id = attempt.id;
return Promise.allSettled(attempt.questions.filter(x => attempt.answers[x.key] !== undefined || (attempt.written && hasWork(boardKey(x.key))))
.map(x => sendWork(`quiz:${id}:${x.key}`, id, x.key).then(ok => { if (ok && attempt?.id === id) (attempt.work ||= []).push(x.key); })));
}
/** The written simulation: keep this question's typed final answer (or "" when only its board has work) on the server, then its board. */
function saveWritten(question) {
if (!attempt?.written || !question) return Promise.resolve();
const box = q("#qz-final"), typed = box && q("#qz-q")?.dataset.key === question.key ? box.value.trim() : (attempt.answers[question.key] || "");
if (!typed && !hasWork(boardKey(question.key)) && attempt.answers[question.key] === undefined) return Promise.resolve();
if (attempt.answers[question.key] === typed && !hasWork(boardKey(question.key))) return Promise.resolve();
attempt.answers[question.key] = typed;
const id = attempt.id, save = saving.then(() => api(`/api/attempts/${id}/answers`, { method: "PUT", body: { key: question.key, final: typed } }));
saving = save.catch(() => {});
return save.then(() => sendWork(boardKey(question.key), id, question.key).then(ok => { if (ok && attempt?.id === id) (attempt.work ||= []).push(question.key); }).catch(() => {}))
.catch(error => {
if (error instanceof ApiError && error.status === 409) return finish(false);
if (q("#qz-fb")) q("#qz-fb").innerHTML = `<p class="error" role="alert">${esc(error.message || "ื”ืชืฉื•ื‘ื” ืœื ื ืฉืžืจื”, ื ืกื• ืฉื•ื‘")}</p>`;
});
}
async function choose(button) {
const question = attempt.questions[at], index = Number(button.dataset.i), before = attempt.answers[question.key];
if (needsWork(question)) return;
attempt.answers[question.key] = index;
layer.querySelectorAll(".qz-choice").forEach(b => { const on = Number(b.dataset.i) === index; b.classList.toggle("picked", on); b.setAttribute("aria-pressed", String(on)); });
q(`.qz-dot[data-go="${at}"]`)?.classList.add("done");
const id = attempt.id, save = saving.then(() => api(`/api/attempts/${id}/answers`, { method: "PUT", body: { key: question.key, choice: index } }));
saving = save.catch(() => {}); // one save at a time, and a submit waits for the last one (else it is graded without it)
try {
await save;
sendWork(boardKey(question.key), id, question.key).then(ok => { if (ok && attempt?.id === id) (attempt.work ||= []).push(question.key); }).catch(() => {});
} catch (error) {
if (error instanceof ApiError && error.status === 409) return finish(false); // time ran out: the server already submitted
if (before === undefined) delete attempt.answers[question.key]; else attempt.answers[question.key] = before;
renderQuestion();
q("#qz-fb").innerHTML = `<p class="error" role="alert">${esc(error.message || "ื”ืชืฉื•ื‘ื” ืœื ื ืฉืžืจื”, ื ืกื• ืฉื•ื‘")}</p>`;
}
}
async function submit() {
await saveWritten(attempt.questions[at]);
const missing = attempt.questions.filter(x => !isAnswered(x)).length;
if (missing && !warned) {
warned = true;
q("#qz-warn").innerHTML = `<div class="ex-note" role="alert"><p>ื™ืฉ ${missing} ${missing === 1 ? "ืฉืืœื”" : "ืฉืืœื•ืช"} ื‘ืœื™ ืชืฉื•ื‘ื”. ื”ืŸ ื™ื™ื—ืฉื‘ื• ืฉื’ื•ื™ื•ืช.</p>
<p><button type="button" class="primary" id="qz-yes">ื”ื’ืฉื” ื‘ื›ืœ ื–ืืช</button> <button type="button" id="qz-back">ื—ื–ืจื” ืœื‘ื•ื—ืŸ</button></p></div>`;
q("#qz-back").focus();
return;
}
finish(true);
}
const VERDICT = { correct: ["โœ“", "ื“ืจืš ื ื›ื•ื ื”"], partial: ["โ—", "ื—ืœืง ืžื”ื“ืจืš ื ื›ื•ืŸ"], wrong: ["โœ—", "ื”ื“ืจืš ืœื ื ื›ื•ื ื”"], unclear: ["?", "ืœื ื”ืฆืœื—ื ื• ืœืงืจื•ื"] };
/** The AI's review of the way (a practice test, the simulation): waiting, failed, or per question with a board its verdict, feedback and tip. */
function reviewRows(r, questions) {
const rows = (r.keys || []).map((key, i) => [i + 1, questions?.[key]]).filter(([, q]) => q);
return rows.length ? `<ol class="plain qz-review-list">${rows.map(([n, q]) => `<li class="v-${esc(q.verdict)}" data-n="${n}"><p><b>ืฉืืœื” ${n}</b>
<span class="tag"><span aria-hidden="true">${VERDICT[q.verdict][0]}</span> ${VERDICT[q.verdict][1]}</span></p>
<p>${fmt(q.feedback)}</p>${q.tip ? `<p class="muted">๐Ÿ’ก ${fmt(q.tip)}</p>` : ""}</li>`).join("")}</ol>` : "";
}
function reviewHtml(r) {
const review = r.review;
if (!review) return "";
if (review.state === "pending") return `<section class="qz-review" id="qz-review" data-state="pending"><h4>ืžืฉื•ื‘ ืขืœ ื”ื“ืจืš</h4>
<p class="muted">ื”ึพAI ืขื•ื‘ืจ ืขืœ ื”ื“ืจืš ืฉื›ืชื‘ืชื ื‘ืœื•ื—, ืฉืืœื” ืื—ืจื™ ืฉืืœื”. ืืคืฉืจ ืœื”ืžืฉื™ืš ืœืงืจื•ื ืืช ื”ืชื•ืฆืื”, ื”ืžืฉื•ื‘ ื™ื•ืคื™ืข ื›ืืŸ.</p>${stepsHtml(review)}
${reviewRows(r, review.questions)}</section>`;
if (review.state === "failed") return `<section class="qz-review" id="qz-review" data-state="failed"><h4>ืžืฉื•ื‘ ืขืœ ื”ื“ืจืš</h4><p class="muted">ืœื ื”ืฆืœื—ื ื• ืœื‘ื“ื•ืง ืืช ื”ื“ืจืš ื”ืคืขื. ื”ืžื•ืจื” ื™ืจืื• ืืช ื”ืœื•ื—ื•ืช.</p></section>`;
const rows = reviewRows(r, review.questions);
return `<section class="qz-review" id="qz-review" data-state="done"><h4>ืžืฉื•ื‘ ืขืœ ื”ื“ืจืš</h4>
${review.summary ? `<p class="qz-review-sum">${fmt(review.summary)}</p>` : ""}
${rows || `<p class="muted">ืœื ื ืฉืžืจื” ื“ืจืš ื‘ืœื•ื— ื‘ืืฃ ืฉืืœื”.</p>`}
<p class="muted qz-review-note">ืžืฉื•ื‘ ืื•ื˜ื•ืžื˜ื™. ื”ืžื•ืจื” ื‘ื•ื“ืงื™ื ืืช ื”ื“ืจืš ื•ื ื•ืชื ื™ื ืืช ื”ื ืงื•ื“ื•ืช.</p></section>`;
}
/** While the review is being written, ask again every few seconds and redraw only its section. */
function waitForReview(id) {
setTimeout(async () => {
if (!layer || attempt?.id !== id || attempt.review?.state !== "pending") return;
try {
const fresh = await api(`/api/attempts/${encodeURIComponent(id)}`);
if (!layer || attempt?.id !== id) return;
if (attempt.checking && !fresh.checking) { show(fresh); return; } // the check ended: the grade and the rest of the result
attempt.review = fresh.review;
if (attempt.checking && fresh.review?.state !== "pending") { show(fresh); return; } // it failed: waiting for the teacher
q("#qz-review")?.replaceWith(Object.assign(document.createElement("div"), { innerHTML: reviewHtml(fresh) }).firstElementChild || "");
} catch { /* try again */ }
waitForReview(id);
}, 4000);
}
/** The written simulation before its check: no grade yet, what is happening, and the check's steps. */
function checkingHtml(r) {
const aiOn = r.review && r.review.state !== "failed";
return `${heading(`ืชื•ืฆืืช ${names(r).title}`)}
<div class="qz-result qz-checking" id="qz-checking"><p class="qz-grade" aria-label="ื”ืžื‘ื—ืŸ ื‘ื‘ื“ื™ืงื”"><b aria-hidden="true">โณ</b><span>ื‘ื‘ื“ื™ืงื”</span></p>
<p>${aiOn ? "ื”ึพAI ื‘ื•ื“ืง ืืช ื”ืคืชืจื•ื ื•ืช ืฉื›ืชื‘ืชื ื‘ืœื•ื—, ืฉืืœื” ืื—ืจื™ ืฉืืœื”. ื”ืฆื™ื•ืŸ ื™ื•ืคื™ืข ื›ืืŸ ื‘ืกื•ืฃ ื”ื‘ื“ื™ืงื”, ืืคืฉืจ ืœืกื’ื•ืจ ื•ืœื—ื–ื•ืจ."
: "ื”ืžื‘ื—ืŸ ื”ื•ื’ืฉ ื•ืžืžืชื™ืŸ ืœื‘ื“ื™ืงืช ื”ืžื•ืจื”. ื”ืฆื™ื•ืŸ ื™ื•ืคื™ืข ืื—ืจื™ ื”ื‘ื“ื™ืงื”."}${r.timed_out ? " ื”ื–ืžืŸ ื ื’ืžืจ ื•ื”ืžื‘ื—ืŸ ื”ื•ื’ืฉ ื›ืžื• ืฉื”ื•ื." : ""}</p></div>
${reviewHtml(r)}
<p class="qz-actions"><button type="button" data-close>ื—ื–ืจื” ืœืžื‘ื—ืŸ</button></p>`;
}
const missedLine = (r, m) => !r.written ? (m.picked ? `<p class="muted">ื‘ื—ืจืชื: <span dir="auto">${fmt(m.picked)}</span></p>` : `<p class="muted">ืœื ืขื ื• ืขืœ ื”ืฉืืœื”.</p>`)
: `${m.no_work ? `<p class="muted">ืœื ื ื›ืชื‘ ืคืชืจื•ืŸ ื‘ืœื•ื—.</p>` : `<p class="muted">${m.points === 0.5 ? "ื—ืฆื™ ืžื”ื ืงื•ื“ื•ืช ืขืœ ื”ืฉืืœื”." : "ืœื ืงื™ื‘ืœืชื ื ืงื•ื“ื•ืช ืขืœ ื”ืฉืืœื”."}</p>`}
${m.picked ? `<p class="muted">ื”ืชืฉื•ื‘ื” ื”ืกื•ืคื™ืช ืฉื›ืชื‘ืชื: <span dir="ltr">${esc(m.picked)}</span></p>` : ""}`;
function renderResult() {
const r = attempt;
stopTimer();
if (r.checking) {
q(".mx-sheet").innerHTML = checkingHtml(r);
if (r.review?.state === "pending") waitForReview(r.id);
return;
}
q(".mx-sheet").innerHTML = `${heading(`ืชื•ืฆืืช ${names(r).title}`)}
<div class="qz-result"><p class="qz-grade" id="qz-grade" aria-label="ื”ืฆื™ื•ืŸ ${r.grade}"><b>${r.grade}</b><span>ืžืชื•ืš 100</span></p>
<p>${r.written ? `${r.right === 1 ? "ืฉืืœื” ืื—ืช" : `${r.right} ืฉืืœื•ืช`} ืขื ื ื™ืงื•ื“ ืžืœื` : r.right === 1 ? "ืชืฉื•ื‘ื” ื ื›ื•ื ื” ืื—ืช" : `${r.right} ืชืฉื•ื‘ื•ืช ื ื›ื•ื ื•ืช`} ืžืชื•ืš ${r.total}${r.timed_out ? ". ื”ื–ืžืŸ ื ื’ืžืจ ื•ื”ื‘ื•ื—ืŸ ื”ื•ื’ืฉ ื›ืžื• ืฉื”ื•ื." : ""}</p>
<p class="muted" id="qz-best"></p></div>
${readinessHtml(r)}
${r.lost_skills.length ? `<h4>ืื™ืคื” ืืคืฉืจ ืœื”ืฉืชืคืจ</h4><ul class="plain" id="qz-lost">${r.lost_skills.map(s =>
`<li><a href="#/skill/${esc(s.id)}">${fmt(s.name)}</a><span class="muted">${s.missed} ${s.missed === 1 ? "ืฉืืœื” ืฉื’ื•ื™ื”" : "ืฉืืœื•ืช ืฉื’ื•ื™ื•ืช"}</span></li>`).join("")}</ul>
<p class="muted">ืืคืฉืจ ืœืชืจื’ืœ ืืช ื”ืžื™ื•ืžื ื•ืช ื•ืื– ืœื ืกื•ืช ืฉื•ื‘.</p>
${r.kind !== "quiz" && r.test.number !== FOCUS ? `<p><a class="button" id="qz-focus" href="#/exam/${esc(r.test.id)}/${FOCUS}">๐ŸŽฏ ืžื‘ื—ืŸ ืชืจื’ื•ืœ ืžืžื•ืงื“ ืขืœ ืžื” ืฉื”ื™ื” ืงืฉื” (15 ืฉืืœื•ืช)</a></p>` : ""}` : `<p id="qz-perfect">ื›ืœ ื”ืชืฉื•ื‘ื•ืช ื ื›ื•ื ื•ืช. ื›ืœ ื”ื›ื‘ื•ื“!</p>`}
${r.missed.length ? `<h4>ื”ื˜ืขื•ื™ื•ืช</h4><ol class="qz-missed" id="qz-missed">${r.missed.map(m => `<li><p class="ex-text" dir="auto">${fmt(m.question)}</p>
${missedLine(r, m)}
${m.mistake ? `<p><b>${esc(m.mistake.name)}</b>${m.mistake.tip ? `<br>${fmt(m.mistake.tip)}` : ""}</p>` : ""}</li>`).join("")}</ol>` : ""}
${reviewHtml(r)}
<p class="qz-actions">${r.missed.length ? `<a class="button primary" id="qz-retry" href="#/retry/${esc(r.id)}">๐Ÿ” ื—ื–ืจื” ืขืœ ื”ืฉืืœื•ืช ืฉื˜ืขื™ืชื™ (${r.missed.length})</a> ` : ""}${names(r).again ? `<button type="button" class="${r.missed.length ? "" : "primary"}" id="qz-retake">${names(r).again}</button> ` : ""}<button type="button" data-close>${r.kind === "quiz" ? "ื—ื–ืจื” ืœืžืกืœื•ืœ" : "ื—ื–ืจื” ืœืžื‘ื—ืŸ"}</button></p>`;
if (r.review?.state === "pending") waitForReview(r.id);
const best = r.kind === "quiz" ? api(`/api/lessons/${encodeURIComponent(r.lesson.id)}/quiz`).then(f => f.best === null ? "" : `ื”ืฆื™ื•ืŸ ืฉืœ ื”ืฉื™ืขื•ืจ: ${f.best}`)
: Promise.resolve("");
const grow = q("#qz-ready .rd-bar i");
if (grow) setTimeout(() => { grow.style.width = `${grow.dataset.to}%`; }, 300);
best.then(text => { if (text && q("#qz-best")) q("#qz-best").textContent = text; }).catch(() => {});
}
function onClick(event) {
const target = event.target;
if (target.closest("[data-close]")) { location.hash = leaveTo(); return; }
if (target.closest("[data-board-toggle]")) { window.MathlyBoard?.toggle(); return; }
if (attempt?.state === "open") {
const go = target.closest("[data-go]");
if (go && !go.disabled) { saveWritten(attempt.questions[at]); at = Number(go.dataset.go); warned = false; renderQuestion(); return; }
const choice = target.closest(".qz-choice");
if (choice) { choose(choice); return; }
if (target.closest("#qz-submit")) { submit(); return; }
if (target.closest("#qz-open-board")) { window.MathlyBoard?.show?.(0); return; }
if (target.closest("#qz-yes")) { finish(true); return; }
if (target.closest("#qz-back")) { q("#qz-warn").innerHTML = ""; warned = false; return; }
} else if (target.closest("#qz-retake")) {
at = 0;
const again = attempt.kind === "quiz" ? start(attempt.lesson.id) : attempt.kind === "simulation" ? startSimulation(attempt.test.id)
: startExam(attempt.test.id, attempt.test.number);
again.catch(error => { q(".qz-actions").insertAdjacentHTML("afterend", `<p class="error" role="alert">${esc(error.message)}</p>`); });
}
}
window.addEventListener("mathly:leave", close);
document.addEventListener("keydown", event => {
if (event.key === "Escape" && layer && !document.querySelector(".mx-board.full")) location.hash = leaveTo();
});