Ashish-K commited on
Commit
8d15c3a
·
verified ·
1 Parent(s): cca9e17

Quiz player with question navigator and sticky timer; chat layout; tutor activity in Progress; fixes

Browse files
Files changed (3) hide show
  1. app.py +34 -1
  2. static/index.html +352 -76
  3. tools/build_quizzes.py +103 -0
app.py CHANGED
@@ -339,7 +339,8 @@ def tutor_message(body: TutorMsg) -> dict:
339
 
340
  # ---------------------------------------------------------------- feedback
341
  FEEDBACK_TAGS = {"wrong answer", "unclear", "too hard", "too easy", "typo", "off topic", "helpful", "great question", "other",
342
- "confusing", "hard to find", "looks wrong", "too slow", "bug", "idea", "love it"}
 
343
 
344
 
345
  class FeedbackIn(BaseModel):
@@ -389,6 +390,38 @@ def set_feedback_status(fid: str, body: FeedbackStatus) -> dict:
389
  return item
390
 
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  # ---------------------------------------------------------------- settings
393
  class SettingsIn(BaseModel):
394
  tutorRouting: str = Field(pattern="^(auto|opus|fable)$")
 
339
 
340
  # ---------------------------------------------------------------- feedback
341
  FEEDBACK_TAGS = {"wrong answer", "unclear", "too hard", "too easy", "typo", "off topic", "helpful", "great question", "other",
342
+ "confusing", "hard to find", "looks wrong", "too slow", "bug", "idea", "love it",
343
+ "in syllabus", "not taught yet", "not in syllabus", "just right"}
344
 
345
 
346
  class FeedbackIn(BaseModel):
 
390
  return item
391
 
392
 
393
+ # ---------------------------------------------------------------- activity (counts only, no chat text)
394
+ @router.get("/api/activity")
395
+ def activity() -> dict:
396
+ out: dict[str, dict] = {sid: {"sessions": [], "ideas": {}} for sid in STORE.students}
397
+ for s in STORE.chats.values():
398
+ if s["studentId"] not in out:
399
+ continue
400
+ ch = CHAPTERS.get(s["setId"], {})
401
+ try:
402
+ mins = max(1, round((datetime.fromisoformat(s["updated"]) - datetime.fromisoformat(s["started"])).total_seconds() / 60))
403
+ except (KeyError, ValueError):
404
+ mins = 0
405
+ out[s["studentId"]]["sessions"].append({
406
+ "id": s["id"], "chapterId": s["setId"], "subject": ch.get("subject", ""), "chapter": ch.get("chapter", s["setId"]),
407
+ "mode": s["mode"], "started": s["started"], "updated": s["updated"], "minutes": mins,
408
+ "messages": sum(1 for m in s["transcript"] if m["role"] == "student") - 1,
409
+ "attempts": len(s["attempts"]), "correct": sum(1 for a in s["attempts"] if a.get("correct"))})
410
+ for sid, m in STORE.mastery.items():
411
+ if sid not in out:
412
+ continue
413
+ for cid, ch in CHAPTERS.items():
414
+ atoms = [{"id": a["id"], "statement": a["statement"], "level": m.get(a["id"], {}).get("level", 0),
415
+ "seen": m.get(a["id"], {}).get("seen", 0)} for a in ch["atoms"]]
416
+ if any(a["seen"] for a in atoms):
417
+ out[sid]["ideas"][cid] = {"subject": ch["subject"], "chapter": ch["chapter"],
418
+ "byLevel": [sum(1 for a in atoms if a["level"] == i) for i in range(5)],
419
+ "atoms": [a for a in atoms if a["seen"]]}
420
+ for v in out.values():
421
+ v["sessions"].sort(key=lambda x: x["updated"], reverse=True)
422
+ return out
423
+
424
+
425
  # ---------------------------------------------------------------- settings
426
  class SettingsIn(BaseModel):
427
  tutorRouting: str = Field(pattern="^(auto|opus|fable)$")
static/index.html CHANGED
@@ -61,9 +61,9 @@ body {
61
  font-size: 16px;
62
  line-height: 1.55;
63
  padding-inline: 16px;
64
- padding-block: 0 96px;
65
  }
66
- .wrap { max-width: 860px; margin: 0 auto; }
67
  h1, h2, h3 { font-family: var(--font-display); text-wrap: balance; margin: 0; line-height: 1.2; }
68
  h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.01em; }
69
  h2 { font-size: 1.25rem; font-weight: 600; }
@@ -80,7 +80,8 @@ header.top {
80
  border-bottom: 1px solid var(--rule);
81
  margin-inline: -16px; padding: 12px 16px;
82
  }
83
- header.top .row { max-width: 860px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
 
84
  .brand { display: flex; align-items: baseline; gap: 10px; margin-right: auto; }
85
  .brand .tag { font-family: var(--font-data); font-size: 0.75rem; color: var(--ink-soft); }
86
  nav.tabs { display: flex; gap: 4px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 999px; padding: 3px; }
@@ -157,7 +158,7 @@ label.opt.wrong { border-color: var(--bad); background: var(--bad-wash); }
157
  .selfmark button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
158
 
159
  .dock { position: fixed; left: 0; right: 0; bottom: 0; z-index: 6; padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px)); background: color-mix(in srgb, var(--paper) 94%, transparent); backdrop-filter: blur(6px); border-top: 1px solid var(--rule); }
160
- .dock .row { max-width: 860px; margin: 0 auto; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; }
161
  .dock .row .status { margin-right: auto; font-size: 0.9rem; color: var(--ink-soft); }
162
 
163
  .score-big { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
@@ -200,7 +201,72 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
200
  .bubble.system { background: var(--bad-wash); justify-self: center; }
201
  .chat.log { display: grid; gap: 10px; padding: 12px; background: var(--paper); border-radius: var(--radius); }
202
  .chat-row { width: 100%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  .composer { display: grid; gap: 8px; width: 100%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  .composer textarea { min-height: 56px; }
205
  .composer-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: flex-end; }
206
  .composer-row .selfmark { margin-right: auto; }
@@ -218,6 +284,17 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
218
  .student.parent { border-style: dashed; }
219
  .fb-chip { border-style: solid; color: var(--accent); }
220
  .app-fb { border-color: var(--accent); }
 
 
 
 
 
 
 
 
 
 
 
221
  .opts-list { margin: 0; padding-left: 1.4em; display: grid; gap: 4px; }
222
  .opts-list li.right { color: var(--good); font-weight: 700; }
223
  @media (prefers-reduced-motion: no-preference) {
@@ -237,7 +314,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
237
  <button id="tab-progress" aria-pressed="false">Progress</button>
238
  <button id="tab-bank" aria-pressed="false" hidden>Review</button>
239
  </nav>
240
- <div class="who"><button id="app-fb" class="who-chip fb-chip" type="button">Feedback on the app</button><button id="who" class="who-chip">Choose your name</button></div>
241
  </div>
242
  </header>
243
 
@@ -289,7 +366,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
289
  ready: false, feedback: [], readOnly: false, dbError: "", pinError: "",
290
  sets: new Map(), students: new Map(), attempts: [],
291
  view: "practise", // practise | test | review | progress
292
- studentId: store.get("sw.student") || null,
293
  progressStudent: null,
294
  run: null, // active test or review
295
  };
@@ -406,7 +483,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
406
  setId, key, phase: "test",
407
  startedAt: draft && draft.startedAt ? draft.startedAt : new Date().toISOString(),
408
  responses: draft && draft.responses ? draft.responses : {},
409
- self: {}, results: null, saved: false,
410
  };
411
  S.view = "test"; render(); window.scrollTo(0, 0); tickTimer();
412
  }
@@ -420,6 +497,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
420
  timerHandle = setInterval(() => {
421
  const el = $("timer"); if (!el || !S.run || S.run.phase !== "test") { clearInterval(timerHandle); return; }
422
  el.textContent = elapsedLabel();
 
423
  }, 1000);
424
  }
425
  function elapsedSec() { return S.run ? Math.max(0, Math.round((Date.now() - Date.parse(S.run.startedAt)) / 1000)) : 0; }
@@ -433,7 +511,11 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
433
  r.results = {};
434
  for (const q of set.questions || []) r.results[q.id] = markQuestion(q, r.responses[q.id]);
435
  r.phase = "review"; r.submittedAt = new Date().toISOString(); r.durationSec = elapsedSec();
436
- clearInterval(timerHandle); S.view = "review"; render(); window.scrollTo(0, 0);
 
 
 
 
437
  }
438
  function reviewTotals() {
439
  const r = S.run; const set = S.sets.get(r.setId);
@@ -609,15 +691,21 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
609
  $("tab-bank").hidden = !isParent;
610
  $("tab-bank").setAttribute("aria-pressed", String(S.view === "bank"));
611
  const main = $("main"); main.replaceChildren();
 
612
  const dock = $("dock"); const dockRow = $("dock-row"); dock.hidden = true; dockRow.replaceChildren();
613
 
614
  if (!S.ready) { main.append(h("section", { class: "sheet" }, h("h2", { text: "Loading your self-checks" }), h("p", { class: "muted", text: "Loading your self-checks and results." }))); return; }
615
  if (S.dbError) { main.append(connectionNotice()); }
616
  if (S.appFb) {
617
  const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` };
618
- fbOpen.add(JSON.stringify(t));
 
 
 
 
 
619
  main.append(h("section", { class: "sheet app-fb" },
620
- h("div", { class: "test-bar" }, h("h2", { text: "Feedback on the app" }), h("button", { class: "btn ghost", text: "Close", onclick: () => { S.appFb = false; render(); } })),
621
  h("p", { class: "muted", text: `What's working, what's confusing, what you'd change. We'll note that you were on: ${where}.` }),
622
  feedbackWidget(t, "Feedback")));
623
  }
@@ -631,6 +719,42 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
631
  renderPractise(main);
632
  }
633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
  // ---------- tutor ----------
635
  const T = { setId: null, sessionId: null, mode: null, msgs: [], busy: false, conf: null, mastery: null, draft: "" };
636
  async function loadMastery() {
@@ -660,7 +784,19 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
660
  T.busy = false; render(); scrollChat();
661
  const nb = $("tutor-input"); if (nb) nb.focus();
662
  }
663
- function scrollChat() { requestAnimationFrame(() => window.scrollTo(0, document.body.scrollHeight)); }
 
 
 
 
 
 
 
 
 
 
 
 
664
  function levelBar(byLevel, total) {
665
  const bar = h("div", { class: "lv-bar", role: "img", "aria-label": `Idea levels: ${byLevel.map((n, i) => `${n} at level ${i}`).join(", ")}` });
666
  byLevel.forEach((n, i) => { if (n) bar.append(h("span", { class: `lv lv${i}`, style: `flex:${n}` })); });
@@ -701,33 +837,58 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
701
  return;
702
  }
703
  const set = S.sets.get(T.setId) || {};
704
- const chat = h("section", { class: "sheet chat" },
705
- h("div", { class: "test-bar" }, h("div", null, h("span", { class: "label", text: `${set.subject || ""} · ${T.mode === "practice" ? "Today's practice" : "Questions"}` }), h("h2", { text: set.chapter || "" }))),
706
- T.sessionId ? feedbackWidget({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId }, "Feedback on this session") : null);
707
  for (const m of T.msgs) {
708
- const b = h("div", { class: `bubble ${m.who}` }, h("p", { text: m.text }));
709
- if (m.who === "tutor" && T.sessionId) b.append(feedbackWidget({ targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) }, "Feedback"));
710
  if (m.conf) b.append(h("span", { class: "hint", text: `You said: ${m.conf}` }));
711
  if (m.changes && m.changes.length) {
712
  const ups = m.changes.filter((c) => c.to > c.from).length, downs = m.changes.filter((c) => c.to < c.from).length;
713
  if (ups || downs) b.append(h("span", { class: `pill ${ups && !downs ? "good" : downs && !ups ? "bad" : "warn"}`, text: [ups ? `${ups} idea${ups > 1 ? "s" : ""} up a level` : "", downs ? `${downs} idea${downs > 1 ? "s" : ""} to revisit` : ""].filter(Boolean).join(" · ") }));
714
  }
715
- chat.append(b);
 
 
 
 
 
 
 
 
716
  }
717
- if (T.busy) chat.append(h("div", { class: "bubble tutor" }, h("p", { class: "muted", text: "Thinking…" })));
718
- main.append(chat);
719
- dock.hidden = false;
720
- const ta = h("textarea", { id: "tutor-input", rows: "2", placeholder: "Type your answer or question", "aria-label": "Your message", disabled: T.busy });
721
  ta.value = T.draft;
722
- ta.addEventListener("input", () => { T.draft = ta.value; });
 
723
  ta.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); tutorSend(); } });
724
  const confRow = h("div", { class: "selfmark", role: "group", "aria-label": "How sure are you?" },
725
  h("span", { class: "hint", text: "How sure?" }),
726
  ...["guess", "think so", "sure"].map((c) => h("button", { type: "button", "aria-pressed": String(T.conf === c), text: c,
727
  onclick: () => { T.conf = T.conf === c ? null : c; T.draft = ta.value; render(); } })));
728
- dockRow.append(h("div", { class: "composer" }, ta, h("div", { class: "composer-row" }, confRow,
729
- h("button", { class: "btn ghost", text: "End", onclick: () => { T.sessionId = null; T.setId = null; T.msgs = []; T.mastery = null; render(); } }),
730
- h("button", { class: "btn accent", text: "Send", disabled: T.busy, onclick: tutorSend }))));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731
  }
732
 
733
  // ---------- parent area ----------
@@ -879,7 +1040,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
879
  input.addEventListener("change", () => {
880
  if (q.type === "mcq") r.responses[q.id] = i;
881
  else { const cur = new Set((r.responses[q.id] || []).map(Number)); input.checked ? cur.add(i) : cur.delete(i); r.responses[q.id] = [...cur].sort(); }
882
- saveDraft(); updateDock();
883
  });
884
  let cls = "opt";
885
  if (mode === "review") {
@@ -892,16 +1053,17 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
892
  } else if (q.type === "numeric") {
893
  const input = h("input", { type: "text", inputmode: "decimal", id: name, autocomplete: "off", disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
894
  input.value = resp == null ? "" : String(resp);
895
- input.addEventListener("input", () => { r.responses[q.id] = input.value; saveDraft(); updateDock(); });
896
  body.append(h("div", { class: "numeric" }, input, q.unit ? h("span", { class: "mono", text: q.unit }) : null));
897
  if (mode === "test") body.append(h("p", { class: "hint", text: "Numbers only. Standard form can be typed as 6.02 x 10^23." }));
898
  } else {
899
  const ta = h("textarea", { id: name, disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
900
  ta.value = resp == null ? "" : String(resp);
901
- ta.addEventListener("input", () => { r.responses[q.id] = ta.value; saveDraft(); updateDock(); });
902
  body.append(ta);
903
  }
904
- if (mode === "review") body.append(reviewBlock(q, res), feedbackWidget({ targetType: "question", setId: S.run.setId, questionId: q.id }));
 
905
  return body;
906
  }
907
  function reviewBlock(q, res) {
@@ -920,7 +1082,7 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
920
  const row = h("div", { class: "selfmark", role: "group", "aria-label": "Marks you award yourself" });
921
  for (let m = 0; m <= res.max; m++) {
922
  row.append(h("button", { type: "button", "aria-pressed": String(r.self[q.id] === m), text: String(m),
923
- onclick: () => { r.self[q.id] = m; render(); } }));
924
  }
925
  box.append(row, h("span", { class: "hint", text: `out of ${res.max}. Give yourself a mark only for each point you clearly made.` }));
926
  }
@@ -938,57 +1100,128 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
938
  const set = S.sets.get(S.run.setId); s.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`;
939
  }
940
 
941
- function renderTest(main, dock, dockRow) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
942
  const set = S.sets.get(S.run.setId);
943
- if (!set) { S.view = "practise"; S.run = null; return render(); }
944
- const st = S.students.get(S.studentId);
945
- main.append(h("section", { class: "sheet" },
946
- h("div", { class: "test-bar" },
947
- h("div", null, h("span", { class: "label", text: `${set.subject || ""} · ${set.code || ""}` }), h("h2", { text: set.chapter || set.id })),
948
- h("span", { class: "timer mono", id: "timer", text: elapsedLabel() })),
949
- h("p", { class: "muted", text: `${st ? st.name + ", w" : "W"}ork on paper where you need to. Your answers are kept on this device until you submit.` })));
950
- const sheet = h("section", { class: "sheet" });
951
- (set.questions || []).forEach((q, i) => {
952
- sheet.append(h("div", { class: "q" },
953
- h("div", null, h("div", { class: "num", text: `Q${i + 1}` }), h("div", { class: "marks", text: `[${q.marks || 1}]` })),
954
- questionBody(q, i, "test")));
955
- });
956
- main.append(sheet);
957
- dock.hidden = false;
958
- dockRow.append(h("span", { class: "status", id: "dock-status" }),
959
- h("button", { class: "btn ghost", text: "Leave", onclick: () => { saveDraft(); S.view = "practise"; S.run = null; clearInterval(timerHandle); render(); } }),
960
- h("button", { class: "btn accent", text: "Submit and mark", onclick: submitTest }));
961
- updateDock();
962
  }
963
-
964
- function renderReview(main, dock, dockRow) {
965
- const set = S.sets.get(S.run.setId); const t = reviewTotals(); const p = pct(t.got, t.max);
966
- const summary = h("section", { class: "sheet" },
967
- h("span", { class: "label", text: `${set.subject || ""} · ${set.chapter || ""}` }),
968
- h("div", { class: "score-big" }, h("span", { class: "n", text: `${t.got}/${t.max}` }), h("span", { class: `pill ${band(p)}`, text: `${p}%` }),
969
- h("span", { class: "muted", text: `${Math.round((S.run.durationSec || 0) / 60)} min` })),
970
- h("div", { class: `bar ${band(p)}` }, h("span", { style: `width:${p}%` })),
971
- t.pendingSelf ? h("p", { class: "muted", text: `Mark ${t.pendingSelf} written answer${t.pendingSelf > 1 ? "s" : ""} below, then save your result.` })
972
- : h("p", { class: "muted", text: S.run.saved ? "Saved. Your Progress page now includes this attempt." : "All marked. Save your result so it counts in your progress." }),
973
- feedbackWidget({ targetType: "set", setId: S.run.setId }, "Feedback on this self-check"));
974
- main.append(summary);
975
- const sheet = h("section", { class: "sheet" });
976
- (set.questions || []).forEach((q, i) => {
977
- sheet.append(h("div", { class: "q" },
978
- h("div", null, h("div", { class: "num", text: `Q${i + 1}` }), h("div", { class: "marks", text: `[${q.marks || 1}]` })),
979
- questionBody(q, i, "review")));
980
- });
981
- main.append(sheet);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
  dock.hidden = false;
983
- dockRow.append(h("span", { class: "status", text: S.run.saved ? "Result saved" : t.pendingSelf ? `${t.pendingSelf} to self-mark` : "Ready to save" }));
984
- if (S.run.saved) {
985
- dockRow.append(h("button", { class: "btn ghost", text: "Back to self-checks", onclick: () => { S.view = "practise"; S.run = null; render(); } }),
986
- h("button", { class: "btn accent", text: "See progress", onclick: () => { S.view = "progress"; S.progressStudent = S.studentId; S.run = null; render(); } }));
 
987
  } else {
988
- dockRow.append(h("button", { class: "btn ghost", text: "Discard", onclick: () => { S.view = "practise"; S.run = null; render(); } }),
989
- h("button", { class: "btn accent", id: "save-btn", text: "Save result", disabled: !!t.pendingSelf, onclick: saveAttempt }));
 
 
 
 
 
 
 
 
 
 
990
  }
991
  }
 
 
 
 
 
 
 
 
 
 
992
 
993
  function renderProgress(main) {
994
  const students = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || ""));
@@ -1037,6 +1270,41 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
1037
  }
1038
  main.append(ws);
1039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1040
  // attempt history
1041
  const hist = attemptsFor(sid);
1042
  const hs = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: attempts` }));
@@ -1059,12 +1327,20 @@ td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-
1059
  // ---------- chrome ----------
1060
  $("tab-practise").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "practise"; S.run = null; render(); });
1061
  $("tab-progress").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "progress"; S.run = null; render(); });
1062
- $("app-fb").addEventListener("click", () => { S.appFb = !S.appFb; render(); window.scrollTo(0, 0); });
1063
  $("tab-bank").addEventListener("click", () => { S.view = "bank"; S.run = null; render(); });
1064
  $("tab-tutor").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "tutor"; S.run = null; T.mastery = null; render(); });
1065
  $("who").addEventListener("click", () => { if (S.view === "test") return toast("Submit or leave the self-check first"); S.view = "practise"; S.picking = true; render(); });
1066
  function confirmLeave() { saveDraft(); toast("Your answers are kept on this device. Open the self-check again to carry on."); clearInterval(timerHandle); return true; }
1067
 
 
 
 
 
 
 
 
 
1068
  render();
1069
  connect().catch(() => { S.dbError = "unavailable"; S.ready = true; render(); });
1070
  })();
 
61
  font-size: 16px;
62
  line-height: 1.55;
63
  padding-inline: 16px;
64
+ padding-block: 0 calc(var(--dock-h, 0px) + 32px);
65
  }
66
+ .wrap { max-width: 1120px; margin: 0 auto; }
67
  h1, h2, h3 { font-family: var(--font-display); text-wrap: balance; margin: 0; line-height: 1.2; }
68
  h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.01em; }
69
  h2 { font-size: 1.25rem; font-weight: 600; }
 
80
  border-bottom: 1px solid var(--rule);
81
  margin-inline: -16px; padding: 12px 16px;
82
  }
83
+ header.top .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; }
84
+ @media (max-width: 720px) { .brand .tag { display: none; } }
85
  .brand { display: flex; align-items: baseline; gap: 10px; margin-right: auto; }
86
  .brand .tag { font-family: var(--font-data); font-size: 0.75rem; color: var(--ink-soft); }
87
  nav.tabs { display: flex; gap: 4px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 999px; padding: 3px; }
 
158
  .selfmark button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
159
 
160
  .dock { position: fixed; left: 0; right: 0; bottom: 0; z-index: 6; padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px)); background: color-mix(in srgb, var(--paper) 94%, transparent); backdrop-filter: blur(6px); border-top: 1px solid var(--rule); }
161
+ .dock .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; }
162
  .dock .row .status { margin-right: auto; font-size: 0.9rem; color: var(--ink-soft); }
163
 
164
  .score-big { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
 
201
  .bubble.system { background: var(--bad-wash); justify-self: center; }
202
  .chat.log { display: grid; gap: 10px; padding: 12px; background: var(--paper); border-radius: var(--radius); }
203
  .chat-row { width: 100%; }
204
+ /* chat: header, its own scrolling message area, and the composer inside one panel */
205
+ body.in-chat { padding-block: 0; overflow: hidden; }
206
+ body.in-chat .wrap { height: calc(100dvh - var(--hdr-h, 64px)); }
207
+ body.in-chat main { height: 100%; padding-block: 12px; display: block; }
208
+ .chat-shell { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); overflow: hidden; }
209
+ .chat-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 12px 16px; border-bottom: 1px solid var(--rule); }
210
+ .chat-head .title { margin-right: auto; min-width: 0; }
211
+ .chat-head h2 { font-size: 1.05rem; }
212
+ .chat-scroll { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 18px 16px; display: flex; flex-direction: column; gap: 14px; scroll-behavior: smooth; }
213
+ @media (prefers-reduced-motion: reduce) { .chat-scroll { scroll-behavior: auto; } }
214
+ .chat-scroll .bubble { max-width: min(760px, 88%); }
215
+ .chat-scroll .bubble.tutor { align-self: flex-start; }
216
+ .chat-scroll .bubble.me { align-self: flex-end; }
217
+ .chat-scroll .bubble.system { align-self: center; }
218
+ .chat-composer { border-top: 1px solid var(--rule); background: var(--paper); padding: 10px 16px calc(10px + env(safe-area-inset-bottom, 0px)); display: grid; gap: 8px; }
219
+ .chat-composer .input-row { display: flex; gap: 8px; align-items: flex-end; }
220
+ .chat-composer textarea { flex: 1; min-width: 0; min-height: 44px; max-height: 180px; resize: none; line-height: 1.45; background: var(--sheet); }
221
+ .chat-composer .meta-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
222
+ .chat-composer .meta-row .selfmark { margin-right: auto; }
223
+ .typing { display: inline-flex; gap: 4px; padding: 4px 0; }
224
+ .typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-soft); opacity: 0.4; }
225
+ @media (prefers-reduced-motion: no-preference) {
226
+ .typing span { animation: blink 1.2s infinite; } .typing span:nth-child(2) { animation-delay: .2s; } .typing span:nth-child(3) { animation-delay: .4s; }
227
+ @keyframes blink { 0%, 80%, 100% { opacity: .25; } 40% { opacity: .9; } }
228
+ }
229
+ .md { display: grid; gap: 8px; }
230
+ .md p { white-space: normal; }
231
+ .md ul, .md ol { margin: 0; padding-left: 1.3em; display: grid; gap: 3px; }
232
+ .md code { font-family: var(--font-data); font-size: 0.9em; background: var(--paper); padding: 0 4px; border-radius: 4px; }
233
+ .bubble-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; opacity: 0.6; }
234
+ .bubble:hover .bubble-actions, .bubble-actions:focus-within { opacity: 1; }
235
+ .react { font: 600 0.75rem var(--font-display); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--rule); background: var(--sheet); color: var(--ink-soft); cursor: pointer; }
236
+ .react[aria-pressed="true"] { border-color: var(--good); color: var(--good); }
237
  .composer { display: grid; gap: 8px; width: 100%; }
238
+
239
+ /* quiz player */
240
+ .quizbar { position: sticky; top: var(--hdr-h, 64px); z-index: 4; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 12px 16px; display: grid; gap: 10px; box-shadow: 0 6px 18px -14px rgba(0,0,0,.35); }
241
+ .quizbar-top { display: flex; align-items: center; gap: 12px; }
242
+ .quizbar-top .title { margin-right: auto; min-width: 0; }
243
+ .quizbar-top h2 { font-size: 1.1rem; }
244
+ .timer-box { display: grid; justify-items: end; line-height: 1.1; }
245
+ .timer-box .timer { font-size: 1.35rem; }
246
+ .timer.over { color: var(--warn); }
247
+ .timer.good { color: var(--good); } .timer.warn { color: var(--warn); } .timer.bad { color: var(--bad); }
248
+ .qnav { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 2px; scrollbar-width: thin; }
249
+ .qchip { flex: 0 0 auto; min-width: 40px; height: 40px; border-radius: 10px; border: 2px solid var(--rule); background: var(--paper); color: var(--ink); font: 700 0.95rem var(--font-data); cursor: pointer; position: relative; }
250
+ .qchip.answered { background: var(--accent-wash); border-color: var(--accent-wash); }
251
+ .qchip.marked::after { content: ""; position: absolute; top: 3px; right: 3px; width: 8px; height: 8px; border-radius: 50%; background: var(--warn); }
252
+ .qchip.right { background: var(--good-wash); border-color: var(--good); color: var(--good); }
253
+ .qchip.part { background: var(--warn-wash); border-color: var(--warn); color: var(--warn); }
254
+ .qchip.wrong { background: var(--bad-wash); border-color: var(--bad); color: var(--bad); }
255
+ .qchip.pending { border-style: dashed; border-color: var(--ink-soft); }
256
+ .qchip.current { outline: 3px solid var(--accent); outline-offset: 2px; }
257
+ .qchip.mini { display: inline-block; min-width: 14px; width: 14px; height: 14px; border-radius: 4px; vertical-align: -2px; margin-right: 6px; cursor: default; }
258
+ .qchip.mini.marked::after { top: 2px; right: 2px; width: 6px; height: 6px; }
259
+ .qcard { gap: 16px; }
260
+ .qcard-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
261
+ .qcard-head .marks { margin-right: auto; }
262
+ .qcard .prompt { font-size: 1.08rem; }
263
+ .qcard-nav { display: flex; justify-content: space-between; gap: 10px; padding-top: 8px; border-top: 1px solid var(--rule); }
264
+ .qflags { display: grid; gap: 8px; padding: 10px 12px; border-radius: 8px; background: var(--paper); }
265
+ .qflag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
266
+ .qflag-row .hint { min-width: 150px; }
267
+ .idea-ch { display: grid; gap: 8px; padding-top: 10px; border-top: 1px solid var(--rule); }
268
+ .idea-list { display: grid; gap: 4px; font-size: 0.92rem; }
269
+ .idea { display: flex; gap: 8px; align-items: baseline; }
270
  .composer textarea { min-height: 56px; }
271
  .composer-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: flex-end; }
272
  .composer-row .selfmark { margin-right: auto; }
 
284
  .student.parent { border-style: dashed; }
285
  .fb-chip { border-style: solid; color: var(--accent); }
286
  .app-fb { border-color: var(--accent); }
287
+ .fb-chip .short { display: none; }
288
+ .timer { white-space: nowrap; }
289
+ @media (max-width: 560px) {
290
+ .fb-chip .long { display: none; } .fb-chip .short { display: inline; }
291
+ header.top .row { gap: 8px; }
292
+ .brand h1 { font-size: 1.1rem; }
293
+ .quizbar { padding: 10px 12px; }
294
+ .quizbar-top .label { display: none; }
295
+ .timer-box .timer { font-size: 1.05rem; }
296
+ .qchip { min-width: 36px; height: 36px; }
297
+ }
298
  .opts-list { margin: 0; padding-left: 1.4em; display: grid; gap: 4px; }
299
  .opts-list li.right { color: var(--good); font-weight: 700; }
300
  @media (prefers-reduced-motion: no-preference) {
 
314
  <button id="tab-progress" aria-pressed="false">Progress</button>
315
  <button id="tab-bank" aria-pressed="false" hidden>Review</button>
316
  </nav>
317
+ <div class="who"><button id="app-fb" class="who-chip fb-chip" type="button" aria-label="Feedback on the app"><span class="long">Feedback on the app</span><span class="short">Feedback</span></button><button id="who" class="who-chip">Choose your name</button></div>
318
  </div>
319
  </header>
320
 
 
366
  ready: false, feedback: [], readOnly: false, dbError: "", pinError: "",
367
  sets: new Map(), students: new Map(), attempts: [],
368
  view: "practise", // practise | test | review | progress
369
+ studentId: null,
370
  progressStudent: null,
371
  run: null, // active test or review
372
  };
 
483
  setId, key, phase: "test",
484
  startedAt: draft && draft.startedAt ? draft.startedAt : new Date().toISOString(),
485
  responses: draft && draft.responses ? draft.responses : {},
486
+ self: {}, results: null, saved: false, idx: 0, marked: new Set(),
487
  };
488
  S.view = "test"; render(); window.scrollTo(0, 0); tickTimer();
489
  }
 
497
  timerHandle = setInterval(() => {
498
  const el = $("timer"); if (!el || !S.run || S.run.phase !== "test") { clearInterval(timerHandle); return; }
499
  el.textContent = elapsedLabel();
500
+ const set = S.sets.get(S.run.setId); el.classList.toggle("over", elapsedSec() > (Number(set && set.minutes) || 0) * 60);
501
  }, 1000);
502
  }
503
  function elapsedSec() { return S.run ? Math.max(0, Math.round((Date.now() - Date.parse(S.run.startedAt)) / 1000)) : 0; }
 
511
  r.results = {};
512
  for (const q of set.questions || []) r.results[q.id] = markQuestion(q, r.responses[q.id]);
513
  r.phase = "review"; r.submittedAt = new Date().toISOString(); r.durationSec = elapsedSec();
514
+ clearInterval(timerHandle); S.view = "review";
515
+ const firstShort = (set.questions || []).findIndex((q) => !r.results[q.id].auto);
516
+ r.idx = firstShort >= 0 ? firstShort : 0;
517
+ render(); window.scrollTo(0, 0);
518
+ if (reviewTotals().pendingSelf === 0) saveAttempt();
519
  }
520
  function reviewTotals() {
521
  const r = S.run; const set = S.sets.get(r.setId);
 
691
  $("tab-bank").hidden = !isParent;
692
  $("tab-bank").setAttribute("aria-pressed", String(S.view === "bank"));
693
  const main = $("main"); main.replaceChildren();
694
+ if (!(S.view === "tutor" && (T.sessionId || T.busy))) document.body.classList.remove("in-chat");
695
  const dock = $("dock"); const dockRow = $("dock-row"); dock.hidden = true; dockRow.replaceChildren();
696
 
697
  if (!S.ready) { main.append(h("section", { class: "sheet" }, h("h2", { text: "Loading your self-checks" }), h("p", { class: "muted", text: "Loading your self-checks and results." }))); return; }
698
  if (S.dbError) { main.append(connectionNotice()); }
699
  if (S.appFb) {
700
  const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` };
701
+ const k = JSON.stringify(t);
702
+ if (S.appFbOpening) { fbOpen.add(k); S.appFbOpening = false; }
703
+ if (!fbOpen.has(k)) S.appFb = false;
704
+ }
705
+ if (S.appFb) {
706
+ const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` };
707
  main.append(h("section", { class: "sheet app-fb" },
708
+ h("div", { class: "test-bar" }, h("h2", { text: "Feedback on the app" }), h("button", { class: "btn ghost", text: "Close", onclick: () => { S.appFb = false; fbOpen.clear(); render(); } })),
709
  h("p", { class: "muted", text: `What's working, what's confusing, what you'd change. We'll note that you were on: ${where}.` }),
710
  feedbackWidget(t, "Feedback")));
711
  }
 
719
  renderPractise(main);
720
  }
721
 
722
+ // ---------- light formatting for tutor replies ----------
723
+ function inline(text) {
724
+ const frag = document.createDocumentFragment();
725
+ const re = /(\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\s][^*\n]*\*|_[^_\s][^_\n]*_|`[^`\n]+`)/g;
726
+ let last = 0, m;
727
+ while ((m = re.exec(text))) {
728
+ if (m.index > last) frag.append(text.slice(last, m.index));
729
+ const t = m[0];
730
+ if (t.startsWith("**") || t.startsWith("__")) frag.append(h("strong", { text: t.slice(2, -2) }));
731
+ else if (t.startsWith("`")) frag.append(h("code", { text: t.slice(1, -1) }));
732
+ else frag.append(h("em", { text: t.slice(1, -1) }));
733
+ last = m.index + t.length;
734
+ }
735
+ if (last < text.length) frag.append(text.slice(last));
736
+ return frag;
737
+ }
738
+ function md(text) {
739
+ const box = h("div", { class: "md" });
740
+ let para = [], list = null, listType = null;
741
+ const flushPara = () => { if (para.length) { const p = h("p"); para.forEach((l, i) => { if (i) p.append(h("br")); p.append(inline(l)); }); box.append(p); para = []; } };
742
+ const flushList = () => { if (list) { box.append(list); list = null; listType = null; } };
743
+ for (const raw of String(text || "").split("\n")) {
744
+ const line = raw.trimEnd();
745
+ const ul = line.match(/^\s*[-•*]\s+(.*)$/), ol = line.match(/^\s*\d+[.)]\s+(.*)$/);
746
+ if (ul || ol) {
747
+ flushPara();
748
+ const type = ul ? "ul" : "ol";
749
+ if (listType !== type) { flushList(); list = h(type); listType = type; }
750
+ list.append(h("li", null, inline((ul || ol)[1])));
751
+ } else if (!line.trim()) { flushPara(); flushList(); }
752
+ else { flushList(); para.push(line); }
753
+ }
754
+ flushPara(); flushList();
755
+ return box;
756
+ }
757
+
758
  // ---------- tutor ----------
759
  const T = { setId: null, sessionId: null, mode: null, msgs: [], busy: false, conf: null, mastery: null, draft: "" };
760
  async function loadMastery() {
 
784
  T.busy = false; render(); scrollChat();
785
  const nb = $("tutor-input"); if (nb) nb.focus();
786
  }
787
+ function scrollChat() { T.stick = true; requestAnimationFrame(() => { const el = $("chat-scroll"); if (el) el.scrollTop = el.scrollHeight; }); }
788
+ async function react(m, up) {
789
+ if (up) {
790
+ m.rated = "up";
791
+ try { const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600), tags: ["helpful"], text: "" }) }); S.feedback.push(f); toast("Thanks"); }
792
+ catch (e) { m.rated = null; toast(e.message); }
793
+ } else {
794
+ m.open = !m.open;
795
+ const k = JSON.stringify({ targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) });
796
+ m.open ? fbOpen.add(k) : fbOpen.delete(k);
797
+ }
798
+ render();
799
+ }
800
  function levelBar(byLevel, total) {
801
  const bar = h("div", { class: "lv-bar", role: "img", "aria-label": `Idea levels: ${byLevel.map((n, i) => `${n} at level ${i}`).join(", ")}` });
802
  byLevel.forEach((n, i) => { if (n) bar.append(h("span", { class: `lv lv${i}`, style: `flex:${n}` })); });
 
837
  return;
838
  }
839
  const set = S.sets.get(T.setId) || {};
840
+ document.body.classList.add("in-chat");
841
+ const scroller = h("div", { class: "chat-scroll", id: "chat-scroll", role: "log", "aria-live": "polite", "aria-label": "Tutor conversation" });
 
842
  for (const m of T.msgs) {
843
+ const b = h("div", { class: `bubble ${m.who}` }, m.who === "tutor" ? md(m.text) : h("p", { text: m.text }));
 
844
  if (m.conf) b.append(h("span", { class: "hint", text: `You said: ${m.conf}` }));
845
  if (m.changes && m.changes.length) {
846
  const ups = m.changes.filter((c) => c.to > c.from).length, downs = m.changes.filter((c) => c.to < c.from).length;
847
  if (ups || downs) b.append(h("span", { class: `pill ${ups && !downs ? "good" : downs && !ups ? "bad" : "warn"}`, text: [ups ? `${ups} idea${ups > 1 ? "s" : ""} up a level` : "", downs ? `${downs} idea${downs > 1 ? "s" : ""} to revisit` : ""].filter(Boolean).join(" · ") }));
848
  }
849
+ const ft = { targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) };
850
+ if (m.open && !fbOpen.has(JSON.stringify(ft))) m.open = false;
851
+ if (m.who === "tutor" && T.sessionId) {
852
+ b.append(h("div", { class: "bubble-actions" },
853
+ h("button", { type: "button", class: "react", "aria-pressed": String(m.rated === "up"), disabled: m.rated === "up", text: m.rated === "up" ? "Marked helpful" : "Helpful", onclick: () => react(m, true) }),
854
+ h("button", { type: "button", class: "react", "aria-pressed": String(!!m.open), text: "Not quite…", onclick: () => react(m, false) })));
855
+ if (m.open) b.append(feedbackWidget(ft, "Tell us what was wrong"));
856
+ }
857
+ scroller.append(b);
858
  }
859
+ if (T.busy) scroller.append(h("div", { class: "bubble tutor", "aria-label": "Tutor is thinking" }, h("div", { class: "typing" }, h("span"), h("span"), h("span"))));
860
+ const ta = h("textarea", { id: "tutor-input", rows: "1", placeholder: T.busy ? "The tutor is thinking…" : "Type your answer or question (Enter to send, Shift+Enter for a new line)", "aria-label": "Your message", disabled: T.busy });
 
 
861
  ta.value = T.draft;
862
+ const grow = () => { ta.style.height = "auto"; ta.style.height = Math.min(ta.scrollHeight, 180) + "px"; };
863
+ ta.addEventListener("input", () => { T.draft = ta.value; grow(); });
864
  ta.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); tutorSend(); } });
865
  const confRow = h("div", { class: "selfmark", role: "group", "aria-label": "How sure are you?" },
866
  h("span", { class: "hint", text: "How sure?" }),
867
  ...["guess", "think so", "sure"].map((c) => h("button", { type: "button", "aria-pressed": String(T.conf === c), text: c,
868
  onclick: () => { T.conf = T.conf === c ? null : c; T.draft = ta.value; render(); } })));
869
+ const sessionFbKey = JSON.stringify({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId });
870
+ const shell = h("section", { class: "chat-shell" },
871
+ h("div", { class: "chat-head" },
872
+ h("div", { class: "title" }, h("span", { class: "label", text: `${set.subject || ""} · ${T.mode === "practice" ? "Today's practice" : "Questions"}` }), h("h2", { text: set.chapter || "" })),
873
+ T.sessionId ? h("button", { type: "button", class: "btn ghost", text: fbOpen.has(sessionFbKey) ? "Close feedback" : "Feedback on session",
874
+ onclick: () => { fbOpen.has(sessionFbKey) ? fbOpen.delete(sessionFbKey) : fbOpen.add(sessionFbKey); render(); } }) : null,
875
+ h("button", { type: "button", class: "btn ghost", text: "End session", onclick: () => { T.sessionId = null; T.setId = null; T.msgs = []; T.mastery = null; document.body.classList.remove("in-chat"); render(); } })),
876
+ T.sessionId && fbOpen.has(sessionFbKey) ? h("div", { class: "chat-head" }, feedbackWidget({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId }, "Feedback on this session")) : null,
877
+ scroller,
878
+ h("div", { class: "chat-composer" },
879
+ h("div", { class: "input-row" }, ta, h("button", { class: "btn accent", text: "Send", disabled: T.busy, onclick: tutorSend })),
880
+ h("div", { class: "meta-row" }, confRow, h("span", { class: "hint", text: "Your parent can read these chats." }))));
881
+ main.append(shell);
882
+ requestAnimationFrame(() => {
883
+ grow();
884
+ if (T.stick || T.scrollPos == null) scroller.scrollTop = scroller.scrollHeight; else scroller.scrollTop = T.scrollPos;
885
+ T.stick = false;
886
+ scroller.addEventListener("scroll", () => {
887
+ const nearBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 60;
888
+ T.scrollPos = nearBottom ? null : scroller.scrollTop;
889
+ }, { passive: true });
890
+ if (!T.busy && document.activeElement === document.body) ta.focus({ preventScroll: true });
891
+ });
892
  }
893
 
894
  // ---------- parent area ----------
 
1040
  input.addEventListener("change", () => {
1041
  if (q.type === "mcq") r.responses[q.id] = i;
1042
  else { const cur = new Set((r.responses[q.id] || []).map(Number)); input.checked ? cur.add(i) : cur.delete(i); r.responses[q.id] = [...cur].sort(); }
1043
+ saveDraft(); updateDock(); updateNav();
1044
  });
1045
  let cls = "opt";
1046
  if (mode === "review") {
 
1053
  } else if (q.type === "numeric") {
1054
  const input = h("input", { type: "text", inputmode: "decimal", id: name, autocomplete: "off", disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
1055
  input.value = resp == null ? "" : String(resp);
1056
+ input.addEventListener("input", () => { r.responses[q.id] = input.value; saveDraft(); updateDock(); updateNav(); });
1057
  body.append(h("div", { class: "numeric" }, input, q.unit ? h("span", { class: "mono", text: q.unit }) : null));
1058
  if (mode === "test") body.append(h("p", { class: "hint", text: "Numbers only. Standard form can be typed as 6.02 x 10^23." }));
1059
  } else {
1060
  const ta = h("textarea", { id: name, disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
1061
  ta.value = resp == null ? "" : String(resp);
1062
+ ta.addEventListener("input", () => { r.responses[q.id] = ta.value; saveDraft(); updateDock(); updateNav(); });
1063
  body.append(ta);
1064
  }
1065
+ if (mode === "review") body.append(reviewBlock(q, res), questionFlags(S.run.setId, q),
1066
+ feedbackWidget({ targetType: "question", setId: S.run.setId, questionId: q.id }, "Something's wrong with this question"));
1067
  return body;
1068
  }
1069
  function reviewBlock(q, res) {
 
1082
  const row = h("div", { class: "selfmark", role: "group", "aria-label": "Marks you award yourself" });
1083
  for (let m = 0; m <= res.max; m++) {
1084
  row.append(h("button", { type: "button", "aria-pressed": String(r.self[q.id] === m), text: String(m),
1085
+ onclick: () => { r.self[q.id] = m; render(); if (!r.saved && reviewTotals().pendingSelf === 0) saveAttempt(); } }));
1086
  }
1087
  box.append(row, h("span", { class: "hint", text: `out of ${res.max}. Give yourself a mark only for each point you clearly made.` }));
1088
  }
 
1100
  const set = S.sets.get(S.run.setId); s.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`;
1101
  }
1102
 
1103
+ // ---------- quiz player: one question at a time ----------
1104
+ const FLAG_GROUPS = [
1105
+ { label: "Is this in your syllabus?", tags: ["in syllabus", "not taught yet", "not in syllabus"] },
1106
+ { label: "For you, this was", tags: ["too easy", "just right", "too hard"] },
1107
+ ];
1108
+ function questionFlags(setId, q) {
1109
+ if (!S.studentId || S.studentId === "parent") return null;
1110
+ const mine = S.feedback.filter((f) => f.by === S.studentId && f.targetType === "question" && f.setId === setId && f.questionId === q.id)
1111
+ .sort((x, y) => String(x.created).localeCompare(String(y.created)));
1112
+ const box = h("div", { class: "qflags" });
1113
+ for (const g of FLAG_GROUPS) {
1114
+ const latest = [...mine].reverse().find((f) => f.tags.some((t) => g.tags.includes(t)));
1115
+ const current = latest && latest.tags.find((t) => g.tags.includes(t));
1116
+ box.append(h("div", { class: "qflag-row" }, h("span", { class: "hint", text: g.label }),
1117
+ h("div", { class: "selfmark", role: "group", "aria-label": g.label }, ...g.tags.map((t) =>
1118
+ h("button", { type: "button", "aria-pressed": String(current === t), text: t, onclick: async () => {
1119
+ try {
1120
+ const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "question", setId, questionId: q.id, tags: [t], text: "" }) });
1121
+ S.feedback.push(f); render();
1122
+ } catch (e) { toast(e.message); }
1123
+ } })))));
1124
+ }
1125
+ return box;
1126
+ }
1127
+ function isAnswered(q) { const v = S.run.responses[q.id]; return v != null && v !== "" && !(Array.isArray(v) && !v.length); }
1128
+ function goTo(i) {
1129
+ const set = S.sets.get(S.run.setId); const n = (set.questions || []).length;
1130
+ S.run.idx = Math.max(0, Math.min(n - 1, i)); render();
1131
+ const card = $("qcard"); if (card) card.scrollIntoView({ block: "nearest" });
1132
+ }
1133
+ function navChip(q, i) {
1134
+ const r = S.run; const cls = ["qchip"];
1135
+ if (i === r.idx) cls.push("current");
1136
+ if (r.phase === "test") {
1137
+ if (isAnswered(q)) cls.push("answered");
1138
+ if (r.marked.has(q.id)) cls.push("marked");
1139
+ } else {
1140
+ const res = r.results[q.id];
1141
+ const got = res.auto ? res.got : r.self[q.id];
1142
+ cls.push(got == null ? "pending" : got >= res.max ? "right" : got > 0 ? "part" : "wrong");
1143
+ }
1144
+ const state = r.phase === "test" ? (isAnswered(q) ? "answered" : "not answered") + (r.marked.has(q.id) ? ", marked to come back to" : "")
1145
+ : cls.includes("pending") ? "needs self-marking" : cls.includes("right") ? "correct" : cls.includes("part") ? "partly correct" : "not correct";
1146
+ return h("button", { type: "button", class: cls.join(" "), "aria-current": i === r.idx ? "step" : null,
1147
+ "aria-label": `Question ${i + 1}, ${state}`, text: String(i + 1), onclick: () => goTo(i) });
1148
+ }
1149
+ function updateNav() {
1150
+ const nav = $("qnav"); if (!nav || !S.run) return;
1151
  const set = S.sets.get(S.run.setId);
1152
+ nav.replaceChildren(...(set.questions || []).map(navChip));
1153
+ const c = $("answered-count"); if (c) c.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1154
  }
1155
+ function renderPlayer(main, dock, dockRow, mode) {
1156
+ const r = S.run; const set = S.sets.get(r.setId);
1157
+ if (!set) { S.view = "practise"; S.run = null; return render(); }
1158
+ const qs = set.questions || []; const n = qs.length; const q = qs[r.idx];
1159
+ const title = set.title ? `${set.title}` : (set.chapter || set.id);
1160
+ const t = mode === "review" ? reviewTotals() : null;
1161
+ // sticky bar: title, timer or score, question numbers
1162
+ const bar = h("div", { class: "quizbar" },
1163
+ h("div", { class: "quizbar-top" },
1164
+ h("div", { class: "title" }, h("span", { class: "label", text: `${set.subject || ""} · ${set.chapter || ""}` }), h("h2", { text: title })),
1165
+ mode === "test"
1166
+ ? h("div", { class: "timer-box", role: "timer", "aria-label": "Time" }, h("span", { class: "hint", text: "Time" }), h("span", { class: "timer mono", id: "timer", text: elapsedLabel() }))
1167
+ : h("div", { class: "timer-box" }, h("span", { class: "hint", text: "Score" }), h("span", { class: `timer mono ${band(pct(t.got, t.max))}`, text: `${t.got}/${t.max}` }))),
1168
+ h("nav", { class: "qnav", id: "qnav", "aria-label": "Questions" }, ...qs.map(navChip)),
1169
+ h("div", { class: "legend" }, ...(mode === "test"
1170
+ ? [h("span", null, h("span", { class: "qchip mini answered" }), "answered"), h("span", null, h("span", { class: "qchip mini marked" }), "come back to"), h("span", { class: "hint", id: "answered-count", text: `${answeredCount()} of ${n} answered` })]
1171
+ : [h("span", null, h("span", { class: "qchip mini right" }), "correct"), h("span", null, h("span", { class: "qchip mini part" }), "partly"), h("span", null, h("span", { class: "qchip mini wrong" }), "not correct"),
1172
+ t.pendingSelf ? h("span", null, h("span", { class: "qchip mini pending" }), `${t.pendingSelf} to mark yourself`) : null])));
1173
+ main.append(bar);
1174
+ if (mode === "review") {
1175
+ const p = pct(t.got, t.max);
1176
+ main.append(h("div", { class: `notice ${r.saved ? "good" : ""}` }, h("p", { text: r.saved
1177
+ ? `Saved: ${t.got}/${t.max} (${p}%) in ${Math.max(1, Math.round((r.durationSec || 0) / 60))} min. Tap any number to see that question.`
1178
+ : t.pendingSelf ? `Mark your written answer${t.pendingSelf > 1 ? "s" : ""} (dashed numbers) and your result saves automatically.` : "Saving your result…" })));
1179
+ }
1180
+ // the question card
1181
+ const card = h("section", { class: "sheet qcard", id: "qcard" },
1182
+ h("div", { class: "qcard-head" }, h("span", { class: "label", text: `Question ${r.idx + 1} of ${n}` }), h("span", { class: "marks", text: `${q.marks || 1} mark${(q.marks || 1) > 1 ? "s" : ""}` }),
1183
+ mode === "test" ? h("button", { type: "button", class: "react", "aria-pressed": String(r.marked.has(q.id)), text: r.marked.has(q.id) ? "Marked to come back to" : "Mark to come back to",
1184
+ onclick: () => { r.marked.has(q.id) ? r.marked.delete(q.id) : r.marked.add(q.id); render(); } }) : null),
1185
+ questionBody(q, r.idx, mode),
1186
+ h("div", { class: "qcard-nav" },
1187
+ h("button", { type: "button", class: "btn ghost", disabled: r.idx === 0, "aria-label": "Previous question", text: "← Previous", onclick: () => goTo(r.idx - 1) }),
1188
+ r.idx < n - 1
1189
+ ? h("button", { type: "button", class: "btn accent", "aria-label": "Next question", text: "Next →", onclick: () => goTo(r.idx + 1) })
1190
+ : mode === "test" ? h("button", { type: "button", class: "btn accent", text: "Submit and mark", onclick: confirmSubmit }) : null));
1191
+ main.append(card);
1192
+ if (mode === "review") main.append(h("section", { class: "sheet" }, feedbackWidget({ targetType: "set", setId: r.setId }, "Feedback on this whole quiz")));
1193
+ // bottom dock: leave / submit, or after review: where next
1194
  dock.hidden = false;
1195
+ if (mode === "test") {
1196
+ dockRow.append(h("span", { class: "status", id: "dock-status" }),
1197
+ h("button", { class: "btn ghost", text: "Leave", onclick: () => { saveDraft(); S.view = "practise"; S.run = null; clearInterval(timerHandle); render(); } }),
1198
+ h("button", { class: "btn accent", text: "Submit and mark", onclick: confirmSubmit }));
1199
+ updateDock();
1200
  } else {
1201
+ dockRow.append(h("span", { class: "status", text: r.saved ? "Result saved" : t.pendingSelf ? `${t.pendingSelf} to mark yourself` : "Saving…" }),
1202
+ h("button", { class: "btn ghost", text: "Back to quizzes", onclick: () => { if (!r.saved && t.pendingSelf) toast("Mark your written answers first, or this result won't be saved"); S.view = "practise"; S.run = null; render(); } }),
1203
+ r.saved ? h("button", { class: "btn accent", text: "See progress", onclick: () => { S.view = "progress"; S.progressStudent = S.studentId; S.run = null; render(); } }) : null);
1204
+ }
1205
+ if (r.confirming) {
1206
+ const left = n - answeredCount();
1207
+ main.append(h("div", { class: "notice", role: "alertdialog", "aria-label": "Submit the quiz?" },
1208
+ h("p", { text: left ? `${left} question${left > 1 ? "s are" : " is"} not answered yet. Submit anyway?` : "Submit your answers for marking?" }),
1209
+ h("div", { class: "students" },
1210
+ h("button", { class: "btn ghost", text: "Keep working", onclick: () => { r.confirming = false; render(); } }),
1211
+ h("button", { class: "btn accent", text: "Submit", onclick: () => { r.confirming = false; submitTest(); } }))));
1212
+ requestAnimationFrame(() => window.scrollTo(0, document.body.scrollHeight));
1213
  }
1214
  }
1215
+ function confirmSubmit() { S.run.confirming = true; render(); }
1216
+ function renderTest(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "test"); }
1217
+ function renderReview(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "review"); }
1218
+ document.addEventListener("keydown", (e) => {
1219
+ if (!S.run || !["test", "review"].includes(S.view)) return;
1220
+ const tag = (e.target && e.target.tagName) || "";
1221
+ if (["INPUT", "TEXTAREA", "SELECT"].includes(tag) && e.target.type !== "radio" && e.target.type !== "checkbox") return;
1222
+ if (e.key === "ArrowRight") { e.preventDefault(); goTo(S.run.idx + 1); }
1223
+ if (e.key === "ArrowLeft") { e.preventDefault(); goTo(S.run.idx - 1); }
1224
+ });
1225
 
1226
  function renderProgress(main) {
1227
  const students = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || ""));
 
1270
  }
1271
  main.append(ws);
1272
 
1273
+ // tutor activity and idea levels (counts only; the parent area has the full chats)
1274
+ if (!S.activity && !S.loadingActivity) {
1275
+ S.loadingActivity = true;
1276
+ api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (S.view === "progress") render(); });
1277
+ }
1278
+ const act = (S.activity && S.activity[sid]) || { sessions: [], ideas: {} };
1279
+ const ts = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: tutor sessions` }));
1280
+ if (!S.activity) ts.append(h("p", { class: "muted", text: "Loading…" }));
1281
+ else if (!act.sessions.length) ts.append(h("p", { class: "muted", text: "No tutor sessions yet." }));
1282
+ else {
1283
+ const mins = act.sessions.reduce((a, x) => a + (x.minutes || 0), 0);
1284
+ const right = act.sessions.reduce((a, x) => a + x.correct, 0), tried = act.sessions.reduce((a, x) => a + x.attempts, 0);
1285
+ ts.append(h("p", { class: "muted", text: `${act.sessions.length} session${act.sessions.length > 1 ? "s" : ""}, about ${mins} min, ${right} of ${tried} tutor questions answered correctly.` }));
1286
+ const tt = h("table"); tt.append(h("thead", null, h("tr", null, h("th", { text: "When" }), h("th", { text: "Chapter" }), h("th", { class: "num", text: "Messages" }), h("th", { class: "num", text: "Right" }), h("th", { class: "num", text: "Time" }))));
1287
+ const tb2 = h("tbody");
1288
+ for (const x of act.sessions.slice(0, 30)) tb2.append(h("tr", null, h("td", { class: "mono", text: fmtDate(x.updated) }),
1289
+ h("td", { text: `${x.subject} · ${x.chapter}${x.mode === "practice" ? " (practice)" : ""}` }), h("td", { class: "num", text: String(Math.max(0, x.messages)) }),
1290
+ h("td", { class: "num", text: `${x.correct}/${x.attempts}` }), h("td", { class: "num", text: `${x.minutes} min` })));
1291
+ tt.append(tb2); ts.append(h("div", { class: "table-wrap" }, tt));
1292
+ }
1293
+ main.append(ts);
1294
+ const ideaCh = Object.entries(act.ideas || {});
1295
+ if (ideaCh.length) {
1296
+ const is = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: idea levels` }),
1297
+ h("p", { class: "muted", text: "From the tutor and quizzes together. Levels: not met, recall, apply, combine, exam-ready." }),
1298
+ h("div", { class: "legend" }, ...[0, 1, 2, 3, 4].map((i) => h("span", null, h("span", { class: `lv-dot lv${i}` }), ["not met", "recall", "apply", "combine", "exam-ready"][i]))));
1299
+ for (const [, ch] of ideaCh) {
1300
+ const total = ch.byLevel.reduce((a, b) => a + b, 0);
1301
+ is.append(h("div", { class: "idea-ch" }, h("h3", { text: `${ch.subject} · ${ch.chapter}` }), levelBar(ch.byLevel, total),
1302
+ h("div", { class: "idea-list" }, ...ch.atoms.slice().sort((a, b) => a.level - b.level).slice(0, 8).map((a) =>
1303
+ h("div", { class: "idea" }, h("span", { class: `lv-dot lv${a.level}` }), h("span", { text: a.statement }))))));
1304
+ }
1305
+ main.append(is);
1306
+ }
1307
+
1308
  // attempt history
1309
  const hist = attemptsFor(sid);
1310
  const hs = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: attempts` }));
 
1327
  // ---------- chrome ----------
1328
  $("tab-practise").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "practise"; S.run = null; render(); });
1329
  $("tab-progress").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "progress"; S.run = null; render(); });
1330
+ $("app-fb").addEventListener("click", () => { S.appFb = !S.appFb; S.appFbOpening = S.appFb; render(); window.scrollTo(0, 0); });
1331
  $("tab-bank").addEventListener("click", () => { S.view = "bank"; S.run = null; render(); });
1332
  $("tab-tutor").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "tutor"; S.run = null; T.mastery = null; render(); });
1333
  $("who").addEventListener("click", () => { if (S.view === "test") return toast("Submit or leave the self-check first"); S.view = "practise"; S.picking = true; render(); });
1334
  function confirmLeave() { saveDraft(); toast("Your answers are kept on this device. Open the self-check again to carry on."); clearInterval(timerHandle); return true; }
1335
 
1336
+ try {
1337
+ const ro = new ResizeObserver(() => {
1338
+ const hd = document.querySelector("header.top"), dk = $("dock");
1339
+ document.documentElement.style.setProperty("--hdr-h", `${hd ? hd.getBoundingClientRect().height : 64}px`);
1340
+ document.documentElement.style.setProperty("--dock-h", `${dk && !dk.hidden ? dk.getBoundingClientRect().height : 0}px`);
1341
+ });
1342
+ ro.observe(document.querySelector("header.top")); ro.observe($("dock"));
1343
+ } catch {}
1344
  render();
1345
  connect().catch(() => { S.dbError = "unavailable"; S.ready = true; render(); });
1346
  })();
tools/build_quizzes.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate syllabus/igcse/quizzes/<chapter>.json files and publish one document per quiz.
2
+
3
+ Writes apps/selfcheck-space/data/sets/<quiz id>.json (and removes the old one-per-chapter
4
+ sets for chapters that now have quizzes). Exit code 1 on any validation error; nothing is
5
+ written for a chapter that fails.
6
+
7
+ Run from the project root: python apps/selfcheck-space/tools/build_quizzes.py
8
+ """
9
+ import json
10
+ import pathlib
11
+ import sys
12
+
13
+ import openpyxl
14
+
15
+ ROOT = pathlib.Path(__file__).resolve().parents[3]
16
+ SRC = ROOT / "syllabus" / "igcse" / "quizzes"
17
+ OUT = ROOT / "apps" / "selfcheck-space" / "data" / "sets"
18
+ KINDS = ("learn", "apply", "mixed")
19
+
20
+
21
+ def atom_statements(atoms_file):
22
+ wb = openpyxl.load_workbook(ROOT / atoms_file, read_only=True, data_only=True)
23
+ out = {}
24
+ for sheet, col in (("atoms", "statement"), ("misconceptions", "wrong belief")):
25
+ it = wb[sheet].iter_rows(values_only=True)
26
+ head = [str(c or "").strip().lower() for c in next(it)]
27
+ i_id, i_txt = head.index("id"), head.index(col)
28
+ for r in it:
29
+ if r and r[i_id]:
30
+ out[str(r[i_id]).strip()] = str(r[i_txt] or "").strip()
31
+ return out
32
+
33
+
34
+ def check_question(q, atoms, errs, where):
35
+ t = q.get("type")
36
+ if t not in ("mcq", "multi", "numeric", "short"):
37
+ errs.append(f"{where}: bad type {t}")
38
+ if t == "mcq" and not (0 <= int(q.get("answer", -1)) < len(q.get("options") or [])):
39
+ errs.append(f"{where}: mcq answer out of range")
40
+ if t == "multi" and not all(0 <= int(i) < len(q.get("options") or []) for i in q.get("answer") or []):
41
+ errs.append(f"{where}: multi answer out of range")
42
+ if t == "numeric" and not isinstance(q.get("answer"), (int, float)):
43
+ errs.append(f"{where}: numeric answer is not a number")
44
+ if not q.get("atom_ids"):
45
+ errs.append(f"{where}: no atom_ids")
46
+ for a in q.get("atom_ids", []) + ([q["misconception_id"]] if q.get("misconception_id") else []):
47
+ if a not in atoms:
48
+ errs.append(f"{where}: unknown atom {a}")
49
+
50
+
51
+ def main():
52
+ ok = True
53
+ for f in sorted(SRC.glob("*.json")):
54
+ c = json.loads(f.read_text(encoding="utf-8"))
55
+ atoms = atom_statements(c["atoms_file"])
56
+ errs, seen = [], set()
57
+ qz = sorted(c["quizzes"], key=lambda z: z["order"])
58
+ for n, z in enumerate(qz, 1):
59
+ w = z.get("id", f"quiz {n}")
60
+ if z.get("id") != f"{c['chapterId']}_q{n:02d}":
61
+ errs.append(f"{w}: id should be {c['chapterId']}_q{n:02d}")
62
+ if z.get("kind") not in KINDS:
63
+ errs.append(f"{w}: kind must be one of {KINDS}")
64
+ if not z.get("title") or len(z["title"]) > 40:
65
+ errs.append(f"{w}: title missing or over 40 characters")
66
+ qs = z.get("questions", [])
67
+ if not 5 <= len(qs) <= 8:
68
+ errs.append(f"{w}: {len(qs)} questions (need 5-8)")
69
+ marks = sum(q.get("marks", 1) for q in qs)
70
+ auto = sum(q.get("marks", 1) for q in qs if q.get("type") != "short")
71
+ if marks and auto / marks < 0.7:
72
+ errs.append(f"{w}: only {round(100 * auto / marks)}% auto-marked")
73
+ if sum(1 for q in qs if q.get("type") == "short") > 2:
74
+ errs.append(f"{w}: more than two short questions")
75
+ for q in qs:
76
+ if q["id"] in seen:
77
+ errs.append(f"{w}: question id {q['id']} used twice in the chapter")
78
+ seen.add(q["id"])
79
+ check_question(q, atoms, errs, f"{w}/{q['id']}")
80
+ if errs:
81
+ ok = False
82
+ print(f"INVALID {f.name}", *errs, sep="\n ")
83
+ continue
84
+ for old in OUT.glob(f"{c['chapterId']}*.json"):
85
+ old.unlink()
86
+ for n, z in enumerate(qz, 1):
87
+ used = {}
88
+ for q in z["questions"]:
89
+ for a in q["atom_ids"] + ([q["misconception_id"]] if q.get("misconception_id") else []):
90
+ used[a] = atoms.get(a, "")
91
+ marks = sum(q.get("marks", 1) for q in z["questions"])
92
+ doc = {"id": z["id"], "chapterId": c["chapterId"], "subject": c["subject"], "code": c["code"],
93
+ "chapter": c["chapter"], "quizNo": n, "quizCount": len(qz), "order": n, "title": z["title"],
94
+ "kind": z["kind"], "intro": z.get("intro", ""), "minutes": max(5, min(12, marks)),
95
+ "active": True, "questions": z["questions"], "atoms": used}
96
+ (OUT / f"{z['id']}.json").write_text(json.dumps(doc, ensure_ascii=False), encoding="utf-8")
97
+ print(f"OK {c['chapterId']}: {len(qz)} quizzes, {len(seen)} questions, "
98
+ + ", ".join(f"{z['title']} ({len(z['questions'])})" for z in qz))
99
+ sys.exit(0 if ok else 1)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()