${esc(c.name)}
שיעורים: ${esc(c.lessons.map(id => names[id] || id).join(", "))}
+ מורה: ${esc(c.teacher_email || "עוד לא נבחר")}
+ ${c.students} תלמידים · AI: ${c.ai_enabled ? "פועל" : "כבוי"} · ${c.ai_daily_checks} בדיקות ביום
diff --git a/app/ai_usage.py b/app/ai_usage.py index 9615040648d3ac4616b7f8e00e24b8a8febfcba2..e7bd4aa15d9b9ff1b6a582a6d67a0dc6a4c160b7 100644 --- a/app/ai_usage.py +++ b/app/ai_usage.py @@ -17,7 +17,7 @@ from .auth import AuthUnavailable log = logging.getLogger("mathly.ai_usage") MIGRATION = "supabase/migrations/20261103220000_math_ai_usage.sql" TABLE = "/rest/v1/math_ai_usage" -FEATURES = ("photo", "grading") +FEATURES = ("photo", "grading", "prompter") # model prefix -> (input, output, cache read) in USD per million tokens. A cache write is 1.25 x input. PRICES = { diff --git a/app/prompter.py b/app/prompter.py index fe962492fdf12f75952695b67c4f53ec27b8888b..2050f502642a8c597fe2f51041717ed31abac75b 100644 --- a/app/prompter.py +++ b/app/prompter.py @@ -2,10 +2,17 @@ For developers only (the management.access permission, like the rest of ניהול). Each account sees only its own texts. They are kept in the Supabase table `math_prompter_texts`, read and written with the server's secret key. + +A text may also have an outline (ראשי פרקים): for a speaker who talks from reminders rather than reading aloud, +Claude rewrites the text as the same slides with two to four very short topic reminders each. It is written once, +on request, kept with the text, and can be edited like the text. Changing the text without sending an outline +drops the outline, so a stale one is never shown. """ from __future__ import annotations +import json import logging +import os import re import urllib.parse from datetime import datetime, timezone @@ -13,15 +20,39 @@ from datetime import datetime, timezone from fastapi import Body, Depends, HTTPException from fastapi.responses import JSONResponse +from . import ai_usage from .access import has_permission from .auth import AuthUnavailable log = logging.getLogger("mathly.prompter") MIGRATION = "supabase/migrations/20261106130000_math_prompter_texts.sql" +OUTLINE_MIGRATION = "supabase/migrations/20261107130000_math_prompter_outline.sql" TABLE = "/rest/v1/math_prompter_texts" -MAX_TITLE, MAX_BODY, MAX_TEXTS = 120, 100_000, 200 +MAX_TITLE, MAX_BODY, MAX_TEXTS, MAX_OUTLINE = 120, 100_000, 200, 20_000 UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") -FIELDS = "id,title,body,updated_at" +FIELDS = "id,title,body,outline,updated_at" +OUTLINE_MODEL = "claude-sonnet-5-5" +OUTLINE_SCHEMA = { + "type": "object", "additionalProperties": False, "required": ["sections"], + "properties": {"sections": {"type": "array", "items": { + "type": "object", "additionalProperties": False, "required": ["part", "heading", "time", "reminders"], + "properties": {"part": {"type": "string"}, "heading": {"type": "string"}, "time": {"type": "string"}, + "reminders": {"type": "array", "items": {"type": "string"}}}}}}, +} +OUTLINE_SYSTEM = """You turn a talk's full script into speaker reminders for a teleprompter. The speaker does not read +the script aloud; they glance at a few words per slide to remember what to talk about, and speak freely. + +The script is in "}]) + except anthropic.APIError as exc: + reason, detail = failure_reason(exc) + log.warning("prompter outline failed: %s (%s)", reason, detail) + raise HTTPException(503, "outline_unavailable") from exc + try: + if response.stop_reason != "end_turn": + raise ValueError(response.stop_reason) + sections = json.loads(next(b.text for b in response.content if b.type == "text"))["sections"] + outline = outline_text(sections) + if not outline: + raise ValueError("empty") + except (ValueError, KeyError, TypeError, StopIteration) as exc: + log.warning("prompter outline was not usable: %s", exc) + raise HTTPException(503, "outline_unavailable") from exc + return outline, ai_usage.usage_of(response) + + def install_prompter_routes(app, signed_in): - """GET/POST /api/prompter/texts and PUT/DELETE /api/prompter/texts/{id}: the developer's own saved texts.""" + """GET/POST /api/prompter/texts, PUT/DELETE /api/prompter/texts/{id}: the developer's own saved texts, and + POST /api/prompter/texts/{id}/outline: Claude writes (or rewrites) the text's outline and it is saved with it.""" def developer(user=Depends(signed_in)) -> str: if not user or not user.get("id"): raise HTTPException(401, "sign_in_required") @@ -52,6 +139,14 @@ def install_prompter_routes(app, signed_in): try: return app.state.auth._admin(path, method, body, prefer=prefer) except AuthUnavailable as exc: + if "outline" in str(exc) and "answered 404" not in str(exc): + # before the outline migration: texts work as before, only outlines are unavailable + log.warning("the math_prompter_texts.outline column is missing; apply %s", OUTLINE_MIGRATION) + if isinstance(body, dict) and body.get("outline"): + raise HTTPException(503, "outline_unavailable") from exc + if isinstance(body, dict): + body = {k: v for k, v in body.items() if k != "outline"} + return admin(path.replace(FIELDS, FIELDS.replace(",outline", "")), method, body, prefer) if "answered 404" in str(exc): log.warning("the math_prompter_texts table is missing; apply %s", MIGRATION) else: @@ -84,11 +179,38 @@ def install_prompter_routes(app, signed_in): @app.put("/api/prompter/texts/{text_id}") def save_text(text_id: str, body: dict = Body(...), user: str = Depends(developer)): row = clean(body) + if "outline" in body: + row["outline"] = clean_outline(body["outline"]) + else: # the outline was written from the old text: it goes when the text changes + old = admin(f"{TABLE}?select=body&" + one(text_id, user)) or [] + if not old: + raise HTTPException(404, "not_found") + if old[0]["body"] != row["body"]: + row["outline"] = None rows = admin(f"{TABLE}?select={FIELDS}&" + one(text_id, user), "PATCH", {**row, "updated_at": now()}) or [] if not rows: raise HTTPException(404, "not_found") return {"text": rows[0]} + @app.post("/api/prompter/texts/{text_id}/outline") + def make_outline(text_id: str, user: str = Depends(developer)): + rows = admin(f"{TABLE}?select=body&" + one(text_id, user)) or [] + if not rows: + raise HTTPException(404, "not_found") + outliner = getattr(app.state, "prompter_outliner", None) + if outliner is None: + key = os.environ.get("ANTHROPIC_API_KEY", "").strip() or os.environ.get("CLAUDE_API_KEY", "").strip() + if not key: + raise HTTPException(503, "outline_unavailable") + outliner = Outliner(key, os.environ.get("PROMPTER_MODEL", "").strip() or OUTLINE_MODEL) + outline, usage = outliner(rows[0]["body"]) + ai_usage.record(app.state.auth, user, "prompter", usage) + # updated_at is left alone: the text itself did not change + saved = admin(f"{TABLE}?select={FIELDS}&" + one(text_id, user), "PATCH", {"outline": outline}) or [] + if not saved: + raise HTTPException(404, "not_found") + return {"text": saved[0]} + @app.delete("/api/prompter/texts/{text_id}") def delete_text(text_id: str, user: str = Depends(developer)): admin(f"{TABLE}?" + one(text_id, user), "DELETE", prefer="return=minimal") diff --git a/docs/mockups/mathly2-screens.html b/docs/mockups/mathly2-screens.html new file mode 100644 index 0000000000000000000000000000000000000000..f8eda70865d8587492feacc2190e75b3487b74a1 --- /dev/null +++ b/docs/mockups/mathly2-screens.html @@ -0,0 +1,362 @@ + + +
+ + +ACC-1 · דף הכניסה בסגנון mathly1
+יש להיכנס כדי לפתוח את מסלול המתמטיקה.
+ +המשימה של היום
+ +המורה רואה את התמונה קודם, ואז מגיעים רמזים אחד־אחד.
+כל איבר בסוגריים הראשונים כופל כל איבר בסוגריים השניים.
+כל איבר בסוגריים הראשונים כופל כל איבר בשניים.
פתחתם עזרה: התשובה לשאלה הזו לא תיספר לשליטה.
נכונות ברצף: 2 מתוך 3 · נדרשים שני ימים שונים
+דורשת: כפל איברים פותחת: פירוק טרינום
+| מה | ציון |
|---|---|
| בוחן · טכניקה אלגברית 1 (הטוב מבין 2) | 85 |
| בוחן · משוואות | 70 |
| מבחן תרגול 1 · מבחן 16.11 | 54 |
| משימה · בוחן כתוב | 85 |
כל מיומנות שנשלטה היא כוכב; שיעור שהושלם מצייר קבוצת כוכבים. שביט שלא נתפס מוצג כ־?.
+TCH-1, TCH-9 · המורה מוסיפה ומסירה תלמידים בכיתה שלה בלבד
+שיעורים: טכניקה אלגברית 1, משוואות, פירוק לגורמים · AI: פועל
+ + +| תלמיד | |
|---|---|
| noa@school.org | |
| yoav@school.org |
AI: כבוי (מנהל הכיתות מפעיל)
TCH-4, AI-4, AI-5 · הישן ראשון; הציון של המורה גובר על הצעת ה־AI
+| מה | תלמיד | הוגש | הצעת AI | |
|---|---|---|---|---|
| דף עבודה: פירוק טרינום | noa@ | ב׳ 08:10 | 70 · "חסר נימוק בסעיף 2" | |
| בקשה לבדוק שוב | yoav@ | ב׳ 12:40 | 60 | |
| בוחן כתוב: טכניקה 1 | dana@ | ג׳ 09:05 | — |
AI-1, AI-6, AI-7 · תלמידים לא פונים ל־AI בעצמם · תקציב יומי לכיתה
+TST-1, TCH-6, RDY-1
+שיעורים: טכניקה אלגברית 1, משוואות · 12 שאלות · 45 דק׳ · מחשבון מותר
+סימולציה: 22 מתוך 25 עשו · חסרים: יואב, עמית, ליה
+| תלמיד | מוכנות | שליטה | תרגול | סימולציה |
|---|---|---|---|---|
| נועה | 81 · כמעט שם | 80% | 70 | 90 |
| יואב | 62 · בדרך | 70% | 54 | — |
TCH-7 · צבע וגם סימן בכל תא
+ +| תלמיד | טכניקה אלגברית 1 | משוואות | |||
|---|---|---|---|---|---|
| 1 | 2 | 3 | 1 | 2 | |
| נועה | ✓ | ✓ | ◐ | ✓ | ○ |
| יואב | ◐ | ○ | ○ | ◐ | ○ |
| דנה | ✓ | ◐ | ◐ | ✓ | ✓ |
✓ נשלטה · ◐ בלמידה · ○ לא התחילו
+CLS-7, MGR-1 · אין למנהל הכיתות גישה לנתוני למידה
+שיעורים: טכניקה אלגברית 1, משוואות, פירוק לגורמים
מורה: rina@school.org
25 תלמידים · AI: פועל · 150 בדיקות ביום
שיעורים: כל 24 השיעורים
מורה: avi@school.org
22 תלמידים · AI: כבוי
CLS-2 – CLS-6 · ה־AI כבוי עד שבית הספר מאשר הסכמת הורים (AI-10)
+MGR-2
+| תלמיד | כיתות |
|---|---|
| noa@school.org | ט׳3 |
| yoav@school.org | ט׳3 · ט׳4 |
| dana@school.org | ט׳3 |
${esc(me.email)}
+תפקיד חדש נותן מנהל ההרשאות.
`}אפשר להקליד גם כתובת שעוד לא נכנסה לאפליקציה: התפקיד יחול מהכניסה הראשונה שלה. שינוי תפקיד נקלט תוך כחצי דקה.
+| חשבון | תפקידים שניתנו | מההגדרות |
|---|---|---|
| ${esc(a.email)} | +${a.roles.map(r => `${ROLE_NAMES[r]} `).join(" ") || '—'} | +${a.from_settings.map(r => `${ROLE_NAMES[r]}`).join(" ") || '—'} |
${esc(message)}
` : ""} + view(`כניסת פיתוח (dev only): ללא Supabase, כל כתובת מייל מתקבלת.
+ ? `כניסת פיתוח (dev only): ללא Supabase, כל כתובת מייל מתקבלת.
` - : ``}טוען…
${esc(error.message || "משהו השתבש")}
${esc(error.message || "משהו השתבש")}
עוד אין. קבוצת כוכבים מופיעה כשכל המיומנויות של שיעור נשלטות.
`} +עוד אין. מיומנות נשלטת אחרי 3 תשובות נכונות ברצף, בלי עזרה, בשני ימים שונים.
`} +שביטים חולפים לפעמים על המסך בזמן תרגול. מי שלוחץ עליהם בזמן תופס אותם.
` + : `${cometCard(comet)}${esc(comet.fact)}
`} +יש לך את כל ההרשאות: אפשר לפתוח את המסכים של כל התפקידים מהכפתורים למעלה.
+כלי המפתח (פרומפטר, מעבדה, עלות ה־AI) יתווספו בשלבים הבאים.
+${esc(me.email)}
${result.right} מתוך ${result.total}
+ ${skill.state === "mastered" ? `🎉 המיומנות נשלטה!
` : ""} + ${result.missed.length ? `${fmt(m.question)}
+ ${m.mistake ? `${esc(m.mistake.name)}${m.mistake.tip ? `
${fmt(m.mistake.tip)}` : ""}
כל התשובות נכונות. כל הכבוד!
`} +
${fmt(skill.help.explanation)}
+ ${ex ? `${fmt(ex.question)}
תשובה: ${fmt(ex.answer)}
` : ""} + ${skill.question ? `פתחתם עזרה: התשובה לשאלה הזו לא תיספר לשליטה.
` : ""}אין עדיין שאלות תרגול למיומנות הזו.
`; + return `${fmt(question.question)}
${figures(question)} +${fmt(skill.description)}
${notice ? `${esc(notice)}
` : ""} + ${helpBox()}${progress()}${questionHtml()}${related()}`; + helped = false; + mountBoard(); +} + +function showNextQuestion(question) { + stop(); + skill.question = question; + q("#ex-q")?.remove(); + q("#no-practice")?.remove(); + const holder = document.createElement("div"); + holder.innerHTML = questionHtml(); + (q("#ex-dots")?.parentElement || q(".ex-explain")).after(holder.firstElementChild); + q("#ex-helpbox").hidden = true; + q("[data-help]")?.setAttribute("aria-expanded", "false"); + helped = false; + mountBoard(); +} + +function updateProgress() { + const round = skill.round; + q("#ex-count").textContent = countText(round); + const row = q("#ex-dots"); + row.setAttribute("aria-label", dotsLabel(round)); + row.innerHTML = dots(round); + if (skill.state === "mastered" && !q(".ex-done")) q("#ex-title").insertAdjacentHTML("beforeend", ' ✓ נשלטה'); +} + +/** The round is over: show its result in place of the question. */ +function showResult() { + stop(); + skill.question = null; + render(); +} + +async function newRound() { + const button = q("#ex-newround"); + button.disabled = true; + try { + await api(`/api/skills/${encodeURIComponent(skill.id)}/round`, { method: "POST" }); + skill = await api(`/api/skills/${encodeURIComponent(skill.id)}`); + render(); + } catch (error) { + button.disabled = false; + button.insertAdjacentHTML("afterend", `${esc(error.message || "משהו השתבש")}
`); + } +} + +async function reloadCurrent() { + skill = await api(`/api/skills/${encodeURIComponent(skill.id)}`); + stop(); + render("השאלה התחלפה בחלון אחר. זו השאלה שעל המסך עכשיו."); +} + +function countdown(next) { + let left = COUNTDOWN; + const label = q("#ex-countdown"); + const tick = () => { + if (!layer || !label?.isConnected) return; + if (left === 0) return next(); + label.textContent = `השאלה הבאה בעוד ${left}…`; + left -= 1; + timer = setTimeout(tick, 1000); + }; + tick(); +} + +async function answer(button) { + const question = skill.question; + const buttons = [...layer.querySelectorAll(".ex-choice")]; + buttons.forEach(b => { b.disabled = true; b.classList.toggle("dim", b !== button); }); + button.classList.add("pending"); // the thinking indicator: the server is checking + button.setAttribute("aria-busy", "true"); + q("#ex-fb").innerHTML = `בודקים…
`; // a live region: a screen reader hears it too + let result; + try { + result = await api(`/api/skills/${encodeURIComponent(skill.id)}/answer`, { method: "POST", body: { question_key: question.key, choice: Number(button.dataset.i) } }); + } catch (error) { + buttons.forEach(b => b.classList.remove("pending", "dim")); + button.removeAttribute("aria-busy"); + if (error instanceof ApiError && error.status === 409) return reloadCurrent(); + buttons.forEach(b => { b.disabled = false; }); + q("#ex-fb").innerHTML = `${esc(error.message || "משהו השתבש")}
`; + return; + } + buttons.forEach(b => b.classList.remove("pending", "dim")); + button.removeAttribute("aria-busy"); + Object.assign(skill, { round: result.round, state: result.state, correct_in_row: result.correct_in_row, today: result.today }); + updateProgress(); + const feedback = q("#ex-fb"); + const next = () => (result.next_question ? showNextQuestion(result.next_question) : showResult()); + if (result.correct) { + button.classList.add("right"); + button.insertAdjacentHTML("beforeend", ''); + navigator.vibrate?.(25); + feedback.innerHTML = `🎉 המיומנות נשלטה!
` : ""} + ${result.next_question ? `סיימתם את הסבב.
`}${fmt(m.tip)}
` : ""} + ${m?.back && m.back_name ? `` : ""} +${esc(a.join(" "))}
`).join(""); + const notes=ops.filter(([op])=>op==="text").map(([,a])=>{const [x,y]=a[0].split(",").map(Number);return {x,y,words:a.slice(1).join(" ")}}); + const all=[...Object.values(P),...notes], xs=all.map(p=>p.x), ys=all.map(p=>p.y); + let x0=Math.min(...xs), x1=Math.max(...xs), y0=Math.min(...ys), y1=Math.max(...ys); + if(grid){ x0=Math.floor(Math.min(x0,0))-1; x1=Math.ceil(Math.max(x1,0))+1; y0=Math.floor(Math.min(y0,0))-1; y1=Math.ceil(Math.max(y1,0))+1; } + const W=320, PAD=grid?14:30, dx=Math.max(x1-x0,1e-6), dy=Math.max(y1-y0,1e-6), s=Math.min((W-2*PAD)/dx,(250-2*PAD)/dy); + const H=Math.round(dy*s+2*PAD), ox=(W-dx*s)/2; + const X=x=>ox+(x-x0)*s, Y=y=>H-PAD-(y-y0)*s, at=n=>[X(P[n].x),Y(P[n].y)]; + const f=v=>v.toFixed(1), unit=([x,y])=>{const l=Math.hypot(x,y)||1;return [x/l,y/l]}; + const named=Object.keys(P).filter(n=>!n.startsWith("_")); + const pts=Object.keys(P), cx=pts.reduce((t,n)=>t+at(n)[0],0)/pts.length, cy=pts.reduce((t,n)=>t+at(n)[1],0)/pts.length; + const txt=(x,y,words,cls="",anchor="")=>`עוד אין ציונים. הבוחן של כל שיעור מחכה בסוף השיעור במסלול.
` : ""} + ${quizzes.length ? `${r.number}${esc(r.label)}
+ +${part("M", "שליטה", r.parts.M)} ${part("E", "מבחני תרגול", r.parts.E)} ${part("S", "סימולציה", r.parts.S)}
+ ${r.waiting_for_simulation ? `עוד לא עשיתם מבחן סימולציה, ולכן המדד לא עובר את ${80}.
` : ""}${lessonsOf(test)}${test.note ? ` · ${esc(test.note)}` : ""}
+ ${readinessBar(test.readiness)} +המשימה להיום${esc(t.label)}
+המורה עוד לא קבע מבחן. בינתיים אפשר להמשיך במסלול.
${data.next_skill ? `להמשיך במסלול: ${fmt(data.next_skill.name)} ` + : `למסלול: כל הכוכבים פתוחים לתרגול `}
+ ${others.length ? `${esc(flash.error)}
` : ""}${flash.message ? `${esc(flash.message)}
` : ""}`; +const tabs = () => `שיעורים: ${esc(c.lessons.map(id => names[id] || id).join(", "))}
+ מורה: ${esc(c.teacher_email || "עוד לא נבחר")}
+ ${c.students} תלמידים · AI: ${c.ai_enabled ? "פועל" : "כבוי"} · ${c.ai_daily_checks} בדיקות ביום
עוד אין כיתות. פתחו כיתה ראשונה, בחרו את השיעורים והוסיפו את התלמידים.
| תלמיד | כיתות |
|---|---|
| ${esc(s.email)} | ${s.classes.map(esc).join(" · ")} |
| עדיין לא נוספו תלמידים לכיתות. | |
כל השיעורים פתוחים, בכל סדר. הינשוף מציע איפה להמשיך, אבל אפשר ללחוץ על כל כוכב.
${goalBar(path.today, path.streak)}${esc(error.message || "משהו השתבש")}
`; + } +} + +const heading = (title) => `${fmt(question.question)}
${figures(question)} +${esc(error.message || "התשובה לא נשמרה, נסו שוב")}
`; + } +} + +function submit() { + const missing = attempt.questions.filter(x => attempt.answers[x.key] === undefined).length; + if (missing && !warned) { + warned = true; + q("#qz-warn").innerHTML = `יש ${missing} ${missing === 1 ? "שאלה" : "שאלות"} בלי תשובה. הן ייחשבו שגויות.
+
${r.grade}מתוך 100
+${r.right === 1 ? "תשובה נכונה אחת" : `${r.right} תשובות נכונות`} מתוך ${r.total}${r.timed_out ? ". הזמן נגמר והבוחן הוגש כמו שהוא." : ""}
+ ${r.kind === "simulation" ? `מבחן סימולציה אפשר לעשות פעם אחת.
` : ""}אפשר לתרגל את המיומנות ואז לנסות שוב.
` : `כל התשובות נכונות. כל הכבוד!
`} + ${r.missed.length ? `${fmt(m.question)}
+ ${m.picked ? `בחרתם: ${fmt(m.picked)}
` : `לא ענו על השאלה.
`} + ${m.mistake ? `${esc(m.mistake.name)}${m.mistake.tip ? `
${fmt(m.mistake.tip)}` : ""}
${names(r).again ? ` ` : ""}
`; + const best = r.kind === "quiz" ? api(`/api/lessons/${encodeURIComponent(r.lesson.id)}/quiz`).then(f => f.best === null ? "" : `הציון של השיעור: ${f.best}`) + : r.kind === "exercise_test" ? api(`/api/tests/${encodeURIComponent(r.test.id)}`).then(t => `הציון הטוב במבחן התרגול: ${t.exercise_tests[r.test.number - 1].best ?? ""}`) : Promise.resolve(""); + best.then(text => { if (text && q("#qz-best")) q("#qz-best").textContent = text; }).catch(() => {}); +} + +function onClick(event) { + const target = event.target; + if (target.closest("[data-close]")) { location.hash = leaveTo(); return; } + if (target.closest("[data-board-toggle]")) { window.MathlyBoard?.toggle(); return; } + if (attempt?.state === "open") { + const go = target.closest("[data-go]"); + if (go && !go.disabled) { at = Number(go.dataset.go); warned = false; renderQuestion(); return; } + const choice = target.closest(".qz-choice"); + if (choice) { choose(choice); return; } + if (target.closest("#qz-submit")) { submit(); return; } + if (target.closest("#qz-yes")) { finish(true); return; } + if (target.closest("#qz-back")) { q("#qz-warn").innerHTML = ""; warned = false; return; } + } else if (target.closest("#qz-retake")) { + at = 0; + const again = attempt.kind === "quiz" ? start(attempt.lesson.id) : startExam(attempt.test.id, attempt.test.number); + again.catch(error => { q(".qz-actions").insertAdjacentHTML("afterend", `${esc(error.message)}
`); }); + } +} + +window.addEventListener("mathly:leave", close); + +document.addEventListener("keydown", event => { + if (event.key === "Escape" && layer && !document.querySelector(".mx-board.full")) location.hash = leaveTo(); +}); diff --git a/mathly2/static/roles.js b/mathly2/static/roles.js new file mode 100644 index 0000000000000000000000000000000000000000..b442504038561f6d353f78144222efd1a1f6a76f --- /dev/null +++ b/mathly2/static/roles.js @@ -0,0 +1,12 @@ +// The five roles: their Hebrew names and what each allows (shown on the "my access" page). +export const ROLE_ORDER = ["student", "teacher", "manager", "admin", "developer"]; +export const ROLE_NAMES = { student: "תלמיד", teacher: "מורה", manager: "מנהל כיתות", admin: "מנהל הרשאות", developer: "מפתח" }; +export const ROLE_ALLOWS = { + student: "לתרגל במסלול, ולראות את ההתקדמות, הציונים והמשימות שלי.", + teacher: "לראות את הכיתות שאני מלמד/ת ואת התלמידים בהן, ולהוסיף ולהסיר תלמידים בכיתות שלי.", + manager: "ליצור, לערוך ולמחוק כיתות (שיעורים, מורה ותלמידים), ולראות את כל התלמידים. בלי גישה לנתוני למידה.", + admin: "לתת תפקידים לחשבונות ולהסיר אותם. בלי גישה לנתוני למידה.", + developer: "כל ההרשאות, לכל הכיתות והחשבונות, וכלי המפתח.", +}; +/** The roles whose screens a person can open: their own, and for a developer all of them. */ +export const visibleRoles = roles => roles.includes("developer") ? ROLE_ORDER : ROLE_ORDER.filter(role => roles.includes(role)); diff --git a/mathly2/static/router.js b/mathly2/static/router.js new file mode 100644 index 0000000000000000000000000000000000000000..85222c7d100e71a15a28055af9d9b9ada1cdc5a2 --- /dev/null +++ b/mathly2/static/router.js @@ -0,0 +1,14 @@ +// One address-bar router for the active screen: whichever role screen is open sets its handler, so screens never stack listeners. +let handler = null; +window.addEventListener("hashchange", () => { if (handler) handler(); }); +/** Make `fn` the screen that reacts to the address after "#". */ +export const route = fn => { handler = fn; }; +/** Tell whatever is open over the screens (a sheet) that the person is leaving. */ +export const leaveScreen = () => window.dispatchEvent(new Event("mathly:leave")); + +/** Forget the open screen. The address after "#" is cleared too, unless `keepAddress`: a link or a reload must land where it points. */ +export const clearRoute = ({ keepAddress = false } = {}) => { + leaveScreen(); + handler = null; + if (!keepAddress) history.replaceState(null, "", location.pathname + location.search); +}; diff --git a/mathly2/static/sky.js b/mathly2/static/sky.js new file mode 100644 index 0000000000000000000000000000000000000000..fc260546a381186b3dd51c6158220171ef4b9612 --- /dev/null +++ b/mathly2/static/sky.js @@ -0,0 +1,114 @@ +import { esc } from "./math.js"; +// The sky look's pictures. The owl is mathly1's (static/math-sky.js), coloured by the --sky-owl* tokens in app.css. +export const owl = (width = 80, cls = "") => ``; + +/** The four-pointed star every skill is (mathly1's spark). Its colour and fill come from CSS (state classes). */ +export const spark = (cls = "") => ``; + +/** The arcs that join a lesson's stars in a ring (from mathly1's orbitRing). One path per neighbouring pair, clockwise from the top; + * an arc is "on" once the star it leaves has been started. The closing arc from the last star back to the first stays faint: + * the ring has a start and an end. Drawn in a 100x100 box that is stretched to the ring's size, so strokes do not scale. */ +export function ringSvg(states) { + const n = states.length; + if (n < 2) return ""; + const angle = i => (-90 + 360 * i / n) * Math.PI / 180; + const gap = Math.min(0.32, Math.PI / n * 0.55); // room left around each star (radians) + const point = t => [50 + 50 * Math.cos(t), 50 + 50 * Math.sin(t)]; + const f = v => v.toFixed(2); + const arc = (from, to, cls) => { + const [x0, y0] = point(from), [x1, y1] = point(to); + return `המורה עוד לא הוסיפה אותך לכיתה. בקשו מהמורה להוסיף את כתובת המייל שבה נכנסתם:
+עוד לא הוסיפו אותך לכיתה. בקשו מהמורה או ממנהל הכיתות להוסיף את כתובת המייל שבה נכנסתם:
${esc(me.email)}
הכיתה: ${esc(me.class.name)}. השיעורים (${lessons.length}) יפתחו כאן בהמשך.
-${esc(error.message || "משהו השתבש")}
${text}
` : ""; +const tabs = active => `עוד אין כיתות. אפשר ליצור את הראשונה כאן.
`}עוד אין תלמידים בכיתה.
`}${l}
`).join("")}${c.ai_enabled ? "AI פועל" : "AI כבוי: מנהל הכיתות מפעיל"}
+ ${c.students.length ? `עוד אין תלמידים בכיתה.
`} +עוד לא שייכו אותך ככיתה. מנהל הכיתות קובע מי מלמד/ת כל כיתה.
${t.lessons.map(l => fmt(l.name)).join(", ")}${t.note ? ` · ${esc(t.note)}` : ""} · ${t.questions} שאלות · ${t.minutes} דקות
+ ${t.simulation.missing.length ? `עוד לא עשו סימולציה: ${t.simulation.missing.map(e => `${esc(e)}`).join(", ")}
` + : t.simulation.total ? `כולם עשו את מבחן הסימולציה.
` : ""} + ${t.students.length ? `| תלמיד | מוכנות | שליטה | תרגול | סימולציה |
|---|---|---|---|---|
| ${esc(s.email)} | ${s.readiness.number} · ${esc(s.readiness.label)} | +${s.readiness.parts.M === null ? "—" : s.readiness.parts.M + "%"} | ${s.readiness.parts.E ?? "—"} | ${s.readiness.parts.S ?? "—"} |
${open ? ` ` : ""}
+עוד לא נקבע מבחן לכיתה.
`} +עוד לא שייכו אותך ככיתה. מנהל הכיתות קובע מי מלמד/ת כל כיתה.
${esc(e.message)}
הימים הם המלצה: אפשר להתחיל כל שלב קודם או אחר כך.
`; +} + +function exercises(test) { + return `הציון: ${s.grade}
${s.review.length ? `מיומנויות לחזרה:
אין מיומנויות לחזרה. כל הכבוד!
`} + ` + : s.open_now ? `חובה המבחן פתוח עד יום המבחן. אפשר לעשות אותו פעם אחת.
+${s.in_progress ? "להמשיך" : "התחלה"}
` + : `מבחן הסימולציה ייפתח ב־${shortDate(s.opens_on)} (בעוד ${s.opens_in_days} ימים). אפשר לעשות אותו פעם אחת.
`; + return `${test.lessons.map(l => fmt(l.name)).join(", ")}${test.note ? ` · ${esc(test.note)}` : ""}
${test.questions} שאלות · ${test.minutes} דקות
כדאי לתרגל קודם: ${test.practice_first.map(s => `${fmt(s.name)}`).join(" ")}
+אלה מיומנויות שעוד לא התחלתם, ולכן אין להן שאלות במבחני התרגול.
` : ""}"+r+"
(x + 3)(x − 5) = ?
x² − 9 = ?
Illustrates the draft specs in openspec/changes/build-skill-learning. Not the real app: fixed sample data, no server.
-כל השיעורים פתוחים, בכל סדר
-Every skill shows state as text + symbol, not colour alone.
-למה עושים את השלב הזה?
- - - - -The next step appears only after "why this step?" is answered.
-דוגמה 2 מתוך 3 - חסרים 2 שלבים
-Help fades: example 1 = 1 gap, example 2 = 2 gaps, ...
-Wrong answers name the mistake (from the bank) and never reveal the correct one.
-מה השגתי
-תזכורות קצרות לכל שקף, במקום לקרוא את הטקסט. לחצו „ראשי פרקים” ליד טקסט שמור ו־Claude יכין אותן; אפשר לערוך כאן ולשמור. כותרת שקף בשורה משלה, ואחריה שורות שמתחילות ב־•
+ +טוענים…
עדיין אין טקסטים שמורים. כתבו טקסט ולחצו „שמירה”.
'; } async function prLoad(){ @@ -1960,26 +1974,44 @@ async function prSave(asNew){ const title=sheet.querySelector("#mxPrompterTitle").value, body=sheet.querySelector("#mxPrompterText").value; if(!body.trim()) return prSay("אין טקסט לשמור."); const id=asNew?null:PR.id; + // the outline goes along only when it was edited here; otherwise the server keeps it, or drops it if the text changed + const send={title,body}; if(id&&PR.outlineEdited) send.outline=sheet.querySelector("#mxPrompterOutline").value; prSay("שומרים…"); try{ - const r=await api(id?`/api/prompter/texts/${id}`:"/api/prompter/texts",{method:id?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title,body})}); + const r=await api(id?`/api/prompter/texts/${id}`:"/api/prompter/texts",{method:id?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(send)}); if(r.status===409) return prSay("יש כבר 200 טקסטים שמורים. מחקו אחד כדי לשמור עוד."); if(r.status===404&&id){ PR.id=null; return prSave(true); } // deleted on another device: keep it as a new one if(!r.ok) throw new Error(); const {text}=await r.json(); PR.texts=[text,...PR.texts.filter(t=>t.id!==text.id)]; PR.id=text.id; - sheet.querySelector("#mxPrompterTitle").value=text.title; prKeep(); prList(); + sheet.querySelector("#mxPrompterTitle").value=text.title; prShowOutline(text.outline); prKeep(); prList(); prSay(`נשמר: „${text.title}”.`); }catch{ prSay("השמירה נכשלה. הטקסט עדיין כאן ובדפדפן הזה; נסו שוב."); } } function prEdit(id){ const t=PR.texts.find(x=>x.id===id); if(!t) return; PR.id=id; sheet.querySelector("#mxPrompterTitle").value=t.title; sheet.querySelector("#mxPrompterText").value=t.body; - prKeep(); prList(); prMark(); sheet.querySelector("#mxPrompterText").focus(); + prShowOutline(t.outline); prKeep(); prList(); prMark(); sheet.querySelector("#mxPrompterText").focus(); } function prNew(){ PR.id=null; sheet.querySelector("#mxPrompterTitle").value=""; sheet.querySelector("#mxPrompterText").value=""; - prKeep(); prList(); prSay(""); sheet.querySelector("#mxPrompterTitle").focus(); + prShowOutline(""); prKeep(); prList(); prSay(""); sheet.querySelector("#mxPrompterTitle").focus(); +} +// ראשי פרקים of a saved text: shown at once if it has them, otherwise Claude writes them first (about half a minute) +async function prOutline(id,btn){ + const t=PR.texts.find(x=>x.id===id); if(!t) return; + if(t.outline) return window.MathlyPrompter?.open(t.outline); + btn.disabled=true; btn.textContent="מכינים…"; + prSay(`Claude מכין ראשי פרקים ל„${t.title}”. זה לוקח כחצי דקה.`); + try{ + const r=await api(`/api/prompter/texts/${id}/outline`,{method:"POST"}); + if(!r.ok) throw new Error(String(r.status)); + const {text}=await r.json(); + PR.texts=PR.texts.map(x=>x.id===text.id?text:x); + if(PR.id===text.id){ prShowOutline(text.outline); prKeep(); } + prList(); prSay(`ראשי הפרקים של „${text.title}” מוכנים ונשמרו. אפשר לערוך אותם ב„עריכה”.`); + window.MathlyPrompter?.open(text.outline); + }catch{ prList(); prSay("לא הצלחנו להכין ראשי פרקים כרגע. נסו שוב בעוד דקה."); } } async function prDelete(id){ const t=PR.texts.find(x=>x.id===id); if(!t||!confirm(`למחוק את „${t.title}”?`)) return; @@ -2051,7 +2083,7 @@ function drawMonSummary(){ tiles.push(tile(!ai?"…":t?usd(t.cost_usd):"–",`עלות Claude ב־${ai?.days||30} יום (הערכה)`, !ai?"טוען…":ai.error?esc(ai.error):ai.unavailable?esc(ai.unavailable): `${t.calls} קריאות · ${tok(t.input_tokens)} אסימוני קלט · ${tok(t.output_tokens)} פלט · היום ${usd(ai.today.cost_usd)}`+ - ` · צילום ${usd(f.photo?.cost_usd)} · בדיקה ${usd(f.grading?.cost_usd)}`)); } + ` · צילום ${usd(f.photo?.cost_usd)} · בדיקה ${usd(f.grading?.cost_usd)}`+(f.prompter?` · פרומפטר ${usd(f.prompter.cost_usd)}`:""))); } // open answers: what is switched on, and how this period's photo checks came out const ans=sum?.answers, act=MON.activity, verdicts=act?.summary?.verdicts||{}; diff --git a/static/prompter.js b/static/prompter.js index a172947cb5efd07bb69db8dab3e1954fa0382912..22dddb61c4bacbcc99457d7aa85d234d4e52fa21 100644 --- a/static/prompter.js +++ b/static/prompter.js @@ -1,66 +1,212 @@ /* Prompter (פרומפטר): a full-screen teleprompter for developers, opened from ניהול. It stands alone, with its own styles. window.MathlyPrompter.open(text) shows it. - Keys: Space play/pause · ↑/↓ speed · +/- text size · M mirror · Home back to start · Esc close. - A presentation clicker: Page Down / → play/pause, Page Up / ← back a few lines. - A mouse: click play/pause · wheel changes the speed while playing (scrolls the text while paused) · - right-click back a few lines · middle-click or the mouse's back button to the start · forward button play/pause. */ + + Two ways to show a text: + · Scrolling (any text): the text rolls up at a set speed. + Keys: Space play/pause · ↑/↓ speed · +/- text size · M mirror · Home back to start · Esc close. + A presentation clicker: Page Down / → play/pause, Page Up / ← back a few lines. + A mouse: click play/pause · wheel changes the speed while playing (scrolls the text while paused) · + right-click back a few lines · middle-click or the mouse's back button to the start · forward button play/pause. + · Slides (a text with "Slide 3 — Title" lines, the speaker notes of a slide presentation): one slide's notes at a + time, which waits for the speaker. A "40 seconds" / "Opening · 35 seconds" line right under a slide heading is + its time budget; "Part 1 — …" lines name the part. The top strip shows the slide, its title and a clock against + the budget (amber near the end, red over) and how far ahead or behind the whole talk is; the bottom shows the + next slide's title. The first tap starts the clock; then a tap or a swipe to the left is the next slide, a swipe + to the right the one before. Keys and clickers: Space / Page Down / → / ↓ next · Page Up / ← / ↑ back · + Home first slide (and resets the clock) · S switches between slides and scrolling. + In the notes, [CLICK] marks a slide click, [PAUSE] or // a pause, and *word* a stressed word; "• " lines are + reminders (an outline, ראשי פרקים, app/prompter.py) and are shown as a large list. + The screen is kept awake while the prompter is open (where the browser allows it), and the text size is kept + separately for scrolling and for slides in portrait and in landscape (a mini iPad turned either way). */ (()=>{ const CSS=` -.mxp{position:fixed;inset:0;z-index:2147483000;background:#000;color:#fff;display:flex;flex-direction:column;font-family:"Rubik","Assistant",system-ui,sans-serif} +.mxp{position:fixed;inset:0;z-index:2147483000;background:#000;color:#fff;display:flex;flex-direction:column;font-family:"Rubik","Assistant",system-ui,sans-serif;-webkit-user-select:none;user-select:none} .mxp-bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:10px 14px;background:#111;border-bottom:1px solid #333;transition:opacity .3s} .mxp.playing .mxp-bar{opacity:.15}.mxp.playing .mxp-bar:hover,.mxp.playing .mxp-bar:focus-within{opacity:1} -.mxp-bar button{background:#222;color:#fff;border:1px solid #444;border-radius:8px;padding:6px 12px;font:inherit;font-size:15px;cursor:pointer;min-width:40px} +.mxp-bar button{background:#222;color:#fff;border:1px solid #444;border-radius:8px;padding:6px 12px;font:inherit;font-size:15px;cursor:pointer;min-width:40px;min-height:40px} .mxp-bar button:hover{background:#333}.mxp-bar button[aria-pressed="true"]{background:#f5c518;color:#000;border-color:#f5c518} .mxp-bar .mxp-play{background:#2e7d32;border-color:#2e7d32;min-width:90px}.mxp.playing .mxp-play{background:#c62828;border-color:#c62828} .mxp-bar label{display:flex;align-items:center;gap:6px;font-size:14px;color:#bbb} .mxp-bar input[type=range]{width:110px;accent-color:#f5c518} .mxp-sp{flex:1} +.mxp.slides .mxp-xo,.mxp:not(.slides) .mxp-so{display:none} .mxp-view{position:relative;flex:1;overflow:hidden} .mxp-scroll{position:absolute;inset:0;overflow-y:scroll;scrollbar-width:none} .mxp-scroll::-webkit-scrollbar{display:none} -.mxp-text{margin:0 auto;max-width:min(1100px,92vw);padding:45vh 0 60vh;white-space:pre-wrap;line-height:1.45;font-weight:600;text-align:center;unicode-bidi:plaintext} -.mxp.mirror .mxp-text{transform:scaleX(-1)} +.mxp-text{margin:0 auto;max-width:min(1100px,92vw);padding:45vh 0 60vh;white-space:pre-wrap;line-height:1.45;font-weight:600;text-align:start;unicode-bidi:plaintext} +.mxp-text .mxp-dir{color:#777;font-size:.45em;font-weight:500;letter-spacing:.02em} +.mxp.mirror .mxp-text,.mxp.mirror .mxp-slide{transform:scaleX(-1)} .mxp-guide{position:absolute;inset-inline:0;top:38%;height:1.6em;pointer-events:none;border-block:2px solid rgba(245,197,24,.55);background:rgba(245,197,24,.07)} .mxp-guide::before,.mxp-guide::after{content:"";position:absolute;top:50%;translate:0 -50%;border:12px solid transparent} .mxp-guide::before{left:4px;border-left-color:#f5c518}.mxp-guide::after{right:4px;border-right-color:#f5c518} .mxp-fade{position:absolute;inset-inline:0;height:22%;pointer-events:none} .mxp-fade.top{top:0;background:linear-gradient(#000,transparent)}.mxp-fade.bot{bottom:0;background:linear-gradient(transparent,#000)} +.mxp.slides .mxp-scroll,.mxp.slides .mxp-guide,.mxp.slides .mxp-fade,.mxp:not(.slides) .mxp-slide{display:none} +.mxp-slide{position:absolute;inset:0;display:flex;flex-direction:column;touch-action:pan-y} +.mxp-shead{display:flex;align-items:center;gap:14px;padding:12px 20px;background:#0d0d0d;border-bottom:1px solid #262626;color:#bbb;font-size:18px;line-height:1.3} +.mxp-snum{flex:none;font-weight:700;color:#f5c518;font-variant-numeric:tabular-nums} +.mxp-stitle{flex:1;min-width:0;color:#eee;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;unicode-bidi:plaintext;text-align:start} +.mxp-stitle small{display:block;color:#888;font-weight:400;font-size:.78em} +.mxp-clock{flex:none;display:flex;flex-direction:column;align-items:flex-end;font-variant-numeric:tabular-nums;font-weight:700} +.mxp-timer{font-size:22px;color:#ddd}.mxp-timer.warn{color:#f5a623}.mxp-timer.over{color:#ff5252} +.mxp-timer.idle{color:#666} +.mxp-delta{font-size:14px;font-weight:600}.mxp-delta.ahead{color:#66bb6a}.mxp-delta.behind{color:#ff8a80} +.mxp-sbody{flex:1;overflow-y:auto;padding:2.5vh max(4vw,20px) 4vh;line-height:1.38;font-weight:600;scrollbar-width:none;animation:mxp-in .25s ease} +.mxp-sbody::-webkit-scrollbar{display:none} +.mxp-sbody p{margin:0 0 .4em;max-width:1100px;unicode-bidi:plaintext;text-align:start} +.mxp-sbody p.gap{height:.35em;margin:0} +.mxp-sbody p.pt{position:relative;padding-inline-start:1.1em;margin-bottom:.7em;font-size:1.25em;line-height:1.25} +.mxp-sbody p.pt::before{content:"";position:absolute;inset-inline-start:.15em;top:.45em;width:.38em;height:.38em;border-radius:50%;background:#f5c518} +.mxp-sbody em{font-style:normal;color:#f5c518} +.mxp-cue{display:inline-block;padding:0 .35em;margin:0 .15em;border-radius:.3em;font-size:.6em;vertical-align:.2em;background:#1565c0;color:#fff;font-weight:700} +.mxp-cue.pause{background:#444} +.mxp-more{position:absolute;inset-inline-end:16px;bottom:56px;padding:4px 12px;border-radius:999px;background:#f5c518;color:#000;font-size:15px;font-weight:700;pointer-events:none} +.mxp-sfoot{padding:10px 20px;border-top:1px solid #262626;color:#888;font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.mxp-sfoot b{color:#bbb;font-weight:600;unicode-bidi:plaintext} +@keyframes mxp-in{from{opacity:.2}to{opacity:1}} .mxp-progress{height:3px;background:#222}.mxp-progress i{display:block;height:100%;width:0;background:#f5c518} .mxp-hint{position:absolute;left:50%;bottom:8%;translate:-50% 0;z-index:2;display:flex;align-items:center;gap:10px;padding:12px 22px;border-radius:999px;background:rgba(20,20,20,.95);border:1px solid rgba(245,197,24,.6);color:#fff;font-size:22px;font-weight:600;white-space:nowrap;pointer-events:none;opacity:0;scale:.92;transition:opacity .25s ease,scale .25s ease} .mxp-hint.on{opacity:1;scale:1} .mxp-hint b{color:#f5c518;font-size:28px;line-height:1} -@media (prefers-reduced-motion:reduce){.mxp-hint{transition:opacity .15s linear;scale:1}} +@media (prefers-reduced-motion:reduce){.mxp-hint{transition:opacity .15s linear;scale:1}.mxp-sbody{animation:none}} .mxp-count{position:absolute;inset:0;display:grid;place-items:center;font-size:30vh;font-weight:700;color:#f5c518;background:rgba(0,0,0,.6);pointer-events:none} `; -let hintTimer=0,wheel=0,keepOpen=false,root,scroller,textEl,guide,bar,raf=0,last=0,playing=false,speed=40,size=64,mirror=false,acc=0,countTimer=0,back=null; +let hintTimer=0,wheel=0,keepOpen=false,root,scroller,textEl,guide,bar,raf=0,last=0,playing=false,speed=40,mirror=false,acc=0,countTimer=0,back=null; +let sizes={scroll:64,slidesP:34,slidesL:32},prefer="slides",mode="scroll",deck=null,cur=0,clock0=0,slide0=0,tickTimer=0,lock=null,touch=null,swiped=false; -function save(){try{localStorage.setItem("mathly.prompter",JSON.stringify({speed,size,mirror}))}catch{}} -function load(){try{const s=JSON.parse(localStorage.getItem("mathly.prompter")||"{}");if(s.speed)speed=s.speed;if(s.size)size=s.size;mirror=!!s.mirror}catch{}} +function save(){try{localStorage.setItem("mathly.prompter",JSON.stringify({speed,sizes,mirror,mode:prefer}))}catch{}} +function load(){try{const s=JSON.parse(localStorage.getItem("mathly.prompter")||"{}");if(s.speed)speed=s.speed;if(s.size)sizes.scroll=s.size;if(s.sizes)Object.assign(sizes,s.sizes);mirror=!!s.mirror;if(s.mode)prefer=s.mode}catch{}} +function sizeKey(){return mode!=="slides"?"scroll":(matchMedia("(orientation: portrait)").matches?"slidesP":"slidesL");} +function size(){return sizes[sizeKey()];} function style(){ if(document.getElementById("mxp-css")) return; const el=document.createElement("style"); el.id="mxp-css"; el.textContent=CSS; document.head.appendChild(el); } +/* ---------- reading a slide script ---------- */ +const SLIDE=/^\s*(?:slide|שקף)\s*(\d+)\s*(?:[—–:.-]\s*(.*))?$/i; +const PART=/^\s*(?:part|חלק)\s*\d+\s*(?:[—–:.-]\s*.*)?$/i; +// "40 seconds", "Opening · 35 seconds", "1 minute 30 seconds", "1:30", "45 שניות" +function duration(line){ + const t=line.trim(); if(!t||t.length>48) return null; + const m=t.match(/^(?:(.*?)\s*[·•|,–—-]\s*)?(?:(\d+):(\d\d)|(?:(\d+(?:\.\d+)?)\s*(?:minutes?|mins?|דקות|דקה)\s*(?:and\s*)?)?(?:(\d+)\s*(?:seconds?|secs?|s|שניות))?)\s*$/i); + if(!m) return null; + const secs=m[2]!=null?(+m[2])*60+(+m[3]):Math.round((+(m[4]||0))*60)+(+(m[5]||0)); + return secs>0?{secs,label:(m[1]||"").trim()}:null; +} +// a list of slides, or null when the text is not a slide script; kinds[i] marks each line as "slide"/"part"/"time"/"" +function parse(text){ + const lines=String(text).split(/\r?\n/), kinds=lines.map(()=>""), slides=[], pre=[]; + let s=null, part=""; + lines.forEach((line,i)=>{ + if(PART.test(line)){ kinds[i]="part"; part=line.trim(); return; } + const m=line.match(SLIDE); + if(m){ kinds[i]="slide"; s={num:+m[1],title:(m[2]||"").trim()||line.trim(),part,secs:0,label:"",lines:[]}; part=""; slides.push(s); return; } + if(s&&!s.lines.some(l=>l.trim())&&!s.secs){ const d=duration(line); if(d){ kinds[i]="time"; s.secs=d.secs; s.label=d.label; return; } } + (s?s.lines:pre).push(line); + }); + if(slides.length<2) return {slides:null,kinds:null}; + if(pre.some(l=>l.trim())) slides.unshift({num:0,title:"פתיחה",part:"",secs:0,label:"",lines:pre}); + return {slides,kinds}; +} +const BULLET=/^\s*[•\-–]\s+(.+)$/; +function esc(s){return s.replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]));} +function cues(line){ + return esc(line) + .replace(/\[(?:click|קליק)\]/gi,'CLICK ⏵') + .replace(/\[(?:pause|הפסקה)\]|(^|\s)\/\/(?=\s|$)/gi,(_,sp)=>(sp||"")+'⏸') + .replace(/\*([^*\n]+)\*/g,"$1"); +} +function fmt(sec){sec=Math.max(0,Math.round(sec));return Math.floor(sec/60)+":"+String(sec%60).padStart(2,"0");} + +/* ---------- drawing ---------- */ function sync(){ - textEl.style.fontSize=size+"px"; guide.style.height=(size*1.45)+"px"; - textEl.style.paddingTop=guide.offsetTop+"px"; // the first line starts on the reading line - root.classList.toggle("mirror",mirror); root.classList.toggle("playing",playing); + const px=size(); + textEl.style.fontSize=sizes.scroll+"px"; guide.style.height=(sizes.scroll*1.45)+"px"; + if(mode==="scroll") textEl.style.paddingTop=guide.offsetTop+"px"; // the first line starts on the reading line + root.classList.toggle("slides",mode==="slides"); + root.classList.toggle("mirror",mirror); root.classList.toggle("playing",mode==="slides"?!!clock0:playing); bar.querySelector(".mxp-play").textContent=playing?"⏸ עצירה":"▶ הפעלה"; bar.querySelector("[data-p=mirror]").setAttribute("aria-pressed",String(mirror)); bar.querySelector(".mxp-speed").value=speed; bar.querySelector(".mxp-speed-v").textContent=speed; - bar.querySelector(".mxp-size-v").textContent=size; + bar.querySelector(".mxp-size-v").textContent=px; + const m=bar.querySelector("[data-p=mode]"); m.hidden=!deck; m.textContent=mode==="slides"?"☰ גלילה":"▭ שקפים"; + if(mode==="slides"&&deck) fit(); + progress(); } function progress(){ + const bar=root.querySelector(".mxp-progress i"); + if(mode==="slides"){ bar.style.width=((cur+1)/deck.length*100)+"%"; return; } const max=scroller.scrollHeight-scroller.clientHeight; - root.querySelector(".mxp-progress i").style.width=(max>0?scroller.scrollTop/max*100:0)+"%"; + bar.style.width=(max>0?scroller.scrollTop/max*100:0)+"%"; } +function drawSlide(){ + const s=deck[cur], el=root.querySelector(".mxp-slide"); + el.querySelector(".mxp-snum").textContent=`${cur+1} / ${deck.length}`; + const t=el.querySelector(".mxp-stitle"); + t.innerHTML=(s.part||s.label?`${esc([s.part,s.label].filter(Boolean).join(" · "))}`:"")+`${esc(s.title)}`; + const body=el.querySelector(".mxp-sbody"); + const lines=s.lines.slice(); while(lines.length&&!lines[0].trim()) lines.shift(); while(lines.length&&!lines.at(-1).trim()) lines.pop(); + // "• " / "- " lines are reminders (an outline, ראשי פרקים): shown as a list, larger and with room between them + body.innerHTML=lines.map(l=>{ + const b=l.match(BULLET); + return b?`${cues(b[1])}
`:l.trim()?`${cues(l)}
`:''; + }).join(""); + body.scrollTop=0; body.style.animation="none"; void body.offsetWidth; body.style.animation=""; + fit(); + drawFoot(); drawClock(); progress(); +} +// a long slide's notes get smaller (down to 75% of the chosen size) so they fit on one screen; what still does not +// fit scrolls with a finger, and a "more" mark shows until the end has been seen +function fit(){ + const body=root.querySelector(".mxp-sbody"), want=size(), floor=Math.max(20,Math.round(want*.75)); + let px=want; body.style.fontSize=px+"px"; + while(px>floor&&body.scrollHeight>body.clientHeight+2){ px-=2; body.style.fontSize=px+"px"; } + more(); +} +function more(){ + const body=root.querySelector(".mxp-sbody"); + root.querySelector(".mxp-more").hidden=body.scrollTop+body.clientHeight>=body.scrollHeight-4; +} +function drawFoot(){ + const next=deck[cur+1], el=root.querySelector(".mxp-sfoot"); + const what=next?`הבא: ${esc(next.title)}`:"סוף המצגת"; + el.innerHTML=(clock0?"":"הקשה על המסך מתחילה את השעון · ")+what; +} +function drawClock(){ + if(mode!=="slides"||!root) return; + const s=deck[cur], now=performance.now(), timer=root.querySelector(".mxp-timer"), delta=root.querySelector(".mxp-delta"); + const spent=clock0?(now-slide0)/1000:0; + timer.textContent=fmt(spent)+(s.secs?" / "+fmt(s.secs):""); + timer.className="mxp-timer"+(!clock0?" idle":s.secs&&spent>s.secs?" over":s.secs&&spent>=s.secs*.85?" warn":""); + // where the talk stands: when this slide began against when the plan says it should, plus any overrun of this slide + const planned=deck.slice(0,cur).reduce((a,x)=>a+x.secs,0), known=deck.some(x=>x.secs); + if(!clock0||!known){ delta.innerHTML=""; delta.className="mxp-delta"; return; } + const d=Math.round((slide0-clock0)/1000-planned+Math.max(0,spent-(s.secs||spent))); + delta.innerHTML=Math.abs(d)<5?"בזמן":(d>0?"מאחור ":"לפני הזמן ")+`${d>0?"+":"−"}${fmt(Math.abs(d))}`; + delta.className="mxp-delta"+(Math.abs(d)<5?"":d>0?" behind":" ahead"); +} + +function go(i){ + if(!deck) return; + const to=Math.max(0,Math.min(deck.length-1,i)); if(to===cur) return; + cur=to; slide0=performance.now(); drawSlide(); +} +function startClock(){ clock0=slide0=performance.now(); drawFoot(); drawClock(); sync(); } +function setMode(m){ + if(m==="slides"&&!deck) return; + mode=m; play(false); sync(); + if(mode==="slides") drawSlide(); else requestAnimationFrame(()=>{ textEl.style.paddingTop=guide.offsetTop+"px"; progress(); }); +} + +/* ---------- scrolling ---------- */ function tick(now){ if(!playing) return; const dt=last?(now-last)/1000:0; last=now; - acc+=speed*dt*(size/64); // speed is in "lines-ish" units, so it feels the same at any text size + acc+=speed*dt*(sizes.scroll/64); // speed is in "lines-ish" units, so it feels the same at any text size const step=Math.floor(acc); if(step){acc-=step; scroller.scrollTop+=step;} progress(); if(scroller.scrollTop>=scroller.scrollHeight-scroller.clientHeight-1){playing=false;sync();return;} @@ -90,8 +236,9 @@ function hint(icon,text){ const HINTS={ play:()=>playing||root.querySelector(".mxp-count")?["▶","הפעלה"]:["⏸","עצירה"], faster:()=>["⏩",`מהירות ${speed}`+(speed>=300?" (מקסימום)":"")], slower:()=>["⏪",`מהירות ${speed}`+(speed<=5?" (מינימום)":"")], - bigger:()=>["A+",`גודל ${size}`], smaller:()=>["A−",`גודל ${size}`], - mirror:()=>["⇋",mirror?"מראה: מופעלת":"מראה: כבויה"], top:()=>["⏮","להתחלה"], back:()=>["↶","כמה שורות אחורה"], + bigger:()=>["A+",`גודל ${size()}`], smaller:()=>["A−",`גודל ${size()}`], + mirror:()=>["⇋",mirror?"מראה: מופעלת":"מראה: כבויה"], top:()=>mode==="slides"?["⏮","לשקף הראשון, השעון אופס"]:["⏮","להתחלה"], + back:()=>["↶","כמה שורות אחורה"], mode:()=>mode==="slides"?["▭","שקף אחר שקף"]:["☰","גלילה"], }; function act(p){ @@ -100,25 +247,32 @@ function act(p){ } function actOnly(p){ + const k=sizeKey(); switch(p){ case "play": return countdown(); + case "next": if(!clock0) return startClock(); return go(cur+1); + case "prev": return go(cur-1); + case "mode": prefer=mode==="slides"?"scroll":"slides"; save(); return setMode(prefer); case "slower": speed=Math.max(5,speed-5); break; case "faster": speed=Math.min(300,speed+5); break; - case "smaller": size=Math.max(24,size-6); break; - case "bigger": size=Math.min(200,size+6); break; + case "smaller": sizes[k]=Math.max(20,sizes[k]-(k==="scroll"?6:4)); break; + case "bigger": sizes[k]=Math.min(200,sizes[k]+(k==="scroll"?6:4)); break; case "mirror": mirror=!mirror; break; - case "top": scroller.scrollTop=0; acc=0; progress(); break; - case "back": scroller.scrollTop-=size*1.45*3; acc=0; progress(); return; + case "top": + if(mode==="slides"){ cur=-1; clock0=0; go(0); sync(); return; } + scroller.scrollTop=0; acc=0; progress(); break; + case "back": scroller.scrollTop-=sizes.scroll*1.45*3; acc=0; progress(); return; case "full": if(document.fullscreenElement){keepOpen=true; document.exitFullscreen?.();} else root.requestFullscreen?.().catch(()=>{}); return; case "close": return close(); } save(); sync(); } +const KEYS={" ":"play",ArrowUp:"faster",ArrowDown:"slower","+":"bigger","=":"bigger","-":"smaller",m:"mirror",M:"mirror","מ":"mirror","צ":"mirror",Home:"top",PageDown:"play",ArrowRight:"play",PageUp:"back",ArrowLeft:"back",f:"full",F:"full","כ":"full",s:"mode",S:"mode","ד":"mode",Escape:"close"}; +const SLIDE_KEYS={...KEYS," ":"next",PageDown:"next",ArrowRight:"next",ArrowDown:"next",Enter:"next",PageUp:"prev",ArrowLeft:"prev",ArrowUp:"prev",Backspace:"prev"}; function onKey(e){ if(!root) return; - const map={" ":"play",ArrowUp:"faster",ArrowDown:"slower","+":"bigger","=":"bigger","-":"smaller",m:"mirror",M:"mirror","מ":"mirror",Home:"top",PageDown:"play",ArrowRight:"play",PageUp:"back",ArrowLeft:"back",f:"full",F:"full",Escape:"close"}; - const p=map[e.key]; if(!p) return; + const p=(mode==="slides"?SLIDE_KEYS:KEYS)[e.key]; if(!p) return; if(e.target.closest?.("input")&&p!=="close") return; e.preventDefault(); e.stopImmediatePropagation(); act(p); } @@ -131,46 +285,90 @@ function onFull(){ close(); } +// keep the screen on (a tablet would otherwise dim and lock in the middle of a talk); the lock is lost whenever the +// page is hidden, so it is asked for again when the page comes back +async function wake(){ + if(!root||document.visibilityState!=="visible"||!navigator.wakeLock) return; + try{ lock=await navigator.wakeLock.request("screen"); }catch{} +} +function onVisible(){ if(document.visibilityState==="visible") wake(); } +function onTurn(){ if(root){ sync(); if(mode==="scroll") textEl.style.paddingTop=guide.offsetTop+"px"; } } + function open(text){ if(!String(text||"").trim()) return; close(); style(); load(); back=document.activeElement; + const parsed=parse(text); deck=parsed.slides; cur=0; clock0=slide0=0; + mode=deck&&prefer==="slides"?"slides":"scroll"; root=document.createElement("div"); root.className="mxp"; root.setAttribute("role","dialog"); root.setAttribute("aria-modal","true"); root.setAttribute("aria-label","פרומפטר"); root.innerHTML=`