// 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//`). */ 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///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//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 `
${x.gain ? `

המוכנות למבחן עלתה ל־${x.after}!

` : `

המוכנות נשארה ${x.after}. ציון מעל ${x.after} יעלה אותה.

`} ${x.level_up ? `

🎉 רמה חדשה: ${esc(x.label)}!

` : ""}

${x.next ? `עוד ${x.next.left} לרמה "${esc(x.next.name)}"` : "הרמה הגבוהה ביותר! 🏆"}

⏱ עוד סימולציה 📝 מבחן תרגול

`; } 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 = `
`; } 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 = ``; } } const heading = (title) => `
${chip(attempt)}

${title}

${attempt.state === "open" ? (window.MathlyBoard?.button() || "") : ""}
`; 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 ? `

${question.final.label ? `${esc(question.final.label)}` : ""}${question.final.unit ? `${esc(question.final.unit)}` : ""}

` : ""; return `

✏️ כמו במבחן אמיתי: כותבים את הפתרון המלא בלוח. הבודק רואה את הדרך, לא רק את התשובה.

${box}
`; } 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)}
${attempt.due_at ? `${clock(left())}` : ""} שאלה ${at + 1} מתוך ${total}
${attempt.questions.map((x, i) => ``).join("")}

${fmt(question.question)}

${figures(question)} ${attempt.written ? writtenHtml(question) : `
${choicesOf(question).map(c => ``).join("")}
`}
`; 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 = ``; 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 = ``; }); } 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 = ``; } } 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 = ``; 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 ? `
    ${rows.map(([n, q]) => `
  1. שאלה ${n} ${VERDICT[q.verdict][1]}

    ${fmt(q.feedback)}

    ${q.tip ? `

    💡 ${fmt(q.tip)}

    ` : ""}
  2. `).join("")}
` : ""; } function reviewHtml(r) { const review = r.review; if (!review) return ""; if (review.state === "pending") return `

משוב על הדרך

ה־AI עובר על הדרך שכתבתם בלוח, שאלה אחרי שאלה. אפשר להמשיך לקרוא את התוצאה, המשוב יופיע כאן.

${stepsHtml(review)} ${reviewRows(r, review.questions)}
`; if (review.state === "failed") return `

משוב על הדרך

לא הצלחנו לבדוק את הדרך הפעם. המורה יראו את הלוחות.

`; const rows = reviewRows(r, review.questions); return `

משוב על הדרך

${review.summary ? `

${fmt(review.summary)}

` : ""} ${rows || `

לא נשמרה דרך בלוח באף שאלה.

`}

משוב אוטומטי. המורה בודקים את הדרך ונותנים את הנקודות.

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

בבדיקה

${aiOn ? "ה־AI בודק את הפתרונות שכתבתם בלוח, שאלה אחרי שאלה. הציון יופיע כאן בסוף הבדיקה, אפשר לסגור ולחזור." : "המבחן הוגש וממתין לבדיקת המורה. הציון יופיע אחרי הבדיקה."}${r.timed_out ? " הזמן נגמר והמבחן הוגש כמו שהוא." : ""}

${reviewHtml(r)}

`; } const missedLine = (r, m) => !r.written ? (m.picked ? `

בחרתם: ${fmt(m.picked)}

` : `

לא ענו על השאלה.

`) : `${m.no_work ? `

לא נכתב פתרון בלוח.

` : `

${m.points === 0.5 ? "חצי מהנקודות על השאלה." : "לא קיבלתם נקודות על השאלה."}

`} ${m.picked ? `

התשובה הסופית שכתבתם: ${esc(m.picked)}

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

${r.grade}מתוך 100

${r.written ? `${r.right === 1 ? "שאלה אחת" : `${r.right} שאלות`} עם ניקוד מלא` : r.right === 1 ? "תשובה נכונה אחת" : `${r.right} תשובות נכונות`} מתוך ${r.total}${r.timed_out ? ". הזמן נגמר והבוחן הוגש כמו שהוא." : ""}

${readinessHtml(r)} ${r.lost_skills.length ? `

איפה אפשר להשתפר

    ${r.lost_skills.map(s => `
  • ${fmt(s.name)}${s.missed} ${s.missed === 1 ? "שאלה שגויה" : "שאלות שגויות"}
  • `).join("")}

אפשר לתרגל את המיומנות ואז לנסות שוב.

${r.kind !== "quiz" && r.test.number !== FOCUS ? `

🎯 מבחן תרגול ממוקד על מה שהיה קשה (15 שאלות)

` : ""}` : `

כל התשובות נכונות. כל הכבוד!

`} ${r.missed.length ? `

הטעויות

    ${r.missed.map(m => `
  1. ${fmt(m.question)}

    ${missedLine(r, m)} ${m.mistake ? `

    ${esc(m.mistake.name)}${m.mistake.tip ? `
    ${fmt(m.mistake.tip)}` : ""}

    ` : ""}
  2. `).join("")}
` : ""} ${reviewHtml(r)}

${r.missed.length ? `🔁 חזרה על השאלות שטעיתי (${r.missed.length}) ` : ""}${names(r).again ? ` ` : ""}

`; 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", ``); }); } } window.addEventListener("mathly:leave", close); document.addEventListener("keydown", event => { if (event.key === "Escape" && layer && !document.querySelector(".mx-board.full")) location.hash = leaveTo(); });