stepwise / static /index.html
Ashish-K's picture
Reminders: web push when she leaves a quiz or the tutor is waiting; app manifest and icons
95be3b8 verified
Raw History Blame Contribute Delete
229 kB
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"> <meta name="robots" content="noindex"> <title>StepWise Self-Checks</title> <link rel="manifest" href="manifest.webmanifest"> <meta name="theme-color" content="#2f5bd3"> <link rel="apple-touch-icon" href="icon-192.png"> <link rel="icon" type="image/png" href="icon-192.png"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:ital,wght@0,400;0,700;1,400&family=Familjen+Grotesk:wght@500;600;700&family=JetBrains+Mono:wght@400;600&display=swap"> <style> html { -webkit-text-size-adjust: 100%; } body { margin: 0; } [hidden] { display: none !important; } /* Layout: a squared exercise-book page. One column of work, a header strip with the student's name, results shown as marks in the margin. */ :root { --paper: #f3f5f2; --sheet: #ffffff; --grid: #e3e8e2; --ink: #1d2738; --ink-soft: #5b6577; --rule: #d5dbd3; --accent: #2f5bd3; --accent-ink: #ffffff; --accent-wash: #e6ecfb; --good: #1f7a4d; --good-wash: #e2f3ea; --warn: #9a6a00; --warn-wash: #fbf1d6; --bad: #b3332b; --bad-wash: #fbe5e3; --font-display: "Familjen Grotesk", "Segoe UI", system-ui, sans-serif; --font-body: "Atkinson Hyperlegible", "Segoe UI", system-ui, sans-serif; --font-data: "JetBrains Mono", ui-monospace, "Cascadia Mono", Consolas, monospace; --radius: 10px; } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5; --rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44; --good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f; --bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark; } } :root[data-theme="dark"] { --paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5; --rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44; --good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f; --bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark; } * { box-sizing: border-box; } body { background-color: var(--paper); background-image: linear-gradient(var(--grid) 1px, transparent 1px), linear-gradient(90deg, var(--grid) 1px, transparent 1px); background-size: 24px 24px; color: var(--ink); font-family: var(--font-body); font-size: 16px; line-height: 1.55; padding-inline: 16px; padding-block: 0 calc(var(--dock-h, 0px) + 32px); } .wrap { max-width: 1120px; margin: 0 auto; } h1, h2, h3 { font-family: var(--font-display); text-wrap: balance; margin: 0; line-height: 1.2; } h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.01em; } h2 { font-size: 1.25rem; font-weight: 600; } h3 { font-size: 1.05rem; font-weight: 600; } p { margin: 0; } .muted { color: var(--ink-soft); } .mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; } .label { font-family: var(--font-display); font-size: 0.75rem; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-soft); } header.top { position: sticky; top: env(safe-area-inset-top, 0px); z-index: 5; background: color-mix(in srgb, var(--paper) 92%, transparent); backdrop-filter: blur(6px); border-bottom: 1px solid var(--rule); margin-inline: -16px; padding: 12px 16px; } header.top .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; } @media (max-width: 720px) { .brand .tag { display: none; } } .brand { display: flex; align-items: baseline; gap: 10px; margin-right: auto; } .brand .tag { font-family: var(--font-data); font-size: 0.75rem; color: var(--ink-soft); } nav.tabs { display: flex; gap: 4px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 999px; padding: 3px; } nav.tabs button { border: 0; background: transparent; color: var(--ink-soft); font: 600 0.9rem var(--font-display); padding: 6px 14px; border-radius: 999px; cursor: pointer; } nav.tabs button[aria-pressed="true"] { background: var(--ink); color: var(--paper); } nav.tabs button { display: inline-flex; align-items: center; gap: 6px; } nav.tabs .ic { font-size: 1rem; line-height: 1; } @media (max-width: 720px) { header.top { backdrop-filter: none; background: var(--paper); } /* a blur would trap the fixed bar inside the header */ nav#places { position: fixed; left: 0; right: 0; bottom: 0; z-index: 7; border-radius: 0; border: 0; border-top: 1px solid var(--rule); justify-content: space-around; padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--sheet); } nav#places button { flex: 1; flex-direction: column; gap: 2px; font-size: .72rem; padding: 6px 2px; border-radius: 12px; } nav#places .ic { font-size: 1.3rem; } body:not(.in-chat):not(.in-quiz) .wrap { padding-bottom: 76px; } body.in-chat nav#places, body.in-quiz nav#places { display: none; } } .prog-list { display: grid; gap: 6px; } .prog-row { display: grid; grid-template-columns: 1fr auto; gap: 4px 10px; align-items: center; text-align: left; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; background: var(--paper); color: var(--ink); font: inherit; cursor: pointer; } .prog-row:hover { border-color: var(--accent); } .prog-row .prog-bar { grid-column: 1 / -1; height: 6px; border-radius: 99px; background: var(--rule); overflow: hidden; } .prog-row .prog-bar span { display: block; height: 100%; background: var(--accent); } .chat-group { margin-top: 14px; } .stat-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 8px 0 12px; } @media (max-width: 520px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } } .stat { border: 1px solid var(--rule); border-radius: 10px; padding: 10px; display: grid; gap: 2px; text-align: center; background: var(--paper); } .stat strong { font-size: 1.5rem; } .trend { font-size: .75rem; font-weight: 600; } .trend.up { color: var(--good); } .trend.down { color: var(--ink-soft); } .chart { margin: 6px 0 12px; } .day-bars { display: flex; align-items: flex-end; gap: 3px; height: 120px; padding-top: 16px; border-bottom: 1px solid var(--rule); } .day-bars .day { flex: 1; height: 100%; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; position: relative; min-width: 0; } .day-bars .bar { width: 100%; max-width: 28px; background: var(--accent); border-radius: 4px 4px 0 0; min-height: 2px; } .day-bars .dot { position: absolute; top: -14px; font-size: .7rem; font-weight: 700; color: var(--good); } .day-bars .lbl { position: absolute; bottom: -18px; font-size: .65rem; color: var(--ink-soft); white-space: nowrap; } .chart { padding-bottom: 18px; } .idea-list ul, .report-extra { margin: 4px 0 10px; padding-left: 20px; display: grid; gap: 4px; } .period { flex-wrap: wrap; } .period-box { display: grid; gap: 8px; margin-bottom: 8px; } .coach .bubble { margin: 8px 0; } .note { border-left: 4px solid var(--accent); padding: 4px 12px; margin: 6px 0; } .note-text { font-size: 1.1rem; margin: 4px 0 8px; } .note-form { display: grid; gap: 8px; margin: 8px 0; } .note-form textarea { font: inherit; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 8px; background: var(--sheet); color: var(--ink); } .note-form .btn { justify-self: start; } .kid-chips { margin: 4px 0 10px; } .chat-log-row { display: block !important; border-top: 0 !important; } .nudge { border: 2px solid var(--accent); border-radius: 12px; padding: 12px 14px; background: var(--sheet); display: grid; gap: 8px; animation: nudge-in .3s ease-out; } .nudge p { margin: 0; } @keyframes nudge-in { from { transform: translateY(6px); opacity: 0; } to { transform: none; opacity: 1; } } .stay-hint { margin: 0 0 8px; } .focus-bar { height: 8px; border-radius: 4px; background: var(--rule); overflow: hidden; margin: 4px 0 6px; } .focus-bar span { display: block; height: 100%; background: var(--accent); } .kid-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; margin: 0 0 12px; } .kid-card { display: grid; gap: 4px; text-align: left; padding: 14px 16px; border: 2px solid var(--rule); border-radius: 12px; background: var(--sheet); color: var(--ink); font: inherit; cursor: pointer; } .kid-card.on { border-color: var(--accent); } .kid-card strong { font-size: 1.15rem; } .chat-log { display: grid; gap: 8px; margin-top: 10px; max-height: 70vh; overflow: auto; padding: 4px; border-top: 1px solid var(--rule); } .topic-fold > summary { list-style: none; display: flex; gap: 12px; align-items: center; cursor: pointer; padding: 4px 0; } .topic-fold > summary::-webkit-details-marker { display: none; } .topic-fold > summary::after { content: "▾"; margin-left: auto; color: var(--ink-soft); transition: transform 120ms; font-size: 1.4rem; padding: 0 6px; } .topic-fold:not([open]) > summary::after { transform: rotate(-90deg); } .topic-fold .topic-sum { display: grid; gap: 2px; } .topic-fold .topic-body { margin: 8px 0 4px 0; display: grid; gap: 10px; } .topic.current .topic-fold > summary strong { color: var(--accent); } .parts-list li.next { background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; padding: 6px; } details.more > summary { cursor: pointer; color: var(--ink-soft); font-size: .9rem; margin: 2px 0 6px; } .btn.small { padding: 6px 12px; font-size: .85rem; } .chat-strip { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; } .chat-strip > span { margin-right: auto; font-weight: 600; } .week-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; text-align: center; } .week-stats strong { display: block; font-size: 1.4rem; } .back-top { margin-bottom: 4px; } .who { display: flex; align-items: center; gap: 8px; } .who-chip { font: 600 0.9rem var(--font-display); padding: 6px 12px; border-radius: 999px; border: 1px dashed var(--rule); background: var(--sheet); color: var(--ink); cursor: pointer; } .who-chip.set { border-style: solid; border-color: var(--accent); } main { display: grid; gap: 20px; padding-top: 20px; } .sheet { background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 20px; display: grid; gap: 14px; min-width: 0; } .notice { border-left: 4px solid var(--warn); background: var(--warn-wash); padding: 12px 14px; border-radius: 6px; } .notice.bad { border-color: var(--bad); background: var(--bad-wash); } .notice.good { border-color: var(--good); background: var(--good-wash); } button.btn, a.btn { display: inline-block; text-decoration: none; font: 600 0.95rem var(--font-display); border-radius: 8px; padding: 10px 16px; cursor: pointer; border: 1px solid var(--ink); background: var(--ink); color: var(--paper); } button.btn.ghost, a.btn.ghost { background: transparent; color: var(--ink); border-color: var(--rule); } button.btn.accent { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } button.btn:disabled { opacity: 0.5; cursor: not-allowed; } button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible, label.opt:focus-within { outline: 3px solid var(--accent); outline-offset: 2px; } .students { display: flex; flex-wrap: wrap; gap: 10px; } .student { font: 600 1rem var(--font-display); padding: 12px 18px; border-radius: 10px; cursor: pointer; border: 1px solid var(--rule); background: var(--sheet); color: var(--ink); min-width: 120px; text-align: left; } .student[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-wash); } .add-student { display: flex; flex-wrap: wrap; gap: 8px; } .add-student input { flex: 1 1 180px; min-width: 0; } input[type="text"], input[type="number"], textarea, select { font: 1rem var(--font-body); color: var(--ink); background: var(--paper); border: 1px solid var(--rule); border-radius: 8px; padding: 10px 12px; } textarea { width: 100%; min-height: 110px; resize: vertical; } .sets { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; } .set-card { text-align: left; cursor: pointer; display: grid; gap: 8px; align-content: start; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 16px; color: var(--ink); font: inherit; } .set-card:hover { border-color: var(--accent); } .set-card .code { font-family: var(--font-data); font-size: 0.8rem; color: var(--ink-soft); } .set-card .meta { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 0.85rem; color: var(--ink-soft); } .pill { display: inline-flex; align-items: center; gap: 6px; font: 600 0.8rem var(--font-data); padding: 3px 9px; border-radius: 999px; background: var(--paper); border: 1px solid var(--rule); } .pill.good { background: var(--good-wash); color: var(--good); border-color: transparent; } .pill.warn { background: var(--warn-wash); color: var(--warn); border-color: transparent; } .pill.bad { background: var(--bad-wash); color: var(--bad); border-color: transparent; } .subject-head { display: flex; align-items: baseline; gap: 10px; margin-top: 4px; } .test-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; } .test-bar .timer { font: 600 1.1rem var(--font-data); } .q { display: grid; grid-template-columns: 52px 1fr; gap: 12px; padding-top: 16px; border-top: 1px solid var(--rule); } .q:first-of-type { border-top: 0; padding-top: 0; } .q .num { font: 700 1.05rem var(--font-data); color: var(--ink-soft); } .q .body { display: grid; gap: 10px; min-width: 0; } .q .prompt { white-space: pre-wrap; overflow-wrap: anywhere; } .q .marks { font: 600 0.8rem var(--font-data); color: var(--ink-soft); } .opts { display: grid; gap: 8px; } label.opt { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 8px; cursor: pointer; background: var(--paper); } label.opt input { margin-top: 4px; accent-color: var(--accent); } label.opt.right { border-color: var(--good); background: var(--good-wash); } label.opt.wrong { border-color: var(--bad); background: var(--bad-wash); } .numeric { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } .numeric input { width: 12rem; max-width: 100%; } .hint { font-size: 0.85rem; color: var(--ink-soft); } .verdict { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } .scheme { background: var(--paper); border: 1px solid var(--rule); border-radius: 8px; padding: 10px 12px; display: grid; gap: 6px; font-size: 0.95rem; } .selfmark { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .selfmark button { font: 600 0.9rem var(--font-data); min-width: 40px; padding: 6px 10px; border-radius: 6px; border: 1px solid var(--rule); background: var(--sheet); color: var(--ink); cursor: pointer; } .selfmark button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } .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); } .dock .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; } .dock .row .status { margin-right: auto; font-size: 0.9rem; color: var(--ink-soft); } .score-big { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; } .score-big .n { font: 700 2.4rem var(--font-data); } .bar { height: 10px; border-radius: 999px; background: var(--paper); border: 1px solid var(--rule); overflow: hidden; } .bar > span { display: block; height: 100%; background: var(--accent); } .bar.good > span { background: var(--good); } .bar.warn > span { background: var(--warn); } .bar.bad > span { background: var(--bad); } .table-wrap { overflow-x: auto; } table { border-collapse: collapse; width: 100%; font-size: 0.92rem; } th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--rule); vertical-align: top; } th { font: 600 0.75rem var(--font-display); letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); } td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-numeric: tabular-nums; white-space: nowrap; } .atom-row { display: grid; grid-template-columns: 1fr 120px 56px; gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--rule); } .atom-row .stmt { min-width: 0; overflow-wrap: anywhere; } .atom-row .id { font: 0.75rem var(--font-data); color: var(--ink-soft); } @media (max-width: 520px) { .q { grid-template-columns: 1fr; } .atom-row { grid-template-columns: 1fr 64px; } .atom-row .bar { display: none; } } .toast { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(84px + env(safe-area-inset-bottom, 0px)); background: var(--ink); color: var(--paper); padding: 10px 16px; border-radius: 8px; font: 600 0.95rem var(--font-display); z-index: 9; } .empty { display: grid; gap: 8px; padding: 8px 0; } /* tutor */ .lv-bar { display: flex; height: 10px; border-radius: 999px; overflow: hidden; border: 1px solid var(--rule); background: var(--paper); } .lv { display: block; height: 100%; } .lv0 { background: var(--rule); } .lv1 { background: #a9c4ef; } .lv2 { background: #6b98e0; } .lv3 { background: var(--accent); } .lv4 { background: var(--good); } .lv-dot { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 6px; vertical-align: -1px; } .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: 0.85rem; color: var(--ink-soft); } .set-card .students { gap: 8px; } .chat { gap: 12px; } .bubble { max-width: 88%; padding: 10px 14px; border-radius: 12px; display: grid; gap: 6px; min-width: 0; } .bubble p { white-space: pre-wrap; overflow-wrap: anywhere; } .bubble.tutor { background: var(--paper); border: 1px solid var(--rule); justify-self: start; border-top-left-radius: 4px; } .bubble.me { background: var(--accent-wash); justify-self: end; border-top-right-radius: 4px; } .bubble.system { background: var(--bad-wash); justify-self: center; } .chat.log { display: grid; gap: 10px; padding: 12px; background: var(--paper); border-radius: var(--radius); } .chat-row { width: 100%; } /* chat: header, its own scrolling message area, and the composer inside one panel */ body.in-chat { padding-block: 0; overflow: hidden; } body.in-chat .wrap { height: calc(100dvh - var(--hdr-h, 64px)); } body.in-chat main { height: 100%; padding-block: 12px; display: block; } .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; } .chat-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 12px 16px; border-bottom: 1px solid var(--rule); } .chat-head .title { margin-right: auto; min-width: 0; } .chat-head h2 { font-size: 1.05rem; } .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; } @media (prefers-reduced-motion: reduce) { .chat-scroll { scroll-behavior: auto; } } .chat-scroll .bubble { max-width: min(760px, 88%); } .chat-scroll .bubble.tutor { align-self: flex-start; } .chat-scroll .bubble.me { align-self: flex-end; } .chat-scroll .bubble.system { align-self: center; } .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; } .chat-composer .input-row { display: flex; gap: 8px; align-items: flex-end; } .chat-composer textarea { flex: 1; min-width: 0; min-height: 44px; max-height: 180px; resize: none; line-height: 1.45; background: var(--sheet); } .chat-composer .meta-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } .chat-composer .meta-row .selfmark { margin-right: auto; } .chat-composer .feel-row { margin: 6px 0 2px; } .chat-composer .feel-row button { font: 600 0.8rem var(--font-body, inherit); } .typing { display: inline-flex; gap: 4px; padding: 4px 0; } .typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-soft); opacity: 0.4; } @media (prefers-reduced-motion: no-preference) { .typing span { animation: blink 1.2s infinite; } .typing span:nth-child(2) { animation-delay: .2s; } .typing span:nth-child(3) { animation-delay: .4s; } @keyframes blink { 0%, 80%, 100% { opacity: .25; } 40% { opacity: .9; } } } .md { display: grid; gap: 8px; } .md p { white-space: normal; } .md ul, .md ol { margin: 0; padding-left: 1.3em; display: grid; gap: 3px; } .md code { font-family: var(--font-data); font-size: 0.9em; background: var(--paper); padding: 0 4px; border-radius: 4px; } .bubble-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; opacity: 0.6; } .bubble:hover .bubble-actions, .bubble-actions:focus-within { opacity: 1; } .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; } .react[aria-pressed="true"] { border-color: var(--good); color: var(--good); } .composer { display: grid; gap: 8px; width: 100%; } .chapter-card .lv-bar { margin-top: 4px; } .topic-path { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; } .topic { display: grid; grid-template-columns: 44px 1fr; gap: 14px; padding: 16px 0; border-top: 1px solid var(--rule); position: relative; } .topic:first-child { border-top: 0; padding-top: 4px; } .topic-num { width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; font: 700 1rem var(--font-display); background: var(--paper); border: 2px solid var(--rule); color: var(--ink-soft); } .topic.done .topic-num { background: var(--good); border-color: var(--good); color: #fff; } .topic.final .topic-num { border-style: dashed; } .topic-body { display: grid; gap: 8px; min-width: 0; } .topic:has(> .topic-fold) { display: block; } .topic-fold .topic-num { flex: 0 0 36px; } .topic-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .steps { list-style: none; margin: 0; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px 14px; border-bottom: 1px solid var(--rule); background: var(--paper); } .step { display: inline-flex; align-items: center; gap: 6px; font: 600 0.82rem var(--font-display); color: var(--ink-soft); } .step .dot { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: 0.75rem; border: 2px solid var(--rule); background: var(--sheet); } .step.done .dot { background: var(--good); border-color: var(--good); color: #fff; } .step.now { color: var(--ink); } .step.now .dot { border-color: var(--accent); color: var(--accent); } .summary-card { align-self: stretch; border: 2px solid var(--good); background: var(--good-wash); border-radius: var(--radius); padding: 14px 16px; display: grid; gap: 8px; } .summary-card ul { margin: 0; padding-left: 1.2em; } .back-link { display: block; margin-bottom: 6px; } /* quiz player */ .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); } .quizbar-top { display: flex; align-items: center; gap: 12px; } .quizbar-top .title { margin-right: auto; min-width: 0; } .quizbar-top h2 { font-size: 1.1rem; } .timer-box { display: grid; justify-items: end; line-height: 1.1; } .timer-box .timer { font-size: 1.35rem; } .timer.over { color: var(--warn); } .timer.good { color: var(--good); } .timer.warn { color: var(--warn); } .timer.bad { color: var(--bad); } .qnav { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 2px; scrollbar-width: thin; } .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; } .qchip.answered { background: var(--accent-wash); border-color: var(--accent-wash); } .qchip.marked::after { content: ""; position: absolute; top: 3px; right: 3px; width: 8px; height: 8px; border-radius: 50%; background: var(--warn); } .qchip.right { background: var(--good-wash); border-color: var(--good); color: var(--good); } .qchip.part { background: var(--warn-wash); border-color: var(--warn); color: var(--warn); } .qchip.wrong { background: var(--bad-wash); border-color: var(--bad); color: var(--bad); } .qchip.pending { border-style: dashed; border-color: var(--ink-soft); } .qchip.notlearnt { border-style: dotted; border-color: var(--ink-soft); color: var(--ink-soft); background: var(--paper); } .notlearnt-btn { margin-top: 10px; } .notlearnt-btn[aria-pressed="true"] { background: var(--warn-wash); color: var(--warn); border-color: var(--warn); } /* learning in parts (CHUNK_MODEL.md) */ .parts-bar { padding: 8px 16px; border-bottom: 1px solid var(--rule); background: var(--paper); display: grid; gap: 6px; } .parts-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } .part-dot { display: inline-flex; align-items: center; gap: 5px; font: 600 0.8rem var(--font-display); color: var(--ink-soft); } .part-dot .dot { width: 20px; height: 20px; border-radius: 6px; display: grid; place-items: center; font-size: 0.72rem; border: 2px solid var(--rule); background: var(--sheet); } .part-dot.learned .dot { background: var(--good); border-color: var(--good); color: #fff; } .part-dot.now { color: var(--ink); } .part-dot.now .dot { border-color: var(--accent); color: var(--accent); } .idea-chips { display: flex; flex-wrap: wrap; gap: 6px; } .idea-chip { font: 500 0.78rem var(--font-data); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--rule); background: var(--sheet); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .idea-chip.learning { background: var(--warn-wash); color: var(--warn); border-color: transparent; } .idea-chip.got { background: var(--good-wash); color: var(--good); border-color: transparent; } .idea-chip.following { background: var(--accent-wash); color: var(--accent); border-color: transparent; } .part-card { align-self: stretch; border: 2px solid var(--accent); background: var(--accent-wash); border-radius: var(--radius); padding: 14px 16px; display: grid; gap: 8px; } .part-card ul { margin: 0; padding-left: 1.2em; } .cheer { margin: 10px 0; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--rule); border-left: 6px solid var(--accent); background: var(--sheet); } .cheer strong { display: block; font-size: 1.1rem; margin-bottom: 4px; } .cheer p { margin: 0; } .cheer.good { border-left-color: #2e7d4f; } .cheer.warn { border-left-color: #b7791f; } .cheer.bad { border-left-color: var(--accent); } .cheer-line { font-style: italic; margin: 4px 0 8px; } .login { max-width: 460px; margin-inline: auto; } .chat-composer.read-only { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: space-between; } .login-form { display: grid; gap: 6px; margin: 12px 0; } .login-form label { font-weight: 600; margin-top: 6px; } .login-form input, .login-form select, .admin-user input[type=text] { font: inherit; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 8px; background: var(--sheet); color: var(--ink); } .login-form .btn { margin-top: 10px; justify-self: start; } .admin-user { display: grid; gap: 8px; padding: 6px 0 12px; } .admin-user .btn { justify-self: start; } .chat-list { list-style: none; margin: 8px 0; padding: 0; display: grid; gap: 8px; } .chat-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding: 8px 0; border-top: 1px solid var(--rule); } .parts-list { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 8px; } .parts-list li { display: grid; grid-template-columns: 26px 1fr; gap: 10px; align-items: start; } .parts-list .pnum { width: 24px; height: 24px; border-radius: 7px; display: grid; place-items: center; font: 700 0.75rem var(--font-data); border: 2px solid var(--rule); } .parts-list li.learned .pnum { background: var(--good); border-color: var(--good); color: #fff; } .parts-list .pbody { display: grid; gap: 4px; min-width: 0; } .parts-list .pbody .topic-actions { gap: 6px; } .qchip.current { outline: 3px solid var(--accent); outline-offset: 2px; } .qchip.mini { display: inline-block; min-width: 14px; width: 14px; height: 14px; border-radius: 4px; vertical-align: -2px; margin-right: 6px; cursor: default; } .qchip.mini.marked::after { top: 2px; right: 2px; width: 6px; height: 6px; } .qcard { gap: 16px; } .qcard-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; } .qcard-head .marks { margin-right: auto; } .qcard .prompt { font-size: 1.08rem; } .qcard-nav { display: flex; justify-content: space-between; gap: 10px; padding-top: 8px; border-top: 1px solid var(--rule); } .qflags { display: grid; gap: 8px; padding: 10px 12px; border-radius: 8px; background: var(--paper); } .qflag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } .qflag-row .hint { min-width: 150px; } .select-n { font: 700 0.8rem var(--font-display); letter-spacing: 0.06em; text-transform: uppercase; color: var(--accent); } .idea-ch { display: grid; gap: 8px; padding-top: 10px; border-top: 1px solid var(--rule); } .idea-list { display: grid; gap: 4px; font-size: 0.92rem; } .idea { display: flex; gap: 8px; align-items: baseline; } .composer textarea { min-height: 56px; } .composer-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: flex-end; } .composer-row .selfmark { margin-right: auto; } /* feedback */ .fb { display: grid; gap: 8px; } .fb-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } .fb-toggle { justify-self: start; background: none; border: 0; padding: 2px 0; color: var(--accent); font: 600 0.85rem var(--font-display); cursor: pointer; text-decoration: underline; text-underline-offset: 3px; } .fb textarea { min-height: 64px; } .fb-actions { display: flex; justify-content: flex-end; gap: 8px; } .fb-list { display: grid; gap: 8px; } .fb-item { border: 1px solid var(--rule); border-left: 4px solid var(--warn); border-radius: 8px; padding: 10px 12px; display: grid; gap: 6px; background: var(--sheet); } .fb-item.resolved { border-left-color: var(--good); opacity: 0.8; } .fb-excerpt { font-size: 0.9rem; color: var(--ink-soft); border-left: 2px solid var(--rule); padding-left: 8px; white-space: pre-wrap; overflow-wrap: anywhere; } .student.parent { border-style: dashed; } .fb-chip { border-style: solid; color: var(--accent); } .app-fb { border-color: var(--accent); } .fb-chip .short { display: none; } .timer { white-space: nowrap; } @media (max-width: 560px) { .fb-chip .long { display: none; } .fb-chip .short { display: inline; } header.top .row { gap: 8px; } .brand h1 { font-size: 1.1rem; } .quizbar { padding: 10px 12px; } .quizbar-top .label { display: none; } .timer-box .timer { font-size: 1.05rem; } .qchip { min-width: 36px; height: 36px; } } .opts-list { margin: 0; padding-left: 1.4em; display: grid; gap: 4px; } .opts-list li.right { color: var(--good); font-weight: 700; } /* home: carry on, review, subjects; subject page: units with a path of chapters */ .student { display: grid; gap: 2px; } .student .hint { font: 400 0.8rem var(--font-body); } .home-hello { display: grid; gap: 4px; padding: 4px 2px 0; } .home-hello h2 { font-size: 1.6rem; font-weight: 700; } .section-title { font-size: 1.1rem; margin: 0 0 10px; } .home-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 20px; } .next-card { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; } .next-card h3 { font-size: 1.3rem; } .q-line { font-style: italic; } .due-list { display: flex; flex-wrap: wrap; gap: 6px; } .subject-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: 14px; } .subject-card { text-align: left; cursor: pointer; display: grid; gap: 10px; align-content: start; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 16px; color: var(--ink); font: inherit; min-width: 0; } .subject-card:hover { border-color: var(--subj); } .subject-card.soon { cursor: default; border-style: dashed; } .subject-card .meta, .ch-card .meta { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 0.85rem; color: var(--ink-soft); align-items: center; } .subject-top { display: flex; gap: 12px; align-items: center; min-width: 0; } .subj-mark { width: 40px; height: 40px; border-radius: 10px; display: grid; place-items: center; font: 700 1.05rem var(--font-display); background: var(--subj); color: #fff; flex: none; } .subject-card .code, .ch-card .code { font-family: var(--font-data); font-size: 0.78rem; color: var(--ink-soft); } .unit-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; } .unit-num { font: 600 0.75rem var(--font-display); letter-spacing: 0.08em; text-transform: uppercase; color: var(--accent); } .ch-path { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; } .ch-stop { display: grid; grid-template-columns: 28px minmax(0, 1fr); gap: 12px; position: relative; } .ch-stop::before { content: ""; position: absolute; left: 13px; top: 42px; bottom: -26px; width: 2px; background: var(--rule); } .ch-stop:last-child::before { display: none; } .ch-dot { width: 28px; height: 28px; border-radius: 50%; margin-top: 14px; border: 2px solid var(--rule); background: var(--sheet); display: grid; place-items: center; font: 700 0.85rem var(--font-display); color: #fff; position: relative; z-index: 1; } .ch-stop.doing .ch-dot { border-color: var(--accent); background: var(--accent-wash); } .ch-stop.done .ch-dot { border-color: var(--good); background: var(--good); } .ch-card { text-align: left; cursor: pointer; display: grid; gap: 8px; background: var(--paper); border: 1px solid var(--rule); border-radius: var(--radius); padding: 14px 16px; color: var(--ink); font: inherit; min-width: 0; } .ch-card:hover { border-color: var(--accent); } .ch-top { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 10px; align-items: center; } .ch-top .pill { font: 600 0.78rem var(--font-display); white-space: normal; } .pill.accent { background: var(--accent-wash); color: var(--accent); border-color: transparent; } .ch-links { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } .kid-subjects { padding: 6px 4px 10px; display: grid; gap: 10px; margin: 0; min-width: 0; } details.fold { border: 1px solid var(--rule); border-radius: 8px; margin: 6px 0; background: var(--sheet); } details.fold > summary { cursor: pointer; padding: 10px 14px; list-style: none; display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; } details.fold > summary::-webkit-details-marker { display: none; } details.fold > summary::before { content: "▸"; color: var(--ink-soft); margin-right: 2px; } details.fold[open] > summary::before { content: "▾"; } details.fold > .fold-body, details.fold > .kid-subjects { padding: 0 12px 10px 22px; } .fold-body { display: grid; gap: 6px; } .quiz-row { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; text-align: left; padding: 8px 12px; border: 1px solid var(--rule); border-radius: 6px; background: var(--paper); color: var(--ink); font: inherit; cursor: pointer; } .quiz-row:hover { border-color: var(--accent); } .board-head { margin: 14px 0 4px; font: 600 .9rem var(--font-display); color: var(--ink-soft); text-transform: uppercase; letter-spacing: .04em; } .kid-subjects legend { font: 600 1rem var(--font-display); padding: 0 6px; } .board-row { display: grid; gap: 4px; } .subj-checks { display: flex; flex-wrap: wrap; gap: 6px 18px; } .subj-check { display: inline-flex; gap: 6px; align-items: center; cursor: pointer; } .subj-check input { accent-color: var(--accent); width: 18px; height: 18px; } @media (prefers-reduced-motion: no-preference) { .set-card, .student, .subject-card, .ch-card { transition: border-color 120ms ease, background-color 120ms ease; } } </style> </head> <body> <header class="top"> <div class="row"> <div class="brand"><h1>StepWise</h1><span class="tag" id="brand-tag"></span></div> <nav class="tabs" id="places" aria-label="Sections"> <button id="tab-practise" aria-pressed="true"><span class="ic" aria-hidden="true">🏠</span><span>Today</span></button> <button id="tab-subjects" aria-pressed="false"><span class="ic" aria-hidden="true">📚</span><span>Subjects</span></button> <button id="tab-chats" aria-pressed="false"><span class="ic" aria-hidden="true">💬</span><span>Chats</span></button> <button id="tab-tutor" aria-pressed="false" hidden>Tutor</button> <button id="tab-progress" aria-pressed="false"><span class="ic" aria-hidden="true">📈</span><span>Report</span></button> <button id="tab-bank" aria-pressed="false" hidden><span class="ic" aria-hidden="true">👪</span><span>Parent</span></button> </nav> <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> </div> </header> <div class="wrap"> <main id="main"> <section class="sheet"> <h2>Loading your self-checks</h2> <p class="muted">Loading your self-checks and results.</p> </section> </main> </div> <div id="dock" class="dock" hidden><div class="row" id="dock-row"></div></div> <div id="toast" class="toast" role="status" hidden></div> <script type="module"> import * as V from "./visuals/render.js"; const st = document.createElement("style"); st.textContent = V.CSS; document.head.append(st); window.StepVis = V; document.dispatchEvent(new Event("stepvis")); </script> <script> (() => { "use strict"; // ---------- tiny DOM helper (text only, never innerHTML for data) ---------- function h(tag, props, ...kids) { const el = document.createElement(tag); if (props) for (const [k, v] of Object.entries(props)) { if (v == null || v === false) continue; if (k === "class") el.className = v; else if (k === "text") el.textContent = v; else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); else el.setAttribute(k, v === true ? "" : v); } for (const kid of kids.flat()) { if (kid == null || kid === false) continue; el.append(kid instanceof Node ? kid : document.createTextNode(String(kid))); } return el; } const $ = (id) => document.getElementById(id); const store = { get(k) { try { return localStorage.getItem(k); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch {} }, del(k) { try { localStorage.removeItem(k); } catch {} }, }; // ---------- focus: counted while a quiz or tutor chat is open ---------- // "focused" = StepWise on screen and touched, scrolled or typed in within IDLE_MS; "away" = another app or tab, // screen off, or idle longer than that. "switches" = times the page was hidden. Shown on the Report. const FT = (() => { const IDLE_MS = 3 * 60 * 1000; const open = new Map(); // key -> { active, away, switches } in ms let lastTick = Date.now(), lastInput = Date.now(), wasHidden = document.hidden; function tick() { const t = Date.now(), dt = Math.max(0, t - lastTick); lastTick = t; const away = wasHidden || t - lastInput > IDLE_MS; for (const c of open.values()) { if (away) c.away += dt; else c.active += dt; } wasHidden = document.hidden; } const touch = () => { tick(); lastInput = Date.now(); }; for (const ev of ["pointerdown", "keydown", "wheel", "touchstart", "scroll", "pointermove"]) addEventListener(ev, touch, { passive: true, capture: true }); document.addEventListener("visibilitychange", () => { tick(); if (document.hidden) for (const c of open.values()) c.switches += 1; else lastInput = Date.now(); }); setInterval(tick, 5000); return { start(key, seed) { tick(); open.set(key, { active: (seed && seed.activeSec || 0) * 1000, away: (seed && seed.awaySec || 0) * 1000, switches: (seed && seed.switches) || 0 }); }, peek(key) { tick(); const c = open.get(key); return c ? { activeSec: Math.round(c.active / 1000), awaySec: Math.round(c.away / 1000), switches: c.switches } : null; }, take(key) { const v = this.peek(key); if (open.has(key)) open.set(key, { active: 0, away: 0, switches: 0 }); return v; }, stop(key) { const v = this.peek(key); open.delete(key); return v; }, }; })(); // ---------- alarm: two short beeps and a buzz on phones that support it ---------- const ALARM = (() => { let ctx = null; const unlock = () => { try { ctx = ctx || new (window.AudioContext || window.webkitAudioContext)(); if (ctx.state === "suspended") ctx.resume(); } catch {} }; addEventListener("pointerdown", unlock, { capture: true, passive: true }); addEventListener("keydown", unlock, { capture: true }); return { ring() { try { if (navigator.vibrate) navigator.vibrate([250, 120, 250]); } catch {} if (!ctx) return; try { for (const [at, f] of [[0, 880], [0.28, 660], [0.56, 880]]) { const o = ctx.createOscillator(), g = ctx.createGain(); o.frequency.value = f; o.type = "sine"; o.connect(g); g.connect(ctx.destination); const t0 = ctx.currentTime + at; g.gain.setValueAtTime(0.0001, t0); g.gain.exponentialRampToValueAtTime(0.3, t0 + 0.02); g.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.22); o.start(t0); o.stop(t0 + 0.25); } } catch {} }, }; })(); const BASE_TITLE = document.title; // ---------- reminders (notifications) ---------- const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); const isStandalone = matchMedia("(display-mode: standalone)").matches || navigator.standalone === true; const PUSHS = { key: null, on: false, checked: false, busy: false }; let swReg = null; if ("serviceWorker" in navigator) navigator.serviceWorker.register("sw.js", { scope: "./" }).then((r) => { swReg = r; }).catch(() => {}); function pushSupported() { return "serviceWorker" in navigator && "PushManager" in window && "Notification" in window; } function b64uToBytes(s) { const p = "=".repeat((4 - s.length % 4) % 4); const b = atob((s + p).replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(b, (c) => c.charCodeAt(0)); } async function pushCheck() { if (PUSHS.checked) return; PUSHS.checked = true; try { const r = await api("api/push/key"); PUSHS.key = r.key; PUSHS.on = r.on; if (pushSupported() && Notification.permission === "granted") { // this device may be subscribed even if another isn't const reg = swReg || await navigator.serviceWorker.ready; const sub = await reg.pushManager.getSubscription(); PUSHS.here = !!sub; if (sub) api("api/push/subscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) }).catch(() => {}); } } catch {} render(); } async function pushEnable() { if (PUSHS.busy) return; PUSHS.busy = true; render(); try { const perm = await Notification.requestPermission(); if (perm !== "granted") { toast("Reminders need notifications allowed"); return; } const reg = swReg || await navigator.serviceWorker.ready; const sub = (await reg.pushManager.getSubscription()) || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uToBytes(PUSHS.key) }); await api("api/push/subscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) }); PUSHS.on = true; PUSHS.here = true; await api("api/push/test", { method: "POST", body: "{}" }).catch(() => {}); toast("Reminders are on"); } catch (e) { toast(e.message || "Couldn't turn on reminders"); } finally { PUSHS.busy = false; render(); } } async function pushDisable() { try { const reg = swReg || await navigator.serviceWorker.ready; const sub = await reg.pushManager.getSubscription(); if (sub) { await api("api/push/unsubscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) }); await sub.unsubscribe(); } PUSHS.here = false; toast("Reminders are off on this device"); } catch (e) { toast(e.message); } render(); } // compact: the Today card (only while not set up on this device); full: the Account page function remindersCard(full) { if (!S.me || S.me.role !== "child") return null; pushCheck(); if (!PUSHS.checked || !PUSHS.key) return null; const here = !!PUSHS.here; // subscribed on this device if (!full && here) return null; const box = h("section", { class: "sheet reminders" }, h("h3", { text: "🔔 Reminders" })); if (isIOS && !isStandalone) { box.append(h("p", { text: "On iPhone or iPad, reminders work once StepWise is on your home screen:" }), h("ol", null, h("li", { text: "Tap the Share button (the square with an arrow) in Safari." }), h("li", { text: "Choose “Add to Home Screen”." }), h("li", { text: "Open StepWise from the new home-screen icon and turn reminders on here." }))); } else if (!pushSupported()) { box.append(h("p", { class: "muted", text: "This browser can't show reminders. Try Chrome, Edge or Safari." })); } else if (Notification.permission === "denied") { box.append(h("p", { class: "muted", text: "Notifications are blocked for StepWise. Allow them in your browser's site settings, then come back here." })); } else if (here) { box.append(h("p", { text: "On for this device. If you leave a quiz or the tutor is waiting for your reply, StepWise will send you a notification." }), h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: "Send a test", onclick: () => api("api/push/test", { method: "POST", body: "{}" }).then(() => toast("Sent")).catch((e) => toast(e.message)) }), h("button", { class: "btn ghost", text: "Turn off on this device", onclick: pushDisable }))); } else { box.append(h("p", { text: "Get a notification if you leave a quiz, or when the tutor is waiting for your reply." }), h("button", { class: "btn accent", disabled: PUSHS.busy, text: PUSHS.busy ? "Turning on…" : "🔔 Turn on reminders", onclick: pushEnable })); } return box; } function awayPing(body) { if (!S.me || S.me.role !== "child") return; const tok = store.get("sw.token"); if (!tok) return; try { fetch("api/away", { method: "POST", keepalive: true, headers: { "Content-Type": "application/json", Authorization: `Bearer ${tok}` }, body: JSON.stringify(body) }).catch(() => {}); } catch {} } let toastTimer = null; function toast(msg) { const t = $("toast"); t.textContent = msg; t.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.hidden = true; }, 2600); } // ---------- state ---------- const S = { ready: false, feedback: [], readOnly: false, dbError: "", pinError: "", sets: new Map(), students: new Map(), attempts: [], view: "practise", // practise | test | review | progress studentId: null, progressStudent: null, run: null, // active test or review }; // ---------- marking ---------- const SUP = { "⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁻":"-","⁺":"+" }; function parseNumber(raw) { if (raw == null) return NaN; let s = String(raw).trim().replace(/^(₹|Rs\.?|INR|US\$|\$)\s*/i, "").replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-"); // superscript powers of ten only (10²³ -> 10^23); a unit like dm³ is left alone s = s.replace(/10([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)/g, (m, g) => "10^" + [...g].map((c) => SUP[c]).join("")); // number, optional "x 10^n" or "e n", optional trailing unit starting with a letter, µ, ° or % const m = s.match(/^([-+]?(?:\d+\.?\d*|\.\d+))(?:[x×*X]10\^?([-+]?\d+)|[eE]([-+]?\d+))?(?:[a-zA-Zµ°%].*)?$/); if (!m) return NaN; const exp = m[2] != null ? m[2] : m[3]; return parseFloat(m[1]) * (exp != null ? Math.pow(10, parseInt(exp, 10)) : 1); } // Significant figures in what the student typed (mantissa only; trailing zeros of a whole number don't count). function sigFigs(raw) { if (raw == null) return 0; let s = String(raw).replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-"); const m = s.match(/^[-+]?(\d*\.?\d+|\d+\.)/); if (!m) return 0; let t = m[1]; if (t.includes(".")) { t = t.replace(".", "").replace(/^0+/, ""); return t.length; } t = t.replace(/^0+/, "").replace(/0+$/, ""); return t.length; } // Trailing zeros in a whole number are ambiguous: "20" may be 1 or 2 s.f. Returns every reading. function sigFigOptions(raw) { const lo = sigFigs(raw); const m = String(raw ?? "").replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-").match(/^[-+]?(\d+)(?![.\d])/); const hi = m ? Math.max(lo, m[1].replace(/^0+/, "").length) : lo; const out = []; for (let k = lo; k <= hi; k++) out.push(k); return out; } function markQuestion(q, resp) { const max = Number(q.marks) || 1; if (q.type === "mcq") { if (resp == null) return { got: 0, max, auto: true, right: false }; const right = Number(resp) === Number(q.answer); return { got: right ? max : 0, max, auto: true, right }; } if (q.type === "multi") { const want = new Set((q.answer || []).map(Number)); const picked = new Set((resp || []).map(Number)); let hits = 0, wrong = 0; picked.forEach((i) => (want.has(i) ? hits++ : wrong++)); // Cambridge "tick N boxes": more than N ticked scores 0; otherwise marks rise with each correct tick. const exact = hits === want.size && wrong === 0; const got = picked.size > want.size ? 0 : Math.floor(max * hits / Math.max(1, want.size)); return { got, max, auto: true, right: exact, over: picked.size > want.size }; } if (q.type === "numeric") { if (resp != null) resp = String(resp).replace(/^\s*[x×X]\s*(?=[\d.])/, ""); // magnification written "×1200" const v0 = parseNumber(resp); // sign_optional: Cambridge accepts PED/PES with or without the minus sign const v = q.sign_optional && Number.isFinite(v0) && Number(q.answer) !== 0 && Math.sign(v0) === -Math.sign(Number(q.answer)) ? -v0 : v0; const a = Number(q.answer); const tol = q.tolerance != null ? Number(q.tolerance) : 0.01; const within = Number.isFinite(v) && (a === 0 ? Math.abs(v) < 1e-9 : Math.abs(v - a) <= Math.abs(a) * tol + 1e-12); // Also right: the correct answer rounded to the precision the student used (at least 2 s.f.), // e.g. 25 for 24.5 N, or 10.0 for 10.048 cm³. // A question can insist on the precision it asks for: dp = decimal places, min_sf = significant figures. const dps = (() => { const m = String(resp ?? "").replace(/\s+/g, "").replace(/−/g, "-").match(/^[-+]?\d*\.(\d+)/); return m ? m[1].length : 0; })(); const sfs = sigFigOptions(resp); const rounded = Number.isFinite(v) && a !== 0 && sfs.some((k) => k >= 2 && (q.min_sf == null || k >= q.min_sf) && Math.abs(Number(a.toPrecision(k)) - v) <= Math.abs(v) * 1e-9); let right = q.exact ? Number.isFinite(v) && Math.abs(v - a) < 1e-9 : within || rounded; // accounts: the exact figure only // Exact precision asked ("give your answer to 2 s.f." / "to 1 d.p."): only the correctly rounded // value at exactly that precision is right, as in Cambridge marking. if (q.sf != null || q.dp != null) { const target = q.sf != null ? Number(a.toPrecision(q.sf)) : Number(a.toFixed(q.dp)); const precOk = q.sf != null ? sfs.includes(q.sf) : dps === q.dp; right = Number.isFinite(v) && precOk && Math.abs(v - target) <= Math.abs(target) * 1e-9 + 1e-12; } return { got: right ? max : 0, max, auto: true, right, parsed: Number.isFinite(v) ? v : null }; } return { got: null, max, auto: false, right: null }; // short: self-marked } function pct(got, max) { return max > 0 ? Math.round((100 * got) / max) : 0; } function band(p) { return p >= 75 ? "good" : p >= 50 ? "warn" : "bad"; } function fmtNum(x) { if (!Number.isFinite(x)) return String(x); const ax = Math.abs(x); if (ax !== 0 && (ax >= 1e5 || ax < 1e-3)) { const [m, e] = x.toExponential(3).split("e"); return `${parseFloat(m)} × 10^${parseInt(e, 10)}`; } return String(Math.round(x * 1e6) / 1e6); } function fmtDate(iso) { try { return new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); } catch { return iso || ""; } } // ---------- data access ---------- function setTitle(set) { return `${set.subject || ""} · ${set.chapter || set.id}`; } function attemptsFor(studentId, setId) { return S.attempts.filter((a) => a.studentId === studentId && (!setId || a.setId === setId)) .sort((a, b) => String(b.submittedAt).localeCompare(String(a.submittedAt))); } function latestPerSet(studentId) { const m = new Map(); for (const a of attemptsFor(studentId)) if (!m.has(a.setId)) m.set(a.setId, a); return m; } async function api(path, opts) { const tok = store.get("sw.token"); const res = await fetch(path, { ...(opts || {}), headers: { "Content-Type": "application/json", ...(tok ? { Authorization: `Bearer ${tok}` } : {}), ...((opts && opts.headers) || {}) } }); let body = null; try { body = await res.json(); } catch {} if (res.status === 401 && path !== "api/login" && tok) { signOut("Please log in again."); } if (!res.ok) { const err = new Error((body && body.detail) || `Request failed (${res.status})`); err.status = res.status; throw err; } return body; } // ---------- logins ---------- function signOut(msg) { store.del("sw.token"); store.del("sw.student"); S.me = null; S.studentId = null; S.view = "practise"; S.picking = false; S.chapterId = null; S.subjectCode = null; S.run = null; S.students = new Map(); S.attempts = []; S.feedback = []; S.myChats = {}; S.activity = null; A.data = null; T.sessionId = null; T.msgs = []; T.mastery = null; document.body.classList.remove("in-chat"); S.replaceRoute = true; render(); if (msg) toast(msg); } function renderLogin(main) { const user = h("input", { type: "text", id: "login-user", autocomplete: "username", autocapitalize: "none", spellcheck: "false", required: true }); const pass = h("input", { type: "password", id: "login-pass", autocomplete: "current-password", required: true }); const err = h("p", { class: "hint", role: "alert" }); const btn = h("button", { class: "btn accent", type: "submit", text: "Log in" }); main.append(h("section", { class: "sheet login" }, h("h2", { text: "Log in to StepWise" }), h("p", { class: "muted", text: "Use the username and password you were given. You stay logged in on this device until you log out." }), h("form", { class: "login-form", onsubmit: async (e) => { e.preventDefault(); btn.disabled = true; err.textContent = ""; try { const r = await api("api/login", { method: "POST", body: JSON.stringify({ username: user.value.trim(), password: pass.value }) }); store.set("sw.token", r.token); S.me = r.me; S.ready = false; render(); await connect(); } catch (x) { err.textContent = x.message; btn.disabled = false; pass.value = ""; pass.focus(); } } }, h("label", { for: "login-user", text: "Username" }), user, h("label", { for: "login-pass", text: "Password" }), pass, err, btn))); requestAnimationFrame(() => user.focus()); } function renderAccount(main) { const me = S.me; const forced = me.mustChange; const old = h("input", { type: "password", id: "pw-old", autocomplete: "current-password", required: true }); const nw = h("input", { type: "password", id: "pw-new", autocomplete: "new-password", minlength: "6", required: true }); const again = h("input", { type: "password", id: "pw-again", autocomplete: "new-password", minlength: "6", required: true }); const err = h("p", { class: "hint", role: "alert" }); const roleName = { admin: "Admin", parent: "Parent", child: "Student" }[me.role] || me.role; main.append(h("section", { class: `sheet ${forced ? "login" : "account"}` }, h("h2", { text: forced ? `Welcome, ${me.name}! Choose your own password` : "👤 Your account" }), h("p", { class: "muted", text: forced ? "You logged in with a starter password. Pick one only you know (at least 6 characters)." : `${me.name} · ${roleName} · username ${me.username}` }), h("form", { class: "login-form", onsubmit: async (e) => { e.preventDefault(); err.textContent = ""; if (nw.value !== again.value) { err.textContent = "The two new passwords don't match."; return; } try { const r = await api("api/me/password", { method: "POST", body: JSON.stringify({ old: old.value, new: nw.value }) }); store.set("sw.token", r.token); S.me = r.me; S.view = me.role === "child" ? "practise" : "bank"; toast("Password changed"); if (S.pendingRoute) { const to = S.pendingRoute; S.pendingRoute = null; return applyRoute(to); } render(); } catch (x) { err.textContent = x.message; } } }, h("label", { for: "pw-old", text: forced ? "Starter password" : "Current password" }), old, h("label", { for: "pw-new", text: "New password" }), nw, h("label", { for: "pw-again", text: "New password again" }), again, err, h("button", { class: "btn accent", type: "submit", text: "Save new password" })), !forced ? remindersCard(true) : null, h("div", { class: "students" }, !forced ? h("button", { class: "btn ghost", text: "Back", onclick: () => { S.view = me.role === "child" ? "practise" : "bank"; render(); } }) : null, h("button", { class: "btn ghost", text: "Log out", onclick: () => signOut("Logged out") })))); } async function connect() { if (!store.get("sw.token")) { S.me = null; S.ready = true; render(); return; } try { const st = await api("api/state"); S.me = st.me; S.notes = st.notes || []; S.family = st.family || {}; S.reportsUnread = st.reportsUnread || 0; S.sets = new Map(st.sets.map((s) => [s.id, s])); S.students = new Map(st.students.map((s) => [s.id, s])); S.attempts = st.attempts; S.feedback = st.feedback || []; S.catalog = st.catalog || { boards: [], subjects: [] }; if (S.me.role === "child") S.studentId = S.me.studentId; else if (!S.studentId || (S.studentId !== "parent" && !S.students.has(S.studentId))) S.studentId = "parent"; S.dbError = ""; S.pinError = ""; try { S.tutorOn = (await api("api/tutor/status")).enabled; } catch { S.tutorOn = false; } try { S.topics = await api("api/topics"); } catch { S.topics = {}; } } catch (e) { if (e.status === 401) return; // signOut has already shown the login S.dbError = "unavailable"; } S.ready = true; if (S.me && !routeReady) { // first load: open the screen in the address, if any routeReady = true; const deep = location.hash && !["#/login", "#/today", "#/account"].includes(location.hash); if (deep && S.me.mustChange) S.pendingRoute = location.hash; // open it once they've chosen a password else if (deep) return applyRoute(location.hash); S.replaceRoute = true; } render(); } async function addStudent(name, stay = false) { const clean = name.trim().replace(/\s+/g, " ").slice(0, 40); if (!clean) return; if ([...S.students.values()].some((s) => (s.name || "").toLowerCase() === clean.toLowerCase())) { toast(`${clean} is already on the list`); return; } try { const s = await api("api/students", { method: "POST", body: JSON.stringify({ name: clean }) }); let st = s; if (stay) { // added by the parent: start with no subjects ticked and open the child's panel to choose try { st = await api(`api/students/${encodeURIComponent(s.id)}/profile`, { method: "POST", body: JSON.stringify({ subjects: [] }) }); } catch { /* keep the default */ } B.open.add(`kid:${s.id}`); } S.students.set(s.id, st); if (!stay) { S.studentId = s.id; store.set("sw.student", s.id); } toast(stay ? `Added ${clean}: now tick ${clean}'s subjects` : `Added ${clean}`); render(); } catch (e) { handleWriteError(e); } } function handleWriteError(e) { toast((e && e.message) || "Couldn't save just now. Check your connection and try again."); } // ---------- test flow ---------- function startTest(setId) { const set = S.sets.get(setId); if (!set || !S.studentId) return; const key = `sw.draft.${S.studentId}.${setId}`; let draft = null; try { draft = JSON.parse(store.get(key) || "null"); } catch {} S.chapterId = set.chapterId || set.id; S.run = { setId, key, phase: "test", startedAt: draft && draft.startedAt ? draft.startedAt : new Date().toISOString(), responses: draft && draft.responses ? draft.responses : {}, self: {}, results: null, saved: false, idx: 0, marked: new Set(), notLearnt: new Set(draft && draft.notLearnt ? draft.notLearnt : []), }; FT.start("quiz", draft && draft.focus); S.run.leaves = (draft && draft.leaves) || 0; S.view = "test"; render(); window.scrollTo(0, 0); tickTimer(); if (draft && draft.leftAt) quizReturned(draft.leftAt); // she closed or reloaded the page mid-quiz } function saveDraft() { const r = S.run; if (!r || r.phase !== "test") return; store.set(r.key, JSON.stringify({ startedAt: r.startedAt, responses: r.responses, notLearnt: [...r.notLearnt], focus: FT.peek("quiz"), leaves: r.leaves || 0, leftAt: r.leftAt || null })); } let timerHandle = null; function tickTimer() { clearInterval(timerHandle); timerHandle = setInterval(() => { const el = $("timer"); if (!el || !S.run || S.run.phase !== "test") { clearInterval(timerHandle); return; } el.textContent = elapsedLabel(); const set = S.sets.get(S.run.setId); el.classList.toggle("over", elapsedSec() > (Number(set && set.minutes) || 0) * 60); }, 1000); } function elapsedSec() { return S.run ? Math.max(0, Math.round((Date.now() - Date.parse(S.run.startedAt)) / 1000)) : 0; } function elapsedLabel() { const s = elapsedSec(); const set = S.sets.get(S.run.setId); const lim = (Number(set && set.minutes) || 0) * 60; const mm = String(Math.floor(s / 60)).padStart(2, "0"), ss = String(s % 60).padStart(2, "0"); return lim ? `${mm}:${ss} / ${String(lim / 60).padStart(2, "0")}:00` : `${mm}:${ss}`; } // Leaving the quiz screen (another app or tab, screen off, closing the page) submits the quiz. // A first, short slip (back within QUIZ_GRACE_MS) only warns; after that, leaving submits. const QUIZ_GRACE_MS = 15000; const inQuiz = () => S.run && S.run.phase === "test" && S.view === "test"; let wakeLock = null; async function keepAwake(on) { // stop the phone locking itself mid-quiz (that would count as leaving) try { if (on && !wakeLock && navigator.wakeLock && !document.hidden) { wakeLock = await navigator.wakeLock.request("screen"); wakeLock.addEventListener("release", () => { wakeLock = null; }); } if (!on && wakeLock) { await wakeLock.release(); wakeLock = null; } } catch { wakeLock = null; } } setInterval(() => keepAwake(inQuiz()), 5000); function quizLeft() { const r = S.run; r.leftAt = Date.now(); r.leaves = (r.leaves || 0) + 1; saveDraft(); if (r.leaves === 1) awayPing({ kind: "quiz" }); } function quizReturned(leftAt) { const r = S.run; if (!r || r.phase !== "test") return; const away = Date.now() - leftAt; r.leftAt = null; if (r.leaves <= 1 && away < QUIZ_GRACE_MS) { r.warning = true; saveDraft(); render(); ALARM.ring(); return; } r.leftQuiz = true; submitTest(); } document.addEventListener("visibilitychange", () => { if (!inQuiz()) return; if (document.hidden) quizLeft(); else { keepAwake(true); if (S.run.leftAt) quizReturned(S.run.leftAt); } }); addEventListener("beforeunload", (e) => { if (inQuiz()) { e.preventDefault(); e.returnValue = ""; } }); function submitTest() { const r = S.run; const set = S.sets.get(r.setId); r.results = {}; for (const q of set.questions || []) r.results[q.id] = r.notLearnt.has(q.id) ? { got: 0, max: Number(q.marks) || 1, auto: true, right: false, notLearnt: true } : markQuestion(q, r.responses[q.id]); r.phase = "review"; r.submittedAt = new Date().toISOString(); r.durationSec = elapsedSec(); r.focus = FT.stop("quiz"); clearInterval(timerHandle); S.view = "review"; const firstShort = (set.questions || []).findIndex((q) => !r.results[q.id].auto); r.idx = firstShort >= 0 ? firstShort : 0; render(); window.scrollTo(0, 0); if (reviewTotals().pendingSelf === 0) saveAttempt(); } // ---------- encouragement after a quiz or a learnt part, matched to how it went ---------- const pick = (arr, seed) => arr[Math.abs([...String(seed)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) | 0, 7)) % arr.length]; function firstName() { const st = S.students.get(S.studentId); return st ? String(st.name).split(" ")[0] : ""; } function quizCheer(r, t) { const p = pct(t.got, t.max); const n = firstName(); const seed = r.attemptId || r.submittedAt; const earlier = attemptsFor(S.studentId).filter((a) => a.setId === r.setId && a.id !== r.attemptId); const prevBest = earlier.length ? Math.max(...earlier.map((a) => pct(a.score, a.max))) : null; const nl = r.notLearnt.size; const mins = Math.max(1, Math.round((r.durationSec || 0) / 60)); let title, lines; if (p === 100) { title = pick([`Full marks, ${n}!`, "Every single one right!", `Perfect score, ${n}!`], seed); lines = prevBest === null ? ["First try, and not one slip. That's real understanding, not luck.", "You clearly know this inside out. Time to take on something harder.", "Flawless on your first go. Bank this feeling for exam day."] : ["You came back and nailed it. That's exactly how mastery is built.", "From not quite there to perfect. That's what practice does.", "Practice paid off: every answer right this time."]; } else if (p >= 85) { title = pick(["Excellent work!", `Brilliant, ${n}!`, "Really strong result!"], seed); lines = ["You're nearly there. Look at the one or two you missed, and you'll own this topic.", "This is exam-ready territory. A quick look at your slip-ups will make it rock solid.", "Strong work. The small mistakes are the most useful ones to learn from now."]; } else if (p >= 60) { title = pick(["Good progress!", `Nice going, ${n}!`, "Solid effort!"], seed); lines = ["You've got the core of it. Fixing your mistakes now is the fastest way to lift this score.", "More right than wrong, and every mistake shows you exactly what to practise next.", "Good foundation. One more round on the tricky bits and you'll see the difference."]; } else if (p >= 40) { title = pick(["You're on your way", `Keep at it, ${n}`, "Building up"], seed); lines = ["Half the battle is done. Go through the ones you missed with the tutor and try again tomorrow.", "Every expert started exactly here. Look at what tripped you up, and it'll stick much better next time.", "This is where the learning happens. Mistakes you understand are mistakes you won't repeat."]; } else { title = pick(["Every try counts", `Don't give up, ${n}`, "A starting point"], seed); lines = ["Tough one! That just means this topic needs a little more time, and that's completely normal.", "Struggling with something is how your brain grows. Try learning it with the tutor, then come back to this quiz.", "This shows you exactly where to focus. Start with one idea at a time, and it'll come together."]; } let line = pick(lines, seed + "l"); if (prevBest !== null && p > prevBest && p < 100) line = `Up from ${prevBest}% to ${p}%. ${p - prevBest >= 20 ? "That's a big jump, and you earned it." : "Steady progress is still progress."} ` + line; else if (prevBest !== null && p < prevBest) { title = pick(["Not your best today", `Shake it off, ${n}`, "Off day? That's okay"], seed); line = `Your best here is ${prevBest}%, so you know this. ` + pick(["Slow down, read each question twice, and have another go.", "Check the ones you missed. Was it a slip or a gap? Either way, you'll catch it next time.", "Everyone has days like this. Take a short break and come back fresh."], seed + "d"); } if (nl) line += ` You also found ${nl} idea${nl > 1 ? "s" : ""} you haven't learnt yet. Knowing that is useful, not a failure.`; if (mins >= 15 && p >= 60) line += ` ${mins} minutes of focused work. Well done for sticking with it.`; return { title, line, band: band(p) }; } function partCheer(seed, misses) { return misses ? pick(["You worked through the tricky bits and got there. That's what real learning looks like.", "It took a second go on some ideas, and that's exactly how they stick.", "You didn't give up when it got hard. Those are the ideas you'll remember best."], seed) : pick(["Smooth! You picked up every idea first time.", "Nicely done. One more step towards the big question.", "Great focus. Each part you learn makes the next one easier."], seed); } function reviewTotals() { const r = S.run; const set = S.sets.get(r.setId); let got = 0, max = 0, pendingSelf = 0; for (const q of set.questions || []) { const res = r.results[q.id]; max += res.max; if (res.auto) got += res.got; else if (r.self[q.id] != null) got += r.self[q.id]; else pendingSelf++; } return { got, max, pendingSelf }; } async function saveAttempt() { const r = S.run; const set = S.sets.get(r.setId); const t = reviewTotals(); if (t.pendingSelf > 0) { toast(`Mark your ${t.pendingSelf} written answer${t.pendingSelf > 1 ? "s" : ""} first`); return; } const answers = {}; const atoms = {}; for (const q of set.questions || []) { const res = r.results[q.id]; const got = res.auto ? res.got : r.self[q.id]; const resp = r.responses[q.id]; answers[q.id] = { response: resp == null || res.notLearnt ? null : resp, got, max: res.max, auto: res.auto, notLearnt: !!res.notLearnt }; if (res.notLearnt) continue; for (const a of q.atom_ids || []) { const cur = atoms[a] || [0, 0]; atoms[a] = [cur[0] + got, cur[1] + res.max]; } } const doc = { studentId: S.studentId, setId: r.setId, subject: set.subject || "", code: set.code || "", chapter: set.chapter || "", startedAt: r.startedAt, submittedAt: r.submittedAt, durationSec: r.durationSec, score: t.got, max: t.max, answers, atoms, }; if (r.saving || r.saved) return; const btn = $("save-btn"); if (btn) btn.disabled = true; r.saving = true; try { const saved = await api("api/attempts", { method: "POST", body: JSON.stringify({ studentId: doc.studentId, setId: doc.setId, startedAt: doc.startedAt, submittedAt: doc.submittedAt, durationSec: doc.durationSec, answers: doc.answers, focus: r.focus || undefined, leftQuiz: !!r.leftQuiz }) }); S.attempts.push(saved); r.saved = true; r.attemptId = saved.id; store.del(r.key); toast("Result saved"); T.mastery = null; render(); } catch (e) { if (btn) btn.disabled = false; handleWriteError(e); } finally { r.saving = false; } } // ---------- feedback ---------- const FB_TAGS = ["wrong answer", "unclear", "too hard", "too easy", "typo", "great question", "helpful", "other"]; const FB_TUTOR_TAGS = ["helpful", "unclear", "wrong answer", "too hard", "too easy", "off topic", "other"]; const FB_APP_TAGS = ["confusing", "hard to find", "looks wrong", "too slow", "bug", "idea", "love it", "other"]; const fbOpen = new Set(); function feedbackFor(t) { return S.feedback.filter((f) => f.targetType === t.targetType && f.setId === t.setId && (f.questionId || null) === (t.questionId || null) && (f.sessionId || null) === (t.sessionId || null) && (t.targetType !== "tutor_message" || f.excerpt === t.excerpt)); } function whoName(by) { if (by === "parent") return "Parent"; if (by === "visitor") return "Visitor"; const st = S.students.get(by) || {}; return (st.name || "Someone") + (st.test ? " (test)" : ""); } function screenName() { if (S.picking || (!S.studentId && S.view === "practise")) return "Name list"; if (S.view === "practise" && !S.chapterId) return S.subjectCode ? `Subject ${S.subjectCode}` : "Home"; return { practise: "Chapter page", test: "Taking a self-check", review: "Marked self-check", tutor: T.sessionId ? "Tutor chat" : "Tutor chapter list", progress: "Progress", bank: B.setId ? "Parent question review" : "Parent feedback inbox" }[S.view] || S.view; } function feedbackWidget(t, label) { const key = JSON.stringify(t); const existing = feedbackFor(t); const box = h("div", { class: "fb" }); const mine = existing.filter((f) => f.by === S.studentId); const head = h("div", { class: "fb-head" }, h("button", { type: "button", class: "fb-toggle", "aria-expanded": String(fbOpen.has(key)), text: fbOpen.has(key) ? "Close feedback" : (label || "Give feedback"), onclick: () => { fbOpen.has(key) ? fbOpen.delete(key) : fbOpen.add(key); render(); } }), mine.length ? h("span", { class: "pill good", text: `You sent ${mine.length}` }) : null, S.studentId === "parent" && existing.length ? h("span", { class: "pill warn", text: `${existing.filter((f) => f.status === "open").length} open of ${existing.length}` }) : null); box.append(head); if (!fbOpen.has(key)) return box; const picked = new Set(); const tags = h("div", { class: "selfmark", role: "group", "aria-label": "What's the feedback about?" }); for (const tag of (t.targetType === "app" ? FB_APP_TAGS : t.targetType.startsWith("tutor") ? FB_TUTOR_TAGS : FB_TAGS)) { const b = h("button", { type: "button", "aria-pressed": "false", text: tag }); b.addEventListener("click", () => { picked.has(tag) ? picked.delete(tag) : picked.add(tag); b.setAttribute("aria-pressed", String(picked.has(tag))); }); tags.append(b); } const ta = h("textarea", { rows: "2", placeholder: "What should change? (optional)", "aria-label": "Feedback comment" }); const send = h("button", { type: "button", class: "btn ghost", text: "Send feedback" }); send.addEventListener("click", async () => { if (!S.studentId && t.targetType !== "app") return toast("Pick your name first"); if (!picked.size && !ta.value.trim()) return toast("Pick a reason or write a comment"); send.disabled = true; try { const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId || "visitor", ...t, tags: [...picked], text: ta.value }) }); S.feedback.push(f); fbOpen.delete(key); if (t.targetType === "app") S.appFb = false; toast("Thanks, feedback sent"); render(); } catch (e) { send.disabled = false; toast(e.message); } }); box.append(tags, ta, h("div", { class: "fb-actions" }, send)); if (existing.length) box.append(feedbackList(existing, false)); return box; } function feedbackList(items, withTarget) { const ul = h("div", { class: "fb-list" }); for (const f of items.slice().sort((a, b) => String(b.created).localeCompare(String(a.created)))) { const set = S.sets.get(f.setId) || {}; const row = h("div", { class: `fb-item ${f.status}` }, h("div", { class: "meta" }, h("strong", { text: whoName(f.by) }), h("span", { class: "mono", text: fmtDate(f.created) }), ...f.tags.map((tg) => h("span", { class: `pill ${["wrong answer", "typo", "unclear"].includes(tg) ? "bad" : ["helpful", "great question", "got insight", "gaining confidence"].includes(tg) ? "good" : "warn"}`, text: tg })), h("span", { class: `pill ${f.status === "resolved" ? "good" : ""}`, text: f.status })), withTarget ? h("p", { class: "hint", text: f.targetType === "app" ? "The app itself" : `${set.subject || ""} · ${set.chapter || f.setId} · ${f.targetType.replace("_", " ")}${f.questionId ? " " + f.questionId : ""}` }) : null, f.excerpt ? h("p", { class: "fb-excerpt", text: f.excerpt }) : null, f.text ? h("p", { text: f.text }) : null, f.note ? h("p", { class: "hint", text: `Parent note: ${f.note}` }) : null); if (S.studentId === "parent") { row.append(h("div", { class: "fb-actions" }, h("button", { type: "button", class: "btn ghost", text: f.status === "open" ? "Mark resolved" : "Reopen", onclick: async () => { try { const u = await api(`api/feedback/${encodeURIComponent(f.id)}/status`, { method: "POST", body: JSON.stringify({ status: f.status === "open" ? "resolved" : "open" }) }); Object.assign(f, u); render(); } catch (e) { toast(e.message); } } }))); } ul.append(row); } return ul; } // ---------- parent page: Children · Questions · Feedback ---------- const B = { setId: null, filter: "open", tab: "reports", open: new Set(), kid: null }; function fold(key, summary, body, startOpen = false) { // a collapsible block that remembers being opened const d = h("details", { class: "fold" }, h("summary", null, summary), body); d.open = B.open.has(key) || startOpen; d.addEventListener("toggle", () => { if (d.open) B.open.add(key); else B.open.delete(key); }); return d; } // Parent: add children and choose which subjects each one sees. function childrenSettings() { const kids = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || "")); const sec = h("section", { class: "sheet" }, h("h2", { text: "Children" }), h("p", { class: "muted", text: "Each child sees the courses of their class (ticked and locked below). Tick any extra subjects they study; changes save straight away." })); if (!kids.length) sec.append(h("p", { class: "muted", text: "No children linked to your account yet. Ask the admin to link them." })); for (const k of kids) { const cur = new Set(k.ownSubjects || []); const fromClass = new Set(k.classCourses || []); const summaryText = () => [...new Set([...fromClass, ...cur])].map((c) => (catSubjects().find((x) => x.code === c) || {}).name).filter(Boolean).join(", ") || "no subjects ticked"; const sumHint = h("span", { class: "hint", text: summaryText() }); const box = h("div", { class: "kid-subjects" }); for (const b of S.catalog.boards || []) { const subs = catSubjects().filter((s) => s.board === b.id); if (!subs.length) continue; box.append(h("div", { class: "board-row" }, h("span", { class: "label", text: b.name }), h("div", { class: "subj-checks" }, ...subs.map((s) => { const id = `subj-${k.id}-${s.code}`; const cb = h("input", { type: "checkbox", id }); cb.checked = cur.has(s.code) || fromClass.has(s.code); cb.disabled = fromClass.has(s.code); cb.addEventListener("change", async () => { if (cb.checked) cur.add(s.code); else cur.delete(s.code); try { const r = await api(`api/students/${encodeURIComponent(k.id)}/profile`, { method: "POST", body: JSON.stringify({ subjects: catSubjects().map((x) => x.code).filter((c) => cur.has(c)) }) }); S.students.set(k.id, r); sumHint.textContent = summaryText(); toast(`Saved ${k.name}'s subjects`); } catch (e) { cb.checked = !cb.checked; if (cb.checked) cur.add(s.code); else cur.delete(s.code); handleWriteError(e); } }); return h("label", { class: "subj-check", for: id }, cb, h("span", { text: s.name + (fromClass.has(s.code) ? " (class)" : "") + (unitsOf(s).length ? "" : " (coming soon)") })); })))); } sec.append(fold(`kid:${k.id}`, [h("strong", { text: k.name + (k.test ? " (test)" : "") }), " ", sumHint], box)); } return sec; } // ---------- admin: logins, families and classes ---------- const A = { data: null, loading: false }; function loadAdmin() { if (A.loading) return; A.loading = true; api("api/admin").then((d) => { A.data = d; }).catch((e) => toast(e.message)).finally(() => { A.loading = false; render(); }); } function starterPassword() { const abc = "abcdefghjkmnpqrstuvwxyz23456789"; const r = new Uint32Array(8); crypto.getRandomValues(r); return [...r].map((x) => abc[x % abc.length]).join(""); } function checkList(items, chosen, idp) { // a row of checkboxes; returns [element, () => chosen ids] const set = new Set(chosen); const el = h("div", { class: "subj-checks" }, ...items.map((it) => { const id = `${idp}-${it.id}`; const cb = h("input", { type: "checkbox", id }); cb.checked = set.has(it.id); cb.addEventListener("change", () => { if (cb.checked) set.add(it.id); else set.delete(it.id); }); return h("label", { class: "subj-check", for: id }, cb, h("span", { text: it.label })); })); return [el, () => items.map((x) => x.id).filter((x) => set.has(x))]; } function adminPage() { const sec = h("section", { class: "sheet" }, h("h2", { text: "Admin" })); if (!A.data) { sec.append(h("p", { class: "muted", text: "Loading accounts…" })); loadAdmin(); return sec; } const d = A.data; const stName = new Map(d.students.map((x) => [x.id, x.name + (x.test ? " (test)" : "")])); const kidItems = d.students.map((x) => ({ id: x.id, label: stName.get(x.id) })); const post = async (path, body, ok) => { try { await api(path, { method: "POST", body: JSON.stringify(body) }); toast(ok); A.data = null; await connect(); } catch (e) { toast(e.message); } }; const roleName = { admin: "Admin", parent: "Parent", child: "Student" }; A.tab = A.tab || "people"; sec.append(h("div", { class: "selfmark", role: "tablist" }, ...[["people", "👤 People"], ["classes", "🏫 Classes"], ["family", "👪 Family"]].map(([k, l]) => h("button", { type: "button", role: "tab", "aria-selected": String(A.tab === k), "aria-pressed": String(A.tab === k), text: l, onclick: () => { A.tab = k; render(); } })))); if (A.tab === "family") { sec.append(h("h3", { text: "Who is Mom, Dad…" }), h("p", { class: "hint", text: "Children share reports with these people, and see their encouragement as \"From Mom\", \"From Dad\" and so on. Linking someone here also lets them see that child." })); const grown = d.users.filter((u) => u.role !== "child" && !u.disabled); for (const st of d.students.filter((x) => !x.test)) { const fam = (d.family && d.family[st.id]) || []; const who = h("select", { "aria-label": `Add someone for ${st.name}` }, ...grown.map((u) => h("option", { value: u.id, text: u.name }))); const rel = h("input", { type: "text", value: "Mom", maxlength: "20", "aria-label": "Shown to the child as", list: "rel-list" }); sec.append(h("div", { class: "admin-user" }, h("strong", { text: st.name }), fam.length ? h("ul", { class: "chat-list" }, ...fam.map((x) => h("li", null, h("span", { text: `${x.relation}: ${x.name}` }), h("button", { class: "react", text: "Remove", onclick: () => post("api/admin/family", { studentId: st.id, userId: x.id, relation: null }, `Removed ${x.name} for ${st.name}`) })))) : h("p", { class: "hint", text: "No one linked yet." }), h("div", { class: "add-student" }, who, h("span", { text: "as" }), rel, h("button", { class: "btn ghost", text: "Link", onclick: () => post("api/admin/family", { studentId: st.id, userId: who.value, relation: rel.value || "Parent" }, `Linked for ${st.name}`) })))); } sec.append(h("datalist", { id: "rel-list" }, ...["Mom", "Dad", "Grandma", "Grandpa", "Guardian", "Tutor"].map((x) => h("option", { value: x })))); return sec; } if (A.tab === "people") { sec.append(h("h3", { text: "Logins" })); for (const u of d.users) { const pw = h("input", { type: "text", value: starterPassword(), "aria-label": `New starter password for ${u.name}`, minlength: "6" }); const body = h("div", { class: "admin-user" }, h("p", { class: "hint", text: `Username ${u.username}${u.role === "child" && u.studentId ? ` · results of ${stName.get(u.studentId) || u.studentId}` : ""}${u.mustChange ? " · has not chosen a password yet" : ""}` })); if (u.role === "parent") { const [el, get] = checkList(kidItems, u.children, `kids-${u.id}`); body.append(h("p", { class: "label", text: "Children" }), el, h("button", { class: "btn ghost", text: "Save children", onclick: () => post(`api/admin/users/${u.id}`, { children: get() }, `Saved ${u.name}'s children`) })); } body.append(h("p", { class: "label", text: "Reset password" }), h("div", { class: "add-student" }, pw, h("button", { class: "btn ghost", text: "Reset", onclick: () => post(`api/admin/users/${u.id}`, { password: pw.value }, `New starter password for ${u.name}: ${pw.value}`) })), u.id !== S.me.id ? h("button", { class: "btn ghost", text: u.disabled ? "Switch login back on" : "Switch login off", onclick: () => post(`api/admin/users/${u.id}`, { disabled: !u.disabled }, u.disabled ? `${u.name} can log in again` : `${u.name} can no longer log in`) }) : null); const kids = u.role === "parent" ? (u.children || []).map((c) => stName.get(c) || c).join(", ") : ""; sec.append(fold(`user:${u.id}`, [h("strong", { text: u.name }), " ", h("span", { class: `pill ${u.disabled ? "bad" : ""}`, text: u.disabled ? "off" : roleName[u.role] }), kids ? h("span", { class: "hint", text: ` · ${kids}` }) : null], body)); } // add a login { const name = h("input", { type: "text", id: "nu-name", maxlength: "40", required: true }); const uname = h("input", { type: "text", id: "nu-user", maxlength: "30", autocapitalize: "none", spellcheck: "false", required: true, pattern: "[a-z0-9][a-z0-9._\\-]{1,29}" }); const pw = h("input", { type: "text", id: "nu-pw", minlength: "6", required: true, value: starterPassword() }); const role = h("select", { id: "nu-role" }, ...["child", "parent", "admin"].map((r) => h("option", { value: r, text: roleName[r] }))); const linked = new Set(d.users.filter((u) => u.studentId).map((u) => u.studentId)); const link = h("select", { id: "nu-link" }, h("option", { value: "", text: "New student record" }), ...d.students.filter((x) => !linked.has(x.id)).map((x) => h("option", { value: x.id, text: `Existing: ${stName.get(x.id)}` }))); const [kidsEl, getKids] = checkList(kidItems, [], "nu-kids"); const childRow = h("div", null, h("label", { for: "nu-link", text: "Results" }), link); const parentRow = h("div", { hidden: true }, h("p", { class: "label", text: "Children" }), kidsEl); role.addEventListener("change", () => { childRow.hidden = role.value !== "child"; parentRow.hidden = role.value !== "parent"; }); name.addEventListener("input", () => { if (!uname.dataset.touched) uname.value = name.value.toLowerCase().replace(/[^a-z0-9]+/g, ""); }); uname.addEventListener("input", () => { uname.dataset.touched = "1"; }); sec.append(h("h3", { text: "Add a login" }), h("form", { class: "login-form", onsubmit: (e) => { e.preventDefault(); const body = { name: name.value.trim(), username: uname.value.trim().toLowerCase(), role: role.value, password: pw.value }; if (role.value === "child" && link.value) body.studentId = link.value; if (role.value === "parent") body.children = getKids(); post("api/admin/users", body, `Added ${body.name}: username ${body.username}, starter password ${body.password}`); } }, h("label", { for: "nu-name", text: "Name" }), name, h("label", { for: "nu-user", text: "Username (lowercase letters and numbers)" }), uname, h("label", { for: "nu-role", text: "Role" }), role, childRow, parentRow, h("label", { for: "nu-pw", text: "Starter password (they choose their own when they first log in)" }), pw, h("button", { class: "btn accent", type: "submit", text: "Add login" }))); } return sec; } // classes sec.append(h("h3", { text: "Classes" }), h("p", { class: "hint", text: "A class has courses and students. Each student sees the courses of all their classes." })); const courseItems = d.subjects.map((x) => ({ id: x.code, label: `${x.name} (${x.board.toUpperCase()} ${x.code})` })); for (const c of d.classes) { const nm = h("input", { type: "text", value: c.name, maxlength: "60", "aria-label": "Class name" }); const [cEl, getC] = checkList(courseItems, c.courses, `cc-${c.id}`); const [sEl, getS] = checkList(kidItems, c.students, `cs-${c.id}`); sec.append(fold(`class:${c.id}`, [h("strong", { text: c.name }), h("span", { class: "hint", text: ` · ${c.courses.length} courses · ${c.students.map((x) => stName.get(x) || x).join(", ") || "no students"}` })], h("div", { class: "admin-user" }, h("p", { class: "label", text: "Name" }), nm, h("p", { class: "label", text: "Courses" }), cEl, h("p", { class: "label", text: "Students" }), sEl, h("div", { class: "students" }, h("button", { class: "btn accent", text: "Save class", onclick: () => post(`api/admin/classes/${c.id}`, { name: nm.value, courses: getC(), students: getS() }, `Saved ${nm.value}`) }), h("button", { class: "btn ghost", text: "Delete class", onclick: async () => { try { await api(`api/admin/classes/${c.id}`, { method: "DELETE" }); toast(`Deleted ${c.name}`); A.data = null; await connect(); } catch (e) { toast(e.message); } } }))))); } const cn = h("input", { type: "text", placeholder: "New class name, e.g. IGCSE Year 10", maxlength: "60", "aria-label": "New class name" }); sec.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); if (cn.value.trim()) post("api/admin/classes", { name: cn.value.trim(), courses: [], students: [] }, "Class added: open it to add courses and students"); } }, cn, h("button", { class: "btn ghost", type: "submit", text: "Add class" }))); return sec; } // Parent: every quiz, organised board > subject > unit > chapter > quizzes (part quizzes folded away). function questionTree() { const open = S.feedback.filter((f) => f.status === "open"); const nOpen = (ids) => open.filter((f) => ids.includes(f.setId)).length; const setsOf = (cid) => [...S.sets.values()].filter((x) => (x.chapterId || x.id) === cid).sort((a, b) => (a.order || 0) - (b.order || 0)); const quizBtn = (z) => { const n = nOpen([z.id]); return h("button", { class: "quiz-row", type: "button", onclick: () => { B.setId = z.id; render(); window.scrollTo(0, 0); } }, h("span", { text: z.title || z.chapter }), h("span", { class: "hint", text: `${(z.questions || []).length} Qs${n ? ` · ${n} open feedback` : ""}` })); }; const sec = h("section", { class: "sheet" }, h("h2", { text: "Questions" }), h("p", { class: "muted", text: "Open a subject, then a chapter, then a quiz to see every question with its answer, mark scheme and explanation. Leave feedback on anything that needs fixing." })); const placed = new Set(); for (const b of S.catalog.boards || []) { const subs = catSubjects().filter((s) => s.board === b.id && unitsOf(s).length); if (!subs.length) continue; sec.append(h("h3", { class: "board-head", text: b.name })); for (const subj of subs) { const chapters = unitsOf(subj).flatMap((u) => u.chapters.map((c) => ({ u, c }))); const subjSets = chapters.flatMap(({ c }) => setsOf(c.id).map((z) => z.id)); const body = h("div", { class: "fold-body" }); for (const { u, c } of chapters) { placed.add(c.id); const all = setsOf(c.id); const main = all.filter((z) => z.kind !== "chunk"); const parts = all.filter((z) => z.kind === "chunk"); const cBody = h("div", { class: "fold-body" }, ...main.map(quizBtn)); if (parts.length) cBody.append(fold(`parts:${c.id}`, [h("span", { text: "Part quizzes" }), " ", h("span", { class: "hint", text: `${parts.length} short quizzes` })], h("div", { class: "fold-body" }, ...parts.map(quizBtn)))); const n = nOpen(all.map((z) => z.id)); body.append(fold(`ch:${c.id}`, [h("span", { text: `${u.num ? `Unit ${u.num} · ` : ""}${chapterTitle(c.id)}` }), " ", h("span", { class: "hint", text: `${main.length} quizzes${parts.length ? ` + ${parts.length} parts` : ""}${n ? ` · ${n} open feedback` : ""}` })], cBody)); } const n = nOpen(subjSets); sec.append(fold(`subj:${subj.code}`, [h("strong", { text: subj.name }), " ", h("span", { class: "hint", text: `${chapters.length} chapter${chapters.length === 1 ? "" : "s"}${n ? ` · ${n} open feedback` : ""}` })], body)); } } const rest = [...new Set([...S.sets.values()].map((z) => z.chapterId || z.id))].filter((cid) => !placed.has(cid)); if (rest.length) sec.append(fold("subj:other", [h("strong", { text: "Other" }), " ", h("span", { class: "hint", text: `${rest.length} chapters not in the catalogue` })], h("div", { class: "fold-body" }, ...rest.map((cid) => fold(`ch:${cid}`, h("span", { text: chapterTitle(cid) }), h("div", { class: "fold-body" }, ...setsOf(cid).map(quizBtn))))))); return sec; } function renderBank(main) { const open = S.feedback.filter((f) => f.status === "open"); if (!B.setId) { const isAdmin = S.me && S.me.role === "admin"; const tabs = [["reports", `📈 Reports${S.reportsUnread ? ` (${S.reportsUnread} new)` : ""}`], ["children", "Children"], ...(isAdmin ? [["questions", "Questions"], ["feedback", `Feedback${open.length ? ` (${open.length})` : ""}`], ["admin", "Admin"]] : [])]; if (!tabs.some(([k]) => k === B.tab)) B.tab = "reports"; main.append(h("section", { class: "sheet parent-head" }, h("h2", { text: "Parent" }), h("div", { class: "selfmark", role: "tablist" }, ...tabs.map(([k, label]) => h("button", { type: "button", role: "tab", "aria-selected": String(B.tab === k), "aria-pressed": String(B.tab === k), text: label, onclick: () => { B.tab = k; render(); } }))))); if (B.tab === "reports") { parentReports(main); return; } if (B.tab === "children") { if (S.catalog) main.append(childrenSettings()); return; } if (B.tab === "admin" && S.me.role === "admin") { main.append(adminPage()); return; } if (B.tab === "questions") { if (S.catalog) main.append(questionTree()); return; } const inbox = h("section", { class: "sheet" }, h("h2", { text: "Feedback inbox" }), h("div", { class: "selfmark" }, ...["open", "all"].map((k) => h("button", { type: "button", "aria-pressed": String(B.filter === k), text: k === "open" ? `Open (${open.length})` : `All (${S.feedback.length})`, onclick: () => { B.filter = k; render(); } })))); const items = B.filter === "open" ? open : S.feedback; inbox.append(items.length ? feedbackList(items, true) : h("p", { class: "muted", text: "No feedback yet. It appears here as soon as anyone sends some." })); main.append(inbox); return; } const set = S.sets.get(B.setId); const atoms = set.atoms || {}; const sheet = h("section", { class: "sheet" }, h("div", { class: "test-bar" }, h("div", null, h("span", { class: "label", text: `${set.subject} · ${set.code}` }), h("h2", { text: set.chapter })), h("button", { class: "btn ghost", text: "← Back to questions", onclick: () => { B.setId = null; B.tab = "questions"; render(); } })), feedbackWidget({ targetType: "set", setId: set.id }, "Feedback on this whole self-check")); (set.questions || []).forEach((q, i) => { const body = h("div", { class: "body" }, h("p", { class: "prompt", text: q.prompt }), q.figure ? figureEl(q.figure, true) : null); if (q.options) body.append(h("ol", { class: "opts-list", type: "A" }, ...q.options.map((o, k) => { const right = q.type === "mcq" ? Number(q.answer) === k : (q.answer || []).map(Number).includes(k); return h("li", { class: right ? "right" : "", text: o + (right ? " ✓" : "") }); }))); if (q.type === "numeric") body.append(h("p", null, h("span", { class: "label", text: "Answer " }), h("span", { class: "mono", text: (() => { const shown = q.sf != null ? (() => { const t = Number(q.answer).toPrecision(q.sf); return t.includes("e") ? String(Number(t)) : t; })() : q.dp != null ? Number(q.answer).toFixed(q.dp) : fmtNum(Number(q.answer)); const tol = q.exact || q.sf != null || q.dp != null ? (q.exact ? " (exact)" : q.sf != null ? ` (${q.sf} s.f.)` : ` (${q.dp} d.p.)`) : ` (±${+((q.tolerance ?? 0.01) * 100).toFixed(1)}%)`; return `${shown}${q.unit ? " " + q.unit : ""}${tol}${q.sign_optional ? "; sign optional" : ""}`; })() }))); const scheme = h("div", { class: "scheme" }); if (q.mark_scheme) scheme.append(h("p", null, h("span", { class: "label", text: "Mark scheme " }), q.mark_scheme)); if (q.explanation) scheme.append(h("p", null, h("span", { class: "label", text: "Why " }), q.explanation)); scheme.append(h("p", { class: "hint", text: `${q.type} · difficulty ${q.difficulty || "?"} · template ${q.template_id || "none"}${q.misconception_id ? " · probes " + q.misconception_id : ""}` })); for (const a of q.atom_ids || []) scheme.append(h("p", { class: "hint", text: `${a}: ${atoms[a] || ""}` })); body.append(scheme, feedbackWidget({ targetType: "question", setId: set.id, questionId: q.id })); sheet.append(h("div", { class: "q" }, h("div", null, h("div", { class: "num", text: `Q${i + 1}` }), h("div", { class: "marks", text: `[${q.marks || 1}]` })), body)); }); main.append(sheet); } // ---------- rendering ---------- // ---------- addresses: every screen has one, so Back and refresh work ---------- let routeReady = false; function routeOf() { if (!S.me) return "#/login"; if (S.view === "account" || S.me.mustChange) return "#/account"; if (S.view === "tutor") return T.sessionId ? `#/chat/${T.sessionId}` : location.hash; // opening: keep the address if ((S.view === "test" || S.view === "review") && S.run) return `#/quiz/${S.run.setId}`; if (S.view === "chats") return "#/chats"; if (S.view === "progress") return "#/progress"; if (S.view === "shared" && S.sharedId) return `#/report/${S.sharedId}`; if (S.picking) return "#/switch"; if (S.studentId === "parent") return `#/parent/${B.tab}`; if (S.chapterId) return `#/chapter/${S.chapterId}`; if (S.subjectCode) return `#/subjects/${S.subjectCode}`; if (S.place === "subjects") return "#/subjects"; return "#/today"; } function syncUrl() { if (!S.ready || !routeReady) return; const r = routeOf(); if (r === location.hash) { S.replaceRoute = false; return; } try { if (S.replaceRoute) history.replaceState(null, "", r); else history.pushState(null, "", r); } catch {} S.replaceRoute = false; } function applyRoute(hash) { const [a, b] = String(hash || "").replace(/^#\/?/, "").split("/").map((x) => decodeURIComponent(x || "")); if (S.view === "test" && S.run && !(a === "quiz" && b === S.run.setId)) confirmLeave(); if (a !== "quiz") S.run = null; if (T.sessionId && !(a === "chat" && b === T.sessionId)) endSession(); S.picking = false; S.replaceRoute = true; const parentish = S.studentId === "parent"; if (a === "account") S.view = "account"; else if (a === "chats" && !parentish) S.view = "chats"; else if (a === "progress") S.view = "progress"; else if (a === "report" && b) { S.view = "shared"; S.sharedId = b; } else if (a === "parent" && parentish) { S.view = "bank"; B.setId = null; if (b) B.tab = b; } else if (a === "switch" && S.me && S.me.role !== "child") { S.view = "practise"; S.picking = true; } else if (a === "chapter" && b && !parentish) { const e = chapterEntry(b); S.view = "practise"; S.place = "subjects"; S.chapterId = b; S.subjectCode = e ? e.subject.code : null; } else if (a === "subjects" && !parentish) { S.view = "practise"; S.place = "subjects"; S.chapterId = null; S.subjectCode = b || null; } else if (a === "chat" && b && !parentish) { if (b !== T.sessionId) { reopenChat(b); return; } } else if (a === "quiz" && S.run && S.run.setId === b) { /* still in that quiz */ } else if (a === "quiz" && b) { const set = S.sets.get(b); S.view = "practise"; S.place = "subjects"; S.chapterId = set ? (set.chapterId || set.id) : null; } else { S.view = parentish ? "bank" : "practise"; S.place = "today"; S.chapterId = null; S.subjectCode = null; } render(); window.scrollTo(0, 0); } window.addEventListener("popstate", () => { if (S.me && routeReady) applyRoute(location.hash); }); function goPlace(place) { if (place !== "chats") S.chatFilter = null; if (S.view === "test" && S.run) confirmLeave(); if (T.sessionId) endSession(); S.run = null; S.picking = false; S.chapterId = null; S.subjectCode = null; if (place === "today" || place === "subjects") { S.view = "practise"; S.place = place; } else S.view = place; render(); window.scrollTo(0, 0); } function render() { renderInner(); syncUrl(); } function renderInner() { const isParent = S.studentId === "parent"; if (isParent && S.view === "practise" && !S.picking) S.view = "bank"; // the parent's home is Review $("tab-practise").hidden = isParent; // parents don't take self-checks $("tab-subjects").hidden = isParent; $("tab-chats").hidden = isParent; const inSubjects = S.view === "practise" && !S.picking && (S.place === "subjects" || S.subjectCode || S.chapterId); $("tab-practise").setAttribute("aria-pressed", String(S.view === "practise" && !inSubjects)); $("tab-subjects").setAttribute("aria-pressed", String(!!inSubjects || ["test", "review"].includes(S.view))); $("tab-chats").setAttribute("aria-pressed", String(S.view === "chats" || S.view === "tutor")); document.body.classList.toggle("in-quiz", ["test", "review"].includes(S.view)); $("tab-tutor").setAttribute("aria-pressed", String(S.view === "tutor")); $("tab-progress").setAttribute("aria-pressed", String(S.view === "progress")); const who = $("who"); const st = S.studentId && S.students.get(S.studentId); who.textContent = isParent ? "Parent" : st ? `👤 ${st.name}` : "Choose your name"; who.classList.toggle("set", !!st || isParent); who.title = S.me && S.me.role === "child" ? "Your account: password and log out" : "Switch view, your account, log out"; $("brand-tag").textContent = isParent ? "Parent" : st && S.catalog ? boardLine(subjectsFor(st)) : ""; $("tab-bank").hidden = !isParent; $("tab-bank").setAttribute("aria-pressed", String(S.view === "bank")); $("tab-progress").replaceChildren(h("span", { class: "ic", "aria-hidden": "true", text: isParent ? "📊" : "📈" }), h("span", { text: isParent ? "Overview" : "Report" })); for (const id of ["tab-practise", "tab-subjects", "tab-chats", "tab-progress", "who", "app-fb"]) if (!S.me) $(id).hidden = true; if (S.me) { $("tab-progress").hidden = isParent && S.me.role !== "admin"; $("who").hidden = false; $("app-fb").hidden = false; } if (S.me && isParent) who.textContent = S.me.role === "admin" ? `👤 ${S.me.name} (admin)` : `👤 ${S.me.name} (parent)`; const main = $("main"); main.replaceChildren(); if (!(S.view === "tutor" && (T.sessionId || T.busy))) document.body.classList.remove("in-chat"); const dock = $("dock"); const dockRow = $("dock-row"); dock.hidden = true; dockRow.replaceChildren(); 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; } if (!S.me) return renderLogin(main); if (S.me.mustChange || S.view === "account") return renderAccount(main); if (S.dbError) { main.append(connectionNotice()); } if (S.appFb) { const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` }; const k = JSON.stringify(t); if (S.appFbOpening) { fbOpen.add(k); S.appFbOpening = false; } if (!fbOpen.has(k)) S.appFb = false; } if (S.appFb) { const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` }; main.append(h("section", { class: "sheet app-fb" }, 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(); } })), h("p", { class: "muted", text: `What's working, what's confusing, what you'd change. We'll note that you were on: ${where}.` }), feedbackWidget(t, "Feedback"))); } if (S.view === "test" && S.run) return renderTest(main, dock, dockRow); if (S.view === "review" && S.run) return renderReview(main, dock, dockRow); if (S.view === "progress") return S.studentId && S.studentId !== "parent" ? renderMyProgress(main) : renderProgress(main); if (S.view === "chats") return renderChats(main); if (S.view === "shared" && S.sharedId) return renderSharedReport(main, S.sharedId); if (S.view === "tutor") return renderTutor(main, dock, dockRow); if (S.view === "bank" && isParent) return renderBank(main); if (isParent && !S.picking) return renderBank(main); renderPractise(main); } // ---------- light formatting for tutor replies ---------- function inline(text) { const frag = document.createDocumentFragment(); const re = /(\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\s][^*\n]*\*|_[^_\s][^_\n]*_|`[^`\n]+`)/g; let last = 0, m; while ((m = re.exec(text))) { if (m.index > last) frag.append(text.slice(last, m.index)); const t = m[0]; if (t.startsWith("**") || t.startsWith("__")) frag.append(h("strong", { text: t.slice(2, -2) })); else if (t.startsWith("`")) frag.append(h("code", { text: t.slice(1, -1) })); else frag.append(h("em", { text: t.slice(1, -1) })); last = m.index + t.length; } if (last < text.length) frag.append(text.slice(last)); return frag; } function md(text) { const box = h("div", { class: "md" }); let para = [], list = null, listType = null; 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 = []; } }; const flushList = () => { if (list) { box.append(list); list = null; listType = null; } }; for (const raw of String(text || "").split("\n")) { const line = raw.trimEnd(); const ul = line.match(/^\s*[-•*]\s+(.*)$/), ol = line.match(/^\s*\d+[.)]\s+(.*)$/); if (ul || ol) { flushPara(); const type = ul ? "ul" : "ol"; if (listType !== type) { flushList(); list = h(type); listType = type; } list.append(h("li", null, inline((ul || ol)[1]))); } else if (!line.trim()) { flushPara(); flushList(); } else { flushList(); para.push(line); } } flushPara(); flushList(); return box; } // ---------- tutor ---------- const T = { setId: null, sessionId: null, mode: null, msgs: [], busy: false, conf: null, mastery: null, draft: "", kind: null, chapterId: null, topicId: null, plan: [], step: 0, goal: "", complete: false, summary: null }; async function loadMastery() { if (!S.studentId || T.loadingM) return; T.loadingM = true; try { T.mastery = await api(`api/mastery/${encodeURIComponent(S.studentId)}`); } catch { T.mastery = { chapters: {}, levels: {} }; } T.loadingM = false; if (S.view === "practise") render(); } function applySession(r) { T.sessionId = r.sessionId; T.kind = r.kind; T.goal = r.goal; T.plan = r.plan || []; T.step = r.step || 0; T.complete = !!r.complete; T.summary = r.summary || null; T.parts = r.parts || null; } function carryOn() { const box = $("tutor-input"); if (box) box.value = "Carry on to the next part."; T.draft = "Carry on to the next part."; tutorSend(); } function partsBar(p) { const k = p.parts.findIndex((x) => x.status === "now"); const cur = k >= 0 ? p.parts[k] : null; const bar = h("div", { class: "parts-bar", "aria-label": "Your progress in this topic" }, h("div", { class: "parts-row" }, h("span", { class: "label", text: cur ? `Part ${k + 1} of ${p.parts.length}: ${cur.title}` : `${p.parts.length} parts` }), h("span", { class: `pill ${p.learnt >= p.of ? "good" : ""}`, text: `${p.learnt} of ${p.of} ideas learnt` })), h("div", { class: "parts-row", role: "list" }, ...p.parts.map((x, i) => h("span", { role: "listitem", class: `part-dot ${x.status}`, title: x.question, "aria-label": `Part ${i + 1}, ${x.title}: ${x.status === "learned" ? "learnt" : x.status === "now" ? "now" : x.status === "skipped" ? "skipped" : "to do"}` }, h("span", { class: "dot", text: x.status === "learned" ? "✓" : x.status === "skipped" ? "–" : String(i + 1) }), h("span", { text: x.title }))))); if (p.ideas && p.ideas.length) { bar.append(h("div", { class: "idea-chips", "aria-label": "Ideas in this part" }, ...p.ideas.map((d) => h("span", { class: `idea-chip ${d.status === "got it" ? "got" : d.status === "following" ? "following" : d.status === "learning" ? "learning" : ""}`, title: `${d.idea} (${d.status === "got it" ? "checked: got it" : d.status === "following" ? "following so far; the check comes next" : d.status === "learning" ? "still learning" : "not yet"})`, text: `${d.status === "got it" ? "✓ " : d.status === "following" ? "→ " : d.status === "learning" ? "… " : ""}${d.idea.length > 48 ? d.idea.slice(0, 46) + "…" : d.idea}` })))); } return bar; } function partCard(p) { const d = p.chunkDone; const quiz = d.quizId && S.sets.get(d.quizId); const idx = p.parts.findIndex((x) => x.id === d.id); const next = p.parts.find((x, i) => i > idx && x.status !== "learned"); const names = new Map(((CHAPTERS_INFO(T.chapterId) || {}).topics || []).flatMap((t) => Object.entries(t.atoms || {}))); const card = h("div", { class: "part-card" }, h("h3", { text: d.status === "learned" ? `Part ${idx + 1} learnt: ${d.title}` : `Part ${idx + 1} skipped: ${d.title}` }), d.status === "learned" ? h("p", { class: "cheer-line", text: partCheer(`${T.sessionId}${d.id}`, (d.ideas || []).some((x) => x.misses)) }) : null); if (d.ideas && d.ideas.length) card.append(h("ul", null, ...d.ideas.map((x) => h("li", { text: `${x.got ? "✓" : "○"} ${names.get(x.atom) || x.atom}${x.got && x.misses ? " (needed another go)" : ""}` })))); const acts = h("div", { class: "students" }); if (quiz && !T.complete) acts.append(h("button", { class: "btn accent", text: `Take the part quiz · ${quiz.questions.length} Qs (recommended)`, onclick: () => { endSession(); startTest(quiz.id); } })); if (next && !T.complete) acts.append(h("button", { class: quiz ? "btn ghost" : "btn accent", text: `Carry on: ${next.title}`, disabled: T.busy, onclick: carryOn })); card.append(acts); return card; } async function tutorStart(opts) { T.readOnly = false; if (!S.tutorOn) return toast("The tutor isn't switched on yet"); T.setId = opts.chapterId; T.chapterId = opts.chapterId; T.topicId = opts.topicId || null; T.kind = opts.kind; T.msgs = []; T.busy = true; T.sessionId = null; T.plan = []; T.goal = ""; T.complete = false; T.summary = null; T.parts = null; S.view = "tutor"; S.run = null; render(); try { const r = await api("api/tutor/start", { method: "POST", body: JSON.stringify({ studentId: S.studentId, ...opts }) }); applySession(r); T.msgs.push({ who: "tutor", text: r.reply }); FT.start("chat"); resetWait(); } catch (e) { toast(e.message); T.busy = false; T.setId = null; S.view = "practise"; document.body.classList.remove("in-chat"); render(); return; } T.busy = false; render(); scrollChat(); } async function tutorSend(preset) { const box = $("tutor-input"); const text = (typeof preset === "string" ? preset : (box ? box.value : T.draft)).trim(); if (!text || T.busy) return; T.nudge = false; T.waitSince = null; document.title = BASE_TITLE; T.msgs.push({ who: "me", text, conf: T.conf }); T.draft = ""; T.busy = true; const conf = T.conf; T.conf = null; render(); scrollChat(); try { const r = await api("api/tutor/message", { method: "POST", body: JSON.stringify({ sessionId: T.sessionId, text, confidence: conf, focus: FT.take("chat") || undefined }) }); applySession(r); T.msgs.push({ who: "tutor", text: r.reply, changes: r.changes }); resetWait(); } catch (e) { T.msgs.push({ who: "system", text: e.message }); } T.busy = false; render(); scrollChat(); const nb = $("tutor-input"); if (nb) nb.focus(); } function endSession() { if (T.chapterId) S.chapterId = T.chapterId; T.sessionId = null; T.setId = null; T.msgs = []; T.mastery = null; T.plan = []; T.complete = false; T.summary = null; T.parts = null; FT.stop("chat"); S.activity = null; S.view = "practise"; document.body.classList.remove("in-chat"); S.myChats = {}; // refresh "Your tutor chats" next time a chapter opens } // ---------- past chats: list them on the chapter page, reopen and carry on ---------- function myChats(cid) { S.myChats = S.myChats || {}; const k = `${S.studentId}|${cid || "*"}`; if (S.myChats[k] === undefined && S.studentId && S.tutorOn) { S.myChats[k] = null; // loading api(`api/tutor/sessions/${encodeURIComponent(S.studentId)}${cid ? `?chapterId=${encodeURIComponent(cid)}` : ""}`) .then((r) => { S.myChats[k] = r; }).catch(() => { S.myChats[k] = []; }) .finally(() => { if (["practise", "chats"].includes(S.view)) render(); }); } return S.myChats[k] || []; } function resumableChat(cid, topicId) { return myChats(cid).find((c) => c.kind === "learn" && c.topicId === topicId && !c.complete && c.atChunk && !c.atPartLearnt); } async function reopenChat(id) { T.busy = true; S.view = "tutor"; S.run = null; T.msgs = []; render(); try { const r = await api(`api/tutor/session/${encodeURIComponent(id)}?studentId=${encodeURIComponent(S.studentId)}`); T.setId = r.chapterId; T.chapterId = r.chapterId; T.topicId = r.topicId || null; T.draft = ""; applySession(r); T.msgs = r.msgs; if (!T.readOnly) { FT.start("chat"); resetWait(); } const row = Object.values(S.myChats || {}).flat().find((c) => c && c.id === id); T.readOnly = !!(r.complete || (row && row.atPartLearnt)); } catch (e) { toast(e.message); T.busy = false; endSession(); render(); return; } T.busy = false; render(); scrollChat(); } const CHAT_KINDS = { learn: "Learn", ask: "Question", fix: "Fix mistakes", review: "Review" }; function chatWhen(iso) { return new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }); } function chatRow(c, withChapter) { const open = !c.complete && !c.atPartLearnt; return h("li", null, h("div", null, h("strong", { text: `${CHAT_KINDS[c.kind] || c.kind}: ${c.title}` }), h("span", { class: "hint", text: ` · ${withChapter ? chapterTitle(c.chapterId) + " · " : ""}${chatWhen(c.updated)} · ${c.messages} messages${c.complete ? " · finished" : c.atPart && !c.atPartLearnt ? ` · stopped at ${c.atPart}` : ""}` })), h("button", { class: open ? "btn accent" : "react", text: open ? "Carry on" : "Read", onclick: () => reopenChat(c.id) })); } function ensureActivity() { if (!S.activity && !S.loadingActivity) { S.loadingActivity = true; api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (["practise", "progress"].includes(S.view)) render(); }); } } // ---------- 📈 Report: numbers for a period, the coach, sharing, encouragement ---------- const R = { sid: null, period: "week", start: "", end: "", data: null, loading: false, err: "", coach: null, busy: false, draft: "", shared: null, key: "" }; const PERIODS = [["today", "Today"], ["yesterday", "Yesterday"], ["week", "This week"], ["lastweek", "Last week"], ["month", "This month"], ["30d", "Last 30 days"], ["custom", "Pick dates"]]; function reportQuery() { return { studentId: R.sid, period: R.period, start: R.period === "custom" ? R.start || null : null, end: R.period === "custom" ? R.end || null : null, tz: new Date().getTimezoneOffset() }; } function loadReport(sid) { const key = JSON.stringify([sid, R.period, R.start, R.end]); if (R.key === key && (R.data || R.loading || R.err)) return; // never retry a failed load on every redraw if (R.sid !== sid || R.key !== key) { R.saved = R.saved || {}; if (R.key) R.saved[R.key] = { coach: R.coach, sharedTo: R.sharedTo, shared: R.shared }; const back = R.saved[key] || {}; R.coach = back.coach || null; R.sharedTo = back.sharedTo || []; R.shared = back.shared || null; R.draft = ""; } R.sid = sid; R.key = key; R.loading = true; R.err = ""; api("api/report", { method: "POST", body: JSON.stringify(reportQuery()) }) .then((d) => { if (R.key === key) R.data = d; }).catch((e) => { R.err = e.message; R.data = null; }) .finally(() => { R.loading = false; render(); }); } function trend(cur, prev, unit = "") { if (cur == null || prev == null || cur === prev) return null; const up = cur > prev; return h("span", { class: `trend ${up ? "up" : "down"}`, text: up ? `▲ up from ${prev}${unit}` : `${prev}${unit} before` }); } function statsView(st) { const pv = st.previous || {}; const card = (big, label, tr) => h("div", { class: "stat" }, h("strong", { text: big }), h("span", { class: "hint", text: label }), tr); const wrap = h("div", { class: "report-body" }); wrap.append(h("div", { class: "stat-grid" }, card(String(st.minutes), "minutes (about)", trend(st.minutes, pv.minutes)), card(String(st.activeDays), st.activeDays === 1 ? "day active" : "days active", trend(st.activeDays, pv.activeDays)), card(String(st.partsLearnt), st.partsLearnt === 1 ? "part learnt" : "parts learnt", trend(st.partsLearnt, pv.partsLearnt)), card(String(st.quizzes), st.quizzes === 1 ? "quiz" : "quizzes", trend(st.quizzes, pv.quizzes)), card(st.average != null ? `${st.average}%` : "–", "average score", trend(st.average, pv.average, "%")), card(st.best != null ? `${st.best}%` : "–", st.fullMarks ? `best · ${st.fullMarks}× full marks` : "best score", null))); if (st.days && st.days.length > 1) { const max = Math.max(10, ...st.days.map((d) => d.minutes)); const bars = h("div", { class: "day-bars", role: "img", "aria-label": st.days.map((d) => `${d.date}: ${d.minutes} minutes, ${d.quizzes} quizzes`).join("; ") }, ...st.days.map((d) => h("div", { class: "day", title: `${d.date}: ${d.minutes} min, ${d.quizzes} quiz${d.quizzes === 1 ? "" : "zes"}${d.average != null ? `, average ${d.average}%` : ""}` }, h("span", { class: "bar", style: `height:${Math.round(100 * d.minutes / max)}%` }), d.quizzes ? h("span", { class: "dot", text: String(d.quizzes) }) : null, st.days.length <= 14 ? h("span", { class: "lbl", text: new Date(d.date + "T12:00").toLocaleDateString(undefined, st.days.length <= 7 ? { weekday: "short" } : { day: "numeric" }) }) : null))); wrap.append(h("div", { class: "chart" }, h("p", { class: "label", text: `Minutes each day · tallest bar ${max} min · green numbers are quizzes` }), bars)); } if (st.focus) { const f = st.focus; wrap.append(h("div", { class: "idea-list focus" }, h("p", { class: "label", text: "🎯 Focus" }), h("p", { text: `${f.focusedMinutes} min focused · ${f.awayMinutes} min away · switched away ${f.switchesAway} time${f.switchesAway === 1 ? "" : "s"}${f.quizzesSubmittedByLeaving ? ` · ${f.quizzesSubmittedByLeaving} quiz${f.quizzesSubmittedByLeaving > 1 ? "zes" : ""} submitted by leaving` : ""}` }), f.focusedShare != null ? h("div", { class: "focus-bar", role: "img", "aria-label": `${f.focusedShare}% of the time focused` }, h("span", { style: `width:${f.focusedShare}%` })) : null, h("p", { class: "hint", text: "Counted during quizzes and tutor chats. Focused means StepWise was on screen and being used. Away means another app or tab, the screen off, or 3 minutes with no tapping, scrolling or typing." }))); } const list = (title, items, fmt) => items && items.length ? h("div", { class: "idea-list" }, h("p", { class: "label", text: title }), h("ul", null, ...items.slice(0, 3).map((x) => h("li", null, ...fmt(x)))), items.length > 3 ? h("details", { class: "more" }, h("summary", { text: `Show ${items.length - 3} more` }), h("ul", null, ...items.slice(3).map((x) => h("li", null, ...fmt(x))))) : null) : null; const strongEl = list("🌟 Strong ideas (right every time)", st.strong, (x) => [h("span", { text: x.idea }), h("span", { class: "hint", text: ` · ${x.chapter} · ${x.right}/${x.of}` })]); const weakEl = list("🎯 Ideas to work on", st.weak, (x) => [h("span", { text: x.idea }), h("span", { class: "hint", text: ` · ${x.chapter} · ${x.right}/${x.of} right` })]); if (strongEl) wrap.append(strongEl); if (weakEl) wrap.append(weakEl); const extra = []; if (st.newChapters && st.newChapters.length) extra.push(`New this period: ${st.newChapters.join(", ")}`); if (st.bySubject && Object.keys(st.bySubject).length) extra.push("Quiz average by subject: " + Object.entries(st.bySubject).map(([k, v]) => `${k} ${v.average}% (${v.quizzes})`).join(" · ")); const fl = st.feelings || {}; const fe = { "feeling lost": "😕", "feeling repetitive": "🔁", "got insight": "💡", "gaining confidence": "💪" }; if (Object.keys(fl).length) extra.push("Feelings pressed: " + Object.entries(fl).map(([k, v]) => `${fe[k] || ""} ${k} ×${v}`).join(" · ")); if (st.notLearntYet) extra.push(`${st.notLearntYet} quiz question${st.notLearntYet > 1 ? "s" : ""} marked "not learnt yet"`); if (extra.length) wrap.append(h("div", { class: "idea-list" }, h("p", { class: "label", text: "📋 Also this period" }), h("ul", { class: "report-extra" }, ...extra.map((t) => h("li", { text: t }))))); if (!st.minutes && !st.quizzes && !st.partsLearnt) wrap.append(h("p", { class: "muted", text: "Nothing recorded in this period yet." })); return wrap; } async function coachSend(text) { if (R.busy) return; R.coach = R.coach || { id: null, msgs: [] }; if (text) R.coach.msgs.push({ who: "me", text }); R.busy = true; render(); try { const r = await api("api/report/coach", { method: "POST", body: JSON.stringify({ ...reportQuery(), coachId: R.coach.id, history: R.coach.msgs.map((m) => ({ role: m.who === "me" ? "user" : "assistant", content: m.text })) }) }); R.coach.id = r.coachId; R.coach.msgs.push({ who: "coach", text: r.reply }); } catch (e) { R.coach.msgs.push({ who: "system", text: e.message }); } R.busy = false; render(); } function coachView(forParent) { const box = h("section", { class: "sheet coach" }, h("h3", { text: forParent ? "✨ Coach: how is it going?" : "✨ Coach: how did I do?" })); if (!S.tutorOn) { box.append(h("p", { class: "muted", text: "The coach isn't switched on yet." })); return box; } if (!R.coach || !R.coach.msgs.length) { box.append(h("p", { class: "muted", text: forParent ? "Get feedback on this period: what went well, what to keep an eye on, and how you can help." : "Get feedback on this period: what went well, what to pay attention to, and what to do next." }), h("button", { class: "btn accent", disabled: R.busy || !R.data, text: R.busy ? "Thinking…" : "✨ Get feedback", onclick: () => coachSend("") })); return box; } for (const m of R.coach.msgs) box.append(h("div", { class: `bubble ${m.who === "me" ? "me" : m.who === "coach" ? "tutor" : "system"}` }, m.who === "coach" ? md(m.text) : h("p", { text: m.text }))); if (R.busy) box.append(h("div", { class: "bubble tutor" }, h("div", { class: "typing" }, h("span"), h("span"), h("span")))); const inp = h("input", { type: "text", placeholder: forParent ? "Ask the coach, e.g. how can I help this week?" : "Ask the coach, e.g. what should I focus on tomorrow?", "aria-label": "Ask the coach", maxlength: "500" }); inp.value = R.draft; inp.addEventListener("input", () => { R.draft = inp.value; }); box.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); const t = inp.value.trim(); if (t) { R.draft = ""; coachSend(t); } } }, inp, h("button", { class: "btn ghost", type: "submit", disabled: R.busy, text: "Ask" }))); return box; } function shareView(st) { const fam = (S.family && S.family[R.sid]) || []; const box = h("section", { class: "sheet share" }, h("h3", { text: "📤 Share this report" })); if (!fam.length) { box.append(h("p", { class: "muted", text: "No parent is linked to your account yet." })); return box; } const commentary = R.coach && (R.coach.msgs.find((m) => m.who === "coach") || {}).text || ""; box.append(h("p", { class: "muted", text: commentary ? "Your numbers and the feedback will be sent." : "Your numbers will be sent. Get feedback first if you'd like to include it." })); R.sharedTo = R.sharedTo || []; const send = async (ids) => { ids = ids.filter((x) => !R.sharedTo.includes(x)); if (!ids.length || R.sharing) return; R.sharing = true; try { const r = await api("api/report/share", { method: "POST", body: JSON.stringify({ ...reportQuery(), to: ids, commentary }) }); R.sharedTo.push(...ids); R.shared = { id: r.id, names: [...((R.shared && R.shared.names) || []), ...r.sharedWith] }; } catch (e) { toast(e.message); } finally { R.sharing = false; render(); } }; const icon = (p) => (p.relation === "Mom" ? "👩" : p.relation === "Dad" ? "👨" : "👤"); const row = h("div", { class: "topic-actions" }, ...fam.map((p) => R.sharedTo.includes(p.id) ? h("button", { class: "btn ghost", disabled: true, text: `✓ Sent to ${p.relation}` }) : h("button", { class: "btn ghost", text: `${icon(p)} ${p.relation}`, onclick: () => send([p.id]) }))); const left = fam.filter((p) => !R.sharedTo.includes(p.id)); if (fam.length > 1 && left.length > 1) row.append(h("button", { class: "btn ghost", text: left.length === 2 ? "👪 Both" : "👪 Everyone", onclick: () => send(left.map((p) => p.id)) })); box.append(row); if (R.shared) { const url = `${location.origin}${location.pathname}#/report/${R.shared.id}`; box.append(h("div", { class: "notice good" }, h("p", { text: `Sent to ${R.shared.names.join(" and ")}. They'll see it in their app. You can also send them this link:` }), h("div", { class: "add-student" }, h("input", { type: "text", value: url, readonly: true, "aria-label": "Report link" }), h("button", { class: "btn ghost", text: navigator.share ? "Send link…" : "Copy link", onclick: async () => { try { if (navigator.share) await navigator.share({ title: "My StepWise report", text: "Here's my StepWise report:", url }); else { await navigator.clipboard.writeText(url); toast("Link copied"); } } catch {} } })))); } return box; } function periodPicker() { const chips = h("div", { class: "selfmark period" }, ...PERIODS.map(([k, label]) => h("button", { type: "button", "aria-pressed": String(R.period === k), text: label, onclick: () => { R.period = k; R.data = null; R.key = ""; render(); } }))); const box = h("div", { class: "period-box" }, chips); if (R.period === "custom") { const st = R.data && R.data.stats; const dflt = (iso) => (iso ? iso.slice(0, 10) : ""); const a = h("input", { type: "date", value: R.start || dflt(st && st.from), "aria-label": "From" }); const b = h("input", { type: "date", value: R.end || (st ? new Date(new Date(st.to).getTime() - 864e5).toISOString().slice(0, 10) : ""), "aria-label": "To" }); box.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); R.start = a.value; R.end = b.value; R.data = null; R.key = ""; render(); } }, h("span", { text: "From" }), a, h("span", { text: "to" }), b, h("button", { class: "btn ghost", type: "submit", text: "Show" }))); } return box; } function renderReportFor(main, sid, forParent) { const st = S.students.get(sid); if (!st) return; loadReport(sid); const first = st.name.split(" ")[0]; main.append(h("section", { class: "home-hello" }, h("h2", { text: forParent ? `📈 ${first}'s report` : "📈 Your report" }), h("p", { class: "muted", text: forParent ? "How the chosen period went, compared with the period before." : "How you did, compared with the period before. Pick a period, get feedback, and share it with your parents." }), !forParent && ((S.family && S.family[sid]) || []).length ? h("p", { class: "hint", text: `👀 ${((S.family && S.family[sid]) || []).map((x) => x.relation).join(" and ")} can always see this page and read your tutor chats. Sharing sends them this period with the feedback, and lets them know.` }) : null)); main.append(h("section", { class: "sheet" }, periodPicker(), R.loading && !R.data ? h("p", { class: "muted", text: "Counting…" }) : R.err ? h("p", { class: "muted", text: R.err }) : R.data ? h("div", null, h("p", { class: "label", text: R.data.label }), statsView(R.data.stats)) : null)); if (R.data) main.append(coachView(forParent)); if (R.data && !forParent) main.append(shareView(R.data.stats)); } function noteBox(sid, reportId) { const st = S.students.get(sid); const first = st ? st.name.split(" ")[0] : ""; const inp = h("textarea", { rows: "2", maxlength: "500", placeholder: `A few words for ${first}…`, "aria-label": `Encouragement for ${first}` }); const send = async (text) => { if (!text.trim()) return; try { const n = await api("api/notes", { method: "POST", body: JSON.stringify({ studentId: sid, text, reportId: reportId || null }) }); S.notes.push(n); toast(`Sent to ${first} 💌`); render(); } catch (e) { toast(e.message); } }; const quick = ["So proud of you! 🌟", "Great effort this week 💪", "Keep going, you've got this! 🚀", "Loved seeing you stick with the hard bits ❤️"]; const sent = (S.notes || []).filter((n) => n.studentId === sid && n.fromUser === S.me.id).slice(-3).reverse(); return h("section", { class: "sheet" }, h("h3", { text: `💌 Send ${first} some encouragement` }), h("div", { class: "due-list" }, ...quick.map((q) => h("button", { class: "react", text: q, onclick: () => { inp.value = q; inp.focus(); } }))), h("form", { class: "note-form", onsubmit: (e) => { e.preventDefault(); send(inp.value); } }, inp, h("button", { class: "btn accent", type: "submit", text: "Send" })), sent.length ? h("div", null, h("p", { class: "label", text: "You sent" }), h("ul", { class: "hint" }, ...sent.map((n) => h("li", { text: `${chatWhen(n.created)} · ${n.text}${n.heart ? " · ❤️ back" : n.seen ? " · seen" : " · not seen yet"}` })))) : null); } async function renderSharedReport(main, rid) { if (!S.sharedReport || S.sharedReport.id !== rid) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "Opening the report…" }))); if (!S.sharedLoading) { S.sharedLoading = true; api(`api/reports/${encodeURIComponent(rid)}`).then((r) => { S.sharedReport = r; S.reportsList = null; }) .catch((e) => { S.sharedReport = { id: rid, error: e.message }; }).finally(() => { S.sharedLoading = false; render(); }); } return; } const r = S.sharedReport; main.append(h("div", null, backLink("← Back", () => { history.length > 1 ? history.back() : goPlace(S.studentId === "parent" ? "bank" : "today"); }))); if (r.error) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: r.error }))); return; } main.append(h("section", { class: "home-hello" }, h("h2", { text: `📈 ${r.student.split(" ")[0]}'s report · ${r.label}` }), h("p", { class: "muted", text: `Shared ${chatWhen(r.created)} with ${r.sharedWithNames.join(" and ")}` }))); main.append(h("section", { class: "sheet" }, statsView(r.stats))); if (r.commentary) main.append(h("section", { class: "sheet coach" }, h("h3", { text: "✨ What the coach said" }), h("div", { class: "bubble tutor" }, md(r.commentary)))); if (S.me.role !== "child") main.append(noteBox(r.studentId, r.id)); } function notesCard(sid) { S.heartedNow = S.heartedNow || new Set(); const mine = (S.notes || []).filter((n) => n.studentId === sid && (!n.seen || S.heartedNow.has(n.id))); const groups = new Map(); // the same words from the same person show once for (const n of mine) { const k = `${n.fromUser}|${n.text}`; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(n); } if (!groups.size) return null; const mark = async (items, heart) => { try { for (const n of items) { Object.assign(n, await api(`api/notes/${n.id}/seen${heart ? "?heart=true" : ""}`, { method: "POST" })); if (heart) S.heartedNow.add(n.id); } render(); } catch (e) { toast(e.message); } }; return h("section", { class: "sheet notes" }, ...[...groups.values()].slice(-3).map((items) => { const n = items[items.length - 1]; const hearted = items.every((x) => x.heart); return h("div", { class: "note" }, h("p", { class: "label", text: `💌 From ${n.relation === "Parent" ? n.fromName : n.relation} · ${chatWhen(n.created)}${items.length > 1 ? ` · ×${items.length}` : ""}` }), h("p", { class: "note-text", text: n.text }), h("div", { class: "topic-actions" }, hearted ? h("span", { class: "pill good", text: "❤️ sent" }) : h("button", { class: "btn accent small", text: "❤️ Thanks!", onclick: () => mark(items, true) }), h("button", { class: "react", text: hearted ? "Close" : "Got it", onclick: () => { items.forEach((x) => S.heartedNow.delete(x.id)); if (hearted) render(); else mark(items, false); } }))); })); } function kidWeek(sid) { S.kidWeek = S.kidWeek || {}; if (S.kidWeek[sid] === undefined) { S.kidWeek[sid] = null; api("api/report", { method: "POST", body: JSON.stringify({ studentId: sid, period: "week", tz: new Date().getTimezoneOffset() }) }) .then((r) => { S.kidWeek[sid] = r.stats; }).catch(() => { S.kidWeek[sid] = false; }).finally(() => render()); } return S.kidWeek[sid]; } function parentReports(main) { const kids = [...S.students.values()].filter((k) => !k.test).sort((a, b) => (a.name || "").localeCompare(b.name || "")); if (!kids.length) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "No children linked to your account yet." }))); return; } if (!B.kid || !S.students.has(B.kid)) B.kid = kids[0].id; const unreadBy = {}; for (const r of S.reportsList || []) if (r.unread) unreadBy[r.studentId] = (unreadBy[r.studentId] || 0) + 1; main.append(h("div", { class: "kid-cards" }, ...kids.map((k) => { const w = kidWeek(k.id); const lost = w && w.feelings ? w.feelings["feeling lost"] || 0 : 0; return h("button", { class: `kid-card ${B.kid === k.id ? "on" : ""}`, "aria-pressed": String(B.kid === k.id), onclick: () => { B.kid = k.id; B.chatOpen = null; render(); } }, h("strong", { text: k.name.split(" ")[0] }), h("span", { class: "hint", text: "This week" }), w ? h("span", { text: `${w.minutes} min · ${w.quizzes} quiz${w.quizzes === 1 ? "" : "zes"}${w.average != null ? ` · avg ${w.average}%` : ""} · ${w.partsLearnt} part${w.partsLearnt === 1 ? "" : "s"} learnt${w.focus && w.focus.focusedShare != null ? ` · ${w.focus.focusedShare}% focused` : ""}` }) : h("span", { class: "hint", text: w === false ? "Couldn't load" : "Loading…" }), h("span", null, unreadBy[k.id] ? h("span", { class: "pill warn", text: `📬 ${unreadBy[k.id]} new report${unreadBy[k.id] > 1 ? "s" : ""}` }) : null, lost ? h("span", { class: "pill", text: `😕 felt lost ×${lost}` }) : null)); }))); if (!S.reportsList && !S.reportsLoading) { S.reportsLoading = true; api("api/reports").then((r) => { S.reportsList = r; }).catch(() => { S.reportsList = []; }).finally(() => { S.reportsLoading = false; render(); }); } const shared = (S.reportsList || []).filter((r) => r.studentId === B.kid); if (shared.length) main.append(h("section", { class: "sheet" }, h("h3", { text: "📬 Reports shared with you" }), h("ul", { class: "chat-list" }, ...shared.slice(0, 8).map((r) => h("li", null, h("div", null, h("strong", { text: `${(S.students.get(r.studentId) || { name: "" }).name.split(" ")[0]} · ${r.label}` }), h("span", { class: "hint", text: ` · ${chatWhen(r.created)}` }), r.unread ? h("span", { class: "pill warn", text: "new" }) : null), h("button", { class: r.unread ? "btn accent small" : "react", text: "Open", onclick: () => { location.hash = `#/report/${r.id}`; } })))))); renderReportFor(main, B.kid, true); main.append(noteBox(B.kid, null)); main.append(kidChats(B.kid)); } function kidChats(sid) { if (!P.chats && !P.loadingChats) { P.loadingChats = true; api("api/parent/chats").then((r) => { P.chats = r; }).catch(() => { P.chats = []; }).finally(() => { P.loadingChats = false; render(); }); } const first = (S.students.get(sid) || { name: "" }).name.split(" ")[0]; const list = (P.chats || []).filter((c) => c.studentId === sid).slice(0, 6); const sec = h("section", { class: "sheet" }, h("h3", { text: `💬 ${first}'s recent tutor chats` }), h("p", { class: "hint", text: "Read-only. The newest first." })); if (!list.length) { sec.append(h("p", { class: "muted", text: P.chats ? "No chats yet." : "Loading…" })); return sec; } const ul = h("ul", { class: "chat-list" }); for (const c of list) { const isOpen = B.chatOpen && B.chatOpen.id === c.id; ul.append(h("li", { id: `pchat-${c.id}` }, h("div", null, h("strong", { text: `${c.subject} · ${c.chapter}` }), h("span", { class: "hint", text: ` · ${chatWhen(c.updated)} · ${c.messages} messages${c.flags && c.flags.length ? ` · ⚠️ ${c.flags.length} flag${c.flags.length > 1 ? "s" : ""}` : ""}` })), h("button", { class: "react", text: isOpen ? "Close" : "Read", onclick: async () => { if (isOpen) { B.chatOpen = null; return render(); } try { B.chatOpen = await api(`api/parent/chats/${encodeURIComponent(c.id)}`); } catch (e) { toast(e.message); } render(); requestAnimationFrame(() => { const el = $(`pchat-${c.id}`); if (el) el.scrollIntoView({ block: "start", behavior: "smooth" }); }); } }))); if (isOpen) { const log = h("li", { class: "chat-log-row" }, h("div", { class: "chat-log" }, h("p", { class: "label", text: `${c.subject} · ${c.chapter} · ${chatWhen(c.updated)}` }))); const box = log.firstChild; for (const f of B.chatOpen.flags || []) box.append(h("div", { class: `notice ${f.kind === "distress" ? "bad" : ""}` }, h("p", { text: `Flag (${f.kind.replace("_", " ")}): ${f.note}` }))); for (const m of B.chatOpen.transcript) box.append(h("div", { class: `bubble ${m.role === "student" ? "me" : "tutor"}` }, m.role === "student" ? h("p", { text: m.text }) : md(m.text))); box.append(h("button", { class: "react", text: "Close this chat", onclick: () => { B.chatOpen = null; render(); } })); ul.append(log); } } sec.append(ul); return sec; } function renderMyProgress(main) { const st = S.studentId && S.students.get(S.studentId); if (!st) { main.append(studentPicker(false)); return; } if (!T.mastery && !T.loadingM) loadMastery(); ensureActivity(); renderReportFor(main, st.id, false); main.append(h("h2", { class: "section-title", text: "📚 All your subjects" })); for (const s of subjectsFor(st)) { const rows = []; for (const u of unitsOf(s)) for (const c of u.chapters) { const pr = chapterProgress(c.id, st.id); if (pr.state === "new") continue; const best = quizzesOf(c.id).map((z) => bestOf(st.id, z.id)).filter(Boolean); const avg = best.length ? Math.round(best.reduce((t, a) => t + pct(a.score, a.max), 0) / best.length) : null; rows.push(h("button", { class: "prog-row", onclick: () => openChapter(c.id) }, h("strong", { text: chapterTitle(c.id) }), avg !== null ? h("span", { class: `pill ${band(avg)}`, text: `quizzes ${avg}%` }) : h("span"), h("span", { class: "prog-bar", "aria-hidden": "true" }, h("span", { style: `width:${pr.of ? Math.round(100 * pr.done / pr.of) : 0}%` })), h("span", { class: "hint", text: `${pr.done} of ${pr.of} ${pr.unit}${pr.quizDone ? ` · ${pr.quizDone} of ${pr.quizzes} quizzes done` : ""}` }))); } main.append(h("section", { class: "sheet" }, h("h3", { text: s.name }), rows.length ? h("div", { class: "prog-list" }, ...rows) : h("p", { class: "muted", text: "Not started yet." }))); } const recent = attemptsFor(st.id).slice(0, 8); if (recent.length) main.append(h("section", { class: "sheet" }, h("h3", { text: "Latest quizzes" }), h("ul", { class: "chat-list" }, ...recent.map((a) => { const set = S.sets.get(a.setId); const p = pct(a.score, a.max); return h("li", null, h("div", null, h("strong", { text: set ? (set.title || set.chapter) : a.chapter }), h("span", { class: "hint", text: ` · ${a.subject} · ${new Date(a.submittedAt).toLocaleDateString(undefined, { day: "numeric", month: "short" })}` })), h("span", { class: `pill ${band(p)}`, text: `${p}%` })); })))); } function renderChats(main) { const st = S.studentId && S.students.get(S.studentId); if (!st) { main.append(studentPicker(false)); return; } const list = myChats(null); const loading = S.myChats[`${S.studentId}|*`] === null; const fam = ((S.family && S.family[S.studentId]) || []).map((x) => x.relation); const sec = h("section", { class: "sheet" }, h("h2", { text: "💬 Your tutor chats" }), h("p", { class: "muted", text: "Every chat you've had with the tutor, newest first. Open one to read it again or carry on where you stopped." }), fam.length ? h("p", { class: "hint", text: `👀 ${fam.join(" and ")} can read these chats.` }) : null); if (!S.tutorOn) sec.append(h("p", { class: "muted", text: "The tutor isn't switched on yet." })); else if (loading) sec.append(h("p", { class: "muted", text: "Loading your chats…" })); else if (!list.length) sec.append(h("p", { class: "muted", text: "No chats yet. Open a topic in 📚 Subjects and press “Learn with the tutor”." })); const shown = S.chatFilter ? list.filter((c) => c.chapterId === S.chatFilter) : list; if (S.chatFilter) sec.append(h("div", { class: "selfmark" }, h("span", { class: "hint", text: `Only: ${chapterTitle(S.chatFilter)}` }), h("button", { type: "button", text: "Show all chats ✕", onclick: () => { S.chatFilter = null; render(); } }))); const groups = new Map(); for (const c of shown) { const subj = (CHAPTERS_INFO(c.chapterId) || {}).subject || "Other"; if (!groups.has(subj)) groups.set(subj, []); groups.get(subj).push(c); } for (const [subj, items] of groups) sec.append(h("div", { class: "chat-group" }, h("h3", { text: subj }), h("ul", { class: "chat-list" }, ...items.map((c) => chatRow(c, true))))); main.append(sec); } function chatsSection(cid) { const list = myChats(cid); if (!list.length) return null; const when = (iso) => new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }); const kinds = { learn: "Learn", ask: "Question", fix: "Fix mistakes", review: "Review" }; const shown = S.allChats === cid ? list : list.slice(0, 4); return h("section", { class: "sheet" }, h("h3", { text: "Your tutor chats" }), h("p", { class: "hint", text: "Open any chat to read it again or carry on where you stopped." }), h("ul", { class: "chat-list" }, ...shown.map((c) => h("li", null, h("div", null, h("strong", { text: `${kinds[c.kind] || c.kind}: ${c.title}` }), h("span", { class: "hint", text: ` · ${when(c.updated)} · ${c.messages} messages${c.complete ? " · finished" : c.atPart && !c.atPartLearnt ? ` · stopped at ${c.atPart}` : ""}` })), h("button", { class: "react", text: c.complete || c.atPartLearnt ? "Read" : "Open and carry on", onclick: () => reopenChat(c.id) })))), list.length > 4 ? h("button", { class: "react", text: S.allChats === cid ? "Show fewer" : `Show all ${list.length}`, onclick: () => { S.allChats = S.allChats === cid ? null : cid; render(); } }) : null); } function CHAPTERS_INFO(cid) { const t = (S.topics || {})[cid]; if (t) return t; const anySet = [...S.sets.values()].find((x) => (x.chapterId || x.id) === cid); return anySet ? { subject: anySet.subject, code: anySet.code, chapter: anySet.chapter } : null; } // Expected reply time: time to read the tutor's last message plus time to think, 2 to 6 minutes. // After that, ring once, show a nudge with help options; ring once more 3 minutes later, then stay quiet. const NUDGE_AGAIN_MS = 3 * 60 * 1000; function expectedReplyMs() { const last = [...T.msgs].reverse().find((m) => m.who === "tutor"); const words = last ? String(last.text).split(/\s+/).length : 60; return Math.min(6 * 60, Math.max(2 * 60, Math.round(words / 3) + 90)) * 1000; } function chatWaiting() { return S.view === "tutor" && T.sessionId && !T.readOnly && !T.busy && !T.complete && T.waitSince; } function resetWait() { T.waitSince = Date.now(); T.nudges = 0; T.nudge = false; document.title = BASE_TITLE; } function checkNudge() { if (!chatWaiting()) { if (document.title !== BASE_TITLE && !T.nudge) document.title = BASE_TITLE; return; } const since = Math.max(T.waitSince, T.lastTyped || 0); const due = expectedReplyMs() + (T.nudges || 0) * NUDGE_AGAIN_MS; if (Date.now() - since < due || (T.nudges || 0) >= 2) return; T.nudges = (T.nudges || 0) + 1; T.nudge = true; if (document.hidden) document.title = "⏰ Your tutor is waiting"; ALARM.ring(); render(); scrollChat(); } setInterval(checkNudge, 5000); document.addEventListener("visibilitychange", () => { if (!document.hidden) { awayPing({ kind: "back" }); document.title = BASE_TITLE; checkNudge(); return; } if (chatWaiting() && (T.nudges || 0) < 2) { const since = Math.max(T.waitSince, T.lastTyped || 0); awayPing({ kind: "chat", sessionId: T.sessionId, dueInMs: Math.max(0, since + expectedReplyMs() + (T.nudges || 0) * NUDGE_AGAIN_MS - Date.now()) }); } }); function nudgeCard() { const say = (text) => { T.draft = ""; const box = $("tutor-input"); if (box) box.value = text; else T.draft = text; resetWait(); tutorSend(text); }; return h("div", { class: "nudge", role: "alert" }, h("p", null, h("strong", { text: "⏰ Still there? " }), h("span", { text: "The tutor is waiting for your answer. If it's hard to answer, that's fine. Pick one:" })), h("div", { class: "topic-actions" }, h("button", { class: "btn accent", text: "🔁 Ask me again, more simply", onclick: () => say("I'm finding this hard to answer. Can you ask me again in a simpler way?") }), h("button", { class: "btn ghost", text: "💡 Give me a hint", onclick: () => say("Can I have a hint?") }), h("button", { class: "btn ghost", text: "✋ I'm here, still thinking", onclick: () => { resetWait(); render(); const b = $("tutor-input"); if (b) b.focus(); } }))); } function scrollChat() { T.stick = true; requestAnimationFrame(() => { const el = $("chat-scroll"); if (el) el.scrollTop = el.scrollHeight; }); } // How the session feels. Every press is saved as session feedback for the parent; "lost" and "repetitive" // also tell the tutor at once so it changes course. const FEELINGS = [ { tag: "feeling lost", label: "😕 Feeling lost", say: "I'm feeling lost." }, { tag: "feeling repetitive", label: "🔁 Feeling repetitive", say: "This feels repetitive." }, { tag: "got insight", label: "💡 Got an insight", say: null }, { tag: "gaining confidence", label: "💪 Gaining confidence", say: null }, ]; async function feel(f) { if (!T.sessionId || T.busy) return; const last = [...T.msgs].reverse().find((m) => m.who === "tutor"); api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId, excerpt: last ? last.text.slice(0, 600) : null, tags: [f.tag], text: "" }) }) .then((x) => S.feedback.push(x)).catch((e) => toast(e.message)); if (!f.say) return toast(f.tag === "got insight" ? "Nice! Noted." : "Great, noted."); const box = $("tutor-input"); const typed = (box ? box.value : T.draft).trim(); T.draft = `[${f.tag}] ${f.say}${typed ? " " + typed : ""}`; if (box) box.value = T.draft; tutorSend(); } async function react(m, up) { if (up) { m.rated = "up"; 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"); } catch (e) { m.rated = null; toast(e.message); } } else { m.open = !m.open; const k = JSON.stringify({ targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) }); m.open ? fbOpen.add(k) : fbOpen.delete(k); } render(); } function levelBar(byLevel, total) { const bar = h("div", { class: "lv-bar", role: "img", "aria-label": `Idea levels: ${byLevel.map((n, i) => `${n} at level ${i}`).join(", ")}` }); byLevel.forEach((n, i) => { if (n) bar.append(h("span", { class: `lv lv${i}`, style: `flex:${n}` })); }); if (!total) bar.append(h("span", { class: "lv lv0", style: "flex:1" })); return bar; } function renderTutor(main, dock, dockRow) { const st = S.studentId && S.students.get(S.studentId); if (S.studentId === "parent") { main.append(h("section", { class: "sheet" }, h("h2", { text: "The tutor is for the girls" }), h("p", { class: "muted", text: "Read every tutor chat, and the feedback on it, in the Progress tab." }))); return; } if (!st) { main.append(studentPicker(false)); return; } if (!S.tutorOn) { main.append(h("section", { class: "sheet" }, h("h2", { text: "The tutor isn't switched on yet" }), h("p", { class: "muted", text: "Your parent needs to finish setting it up. Self-checks work as normal." }))); return; } if (!T.sessionId && !T.busy) { S.view = "practise"; document.body.classList.remove("in-chat"); return render(); } if (false) { main.append(h("section", { class: "sheet" }, h("h2", { text: `${st.name}, pick a chapter` }), h("p", { class: "muted", text: "Today's practice is a short planned session: a few quick reviews, one or two new ideas, a stretch question and an exit ticket. Ask questions is free chat about the chapter. Your parent can read these chats." }), 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]))))); const grid = h("div", { class: "sets" }); const sets = [...S.sets.values()].sort((a, b) => (a.subject || "").localeCompare(b.subject || "")); for (const s of sets) { const ms = T.mastery && T.mastery[s.id]; grid.append(h("div", { class: "set-card" }, h("span", { class: "code", text: `${s.subject} · ${s.code}` }), h("h3", { text: s.chapter }), ms ? levelBar(ms.byLevel, ms.atoms) : h("div", { class: "lv-bar" }, h("span", { class: "lv lv0", style: "flex:1" })), ms ? h("span", { class: "hint", text: `${ms.byLevel.slice(2).reduce((a, b) => a + b, 0)} of ${ms.atoms} ideas at apply level or above` }) : null, h("div", { class: "students" }, h("button", { class: "btn accent", text: "Today's practice", onclick: () => tutorStart(s.id, "practice") }), h("button", { class: "btn ghost", text: "Ask questions", onclick: () => tutorStart(s.id, "chat") })))); } main.append(grid); return; } const set = S.sets.get(T.setId) || {}; document.body.classList.add("in-chat"); const scroller = h("div", { class: "chat-scroll", id: "chat-scroll", role: "log", "aria-live": "polite", "aria-label": "Tutor conversation" }); for (const m of T.msgs) { const b = h("div", { class: `bubble ${m.who}` }, m.who === "tutor" ? md(m.text) : h("p", { text: m.text })); if (m.conf) b.append(h("span", { class: "hint", text: `You said: ${m.conf}` })); if (m.changes && m.changes.length) { const ups = m.changes.filter((c) => c.to > c.from).length, downs = m.changes.filter((c) => c.to < c.from).length; 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(" · ") })); } const ft = { targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) }; if (m.open && !fbOpen.has(JSON.stringify(ft))) m.open = false; if (m.who === "tutor" && T.sessionId && !T.readOnly) { b.append(h("div", { class: "bubble-actions" }, 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) }), h("button", { type: "button", class: "react", "aria-pressed": String(!!m.open), text: "Not quite…", onclick: () => react(m, false) }))); if (m.open) b.append(feedbackWidget(ft, "Tell us what was wrong")); } scroller.append(b); } 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")))); if (!T.busy && T.parts && T.parts.chunkDone && !T.complete) scroller.append(partCard(T.parts)); if (T.nudge && chatWaiting()) scroller.append(nudgeCard()); if (T.complete && T.summary) { const sm = T.summary; const card = h("div", { class: "summary-card" }, h("h3", { text: T.parts ? "Topic learnt" : "Session complete" }), h("p", { class: "cheer-line", text: T.parts ? pick([`You've learnt the whole topic, ${firstName()}! Every part, one step at a time. That's real work.`, "Topic complete! You answered the big question piece by piece. That's how experts learn.", "That's the whole topic done. The quiz is your chance to show what you now know."], T.sessionId) : pick(["Well done for putting the time in today.", "Session done. Every one of these makes the next one easier.", "Nice work. Steady practice is what builds confidence."], T.sessionId) }), h("p", { class: "muted", text: T.parts ? `${T.parts.learnt} of ${T.parts.of} ideas learnt${sm.answered ? ` · ${sm.right} of ${sm.answered} answers right` : ""}` : `${sm.steps} of ${sm.of} steps done${sm.answered ? ` · ${sm.right} of ${sm.answered} answers right` : ""}` })); if (sm.up && sm.up.length) card.append(h("p", { class: "label", text: "Ideas that moved up" }), h("ul", null, ...sm.up.slice(0, 6).map((u) => h("li", { text: u.idea || u.atom })))); if (sm.down && sm.down.length) card.append(h("p", { class: "label", text: "Ideas to revisit" }), h("ul", null, ...sm.down.slice(0, 6).map((u) => h("li", { text: u.idea || u.atom })))); const acts = h("div", { class: "students" }); const lastPart = T.parts && T.parts.chunkDone && T.parts.chunkDone.quizId && S.sets.get(T.parts.chunkDone.quizId); if (lastPart) acts.append(h("button", { class: "btn ghost", text: `Part quiz: ${T.parts.chunkDone.title} · ${lastPart.questions.length} Qs`, onclick: () => { endSession(); startTest(lastPart.id); } })); if (sm.next && sm.next.kind === "quiz" && S.sets.has(sm.next.id)) acts.append(h("button", { class: "btn accent", text: sm.next.label, onclick: () => { endSession(); startTest(sm.next.id); } })); if (sm.next && sm.next.kind === "learn") { const cid = T.chapterId; acts.append(h("button", { class: "btn accent", text: sm.next.label, onclick: () => { endSession(); tutorStart({ chapterId: cid, kind: "learn", topicId: sm.next.topicId, chunkId: sm.next.chunkId }); } })); } acts.append(h("button", { class: "btn ghost", text: "Back to the chapter", onclick: () => { endSession(); render(); } })); card.append(acts); scroller.append(card); } 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 }); ta.value = T.draft; const grow = () => { ta.style.height = "auto"; ta.style.height = Math.min(ta.scrollHeight, 180) + "px"; }; ta.addEventListener("input", () => { T.draft = ta.value; T.lastTyped = Date.now(); if (T.nudge) { T.nudge = false; document.title = BASE_TITLE; } grow(); }); ta.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); tutorSend(); } }); const confRow = h("div", { class: "selfmark", role: "group", "aria-label": "How sure are you?" }, h("span", { class: "hint", text: "How sure?" }), ...["guess", "think so", "sure"].map((c) => h("button", { type: "button", "aria-pressed": String(T.conf === c), text: c, onclick: () => { T.conf = T.conf === c ? null : c; T.draft = ta.value; render(); } }))); const sessionFbKey = JSON.stringify({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId }); const shell = h("section", { class: "chat-shell" }, h("div", { class: "chat-head" }, h("div", { class: "title" }, backLink("← Back", () => { const ro = T.readOnly; if (history.length > 1) history.back(); else { endSession(); render(); } if (!ro && T.msgs.length > 1) toast("Saved. Carry on any time from 💬 Chats."); }), h("span", { class: "label", text: `${(CHAPTERS_INFO(T.chapterId) || {}).subject || ""} · ${(CHAPTERS_INFO(T.chapterId) || {}).chapter || ""}` }), h("h2", { text: T.goal || "Starting…" })), T.sessionId ? h("button", { type: "button", class: "react", text: fbOpen.has(sessionFbKey) ? "Close feedback" : "Feedback on session", onclick: () => { fbOpen.has(sessionFbKey) ? fbOpen.delete(sessionFbKey) : fbOpen.add(sessionFbKey); render(); } }) : null), T.parts && T.parts.parts && !T.readOnly ? partsBar(T.parts) : null, T.plan.length && !(T.parts && T.complete) ? h("ol", { class: "steps", "aria-label": "Session steps" }, ...T.plan.map((p, i) => h("li", { class: `step ${p.status !== "todo" ? "done" : i === T.step ? "now" : ""}`, "aria-current": i === T.step && !T.complete ? "step" : null }, h("span", { class: "dot", text: p.status === "done" ? "✓" : p.status === "skipped" ? "–" : String(i + 1) }), h("span", { text: p.label })))) : null, 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, scroller, T.readOnly ? h("div", { class: "chat-composer read-only" }, h("p", { class: "muted", text: T.complete ? "This chat is finished. You can read it here any time." : "You've learnt this part since this chat, so it's here to read." }), h("button", { class: "btn ghost", text: "← Back", onclick: () => { if (history.length > 1) history.back(); else { endSession(); render(); } } })) : h("div", { class: "chat-composer" }, h("div", { class: "input-row" }, ta, h("button", { class: "btn accent", text: "Send", disabled: T.busy, onclick: tutorSend })), T.sessionId ? h("div", { class: "selfmark feel-row", role: "group", "aria-label": "How is this going?" }, h("span", { class: "hint", text: "🙂 How's it going?" }), ...FEELINGS.map((f) => h("button", { type: "button", disabled: T.busy, text: f.label, onclick: () => feel(f) }))) : null, h("div", { class: "meta-row" }, confRow, h("span", { class: "hint", text: "Your parent can read these chats." })))); main.append(shell); requestAnimationFrame(() => { grow(); if (T.stick || T.scrollPos == null) scroller.scrollTop = scroller.scrollHeight; else scroller.scrollTop = T.scrollPos; T.stick = false; scroller.addEventListener("scroll", () => { const nearBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 60; T.scrollPos = nearBottom ? null : scroller.scrollTop; }, { passive: true }); if (!T.busy && !T.readOnly && document.activeElement === document.body && window.innerWidth > 720) ta.focus({ preventScroll: true }); }); } // ---------- parent area ---------- const P = { chats: null, open: null }; const papi = (path) => api(path); async function loadParent() { try { [P.chats, P.settings, P.costs] = await Promise.all([papi("api/parent/chats"), papi("api/settings"), papi("api/costs")]); P.err = ""; } catch (e) { P.chats = []; toast(e.message); } render(); } async function openChat(id) { if (P.open && P.open.id === id) { P.open = null; return render(); } try { P.open = await papi(`api/parent/chats/${encodeURIComponent(id)}`); } catch (e) { toast(e.message); } render(); } function parentArea() { const sec = h("section", { class: "sheet" }, h("h2", { text: "Parent area" })); if (S.studentId !== "parent") { sec.append(h("p", { class: "muted", text: "Choose \"I'm the parent\" from the name list to read tutor chats and download results." })); return sec; } if (P.chats == null) { loadParent(); sec.append(h("p", { class: "muted", text: "Loading chats…" })); return sec; } sec.append(h("div", { class: "students" }, h("a", { class: "btn ghost", href: `api/export/attempts.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Attempts (CSV)" }), h("a", { class: "btn ghost", href: `api/export/answers.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Every answer (CSV)" }), h("a", { class: "btn ghost", href: `api/export/atoms.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Ideas by student (CSV)" }), h("a", { class: "btn ghost", href: `api/export/chats.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "All tutor chats (CSV)" }), h("a", { class: "btn ghost", href: `api/export/feedback.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "All feedback (CSV)" }))); // tutor model routing and running costs const modeLabels = { auto: "Auto (by question)", opus: "Always Opus 5.5", fable: "Always Fable 5.1" }; const current = (P.settings && P.settings.tutorRouting) || "auto"; sec.append(h("h3", { text: "Tutor model" }), h("p", { class: "muted", text: "Auto sends quick replies to Opus 5.5 at low effort and sends 'why' questions, multi-step working and replies after a wrong answer to Fable 5.1. Pick a fixed model to compare them." }), h("div", { class: "selfmark", role: "group", "aria-label": "Tutor model" }, ...Object.entries(modeLabels).map(([k, label]) => h("button", { type: "button", "aria-pressed": String(current === k), text: label, onclick: async () => { try { P.settings = await api("api/settings", { method: "POST", body: JSON.stringify({ tutorRouting: k }) }); toast(`Tutor now uses: ${label}`); render(); } catch (e) { toast(e.message); } } })))); const bm = (P.costs && P.costs.byModel) || {}; if (Object.keys(bm).length) { const t = h("table"); t.append(h("thead", null, h("tr", null, h("th", { text: "Model" }), h("th", { class: "num", text: "Replies" }), h("th", { class: "num", text: "Avg time" }), h("th", { class: "num", text: "Avg cost" }), h("th", { class: "num", text: "Total" })))); const tb = h("tbody"); for (const v of Object.values(bm)) tb.append(h("tr", null, h("td", { text: v.label }), h("td", { class: "num", text: String(v.turns) }), h("td", { class: "num", text: `${v.avgSeconds}s` }), h("td", { class: "num", text: `$${v.avgCost.toFixed(3)}` }), h("td", { class: "num", text: `$${v.cost.toFixed(2)}` }))); tb.append(h("tr", null, h("td", { text: "All tutor use" }), h("td"), h("td"), h("td"), h("td", { class: "num", text: `$${(P.costs.total || 0).toFixed(2)}` }))); t.append(tb); sec.append(h("div", { class: "table-wrap" }, t)); } else sec.append(h("p", { class: "hint", text: "Costs appear here after the first tutor session." })); sec.append(h("h3", { text: "Tutor chats" })); if (!P.chats.length) sec.append(h("p", { class: "muted", text: "No tutor chats yet." })); for (const c of P.chats) { const flags = c.flags || []; const row = h("button", { class: "set-card chat-row", onclick: () => openChat(c.id) }, h("div", { class: "meta" }, h("strong", { text: c.student }), h("span", { text: `${c.subject} · ${c.chapter}` }), h("span", { text: c.mode === "practice" ? "practice" : "questions" }), h("span", { class: "mono", text: fmtDate(c.updated) })), h("div", { class: "meta" }, h("span", { text: `${c.messages} messages` }), h("span", { text: `${c.correct}/${c.attempts} answers right` }), h("span", { class: "mono", text: `$${(c.cost || 0).toFixed(2)}` }), h("span", { text: (c.models || []).join(" + ") }), ...flags.map((f) => h("span", { class: `pill ${f.kind === "distress" ? "bad" : "warn"}`, text: f.kind.replace("_", " ") })))); sec.append(row); if (P.open && P.open.id === c.id) { const log = h("div", { class: "chat log" }); const sessFb = S.feedback.filter((f) => f.sessionId === c.id); if (sessFb.length) log.append(h("p", { class: "label", text: "Feedback on this session" }), feedbackList(sessFb, false)); for (const f of P.open.flags || []) log.append(h("div", { class: `notice ${f.kind === "distress" ? "bad" : ""}` }, h("p", { text: `Flag (${f.kind.replace("_", " ")}): ${f.note}` }))); for (const m of P.open.transcript) log.append(h("div", { class: `bubble ${m.role === "student" ? "me" : "tutor"}` }, h("span", { class: "hint", text: `${m.role === "student" ? c.student : "Tutor"} · ${fmtDate(m.t)}${m.confidence ? " · " + m.confidence : ""}` + (m.model ? ` · ${m.model.includes("fable") ? "Fable 5.1" : m.model.includes("opus-5-5") ? "Opus 5.5" : m.model} ${m.effort || ""} · ${m.seconds}s · $${(m.cost || 0).toFixed(3)} · ${m.why || ""}` : "") }), h("p", { text: m.text }))); sec.append(log); } } return sec; } function connectionNotice() { return h("div", { class: "notice bad" }, h("p", { text: "The results store isn't answering. Check the internet connection and reload the page." })); } function studentPicker(compact) { const wrap = h("section", { class: "sheet" }); wrap.append(h("div", null, h("h2", { text: compact ? "Switch student" : "Who is practising?" }), h("p", { class: "muted", text: "Open a child's view to practise or look around as them, or go back to the parent view." }))); const list = h("div", { class: "students" }); const names = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || "")); if (!names.length) list.append(h("p", { class: "muted", text: "No students yet. Add the first name below." })); for (const s of names) { const subs = subjectsFor(s).map((x) => x.name); list.append(h("button", { class: "student", "aria-pressed": String(s.id === S.studentId), onclick: () => { S.studentId = s.id; store.set("sw.student", s.id); S.picking = false; S.subjectCode = null; S.chapterId = null; T.mastery = null; S.activity = null; render(); } }, h("span", { text: s.name + (s.test ? " (test)" : "") }), subs.length ? h("span", { class: "hint", text: subs.length > 4 ? `${subs.slice(0, 4).join(", ")} +${subs.length - 4}` : subs.join(", ") }) : null)); } list.append(h("button", { class: "student parent", "aria-pressed": String(S.studentId === "parent"), text: S.me && S.me.role === "admin" ? "Admin and parent view" : "Parent view", onclick: () => { S.studentId = "parent"; store.set("sw.student", "parent"); S.picking = false; S.view = "bank"; render(); } })); wrap.append(list); wrap.append(h("div", { class: "students" }, h("button", { class: "btn ghost", text: "My account", onclick: () => { S.picking = false; S.view = "account"; render(); } }), h("button", { class: "btn ghost", text: "Log out", onclick: () => signOut("Logged out") }))); return wrap; } function chapterIds() { const ids = new Set(Object.keys(S.topics || {})); for (const x of S.sets.values()) ids.add(x.chapterId || x.id); return [...ids].sort((a, b) => ((CHAPTERS_INFO(a) || {}).subject || "").localeCompare((CHAPTERS_INFO(b) || {}).subject || "") || a.localeCompare(b)); } function quizzesOf(cid) { return [...S.sets.values()].filter((x) => (x.chapterId || x.id) === cid && x.active !== false && x.kind !== "chunk").sort((a, b) => (a.order || 0) - (b.order || 0)); } function partStatus(cid, chunkId) { const c = (T.mastery && T.mastery.chunks) || {}; return (c[`${cid}/${chunkId}`] || {}).status || "todo"; } // Where to learn the ideas a student marked "not learnt yet": the earliest part (or topic) that teaches any of them. function learnTargetFor(cid, atomIds) { const tdoc = (S.topics || {})[cid]; if (!tdoc || !atomIds.length) return null; const want = new Set(atomIds); for (const t of tdoc.topics) { for (const c of t.chunks || []) if ((c.atom_ids || []).some((a) => want.has(a))) return { chapterId: cid, kind: "learn", topicId: t.id, chunkId: c.id, label: c.title }; if (!(t.chunks || []).length && (t.atom_ids || []).some((a) => want.has(a))) return { chapterId: cid, kind: "learn", topicId: t.id, label: t.title }; } return null; } function bestOf(studentId, quizId) { const xs = attemptsFor(studentId, quizId); if (!xs.length) return null; return xs.reduce((m, a) => (pct(a.score, a.max) > pct(m.score, m.max) ? a : m)); } function learnedTopics(cid) { const act = (S.activity && S.activity[S.studentId]) || { sessions: [] }; const out = new Set(act.sessions.filter((x) => x.chapterId === cid && x.kind === "learn" && x.complete).map((x) => x.topicId)); for (const t of ((S.topics || {})[cid] || {}).topics || []) { // a topic in parts is learnt only when every part is if ((t.chunks || []).length) { if (t.chunks.every((c) => partStatus(cid, c.id) === "learned")) out.add(t.id); else out.delete(t.id); } } return out; } function renderPractise(main) { const st = S.studentId && S.students.get(S.studentId); if (!st || S.picking) { main.append(studentPicker(!!st)); if (!st) return; } if (!T.mastery && !T.loadingM) loadMastery(); if (!S.activity && !S.loadingActivity) { S.loadingActivity = true; api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (["practise", "progress"].includes(S.view)) render(); }); } if (S.chapterId && chapterIds().includes(S.chapterId)) return renderChapter(main, st); const subj = S.subjectCode && catSubjects().find((x) => x.code === S.subjectCode); if (subj) return renderSubject(main, st, subj); if (S.place === "subjects") return renderSubjectList(main, st); renderHome(main, st); } // ---------- catalogue: board → subject → syllabus unit → chapter (data/catalog.json) ---------- function catSubjects() { return (S.catalog && S.catalog.subjects) || []; } function boardName(id) { const b = ((S.catalog && S.catalog.boards) || []).find((x) => x.id === id); return b ? b.name : ""; } function boardLine(subjects) { return [...new Set(subjects.map((s) => boardName(s.board)))].filter(Boolean).join(" · "); } function hasContent(cid) { return !!((S.topics || {})[cid] || quizzesOf(cid).length); } // A subject's units with their published chapters; chapters the catalogue doesn't place yet go last. function unitsOf(subj) { const placed = new Set(subj.units.flatMap((u) => u.chapters.map((c) => c.id))); const units = subj.units.map((u) => ({ ...u, chapters: u.chapters.filter((c) => hasContent(c.id)) })).filter((u) => u.chapters.length); const extra = chapterIds().filter((cid) => !placed.has(cid) && (CHAPTERS_INFO(cid) || {}).code === subj.code).map((id) => ({ id })); if (extra.length) units.push({ num: "", title: "More chapters", chapters: extra }); return units; } function chapterEntry(cid) { for (const s of catSubjects()) for (const u of s.units) for (const c of u.chapters) if (c.id === cid) return { subject: s, unit: u, ch: c }; const s = catSubjects().find((x) => x.code === (CHAPTERS_INFO(cid) || {}).code); return s ? { subject: s, unit: null, ch: { id: cid } } : null; } // The subjects a child sees. Not set up yet: every IGCSE subject that has chapters (the old behaviour). function subjectsFor(st) { const all = catSubjects(); if (st && Array.isArray(st.subjects)) return all.filter((s) => st.subjects.includes(s.code)); return all.filter((s) => s.board === "igcse" && unitsOf(s).length); } function chapterTitle(cid) { return (CHAPTERS_INFO(cid) || {}).chapter || cid; } function openChapter(cid) { const e = chapterEntry(cid); if (e) S.subjectCode = e.subject.code; S.chapterId = cid; S.view = "practise"; S.run = null; render(); window.scrollTo(0, 0); } // How far a child is through a chapter: parts learnt if it has parts, else topics learnt, else quizzes done. function chapterProgress(cid, sid) { const tdoc = (S.topics || {})[cid]; const parts = tdoc ? tdoc.topics.flatMap((t) => (t.chunks || []).map((c) => c.id)) : []; const qz = quizzesOf(cid); const quizDone = qz.filter((z) => bestOf(sid, z.id)).length; let done, of, unit; if (parts.length) { done = parts.filter((p) => partStatus(cid, p) === "learned").length; of = parts.length; unit = "parts"; } else if (tdoc) { const L = learnedTopics(cid); done = tdoc.topics.filter((t) => L.has(t.id)).length; of = tdoc.topics.length; unit = "topics"; } else { done = quizDone; of = qz.length; unit = "quizzes"; } const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[cid]; const touched = done > 0 || quizDone > 0 || !!(ms && ms.seen); return { done, of, unit, quizDone, quizzes: qz.length, ms, state: of && done >= of ? "done" : touched ? "doing" : "new" }; } // The next thing to learn in a chapter: its first part (or topic) not learnt yet. function nextInChapter(cid) { const tdoc = (S.topics || {})[cid]; if (!tdoc) return null; const learned = learnedTopics(cid); for (const t of tdoc.topics) { const chunks = t.chunks || []; if (chunks.length) { const c = chunks.find((x) => partStatus(cid, x.id) !== "learned"); if (c) return { chapterId: cid, topicId: t.id, chunkId: c.id, title: c.title, topic: t.title, question: c.question }; } else if (!learned.has(t.id)) return { chapterId: cid, topicId: t.id, title: t.title, topic: t.title, question: t.goal }; } return null; } // Carry on from the last Learn session; otherwise the first chapter in progress; otherwise the first not done. function carryOnTarget(st, subjects) { const order = subjects.flatMap((s) => unitsOf(s).flatMap((u) => u.chapters.map((c) => c.id))); const act = (S.activity && S.activity[st.id]) || { sessions: [] }; const last = act.sessions.find((x) => x.kind === "learn" && order.includes(x.chapterId)); if (last) { const n = nextInChapter(last.chapterId); if (n) return { ...n, resume: true }; } for (const want of ["doing", "new"]) for (const cid of order) { if (chapterProgress(cid, st.id).state !== want) continue; const n = nextInChapter(cid); if (n) return { ...n, resume: want === "doing" }; } return null; } function backLink(text, fn) { return h("button", { type: "button", class: "fb-toggle back-link", text, onclick: fn }); } function renderHome(main, st) { const subjects = subjectsFor(st); main.append(h("section", { class: "home-hello" }, h("h2", { text: `Hello ${st.name}` }), h("p", { class: "muted", text: subjects.length ? `${boardLine(subjects)} · ${subjects.map((s) => s.name).join(", ")}` : "No subjects chosen yet." }))); const nc = notesCard(st.id); if (nc) main.append(nc); const rc = remindersCard(false); if (rc) main.append(rc); const row = h("div", { class: "home-row" }); const next = carryOnTarget(st, subjects); if (next) { const e = chapterEntry(next.chapterId); row.append(h("section", { class: "sheet next-card" }, h("p", { class: "label", text: next.resume ? "Carry on" : "Start here" }), h("h3", { text: next.title }), h("p", { class: "muted", text: [e && e.subject.name, chapterTitle(next.chapterId), next.topic !== next.title ? next.topic : ""].filter(Boolean).join(" · ") }), next.question && next.question !== next.title ? h("p", { class: "q-line", text: next.question }) : null, h("div", { class: "topic-actions" }, S.tutorOn ? h("button", { class: "btn accent", text: next.chunkId ? "Learn this part" : "Learn this topic", onclick: () => tutorStart({ chapterId: next.chapterId, kind: "learn", topicId: next.topicId, chunkId: next.chunkId }) }) : null, h("button", { class: "btn ghost", text: "Open the chapter", onclick: () => openChapter(next.chapterId) })))); } const due = []; for (const s of subjects) for (const u of unitsOf(s)) for (const c of u.chapters) { const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[c.id]; if (ms && ms.due) due.push({ cid: c.id, n: ms.due, subject: s.name }); } if (due.length && S.tutorOn) { due.sort((a, b) => b.n - a.n); const top = due[0]; row.append(h("section", { class: "sheet" }, h("p", { class: "label", text: "🔁 Quick review" }), h("h3", { text: `${top.subject} · ${chapterTitle(top.cid)}` }), h("p", { class: "muted", text: "A few quick questions on ideas you met a while ago, so they don't fade. About 5 minutes." }), h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: "Start a quick review", onclick: () => tutorStart({ chapterId: top.cid, kind: "review" }) })), due.length > 1 ? h("details", { class: "more" }, h("summary", { text: `Other chapters to review (${due.length - 1})` }), h("div", { class: "due-list" }, ...due.slice(1, 8).map((d) => h("button", { class: "react", text: `${d.subject} · ${chapterTitle(d.cid)}`, onclick: () => tutorStart({ chapterId: d.cid, kind: "review" }) })))) : null)); } const wk0 = weekSummary(st.id); const ws = kidWeek(st.id); const wk = ws ? { minutes: ws.minutes, quizzes: ws.quizzes, best: ws.best, parts: ws.partsLearnt } : wk0; row.append(h("section", { class: "sheet week" }, h("p", { class: "label", text: "📅 This week" }), h("div", { class: "week-stats" }, h("div", null, h("strong", { text: String(wk.minutes) }), h("span", { class: "hint", text: "minutes (about)" })), h("div", null, h("strong", { text: String(wk.quizzes) }), h("span", { class: "hint", text: wk.quizzes === 1 ? "quiz" : "quizzes" })), h("div", null, h("strong", { text: wk.best !== null ? `${wk.best}%` : "–" }), h("span", { class: "hint", text: "best score" })), h("div", null, h("strong", { text: String(wk.parts) }), h("span", { class: "hint", text: wk.parts === 1 ? "part learnt" : "parts learnt" }))))); const open = S.tutorOn ? myChats(null).filter((c) => !c.complete && !c.atPartLearnt).slice(0, 2) : []; if (open.length) row.append(h("section", { class: "sheet" }, h("p", { class: "label", text: "💬 Chats you can carry on" }), h("ul", { class: "chat-list" }, ...open.map((c) => chatRow(c, true))))); if (row.children.length) main.append(row); main.append(h("div", { class: "students" }, h("button", { class: "btn ghost", text: "📚 See all your subjects", onclick: () => goPlace("subjects") }))); } // Monday-to-now totals for the Today card function weekSummary(sid) { const d = new Date(); const day = (d.getDay() + 6) % 7; d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - day); const since = d.toISOString(); const qs = S.attempts.filter((a) => a.studentId === sid && a.submittedAt >= since); const sess = ((S.activity && S.activity[sid]) || { sessions: [] }).sessions.filter((x) => x.updated >= since); const chunks = (T.mastery && T.mastery.chunks) || {}; return { quizzes: qs.length, best: qs.length ? Math.max(...qs.map((a) => pct(a.score, a.max))) : null, minutes: sess.reduce((t, x) => t + Math.min(45, x.minutes || 0), 0) + Math.round(qs.reduce((t, a) => t + Math.min(1800, a.durationSec || 0), 0) / 60), // a chat or quiz left open counts at most 45 / 30 min parts: Object.values(chunks).filter((c) => c.status === "learned" && c.at >= since).length }; } function renderSubjectList(main, st) { const subjects = subjectsFor(st); const grid = h("div", { class: "subject-grid" }, ...subjects.map((s) => subjectCard(s, st))); main.append(h("section", { class: "home-subjects" }, h("h2", { class: "section-title", text: "📚 Your subjects" }), subjects.length ? grid : h("div", { class: "sheet" }, h("p", { class: "muted", text: "No subjects yet. Ask a parent or the admin to add you to a class." })))); } function subjectCard(s, st) { const units = unitsOf(s); const style = `--subj: hsl(${s.hue || 220} 55% 45%)`; const top = h("div", { class: "subject-top" }, h("span", { class: "subj-mark", "aria-hidden": "true", text: s.mark || s.name[0] }), h("div", null, h("h3", { text: s.name }), h("span", { class: "code", text: `${boardName(s.board)} · ${s.code}` }))); if (!units.length) return h("div", { class: "subject-card soon", style }, top, h("p", { class: "muted", text: "Chapters are being written. They'll appear here when they're ready." })); const byL = [0, 0, 0, 0, 0]; let atoms = 0, chapters = 0, started = 0, done = 0; for (const u of units) for (const c of u.chapters) { const p = chapterProgress(c.id, st.id); chapters++; if (p.state !== "new") started++; if (p.state === "done") done++; if (p.ms) { p.ms.byLevel.forEach((n, i) => { byL[i] += n; }); atoms += p.ms.atoms; } } const solid = byL[2] + byL[3] + byL[4]; return h("button", { class: "subject-card", style, onclick: () => { S.subjectCode = s.code; S.chapterId = null; render(); window.scrollTo(0, 0); } }, top, h("div", { class: "meta" }, h("span", { text: `${units.length} unit${units.length > 1 ? "s" : ""} · ${chapters} chapter${chapters > 1 ? "s" : ""}` }), h("span", { text: done ? `${done} done · ${started - done} in progress` : started ? `${started} in progress` : "Not started" })), levelBar(byL, atoms), h("span", { class: "hint", text: atoms ? `${solid} of ${atoms} ideas solid` : "" })); } function renderSubject(main, st, s) { main.append(h("section", { class: "sheet" }, h("div", null, backLink("← Subjects", () => { S.subjectCode = null; S.place = "subjects"; render(); window.scrollTo(0, 0); }), h("span", { class: "label", text: `${boardName(s.board)} · ${s.code}` }), h("h2", { text: s.name })), h("p", { class: "muted", text: "Chapters grouped by syllabus unit. “Best after” means a chapter builds on an earlier one; you can still open any chapter." }))); const units = unitsOf(s); if (!units.length) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "Chapters for this subject are being written. They'll appear here as soon as they're ready." }))); return; } for (const u of units) { main.append(h("section", { class: "sheet unit" }, h("div", { class: "unit-head" }, u.num ? h("span", { class: "unit-num", text: `Unit ${u.num}` }) : null, h("h3", { text: u.title })), h("ol", { class: "ch-path" }, ...u.chapters.map((c) => chapterStop(c, st))))); } } function chapterStop(c, st) { const p = chapterProgress(c.id, st.id); const before = (c.buildsOn || []).filter((b) => hasContent(b) && chapterProgress(b, st.id).state !== "done"); const [cls, label] = p.state === "done" ? ["good", "Done"] : p.state === "doing" ? ["warn", "In progress"] : before.length ? ["", `Best after: ${before.map(chapterTitle).join(", ")}`] : ["accent", "Ready to start"]; const where = [c.ref ? `Syllabus ${c.ref}` : "", c.book ? `Book ${c.book}` : ""].filter(Boolean).join(" · "); return h("li", { class: `ch-stop ${p.state}` }, h("span", { class: "ch-dot", "aria-hidden": "true", text: p.state === "done" ? "✓" : "" }), h("button", { class: "ch-card", onclick: () => openChapter(c.id) }, h("div", { class: "ch-top" }, h("span", { class: "code", text: where }), h("span", { class: `pill ${cls}`, text: label })), h("h3", { text: chapterTitle(c.id) }), h("div", { class: "meta" }, p.of ? h("span", { text: `${p.done} of ${p.of} ${p.unit} learnt` }) : null, p.quizzes && p.unit !== "quizzes" ? h("span", { text: `${p.quizDone} of ${p.quizzes} quizzes done` }) : null, p.ms && p.ms.due ? h("span", { class: "pill warn", text: `${p.ms.due} to review` }) : null), p.ms ? levelBar(p.ms.byLevel, p.ms.atoms) : null)); } function chapterLinks(cid) { const e = chapterEntry(cid); if (!e) return null; const before = (e.ch.buildsOn || []).filter(hasContent); const after = catSubjects().flatMap((s) => s.units.flatMap((u) => u.chapters)).filter((c) => (c.buildsOn || []).includes(cid) && hasContent(c.id)).map((c) => c.id); if (!before.length && !after.length) return null; const chip = (x) => h("button", { class: "react", text: chapterTitle(x), onclick: () => openChapter(x) }); return h("div", { class: "ch-links" }, before.length ? h("span", { class: "hint", text: "Builds on" }) : null, ...before.map(chip), after.length ? h("span", { class: "hint", text: before.length ? " · Leads to" : "Leads to" }) : null, ...after.map(chip)); } function renderChapter(main, st) { const cid = S.chapterId; const info = CHAPTERS_INFO(cid) || {}; const tdoc = (S.topics || {})[cid]; const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[cid]; const lv = (T.mastery && T.mastery.levels) || {}; const ent = chapterEntry(cid); const where = ent ? [ent.subject.name, ent.unit && ent.unit.num ? `Unit ${ent.unit.num}` : "", ent.ch.ref ? `Syllabus ${ent.ch.ref}` : "", ent.ch.book ? `Book ${ent.ch.book}` : ""].filter(Boolean).join(" · ") : `${info.subject || ""} · ${info.code || ""}`; const head = h("section", { class: "sheet" }, h("div", { class: "test-bar" }, h("div", null, backLink(ent ? `← ${ent.subject.name}` : "← Home", () => { S.chapterId = null; if (ent) S.subjectCode = ent.subject.code; render(); }), h("span", { class: "label", text: where }), h("h2", { text: info.chapter || cid })), S.tutorOn && ms && (ms.due || ms.seen) ? h("button", { class: "btn ghost", text: ms.due ? `Review ${ms.due} due idea${ms.due > 1 ? "s" : ""} with the tutor` : "Quick review with the tutor", onclick: () => tutorStart({ chapterId: cid, kind: "review" }) }) : null), chapterLinks(cid), ms ? levelBar(ms.byLevel, ms.atoms) : null, ms ? h("details", { class: "more" }, h("summary", { text: "What do the colours mean?" }), 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])))) : null); main.append(head); if (S.tutorOn) { const list = myChats(cid); if (list.length) { const open = list.find((c) => !c.complete && !c.atPartLearnt); main.append(h("section", { class: "sheet chat-strip" }, h("span", { text: `💬 ${list.length} chat${list.length > 1 ? "s" : ""} in this chapter` }), open ? h("button", { class: "btn accent small", text: `Carry on: ${open.atPart || open.title}`, onclick: () => reopenChat(open.id) }) : null, h("button", { class: "react", text: "See this chapter's chats", onclick: () => { S.chatFilter = cid; goPlace("chats"); } }))); } } if (!tdoc) { // chapter not split into topics yet: list its quizzes const list = h("section", { class: "sheet" }, h("p", { class: "muted", text: "Topics for this chapter are on their way. For now, here is its quiz." })); for (const z of quizzesOf(cid)) list.append(quizButton(st, z)); main.append(list); return; } const learned = learnedTopics(cid); const path = h("ol", { class: "topic-path" }); const topicDone = (t) => learned.has(t.id) || ((t.chunks || []).length && (t.chunks || []).every((c) => partStatus(cid, c.id) === "learned")); const current = tdoc.topics.find((t) => !topicDone(t)) || tdoc.topics.find((t) => { const q = S.sets.get(t.quizId); return q && !bestOf(st.id, q.id); }); S.openTopics = S.openTopics || new Set(); tdoc.topics.forEach((t, i) => { const quiz = S.sets.get(t.quizId); const best = quiz && bestOf(st.id, quiz.id); const ids = t.atom_ids || []; const byL = [0, 0, 0, 0, 0]; ids.forEach((a) => { byL[Math.min(4, lv[a] || 0)]++; }); const chunks = t.chunks || []; const nLearnt = chunks.filter((c) => partStatus(cid, c.id) === "learned").length; const nextPart = chunks.find((c) => partStatus(cid, c.id) !== "learned"); const isDone = topicDone(t); const resume = S.tutorOn && !isDone ? resumableChat(cid, t.id) : null; const status = isDone ? `✓ learnt${best ? ` · quiz ${pct(best.score, best.max)}%` : quiz ? " · quiz not taken yet" : ""}` : chunks.length ? (nLearnt ? `${nLearnt} of ${chunks.length} parts learnt` : `${chunks.length} parts`) : "Not started"; let partsEl = null; if (chunks.length) { partsEl = h("ol", { class: "parts-list", "aria-label": `Parts of ${t.title}` }, ...chunks.map((c, j) => { const stt = partStatus(cid, c.id); const pq = S.sets.get(c.quizId); const pb = pq && bestOf(st.id, pq.id); const isNext = nextPart && c.id === nextPart.id; const act = stt === "learned" ? (pq ? h("button", { class: "react", text: pb ? `Part quiz · best ${pct(pb.score, pb.max)}%` : `Part quiz · ${pq.questions.length} Qs`, onclick: () => startTest(pq.id) }) : null) : S.tutorOn ? h("button", { class: "react", text: "Learn this part", onclick: () => tutorStart({ chapterId: cid, kind: "learn", topicId: t.id, chunkId: c.id }) }) : null; return h("li", { class: `${stt}${isNext ? " next" : ""}` }, h("span", { class: "pnum", text: stt === "learned" ? "✓" : stt === "skipped" ? "–" : String(j + 1) }), h("div", { class: "pbody" }, h("strong", { text: c.title }), isNext ? h("span", { class: "hint", text: c.question }) : null, h("div", { class: "topic-actions" }, act))); })); } // one main action, one quiz button, everything else under "More" const main1 = S.tutorOn && !isDone ? h("button", { class: "btn accent", text: resume ? `Carry on your chat: ${resume.atPart}` : nextPart && nLearnt ? `Continue: ${nextPart.title}` : "Learn with the tutor", onclick: () => (resume ? reopenChat(resume.id) : tutorStart({ chapterId: cid, kind: "learn", topicId: t.id })) }) : null; const quizBtn = quiz ? h("button", { class: isDone && !best ? "btn accent" : "btn ghost", text: best ? `Quiz again · best ${pct(best.score, best.max)}%` : `Take the ${chunks.length ? "topic " : ""}quiz · ${quiz.questions.length} Qs`, onclick: () => startTest(quiz.id) }) : null; const more = [ S.tutorOn && isDone ? h("button", { class: "react", text: "Learn again", onclick: () => tutorStart({ chapterId: cid, kind: "learn", topicId: t.id }) }) : null, S.tutorOn ? h("button", { class: "react", text: "Ask the tutor a question", onclick: () => tutorStart({ chapterId: cid, kind: "ask", topicId: t.id }) }) : null, t.visualQuizId && S.sets.get(t.visualQuizId) ? (() => { const vz = S.sets.get(t.visualQuizId); const vb = bestOf(st.id, vz.id); return h("button", { class: "react", text: vb ? `Diagram quiz · best ${pct(vb.score, vb.max)}%` : `Diagram quiz · ${vz.questions.length} Qs`, onclick: () => startTest(vz.id) }); })() : null, t.visual ? h("button", { class: "react", "aria-expanded": String(S.explore === `${cid}/${t.id}`), text: S.explore === `${cid}/${t.id}` ? "Hide the diagram" : "Explore the diagram", onclick: () => { S.explore = S.explore === `${cid}/${t.id}` ? null : `${cid}/${t.id}`; S.openTopics.add(`${cid}/${t.id}`); render(); } }) : null].filter(Boolean); const moreEl = more.length ? h("details", { class: "more" }, h("summary", { text: "More" }), h("div", { class: "topic-actions" }, ...more)) : null; const key = `${cid}/${t.id}`; const det = h("details", { class: "topic-fold" }, h("summary", null, h("span", { class: "topic-num", text: isDone ? "✓" : String(i + 1) }), h("span", { class: "topic-sum" }, h("strong", { text: t.title }), h("span", { class: "hint", text: status }))), h("div", { class: "topic-body" }, h("p", { class: "muted", text: t.goal }), levelBar(byL, ids.length), partsEl, h("div", { class: "topic-actions" }, main1, quizBtn), moreEl, t.visual && S.explore === key ? explorerEl(t.visual, key) : null)); det.open = S.openTopics.has(key) || (!S.closedTopics || !S.closedTopics.has(key)) && current && current.id === t.id; // remember the choice the moment it's tapped, so a redraw straight after can't undo it det.querySelector("summary").addEventListener("click", () => { S.closedTopics = S.closedTopics || new Set(); if (!det.open) { S.openTopics.add(key); S.closedTopics.delete(key); } else { S.openTopics.delete(key); S.closedTopics.add(key); } }); path.append(h("li", { class: `topic ${isDone ? "done" : ""}${current && current.id === t.id ? " current" : ""}` }, det)); }); const mixed = S.sets.get(tdoc.mixedQuizId); if (mixed) { const best = bestOf(st.id, mixed.id); path.append(h("li", { class: `topic final ${best ? "done" : ""}` }, h("div", { class: "topic-num", text: best ? "✓" : "★" }), h("div", { class: "topic-body" }, h("h3", { text: mixed.title }), h("p", { class: "muted", text: mixed.intro || "A mixed review across the whole chapter." }), h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: best ? `Again · best ${pct(best.score, best.max)}%` : `Take the review · ${mixed.questions.length} Qs`, onclick: () => startTest(mixed.id) }))))); } main.append(h("section", { class: "sheet" }, path)); } function quizButton(st, z) { const best = bestOf(st.id, z.id); const marks = (z.questions || []).reduce((t, q) => t + (Number(q.marks) || 1), 0); return h("button", { class: "set-card", onclick: () => startTest(z.id) }, h("h3", { text: z.title || z.chapter }), h("div", { class: "meta" }, h("span", { text: `${(z.questions || []).length} questions` }), h("span", { text: `${marks} marks` }), h("span", { text: `${z.minutes || 10} min` })), best ? h("span", { class: `pill ${band(pct(best.score, best.max))}`, text: `Best ${pct(best.score, best.max)}%` }) : h("span", { class: "pill", text: "Not tried yet" })); } // Diagrams come from static/visuals (an ES module loaded beside this script); until it arrives, show a placeholder. function figureEl(fig, reveal) { if (window.StepVis) return window.StepVis.renderFigure(fig, { reveal }) || h("span"); const ph = h("p", { class: "muted", text: "Loading the diagram…" }); document.addEventListener("stepvis", () => ph.replaceWith(window.StepVis.renderFigure(fig, { reveal }) || h("span")), { once: true }); return ph; } const exploreSeeds = {}; function explorerEl(v, key) { const wrap = h("div", { class: "explore" }); const scen = v.scenarios || [v.scenario]; const build = () => { if (!window.StepVis) { wrap.replaceChildren(h("p", { class: "muted", text: "Loading the diagram…" })); document.addEventListener("stepvis", build, { once: true }); return; } const seed = exploreSeeds[key] || 1; const sc = scen[(seed - 1) % scen.length]; const inst = window.StepVis.sampleFor(v.cls, sc, seed * 7919); wrap.replaceChildren(inst ? window.StepVis.explorer(v.cls, inst) : h("p", { class: "muted", text: "No example could be made." }), h("button", { class: "react", type: "button", text: "Try a new example", onclick: () => { exploreSeeds[key] = seed + 1; build(); } })); }; build(); return wrap; } function questionBody(q, idx, mode) { const r = S.run; const resp = r.responses[q.id]; const res = r.results && r.results[q.id]; const body = h("div", { class: "body" }); body.append(h("p", { class: "prompt", text: q.prompt || "" })); if (q.figure) body.append(figureEl(q.figure, mode === "review")); const name = `q-${q.id}`; if (q.type === "mcq" || q.type === "multi") { if (q.type === "multi") body.append(h("p", { class: "select-n", text: `Select ${(q.answer || []).length}` })); const opts = h("div", { class: "opts", role: q.type === "mcq" ? "radiogroup" : "group" }); (q.options || []).forEach((opt, i) => { const checked = q.type === "mcq" ? Number(resp) === i && resp != null : (resp || []).map(Number).includes(i); const input = h("input", { type: q.type === "mcq" ? "radio" : "checkbox", name, id: `${name}-${i}`, value: String(i), disabled: mode !== "test" }); input.checked = checked; input.addEventListener("change", () => { r.notLearnt.delete(q.id); if (q.type === "mcq") r.responses[q.id] = i; else { const cur = new Set((r.responses[q.id] || []).map(Number)); const n = (q.answer || []).length; if (input.checked && cur.size >= n) toast(`This question asks for ${n}. Ticking more than ${n} scores 0, so untick one first if you change your mind.`); input.checked ? cur.add(i) : cur.delete(i); r.responses[q.id] = [...cur].sort(); } saveDraft(); updateDock(); updateNav(); }); let cls = "opt"; if (mode === "review") { const isAns = q.type === "mcq" ? Number(q.answer) === i : (q.answer || []).map(Number).includes(i); if (isAns) cls += " right"; else if (checked) cls += " wrong"; } opts.append(h("label", { class: cls, for: `${name}-${i}` }, input, h("span", null, h("span", { class: "mono muted", text: String.fromCharCode(65 + i) + " " }), opt))); }); body.append(opts); } else if (q.type === "numeric") { const input = h("input", { type: "text", inputmode: "decimal", id: name, autocomplete: "off", disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` }); input.value = resp == null ? "" : String(resp); input.addEventListener("input", () => { r.responses[q.id] = input.value; r.notLearnt.delete(q.id); saveDraft(); updateDock(); updateNav(); }); body.append(h("div", { class: "numeric" }, input, q.unit ? h("span", { class: "mono", text: q.unit }) : null)); if (mode === "test") body.append(h("p", { class: "hint", text: "Numbers only. Standard form can be typed as 6.02 x 10^23." })); } else { const ta = h("textarea", { id: name, disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` }); ta.value = resp == null ? "" : String(resp); ta.addEventListener("input", () => { r.responses[q.id] = ta.value; r.notLearnt.delete(q.id); saveDraft(); updateDock(); updateNav(); }); body.append(ta); } if (mode === "test") { const on = r.notLearnt.has(q.id); body.append(h("button", { type: "button", class: "react notlearnt-btn", "aria-pressed": String(on), text: on ? "Marked: I haven't learnt this yet (tap to undo)" : "I haven't learnt this yet", onclick: () => { if (on) r.notLearnt.delete(q.id); else { r.notLearnt.add(q.id); delete r.responses[q.id]; } saveDraft(); render(); } })); if (on) body.append(h("p", { class: "hint", text: "That's fine. It scores 0 but isn't counted as a mistake, and after the quiz you can learn it with the tutor." })); } if (mode === "review") body.append(reviewBlock(q, res), questionFlags(S.run.setId, q), feedbackWidget({ targetType: "question", setId: S.run.setId, questionId: q.id }, "Something's wrong with this question")); return body; } function reviewBlock(q, res) { const r = S.run; const box = h("div", { class: "scheme" }); if (res.notLearnt) { box.append(h("div", { class: "verdict" }, h("span", { class: "pill", text: `0/${res.max}` }), h("span", { text: "Not learnt yet: not counted as a mistake. Learn it with the tutor, then try again." }))); } else if (res.auto) { const v = h("div", { class: "verdict" }, h("span", { class: `pill ${res.right ? "good" : res.got > 0 ? "warn" : "bad"}`, text: `${res.got}/${res.max}` }), h("span", { text: res.right ? "Correct" : res.got > 0 ? "Partly correct" : res.over ? `Not correct: more than ${(q.answer || []).length} options were selected` : "Not correct" })); box.append(v); if (q.type === "numeric") { const sfText = (x, n) => { const t = Number(x).toPrecision(n); return t.includes("e") ? String(Number(t)) : t; }; const shown = q.sf != null ? sfText(q.answer, q.sf) : q.dp != null ? Number(q.answer).toFixed(q.dp) : fmtNum(Number(q.answer)); box.append(h("p", null, h("span", { class: "label", text: "Answer " }), h("span", { class: "mono", text: `${shown}${q.unit ? " " + q.unit : ""}` }), q.sf != null ? h("span", { class: "hint", text: ` (to ${q.sf} significant figures)` }) : q.dp != null ? h("span", { class: "hint", text: ` (to ${q.dp} decimal place${q.dp > 1 ? "s" : ""})` }) : null)); if (res.parsed == null && r.responses[q.id]) box.append(h("p", { class: "hint", text: "Your answer couldn't be read as a number. Type digits only, for example 0.25 or 2.5 x 10^-3." })); } } else { box.append(h("p", { class: "label", text: "Mark your own answer" })); const row = h("div", { class: "selfmark", role: "group", "aria-label": "Marks you award yourself" }); for (let m = 0; m <= res.max; m++) { row.append(h("button", { type: "button", "aria-pressed": String(r.self[q.id] === m), text: String(m), onclick: () => { r.self[q.id] = m; render(); if (!r.saved && reviewTotals().pendingSelf === 0) saveAttempt(); } })); } box.append(row, h("span", { class: "hint", text: `out of ${res.max}. Give yourself a mark only for each point you clearly made.` })); } if (q.mark_scheme) box.append(h("p", null, h("span", { class: "label", text: "Mark scheme " }), q.mark_scheme)); if (q.explanation) box.append(h("p", null, h("span", { class: "label", text: "Why " }), q.explanation)); return box; } function answeredCount() { const set = S.sets.get(S.run.setId); return (set.questions || []).filter((q) => isAnswered(q)).length; } function updateDock() { const s = $("dock-status"); if (!s || !S.run) return; const set = S.sets.get(S.run.setId); s.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`; } // ---------- quiz player: one question at a time ---------- const FLAG_GROUPS = [ { label: "Is this in your syllabus?", tags: ["in syllabus", "not taught yet", "not in syllabus"] }, { label: "For you, this was", tags: ["too easy", "just right", "too hard"] }, ]; function questionFlags(setId, q) { if (!S.studentId || S.studentId === "parent") return null; const mine = S.feedback.filter((f) => f.by === S.studentId && f.targetType === "question" && f.setId === setId && f.questionId === q.id) .sort((x, y) => String(x.created).localeCompare(String(y.created))); const box = h("div", { class: "qflags" }); for (const g of FLAG_GROUPS) { const latest = [...mine].reverse().find((f) => f.tags.some((t) => g.tags.includes(t))); const current = latest && latest.tags.find((t) => g.tags.includes(t)); box.append(h("div", { class: "qflag-row" }, h("span", { class: "hint", text: g.label }), h("div", { class: "selfmark", role: "group", "aria-label": g.label }, ...g.tags.map((t) => h("button", { type: "button", "aria-pressed": String(current === t), text: t, onclick: async () => { try { const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "question", setId, questionId: q.id, tags: [t], text: "" }) }); S.feedback.push(f); render(); } catch (e) { toast(e.message); } } }))))); } return box; } function isAnswered(q) { if (S.run.notLearnt && S.run.notLearnt.has(q.id)) return true; const v = S.run.responses[q.id]; return v != null && v !== "" && !(Array.isArray(v) && !v.length); } function goTo(i) { const set = S.sets.get(S.run.setId); const n = (set.questions || []).length; S.run.idx = Math.max(0, Math.min(n - 1, i)); render(); const card = $("qcard"); if (card) card.scrollIntoView({ block: "nearest" }); } function navChip(q, i) { const r = S.run; const cls = ["qchip"]; if (i === r.idx) cls.push("current"); if (r.phase === "test") { if (isAnswered(q)) cls.push("answered"); if (r.marked.has(q.id)) cls.push("marked"); } else { const res = r.results[q.id]; const got = res.auto ? res.got : r.self[q.id]; cls.push(res.notLearnt ? "notlearnt" : got == null ? "pending" : got >= res.max ? "right" : got > 0 ? "part" : "wrong"); } const state = r.phase === "test" ? (isAnswered(q) ? "answered" : "not answered") + (r.marked.has(q.id) ? ", marked to come back to" : "") : cls.includes("notlearnt") ? "not learnt yet" : cls.includes("pending") ? "needs self-marking" : cls.includes("right") ? "correct" : cls.includes("part") ? "partly correct" : "not correct"; return h("button", { type: "button", class: cls.join(" "), "aria-current": i === r.idx ? "step" : null, "aria-label": `Question ${i + 1}, ${state}`, text: String(i + 1), onclick: () => goTo(i) }); } function updateNav() { const nav = $("qnav"); if (!nav || !S.run) return; const set = S.sets.get(S.run.setId); nav.replaceChildren(...(set.questions || []).map(navChip)); const c = $("answered-count"); if (c) c.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`; } function renderPlayer(main, dock, dockRow, mode) { const r = S.run; const set = S.sets.get(r.setId); if (!set) { S.view = "practise"; S.run = null; return render(); } const qs = set.questions || []; const n = qs.length; const q = qs[r.idx]; const title = set.title ? `${set.title}` : (set.chapter || set.id); const t = mode === "review" ? reviewTotals() : null; // sticky bar: title, timer or score, question numbers const bar = h("div", { class: "quizbar" }, h("div", { class: "quizbar-top" }, h("div", { class: "title" }, backLink(mode === "test" ? "← Leave quiz" : "← Back to the chapter", () => { if (mode === "test") { saveDraft(); clearInterval(timerHandle); toast("Your answers are kept on this device. Open the quiz again to carry on."); } S.chapterId = set.chapterId || set.id; S.view = "practise"; S.place = "subjects"; S.run = null; render(); window.scrollTo(0, 0); }), h("span", { class: "label", text: `${set.subject || ""} · ${set.chapter || ""}` }), h("h2", { text: title })), mode === "test" ? 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() })) : 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}` }))), h("nav", { class: "qnav", id: "qnav", "aria-label": "Questions" }, ...qs.map(navChip)), h("div", { class: "legend" }, ...(mode === "test" ? [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` })] : [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"), r.notLearnt.size ? h("span", null, h("span", { class: "qchip mini notlearnt" }), "not learnt yet") : null, t.pendingSelf ? h("span", null, h("span", { class: "qchip mini pending" }), `${t.pendingSelf} to mark yourself`) : null]))); main.append(bar); if (mode === "test") { main.append(r.warning ? h("div", { class: "notice bad", role: "alert" }, h("p", { text: "⚠️ You left the quiz. That was your one warning: if you switch to another app or tab again, the quiz will be submitted as it is." }), h("button", { class: "btn ghost", text: "OK, I'll stay", onclick: () => { r.warning = false; render(); } })) : h("p", { class: "hint stay-hint", text: "🔒 Stay on this screen until you submit. Switching to another app or tab submits the quiz." })); } if (mode === "review" && r.leftQuiz) main.append(h("div", { class: "notice bad" }, h("p", { text: "This quiz was submitted because you left the quiz screen. Unanswered questions count as wrong. Next time, stay on the quiz until you press Submit." }))); if (mode === "review") { const p = pct(t.got, t.max); main.append(h("div", { class: `notice ${r.saved ? "good" : ""}` }, h("p", { text: r.saved ? `Saved: ${t.got}/${t.max} (${p}%) in ${Math.max(1, Math.round((r.durationSec || 0) / 60))} min. Tap any number to see that question.` : t.pendingSelf ? `Mark your written answer${t.pendingSelf > 1 ? "s" : ""} (dashed numbers) and your result saves automatically.` : "Saving your result…" }))); if (r.saved && S.studentId !== "parent") { r.cheer = r.cheer || quizCheer(r, t); main.append(h("div", { class: `cheer ${r.cheer.band}`, role: "status" }, h("strong", { text: r.cheer.title }), h("p", { text: r.cheer.line }))); } if (r.notLearnt.size) { const cid = set.chapterId || set.id; const atomIds = qs.filter((x) => r.notLearnt.has(x.id)).flatMap((x) => x.atom_ids || []); const target = set.kind === "chunk" && set.chunkId ? { chapterId: cid, kind: "learn", topicId: set.topicId, chunkId: set.chunkId, label: set.chunkTitle } : learnTargetFor(cid, atomIds); main.append(h("div", { class: "notice" }, h("p", { text: `You marked ${r.notLearnt.size} question${r.notLearnt.size > 1 ? "s" : ""} as not learnt yet. That's not counted as a mistake.` }), target && S.tutorOn ? h("div", { class: "students" }, h("button", { class: "btn accent", text: `Learn ${r.notLearnt.size > 1 ? "them" : "it"} now: ${target.label}`, onclick: () => { const { label, ...opts } = target; tutorStart(opts); } })) : null)); } } // the question card const card = h("section", { class: "sheet qcard", id: "qcard" }, 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" : ""}` }), 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", onclick: () => { r.marked.has(q.id) ? r.marked.delete(q.id) : r.marked.add(q.id); render(); } }) : null), questionBody(q, r.idx, mode), h("div", { class: "qcard-nav" }, h("button", { type: "button", class: "btn ghost", disabled: r.idx === 0, "aria-label": "Previous question", text: "← Previous", onclick: () => goTo(r.idx - 1) }), r.idx < n - 1 ? h("button", { type: "button", class: "btn accent", "aria-label": "Next question", text: "Next →", onclick: () => goTo(r.idx + 1) }) : mode === "test" ? h("button", { type: "button", class: "btn accent", text: "Submit and mark", onclick: confirmSubmit }) : null)); main.append(card); if (mode === "review") main.append(h("section", { class: "sheet" }, feedbackWidget({ targetType: "set", setId: r.setId }, "Feedback on this whole quiz"))); // bottom dock: leave / submit, or after review: where next dock.hidden = false; if (mode === "test") { dockRow.append(h("span", { class: "status", id: "dock-status" }), h("button", { class: "btn accent", text: "Submit and mark", onclick: confirmSubmit })); updateDock(); } else { dockRow.append(h("span", { class: "status", text: r.saved ? "Result saved" : t.pendingSelf ? `${t.pendingSelf} to mark yourself` : "Saving…" }), h("button", { class: "btn ghost", text: "Back to the chapter", onclick: () => { if (!r.saved && t.pendingSelf) toast("Mark your written answers first, or this result won't be saved"); S.chapterId = set.chapterId || set.id; S.view = "practise"; S.run = null; render(); } }), r.saved && S.tutorOn && qs.some((x) => { const res = r.results[x.id]; const g = res.auto ? res.got : r.self[x.id]; return !res.notLearnt && g != null && g < res.max; }) ? h("button", { class: "btn accent", text: `Fix my mistakes with the tutor`, onclick: () => tutorStart({ chapterId: set.chapterId || set.id, kind: "fix", attemptId: r.attemptId }) }) : null); } if (r.confirming) { const left = n - answeredCount(); main.append(h("div", { class: "notice", role: "alertdialog", "aria-label": "Submit the quiz?" }, h("p", { text: left ? `${left} question${left > 1 ? "s are" : " is"} not answered yet. Submit anyway?` : "Submit your answers for marking?" }), h("div", { class: "students" }, h("button", { class: "btn ghost", text: "Keep working", onclick: () => { r.confirming = false; render(); } }), h("button", { class: "btn accent", text: "Submit", onclick: () => { r.confirming = false; submitTest(); } })))); requestAnimationFrame(() => window.scrollTo(0, document.body.scrollHeight)); } } function confirmSubmit() { S.run.confirming = true; render(); } function renderTest(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "test"); } function renderReview(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "review"); } document.addEventListener("keydown", (e) => { if (!S.run || !["test", "review"].includes(S.view)) return; const tag = (e.target && e.target.tagName) || ""; if (["INPUT", "TEXTAREA", "SELECT"].includes(tag) && e.target.type !== "radio" && e.target.type !== "checkbox") return; if (e.key === "ArrowRight") { e.preventDefault(); goTo(S.run.idx + 1); } if (e.key === "ArrowLeft") { e.preventDefault(); goTo(S.run.idx - 1); } }); function renderProgress(main) { const students = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || "")); if (!students.length) { main.append(studentPicker(false)); return; } const sid = S.progressStudent && S.students.has(S.progressStudent) ? S.progressStudent : (S.studentId && S.students.has(S.studentId) ? S.studentId : students[0].id); S.progressStudent = sid; const codes = new Set(students.flatMap((s) => subjectsFor(s).map((x) => x.code))); // only the shown children's courses const sets = [...S.sets.values()].filter((x) => codes.has(x.code)) .sort((a, b) => (a.subject || "").localeCompare(b.subject || "") || (a.order || 0) - (b.order || 0)); // overview matrix: students × sets, latest % const ov = h("section", { class: "sheet" }, h("h2", { text: "Everyone at a glance" }), h("p", { class: "muted", text: "Latest score on each self-check. Pick a name to see which ideas need more practice." })); const tw = h("div", { class: "table-wrap" }); const table = h("table"); table.append(h("thead", null, h("tr", null, h("th", { text: "Self-check" }), ...students.map((s) => h("th", { class: "num" }, h("button", { class: "student", style: "min-width:0;padding:4px 10px;font-size:.85rem", "aria-pressed": String(s.id === sid), text: s.name, onclick: () => { S.progressStudent = s.id; render(); } })))))); const tb = h("tbody"); if (!sets.length) tb.append(h("tr", null, h("td", { colspan: String(students.length + 1), class: "muted", text: "No self-checks published yet." }))); const latestByStudent = new Map(students.map((s) => [s.id, latestPerSet(s.id)])); for (const set of sets) { tb.append(h("tr", null, h("td", null, h("div", { text: set.chapter || set.id }), h("div", { class: "mono muted", style: "font-size:.75rem", text: `${set.subject || ""} ${set.code || ""}` })), ...students.map((s) => { const a = latestByStudent.get(s.id).get(set.id); if (!a) return h("td", { class: "num muted", text: "—" }); const p = pct(a.score, a.max); return h("td", { class: "num" }, h("span", { class: `pill ${band(p)}`, text: `${p}%` })); }))); } table.append(tb); tw.append(table); ov.append(tw); main.append(ov); // weak ideas for the chosen student, from the latest attempt of each set const st = S.students.get(sid); const latest = latestByStudent.get(sid); const atomAgg = new Map(); for (const a of latest.values()) { const set = S.sets.get(a.setId); const names = (set && set.atoms) || {}; for (const [atom, gm] of Object.entries(a.atoms || {})) { const cur = atomAgg.get(atom) || { got: 0, max: 0, text: names[atom] || "", subject: a.subject, code: a.code }; cur.got += Number(gm[0]) || 0; cur.max += Number(gm[1]) || 0; atomAgg.set(atom, cur); } } const weak = [...atomAgg.entries()].filter(([, v]) => v.max > 0) .map(([id, v]) => ({ id, ...v, p: pct(v.got, v.max) })).sort((a, b) => a.p - b.p || b.max - a.max); const ws = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: ideas to work on` }), h("p", { class: "muted", text: "Each idea is scored across the questions that test it, using the latest attempt of each self-check. Lowest first." })); if (!weak.length) ws.append(h("p", { class: "muted", text: `No saved attempts for ${st.name} yet. Results appear here after the first self-check is saved.` })); for (const w of weak.slice(0, 25)) { ws.append(h("div", { class: "atom-row" }, h("div", { class: "stmt" }, h("div", { text: w.text || w.id }), h("div", { class: "id", text: `${w.subject || ""} · ${w.id}` })), h("div", { class: `bar ${band(w.p)}` }, h("span", { style: `width:${w.p}%` })), h("span", { class: `pill ${band(w.p)}`, text: `${w.p}%` }))); } main.append(ws); // tutor activity and idea levels (counts only; the parent area has the full chats) if (!S.activity && !S.loadingActivity) { S.loadingActivity = true; api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (S.view === "progress") render(); }); } const act = (S.activity && S.activity[sid]) || { sessions: [], ideas: {} }; const ts = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: tutor sessions` })); if (!S.activity) ts.append(h("p", { class: "muted", text: "Loading…" })); else if (!act.sessions.length) ts.append(h("p", { class: "muted", text: "No tutor sessions yet." })); else { const mins = act.sessions.reduce((a, x) => a + (x.minutes || 0), 0); const right = act.sessions.reduce((a, x) => a + x.correct, 0), tried = act.sessions.reduce((a, x) => a + x.attempts, 0); 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.` })); 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" })))); const tb2 = h("tbody"); for (const x of act.sessions.slice(0, 30)) tb2.append(h("tr", null, h("td", { class: "mono", text: fmtDate(x.updated) }), h("td", { text: `${x.subject} · ${x.chapter}${x.mode === "practice" ? " (practice)" : ""}` }), h("td", { class: "num", text: String(Math.max(0, x.messages)) }), h("td", { class: "num", text: `${x.correct}/${x.attempts}` }), h("td", { class: "num", text: `${x.minutes} min` }))); tt.append(tb2); ts.append(h("div", { class: "table-wrap" }, tt)); } main.append(ts); const ideaCh = Object.entries(act.ideas || {}); if (ideaCh.length) { const is = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: idea levels` }), h("p", { class: "muted", text: "From the tutor and quizzes together. Levels: not met, recall, apply, combine, exam-ready." }), 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])))); for (const [, ch] of ideaCh) { const total = ch.byLevel.reduce((a, b) => a + b, 0); is.append(h("div", { class: "idea-ch" }, h("h3", { text: `${ch.subject} · ${ch.chapter}` }), levelBar(ch.byLevel, total), h("div", { class: "idea-list" }, ...ch.atoms.slice().sort((a, b) => a.level - b.level).slice(0, 8).map((a) => h("div", { class: "idea" }, h("span", { class: `lv-dot lv${a.level}` }), h("span", { text: a.statement })))))); } main.append(is); } // attempt history const hist = attemptsFor(sid); const hs = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: attempts` })); if (!hist.length) hs.append(h("p", { class: "muted", text: "Nothing saved yet." })); else { const t2 = h("table"); t2.append(h("thead", null, h("tr", null, h("th", { text: "When" }), h("th", { text: "Self-check" }), h("th", { class: "num", text: "Score" }), h("th", { class: "num", text: "Time" })))); const b2 = h("tbody"); for (const a of hist.slice(0, 50)) { const p = pct(a.score, a.max); b2.append(h("tr", null, h("td", { class: "mono", text: fmtDate(a.submittedAt) }), h("td", { text: `${a.subject || ""} · ${a.chapter || a.setId}` }), h("td", { class: "num" }, h("span", { class: `pill ${band(p)}`, text: `${a.score}/${a.max}` })), h("td", { class: "num", text: `${Math.round((a.durationSec || 0) / 60)} min` }))); } t2.append(b2); hs.append(h("div", { class: "table-wrap" }, t2)); } main.append(hs); main.append(parentArea()); } // ---------- chrome ---------- $("tab-practise").addEventListener("click", () => goPlace("today")); $("tab-subjects").addEventListener("click", () => goPlace("subjects")); $("tab-chats").addEventListener("click", () => goPlace("chats")); $("tab-progress").addEventListener("click", () => goPlace("progress")); $("app-fb").addEventListener("click", () => { S.appFb = !S.appFb; S.appFbOpening = S.appFb; render(); window.scrollTo(0, 0); }); $("tab-bank").addEventListener("click", () => { S.view = "bank"; S.run = null; render(); }); $("tab-tutor").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "tutor"; S.run = null; T.mastery = null; render(); }); $("who").addEventListener("click", () => { if (S.view === "test") return toast("Submit or leave the self-check first"); if (S.me && S.me.role === "child") { S.view = "account"; return render(); } S.view = "practise"; S.picking = true; render(); }); function confirmLeave() { saveDraft(); toast("Your answers are kept on this device. Open the self-check again to carry on."); clearInterval(timerHandle); return true; } try { const ro = new ResizeObserver(() => { const hd = document.querySelector("header.top"), dk = $("dock"); document.documentElement.style.setProperty("--hdr-h", `${hd ? hd.getBoundingClientRect().height : 64}px`); document.documentElement.style.setProperty("--dock-h", `${dk && !dk.hidden ? dk.getBoundingClientRect().height : 0}px`); }); ro.observe(document.querySelector("header.top")); ro.observe($("dock")); } catch {} render(); connect().catch(() => { S.dbError = "unavailable"; S.ready = true; render(); }); })(); </script> </body> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex">
<title>StepWise Self-Checks</title>
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#2f5bd3">
<link rel="apple-touch-icon" href="icon-192.png">
<link rel="icon" type="image/png" href="icon-192.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:ital,wght@0,400;0,700;1,400&family=Familjen+Grotesk:wght@500;600;700&family=JetBrains+Mono:wght@400;600&display=swap">
<style>
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; }
[hidden] { display: none !important; }
/* Layout: a squared exercise-book page. One column of work, a header strip with the
student's name, results shown as marks in the margin. */
:root {
--paper: #f3f5f2;
--sheet: #ffffff;
--grid: #e3e8e2;
--ink: #1d2738;
--ink-soft: #5b6577;
--rule: #d5dbd3;
--accent: #2f5bd3;
--accent-ink: #ffffff;
--accent-wash: #e6ecfb;
--good: #1f7a4d;
--good-wash: #e2f3ea;
--warn: #9a6a00;
--warn-wash: #fbf1d6;
--bad: #b3332b;
--bad-wash: #fbe5e3;
--font-display: "Familjen Grotesk", "Segoe UI", system-ui, sans-serif;
--font-body: "Atkinson Hyperlegible", "Segoe UI", system-ui, sans-serif;
--font-data: "JetBrains Mono", ui-monospace, "Cascadia Mono", Consolas, monospace;
--radius: 10px;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5;
--rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44;
--good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f;
--bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark;
}
}
:root[data-theme="dark"] {
--paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5;
--rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44;
--good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f;
--bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark;
}
* { box-sizing: border-box; }
body {
background-color: var(--paper);
background-image:
linear-gradient(var(--grid) 1px, transparent 1px),
linear-gradient(90deg, var(--grid) 1px, transparent 1px);
background-size: 24px 24px;
color: var(--ink);
font-family: var(--font-body);
font-size: 16px;
line-height: 1.55;
padding-inline: 16px;
padding-block: 0 calc(var(--dock-h, 0px) + 32px);
}
.wrap { max-width: 1120px; margin: 0 auto; }
h1, h2, h3 { font-family: var(--font-display); text-wrap: balance; margin: 0; line-height: 1.2; }
h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.01em; }
h2 { font-size: 1.25rem; font-weight: 600; }
h3 { font-size: 1.05rem; font-weight: 600; }
p { margin: 0; }
.muted { color: var(--ink-soft); }
.mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; }
.label { font-family: var(--font-display); font-size: 0.75rem; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-soft); }
header.top {
position: sticky; top: env(safe-area-inset-top, 0px); z-index: 5;
background: color-mix(in srgb, var(--paper) 92%, transparent);
backdrop-filter: blur(6px);
border-bottom: 1px solid var(--rule);
margin-inline: -16px; padding: 12px 16px;
}
header.top .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; }
@media (max-width: 720px) { .brand .tag { display: none; } }
.brand { display: flex; align-items: baseline; gap: 10px; margin-right: auto; }
.brand .tag { font-family: var(--font-data); font-size: 0.75rem; color: var(--ink-soft); }
nav.tabs { display: flex; gap: 4px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 999px; padding: 3px; }
nav.tabs button { border: 0; background: transparent; color: var(--ink-soft); font: 600 0.9rem var(--font-display); padding: 6px 14px; border-radius: 999px; cursor: pointer; }
nav.tabs button[aria-pressed="true"] { background: var(--ink); color: var(--paper); }
nav.tabs button { display: inline-flex; align-items: center; gap: 6px; }
nav.tabs .ic { font-size: 1rem; line-height: 1; }
@media (max-width: 720px) {
header.top { backdrop-filter: none; background: var(--paper); } /* a blur would trap the fixed bar inside the header */
nav#places { position: fixed; left: 0; right: 0; bottom: 0; z-index: 7; border-radius: 0; border: 0; border-top: 1px solid var(--rule);
justify-content: space-around; padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--sheet); }